feat(viewer): localize interface and tutorials in 15 languages

This commit is contained in:
coyotte508 2026-09-25 16:29:20 +02:00
commit 6e1dd3dd1b
24 changed files with 17940 additions and 3 deletions

View file

@ -11,7 +11,8 @@
"build": "node scripts/build.mjs",
"test": "node --test test/*.test.js",
"dev": "node scripts/dev.mjs",
"test:browser": "pnpm build && node test/analysis-chat-browser.mjs && node test/preferences-browser.mjs && node test/new-genes-browser.mjs && node test/turn-controls-browser.mjs"
"test:browser": "pnpm build && node test/analysis-chat-browser.mjs && node test/preferences-browser.mjs && node test/new-genes-browser.mjs && node test/turn-controls-browser.mjs",
"test:locales": "node scripts/check-locales.mjs viewer/localization && node --test scripts/localization.test.mjs"
},
"dependencies": {
"@boardgamers/protocol": "0.6.0",

49
scripts/check-locales.mjs Normal file
View file

@ -0,0 +1,49 @@
import assert from "node:assert/strict";
import { readFile } from "node:fs/promises";
import { join } from "node:path";
const directory = process.argv[2];
if (!directory) {
throw Error("Usage: node check-locales.mjs <localization directory>");
}
const source = JSON.parse(await readFile(join(directory, "en.json"), "utf8"));
const placeholders = (text) =>
[...text.matchAll(/\{\w+\}/g)].map((match) => match[0]).sort();
const locales = [
"en",
"de",
"fr",
"pl",
"ro",
"el",
"hi",
"ru",
"da",
"pt-BR",
"ko",
"zh-TW",
"vi",
"it",
"nl",
];
for (const locale of locales) {
const catalog = JSON.parse(
await readFile(join(directory, `${locale}.json`), "utf8"),
);
assert.deepEqual(
Object.keys(catalog).sort(),
Object.keys(source).sort(),
`${locale}: missing or extra strings`,
);
for (const [key, text] of Object.entries(catalog)) {
assert.equal(typeof text, "string", `${locale}: ${key}`);
assert.ok(text.trim(), `${locale}: empty translation of ${key}`);
assert.deepEqual(
placeholders(text),
placeholders(source[key]),
`${locale}: changed placeholders in ${key}`,
);
}
}
console.log(
`${locales.length} languages × ${Object.keys(source).length} messages validated`,
);

View file

@ -0,0 +1,69 @@
import assert from "node:assert/strict";
import test from "node:test";
import { readFile } from "node:fs/promises";
const source = await readFile(
new URL("../viewer/localization/runtime.js", import.meta.url),
"utf8",
);
const { createTranslator, resolveLocale } = await import(
"data:text/javascript;base64," + Buffer.from(source).toString("base64")
);
const catalogs = {
nl: {
Draw: "Tekenen",
"Your cash: $": "Je geld: $",
Ore: "Erts",
east: "oost",
"{p0} · ◈ {p1}": "{p0} · ◈ {p1}",
Round: "Ronde",
"Build {p0} for {p1}": "Bouw voor {p1}: {p0}",
"{p0} buys {p1}": "{p0} koopt {p1}",
"Make money by trading": "Verdien geld door te handelen",
"Gain {p0} points{p1}": "Krijg {p0} punten{p1}",
},
fr: { Round: "Manche" },
};
test("regional language preferences select supported catalogues", () => {
assert.equal(resolveLocale("nl-BE"), "nl");
assert.equal(resolveLocale("pt-PT"), "pt-BR");
assert.equal(resolveLocale("zh-Hant-TW"), "zh-TW");
assert.equal(resolveLocale("zh-CN"), "en");
assert.equal(resolveLocale(undefined), "en");
});
test("dynamic values are reordered while player names stay unchanged", () => {
const t = createTranslator(catalogs, "nl");
t.setNames(["Draw"]);
assert.equal(t.translate("Draw buys 3"), "Draw koopt 3");
assert.equal(t.translate("Build 2 for 10"), "Bouw voor 10: 2");
assert.equal(t.translate("Draw"), "Draw");
assert.equal(t.translate("Gain 2 points"), "Krijg 2 punten");
});
test("tutorial numbering and whitespace survive translation", () => {
const t = createTranslator(catalogs, "nl");
assert.equal(
t.translate(" 1/5 · Make money by trading\n"),
" 1/5 · Verdien geld door te handelen\n",
);
assert.equal(t.translate("Round 2"), "Ronde 2");
assert.equal(t.translate("Unknown sentence"), "Unknown sentence");
});
test("language changes clear caches and preserve the English fallback", () => {
const t = createTranslator(catalogs, "nl");
assert.equal(t.translate("Round"), "Ronde");
t.setLocale("fr");
assert.equal(t.translate("Round"), "Manche");
t.setLocale("en");
assert.equal(t.translate("Round"), "Round");
});
test("icon-separated values and uppercase labels are localized", () => {
const t = createTranslator(catalogs, "nl");
assert.equal(t.translate("Ore · ◈ 10"), "Erts · ◈ 10");
assert.equal(t.translate("EAST"), "OOST");
});
test("decorative arrows and attached currency values keep their meaning", () => {
const t = createTranslator(catalogs, "nl");
assert.equal(t.translate("Draw →"), "Tekenen →");
assert.equal(t.translate("Your cash: $20"), "Je geld: $20");
});

View file

@ -1,3 +1,4 @@
import { mountLocalization, localizeTutorial } from "./localization/index.js";
import {
createBoardThumbnail,
installPlayerCards,
@ -58,6 +59,7 @@ export async function mountLesson(target, options) {
registerViewer(
"primordialSoup",
(ctx) => {
const localization = mountLocalization(ctx.target);
let pending, timeout;
const chat = new ChatController();
const ui = mountGame(ctx.target, {
@ -92,6 +94,7 @@ registerViewer(
);
},
onPreferences(preferences) {
localization.setLocale(preferences.locale);
ui.setAnalysisMode(preferences.analysis === true);
ui.setColorBlind(preferences[COLOR_BLIND_PREFERENCE.name] === true);
},
@ -99,6 +102,7 @@ registerViewer(
ui.setPlayer(player.index);
},
onState(state) {
localization.setState(state);
ui.render(state);
if (pending) {
clearTimeout(timeout);
@ -114,6 +118,7 @@ registerViewer(
}
},
destroy() {
localization.destroy();
removeCards();
thumbnail.destroy();
clearTimeout(timeout);
@ -122,5 +127,5 @@ registerViewer(
},
};
},
{ tutorial: mountLesson },
{ tutorial: localizeTutorial(mountLesson) },
);

View file

@ -0,0 +1,11 @@
# Viewer translations
The viewer follows BGS's shared `preferences.locale` value. Tutorials receive `options.locale`. Supported locales match BGS: English, German, French, Polish, Romanian, Greek, Hindi, Russian, Danish, Brazilian Portuguese, Korean, Traditional Chinese, Vietnamese, Italian and Dutch.
`en.json` contains source UI text, including tutorial explanations and engine-generated descriptions rendered by the viewer. The other catalogues use the same keys. `{p0}`, `{p1}`, etc. represent dynamic display values: translators may reorder them but must preserve every placeholder. Add or update the corresponding entries in all catalogues when changing source wording. Component names and terminology need game-specific review; translations were initially machine-assisted.
The rendering adapter translates text and accessible labels, including tooltips, without changing state, action identifiers, input values or HTML structure. It remembers source text so a language change is reversible, observes subsequent framework updates, and disconnects on viewer destruction. Player names and chat messages are excluded. `translate="no"` also excludes any element and its descendants. Keep user-provided content inside excluded elements.
For rich text that is split into icons and spans, call `translateText` on the complete sentence before splitting it; localize the tokenizer's resource labels too. This preserves sentence grammar. Avoid relying on rendered labels to identify an action—use action IDs or data attributes.
Run `node scripts/check-locales.mjs viewer/localization` to verify catalogue coverage and placeholders. The viewer's normal build and browser tests should also cover language switching, action controls, translated tutorial progression and narrow layouts. Browser text must remain readable if a translation is missing; English is the fallback.

1160
viewer/localization/da.json Normal file

File diff suppressed because it is too large Load diff

1160
viewer/localization/de.json Normal file

File diff suppressed because it is too large Load diff

1160
viewer/localization/el.json Normal file

File diff suppressed because it is too large Load diff

1160
viewer/localization/en.json Normal file

File diff suppressed because it is too large Load diff

1160
viewer/localization/fr.json Normal file

File diff suppressed because it is too large Load diff

1160
viewer/localization/hi.json Normal file

File diff suppressed because it is too large Load diff

19
viewer/localization/index.d.ts vendored Normal file
View file

@ -0,0 +1,19 @@
import type { TutorialMount } from "@boardgamers/protocol/tutorial";
export interface Localization {
readonly locale: string;
translate(text: string): string;
setLocale(locale: unknown): void;
setState(state: unknown): void;
setNames(names: unknown[]): void;
refresh(): void;
destroy(): void;
}
export const catalogs: Record<string, Record<string, string>>;
export const languages: Record<string, string>;
export function resolveLocale(value: unknown): string;
export function translateText(text: string, locale?: string): string;
export function mountLocalization(
target: Element,
locale?: unknown,
): Localization;
export function localizeTutorial(mount: TutorialMount): TutorialMount;

View file

@ -0,0 +1,64 @@
import catalog0 from "./en.json";
import catalog1 from "./de.json";
import catalog2 from "./fr.json";
import catalog3 from "./pl.json";
import catalog4 from "./ro.json";
import catalog5 from "./el.json";
import catalog6 from "./hi.json";
import catalog7 from "./ru.json";
import catalog8 from "./da.json";
import catalog9 from "./pt-BR.json";
import catalog10 from "./ko.json";
import catalog11 from "./zh-TW.json";
import catalog12 from "./vi.json";
import catalog13 from "./it.json";
import catalog14 from "./nl.json";
import { mountLocalization as mount, createTranslator } from "./runtime.js";
export { languages, resolveLocale } from "./runtime.js";
export const catalogs = {
en: catalog0,
de: catalog1,
fr: catalog2,
pl: catalog3,
ro: catalog4,
el: catalog5,
hi: catalog6,
ru: catalog7,
da: catalog8,
"pt-BR": catalog9,
ko: catalog10,
"zh-TW": catalog11,
vi: catalog12,
it: catalog13,
nl: catalog14,
};
const translators = new Map();
export function translateText(text, locale = "en") {
if (!translators.has(locale)) {
translators.set(locale, createTranslator(catalogs, locale));
}
return translators.get(locale).translate(text);
}
export function mountLocalization(target, locale) {
return mount(
target,
catalogs,
locale ?? target.ownerDocument.documentElement.lang ?? "en",
);
}
export function localizeTutorial(mountTutorial) {
return async (target, options) => {
const localization = mountLocalization(target, options.locale);
try {
const dispose = await mountTutorial(target, options);
localization.refresh();
return () => {
localization.destroy();
dispose?.();
};
} catch (error) {
localization.destroy();
throw error;
}
};
}

1160
viewer/localization/it.json Normal file

File diff suppressed because it is too large Load diff

1160
viewer/localization/ko.json Normal file

File diff suppressed because it is too large Load diff

1160
viewer/localization/nl.json Normal file

File diff suppressed because it is too large Load diff

1160
viewer/localization/pl.json Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

1160
viewer/localization/ro.json Normal file

File diff suppressed because it is too large Load diff

1160
viewer/localization/ru.json Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,319 @@
export const languages = {
en: "English",
de: "Deutsch",
fr: "Français",
pl: "Polski",
ro: "Română",
el: "Ελληνικά",
hi: "हिन्दी",
ru: "Русский",
da: "Dansk",
"pt-BR": "Português (Brasil)",
ko: "한국어",
"zh-TW": "繁體中文",
vi: "Tiếng Việt",
it: "Italiano",
nl: "Nederlands",
};
export function resolveLocale(value) {
if (typeof value !== "string") {
return "en";
}
const tag = value.toLowerCase().replaceAll("_", "-");
const exact = Object.keys(languages).find(
(locale) => locale.toLowerCase() === tag,
);
if (exact) {
return exact;
}
if (tag === "pt" || tag.startsWith("pt-")) {
return "pt-BR";
}
if (/^zh-(?:tw|hk|mo|hant)(?:-|$)/.test(tag)) {
return "zh-TW";
}
return (
Object.keys(languages).find((locale) => locale === tag.split("-")[0]) ??
"en"
);
}
const normalize = (text) => text.replace(/\s+/g, " ").trim();
export function createTranslator(catalogs, initialLocale = "en") {
let locale = resolveLocale(initialLocale);
let names = new Set();
let patterns = [];
let upperCase = new Map();
const cache = new Map();
function prepare() {
cache.clear();
upperCase = new Map(
Object.entries(catalogs[locale] ?? {})
.filter(([source]) => !/\{p\d+\}/.test(source))
.map(([source, value]) => [
source.toLocaleUpperCase(),
value.toLocaleUpperCase(),
]),
);
patterns = Object.keys(catalogs[locale] ?? {})
.filter(
(source) =>
/\{p\d+\}/.test(source) &&
source.replace(/\{p\d+\}/g, "").trim().length >= 1,
)
.sort(
(a, b) =>
b.replace(/\{p\d+\}/g, "").length - a.replace(/\{p\d+\}/g, "").length,
)
.map((source) => ({ source, pieces: source.split(/(\{p\d+\})/) }))
.filter(({ pieces }) =>
pieces.every(
(piece, i) =>
i === 0 ||
i === pieces.length - 1 ||
i % 2 !== 0 ||
piece.length > 0,
),
);
}
function translate(value, depth = 0) {
if (typeof value !== "string" || locale === "en") {
return value;
}
const text = normalize(value);
if (!text || names.has(text) || !/[A-Za-zÀ-ž]/.test(text)) {
return value;
}
const catalog = catalogs[locale] ?? {};
let translated = Object.prototype.hasOwnProperty.call(catalog, text)
? catalog[text]
: undefined;
if (translated === undefined && text === text.toLocaleUpperCase()) {
translated = upperCase.get(text);
}
if (translated === undefined && cache.has(text)) {
translated = cache.get(text);
}
if (translated === undefined && depth < 2 && text.length <= 2500) {
for (const { source, pieces } of patterns) {
if (!text.startsWith(pieces[0])) {
continue;
}
let offset = pieces[0].length;
const parameters = {};
let matches = true;
for (let i = 1; i < pieces.length; i += 2) {
const delimiter = pieces[i + 1];
const last = i + 2 >= pieces.length;
const end = last
? text.endsWith(delimiter)
? text.length - delimiter.length
: -1
: text.indexOf(delimiter, offset);
if (end < 0 || end - offset > 500) {
matches = false;
break;
}
parameters[pieces[i]] = text.slice(offset, end);
offset = end + delimiter.length;
}
if (!matches || offset !== text.length) {
continue;
}
translated = catalog[source].replace(/\{p\d+\}/g, (key) =>
translate(parameters[key] ?? key, depth + 1),
);
break;
}
}
if (translated === undefined) {
const prefix = /^(\d+\s*\/\s*\d+\s*·\s*)(.+)$/u.exec(text);
if (prefix && depth < 2) {
translated = prefix[1] + translate(prefix[2], depth + 1);
}
}
if (translated === undefined) {
const match =
/^(.*?)(\s*[:.!?—–·→←↑↓↗↙↘↖↻↺✓✗]\s*|\s+\d+(?:\s*\/\s*\d+)?\s*)$/u.exec(
text,
);
if (match && catalog[match[1]] !== undefined) {
translated = catalog[match[1]] + match[2];
}
}
if (translated === undefined) {
const amount = /^(.*?[$€£◈])(\d+(?:[.,]\d+)?)$/.exec(text);
if (amount && catalog[amount[1]] !== undefined) {
translated = catalog[amount[1]] + amount[2];
}
}
if (translated === undefined) {
translated = text;
}
if (cache.size > 5000) {
cache.clear();
}
cache.set(text, translated);
return (
value.slice(0, value.indexOf(value.trimStart())) +
translated +
value.slice(value.trimEnd().length)
);
}
prepare();
return {
translate,
get locale() {
return locale;
},
setLocale(value) {
const next = resolveLocale(value);
if (next === locale) {
return false;
}
locale = next;
prepare();
return true;
},
setNames(values) {
const next = new Set(
values.filter((value) => typeof value === "string").map(normalize),
);
if (
next.size === names.size &&
[...next].every((name) => names.has(name))
) {
return false;
}
names = next;
cache.clear();
return true;
},
};
}
// Only presentation text is changed. Never translate player input or rewrite game state.
export function mountLocalization(target, catalogs, initialLocale = "en") {
const translator = createTranslator(catalogs, initialLocale);
const originals = new WeakMap();
const attributes = ["title", "aria-label", "placeholder", "alt"];
const excluded =
'script,style,code,pre,[contenteditable="true"],[translate="no"],[data-bgs-player],[data-message-id],.chat-message-text,.chat-message-body,.chat-content,.message-text,.chat-author,.chat-segment';
let destroyed = false;
function apply(node, attribute) {
const element = node.nodeType === 3 ? node.parentElement : node;
if (!element || element.closest?.(excluded)) {
return;
}
const value = attribute ? node.getAttribute(attribute) : node.data;
if (typeof value !== "string") {
return;
}
let record = originals.get(node);
if (!record) {
record = new Map();
originals.set(node, record);
}
const key = attribute ?? "text";
const previous = record.get(key);
const source = previous?.output === value ? previous.source : value;
const output = translator.translate(source);
record.set(key, { source, output });
if (value !== output) {
if (attribute) {
node.setAttribute(attribute, output);
} else {
node.data = output;
}
}
}
function visit(node) {
if (destroyed) {
return;
}
if (node.nodeType === 3) {
apply(node);
return;
}
if (node.nodeType !== 1 && node !== target) {
return;
}
if (node.matches?.(excluded)) {
return;
}
for (const attr of attributes) {
if (node.hasAttribute?.(attr)) {
apply(node, attr);
}
}
if (node.matches?.("input,textarea")) {
return;
}
for (const child of node.childNodes ?? []) {
visit(child);
}
}
const observer = new MutationObserver((records) => {
for (const record of records) {
if (record.type === "characterData") {
apply(record.target);
} else if (record.type === "attributes") {
apply(record.target, record.attributeName);
} else {
for (const node of record.addedNodes) {
visit(node);
}
}
}
});
observer.observe(target, {
subtree: true,
childList: true,
characterData: true,
attributes: true,
attributeFilter: attributes,
});
function refresh() {
target.lang = translator.locale;
visit(target);
}
refresh();
return {
translate: translator.translate,
get locale() {
return translator.locale;
},
setLocale(locale) {
if (translator.setLocale(locale)) {
refresh();
}
},
setNames(names) {
if (translator.setNames(names)) {
refresh();
}
},
setState(state) {
const players = state?.players ?? state?.game?.players;
if (players && typeof players === "object") {
if (
translator.setNames(
Object.values(players).flatMap((player) => [
player?.name,
player?.username,
]),
)
) {
refresh();
}
}
},
refresh,
destroy() {
destroyed = true;
observer.disconnect();
},
};
}

1160
viewer/localization/vi.json Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -226,7 +226,7 @@ export function mountGame(
let colonySymbols = onColorBlindChange ? false : readLocalColorBlindMode();
root.classList.toggle("colony-symbols", colonySymbols);
target.append(root);
root.innerHTML = `<header class="topbar"><div class="brand"><span>${amoeba("green", 0)}</span><div><h1>primordial soup<span class="title-dot">.</span></h1><span class="byline">DORIS MATTHÄUS & FRANK NESTEL</span></div></div><nav class="utilities" aria-label="Game options"><button class="quiet-button" data-ui="genes" aria-label="Genes" title="Gene pool">${icon("gene")}<span class="utility-label">Genes</span></button><button class="icon-button" data-ui="colony-symbols" aria-label="Color-blind mode" aria-pressed="${colonySymbols}" title="Color-blind mode: match colonies by symbol">${icon("colony-symbols")}</button><button class="icon-button" data-ui="rules" aria-label="How to play">${icon("help")}</button><button class="icon-button" data-ui="fullscreen" aria-label="Fullscreen">${icon("expand")}</button></nav></header>
root.innerHTML = `<header class="topbar"><div class="brand"><span>${amoeba("green", 0)}</span><div><h1 translate="no">primordial soup<span class="title-dot">.</span></h1><span class="byline">DORIS MATTHÄUS & FRANK NESTEL</span></div></div><nav class="utilities" aria-label="Game options"><button class="quiet-button" data-ui="genes" aria-label="Genes" title="Gene pool">${icon("gene")}<span class="utility-label">Genes</span></button><button class="icon-button" data-ui="colony-symbols" aria-label="Color-blind mode" aria-pressed="${colonySymbols}" title="Color-blind mode: match colonies by symbol">${icon("colony-symbols")}</button><button class="icon-button" data-ui="rules" aria-label="How to play">${icon("help")}</button><button class="icon-button" data-ui="fullscreen" aria-label="Fullscreen">${icon("expand")}</button></nav></header>
<div class="tutorial-slot"></div><section class="players" aria-label="The colonies" data-tutorial="colonies"></section>
<main class="play-area"><section class="pond-section" aria-label="Primordial soup board"><div class="board-wrap"><div class="board" data-tutorial="board"><div class="pond-tools">${chat ? `<button class="quiet-button" data-ui="chat">${icon("chat")} Chat</button>` : ""}<button class="quiet-button" data-ui="journal">${icon("history")} Journal</button></div><svg id="pond-art" viewBox="0 0 900 650" preserveAspectRatio="none" aria-hidden="true">${pondArt()}</svg><div class="cells"></div><div class="organisms"></div><div class="board-actions" hidden></div><div class="current-compass" data-tutorial="current"><div class="environment-current"><span>CURRENT</span><div class="compass-arrow">➜</div><b class="compass-label"></b></div><div class="environment-ozone" role="img" tabindex="0" title="${OZONE_HELP}"><span class="ozone-value">${icon("ozone")}<strong class="ozone"></strong></span></div></div></div><div class="board-reference"><div class="game-progress"></div><aside class="soup-board-key" data-tutorial="scoring" aria-label="Scoring reference"></aside></div></div><div class="private-forecast" hidden></div><div class="pond-bottom"><div class="last-move" aria-live="polite"></div><span class="food-reserve" title="Food cubes remaining in the common supply"></span></div></section><aside class="colony-panel" data-tutorial="colony"></aside></main>
<footer class="turnbar" data-tutorial="actions"><div class="round"><span>ROUND</span><strong class="round-number"></strong></div><div class="turn-details"><div class="phase-label"></div><div class="phase-instruction" aria-live="polite"></div><ol class="phase-steps" aria-label="Round phases"></ol></div><div class="action-buttons"></div></footer><div class="game-message" role="alert"></div>