Open History to see the last commit
1export const SYSTEM_LANGUAGE = "system";
2
3// Shown in their own language so a user can find theirs from any UI language.
4const NATIVE_LANGUAGE_NAMES: Readonly<Record<string, string>> = {
5 en: "English",
6 de: "Deutsch",
7 es: "Español",
8 fr: "Français",
9 ja: "日本語",
10 ko: "한국어",
11 "pt-BR": "Português (Brasil)",
12 ru: "Русский",
13 sv: "Svenska",
14 zh: "中文(简体)",
15};
16
17export function nativeLanguageName(locale: string): string {
18 return NATIVE_LANGUAGE_NAMES[locale] ?? locale;
19}
20
21// Our `zh` is Simplified, so Traditional tags only match an exact locale.
22const TRADITIONAL_CHINESE = /^zh[-_](hant|tw|hk|mo)\b/;
23
24function matchSupportedLocale(tag: string, supported: ReadonlyArray<string>): string | undefined {
25 const normalized = tag.trim().toLowerCase();
26 const language = normalized.split(/[-_]/)[0];
27 const exact = supported.find((locale) => locale.toLowerCase() === normalized);
28 if (exact || TRADITIONAL_CHINESE.test(normalized)) return exact;
29 return supported.find((locale) => locale.toLowerCase() === language);
30}
31
32/** Saved setting to active locale; "system" and unknown values follow the host's languages. */
33export function resolveLocale(
34 language: string,
35 systemLocales: ReadonlyArray<string>,
36 supported: ReadonlyArray<string>,
37 fallback: string,
38): string {
39 return resolveLocaleSelection(language, systemLocales, supported, fallback).catalogLocale;
40}
41
42/** Keep the matching system tag for regional formats while loading a supported catalog. */
43export function resolveLocaleSelection(
44 language: string,
45 systemLocales: ReadonlyArray<string>,
46 supported: ReadonlyArray<string>,
47 fallback: string,
48): { readonly catalogLocale: string; readonly formattingLocale: string } {
49 if (supported.includes(language)) return { catalogLocale: language, formattingLocale: language };
50 for (const tag of systemLocales) {
51 const match = matchSupportedLocale(tag, supported);
52 if (match) return { catalogLocale: match, formattingLocale: tag.trim().replaceAll("_", "-") };
53 }
54 return { catalogLocale: fallback, formattingLocale: fallback };
55}