diff options
Diffstat (limited to 'web/src/lib/i18n/index.ts')
| -rw-r--r-- | web/src/lib/i18n/index.ts | 73 |
1 files changed, 73 insertions, 0 deletions
diff --git a/web/src/lib/i18n/index.ts b/web/src/lib/i18n/index.ts new file mode 100644 index 0000000..9634712 --- /dev/null +++ b/web/src/lib/i18n/index.ts @@ -0,0 +1,73 @@ +/** + * UI string i18n (Phase 3: English first, locale plumbing in place). + * + * The reference app generates its UI strings from `.arb` files (gen-l10n); + * here we port the English set as a plain object and keep the same shape so + * the other 9 locales can be dropped in later (Phase 6). `t()` falls back to + * English for any key a locale is missing. + */ + +import { get, writable, type Writable } from 'svelte/store'; + +import { en } from './en'; + +export type Locale = + | 'en' + | 'de' + | 'es' + | 'fr' + | 'ko' + | 'pl' + | 'ru' + | 'th' + | 'zh' + | 'zh_Hant'; + +/** Locale → its string table. English is the only one ported in Phase 3. */ +const tables: Record<string, Record<string, string>> = { en }; + +const LOCALE_KEY = 'x-haven-locale'; + +function initialLocale(): Locale { + try { + const stored = window.localStorage.getItem(LOCALE_KEY); + if (stored && tables[stored]) return stored as Locale; + } catch { + // localStorage unavailable (SSR / privacy mode) — fall through. + } + return 'en'; +} + +export const locale: Writable<Locale> = writable<Locale>(initialLocale()); + +locale.subscribe((value) => { + try { + window.localStorage.setItem(LOCALE_KEY, value); + } catch { + // ignore + } +}); + +/** The locales currently available in the client (for the settings picker). */ +export const availableLocales = Object.keys(tables); + +/** + * Translate a key with the active locale, falling back to English. Returns + * the key itself when it is unknown everywhere (so missing strings are + * visible rather than silently blank). + */ +export function t(key: string, vars?: Record<string, string | number>): string { + const active = tables[get(locale)] ?? {}; + let template = active[key] ?? en[key] ?? key; + if (vars) { + for (const [name, value] of Object.entries(vars)) { + template = template.replaceAll(`{${name}}`, String(value)); + } + } + return template; +} + +/** True when [key] exists in the active locale (vs. falling back). */ +export function hasLocaleKey(key: string): boolean { + return key in (tables[get(locale)] ?? {}); +} |
