cdrdpyj/src/i18n/index.ts

60 lines
1.7 KiB
TypeScript

import es from "./es.json";
import en from "./en.json";
import fr from "./fr.json";
import he from "./he.json";
import uk from "./uk.json";
import pt from "./pt.json";
import ru from "./ru.json";
import rw from "./rw.json";
import kr from "./kr.json";
const dictionaries = { es, en, fr, he, uk, pt, ru, rw, kr } as const;
export type Locale = keyof typeof dictionaries;
export type I18nKey = keyof typeof es;
export const routeTranslations = {
news: {
es: "noticias",
en: "news",
fr: "informations",
he: "חדשות",
uk: "noticias",
pt: "noticias",
ru: "новости",
rw: "amakuru",
kr: "nouvel",
}
} as const;
export function getLocalizedRoute(route: keyof typeof routeTranslations, locale: string | undefined): string {
const l = (locale in routeTranslations[route] ? locale : "es") as Locale;
return routeTranslations[route][l as keyof (typeof routeTranslations)[typeof route]] || routeTranslations[route]["en" as keyof (typeof routeTranslations)[typeof route]];
}
export function t(
locale: string | undefined,
key: I18nKey,
vars?: Record<string, string | number>
) {
const l = (locale in dictionaries ? locale : "es") as Locale;
// fallback chain: requested locale -> default locale -> key itself
const template =
dictionaries[l][key] ??
dictionaries.es[key] ??
String(key);
if (!vars) return template;
// simple interpolation: "Hello {name}"
return template.replace(/\{(\w+)\}/g, (_, name) =>
vars[name] === undefined ? `{${name}}` : String(vars[name])
);
}
export function createTranslator(locale: string | undefined) {
return function tl(key: I18nKey, vars?: Record<string, string | number>) {
return t(locale, key, vars);
};
}