Merge pull request #26 from daniloctdev/feat/i18n-italian

Add Italian translation and a language switch.
This commit is contained in:
Frederic Jung 2026-10-24 22:18:28 +02:00
commit f1ea017b39
No known key found for this signature in database
8 changed files with 3218 additions and 1063 deletions

View file

@ -6,6 +6,9 @@ All notable changes to this project are documented here. The project follows
## [Unreleased]
- Series of Tubes now speaks Italian. The game follows your browser's
language the first time, and you can switch between English and Italian
under Settings or on the title screen; the choice is remembered (#26, thanks @daniloctdev).
- Want the real thing? The title screen, the help page and the victory screen
now point to How the Internet Works by Thomas Kjær Aabo, an interactive,
zoomable guide to how your packets actually travel.

View file

@ -44,17 +44,22 @@ open site/index.html # or: npm run serve
Progress is saved in your browser's local storage.
The game speaks English and Italian. It follows your browser's language the first time
and remembers the one you pick under Settings or on the title screen.
## Development
```sh
npm ci
npm test # headless tests: boot, geography, a year of play, every incident, every panel
npm run build # writes the deployable site to _site/ with version and date stamped in
npm run i18n:check # lists text missing from (or stale in) the translations
```
```
site/ everything that is deployed
index.html the whole game (HTML, CSS and JS in one file)
i18n/it.js Italian translation, loaded only when the game runs in Italian
images/og-image.png social preview (1200×630)
favicon.*, icon-* favicons, app icons, manifest
robots.txt, sitemap.xml, llms.txt, 404.html, CNAME
@ -63,6 +68,17 @@ tests/ node:test + jsdom
.github/workflows/ ci.yml (pushes to main and PRs) and release.yml (Pages deploy)
```
## Translations
English is the source text. Player-facing strings in `index.html` go through
`tr('Unlocks at level {n}.', {n})` (or `trn(one, other, n)` for plurals); static markup
uses `data-i18n`, and `aria-label`/`title` are translated at boot. Each language is a
`site/i18n/<lang>.js` file mapping the English text to its translation, plus an entry in
`SOT_LANGS` (the language loader at the top of the page). Missing entries fall back to
English, so new English text never breaks the game; `npm run i18n:check` lists what
needs translating, and the tests make sure every translation keeps its `{placeholders}`
and HTML tags.
## Releasing
Only published releases reach [seriesoftub.es](https://seriesoftub.es). Ordinary

View file

@ -6,8 +6,9 @@
"homepage": "https://seriesoftub.es/",
"repository": { "type": "git", "url": "git+https://github.com/fjaeckel/seriesoftubes.git" },
"scripts": {
"test": "node --test --test-concurrency=1 tests/game.test.js tests/build.test.js tests/persist.test.js tests/services.test.js tests/peering.test.js tests/issues.test.js tests/regions.test.js tests/modes.test.js",
"test": "node --test --test-concurrency=1 tests/game.test.js tests/build.test.js tests/persist.test.js tests/services.test.js tests/peering.test.js tests/issues.test.js tests/regions.test.js tests/modes.test.js tests/i18n.test.js",
"build": "bash scripts/build.sh",
"i18n:check": "node scripts/i18n-check.js",
"serve": "npm run build && npx --yes serve@14.2.4 _site"
},
"engines": { "node": ">=20" },

72
scripts/i18n-check.js Normal file
View file

@ -0,0 +1,72 @@
#!/usr/bin/env node
// Checks a translation against the English text in site/index.html: every tr()/trn()/N_() literal and
// every data-i18n text, aria-label and title in the static markup should have an entry, no stale entry
// should linger, and each translation must keep the {placeholders} and HTML tags of its English key.
// Usage: node scripts/i18n-check.js [lang ...] (default: every site/i18n/*.js)
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const SITE = path.join(__dirname, '..', 'site');
const LIT = String.raw`'(?:[^'\\\n]|\\.)*'|"(?:[^"\\\n]|\\.)*"|\x60(?:[^\x60\\$]|\\.|\$(?!\{))*\x60`;
const CALL = new RegExp(String.raw`(?<![\w$.])(tr|trn|N_)\(\s*(${LIT})(?:\s*,\s*(${LIT}))?`, 'g');
const CTX = vm.createContext({});
const literal = (s) => vm.runInContext(s, CTX);
// English keys used by the game. Calls whose text is not a literal cannot be checked and are skipped.
function sourceKeys(html) {
const keys = new Set();
const scripts = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map((m) => m[1]).join('\n');
for (const m of scripts.matchAll(CALL)) {
keys.add(literal(m[2]));
if (m[1] === 'trn' && m[3]) keys.add(literal(m[3]));
}
const { JSDOM } = require('jsdom');
const doc = new JSDOM(html).window.document;
for (const el of doc.querySelectorAll('[data-i18n]')) keys.add(el.textContent);
for (const a of ['aria-label', 'title']) for (const el of doc.querySelectorAll(`[${a}]`)) keys.add(el.getAttribute(a));
return keys;
}
function loadDict(file) {
const window = {};
vm.runInNewContext(fs.readFileSync(file, 'utf8'), { window });
const lang = path.basename(file, '.js');
return (window.I18N || {})[lang] || {};
}
const placeholders = (s) => (s.match(/\{\w+\}/g) || []).sort().join(' ');
const tags = (s) => (s.match(/<\/?[a-z][a-z0-9]*/gi) || []).map((t) => t.toLowerCase()).sort().join(' ');
// Entries whose translation drops or invents a {placeholder} or an HTML tag, or is empty.
function brokenEntries(dict) {
return Object.entries(dict).filter(([en, xx]) => typeof xx !== 'string' || !xx.trim() ||
placeholders(en) !== placeholders(xx) || tags(en) !== tags(xx)).map(([en]) => en);
}
function check(keys, dict) {
return {
missing: [...keys].filter((k) => !(k in dict)),
unused: Object.keys(dict).filter((k) => !keys.has(k)),
broken: brokenEntries(dict),
};
}
module.exports = { loadDict, brokenEntries };
if (require.main === module) {
const keys = sourceKeys(fs.readFileSync(path.join(SITE, 'index.html'), 'utf8'));
const langs = process.argv.slice(2);
const files = (langs.length ? langs.map((l) => `${l}.js`) : fs.readdirSync(path.join(SITE, 'i18n')))
.map((f) => path.join(SITE, 'i18n', f));
let bad = false;
for (const file of files) {
const r = check(keys, loadDict(file));
console.log(`${path.basename(file)}: ${r.missing.length} missing, ${r.unused.length} unused, ${r.broken.length} broken`);
for (const [label, list] of [['missing', r.missing], ['unused', r.unused], ['broken', r.broken]]) {
for (const k of list) console.log(` ${label}: ${JSON.stringify(k)}`);
}
bad ||= r.missing.length + r.unused.length + r.broken.length > 0;
}
process.exit(bad ? 1 : 0);
}

1911
site/i18n/it.js Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

View file

@ -23,6 +23,9 @@ function load(opts = {}) {
// Seed before the game script runs, so nothing random happens at load time either.
if (opts.seed !== false) { let r = opts.seed || 12345; window.Math.random = () => { r = (r * 16807) % 2147483647; return r / 2147483647; }; window.__reseed = (n) => { r = n; }; }
for (const [k, v] of Object.entries(opts.storage || {})) window.localStorage.setItem(k, v);
if (opts.navigatorLanguage) Object.defineProperty(window.navigator, 'language', { value: opts.navigatorLanguage });
// A non-English game: jsdom does not fetch the dictionary script, so register it up front.
if (opts.lang) { window.localStorage.setItem('sot-lang', opts.lang); window.eval(fs.readFileSync(path.join(__dirname, '..', 'site', 'i18n', opts.lang + '.js'), 'utf8')); }
window.Path2D = class { moveTo() {} lineTo() {} quadraticCurveTo() {} bezierCurveTo() {} arc() {} rect() {} closePath() {} };
// A recording 2D context, so draw code really runs under test (jsdom has no canvas).
const fake = () => { const calls = { n: 0 };

121
tests/i18n.test.js Normal file
View file

@ -0,0 +1,121 @@
const test = require('node:test');
const assert = require('node:assert/strict');
const path = require('node:path');
const { load, seed } = require('./harness');
const { loadDict, brokenEntries } = require('../scripts/i18n-check');
const SCREENS = ['hud', 'panelBody', 'leftBody', 'modalCard', 'dashCard', 'bankCard', 'toasts', 'coach', 'hint', 'mega'];
// Drives the game through nearly every screen, every failure and every event, and returns what threw
// plus any rendered text with an unfilled {placeholder}, "undefined" or "NaN" in it.
function tour(ev) {
const thrown = [], leaks = new Set();
const step = (label, src) => {
try { ev(src); } catch (e) { thrown.push(`${label}: ${e.message}`); }
const txt = ev(`${JSON.stringify(SCREENS)}.map(i=>{const e=document.getElementById(i);return e?e.textContent:''}).join('\\n')`);
for (const m of txt.match(/[^\n]{0,40}(\{[a-z]\w*\}|undefined|NaN)[^\n]{0,40}/g) || []) leaks.add(m.trim());
};
step('title', 'showTitle()');
step('start', 'ACT.start({});S.cash=1e8;S.lvl=4;S.day=100');
step('pops', "for(const c of ['ams','lon','nyc','mos','mnl','sin','sao','dxb','tpe','jnb'])if(CITY[c])ACT.buildPop({city:c})");
step('basics', "ACT.launchBB({city:'fra'});ACT.buyTransit({city:'fra',net:'cog',tier:1});ACT.buyIx({city:'fra',tier:1,signed:true});ACT.rs({city:'fra'})");
step('links', "UI.pending={a:'fra',b:'ams'};ACT.buildLink({tier:1});UI.via='grace';openLinkModal('nyc','lon');ACT.buildLink({tier:1});closeModal()");
step('dark fiber', "UI.pending={a:'fra',b:'ams'};UI.lmode='df';UI.dfSys='roadm';openLinkModal('fra','ams');ACT.orderDf();UI.lmode='wave';S.pops.fra.rgen=2;S.pops.ams.rgen=2;const df=S.links.find(l=>l.kind==='df');if(df){ACT.addCh({id:df.id,o:'zr4'});df.ready=S.day}");
for (let d = 0; d < 40; d++) step('day ' + d, 'dayTick();if(S.day%10===0)for(const o of S.offers.slice())if(S.pops[o.city]&&(!o.city2||S.pops[o.city2]))ACT.accept({id:o.id})');
for (const c of ['fra', 'ams', 'nyc', 'sha', 'sin', 'sao', 'mos', 'lon', 'stg']) {
for (const t of ['cust', 'up', 'peer', 'links']) step(`panel ${c}/${t}`, `selectCity('${c}');ACT.tab({t:'${t}'})`);
}
step('link panels', 'for(const l of S.links){ACT.selLink({id:l.id});renderPanel()}');
for (const t of ['goals', 'deals', 'noc', 'nets']) step('left ' + t, `ACT.leftTab({t:'${t}'})`);
for (const [label, src] of [['dash', 'ACT.dash({});ACT.dashClose()'], ['bank', 'ACT.bank();ACT.bankClose()'],
['help', 'showHelp();closeModal()'], ['menu', 'ACT.menu();closeModal()'], ['reset', 'ACT.resetAsk();closeModal()'],
['scenarios', 'scenarioModal();closeModal()'], ['trace', "traceModal('fra');closeModal()"],
['route script', 'ACT.buyTE();ACT.teEdit();ACT.teExample();ACT.teCheck();closeModal()'],
['routers', "selectCity('fra');ACT.tab({t:'links'});ACT.models()"], ['vxc', "openVxcModal({from:'fra',to:'ams'});closeModal()"],
['tutorial', 'S.tut=0;renderCoach();S.tut=3;renderCoach();S.tut=null;renderCoach()'], ['win', 'showWin()']]) step(label, src);
const failSrc = ev('fireFailure.toString()');
for (const t of ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'maxpfx', 'prepend', 'rpki', 'amp', 'roadmff', 'optic', 'ac', 'cut', 'crash', 'power', 'transit', 'ixloop', 'leak', 'ddos']) {
const kind = ['harmless', 'fatwave', 'label', 'mtu', 'oops', 'cleaner', 'maxpfx', 'prepend', 'rpki', 'roadmff', 'ac'].includes(t) ? 'funny' : t;
const patched = failSrc.replace(/^function fireFailure/, 'function')
.replace('let tot=opts.reduce', `if(!opts.some(o=>o[0]==='${kind}'))return;opts.splice(0,opts.length,['${kind}',1]);let tot=opts.reduce`)
.replace('type=pick(f);}', `type=f.includes('${t}')?'${t}':pick(f);}`);
assert.ok(patched.includes(`['${kind}',1]`) && patched.includes(`f.includes('${t}')`), 'fireFailure still has the hooks this tour forces');
step('failure ' + t, `window.__ff=${patched};S.links.forEach(l=>{l.cut=0;l.eqDown=0;l.chFail=null});S.transit.forEach(t=>t.down=0);for(const c in S.pops)S.pops[c].down=0;compute();__ff();dayTick();ACT.leftTab({t:'noc'})`);
}
const evSrc = ev('fireEvent.toString()');
for (const e of ['viral', 'price', 'grant', 'sanction', 'tariff', 'hijack', 'landban', 'shutdown', 'redsea', 'baltic', 'runet', 'typhoon', 'golden', 'gfw', 'gulf']) {
const patched = evSrc.replace(/^function fireEvent/, 'function').replace('const e=pick(opts);', `const e='${e}';`);
assert.ok(patched.includes(`const e='${e}';`), 'fireEvent still has the hook this tour forces');
step('event ' + e, `window.__fe=${patched};__fe();dayTick();ACT.leftTab({t:'deals'})`);
}
for (let d = 0; d < 60; d++) step('late day ' + d, 'dayTick()');
step('lose', 'showLose()');
return { thrown, leaks: [...leaks] };
}
test('the game starts in English unless the player or the browser asks for another language', () => {
assert.equal(load().ev('LANG'), 'en');
assert.equal(load({ navigatorLanguage: 'it-IT' }).ev('SOT_LANG'), 'it', 'an Italian browser asks for Italian');
const it = load({ lang: 'it' });
assert.equal(it.ev('LANG'), 'it');
assert.equal(it.ev('document.documentElement.lang'), 'it');
assert.equal(load({ navigatorLanguage: 'it-IT', storage: { 'sot-lang': 'en' } }).ev('LANG'), 'en', 'a saved choice wins');
assert.equal(load({ storage: { 'sot-lang': 'xx' } }).ev('LANG'), 'en', 'unknown languages fall back to English');
const offline = load({ storage: { 'sot-lang': 'it' } });
assert.equal(offline.ev('LANG'), 'en', 'no dictionary, no Italian');
assert.equal(offline.ev('document.documentElement.lang'), 'en');
});
test('missing translations fall back to the English text, with placeholders filled', () => {
const { ev } = load({ lang: 'it' });
assert.equal(ev("tr('No such text, {n} times',{n:3})"), 'No such text, 3 times');
assert.equal(ev("trn('{n} cat','{n} cats',1)"), '1 cat');
assert.equal(ev("trn('{n} cat','{n} cats',2)"), '2 cats');
});
test('every Italian entry keeps the placeholders and HTML tags of its English text', () => {
const dict = loadDict(path.join(__dirname, '..', 'site', 'i18n', 'it.js'));
assert.ok(Object.keys(dict).length > 100);
assert.deepEqual(brokenEntries(dict), []);
});
test('the language buttons on the title screen work before any game exists', () => {
const { ev } = load();
ev("[...document.querySelectorAll('#modalCard [data-act=langSet]')].find(b=>b.textContent==='Italiano').click()");
assert.equal(ev("localStorage.getItem('sot-lang')"), 'it');
});
test('picking a language saves the choice and the game, then reloads', () => {
const { ev } = load();
ev('ACT.start({});dayTick()');
ev("ACT.langSet({v:'it'})");
assert.equal(ev("localStorage.getItem('sot-lang')"), 'it');
assert.ok(ev("localStorage.getItem('sot-save-v1')"));
ev("ACT.langSet({v:'klingon'})");
assert.equal(ev("localStorage.getItem('sot-lang')"), 'it');
});
test('a scenario started in English shows its Italian name after switching', () => {
const en = load();
en.ev("ACT.startScn({id:'stg'});save()");
const { ev } = load({ lang: 'it', storage: { 'sot-save-v1': en.ev("localStorage.getItem('sot-save-v1')") } });
const name = ev("SCN.find(x=>x.id==='stg').n");
assert.notEqual(name, en.ev("SCN.find(x=>x.id==='stg').n"));
assert.ok(ev("document.getElementById('hAsn').textContent").includes(name));
});
for (const lang of ['en', 'it']) {
test(`${lang}: every screen, failure and event renders without errors or unfilled placeholders`, () => {
const { ev, errors } = load(lang === 'en' ? {} : { lang });
seed(ev, 3);
if (lang === 'it') {
assert.match(ev("document.getElementById('modalCard').textContent"), /Come si gioca/);
assert.equal(ev("document.querySelector('#hud [data-act=bank] .lbl').textContent"), 'Cassa · Banca');
}
const { thrown, leaks } = tour(ev);
assert.ok(ev('(S.stats.f||{}).anchor'), 'Baltic and Red Sea anchors count for the badge in every language');
assert.deepEqual(thrown, []);
assert.deepEqual(leaks, []);
assert.deepEqual(errors, []);
});
}