textmachine/frontend/src/i18n/fill.ts

23 lines
1.2 KiB
TypeScript

// Filling the `{name}` places of a line. Its own module for one reason: the scene harness reads the
// same catalogue and has to build the same phrase to look for on screen, and two fillers would be
// two answers to "what does this line say".
//
// Ours, and it has to be: `@internationalized/string` substitutes nothing into a plain string —
// `LocalizedStringFormatter.format` returns a string value verbatim and calls only a FUNCTION value
// with the variables (read in its source, not assumed). Those functions are what
// `@internationalized/string-compiler` produces out of ICU at BUILD time, and a build step is what
// this stack rejected when it weighed lingui (STACK_DECISIONS §1).
/** Variables of a string: `{count}` in the catalogue, a number or a word here. */
export type Variables = Record<string, string | number>;
/**
* A place with no variable given is left as it is written rather than blanked: a visible `{count}`
* says "a variable was forgotten", an empty space says nothing.
*/
export const fill = (line: string, variables: Variables | undefined): string =>
variables === undefined
? line
: line.replace(/\{(\w+)\}/g, (place, name: string) =>
Object.hasOwn(variables, name) ? String(variables[name]) : place,
);