feat(viewer): localize interface and tutorials in 15 languages
This commit is contained in:
parent
b7908c20c6
commit
7370ce31d1
30 changed files with 62027 additions and 12 deletions
1
.github/workflows/viewer-test.yml
vendored
1
.github/workflows/viewer-test.yml
vendored
|
|
@ -31,6 +31,7 @@ jobs:
|
||||||
node-version: "24"
|
node-version: "24"
|
||||||
- run: corepack enable
|
- run: corepack enable
|
||||||
- run: pnpm install
|
- run: pnpm install
|
||||||
|
- run: pnpm --dir .. test:locales
|
||||||
- run: pnpm lint
|
- run: pnpm lint
|
||||||
# The full suite (810+ specs through mochapack/webpack) exceeds node's default ~4 GB heap (peaks ~10 GB; runners have 16 GB).
|
# The full suite (810+ specs through mochapack/webpack) exceeds node's default ~4 GB heap (peaks ~10 GB; runners have 16 GB).
|
||||||
- run: pnpm test
|
- run: pnpm test
|
||||||
|
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "@gaia-project/old-ui",
|
"name": "@gaia-project/old-ui",
|
||||||
"version": "1.0.11",
|
"version": "1.0.12",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"serve": "vite --port 5193",
|
"serve": "vite --port 5193",
|
||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,8 @@
|
||||||
"postinstall": "husky install",
|
"postinstall": "husky install",
|
||||||
"prettier": "prettier --write .",
|
"prettier": "prettier --write .",
|
||||||
"prettier-check": "prettier --check .",
|
"prettier-check": "prettier --check .",
|
||||||
"test": "vitest run"
|
"test": "vitest run",
|
||||||
|
"test:locales": "node scripts/check-locales.mjs viewer/src/localization && node --test scripts/localization.test.mjs"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"husky": "^5.0.9",
|
"husky": "^5.0.9",
|
||||||
|
|
|
||||||
20
scripts/check-locales.mjs
Normal file
20
scripts/check-locales.mjs
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
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`);
|
||||||
63
scripts/localization.test.mjs
Normal file
63
scripts/localization.test.mjs
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
import test from "node:test";
|
||||||
|
const source = await readFile(new URL("../viewer/src/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");
|
||||||
|
});
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
{
|
{
|
||||||
"name": "@gaia-project/viewer",
|
"name": "@gaia-project/viewer",
|
||||||
"version": "5.20.25",
|
"version": "5.20.26",
|
||||||
"description": "Functions to visualize the map and boards for gaia project inside html canvas",
|
"description": "Functions to visualize the map and boards for gaia project inside html canvas",
|
||||||
"contributors": [
|
"contributors": [
|
||||||
"coyotte508",
|
"coyotte508",
|
||||||
|
|
|
||||||
|
|
@ -83,6 +83,17 @@ describe("chat beside the mobile action bar", () => {
|
||||||
document.body.innerHTML = "";
|
document.body.innerHTML = "";
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("keeps the localized shortcut stable when its action-bar location changes", async () => {
|
||||||
|
emitter.emit("preferences", { locale: "fr" });
|
||||||
|
expect(shortcut.textContent).toBe("Discussion");
|
||||||
|
expect(shortcut.getAttribute("translate")).toBe("no");
|
||||||
|
document.querySelector("#host")!.append(document.createElement("span"));
|
||||||
|
await Promise.resolve();
|
||||||
|
expect(shortcut.textContent).toBe("Discussion");
|
||||||
|
emitter.emit("preferences", { locale: "en" });
|
||||||
|
expect(shortcut.textContent).toBe("Chat");
|
||||||
|
});
|
||||||
|
|
||||||
it("does not count replacement history as unread", () => {
|
it("does not count replacement history as unread", () => {
|
||||||
vi.spyOn(panel, "getBoundingClientRect").mockReturnValue(rect(900, 130));
|
vi.spyOn(panel, "getBoundingClientRect").mockReturnValue(rect(900, 130));
|
||||||
vi.spyOn(list, "getBoundingClientRect").mockReturnValue(rect(920, 60));
|
vi.spyOn(list, "getBoundingClientRect").mockReturnValue(rect(920, 60));
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ import { attachChat } from "@boardgamers/protocol/viewer";
|
||||||
import { Faction } from "@gaia-project/engine";
|
import { Faction } from "@gaia-project/engine";
|
||||||
import { factionArt } from "./data/faction-art";
|
import { factionArt } from "./data/faction-art";
|
||||||
import { factionColor } from "./graphics/utils";
|
import { factionColor } from "./graphics/utils";
|
||||||
|
import { resolveLocale, translateText } from "./localization";
|
||||||
type ChatEmitter = Pick<ViewerEmitter<any, any>, "on" | "emit">;
|
type ChatEmitter = Pick<ViewerEmitter<any, any>, "on" | "emit">;
|
||||||
export function mountGameChat(emitter: ViewerEmitter<any, any>, host: Element): () => void {
|
export function mountGameChat(emitter: ViewerEmitter<any, any>, host: Element): () => void {
|
||||||
const chat = new ChatController();
|
const chat = new ChatController();
|
||||||
|
|
@ -72,6 +73,7 @@ export function mountGameChat(emitter: ViewerEmitter<any, any>, host: Element):
|
||||||
|
|
||||||
`;
|
`;
|
||||||
slot.append(style);
|
slot.append(style);
|
||||||
|
let locale = "en";
|
||||||
let players: { id: number; name: string; color?: string; faction?: string }[] = [];
|
let players: { id: number; name: string; color?: string; faction?: string }[] = [];
|
||||||
let localPlayer: number | undefined;
|
let localPlayer: number | undefined;
|
||||||
let avatars: string[] = [];
|
let avatars: string[] = [];
|
||||||
|
|
@ -133,16 +135,18 @@ export function mountGameChat(emitter: ViewerEmitter<any, any>, host: Element):
|
||||||
return wrapper;
|
return wrapper;
|
||||||
}
|
}
|
||||||
function updateShortcut() {
|
function updateShortcut() {
|
||||||
|
shortcut.setAttribute("translate", "no");
|
||||||
const count = chat.unread;
|
const count = chat.unread;
|
||||||
const label = count ? `Chat · ${count} unread` : "Chat";
|
const sourceLabel = count ? `Chat · ${count} unread` : "Chat";
|
||||||
|
const label = translateText(sourceLabel, locale);
|
||||||
const barSlot = window.innerWidth < 768 ? host.querySelector(".mobile-sticky-actions .chat-shortcut-host") : null;
|
const barSlot = window.innerWidth < 768 ? host.querySelector(".mobile-sticky-actions .chat-shortcut-host") : null;
|
||||||
const destination = barSlot || slot;
|
const destination = barSlot || slot;
|
||||||
if (shortcut.parentElement !== destination) destination.append(shortcut);
|
if (shortcut.parentElement !== destination) destination.append(shortcut);
|
||||||
shortcut.classList.toggle("chat-shortcut--inline", !!barSlot);
|
shortcut.classList.toggle("chat-shortcut--inline", !!barSlot);
|
||||||
const text = barSlot && count ? `Chat · ${count}` : label;
|
const text = barSlot && count ? translateText(`Chat · ${count}`, locale) : label;
|
||||||
if (shortcut.textContent !== text) shortcut.textContent = text;
|
if (shortcut.textContent !== text) shortcut.textContent = text;
|
||||||
shortcut.hidden = analysis || count === 0 || (!barSlot && chatVisible);
|
shortcut.hidden = analysis || count === 0 || (!barSlot && chatVisible);
|
||||||
shortcut.setAttribute("aria-label", `Open ${label}`);
|
shortcut.setAttribute("aria-label", translateText(`Open ${sourceLabel}`, locale));
|
||||||
}
|
}
|
||||||
shortcut.onclick = () => {
|
shortcut.onclick = () => {
|
||||||
view.open();
|
view.open();
|
||||||
|
|
@ -150,6 +154,7 @@ export function mountGameChat(emitter: ViewerEmitter<any, any>, host: Element):
|
||||||
const dispose = [
|
const dispose = [
|
||||||
detach,
|
detach,
|
||||||
emitter.on("preferences", (preferences) => {
|
emitter.on("preferences", (preferences) => {
|
||||||
|
locale = resolveLocale(preferences.locale);
|
||||||
analysis = preferences.analysis === true;
|
analysis = preferences.analysis === true;
|
||||||
slot.style.display = analysis ? "none" : "";
|
slot.style.display = analysis ? "none" : "";
|
||||||
updateShortcut();
|
updateShortcut();
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@ import Resource from "./components/Resource.vue";
|
||||||
import TechContent from "./components/TechContent.vue";
|
import TechContent from "./components/TechContent.vue";
|
||||||
import { mountGameChat } from "./game-chat";
|
import { mountGameChat } from "./game-chat";
|
||||||
import { createBoardThumbnail, installPlayerCards } from "./host-presentation";
|
import { createBoardThumbnail, installPlayerCards } from "./host-presentation";
|
||||||
|
import { mountLocalization } from "./localization";
|
||||||
import { installBoardTouch } from "./logic/board-touch";
|
import { installBoardTouch } from "./logic/board-touch";
|
||||||
import { installActionSounds } from "./sounds";
|
import { installActionSounds } from "./sounds";
|
||||||
import { makeStore } from "./store";
|
import { makeStore } from "./store";
|
||||||
|
|
@ -98,6 +99,7 @@ function launch(selector: string, component: VueConstructor<Vue> = Game) {
|
||||||
const item: EventEmitter & { store: typeof store; app: Vue } = Object.assign(new EventEmitter(), { store, app });
|
const item: EventEmitter & { store: typeof store; app: Vue } = Object.assign(new EventEmitter(), { store, app });
|
||||||
|
|
||||||
const thumbnail = createBoardThumbnail(app.$el);
|
const thumbnail = createBoardThumbnail(app.$el);
|
||||||
|
const localization = mountLocalization(target.ownerDocument.body);
|
||||||
let replaying = false;
|
let replaying = false;
|
||||||
const viewer = createViewer<Record<string, any>, string | PremoveCommand>({
|
const viewer = createViewer<Record<string, any>, string | PremoveCommand>({
|
||||||
async onThumbnail(size) {
|
async onThumbnail(size) {
|
||||||
|
|
@ -105,6 +107,7 @@ function launch(selector: string, component: VueConstructor<Vue> = Game) {
|
||||||
return thumbnail.render(app.$el.querySelector(".space-map-canvas, .old-map-canvas"), size, "#10172b");
|
return thumbnail.render(app.$el.querySelector(".space-map-canvas, .old-map-canvas"), size, "#10172b");
|
||||||
},
|
},
|
||||||
async onState(data) {
|
async onState(data) {
|
||||||
|
localization.setState(data);
|
||||||
await store.dispatch("externalData", data);
|
await store.dispatch("externalData", data);
|
||||||
if (!replaying) viewer.replaceLog(data?.moveHistory || []);
|
if (!replaying) viewer.replaceLog(data?.moveHistory || []);
|
||||||
await app.$nextTick();
|
await app.$nextTick();
|
||||||
|
|
@ -116,6 +119,7 @@ function launch(selector: string, component: VueConstructor<Vue> = Game) {
|
||||||
store.commit("playerSettings", data);
|
store.commit("playerSettings", data);
|
||||||
},
|
},
|
||||||
onPreferences(data) {
|
onPreferences(data) {
|
||||||
|
localization.setLocale(data.locale);
|
||||||
store.commit("preferences", data);
|
store.commit("preferences", data);
|
||||||
},
|
},
|
||||||
onPlayer(data) {
|
onPlayer(data) {
|
||||||
|
|
@ -168,6 +172,7 @@ function launch(selector: string, component: VueConstructor<Vue> = Game) {
|
||||||
const removeCards = installPlayerCards(app.$el, viewer);
|
const removeCards = installPlayerCards(app.$el, viewer);
|
||||||
const removeChat = mountGameChat(viewer.emitter, app.$el);
|
const removeChat = mountGameChat(viewer.emitter, app.$el);
|
||||||
app.$once("hook:beforeDestroy", () => {
|
app.$once("hook:beforeDestroy", () => {
|
||||||
|
localization.destroy();
|
||||||
removeCards();
|
removeCards();
|
||||||
thumbnail.destroy();
|
thumbnail.destroy();
|
||||||
removeChat();
|
removeChat();
|
||||||
|
|
|
||||||
11
viewer/src/localization/README.md
Normal file
11
viewer/src/localization/README.md
Normal 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/src/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.
|
||||||
4102
viewer/src/localization/da.json
Normal file
4102
viewer/src/localization/da.json
Normal file
File diff suppressed because it is too large
Load diff
4102
viewer/src/localization/de.json
Normal file
4102
viewer/src/localization/de.json
Normal file
File diff suppressed because it is too large
Load diff
4102
viewer/src/localization/el.json
Normal file
4102
viewer/src/localization/el.json
Normal file
File diff suppressed because it is too large
Load diff
4102
viewer/src/localization/en.json
Normal file
4102
viewer/src/localization/en.json
Normal file
File diff suppressed because it is too large
Load diff
4102
viewer/src/localization/fr.json
Normal file
4102
viewer/src/localization/fr.json
Normal file
File diff suppressed because it is too large
Load diff
4102
viewer/src/localization/hi.json
Normal file
4102
viewer/src/localization/hi.json
Normal file
File diff suppressed because it is too large
Load diff
16
viewer/src/localization/index.d.ts
vendored
Normal file
16
viewer/src/localization/index.d.ts
vendored
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
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;
|
||||||
60
viewer/src/localization/index.js
Normal file
60
viewer/src/localization/index.js
Normal file
|
|
@ -0,0 +1,60 @@
|
||||||
|
import catalog8 from "./da.json";
|
||||||
|
import catalog1 from "./de.json";
|
||||||
|
import catalog5 from "./el.json";
|
||||||
|
import catalog0 from "./en.json";
|
||||||
|
import catalog2 from "./fr.json";
|
||||||
|
import catalog6 from "./hi.json";
|
||||||
|
import catalog13 from "./it.json";
|
||||||
|
import catalog10 from "./ko.json";
|
||||||
|
import catalog14 from "./nl.json";
|
||||||
|
import catalog3 from "./pl.json";
|
||||||
|
import catalog9 from "./pt-BR.json";
|
||||||
|
import catalog4 from "./ro.json";
|
||||||
|
import catalog7 from "./ru.json";
|
||||||
|
import { createTranslator, mountLocalization as mount } from "./runtime.js";
|
||||||
|
import catalog12 from "./vi.json";
|
||||||
|
import catalog11 from "./zh-TW.json";
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
4102
viewer/src/localization/it.json
Normal file
4102
viewer/src/localization/it.json
Normal file
File diff suppressed because it is too large
Load diff
4102
viewer/src/localization/ko.json
Normal file
4102
viewer/src/localization/ko.json
Normal file
File diff suppressed because it is too large
Load diff
4102
viewer/src/localization/nl.json
Normal file
4102
viewer/src/localization/nl.json
Normal file
File diff suppressed because it is too large
Load diff
4102
viewer/src/localization/pl.json
Normal file
4102
viewer/src/localization/pl.json
Normal file
File diff suppressed because it is too large
Load diff
4102
viewer/src/localization/pt-BR.json
Normal file
4102
viewer/src/localization/pt-BR.json
Normal file
File diff suppressed because it is too large
Load diff
4102
viewer/src/localization/ro.json
Normal file
4102
viewer/src/localization/ro.json
Normal file
File diff suppressed because it is too large
Load diff
4102
viewer/src/localization/ru.json
Normal file
4102
viewer/src/localization/ru.json
Normal file
File diff suppressed because it is too large
Load diff
275
viewer/src/localization/runtime.js
Normal file
275
viewer/src/localization/runtime.js
Normal file
|
|
@ -0,0 +1,275 @@
|
||||||
|
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();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
4102
viewer/src/localization/vi.json
Normal file
4102
viewer/src/localization/vi.json
Normal file
File diff suppressed because it is too large
Load diff
4102
viewer/src/localization/zh-TW.json
Normal file
4102
viewer/src/localization/zh-TW.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1,6 +1,7 @@
|
||||||
import { Resource as ResourceKind } from "@gaia-project/engine";
|
import { Resource as ResourceKind } from "@gaia-project/engine";
|
||||||
import Vue from "vue";
|
import Vue from "vue";
|
||||||
import Resource from "../components/Resource.vue";
|
import Resource from "../components/Resource.vue";
|
||||||
|
import { translateText } from "../localization";
|
||||||
import type { makeStore } from "../store";
|
import type { makeStore } from "../store";
|
||||||
|
|
||||||
const symbols = [
|
const symbols = [
|
||||||
|
|
@ -28,14 +29,28 @@ const words: Record<string, ResourceKind> = {
|
||||||
"victory points": ResourceKind.VictoryPoint,
|
"victory points": ResourceKind.VictoryPoint,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function resourceTextParts(text: string): { text: string; kind?: ResourceKind }[] {
|
export function resourceTextParts(
|
||||||
const pattern =
|
text: string,
|
||||||
/\b(?:\d+(?:[–-]\d+)?[\s-]+)?(Q\.I\.C\.|QICs?|ores?|knowledge|credits?|power(?: tokens?)?|VP|victory points?)(?!\w)/gi;
|
translate = (text: string) => text
|
||||||
|
): { text: string; kind?: ResourceKind }[] {
|
||||||
|
const localizedWords = Object.fromEntries(
|
||||||
|
Object.entries(words).flatMap(([word, kind]) => [
|
||||||
|
[word, kind],
|
||||||
|
[translate(word).toLocaleLowerCase(), kind],
|
||||||
|
])
|
||||||
|
);
|
||||||
|
const terms = Object.keys(localizedWords)
|
||||||
|
.sort((a, b) => b.length - a.length)
|
||||||
|
.map((word) => word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
||||||
|
const pattern = new RegExp(
|
||||||
|
"(?<![\\p{L}\\p{N}])(?:\\d+(?:[–-]\\d+)?[\\s-]+)?(Q\\.I\\.C\\.|" + terms.join("|") + ")(?![\\p{L}\\p{N}])",
|
||||||
|
"giu"
|
||||||
|
);
|
||||||
const parts: { text: string; kind?: ResourceKind }[] = [];
|
const parts: { text: string; kind?: ResourceKind }[] = [];
|
||||||
let end = 0;
|
let end = 0;
|
||||||
for (let match = pattern.exec(text); match; match = pattern.exec(text)) {
|
for (let match = pattern.exec(text); match; match = pattern.exec(text)) {
|
||||||
if (match.index > end) parts.push({ text: text.slice(end, match.index) });
|
if (match.index > end) parts.push({ text: text.slice(end, match.index) });
|
||||||
parts.push({ text: match[0], kind: words[match[1].toLowerCase().replace(/\./g, "")] });
|
parts.push({ text: match[0], kind: localizedWords[match[1].toLocaleLowerCase().replace(/\./g, "")] });
|
||||||
end = match.index + match[0].length;
|
end = match.index + match[0].length;
|
||||||
}
|
}
|
||||||
if (end < text.length) parts.push({ text: text.slice(end) });
|
if (end < text.length) parts.push({ text: text.slice(end) });
|
||||||
|
|
@ -68,7 +83,8 @@ export function createResourceText(store: ReturnType<typeof makeStore>) {
|
||||||
return (target: HTMLElement) => {
|
return (target: HTMLElement) => {
|
||||||
const doc = target.ownerDocument;
|
const doc = target.ownerDocument;
|
||||||
const fragment = doc.createDocumentFragment();
|
const fragment = doc.createDocumentFragment();
|
||||||
for (const part of resourceTextParts(target.textContent ?? "")) {
|
const translate = (text: string) => translateText(text, target.ownerDocument.documentElement.lang);
|
||||||
|
for (const part of resourceTextParts(translate(target.textContent ?? ""), translate)) {
|
||||||
if (!part.kind) {
|
if (!part.kind) {
|
||||||
fragment.append(doc.createTextNode(part.text));
|
fragment.append(doc.createTextNode(part.text));
|
||||||
continue;
|
continue;
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,4 @@
|
||||||
|
import { localizeTutorial } from "./localization";
|
||||||
// Import vue component
|
// Import vue component
|
||||||
import type { TutorialLaunchOptions } from "@boardgamers/protocol/tutorial";
|
import type { TutorialLaunchOptions } from "@boardgamers/protocol/tutorial";
|
||||||
import { createTutorialLauncher } from "@boardgamers/protocol/tutorial";
|
import { createTutorialLauncher } from "@boardgamers/protocol/tutorial";
|
||||||
|
|
@ -5,7 +6,7 @@ import launchGame, { destroyViewer } from "./launcher";
|
||||||
import launchOffline from "./self-contained";
|
import launchOffline from "./self-contained";
|
||||||
import { mountTutorial } from "./tutorial/mount";
|
import { mountTutorial } from "./tutorial/mount";
|
||||||
|
|
||||||
const tutorial = createTutorialLauncher(mountTutorial);
|
const tutorial = createTutorialLauncher(localizeTutorial(mountTutorial));
|
||||||
function launch(selector: string) {
|
function launch(selector: string) {
|
||||||
tutorial.destroy();
|
tutorial.destroy();
|
||||||
return launchGame(selector);
|
return launchGame(selector);
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue