main init
This commit is contained in:
46
Library/mobile/kit/i18n.ts
Normal file
46
Library/mobile/kit/i18n.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
// Kit i18n (v1) - tiny translation helper. From _Tools\Library\mobile\kit.
|
||||
//
|
||||
// const en = { hello: "Hello {name}!", coins: "{n} coins" };
|
||||
// const de: Partial<typeof en> = { hello: "Hallo {name}!" }; // missing keys fall back to en
|
||||
// export const { t, lang, setLang, langs } = createI18n({ en, de }, "mygame_lang");
|
||||
// t("hello", { name: "Ana" })
|
||||
//
|
||||
// Language: saved choice, else the device language if available, else the first dictionary.
|
||||
// setLang() saves and reloads the page (all UI re-renders from scratch).
|
||||
|
||||
export function createI18n<D extends Record<string, string>>(
|
||||
dicts: { [lang: string]: Partial<D> } & { en: D },
|
||||
storageKey: string
|
||||
) {
|
||||
const langs = Object.keys(dicts);
|
||||
const pick = (): string => {
|
||||
try {
|
||||
const saved = localStorage.getItem(storageKey);
|
||||
if (saved && langs.includes(saved)) return saved;
|
||||
} catch {
|
||||
// storage unavailable
|
||||
}
|
||||
const device = (navigator.language || "en").slice(0, 2).toLowerCase();
|
||||
return langs.includes(device) ? device : langs[0];
|
||||
};
|
||||
const lang = pick();
|
||||
const dict = dicts[lang] as Partial<D>;
|
||||
|
||||
function t(key: keyof D & string, vars?: Record<string, string | number>): string {
|
||||
let s = (dict[key] ?? dicts.en[key] ?? key) as string;
|
||||
if (vars) for (const [k, v] of Object.entries(vars)) s = s.split(`{${k}}`).join(String(v));
|
||||
return s;
|
||||
}
|
||||
|
||||
function setLang(l: string): void {
|
||||
if (!langs.includes(l)) return;
|
||||
try {
|
||||
localStorage.setItem(storageKey, l);
|
||||
} catch {
|
||||
// session only
|
||||
}
|
||||
location.reload();
|
||||
}
|
||||
|
||||
return { t, lang, setLang, langs };
|
||||
}
|
||||
Reference in New Issue
Block a user