Files
partey_workadventure/front/src/i18n/locales.ts
T
_Bastler 8647199625 i18n
2022-05-09 08:40:29 +02:00

63 lines
2.1 KiB
TypeScript

import { detectLocale, navigatorDetector, initLocalStorageDetector } from "typesafe-i18n/detectors";
import { FALLBACK_LOCALE } from "../Enum/EnvironmentVariable";
import { setLocale, locale } from "./i18n-svelte";
import type { Locales } from "./i18n-types";
import { baseLocale, locales } from "./i18n-util";
import { loadLocaleAsync } from "./i18n-util.async";
import { get } from "svelte/store";
const fallbackLocale = (FALLBACK_LOCALE || baseLocale) as Locales;
const localStorageProperty = "language";
export const localeDetector = async () => {
const exist = localStorage.getItem(localStorageProperty);
let detectedLocale: Locales = fallbackLocale;
if (exist) {
const localStorageDetector = initLocalStorageDetector(localStorageProperty);
detectedLocale = detectLocale(fallbackLocale, locales, localStorageDetector);
} else {
detectedLocale = detectLocale(fallbackLocale, locales, navigatorDetector);
}
await setCurrentLocale(detectedLocale);
};
export const setCurrentLocale = async (locale: Locales) => {
localStorage.setItem(localStorageProperty, locale);
await loadLocaleAsync(locale);
setLocale(locale);
};
export const displayableLocales: { id: Locales; language: string; region: string }[] = locales.map((locale) => {
const [language, region] = locale.split("-");
// backwards compatibility
if (!Intl.DisplayNames) {
return { id: locale, language, region };
}
return {
id: locale,
language: new Intl.DisplayNames(locale, { type: "language" }).of(language),
region: new Intl.DisplayNames(locale, { type: "region" }).of(region),
};
});
export const i18nJson = (text: string): string => {
if (text.trim().startsWith("{")) {
try {
const textObject = JSON.parse(text);
if (textObject[get(locale)]) {
return textObject[get(locale)];
} else if (Object.keys(textObject).length > 0) {
// fallback to first value
return textObject[Object.keys(textObject)[0]];
}
} catch (err) {
//
}
}
return text;
};