Merge pull request #413 from BlackGownQ/feat/i18n-zh-cn

feat(i18n): add Simplified Chinese locale using the existing translation layer
This commit is contained in:
BaaRai
2026-11-20 20:00:03 +01:00
committed by GitHub
6 changed files with 2793 additions and 38 deletions
+1 -1
View File
@@ -16,7 +16,7 @@
"test:polling": "node --test scripts/polling.test.mjs",
"test:replay": "node --test scripts/replay.test.mjs",
"test:upload": "node --test scripts/upload.test.mjs",
"test:i18n": "node scripts/check-i18n.mjs"
"test:i18n": "node scripts/check-i18n.mjs && node --test scripts/i18n.test.mjs"
},
"lint-staged": {
"*.{js,ts,jsx,tsx}": [
+27 -30
View File
@@ -2,11 +2,14 @@ import { readFileSync, readdirSync, statSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
// Every literal t("...") / t('...') key must exist in the locale dictionary
// with the same {placeholders}. Dynamic keys (variables, template literals
// with ${}) are skipped: there is nothing to compare them against.
// English source text is the key. Check every shipped dictionary, including
// dynamic entries, while retaining the existing literal-call coverage check.
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const dict = JSON.parse(readFileSync(join(root, "src/i18n/locales/tr.json"), "utf8"));
const localeDir = join(root, "src/i18n/locales");
const dictionaries = readdirSync(localeDir)
.filter((name) => name.endsWith(".json"))
.sort()
.map((name) => [name, JSON.parse(readFileSync(join(localeDir, name), "utf8"))]);
const files = [];
function walk(dir) {
@@ -19,7 +22,7 @@ function walk(dir) {
}
walk(join(root, "src"));
const calls = new Map(); // key -> first file that uses it
const calls = new Map();
const literalCall = /(?:^|[^\w$.])t\(\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)')/gm;
for (const file of files) {
const src = readFileSync(file, "utf8");
@@ -31,34 +34,28 @@ for (const file of files) {
}
function placeholders(s) {
return [...s.matchAll(/\{(\w+)\}/g)]
.map((m) => m[1])
.sort()
.join(",");
return [...s.matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort().join(",");
}
const missing = [];
const mismatch = [];
for (const [key, file] of calls) {
if (!Object.prototype.hasOwnProperty.call(dict, key)) {
missing.push(`${file}: ${JSON.stringify(key)}`);
continue;
}
if (placeholders(dict[key]) !== placeholders(key)) {
mismatch.push(`${JSON.stringify(key)}: source {${placeholders(key)}} dict {${placeholders(dict[key])}}`);
const allKeys = new Set(dictionaries.flatMap(([, dict]) => Object.keys(dict)));
const errors = [];
if (!dictionaries.length) errors.push("No locale dictionaries found");
for (const [name, dict] of dictionaries) {
for (const key of new Set([...allKeys, ...calls.keys()])) {
if (!Object.prototype.hasOwnProperty.call(dict, key)) {
errors.push(`${name}: missing ${JSON.stringify(key)} (${calls.get(key) ?? "dictionary parity"})`);
continue;
}
const value = dict[key];
if (typeof value !== "string" || !value.trim()) {
errors.push(`${name}: empty or non-string value for ${JSON.stringify(key)}`);
} else if (placeholders(value) !== placeholders(key)) {
errors.push(`${name}: placeholder mismatch for ${JSON.stringify(key)}`);
}
}
console.log(`i18n: ${calls.size} literal keys checked against ${Object.keys(dict).length} ${name} entries`);
}
if (missing.length || mismatch.length) {
if (missing.length) {
console.error(`Missing tr.json entries (${missing.length}):\n${missing.join("\n")}`);
}
if (mismatch.length) {
console.error(`Placeholder mismatches (${mismatch.length}):\n${mismatch.join("\n")}`);
}
if (errors.length) {
console.error(errors.join("\n"));
process.exit(1);
}
console.log(
`i18n: ${calls.size} literal keys checked against ${Object.keys(dict).length} tr.json entries`,
);
+93
View File
@@ -0,0 +1,93 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { createRequire } from "node:module";
import test from "node:test";
import vm from "node:vm";
import ts from "typescript";
const sourceURL = new URL("../src/i18n/index.ts", import.meta.url);
const require = createRequire(sourceURL);
const code = ts.transpileModule(readFileSync(sourceURL, "utf8"), {
compilerOptions: { module: ts.ModuleKind.CommonJS, esModuleInterop: true },
}).outputText;
function load({ saved = null, languages = ["en-US"], language = "en-US", blocked = false, server = false } = {}) {
const writes = [];
let reloads = 0;
const context = { exports: {}, require };
if (!server) {
context.document = { documentElement: { lang: "en" } };
context.window = {
localStorage: {
getItem(key) {
assert.equal(key, "artex.locale");
if (blocked) throw new Error("Storage blocked");
return saved;
},
setItem(key, value) {
if (blocked) throw new Error("Storage blocked");
writes.push([key, value]);
},
},
navigator: { languages, language },
location: { reload: () => { reloads++; } },
};
}
vm.runInNewContext(code, context, { filename: "i18n/index.js" });
return { api: context.exports, document: context.document, writes, reloads: () => reloads };
}
test("static export remains English and unknown keys fall back safely", () => {
const { api } = load({ server: true });
assert.equal(api.locale, "en");
assert.equal(api.intlLocale, "en-US");
assert.equal(api.t("Unknown {value}", { value: 3 }), "Unknown 3");
});
test("saved Chinese preference wins and sets the document and Intl locale", () => {
const { api, document } = load({ saved: "zh-CN", languages: ["tr-TR"] });
assert.equal(api.locale, "zh-CN");
assert.equal(api.intlLocale, "zh-CN");
assert.equal(document.documentElement.lang, "zh-CN");
assert.equal(api.t("Language"), "语言");
assert.equal(api.t("{count} tasks", { count: 3 }), "3 个任务");
assert.equal(api.t("Task #{id}"), "任务 #{id}");
assert.equal(api.t("constructor"), "constructor");
assert.equal(api.t("toString"), "toString");
assert.equal(api.t("__proto__"), "__proto__");
assert.equal(api.t("{count} tasks", Object.create({ count: 3 })), "{count} 个任务");
});
test("Chinese browser tags, fallback languages, invalid preferences and blocked storage", () => {
for (const tag of ["zh", "zh-CN", "zh-SG", "zh-Hans-CN", "ZH-cn"]) {
assert.equal(load({ languages: [tag] }).api.locale, "zh-CN");
}
assert.equal(load({ saved: "invalid", languages: ["fr-FR", "zh-CN"] }).api.locale, "zh-CN");
assert.equal(load({ blocked: true, languages: ["zh-CN"] }).api.locale, "zh-CN");
assert.equal(load({ languages: null, language: "zh-CN" }).api.locale, "zh-CN");
assert.equal(load({ languages: [], language: "zh-CN" }).api.locale, "en");
assert.equal(load({ languages: ["fr-FR"] }).api.locale, "en");
});
test("existing English and Turkish preferences and formatting are preserved", () => {
const english = load({ saved: "en", languages: ["zh-CN"] }).api;
const turkish = load({ saved: "tr", languages: ["zh-CN"] }).api;
assert.equal(english.locale, "en");
assert.equal(english.t("Language"), "Language");
assert.equal(turkish.locale, "tr");
assert.equal(turkish.intlLocale, "tr-TR");
assert.equal(turkish.t("Language"), "Dil");
assert.equal(load({ languages: ["tr-TR"] }).api.locale, "tr");
});
test("switching persists the existing storage key and reloads once", () => {
const state = load();
state.api.setLocale("en");
assert.equal(state.reloads(), 0);
state.api.setLocale("zh-CN");
assert.deepEqual(state.writes, [["artex.locale", "zh-CN"]]);
assert.equal(state.reloads(), 1);
const blocked = load({ blocked: true });
assert.doesNotThrow(() => blocked.api.setLocale("zh-CN"));
assert.equal(blocked.reloads(), 1);
});
+29
View File
@@ -0,0 +1,29 @@
# UI localization
English source text is the translation key. `t(key, vars)` is shared by React
components, module constants, toasts and non-React helpers; missing keys fall back
to English. Keep keys, `{name}` placeholders, HTML formatting tags, Go template
actions and literal command/API examples intact when adding translations.
The registered locales are English (`en`), Turkish (`tr`) and Simplified Chinese
(`zh-CN`). The Preferences language control renders `LOCALES` directly. A saved
`artex.locale` browser preference takes priority over browser language detection;
otherwise an exact language tag, then its base language, is matched. Chinese
browser variants use the available Simplified Chinese dictionary. Static export
and unsupported languages retain the English default. Switching language saves
the preference and reloads the page, following the existing module-level design.
To add a locale, add `locales/<code>.json` and register it in `Locale`, `LOCALES`,
`DICTIONARIES` and `INTL_LOCALES` in `index.ts`. Date/number formatting uses
`intlLocale`, and the HTML `lang` attribute follows the selected locale.
Run `npm run test:i18n` and `npm run build:static` from `web/`. The dictionary
checker covers every locale, checks literal call sites, requires matching keys
including dynamic entries, and validates placeholders. Runtime tests exercise
language detection, persistence, English fallback and prototype-safe lookups.
The initial Simplified Chinese dictionary reuses Chinese wording from this
repository's parent of commit `e233c02` (the English translation migration), with
additional translations for current functionality and normalized UI terminology.
This only localizes interface text; backend data, user content, model responses,
protocol identifiers and tool output are not rewritten.
+21 -7
View File
@@ -8,11 +8,12 @@
// setLocale() stores the choice and reloads. That keeps t() usable anywhere (components,
// module constants, toasts, non-React helpers) without hooks or re-render plumbing.
//
// To translate the UI into another language, add locales/<code>.json and list it in LOCALES.
// To translate the UI into another language, add locales/<code>.json and register it below.
import tr from "./locales/tr.json";
import zhCN from "./locales/zh-CN.json";
export type Locale = "tr" | "en";
export type Locale = "tr" | "en" | "zh-CN";
// Used when nothing is saved and the browser language is not one of LOCALES,
// and for the static prerender, which has no browser.
@@ -21,6 +22,7 @@ export const DEFAULT_LOCALE: Locale = "en";
export const LOCALES: { code: Locale; label: string }[] = [
{ code: "tr", label: "Türkçe" },
{ code: "en", label: "English" },
{ code: "zh-CN", label: "简体中文" },
];
const STORAGE_KEY = "artex.locale";
@@ -28,6 +30,13 @@ const STORAGE_KEY = "artex.locale";
const DICTIONARIES: Record<Locale, Record<string, string>> = {
tr: tr as Record<string, string>,
en: {},
"zh-CN": zhCN as Record<string, string>,
};
const INTL_LOCALES: Record<Locale, string> = {
tr: "tr-TR",
en: "en-US",
"zh-CN": "zh-CN",
};
function detectLocale(): Locale {
@@ -35,13 +44,18 @@ function detectLocale(): Locale {
if (typeof window === "undefined") return DEFAULT_LOCALE;
try {
const saved = window.localStorage.getItem(STORAGE_KEY);
if (saved === "tr" || saved === "en") return saved;
const match = LOCALES.find((l) => l.code === saved);
if (match) return match.code;
} catch {
/* storage blocked: fall through to the browser language */
}
for (const lang of window.navigator.languages ?? [window.navigator.language]) {
const base = lang?.toLowerCase().split("-")[0];
const match = LOCALES.find((l) => l.code === base);
const tag = lang?.toLowerCase();
const base = tag?.split("-")[0];
// Prefer a full BCP 47 match, then the available locale for that language.
const match =
LOCALES.find((l) => l.code.toLowerCase() === tag) ??
LOCALES.find((l) => l.code.toLowerCase().split("-")[0] === base);
if (match) return match.code;
}
return DEFAULT_LOCALE;
@@ -52,7 +66,7 @@ export const locale: Locale = detectLocale();
if (typeof document !== "undefined") document.documentElement.lang = locale;
/** BCP 47 tag for Intl / toLocaleString calls, e.g. date.toLocaleString(intlLocale). */
export const intlLocale = locale === "tr" ? "tr-TR" : "en-US";
export const intlLocale = INTL_LOCALES[locale];
const dict = DICTIONARIES[locale];
@@ -71,7 +85,7 @@ export function setLocale(next: Locale) {
try {
window.localStorage.setItem(STORAGE_KEY, next);
} catch {
/* storage blocked: the switch lasts only until the next load */
/* storage blocked: fall back to browser-language detection on reload */
}
window.location.reload();
}
File diff suppressed because it is too large Load Diff