Show tutorial rejections once and preserve editable choices

This commit is contained in:
coyotte508 2026-10-04 23:27:13 +02:00
commit f717e85148
5 changed files with 178 additions and 8 deletions

View file

@ -14,7 +14,7 @@
"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"
"test:tutorial:browser": "node test/tutorial-browser.mjs && node test/tutorial-walkthrough-browser.mjs && node test/tutorial-errors-browser.mjs"
},
"dependencies": {
"@boardgamers/protocol": "0.9.0",

View file

@ -0,0 +1,126 @@
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";
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 {
for (const width of [390, 1440])
for (const locale of ["en", "fr"]) {
const page = await browser.newPage({ viewport: { width, height: 844 } });
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.goto(`${base}/?lesson=full-round&locale=${locale}`);
const guide = page.locator(".vanuatu-tutorial");
const instruction = guide.locator(".bgs-tutorial-body > p").first();
const alert = guide.locator('[role="alert"]');
const accept = async () =>
page.locator("dialog[open] [data-move]").first().click();
const assertCorrection = async () => {
await alert.waitFor({ state: "visible" });
await page.waitForFunction(
() => !document.querySelector("dialog[open]"),
);
assert.equal(await page.locator('[role="alert"]:visible').count(), 1);
assert.equal(
await page.locator(".vanuatu .feedback").isVisible(),
false,
);
assert.equal(
await instruction.isVisible(),
false,
"Do not repeat the instruction",
);
await page.waitForFunction(() => {
const el = document.querySelector(".tutorial-error");
const b = el.getBoundingClientRect();
return b.top >= 0 && b.bottom <= innerHeight;
});
assert.ok(
await page.evaluate(
() => document.documentElement.scrollWidth <= innerWidth,
),
);
};
// A wrong choice in a modal must not leave the correction behind that modal.
await page.locator('[data-character-choice="builder"]').click();
await accept();
await assertCorrection();
await page.locator('[data-character-choice="navigator"]').click();
await accept();
assert.equal(await alert.isVisible(), false);
assert.equal(await instruction.isVisible(), true);
const saved = await page.evaluate(() =>
localStorage.getItem("bgs:tutorial:vanuatu:full-round"),
);
// Match the reported rejected pair. Also reopen a collapsed tutorial guide.
await guide.locator(".bgs-tutorial-heading button").click();
await page.locator('[data-action="fish"]').click();
await page.locator('[data-action="draw"]').click();
await page.locator(".turn-tray [data-move]").click();
await assertCorrection();
assert.equal(
await page.evaluate(() =>
localStorage.getItem("bgs:tutorial:vanuatu:full-round"),
),
saved,
"Rejected choices must not change the lesson history",
);
assert.equal(await page.locator(".draft-slot .icon-fish").count(), 1);
assert.equal(await page.locator(".draft-slot .icon-draw").count(), 1);
await guide.screenshot({
path: `.local/qa/tutorial-correction-${locale}-${width}.png`,
});
// Keep the valid first marker and replace only the wrong second marker.
await page.locator("[data-undo]").click();
await page.locator('[data-action="sell"]').click();
await page.locator(".turn-tray [data-move]").click();
await page.waitForFunction(() =>
document
.querySelector(".bgs-tutorial-heading strong")
.textContent.startsWith("3/12"),
);
assert.equal(await alert.isVisible(), false);
assert.equal(await instruction.isVisible(), true);
assert.equal(await page.locator(".draft-marker").count(), 0);
assert.deepEqual(errors, []);
await page.close();
console.log(
`${width}/${locale}: one inline correction, unchanged state, editable draft and successful retry`,
);
}
} finally {
await browser.close();
server.close();
}

View file

@ -1905,3 +1905,20 @@ body:has(.vanuatu) {
min-height: 20px;
vertical-align: baseline;
}
.vanuatu-tutorial .tutorial-error {
display: flex;
align-items: flex-start;
gap: 9px;
padding: 10px 12px;
border-inline-start: 3px solid #b77b3c;
border-radius: 4px;
background: #fff1da;
color: #784922;
}
.vanuatu-tutorial .tutorial-error > .icon {
flex: none;
width: 21px;
height: 21px;
color: #ad7132;
}

View file

@ -2,6 +2,7 @@ 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 { icon } from "./art.js";
import { pictogramText } from "./prose.js";
import { translateText } from "./localization/index.js";
import { mountGame } from "./ui.js";
@ -20,16 +21,22 @@ export async function mountLesson(target, options) {
const guide = document.createElement("div");
guide.className = "vanuatu-tutorial";
target.append(guide);
let errorFrame;
const ui = mountGame(target, {
language: options.locale ?? "en",
onMove: async (m) => {
const accepted = await tutorial.play(m);
if (!accepted)
throw Error(
tutorial.snapshot.error ||
tutorial.snapshot.feedback ||
"Try the action described in this step.",
);
if (!accepted) {
cancelAnimationFrame(errorFrame);
errorFrame = requestAnimationFrame(() => {
const error = guide.querySelector('[role="alert"]:not([hidden])');
if (!error) return;
const bounds = error.getBoundingClientRect();
if (bounds.top < 0 || bounds.bottom > window.innerHeight)
window.scrollBy({ top: bounds.top - 16, behavior: "instant" });
});
}
return accepted;
},
});
if (options.locale) ui.setPreferences({ locale: options.locale });
@ -49,6 +56,9 @@ export async function mountLesson(target, options) {
".bgs-tutorial-body > p:nth-child(-n+2)",
);
for (const paragraph of paragraphs) paragraph.setAttribute("translate", "no");
const error = guide.querySelector('[role="alert"]');
error.setAttribute("translate", "no");
error.classList.add("tutorial-error");
const offProse = tutorial.subscribe((snapshot) => {
[snapshot.text, snapshot.hint].forEach((source, i) => {
const paragraph = paragraphs[i];
@ -58,8 +68,20 @@ export async function mountLesson(target, options) {
options.locale,
);
});
// Validators often return the current instruction. Show it once, as the
// inline correction, instead of repeating it and adding a floating toast.
paragraphs[0].hidden =
!!snapshot.error && snapshot.error.trim() === snapshot.text.trim();
if (snapshot.error) {
error.innerHTML = `${icon("warning", "")}<span>${pictogramText(translateText(snapshot.error, options.locale), options.locale)}</span>`;
guide.querySelector(".bgs-tutorial-body").hidden = false;
const collapse = guide.querySelector(".bgs-tutorial-heading button");
collapse.setAttribute("aria-expanded", "true");
collapse.textContent = translateText("Hide", options.locale);
}
});
return () => {
cancelAnimationFrame(errorFrame);
offProse();
off();
unmount();

View file

@ -578,7 +578,12 @@ export function mountGame(target, options = {}) {
feedback.hidden = true;
render();
try {
await options.onMove?.(m);
// A tutorial rejection is already explained by its guide. Keep the draft
// available to correct, without playing a move sound or a second alert.
if ((await options.onMove?.(m)) === false) {
closeDialog();
return;
}
void moveSound.play();
selected = null;
action = null;