Files
outline/app/utils/i18n.ts
T
Tom Moor 4a96de653b perf: Smaller locale files and fewer locale fetches (#14592)
* perf: Smaller locale files, start i18n with stored user language, preload locale

* fix: Set spellchecker when locale is unchanged, match lng from allowlist

* refactor: Type-safe locale cache keyed by supported language

* Remove locale preload

* fix: Ignore unsupported languages in changeLanguage
2026-11-14 19:57:53 -05:00

59 lines
1.7 KiB
TypeScript

import i18n from "i18next";
import backend from "i18next-http-backend";
import { initReactI18next } from "react-i18next";
import { languages } from "@shared/i18n";
import { unicodeCLDRtoBCP47, unicodeBCP47toCLDR } from "@shared/utils/date";
import { isRTLLanguage } from "@shared/utils/rtl";
import { cdnPath } from "@shared/utils/urls";
import Logger from "./Logger";
/**
* Initializes i18n library, loading all available translations from the
* API backend.
*
* @param defaultLanguage The default language to use if the user's language
* is not supported.
* @returns A promise resolving to the i18n instance
*/
export function initI18n(defaultLanguage = "en_US") {
const lng = unicodeCLDRtoBCP47(defaultLanguage);
if (typeof document !== "undefined") {
document.documentElement.dir = isRTLLanguage(defaultLanguage)
? "rtl"
: "ltr";
}
void i18n
.use(backend)
.use(initReactI18next)
.init({
compatibilityJSON: "v3",
backend: {
// this must match the path defined in routes. It's the path that the
// frontend UI code will hit to load missing translations.
loadPath: (locale: string[]) =>
cdnPath(`/locales/${unicodeBCP47toCLDR(locale[0])}.json`),
},
interpolation: {
escapeValue: false,
},
react: {
useSuspense: false,
},
lng,
// Keys are the English strings, and the server omits entries that match
// their key, so a missing entry must show the key.
fallbackLng: false,
supportedLngs: languages.map(unicodeCLDRtoBCP47),
keySeparator: false,
returnNull: false,
})
.catch((err) => {
Logger.error("Failed to initialize i18n", err);
});
return i18n;
}