Debian Codegraph @

frontend/src/i18n.ts

raw
1 import { getScriptTagValue } from "./lib/dom";
2 import { ok } from "./lib/result";
3 import { record, string } from "./lib/validation";
4 import { log_error } from "./log";
5
6 let translations: Record<string, string> | undefined;
7 const validator = record(string);
8
9 /**
10 * Translate the given string.
11 */
12 // eslint-disable-next-line @typescript-eslint/naming-convention
13 export function _(text: string): string {
14 if (translations === undefined) {
15 const res =
16 // The DOM is not available in tests
17 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
18 globalThis.document !== undefined
19 ? getScriptTagValue("#translations", validator)
20 : ok({});
21 translations = res.unwrap_or({});
22 if (res.is_err) {
23 log_error(`Loading translations failed:`, res.error);
24 }
25 }
26 return translations[text] ?? text;
27 }
28
29 /**
30 * Replace the placeholders in a translation string.
31 */
32 export function format(text: string, values: Record<string, string>): string {
33 return text.replace(
34 /%\(\w+\)s/g,
35 (match) => values[match.slice(2, -2)] ?? "MISSING",
36 );
37 }