mirror of
https://github.com/outline/outline.git
synced 2026-11-20 21:23:06 +03:00
* 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
62 lines
2.0 KiB
TypeScript
62 lines
2.0 KiB
TypeScript
import type { i18n } from "i18next";
|
|
import { languages } from "@shared/i18n";
|
|
import type { locales } from "@shared/utils/date";
|
|
import { unicodeCLDRtoBCP47 } from "@shared/utils/date";
|
|
import { isRTLLanguage } from "@shared/utils/rtl";
|
|
import Desktop from "./Desktop";
|
|
|
|
/**
|
|
* Detects the user's language based on the browser's language settings. A
|
|
* language without a region, such as "ja", resolves to its most likely region.
|
|
*
|
|
* @returns The user's language in CLDR format (en_US)
|
|
*/
|
|
export function detectLanguage() {
|
|
try {
|
|
const { language, region } = new Intl.Locale(navigator.language).maximize();
|
|
if (region) {
|
|
return `${language}_${region}` as keyof typeof locales;
|
|
}
|
|
} catch (_err) {
|
|
// invalid language tag, fall back to splitting the string
|
|
}
|
|
|
|
const [ln, r] = navigator.language.split("-");
|
|
const region = (r || ln).toUpperCase();
|
|
return `${ln}_${region}` as keyof typeof locales;
|
|
}
|
|
|
|
/**
|
|
* Changes the language of the app, and updates the spellchecker language
|
|
* if running in the desktop shell. An unsupported language is ignored.
|
|
*
|
|
* @param locale The locale to change to, in CLDR format (en_US)
|
|
* @param instance The i18n instance to use
|
|
*/
|
|
export async function changeLanguage(
|
|
locale: string | null | undefined,
|
|
instance: i18n
|
|
) {
|
|
const language = languages.find((value) => value === locale);
|
|
|
|
// An unsupported language keeps the current language.
|
|
if (!language) {
|
|
return;
|
|
}
|
|
|
|
// Languages are stored in en_US format in the database, however the
|
|
// frontend translation framework (i18next) expects en-US
|
|
const localeBCP = unicodeCLDRtoBCP47(language);
|
|
|
|
if (instance.languages?.[0] !== localeBCP) {
|
|
await instance.changeLanguage(localeBCP);
|
|
}
|
|
|
|
// i18n can start in this locale, so set the spellchecker in all cases.
|
|
await Desktop.bridge?.setSpellCheckerLanguages(["en-US", localeBCP]);
|
|
|
|
if (typeof document !== "undefined") {
|
|
document.documentElement.dir = isRTLLanguage(language) ? "rtl" : "ltr";
|
|
}
|
|
}
|