feat(viewer): localize interface and tutorials in 15 languages
This commit is contained in:
parent
09de708a47
commit
25834723ee
26 changed files with 31973 additions and 3 deletions
1
.github/workflows/viewer-test.yml
vendored
1
.github/workflows/viewer-test.yml
vendored
|
|
@ -30,6 +30,7 @@ jobs:
|
|||
node-version: '24'
|
||||
- run: corepack enable
|
||||
- run: pnpm install
|
||||
- run: pnpm --dir .. test:locales
|
||||
# - run: pnpm lint
|
||||
# - run: pnpm test
|
||||
- run: pnpm build
|
||||
|
|
|
|||
|
|
@ -4,7 +4,8 @@
|
|||
"lint-staged": "lint-staged",
|
||||
"postinstall": "husky install",
|
||||
"prettier": "prettier --plugin-search-dir=. --write .",
|
||||
"prettier-check": "prettier --plugin-search-dir=. --check ."
|
||||
"prettier-check": "prettier --plugin-search-dir=. --check .",
|
||||
"test:locales": "node scripts/check-locales.mjs viewer/src/localization && node --test scripts/localization.test.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"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 test from 'node:test';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
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": "powergrid-viewer",
|
||||
"version": "2.1.12",
|
||||
"version": "2.1.13",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/boardgamers/powergrid.git",
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { mountLocalization } from './localization';
|
||||
import { installPlayerCards, createBoardThumbnail } from './host-presentation';
|
||||
import { createViewer } from '@boardgamers/protocol/viewer';
|
||||
import { EventEmitter } from 'events';
|
||||
|
|
@ -53,6 +54,7 @@ function launch(selector: string) {
|
|||
}).$mount(mountPoint);
|
||||
|
||||
const thumbnail = createBoardThumbnail(app.$el);
|
||||
const localization = mountLocalization(target.ownerDocument.body);
|
||||
let replaying = false;
|
||||
const viewer = createViewer<GameState, Move[] | PremoveCommand>({
|
||||
async onThumbnail(size) {
|
||||
|
|
@ -60,6 +62,7 @@ function launch(selector: string) {
|
|||
return thumbnail.render(app.$el.querySelector('[data-tutorial="map"]'), size, '#e7e6df');
|
||||
},
|
||||
async onState(data) {
|
||||
localization.setState(data);
|
||||
params.state = data;
|
||||
app.$forceUpdate();
|
||||
await app.$nextTick();
|
||||
|
|
@ -69,6 +72,7 @@ function launch(selector: string) {
|
|||
app.$forceUpdate();
|
||||
},
|
||||
onPreferences(data) {
|
||||
localization.setLocale(data.locale);
|
||||
Object.assign(params.preferences, data);
|
||||
app.$forceUpdate();
|
||||
},
|
||||
|
|
@ -114,6 +118,7 @@ function launch(selector: string) {
|
|||
const removeCards = installPlayerCards(app.$el, viewer);
|
||||
const removeChat = mountGameChat(item, app.$el);
|
||||
app.$once('hook:beforeDestroy', () => {
|
||||
localization.destroy();
|
||||
removeCards();
|
||||
thumbnail.destroy();
|
||||
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.
|
||||
2101
viewer/src/localization/da.json
Normal file
2101
viewer/src/localization/da.json
Normal file
File diff suppressed because it is too large
Load diff
2101
viewer/src/localization/de.json
Normal file
2101
viewer/src/localization/de.json
Normal file
File diff suppressed because it is too large
Load diff
2101
viewer/src/localization/el.json
Normal file
2101
viewer/src/localization/el.json
Normal file
File diff suppressed because one or more lines are too long
2101
viewer/src/localization/en.json
Normal file
2101
viewer/src/localization/en.json
Normal file
File diff suppressed because it is too large
Load diff
2101
viewer/src/localization/fr.json
Normal file
2101
viewer/src/localization/fr.json
Normal file
File diff suppressed because it is too large
Load diff
2101
viewer/src/localization/hi.json
Normal file
2101
viewer/src/localization/hi.json
Normal file
File diff suppressed because one or more lines are too long
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 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;
|
||||
}
|
||||
};
|
||||
}
|
||||
2101
viewer/src/localization/it.json
Normal file
2101
viewer/src/localization/it.json
Normal file
File diff suppressed because it is too large
Load diff
2101
viewer/src/localization/ko.json
Normal file
2101
viewer/src/localization/ko.json
Normal file
File diff suppressed because it is too large
Load diff
2101
viewer/src/localization/nl.json
Normal file
2101
viewer/src/localization/nl.json
Normal file
File diff suppressed because it is too large
Load diff
2101
viewer/src/localization/pl.json
Normal file
2101
viewer/src/localization/pl.json
Normal file
File diff suppressed because it is too large
Load diff
2101
viewer/src/localization/pt-BR.json
Normal file
2101
viewer/src/localization/pt-BR.json
Normal file
File diff suppressed because it is too large
Load diff
2101
viewer/src/localization/ro.json
Normal file
2101
viewer/src/localization/ro.json
Normal file
File diff suppressed because it is too large
Load diff
2101
viewer/src/localization/ru.json
Normal file
2101
viewer/src/localization/ru.json
Normal file
File diff suppressed because one or more lines are too long
277
viewer/src/localization/runtime.js
Normal file
277
viewer/src/localization/runtime.js
Normal file
|
|
@ -0,0 +1,277 @@
|
|||
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();
|
||||
},
|
||||
};
|
||||
}
|
||||
2101
viewer/src/localization/vi.json
Normal file
2101
viewer/src/localization/vi.json
Normal file
File diff suppressed because it is too large
Load diff
2101
viewer/src/localization/zh-TW.json
Normal file
2101
viewer/src/localization/zh-TW.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1,8 +1,9 @@
|
|||
import { localizeTutorial } from './localization';
|
||||
import { createTutorialLauncher, TutorialLaunchOptions } from '@boardgamers/protocol/tutorial';
|
||||
import launchGame, { destroyViewer } from './launch';
|
||||
import { mountTutorial } from './tutorial/mount';
|
||||
|
||||
const tutorial = createTutorialLauncher(mountTutorial);
|
||||
const tutorial = createTutorialLauncher(localizeTutorial(mountTutorial));
|
||||
export function launch(selector: string) {
|
||||
tutorial.destroy();
|
||||
return launchGame(selector);
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue