Compare commits

...
Author SHA1 Message Date
bincxz a1b0596636 feat(i18n): default UI language to system locale on first launch 2026-11-23 19:07:51 +08:00
5 changed files with 370 additions and 13 deletions

No files matched your search

+2 -2
View File
@@ -91,7 +91,7 @@ import {
STORAGE_KEY_SHOW_TAB_NUMBER_BADGES,
STORAGE_KEY_DISABLE_TERMINAL_FONT_ZOOM,
} from '../../infrastructure/config/storageKeys';
import { DEFAULT_UI_LOCALE, resolveSupportedLocale } from '../../infrastructure/config/i18n';
import { resolveDefaultUiLocale, resolveSupportedLocale } from '../../infrastructure/config/i18n';
import {
areCustomKeyBindingsEqual,
nextCustomKeyBindingsSyncVersion,
@@ -357,7 +357,7 @@ export const useSettingsState = (options: { enableSettingsSync?: boolean; enable
}, []);
const [uiLanguage, setUiLanguage] = useState<UILanguage>(() => {
const stored = readStoredString(STORAGE_KEY_UI_LANGUAGE);
return resolveSupportedLocale(stored || DEFAULT_UI_LOCALE);
return resolveDefaultUiLocale(stored);
});
const [appLockSettings, setAppLockSettingsState] = useState<AppLockSettings>({
enabled: false,
@@ -0,0 +1,146 @@
import assert from "node:assert/strict";
import test from "node:test";
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { JSDOM } from "jsdom";
import { STORAGE_KEY_UI_LANGUAGE } from "../../infrastructure/config/storageKeys.ts";
import { useSettingsState } from "./useSettingsState.ts";
const withLanguageDom = async (
options: {
storedLanguage?: string;
languages?: readonly string[];
language?: string;
},
run: (env: {
dom: JSDOM;
root: Root;
setLanguageCalls: string[];
}) => Promise<void>,
) => {
const dom = new JSDOM("<!doctype html><html><body></body></html>", { url: "http://localhost" });
const globalAny = globalThis as Record<string, unknown>;
const saved = {
window: Object.getOwnPropertyDescriptor(globalThis, "window"),
document: Object.getOwnPropertyDescriptor(globalThis, "document"),
localStorage: Object.getOwnPropertyDescriptor(globalThis, "localStorage"),
navigator: Object.getOwnPropertyDescriptor(globalThis, "navigator"),
actEnv: Object.getOwnPropertyDescriptor(globalThis, "IS_REACT_ACT_ENVIRONMENT"),
};
Object.defineProperty(globalThis, "window", { configurable: true, value: dom.window });
Object.defineProperty(globalThis, "document", { configurable: true, value: dom.window.document });
Object.defineProperty(globalThis, "localStorage", { configurable: true, value: dom.window.localStorage });
Object.defineProperty(globalThis, "navigator", {
configurable: true,
value: {
languages: options.languages ?? [],
language: options.language ?? "",
},
});
Object.defineProperty(globalAny, "IS_REACT_ACT_ENVIRONMENT", { configurable: true, value: true });
const setLanguageCalls: string[] = [];
dom.window.netcatty = {
setLanguage: async (language: string) => {
setLanguageCalls.push(language);
return true;
},
notifySettingsChanged: () => {},
} as unknown as Window["netcatty"];
if (options.storedLanguage !== undefined) {
dom.window.localStorage.setItem(STORAGE_KEY_UI_LANGUAGE, options.storedLanguage);
}
const container = dom.window.document.createElement("div");
dom.window.document.body.appendChild(container);
const root = createRoot(container);
try {
await run({ dom, root, setLanguageCalls });
} finally {
await act(async () => {
root.unmount();
});
container.remove();
dom.window.close();
for (const [key, desc] of Object.entries(saved)) {
const targetKey = key === "actEnv" ? "IS_REACT_ACT_ENVIRONMENT" : key;
if (desc) {
Object.defineProperty(globalThis, targetKey, desc);
} else {
delete globalAny[targetKey];
}
}
}
};
test("useSettingsState defaults UI language to system locale on first launch", async () => {
await withLanguageDom(
{ languages: ["zh-CN", "en-US"], language: "zh-CN" },
async ({ dom, root, setLanguageCalls }) => {
let observedLanguage = "";
function Probe() {
const settings = useSettingsState({ enableSettingsSync: false, enableSystemEffects: false });
observedLanguage = settings.uiLanguage;
return null;
}
await act(async () => {
root.render(React.createElement(Probe));
});
assert.equal(observedLanguage, "zh-CN");
assert.equal(dom.window.localStorage.getItem(STORAGE_KEY_UI_LANGUAGE), "zh-CN");
assert.equal(dom.window.document.documentElement.lang, "zh-CN");
assert.deepEqual(setLanguageCalls, ["zh-CN"]);
},
);
});
test("useSettingsState maps Traditional Chinese priority locale on first launch", async () => {
await withLanguageDom(
{ languages: ["ja-JP", "zh-HK", "en-US"], language: "ja-JP" },
async ({ dom, root, setLanguageCalls }) => {
let observedLanguage = "";
function Probe() {
const settings = useSettingsState({ enableSettingsSync: false, enableSystemEffects: false });
observedLanguage = settings.uiLanguage;
return null;
}
await act(async () => {
root.render(React.createElement(Probe));
});
assert.equal(observedLanguage, "zh-TW");
assert.equal(dom.window.localStorage.getItem(STORAGE_KEY_UI_LANGUAGE), "zh-TW");
assert.equal(dom.window.document.documentElement.lang, "zh-TW");
assert.deepEqual(setLanguageCalls, ["zh-TW"]);
},
);
});
test("useSettingsState preserves explicit stored UI language over system locale", async () => {
await withLanguageDom(
{ storedLanguage: "en", languages: ["zh-CN"], language: "zh-CN" },
async ({ dom, root, setLanguageCalls }) => {
let observedLanguage = "";
function Probe() {
const settings = useSettingsState({ enableSettingsSync: false, enableSystemEffects: false });
observedLanguage = settings.uiLanguage;
return null;
}
await act(async () => {
root.render(React.createElement(Probe));
});
assert.equal(observedLanguage, "en");
assert.equal(dom.window.localStorage.getItem(STORAGE_KEY_UI_LANGUAGE), "en");
assert.equal(dom.window.document.documentElement.lang, "en");
assert.deepEqual(setLanguageCalls, ["en"]);
},
);
});
+3 -3
View File
@@ -14,7 +14,7 @@ import '@fontsource/jetbrains-mono/600.css';
import App from './App';
import { AppLockGate } from './components/AppLockGate';
import { loadLocaleMessages } from './application/i18n/messages';
import { DEFAULT_UI_LOCALE, resolveSupportedLocale } from './infrastructure/config/i18n';
import { resolveDefaultUiLocale } from './infrastructure/config/i18n';
import { STORAGE_KEY_UI_LANGUAGE } from './infrastructure/config/storageKeys';
import { localStorageAdapter } from './infrastructure/persistence/localStorageAdapter';
@@ -265,11 +265,11 @@ const renderApp = () => {
}
};
// Load the saved UI language before the first render (only English ships in
// Load the resolved UI language before the first render (only English ships in
// the startup chunk), so no window flashes English first. Render regardless
// if the dictionary fails to load; I18nProvider retries and falls back to en.
void loadLocaleMessages(
resolveSupportedLocale(localStorageAdapter.readString(STORAGE_KEY_UI_LANGUAGE) || DEFAULT_UI_LOCALE),
resolveDefaultUiLocale(localStorageAdapter.readString(STORAGE_KEY_UI_LANGUAGE)),
)
.catch(() => {})
.finally(() => {
+137
View File
@@ -0,0 +1,137 @@
import assert from "node:assert/strict";
import test from "node:test";
import {
DEFAULT_UI_LOCALE,
getSystemLocales,
matchSupportedLocale,
resolveDefaultUiLocale,
resolveSupportedLocale,
} from "./i18n.ts";
test("explicit stored locale always wins over system locales", () => {
assert.equal(resolveDefaultUiLocale("en", ["zh-CN", "zh-TW"]), "en");
assert.equal(resolveDefaultUiLocale("zh-TW", ["en-US"]), "zh-TW");
assert.equal(resolveDefaultUiLocale("zh-CN", ["es-MX"]), "zh-CN");
assert.equal(resolveDefaultUiLocale("ru", ["zh-CN"]), "ru");
assert.equal(resolveDefaultUiLocale("es", ["en-US"]), "es");
assert.equal(resolveDefaultUiLocale(" en ", ["zh-CN"]), "en");
});
test("stored unsupported locale falls back to DEFAULT_UI_LOCALE rather than overriding with system locale", () => {
assert.equal(resolveDefaultUiLocale("fr-FR", ["zh-CN"]), DEFAULT_UI_LOCALE);
});
test("first launch maps Simplified Chinese system locales to zh-CN", () => {
for (const tag of ["zh", "zh-CN", "zh-SG", "zh-Hans", "zh-Hans-CN", "zh-Hans-SG", "zh-Hans-HK", "zh_CN", "ZH-HANS-CN"]) {
assert.equal(resolveDefaultUiLocale(null, [tag]), "zh-CN", `expected ${tag} -> zh-CN`);
}
});
test("first launch maps Traditional Chinese system locales to zh-TW", () => {
for (const tag of ["zh-TW", "zh-HK", "zh-MO", "zh-Hant", "zh-Hant-TW", "zh-Hant-HK", "zh-Hant-US", "zh_TW", "ZH-HK"]) {
assert.equal(resolveDefaultUiLocale(null, [tag]), "zh-TW", `expected ${tag} -> zh-TW`);
}
});
test("Chinese locale matching ignores BCP-47 extension subtags", () => {
assert.equal(matchSupportedLocale("zh-u-rg-twzzzz"), "zh-CN");
assert.equal(matchSupportedLocale("zh-TW-u-nu-latn"), "zh-TW");
assert.equal(matchSupportedLocale("zh-CN-u-ca-chinese"), "zh-CN");
});
test("first launch maps Spanish, Russian, and English system locales", () => {
assert.equal(resolveDefaultUiLocale(null, ["es"]), "es");
assert.equal(resolveDefaultUiLocale(null, ["es-MX"]), "es");
assert.equal(resolveDefaultUiLocale(null, ["es-419"]), "es");
assert.equal(resolveDefaultUiLocale(null, ["ru"]), "ru");
assert.equal(resolveDefaultUiLocale(null, ["ru-RU"]), "ru");
assert.equal(resolveDefaultUiLocale(null, ["en"]), "en");
assert.equal(resolveDefaultUiLocale(null, ["en-US"]), "en");
assert.equal(resolveDefaultUiLocale(null, ["en-GB"]), "en");
});
test("first launch falls back to DEFAULT_UI_LOCALE for unsupported or empty locales", () => {
assert.equal(resolveDefaultUiLocale(null, ["fr-FR"]), DEFAULT_UI_LOCALE);
assert.equal(resolveDefaultUiLocale(undefined, ["ja-JP"]), DEFAULT_UI_LOCALE);
assert.equal(resolveDefaultUiLocale("", ["de-DE", "ko-KR"]), DEFAULT_UI_LOCALE);
assert.equal(resolveDefaultUiLocale(" ", []), DEFAULT_UI_LOCALE);
assert.equal(resolveDefaultUiLocale(null, null), DEFAULT_UI_LOCALE);
assert.equal(matchSupportedLocale("fr-FR"), null);
assert.equal(matchSupportedLocale("ja-JP"), null);
assert.equal(matchSupportedLocale(""), null);
});
test("first launch respects multi-locale priority lists", () => {
assert.equal(resolveDefaultUiLocale(null, ["ja-JP", "zh-TW", "en-US"]), "zh-TW");
assert.equal(resolveDefaultUiLocale(null, ["fr-FR", "zh-HK", "zh-CN"]), "zh-TW");
assert.equal(resolveDefaultUiLocale(null, ["de-DE", "es-MX", "zh-CN"]), "es");
assert.equal(resolveDefaultUiLocale(null, ["ja-JP", "en-US", "zh-CN"]), "en");
assert.equal(resolveDefaultUiLocale(null, ["", " ", "ru-RU"]), "ru");
});
test("resolveSupportedLocale handles regional and script variants cleanly", () => {
assert.equal(resolveSupportedLocale("zh-HK"), "zh-TW");
assert.equal(resolveSupportedLocale("zh-Hant-TW"), "zh-TW");
assert.equal(resolveSupportedLocale("zh-Hans-CN"), "zh-CN");
assert.equal(resolveSupportedLocale("es-MX"), "es");
assert.equal(resolveSupportedLocale("ru-RU"), "ru");
assert.equal(resolveSupportedLocale("fr-FR"), DEFAULT_UI_LOCALE);
});
test("getSystemLocales falls back from navigator.languages to navigator.language", () => {
assert.deepEqual(
getSystemLocales({ languages: ["ja-JP", "zh-TW"], language: "ja-JP" }),
["ja-JP", "zh-TW"],
);
assert.deepEqual(
getSystemLocales({ languages: [], language: "zh-CN" }),
["zh-CN"],
);
assert.deepEqual(
getSystemLocales({ languages: ["fr-FR"], language: "ru-RU" }),
["fr-FR", "ru-RU"],
);
assert.deepEqual(getSystemLocales(null), []);
assert.deepEqual(getSystemLocales(undefined), []);
});
test("resolveDefaultUiLocale handles missing global navigator safely", () => {
const savedDescriptor = Object.getOwnPropertyDescriptor(globalThis, "navigator");
Object.defineProperty(globalThis, "navigator", {
configurable: true,
value: undefined,
});
try {
assert.deepEqual(getSystemLocales(), []);
assert.equal(resolveDefaultUiLocale(null), DEFAULT_UI_LOCALE);
assert.equal(resolveDefaultUiLocale("zh-CN"), "zh-CN");
} finally {
if (savedDescriptor) {
Object.defineProperty(globalThis, "navigator", savedDescriptor);
} else {
delete (globalThis as Record<string, unknown>).navigator;
}
}
});
test("resolveDefaultUiLocale reads global navigator when systemLocales is omitted", () => {
const savedDescriptor = Object.getOwnPropertyDescriptor(globalThis, "navigator");
Object.defineProperty(globalThis, "navigator", {
configurable: true,
value: {
languages: ["ja-JP", "zh-HK", "en-US"],
language: "ja-JP",
},
});
try {
assert.equal(resolveDefaultUiLocale(null), "zh-TW");
assert.equal(resolveDefaultUiLocale("en"), "en");
} finally {
if (savedDescriptor) {
Object.defineProperty(globalThis, "navigator", savedDescriptor);
} else {
delete (globalThis as Record<string, unknown>).navigator;
}
}
});
+82 -8
View File
@@ -14,17 +14,91 @@ export const SUPPORTED_UI_LOCALES: LocaleOption[] = [
{ id: 'zh-TW', label: '繁體中文' },
];
const isSupportedLocale = (locale: string): boolean => {
return SUPPORTED_UI_LOCALES.some((l) => l.id === locale);
const TRADITIONAL_CHINESE_REGIONS = new Set(['tw', 'hk', 'mo']);
export const matchSupportedLocale = (locale: string): string | null => {
if (typeof locale !== 'string') return null;
const normalized = locale.trim().replace(/_/g, '-');
if (!normalized) return null;
const rawParts = normalized.split('-').filter(Boolean);
if (rawParts.length === 0) return null;
const lowerParts = rawParts.map((part) => part.toLowerCase());
const primary = lowerParts[0];
if (primary === 'zh') {
// Stop before BCP-47 extension/private-use singletons (e.g. -u-, -t-, -x-).
const coreSubtags: string[] = [];
for (let i = 1; i < lowerParts.length; i += 1) {
if (lowerParts[i].length === 1) break;
coreSubtags.push(lowerParts[i]);
}
if (coreSubtags.includes('hant')) return 'zh-TW';
if (coreSubtags.includes('hans')) return 'zh-CN';
if (coreSubtags.some((part) => TRADITIONAL_CHINESE_REGIONS.has(part))) {
return 'zh-TW';
}
return 'zh-CN';
}
const normalizedLower = lowerParts.join('-');
const exact = SUPPORTED_UI_LOCALES.find((l) => l.id.toLowerCase() === normalizedLower)?.id;
if (exact) return exact;
const baseExact = SUPPORTED_UI_LOCALES.find((l) => l.id.toLowerCase() === primary)?.id;
if (baseExact) return baseExact;
const basePrefix = SUPPORTED_UI_LOCALES.find((l) =>
l.id.toLowerCase().startsWith(`${primary}-`),
)?.id;
if (basePrefix) return basePrefix;
return null;
};
export const resolveSupportedLocale = (locale: string): string => {
if (isSupportedLocale(locale)) return locale;
const base = locale.split('-')[0] || locale;
const baseExact = SUPPORTED_UI_LOCALES.find((l) => l.id === base)?.id;
if (baseExact) return baseExact;
const basePrefix = SUPPORTED_UI_LOCALES.find((l) => l.id.startsWith(`${base}-`))?.id;
if (basePrefix) return basePrefix;
return matchSupportedLocale(locale) ?? DEFAULT_UI_LOCALE;
};
export function getSystemLocales(
nav?: Partial<Pick<Navigator, 'languages' | 'language'>> | null,
): readonly string[] {
const source = arguments.length === 0
? (typeof navigator !== 'undefined' ? navigator : undefined)
: nav;
if (!source) return [];
const locales: string[] = [];
if (Array.isArray(source.languages)) {
for (const locale of source.languages) {
if (typeof locale === 'string' && locale.trim()) {
locales.push(locale);
}
}
}
if (typeof source.language === 'string' && source.language.trim()) {
if (!locales.includes(source.language)) {
locales.push(source.language);
}
}
return locales;
}
export const resolveDefaultUiLocale = (
storedLocale: string | null | undefined,
systemLocales?: readonly string[] | null,
): string => {
const trimmedStored = typeof storedLocale === 'string' ? storedLocale.trim() : '';
if (trimmedStored) {
return resolveSupportedLocale(trimmedStored);
}
const candidates = systemLocales === undefined ? getSystemLocales() : (systemLocales ?? []);
for (const candidate of candidates) {
const matched = matchSupportedLocale(candidate);
if (matched) return matched;
}
return DEFAULT_UI_LOCALE;
};