Lutra/ui/src/i18n/index.ts
danny 7c0fb312f6 M1.11: English message catalog for every UI string
ui/src/i18n: en.json (20 flat dotted keys) and t(key, params?) with
{name} interpolation; a missing key warns in dev and returns the key.
All template text, title/aria-label attributes, notices and frontend
error texts go through t. ESLint vue/no-bare-strings-in-template is an
error. Catalog tests: interpolation, missing key, every t() key exists,
no unused keys. Engine messages stay English (G14). Docs updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 06:39:42 +02:00

57 lines
1.8 KiB
TypeScript

/**
* Message catalog of the frontend.
*
* Every interface string comes from a catalog keyed by flat dotted ids
* grouped by area (`app.*`, `project.*`, `editor.*`, `common.*`). English
* (`en.json`) is the source catalog; other languages follow with G14.
* Messages that come from the engine (`EngineError.message`) are not in
* the catalog yet and stay English.
*/
import en from "./en.json";
/** A key of the English catalog. */
export type MessageKey = keyof typeof en;
/** Values for the `{name}` placeholders of a message. */
export type MessageParams = Readonly<Record<string, string | number>>;
/** The active catalog. */
const catalog: Readonly<Record<string, string>> = en;
/**
* Whether a key exists in the active catalog.
*
* @param key - the message key.
*/
export function hasMessage(key: string): boolean {
return Object.hasOwn(catalog, key);
}
/**
* Looks up a message and fills in its placeholders.
*
* A placeholder is a name in braces (`{name}`). A placeholder without a
* value in `params` stays as it is. A missing key never throws: it logs a
* warning in development builds and returns the key itself, so the gap is
* visible in the interface.
*
* @param key - the message key, for example `project.openFolder`.
* @param params - values for the placeholders.
* @returns the message text.
*/
export function t(key: string, params?: MessageParams): string {
const message = hasMessage(key) ? catalog[key] : undefined;
if (message === undefined) {
if (import.meta.env.DEV) {
console.warn(`[i18n] missing message key: ${key}`);
}
return key;
}
if (!params) {
return message;
}
return message.replace(/\{(\w+)\}/g, (placeholder, name: string) => {
const value = Object.hasOwn(params, name) ? params[name] : undefined;
return value === undefined ? placeholder : String(value);
});
}