59 lines
2.1 KiB
TypeScript
59 lines
2.1 KiB
TypeScript
|
|
import i18n from "i18next";
|
||
|
|
import { initReactI18next } from "react-i18next";
|
||
|
|
|
||
|
|
// Endonyms (shown as-is regardless of the active language — the convention for language pickers).
|
||
|
|
export const LANGUAGES = [
|
||
|
|
{ code: "en", label: "English" },
|
||
|
|
{ code: "hu", label: "Magyar" },
|
||
|
|
{ code: "de", label: "Deutsch" },
|
||
|
|
] as const;
|
||
|
|
export type LangCode = (typeof LANGUAGES)[number]["code"];
|
||
|
|
const SUPPORTED = LANGUAGES.map((l) => l.code) as readonly string[];
|
||
|
|
export const LANG_KEY = "siftlode.lang";
|
||
|
|
|
||
|
|
// Auto-load every locale file (locales/<lang>/<area>.json) and merge each <area> under one
|
||
|
|
// `translation` namespace, so components use t("area.key") and adding an area needs no wiring.
|
||
|
|
const mods = import.meta.glob("./locales/*/*.json", { eager: true }) as Record<
|
||
|
|
string,
|
||
|
|
{ default: Record<string, unknown> }
|
||
|
|
>;
|
||
|
|
|
||
|
|
const resources: Record<string, { translation: Record<string, unknown> }> = {};
|
||
|
|
for (const [path, mod] of Object.entries(mods)) {
|
||
|
|
const m = path.match(/\/locales\/([a-z]{2})\/([a-zA-Z0-9_]+)\.json$/);
|
||
|
|
if (!m) continue;
|
||
|
|
const [, lang, area] = m;
|
||
|
|
(resources[lang] ??= { translation: {} }).translation[area] = mod.default;
|
||
|
|
}
|
||
|
|
|
||
|
|
export function isSupported(code: string | null | undefined): code is LangCode {
|
||
|
|
return !!code && SUPPORTED.includes(code);
|
||
|
|
}
|
||
|
|
|
||
|
|
// Initial language before the server preference is known: stored choice, else the browser
|
||
|
|
// language, else English. (After login, App adopts the server-persisted preference.)
|
||
|
|
export function detectInitialLang(): LangCode {
|
||
|
|
const stored = localStorage.getItem(LANG_KEY);
|
||
|
|
if (isSupported(stored)) return stored;
|
||
|
|
const nav = (navigator.language || "en").slice(0, 2).toLowerCase();
|
||
|
|
return isSupported(nav) ? nav : "en";
|
||
|
|
}
|
||
|
|
|
||
|
|
const initial = detectInitialLang();
|
||
|
|
void i18n.use(initReactI18next).init({
|
||
|
|
resources,
|
||
|
|
lng: initial,
|
||
|
|
fallbackLng: "en",
|
||
|
|
interpolation: { escapeValue: false },
|
||
|
|
returnNull: false,
|
||
|
|
});
|
||
|
|
document.documentElement.lang = initial;
|
||
|
|
|
||
|
|
export function setLanguage(code: LangCode): void {
|
||
|
|
void i18n.changeLanguage(code);
|
||
|
|
localStorage.setItem(LANG_KEY, code);
|
||
|
|
document.documentElement.lang = code;
|
||
|
|
}
|
||
|
|
|
||
|
|
export default i18n;
|