Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions web/src/i18n/__tests__/noHardcodedZh.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { readFileSync } from "node:fs";
import { join } from "node:path";
import { describe, expect, it } from "vitest";

/**
* 英文语言下的「无中文残留」回归护栏。
*
* 列表 / 统计 / 账单等页面的界面文案必须经 `tr()`(静态串)或 `trText()`(含插值的
* 动态串)取词,否则切到英文仍是中文。这里直接扫源码:剥掉注释与 `tr("…")` /
* `trText(…` 里的 msgid 后,不允许再出现中日韩字符。
*
* 允许保留的中文:注释、`tr/trText` 的中文 msgid(英文译文在 i18n/text.ts)。
*/
const FILES = [
"pages/UsersPage.tsx",
"pages/ApiKeysPage.tsx",
"pages/LogsPage.tsx",
"pages/StatsPage.tsx",
"pages/BillingPage.tsx",
"pages/stats/AuxCharts.tsx",
"pages/stats/EventsPanel.tsx",
"pages/stats/FailurePanel.tsx",
"pages/stats/GroupStatsPanel.tsx",
"pages/stats/PrivacyNotice.tsx",
"pages/stats/StatsFilters.tsx",
"pages/stats/StatsOverviewCards.tsx",
"pages/stats/TrendChartPanel.tsx",
"pages/stats/cells.tsx",
"pages/stats/compression.ts",
"pages/stats/constants.tsx",
"pages/credentials/cells.tsx",
"pages/credentials/groupHeader.tsx",
"pages/credentials/actions.tsx",
"pages/apikeys/KeyRow.tsx",
"pages/apikeys/clientEntry.tsx",
"pages/apikeys/ccSwitch.tsx",
"pages/apikeys/meta.ts",
"pages/apikeys/quota.tsx",
"components/Pagination.tsx",
];

const CJK = /[\u4e00-\u9fff]/;

/**
* 把 `tr(...)` / `trText(...)` 的实参整段抹掉(括号配对、跳过字符串与模板字面量),
* 再剥掉块注释与行注释——剩下的中文就是「会原样渲染到界面」的硬编码。
*/
function stripCalls(source: string): string {
const OPEN: Record<string, string> = { "(": ")", "[": "]", "{": "}" };
let out = "";
let i = 0;
while (i < source.length) {
const rest = source.slice(i);
const call = /\b(tr|trText)\(/.exec(rest);
if (!call) {
out += rest;
break;
}
const start = i + call.index;
out += source.slice(i, start) + call[1] + "()";
let j = start + call[0].length;
let depth = 1;
while (j < source.length && depth > 0) {
const ch = source[j];
if (ch === '"' || ch === "'" || ch === "`") {
j += 1;
while (j < source.length && source[j] !== ch) j += source[j] === "\\" ? 2 : 1;
} else if (OPEN[ch]) {
depth += 1;
} else if (ch === ")" || ch === "]" || ch === "}") {
depth -= 1;
}
j += 1;
}
i = j;
}
return out;
}

function stripTranslated(source: string): string {
return stripCalls(source)
.replace(/\/\*[\s\S]*?\*\//g, "")
.split("\n")
.filter((line) => !line.trim().startsWith("//"))
.join("\n");
}

describe("列表与统计页英文无中文残留", () => {
for (const file of FILES) {
it(`${file} 的界面文案均经 tr / trText 取词`, () => {
const source = readFileSync(join(process.cwd(), "src", file), "utf8");
const leftover = stripTranslated(source)
.split("\n")
.map((line, index) => ({ line: line.trim(), index: index + 1 }))
.filter(({ line }) => CJK.test(line));
expect(leftover).toEqual([]);
});
}
});
131 changes: 131 additions & 0 deletions web/src/i18n/__tests__/text.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import { render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { I18nProvider, TEXT_EN, tr, trText, setTrLang } from "@/i18n";
import { Pagination } from "@/components/Pagination";

const CJK = /[\u4e00-\u9fff]/;

afterEach(() => {
setTrLang("zh");
});

describe("就地文案翻译(源串即 msgid)", () => {
it("tr 按当前语言取词,英文缺项回落中文", () => {
setTrLang("zh");
expect(tr("上一页")).toBe("上一页");
setTrLang("en");
expect(tr("上一页")).toBe("Previous");
expect(tr("此 key 不存在")).toBe("此 key 不存在");
});

it("tr 支持 {0} 位置参数", () => {
setTrLang("en");
expect(tr("共 {0} 条 · 保留 45 天", [123])).toBe("123 total · kept 45 days");
});

it("trText 对含插值的动态串做短语替换", () => {
setTrLang("en");
expect(trText("第 2 / 3 页")).toBe("Page 2 / 3");
expect(trText("输入 100 · 输出 200")).toBe("Input 100 · Output 200");
});

it("英文词条表不含中文残留", () => {
const offenders = Object.entries(TEXT_EN).filter(([, en]) => CJK.test(en));
expect(offenders).toEqual([]);
});

// 回归:tr() 的 msgid 只要缺英文译文,英文界面就会露出中文。
// 直接扫源码里的 tr("…") 字面量(而不是渲染结果),漏译一处就红。
it("源码里每个 tr() 的 msgid 都有英文译文", () => {
setTrLang("en");
const sources = import.meta.glob("../../**/*.{ts,tsx}", {
query: "?raw",
import: "default",
eager: true,
}) as Record<string, string>;
const missing: string[] = [];
for (const [file, src] of Object.entries(sources)) {
if (file.includes("__tests__") || file.includes(".test.")) continue;
// 去掉块注释与整行注释,避免把注释里的示例文案当成待翻译项
const code = src
.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " "))
.split("\n")
.filter((line) => !/^\s*(\/\/|\*)/.test(line))
.join("\n");
for (const m of code.matchAll(/\btr\(\s*(["'])((?:[^"'\\]|\\.)*)\1/g)) {
// 源码里的转义(如 \" )要先还原成运行时字符串,才能和词条表对齐
const msgid = m[2].replace(/\\(["'`\\])/g, "$1");
if (!(msgid in TEXT_EN)) {
missing.push(`${file}: ${msgid}`);
continue;
}
// 有译文也可能仍是中文(漏译成原串),英文渲染必须无中日韩字符
if (CJK.test(tr(msgid))) missing.push(`${file}: 译后仍是中文 ${msgid}`);
}
}
expect(missing).toEqual([]);
});

// 回归:上面那条只查 tr("…") 字面量,但 trText(`…${x}…`) 的模板实参同样会渲染到界面。
// 这里把模板里的插值换成 {0} 后,既要求有英文译文,也要求译文在英文下不再含中文。
it("源码里每个 trText() 的模板串都有英文译文且译后无中文", () => {
const sources = import.meta.glob("../../**/*.{ts,tsx}", {
query: "?raw",
import: "default",
eager: true,
}) as Record<string, string>;
setTrLang("en");
const missing: string[] = [];
for (const [file, src] of Object.entries(sources)) {
if (file.includes("__tests__") || file.includes(".test.")) continue;
const code = src
.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " "))
.split("\n")
.filter((line) => !/^\s*(\/\/|\*)/.test(line))
.join("\n");
for (const m of code.matchAll(/\btrText\(\s*`((?:[^`\\]|\\.)*)`\s*\)/g)) {
// 插值表达式可能是任意代码,统一折成 {0} 与词条表对齐
const msgid = m[1].replace(/\$\{[^}]*\}/g, "{0}").replace(/\\(["'`\\])/g, "$1");
// 整个模板都是插值(如 `${a}${b}`)时没有可翻译的字面量,跳过
if (!CJK.test(msgid)) continue;
if (!(msgid in TEXT_EN)) {
missing.push(`${file}: ${msgid}`);
continue;
}
// 有译文也可能仍是中文(漏译成原串),英文渲染必须无中日韩字符
if (CJK.test(tr(msgid))) missing.push(`${file}: 译后仍是中文 ${msgid}`);
}
}
expect(missing).toEqual([]);
});

// 回归:JSX 注释里的 tr() 不是代码而是字面量,会把「tr("…")」原样渲染到页面上。
it("JSX 注释里不残留 tr() 调用", () => {
const sources = import.meta.glob("../../**/*.tsx", {
query: "?raw",
import: "default",
eager: true,
}) as Record<string, string>;
const offenders: string[] = [];
for (const [file, src] of Object.entries(sources)) {
if (file.includes("__tests__") || file.includes(".test.")) continue;
for (const m of src.matchAll(/\{\/\*[\s\S]*?\*\/\}/g)) {
if (/\btr(Text)?\(/.test(m[0])) offenders.push(`${file}: ${m[0].slice(0, 60)}`);
}
}
expect(offenders).toEqual([]);
});

it("Pagination 在英文下渲染英文分页控件", () => {
render(
<I18nProvider initial="en">
<Pagination page={0} pageSize={10} total={25} onPageChange={() => {}} onPageSizeChange={() => {}} />
</I18nProvider>,
);
expect(screen.getByTestId("pagination-page-info")).toHaveTextContent("Page 1 of 3");
expect(screen.getByTestId("pagination-prev")).toHaveTextContent("Previous");
expect(screen.getByTestId("pagination-next")).toHaveTextContent("Next");
expect(screen.getByTestId("pagination")).toHaveTextContent("Per page");
expect(screen.getByTestId("pagination")).toHaveTextContent("10 items");
});
});
14 changes: 12 additions & 2 deletions web/src/i18n/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { createContext, useCallback, useContext, useMemo, useState } from "react";
import { Fragment, createContext, useCallback, useContext, useMemo, useState } from "react";
import { EN, ZH, type MessageKey } from "./messages";
import { setTrLang } from "./text";

export { tr, trText, TEXT_EN, getTrLang, setTrLang } from "./text";

export type Lang = "zh" | "en";

Expand Down Expand Up @@ -83,6 +86,9 @@ export function I18nProvider({
initial?: Lang;
}) {
const [lang, setLangState] = useState<Lang>(() => initial ?? detectLang());
// 同步「就地文案」翻译器(tr)的当前语言;语言切换时整树重挂(下方 keyed Fragment)
// 让直接调用 tr 的组件也能重新求值。
setTrLang(lang);
const setLang = useCallback((next: Lang) => {
setLangState(next);
saveLang(next);
Expand All @@ -91,7 +97,11 @@ export function I18nProvider({
() => ({ lang, setLang, t: (key: MessageKey) => translate(key, lang) }),
[lang, setLang],
);
return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
return (
<I18nContext.Provider value={value}>
<Fragment key={lang}>{children}</Fragment>
</I18nContext.Provider>
);
}

/** 取当前语言与 `t()`。语言变化会通过 context 触发订阅者重渲染。 */
Expand Down
Loading