diff --git a/application/state/useSettingsState.ts b/application/state/useSettingsState.ts index bae4867ab..7cb5c2808 100644 --- a/application/state/useSettingsState.ts +++ b/application/state/useSettingsState.ts @@ -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(() => { const stored = readStoredString(STORAGE_KEY_UI_LANGUAGE); - return resolveSupportedLocale(stored || DEFAULT_UI_LOCALE); + return resolveDefaultUiLocale(stored); }); const [appLockSettings, setAppLockSettingsState] = useState({ enabled: false, diff --git a/application/state/useSettingsState.uiLanguage.test.ts b/application/state/useSettingsState.uiLanguage.test.ts new file mode 100644 index 000000000..ec2c6e854 --- /dev/null +++ b/application/state/useSettingsState.uiLanguage.test.ts @@ -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, +) => { + const dom = new JSDOM("", { url: "http://localhost" }); + const globalAny = globalThis as Record; + 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"]); + }, + ); +}); diff --git a/index.tsx b/index.tsx index 714f87355..1d0058388 100755 --- a/index.tsx +++ b/index.tsx @@ -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(() => { diff --git a/infrastructure/config/i18n.test.ts b/infrastructure/config/i18n.test.ts new file mode 100644 index 000000000..f9080aa3a --- /dev/null +++ b/infrastructure/config/i18n.test.ts @@ -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).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).navigator; + } + } +}); diff --git a/infrastructure/config/i18n.ts b/infrastructure/config/i18n.ts index f713ca734..28d3c6ead 100644 --- a/infrastructure/config/i18n.ts +++ b/infrastructure/config/i18n.ts @@ -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> | 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; };