Debian Codegraph @

frontend/src/format.ts

raw
1 /**
2 * Helper functions to format numbers and dates.
3 */
4
5 import { format } from "d3-format";
6 import { timeFormat, utcFormat } from "d3-time-format";
7
8 import type { Interval } from "./lib/interval";
9
10 /**
11 * A number formatting function for a locale.
12 * @param locale - The locale to use.
13 * @param precision - The number of decimal digits to show.
14 */
15 export function localeFormatter(
16 locale: string | null,
17 precision = 2,
18 ): (num: number) => string {
19 if (locale == null) {
20 return format(`.${precision.toString()}f`);
21 }
22 // this needs to be between 0 and 20
23 const digits = Math.max(0, Math.min(precision, 20));
24 const fmt = new Intl.NumberFormat(locale.replace("_", "-"), {
25 minimumFractionDigits: digits,
26 maximumFractionDigits: digits,
27 });
28 return fmt.format.bind(fmt);
29 }
30
31 const formatterPer = format(".2f");
32 export function formatPercentage(number: number): string {
33 return `${formatterPer(Math.abs(number) * 100)}%`;
34 }
35
36 /** Obscure numbers for incognito mode. */
37 export const replaceNumbers = (num: string): string =>
38 num.replace(/[0-9]/g, "X");
39
40 export interface FormatterContext {
41 /** Render an amount to a string like "2.00 USD". */
42 amount: (num: number, currency: string) => string;
43 /** Render an number for a currency like "2.00". */
44 num: (num: number, currency: string) => string;
45 }
46
47 /** Build the formatter context for the given configuration */
48 export function formatter_context(
49 incognito: boolean,
50 locale: string | null,
51 precisions: Record<string, number>,
52 ): FormatterContext {
53 const formatter = localeFormatter(locale);
54 const currencyFormatters = Object.fromEntries(
55 Object.entries(precisions).map(([currency, prec]) => [
56 currency,
57 localeFormatter(locale, prec),
58 ]),
59 );
60 const num_raw = (n: number, c: string) =>
61 (currencyFormatters[c] ?? formatter)(n);
62
63 const num = incognito
64 ? (n: number, c: string) => replaceNumbers(num_raw(n, c))
65 : num_raw;
66
67 return {
68 amount: (n, c) => `${num(n, c)} ${c}`,
69 num,
70 };
71 }
72
73 type DateFormatter = (date: Date) => string;
74
75 /** Format the date as a ISO-8601 date string. */
76 export const day = utcFormat("%Y-%m-%d");
77
78 /** Date formatters for human consumption. */
79 export const dateFormat: Record<Interval, DateFormatter> = {
80 year: utcFormat("%Y"),
81 quarter: (date) =>
82 `${date.getUTCFullYear().toString()}Q${(Math.floor(date.getUTCMonth() / 3) + 1).toString()}`,
83 month: utcFormat("%b %Y"),
84 week: utcFormat("%GW%V"),
85 day,
86 };
87
88 /** Date formatters for the entry filter form. */
89 export const timeFilterDateFormat: Record<Interval, DateFormatter> = {
90 year: utcFormat("%Y"),
91 quarter: (date) =>
92 `${date.getUTCFullYear().toString()}-Q${(Math.floor(date.getUTCMonth() / 3) + 1).toString()}`,
93 month: utcFormat("%Y-%m"),
94 week: utcFormat("%G-W%V"),
95 day,
96 };
97
98 const local_day = timeFormat("%Y-%m-%d");
99
100 /** Today as a ISO-8601 date string. */
101 export function todayAsString(): string {
102 return local_day(new Date());
103 }