breakout71/src/i18n/i18n.ts

32 lines
981 B
TypeScript
Raw Normal View History

2025-03-16 17:45:29 +01:00
import fr from "./fr.json";
import en from "./en.json";
import { getSettingValue } from "../settings";
2025-03-15 21:29:38 +01:00
2025-03-16 17:45:29 +01:00
type translationKeys = keyof typeof en;
type translation = { [key in translationKeys]: string };
const languages: Record<string, translation> = { fr, en };
export function getCurrentLang() {
return getSettingValue("lang", getFirstBrowserLanguage());
}
2025-03-15 21:29:38 +01:00
2025-03-16 17:45:29 +01:00
export function t(
key: translationKeys,
params: { [key: string]: any } = {},
): string {
const lang = getCurrentLang();
let template = languages[lang]?.[key] || languages.en[key];
for (let key in params) {
template = template.split("{{" + key + "}}").join(`${params[key]}`);
}
return template;
2025-03-15 21:29:38 +01:00
}
function getFirstBrowserLanguage() {
2025-03-16 17:45:29 +01:00
const preferred_languages = [...navigator.languages, navigator.language, "en"]
.filter((i) => i)
.map((i) => i.slice(0, 2).toLowerCase());
const supported = Object.keys(languages);
2025-03-15 21:29:38 +01:00
2025-03-16 17:45:29 +01:00
return preferred_languages.find((k) => supported.includes(k)) || "en";
}