Use inline pictograms in Vanuatu tutorial and game explanations
This commit is contained in:
parent
e6d4b50a53
commit
a24b86d352
8 changed files with 316 additions and 6 deletions
|
|
@ -11,7 +11,7 @@
|
|||
"build": "node scripts/build.mjs",
|
||||
"test": "node --test test/*.test.js",
|
||||
"dev": "node scripts/dev.mjs",
|
||||
"test:browser": "node test/browser.mjs && node test/journal-browser.mjs && node test/map-zoom-browser.mjs && node test/redraw-browser.mjs && node test/mobile-layout-browser.mjs",
|
||||
"test:browser": "node test/browser.mjs && node test/journal-browser.mjs && node test/map-zoom-browser.mjs && node test/redraw-browser.mjs && node test/mobile-layout-browser.mjs && node test/prose-browser.mjs",
|
||||
"check": "pnpm test:locales && pnpm build && pnpm test && pnpm test:browser && pnpm test:tutorial:browser",
|
||||
"test:locales": "node scripts/check-locales.mjs viewer/localization && node --test scripts/localization.test.mjs",
|
||||
"test:tutorial:browser": "node test/tutorial-browser.mjs && node test/tutorial-walkthrough-browser.mjs"
|
||||
|
|
|
|||
101
test/prose-browser.mjs
Normal file
101
test/prose-browser.mjs
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
import assert from "node:assert/strict";
|
||||
import { createServer } from "node:http";
|
||||
import { readFile, mkdir } from "node:fs/promises";
|
||||
import { extname, resolve } from "node:path";
|
||||
import { chromium } from "playwright";
|
||||
import { languages } from "../viewer/localization/runtime.js";
|
||||
const dist = resolve("dist");
|
||||
const server = createServer(async (req, res) => {
|
||||
try {
|
||||
const path = resolve(
|
||||
dist,
|
||||
"." +
|
||||
new URL(req.url, "http://localhost").pathname.replace(
|
||||
/^\/$/,
|
||||
"/index.html",
|
||||
),
|
||||
);
|
||||
if (!path.startsWith(dist + "/")) throw Error("Invalid path");
|
||||
res.setHeader(
|
||||
"Content-Type",
|
||||
{
|
||||
".js": "text/javascript",
|
||||
".css": "text/css",
|
||||
".html": "text/html",
|
||||
".json": "application/json",
|
||||
}[extname(path)] ?? "application/octet-stream",
|
||||
);
|
||||
res.end(await readFile(path));
|
||||
} catch {
|
||||
res.writeHead(404);
|
||||
res.end();
|
||||
}
|
||||
});
|
||||
await new Promise((r) => server.listen(0, "127.0.0.1", r));
|
||||
const base = `http://127.0.0.1:${server.address().port}`;
|
||||
const browser = await chromium.launch();
|
||||
await mkdir(".local/qa", { recursive: true });
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 390, height: 844 } });
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
for (const locale of Object.keys(languages)) {
|
||||
await page.goto(`${base}/?lesson=beggar&locale=${locale}`);
|
||||
const prose = page.locator(".bgs-tutorial-body > p").first();
|
||||
for (const name of ["coin", "point", "draw", "build"])
|
||||
await prose.locator(`.icon-${name}`).first().waitFor();
|
||||
for (const symbol of await prose.locator(".prose-icon").all()) {
|
||||
assert.ok(await symbol.getAttribute("aria-label"));
|
||||
assert.equal(
|
||||
await symbol.getAttribute("title"),
|
||||
await symbol.getAttribute("aria-label"),
|
||||
);
|
||||
const box = await symbol.locator("svg").boundingBox();
|
||||
assert.ok(box.width >= 20 && box.height >= 20, locale);
|
||||
}
|
||||
assert.ok(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= innerWidth,
|
||||
),
|
||||
locale,
|
||||
);
|
||||
if (["fr", "en"].includes(locale)) {
|
||||
await page
|
||||
.locator(".vanuatu-tutorial")
|
||||
.screenshot({ path: `.local/qa/prose-beggar-${locale}.png` });
|
||||
await page.locator(".bgs-tutorial-playback button").nth(3).click();
|
||||
await prose.locator(".icon-point").first().waitFor();
|
||||
await page.locator(".bgs-tutorial-playback button").nth(1).click();
|
||||
await prose.locator(".icon-coin").first().waitFor();
|
||||
}
|
||||
}
|
||||
await page.goto(`${base}/?new&hotseat&locale=fr`);
|
||||
await page.locator('[data-character-choice="beggar"]').click();
|
||||
const help = page.locator('dialog [data-character-help="beggar"]');
|
||||
await help.locator(".icon-coin").waitFor();
|
||||
await help.locator(".icon-point").waitFor();
|
||||
assert.equal(
|
||||
await help.locator(".icon-point").locator("..").getAttribute("aria-label"),
|
||||
"points de prospérité",
|
||||
);
|
||||
await page
|
||||
.locator("dialog")
|
||||
.screenshot({ path: ".local/qa/prose-game-fr.png" });
|
||||
await page.evaluate(() => vanuatuDemo.ui.setPreferences({ language: "en" }));
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
document
|
||||
.querySelector("dialog [data-character-help] .icon-point")
|
||||
?.parentElement.getAttribute("aria-label") === "prosperity",
|
||||
);
|
||||
await page.locator("dialog [data-close]").click();
|
||||
await page.locator("[data-help]").first().click();
|
||||
assert.ok(await page.locator(".rules .prose-icon").count());
|
||||
assert.deepEqual(errors, []);
|
||||
console.log(
|
||||
"16-language tutorial pictograms, replay, mobile layout, accessible labels, and live game help passed.",
|
||||
);
|
||||
} finally {
|
||||
await browser.close();
|
||||
server.close();
|
||||
}
|
||||
56
test/prose.test.js
Normal file
56
test/prose.test.js
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { pictogramText } from "../viewer/prose.js";
|
||||
import { LESSON } from "../viewer/tutorial-copy.js";
|
||||
import { languages } from "../viewer/localization/runtime.js";
|
||||
|
||||
for (const locale of Object.keys(languages))
|
||||
test(`tutorial prose preserves ${locale} grammar around the four symbols`, async () => {
|
||||
const catalog = JSON.parse(
|
||||
await readFile(
|
||||
new URL(`../viewer/localization/${locale}.json`, import.meta.url),
|
||||
"utf8",
|
||||
),
|
||||
);
|
||||
const text = catalog[LESSON.beggarStart];
|
||||
const html = pictogramText(text, locale);
|
||||
for (const name of ["coin", "point", "draw", "build"])
|
||||
assert.ok(html.includes(`icon-${name}`), `${locale}: ${name}`);
|
||||
// Replace the generated icon with its accessible name: no translated text,
|
||||
// punctuation or amounts may disappear or change order.
|
||||
const plain = html.replace(
|
||||
/<span class="prose-icon" role="img" aria-label="([^"]*)"[^>]*>.*?<\/span>/g,
|
||||
"$1",
|
||||
);
|
||||
const escaped = text.replace(
|
||||
/[&<>"']/g,
|
||||
(c) =>
|
||||
({
|
||||
"&": "&",
|
||||
"<": "<",
|
||||
">": ">",
|
||||
'"': """,
|
||||
"'": "'",
|
||||
})[c],
|
||||
);
|
||||
assert.equal(plain, escaped);
|
||||
});
|
||||
|
||||
test("prose escapes HTML and matches whole terms without changing character names", () => {
|
||||
assert.equal(
|
||||
pictogramText('<img src=x onerror="oops"> Builder Drawbridge rebuild'),
|
||||
"<img src=x onerror="oops"> Builder Drawbridge rebuild",
|
||||
);
|
||||
assert.match(
|
||||
pictogramText("5 points de prospérité", "fr"),
|
||||
/aria-label="points de prospérité"/,
|
||||
);
|
||||
assert.equal(
|
||||
(pictogramText("5 points de prospérité", "fr").match(/prose-icon/g) ?? [])
|
||||
.length,
|
||||
1,
|
||||
);
|
||||
assert.match(pictogramText("0바투", "ko"), /icon-coin/);
|
||||
assert.match(pictogramText("0 رفاه", "fa-IR"), /icon-point/);
|
||||
});
|
||||
102
viewer/prose.js
Normal file
102
viewer/prose.js
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
import { esc, icon } from "./art.js";
|
||||
import { resolveLocale } from "./localization/runtime.js";
|
||||
|
||||
// Only authored explanatory prose uses this formatter, never player names, chat,
|
||||
// inputs or HTML. Translate the complete sentence first, then replace whole terms.
|
||||
// Include grammatical forms used by the catalogues; longest phrases win.
|
||||
const terms = {
|
||||
en: ["vatus|vatu", "prosperity points|prosperity", "Build", "Draw"],
|
||||
fr: [
|
||||
"vatus|vatu",
|
||||
"points de prospérité|point de prospérité|prospérité",
|
||||
"Construire",
|
||||
"Dessiner",
|
||||
],
|
||||
de: [
|
||||
"Vatus|Vatu",
|
||||
"Wohlstandspunkte|Wohlstandspunkten|Wohlstands|Wohlstand",
|
||||
"Bauen",
|
||||
"Zeichnen",
|
||||
],
|
||||
nl: ["vatus|vatu", "welvaartspunten|welvaart", "Bouwen", "Tekenen"],
|
||||
da: ["vatus|vatu", "velstandspoint|velstand", "Byg", "Tegn"],
|
||||
it: [
|
||||
"vatus|vatu",
|
||||
"punti prosperità|punti di prosperità|prosperità",
|
||||
"Costruisci|Costruire",
|
||||
"Disegnare|Disegna",
|
||||
],
|
||||
"pt-BR": [
|
||||
"vatus|vatu",
|
||||
"pontos de prosperidade|ponto de prosperidade|prosperidade",
|
||||
"Construir",
|
||||
"Desenhar",
|
||||
],
|
||||
pl: [
|
||||
"vatus|vatu",
|
||||
"punkty dobrobytu|punktów dobrobytu|dobrobytu|dobrobyt",
|
||||
"Buduj|Budowa|Budowy|Budowę",
|
||||
"Rysuj|Rysowanie|Rysowania",
|
||||
],
|
||||
ro: [
|
||||
"vatus|vatu",
|
||||
"puncte de prosperitate|prosperitate",
|
||||
"Construiește|Construcție",
|
||||
"Desenează|Desen",
|
||||
],
|
||||
ru: [
|
||||
"вату",
|
||||
"очки процветания|очков процветания|процветания|процветание",
|
||||
"Строить|Строительство|Строительства",
|
||||
"Рисовать|Рисование|Рисования",
|
||||
],
|
||||
el: [
|
||||
"βάτου",
|
||||
"πόντοι ευημερίας|πόντους ευημερίας|ευημερία|ευημερίας",
|
||||
"Χτίσε|Κατασκευή|Κατασκευής",
|
||||
"Σχεδίαση|Σχέδιο|Σχεδίου",
|
||||
],
|
||||
hi: ["वातु", "समृद्धि अंक|समृद्धि", "निर्माण", "चित्र बनाएँ|चित्र"],
|
||||
ko: ["바투", "번영 점수|번영", "건설", "모래그림|그림"],
|
||||
"zh-TW": ["瓦圖", "繁榮點數|繁榮分數|繁榮", "建造", "沙畫"],
|
||||
vi: ["vatus|vatu", "điểm thịnh vượng|thịnh vượng", "Xây dựng|Xây", "Vẽ"],
|
||||
fa: ["واتو|واتوی", "امتیاز شکوفایی|شکوفایی|رفاه", "ساخت", "نقاشی"],
|
||||
};
|
||||
const cache = new Map();
|
||||
const escapePattern = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
function vocabulary(locale) {
|
||||
if (cache.has(locale)) return cache.get(locale);
|
||||
const names = ["coin", "point", "build", "draw"];
|
||||
const words = new Map(
|
||||
(terms[locale] ?? terms.en).flatMap((group, i) =>
|
||||
group.split("|").map((word) => [word.toLowerCase(), names[i]]),
|
||||
),
|
||||
);
|
||||
const body = [...words.keys()]
|
||||
.sort((a, b) => b.length - a.length)
|
||||
.map(escapePattern)
|
||||
.join("|");
|
||||
// Korean particles and Chinese words have no separating spaces. Numbers can
|
||||
// touch a unit in any language (e.g. 0바투); letters in other words cannot.
|
||||
const boundary = ["ko", "zh-TW"].includes(locale) ? "" : "[\\p{L}\\p{M}]";
|
||||
const pattern = new RegExp(
|
||||
`${boundary ? `(?<!${boundary})` : ""}(?:${body})${boundary ? `(?!${boundary})` : ""}`,
|
||||
"giu",
|
||||
);
|
||||
const result = { words, pattern };
|
||||
cache.set(locale, result);
|
||||
return result;
|
||||
}
|
||||
export function pictogramText(text, locale = "en") {
|
||||
const { words, pattern } = vocabulary(resolveLocale(locale));
|
||||
let result = "",
|
||||
end = 0;
|
||||
for (const match of String(text).matchAll(pattern)) {
|
||||
const label = match[0],
|
||||
name = words.get(label.toLowerCase());
|
||||
result += esc(text.slice(end, match.index));
|
||||
result += `<span class="prose-icon" role="img" aria-label="${esc(label)}" title="${esc(label)}">${icon(name, label)}</span>`;
|
||||
end = match.index + label.length;
|
||||
}
|
||||
return result + esc(text.slice(end));
|
||||
}
|
||||
|
|
@ -14,8 +14,10 @@ import {
|
|||
esc,
|
||||
} from "./art.js";
|
||||
import { PRICES, VALUES } from "../engine/catalog.js";
|
||||
import { pictogramText } from "./prose.js";
|
||||
import { translateText } from "./localization/index.js";
|
||||
export function rulesHtml(lang = "en", colorBlind = false) {
|
||||
const prose = (text) => pictogramText(t(text), lang);
|
||||
const t = (text) => translateText(text, lang);
|
||||
const icon = (name) =>
|
||||
renderIcon(name, t(iconLabel(name)), false, colorBlind);
|
||||
|
|
@ -77,7 +79,7 @@ export function rulesHtml(lang = "en", colorBlind = false) {
|
|||
],
|
||||
[
|
||||
"Export",
|
||||
esc(t(EXPORT_RULE)) +
|
||||
prose(EXPORT_RULE) +
|
||||
'<span class="export-prices" role="list">' +
|
||||
Object.keys(PRICES)
|
||||
.map(
|
||||
|
|
@ -180,5 +182,5 @@ export function rulesHtml(lang = "en", colorBlind = false) {
|
|||
"Final scoring": "point",
|
||||
"Rising Waters (expansion only)": "water",
|
||||
};
|
||||
return `<div class="rules">${paragraphs.map(([h, p]) => `<section><h3>${sectionIcons[h] ? icon(sectionIcons[h]) + " " : ""}${esc(t(h))}</h3><p translate="no">${p.includes("<") ? p : esc(t(p))}</p></section>`).join("")}</div><p class="rules-links"><a href="https://www.quined.nl/wp-content/uploads/2019/01/Vanuatu_Rulebook_${lang === "fr" ? "FR-WEBversion" : "UK_WEBversion-4"}.pdf" target="_blank" rel="noopener">${esc(t("Original rulebook"))} ↗</a> · <a href="https://quined.nl/wp-content/uploads/2017/06/Vanuatu2p_EN.pdf" target="_blank" rel="noopener">${esc(t("Two-player rules"))} ↗</a></p>`;
|
||||
return `<div class="rules">${paragraphs.map(([h, p]) => `<section><h3>${sectionIcons[h] ? icon(sectionIcons[h]) + " " : ""}${esc(t(h))}</h3><p translate="no">${p.includes("<") ? p : prose(p)}</p></section>`).join("")}</div><p class="rules-links"><a href="https://www.quined.nl/wp-content/uploads/2019/01/Vanuatu_Rulebook_${lang === "fr" ? "FR-WEBversion" : "UK_WEBversion-4"}.pdf" target="_blank" rel="noopener">${esc(t("Original rulebook"))} ↗</a> · <a href="https://quined.nl/wp-content/uploads/2017/06/Vanuatu2p_EN.pdf" target="_blank" rel="noopener">${esc(t("Two-player rules"))} ↗</a></p>`;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1889,3 +1889,19 @@ body:has(.vanuatu) {
|
|||
vertical-align: -2px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* Inline rules/tutorial symbols stay legible at prose size and keep native
|
||||
tooltip labels. They do not intercept gestures or add another scroll area. */
|
||||
:is(.vanuatu, .vanuatu-tutorial) .prose-icon {
|
||||
display: inline-block;
|
||||
vertical-align: -0.3em;
|
||||
line-height: 1;
|
||||
white-space: nowrap;
|
||||
}
|
||||
:is(.vanuatu, .vanuatu-tutorial) .prose-icon > .icon {
|
||||
width: 1.55em;
|
||||
height: 1.55em;
|
||||
min-width: 20px;
|
||||
min-height: 20px;
|
||||
vertical-align: baseline;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ import { createTutorial } from "@boardgamers/protocol/tutorial";
|
|||
import { mountTutorialGuide } from "@boardgamers/protocol/tutorial/dom";
|
||||
import { stripSecret } from "../engine/index.js";
|
||||
import { chapters } from "./tutorials.js";
|
||||
import { pictogramText } from "./prose.js";
|
||||
import { translateText } from "./localization/index.js";
|
||||
import { mountGame } from "./ui.js";
|
||||
export async function mountLesson(target, options) {
|
||||
const config = chapters[options.chapter];
|
||||
|
|
@ -41,7 +43,24 @@ export async function mountLesson(target, options) {
|
|||
const unmount = mountTutorialGuide(guide, tutorial, {
|
||||
nextChapter: options.nextChapter,
|
||||
});
|
||||
// The protocol owns the guide and navigation. Format its authored paragraphs
|
||||
// after each snapshot; no DOM observer or changes to the board are needed.
|
||||
const paragraphs = guide.querySelectorAll(
|
||||
".bgs-tutorial-body > p:nth-child(-n+2)",
|
||||
);
|
||||
for (const paragraph of paragraphs) paragraph.setAttribute("translate", "no");
|
||||
const offProse = tutorial.subscribe((snapshot) => {
|
||||
[snapshot.text, snapshot.hint].forEach((source, i) => {
|
||||
const paragraph = paragraphs[i];
|
||||
if (!paragraph || !source) return;
|
||||
paragraph.innerHTML = pictogramText(
|
||||
translateText(source, options.locale),
|
||||
options.locale,
|
||||
);
|
||||
});
|
||||
});
|
||||
return () => {
|
||||
offProse();
|
||||
off();
|
||||
unmount();
|
||||
tutorial.destroy();
|
||||
|
|
|
|||
20
viewer/ui.js
20
viewer/ui.js
|
|
@ -27,6 +27,7 @@ import { boardSvg, center, tilePreviewSvg } from "./board.js";
|
|||
import { mountMapZoom } from "./map-zoom.js";
|
||||
import { translator, characterHelp } from "./labels.js";
|
||||
import { mountActivity } from "./activity.js";
|
||||
import { pictogramText } from "./prose.js";
|
||||
import { rulesHtml } from "./rules.js";
|
||||
import { createMoveSound } from "./sound.js";
|
||||
import {
|
||||
|
|
@ -169,6 +170,8 @@ export function mountGame(target, options = {}) {
|
|||
const own = () => s?.players[player];
|
||||
const charName = (c) => esc(CHARACTERS[c]?.["name"] ?? c);
|
||||
const charHelp = (c) => esc(characterHelp[c]?.[0] ?? "");
|
||||
const charHelpHtml = (c) =>
|
||||
`<span data-character-help="${esc(c)}" data-prose-locale="${lang}" translate="no">${pictogramText(translateText(characterHelp[c]?.[0] ?? "", lang), lang)}</span>`;
|
||||
function btn(content, attr = "", className = "") {
|
||||
return `<button type="button" class="${className}" ${attr}>${content}</button>`;
|
||||
}
|
||||
|
|
@ -346,7 +349,7 @@ export function mountGame(target, options = {}) {
|
|||
.map((m) => {
|
||||
const c = CHARACTERS[m.character];
|
||||
return btn(
|
||||
`<img src="${assets["character-" + c.art]}" alt=""><strong>${charName(m.character)}</strong><span>${charHelp(m.character)}</span>`,
|
||||
`<img src="${assets["character-" + c.art]}" alt=""><strong>${charName(m.character)}</strong>${charHelpHtml(m.character)}`,
|
||||
`data-character-choice="${m.character}"`,
|
||||
"character-choice",
|
||||
);
|
||||
|
|
@ -505,6 +508,17 @@ export function mountGame(target, options = {}) {
|
|||
rules.innerHTML = rulesHtml(lang, colorBlind);
|
||||
rules.dataset.presentation = rulesKey;
|
||||
}
|
||||
for (const help of dialog.querySelectorAll("[data-character-help]")) {
|
||||
if (help.dataset.proseLocale === lang) continue;
|
||||
help.innerHTML = pictogramText(
|
||||
translateText(
|
||||
characterHelp[help.dataset.characterHelp]?.[0] ?? "",
|
||||
lang,
|
||||
),
|
||||
lang,
|
||||
);
|
||||
help.dataset.proseLocale = lang;
|
||||
}
|
||||
activity.update(s, analysis, colorBlind);
|
||||
updateUnread();
|
||||
}
|
||||
|
|
@ -708,13 +722,13 @@ export function mountGame(target, options = {}) {
|
|||
(m) => m.type === "character" && m.character === d.characterChoice,
|
||||
);
|
||||
showDialog(
|
||||
`<div class="character-detail"><img src="${assets["character-" + CHARACTERS[m.character].art]}" alt=""><div><h2>${charName(m.character)}</h2><p>${charHelp(m.character)}</p>${moveButton(m, true)}</div></div>`,
|
||||
`<div class="character-detail"><img src="${assets["character-" + CHARACTERS[m.character].art]}" alt=""><div><h2>${charName(m.character)}</h2><p>${charHelpHtml(m.character)}</p>${moveButton(m, true)}</div></div>`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
if ("character" in d) {
|
||||
showDialog(
|
||||
`<div class="character-detail"><img src="${assets["character-" + CHARACTERS[d.character].art]}" alt=""><div><h2>${charName(d.character)}</h2><p>${charHelp(d.character)}</p><small>${"Once per round."}</small></div></div>`,
|
||||
`<div class="character-detail"><img src="${assets["character-" + CHARACTERS[d.character].art]}" alt=""><div><h2>${charName(d.character)}</h2><p>${charHelpHtml(d.character)}</p><small>${"Once per round."}</small></div></div>`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue