feedback5 WI: UI strings through t() with an English switch on the title screen and in 设置; pilot screens converted
public/i18n/en.json: Chinese msgid -> English, seeded from PR #70 (@YuriRestia, credited) for every Chinese literal of the current code (≈830 entries; 966 of the 1 036 literals left for phase 2 already translated), completed by hand in the official EN terms. public/js/ui/lang.js: boot language (?lang=en|zh, then localStorage sp.pref.lang, else Chinese; the browser language is not consulted), switchLang, useLang, LangToggle; main.js renders after initLang and re-renders in place on a switch, and translates server texts (m.toast / m.ticker frames, room.closed reasons, error codes via ui/toasts.js describeError). Converted: title screen (English title, wordmark hidden), lobby, room, settings (语言 row, On/Off, quality, hotkeys), the shell (crash screen, toasts) and DifficultyTag. tools/i18n.mjs: extract (msgids + untranslated literals per file), check (msgids missing from en.json), codemod (html`` text / attributes / strings / template literals -> t(), nested strings, N_ for module level, i18n-ignore lines), seed (fill en.json from a msgid map).
This commit is contained in:
1 parent
e596478bef
commit
a12a539e4d
13 files changed
+2102
-171
No files matched your search
@@ -0,0 +1,162 @@
|
||||
// i18n core (shared/i18n.js) and the UI string table (public/i18n/en.json): t() / tc() fallback and params, plurals,
|
||||
// lists, data names, language state, the server message wire format (msg → wireMessage → translateWire), and the
|
||||
// tooling's msgid derivation (tools/i18n.mjs). docs/I18N.md.
|
||||
|
||||
import { test, afterEach } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
t, tc, N_, setLang, getLang, onLangChange, addMessages, setMessages, hasMessage, normalizeLang, format, setNameResolver,
|
||||
tName, dn, msg, renderMessage, wireMessage, translateWire, DEFAULT_LANG,
|
||||
} from '../shared/i18n.js';
|
||||
import { templateMsgid, paramName, quote, codemodSource, scanSource } from '../tools/i18n.mjs';
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const EN = JSON.parse(readFileSync(path.join(ROOT, 'public/i18n/en.json'), 'utf8'));
|
||||
|
||||
afterEach(() => { setLang('zh'); setMessages('en', {}); setNameResolver(null); });
|
||||
|
||||
test('t(): Chinese is the default and the msgid; a missing translation falls back to the Chinese text', () => {
|
||||
assert.equal(getLang(), DEFAULT_LANG);
|
||||
addMessages('en', { 整备区已满: 'Bench is full' });
|
||||
assert.equal(t('整备区已满'), '整备区已满', 'zh shows the msgid');
|
||||
setLang('en');
|
||||
assert.equal(t('整备区已满'), 'Bench is full');
|
||||
assert.equal(t('没有翻译的句子'), '没有翻译的句子', 'untranslated → Chinese');
|
||||
assert.equal(t(null), '');
|
||||
assert.equal(t(42), '42');
|
||||
assert.equal(hasMessage('整备区已满'), true);
|
||||
assert.equal(hasMessage('没有翻译的句子'), false);
|
||||
assert.equal(hasMessage('没有翻译的句子', 'zh'), true, 'the source language has every msgid');
|
||||
});
|
||||
|
||||
test('params: {name}, positional {0}, plural {n|one|other}, lists and missing values', () => {
|
||||
addMessages('en', { '还剩 {n} 秒': '{n} {n|second|seconds} left', '{0}博士对敌方领袖造成的伤害超过20%!': 'Dr. {0} dealt over 20%!' });
|
||||
assert.equal(t('还剩 {n} 秒', { n: 3 }), '还剩 3 秒');
|
||||
setLang('en');
|
||||
assert.equal(t('还剩 {n} 秒', { n: 1 }), '1 second left');
|
||||
assert.equal(t('还剩 {n} 秒', { n: 5 }), '5 seconds left');
|
||||
assert.equal(t('{0}博士对敌方领袖造成的伤害超过20%!', ['阿米娅']), 'Dr. 阿米娅 dealt over 20%!', 'array params fill {0}');
|
||||
assert.equal(format('{a} / {b}', { a: 'x' }), 'x / {b}', 'a missing value keeps the placeholder');
|
||||
assert.equal(format('{names}', { names: ['甲', '乙'] }, { lang: 'zh' }), '甲、乙');
|
||||
assert.equal(format('{names}', { names: ['A', 'B'] }, { lang: 'en' }), 'A, B');
|
||||
assert.equal(format('官方{0:0%}', { 0: 1 }), '官方{0:0%}', 'official format placeholders are not ours: untouched');
|
||||
assert.equal(format('{constructor}', {}), '{constructor}', 'no prototype lookups');
|
||||
});
|
||||
|
||||
test('tc(): a context key wins, else the plain msgid; Chinese shows the msgid', () => {
|
||||
addMessages('en', { 'toggle::关闭': 'Off', 关闭: 'Close' });
|
||||
assert.equal(tc('toggle', '关闭'), '关闭');
|
||||
setLang('en');
|
||||
assert.equal(tc('toggle', '关闭'), 'Off');
|
||||
assert.equal(tc('dialog', '关闭'), 'Close');
|
||||
assert.equal(t('关闭'), 'Close');
|
||||
assert.equal(N_('标记'), '标记', 'N_ only marks a msgid');
|
||||
});
|
||||
|
||||
test('data names: { dn } params and tName go through the resolver, only outside Chinese; player names never do', () => {
|
||||
setNameResolver((name) => ({ 琳琅诗怀雅: 'Swire the Elegant Wit', 阿米娅: 'Amiya' })[name] || name);
|
||||
addMessages('en', { '{names}只能部署在召唤者攻击范围内,已退回整备区': '{names} were returned to the Bench', '{name}博士中途退出了模拟': 'Dr. {name} left the simulation' });
|
||||
const m = msg('{names}只能部署在召唤者攻击范围内,已退回整备区', { names: ['琳琅诗怀雅', '无名'].map(dn) });
|
||||
assert.equal(translateWire(wireMessage(m)), '琳琅诗怀雅、无名只能部署在召唤者攻击范围内,已退回整备区', 'zh: names as sent');
|
||||
setLang('en');
|
||||
assert.equal(translateWire(wireMessage(m)), 'Swire the Elegant Wit, 无名 were returned to the Bench');
|
||||
// a player called 阿米娅 stays 阿米娅 (plain string param, not dn)
|
||||
assert.equal(translateWire(wireMessage(msg('{name}博士中途退出了模拟', { name: '阿米娅' }))), 'Dr. 阿米娅 left the simulation');
|
||||
assert.equal(tName('阿米娅'), 'Amiya');
|
||||
setLang('zh');
|
||||
assert.equal(tName('阿米娅'), '阿米娅');
|
||||
});
|
||||
|
||||
test('language state: setLang normalizes, notifies listeners once per change; normalizeLang', () => {
|
||||
const seen = [];
|
||||
const off = onLangChange((l, prev) => seen.push(`${prev}>${l}`));
|
||||
assert.equal(setLang('en-US'), true);
|
||||
assert.equal(setLang('en'), false, 'no change, no event');
|
||||
assert.equal(setLang('xx'), true, 'unknown → default zh');
|
||||
off();
|
||||
setLang('en');
|
||||
assert.deepEqual(seen, ['zh>en', 'en>zh']);
|
||||
assert.equal(normalizeLang('zh_CN'), 'zh');
|
||||
assert.equal(normalizeLang('EN'), 'en');
|
||||
assert.equal(normalizeLang('fr'), null);
|
||||
assert.equal(normalizeLang(undefined), null);
|
||||
});
|
||||
|
||||
test('server wire format: text keeps the Chinese rendering for older clients; params are sanitized', () => {
|
||||
assert.deepEqual(wireMessage('整备区已满,获得的装备已销毁'), { text: '整备区已满,获得的装备已销毁' });
|
||||
const w = wireMessage(msg('【{label}】层数达成,获得{gain}资金', { label: dn('奇迹'), gain: 20, evil: { x: 1 }, 'bad key': 1 }));
|
||||
assert.deepEqual(w, { text: '【奇迹】层数达成,获得20资金', msgid: '【{label}】层数达成,获得{gain}资金', params: { label: { dn: '奇迹' }, gain: 20, evil: null } });
|
||||
assert.equal(renderMessage(msg('{who}:获得{name}', { who: dn('歌蕾蒂娅'), name: dn('斯卡蒂') })), '歌蕾蒂娅:获得斯卡蒂');
|
||||
// a frame from an older server (no msgid): its text is the msgid
|
||||
addMessages('en', { 隐秘核心已解锁: 'Hidden Core unlocked' });
|
||||
setLang('en');
|
||||
assert.equal(translateWire({ text: '隐秘核心已解锁' }), 'Hidden Core unlocked');
|
||||
assert.equal(translateWire({ text: 'Doctor 7 博士的目标生命值已耗尽' }), 'Doctor 7 博士的目标生命值已耗尽', 'unknown text shows as is');
|
||||
assert.equal(translateWire(null), '');
|
||||
});
|
||||
|
||||
test('public/i18n/en.json: valid, English values, placeholders kept, the pilot screens and server messages translated', () => {
|
||||
const entries = Object.entries(EN).filter(([k]) => !k.startsWith('_'));
|
||||
assert.ok(entries.length > 800, `seeded from PR #70: ${entries.length}`);
|
||||
for (const [k, v] of entries) {
|
||||
assert.equal(typeof v, 'string', k);
|
||||
assert.ok(v.trim(), `empty translation for ${k}`);
|
||||
assert.ok(!/[一-鿿]/.test(v.replace(/\{[^{}]*\}/g, '')), `Chinese left in the translation of ${k}: ${v}`);
|
||||
const want = new Set([...k.matchAll(/\{([A-Za-z0-9_$]+)\}/g)].map((m) => m[1]));
|
||||
const have = new Set([...v.matchAll(/\{([A-Za-z0-9_$]+)(?:\|[^{}]*)?\}/g)].map((m) => m[1]));
|
||||
for (const p of want) assert.ok(have.has(p), `${k}: {${p}} missing in "${v}"`);
|
||||
}
|
||||
for (const k of ['开始', '博士代号', '设置', '语言', '同盟模拟', '创建同盟', '加入同盟', '开始模拟', 'toggle::关闭', '整备区已满',
|
||||
'{names}只能部署在召唤者攻击范围内,已退回整备区', '{name}博士的目标生命值已耗尽', '联防阶段:{names} 迎战突破防线的敌人', '【维多利亚】获得{n}件维式重锤']) {
|
||||
assert.ok(EN[k], `en.json lacks ${k}`);
|
||||
}
|
||||
});
|
||||
|
||||
test('every msgid of the pilot screens, the shell and the server messages is in public/i18n/en.json', async () => {
|
||||
const files = ['public/js/screens/title.js', 'public/js/screens/lobby.js', 'public/js/screens/room.js', 'public/js/ui/settings.js',
|
||||
'public/js/main.js', 'public/js/ui/toasts.js', 'server/match/match/messaging.js', 'server/match/player/placement.js',
|
||||
'server/match/player/basics.js', 'server/match/player/acquire.js', 'server/match/effectsMeta.js', 'server/match/match/settle.js',
|
||||
'server/match/match/platform.js', 'server/match/match/unitePhase.js', 'server/match/match/bossRounds.js',
|
||||
'server/sim/content/bonds/addon/meta.js', 'server/sim/content/bonds/core.js'];
|
||||
const missing = [];
|
||||
for (const f of files) {
|
||||
const { msgids, literals } = await scanSource(readFileSync(path.join(ROOT, f), 'utf8'), f);
|
||||
const server = f.startsWith('server/');
|
||||
for (const m of msgids) if ((!server || m.via === 'msg' || m.via === 'server') && !EN[m.msgid]) missing.push(`${f}:${m.line} ${m.msgid}`);
|
||||
if (!server) for (const l of literals) if (!l.reason) missing.push(`${f}:${l.line} not wrapped: ${l.msgid}`);
|
||||
}
|
||||
assert.deepEqual(missing, []);
|
||||
});
|
||||
|
||||
test('tools/i18n.mjs: msgids of template literals name their params; the codemod wraps text, attributes and nested strings', async () => {
|
||||
assert.equal(paramName('poolN', 0), 'poolN');
|
||||
assert.equal(paramName('info.rounds', 1), 'rounds');
|
||||
assert.equal(paramName('ids.length', 0), 'n');
|
||||
assert.equal(paramName('MAX_SEATS - 1', 2), '2');
|
||||
assert.deepEqual(templateMsgid(['战场随机(共', '张)'], ['ids.length']), { msgid: '战场随机(共{n}张)', params: [{ name: 'n', src: 'ids.length' }] });
|
||||
assert.equal(templateMsgid(['', ' / ', ''], ['a.x', 'b.x']).msgid, '{x} / {x2}', 'same name from two expressions: numbered');
|
||||
assert.equal(quote("it's\n"), "'it\\'s\\n'");
|
||||
const src = [
|
||||
"import { html } from './components.js';",
|
||||
"const TABLE = { a: '甲' };",
|
||||
"export function V({ name, n }) {",
|
||||
" if (name === '比较') return null;",
|
||||
" toast(`剩余 ${n} 名`, 'warn');",
|
||||
" return html`<p title=\"提示 ${n}\">你好 ${name || '博士'} 世界<b>${n}</b> 回合</p>`;",
|
||||
" const sample = '字体样例'; // i18n-ignore",
|
||||
"}",
|
||||
].join('\n');
|
||||
const out = await codemodSource(src, path.join(ROOT, 'public/js/ui/x.js'));
|
||||
assert.match(out.src, /import \{ t, N_ \} from '\.\.\/\.\.\/\.\.\/shared\/i18n\.js';/);
|
||||
assert.match(out.src, /const TABLE = \{ a: N_\('甲'\) \};/, 'module level: marked, not translated');
|
||||
assert.match(out.src, /name === '比较'/, 'compared literals are left alone');
|
||||
assert.match(out.src, /toast\(t\('剩余 \{n\} 名', \{ n \}\), 'warn'\)/);
|
||||
assert.match(out.src, /title=\$\{t\('提示 \{n\}', \{ n \}\)\}/);
|
||||
// a child that is not a plain value splits the run; the string inside it is wrapped too
|
||||
assert.match(out.src, />\$\{t\('你好'\)\} \$\{name \|\| t\('博士'\)\} \$\{t\('世界'\)\}<b>/);
|
||||
assert.match(out.src, /<\/b> \$\{t\('回合'\)\}<\/p>/);
|
||||
assert.equal(out.manual.length, 1);
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
// Browser check of the language switch (puppeteer-core + system Chrome; opt-in: SP_E2E=1, ~20 s):
|
||||
//
|
||||
// SP_E2E=1 node --test test/ui/i18n.e2e.test.js
|
||||
//
|
||||
// The title screen opens in Chinese; 中文 | English → English in place (no reload): the title, the start button, the
|
||||
// connection line, <html lang>, the tab title; the choice is kept across a reload (localStorage sp.pref.lang) and the
|
||||
// game-data overlay (data/i18n/en.json) is applied; `?lang=zh` switches back and leaves the address bar. No console /
|
||||
// page / request errors. docs/I18N.md.
|
||||
|
||||
import { test, describe, before, after } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { CHROME, hasChrome, sleep } from '../e2e/client.mjs';
|
||||
import { NAME_MAX_LEN } from '../../shared/constants.js';
|
||||
|
||||
const ENABLED = process.env.SP_E2E === '1' && hasChrome();
|
||||
|
||||
describe('language switch on the title screen', { skip: !ENABLED && 'set SP_E2E=1 (Chrome)' }, () => {
|
||||
let srv;
|
||||
let browser;
|
||||
let base;
|
||||
before(async () => {
|
||||
const { startServer } = await import('../../server/index.js');
|
||||
const puppeteer = (await import('puppeteer-core')).default;
|
||||
srv = await startServer({ port: 0, host: '127.0.0.1', quiet: true });
|
||||
base = `http://127.0.0.1:${srv.port}`;
|
||||
browser = await puppeteer.launch({ executablePath: CHROME, headless: true, args: ['--no-sandbox', '--force-device-scale-factor=1'] });
|
||||
});
|
||||
after(async () => { await browser?.close(); await srv?.close(); });
|
||||
|
||||
const text = (page, sel) => page.$eval(sel, (el) => el.textContent.replace(/\s+/g, ' ').trim());
|
||||
|
||||
test('中文 by default; English in place, kept across a reload; ?lang=zh back to Chinese', async () => {
|
||||
const page = await browser.newPage();
|
||||
await page.setViewport({ width: 1600, height: 900 });
|
||||
const problems = [];
|
||||
page.on('console', (m) => { if (m.type() === 'error') problems.push(`console: ${m.text()}`); });
|
||||
page.on('pageerror', (e) => problems.push(`pageerror: ${e.message}`));
|
||||
page.on('response', (r) => { if (r.status() >= 400 && !/fonts\.(googleapis|gstatic)/.test(r.url())) problems.push(`http ${r.status()}: ${r.url()}`); });
|
||||
await page.goto(`${base}/`, { waitUntil: 'networkidle0' });
|
||||
await page.waitForSelector('.title-screen [data-testid="lang-toggle"]');
|
||||
assert.equal(await text(page, '.title-cn'), '卫戍协议:盟约');
|
||||
assert.equal(await text(page, '.title-login .btn--primary'), '开始');
|
||||
assert.equal(await page.evaluate(() => document.documentElement.lang), 'zh-CN');
|
||||
|
||||
await page.click('[data-testid="lang-toggle"] button[data-lang="en"]');
|
||||
await page.waitForFunction(() => document.querySelector('.title-cn')?.textContent.includes('Stronghold Protocol'), { timeout: 8000 });
|
||||
assert.equal(await text(page, '.title-cn'), 'Stronghold Protocol: Alliance');
|
||||
assert.equal(await text(page, '.title-login .btn--primary'), 'Start');
|
||||
assert.match(await text(page, '.title-tag'), /^Allocate Funds and Operators/);
|
||||
assert.match(await text(page, '.title-conn'), /Connect|Ready to connect/);
|
||||
assert.equal(await page.$eval('.title-login input', (el) => el.placeholder), `Callsign (max ${NAME_MAX_LEN} chars)`);
|
||||
assert.deepEqual(await page.evaluate(() => ({ lang: document.documentElement.lang, title: document.title, pref: localStorage.getItem('sp.pref.lang') })),
|
||||
{ lang: 'en', title: 'Stronghold Protocol: Alliance · Web Simulation', pref: '"en"' });
|
||||
// the game texts follow (data/i18n/en.json applied by data.js)
|
||||
await page.waitForFunction(() => globalThis.__SP__?.data?.locale() === 'en', { timeout: 8000 });
|
||||
assert.equal(await page.evaluate(() => globalThis.__SP__.data.get('config').modes.mode_multi_abyss.name), 'Ultimate Simulation');
|
||||
|
||||
await page.reload({ waitUntil: 'networkidle0' });
|
||||
await page.waitForSelector('.title-screen .title-cn');
|
||||
assert.equal(await text(page, '.title-cn'), 'Stronghold Protocol: Alliance', 'the choice survives a reload');
|
||||
assert.equal(await text(page, '.title-login .btn--primary'), 'Start');
|
||||
|
||||
await page.goto(`${base}/?lang=zh`, { waitUntil: 'networkidle0' });
|
||||
await page.waitForSelector('.title-screen .title-cn');
|
||||
await sleep(200);
|
||||
assert.equal(await text(page, '.title-cn'), '卫戍协议:盟约');
|
||||
assert.equal(await page.evaluate(() => location.search), '', '?lang is removed from the address bar');
|
||||
assert.equal(await page.evaluate(() => localStorage.getItem('sp.pref.lang')), '"zh"');
|
||||
assert.deepEqual(problems, []);
|
||||
await page.close();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user