diff --git a/package.json b/package.json index 64c6cb6..c14e8dc 100644 --- a/package.json +++ b/package.json @@ -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", + "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", "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" diff --git a/test/engine.test.js b/test/engine.test.js index d7b2222..8901500 100644 --- a/test/engine.test.js +++ b/test/engine.test.js @@ -247,6 +247,68 @@ test("batched planning accounts for the first new marker as a prerequisite", () ), ); }); +test("planning a sale before export uses the cash left after immediate conversion", () => { + for (const { money, fish, market, cash, points, allowed } of [ + { money: 0, fish: [3], market: 3, cash: 9, points: 0, allowed: true }, + // Reported position: 1 + 3 × 3 = 10 vatus becomes 5 prosperity, 0 cash. + { money: 1, fish: [3], market: 3, cash: 0, points: 5, allowed: false }, + { money: 1, fish: [3], market: 2, cash: 7, points: 0, allowed: true }, + { money: 1, fish: [1], market: 3, cash: 4, points: 0, allowed: true }, + { money: 1, fish: [1], market: 1, cash: 2, points: 0, allowed: false }, + ]) { + const s = actionState(); + s.phase = "plan"; + s.planningPass = 0; + Object.assign(s.players[0], { + money, + fish, + markers: Object.fromEntries(E.ACTIONS.map((a) => [a, 0])), + }); + s.market = market; + s.board["0,0"].huts = [0]; + s.board["0,0"].goods = { kava: 0, copra: 0, beef: 1 }; + const label = JSON.stringify({ money, fish, market }); + assert.equal( + E.availableMoves(s).some( + (m) => m.type === "plan" && m.actions.join() === "sell,buy", + ), + allowed, + label, + ); + + s.phase = "actions"; + s.players[0].markers.sell = 1; + s.players[0].markers.buy = 1; + const afterSale = E.move(s, act(s, 0, "sell", { fish }), 0); + assert.equal(afterSale.players[0].money, cash, label); + assert.equal(afterSale.players[0].score, points, label); + assert.equal( + E.actionOptions(afterSale, 0, "buy").some((m) => m.good === "beef"), + allowed, + label, + ); + } +}); +test("planned sailing can spend a vatu before a sale to avoid conversion and fund export", () => { + const s = actionState(); + s.phase = "plan"; + s.planningPass = 0; + Object.assign(s.players[0], { + money: 1, + fish: [3], + markers: Object.fromEntries(E.ACTIONS.map((a) => [a, 0])), + }); + s.market = 3; + s.board["0,0"].huts = [0]; + s.board["0,0"].goods = { kava: 0, copra: 0, beef: 1 }; + const sellThenExport = () => + E.availableMoves(s).some( + (m) => m.type === "plan" && m.actions.join() === "sell,buy", + ); + assert.equal(sellThenExport(), false); + s.players[0].markers.sail = 1; + assert.equal(sellThenExport(), true); +}); test("an optional treasure sale is not skipped by automatic marker retrieval", () => { let s = actionState(); s.actor = 0; diff --git a/test/map-zoom-browser.mjs b/test/map-zoom-browser.mjs index 7291aad..f96704f 100644 --- a/test/map-zoom-browser.mjs +++ b/test/map-zoom-browser.mjs @@ -45,6 +45,17 @@ try { page.on("pageerror", (error) => errors.push(error.message)); await page.goto(base + "/?new&hotseat&locale=fr"); await page.waitForSelector(".map-scroll[data-zoom]"); + assert.equal( + await page + .locator(".archipelago") + .evaluate((svg) => + svg + .getAnimations({ subtree: true }) + .some((a) => a.playState === "running"), + ), + false, + "The mobile board must not continuously repaint decorative water", + ); await page.locator(".sea-board").scrollIntoViewIfNeeded(); const map = page.locator(".map-scroll"); const zoom = () => map.evaluate((el) => Number(el.dataset.zoom)); @@ -80,6 +91,11 @@ try { { id: 1, x: midpoint.x - distance / 2, y: midpoint.y }, { id: 2, x: midpoint.x + distance / 2, y: midpoint.y }, ]; + // Real pinches usually begin with one finger, then add the second. + await cdp.send("Input.dispatchTouchEvent", { + type: "touchStart", + touchPoints: points(80).slice(0, 1), + }); await cdp.send("Input.dispatchTouchEvent", { type: "touchStart", touchPoints: points(80), diff --git a/test/mobile-layout-browser.mjs b/test/mobile-layout-browser.mjs new file mode 100644 index 0000000..e4bddf1 --- /dev/null +++ b/test/mobile-layout-browser.mjs @@ -0,0 +1,208 @@ +import assert from "node:assert/strict"; +import { chromium } from "playwright"; +import { readFile } from "node:fs/promises"; +import { createServer } from "node:http"; +import { resolve, extname } from "node:path"; + +const dist = resolve("dist"); +const server = createServer(async (req, res) => { + try { + const url = new URL(req.url, "http://localhost"); + const path = resolve( + dist, + "." + (url.pathname === "/" ? "/index.html" : url.pathname), + ); + if (!path.startsWith(dist + "/")) throw Error("Invalid path"); + res.setHeader( + "Content-Type", + { ".js": "text/javascript", ".css": "text/css", ".html": "text/html" }[ + extname(path) + ] ?? "application/octet-stream", + ); + res.end(await readFile(path)); + } catch { + res.writeHead(404); + res.end(); + } +}); +await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); +const base = `http://127.0.0.1:${server.address().port}`; +const browser = await chromium.launch({ + headless: true, + ...(process.env.CHROME_PATH + ? { executablePath: process.env.CHROME_PATH } + : {}), +}); +const errors = []; +try { + for (const width of [320, 390, 430]) { + const page = await browser.newPage({ + viewport: { width, height: 844 }, + isMobile: true, + hasTouch: true, + }); + page.on("pageerror", (error) => errors.push(error.message)); + for (const count of [2, 3, 5]) { + await page.goto(`${base}/?new&hotseat&players=${count}&locale=fr`); + await page.waitForFunction(() => window.vanuatuDemo); + await page.evaluate(() => { + let s = vanuatuDemo.state; + while (s.phase === "character") + s = vanuatuDemo.engine.moveAI(s, s.actor); + s.phase = "plan"; + s.actor = 0; + s.planningPass = 0; + s.players.forEach((p, i) => { + p.fish = [3, 2]; + p.treasures = [2, 1]; + p.score = 100 + i; + p.markers.rest = 1; + p.name = [ + "AlphaZero", + "coyote508", + "SchweddyBalls", + "Spock", + "TheLongName", + ][i]; + }); + vanuatuDemo.setState(s); + vanuatuDemo.ui.setPreferences({ language: "fr", colorBlind: true }); + }); + // Even five players' stacks plus a draft marker fit in the same band. + await page.locator('[data-action="rest"]').click(); + assert.equal(await page.locator(".draft-marker").textContent(), "+1"); + const layout = await page.evaluate(() => { + const dock = document.querySelector(".action-dock"); + const strip = document.querySelector(".players"); + const cards = [...strip.children]; + const contained = (outer, inner) => { + const a = outer.getBoundingClientRect(), + b = inner.getBoundingClientRect(); + return ( + b.left >= a.left - 1 && + b.right <= a.right + 1 && + b.top >= a.top - 1 && + b.bottom <= a.bottom + 1 + ); + }; + return { + dockWidth: dock.clientWidth, + dockScroll: dock.scrollWidth, + dockHeight: dock.clientHeight, + actions: [...dock.children].length, + controlsFit: [ + ...dock.querySelectorAll( + ".action-symbol, .marker-stack, .draft-marker", + ), + ].every((e) => contained(e.closest("button"), e)), + badgesFit: [...dock.querySelectorAll(".marker-stack")].every( + (e) => e.scrollWidth <= e.clientWidth + 1, + ), + twoCards: contained(strip, cards[0]) && contained(strip, cards[1]), + cardsFit: cards.every((card) => + [ + ...card.querySelectorAll( + ".player-supplies .token b, .score b, .character-owned", + ), + ].every((e) => contained(card, e)), + ), + height: strip.clientHeight, + supplies: cards.map((c) => + [...c.querySelectorAll(".player-supplies b")].map( + (e) => e.textContent, + ), + ), + names: cards.map((c) => c.querySelector(".profile").title), + }; + }); + assert.equal(layout.actions, 9); + assert.equal( + layout.dockScroll, + layout.dockWidth, + "all nine actions fit without horizontal scrolling", + ); + assert.ok( + layout.dockHeight >= 44 && layout.dockHeight <= 74, + "action strip keeps a touch target of at least 44px without becoming taller than before", + ); + assert.ok( + layout.controlsFit, + "all marker counts and draft counters stay inside their button", + ); + assert.ok( + layout.badgesFit, + "color-blind symbols and counts stay readable", + ); + assert.ok(layout.twoCards, "two complete player cards fit side by side"); + assert.ok( + layout.cardsFit, + "individual stock values and scores are not clipped", + ); + assert.ok( + layout.height <= 140, + "loaded player cards stay shorter than the previous 191px strip", + ); + for (const values of layout.supplies) + assert.deepEqual(values.slice(1), ["3", "2", "2", "1", "8"]); + assert.equal( + layout.names[2] ?? layout.names[1], + count === 2 ? "coyote508" : "SchweddyBalls", + ); + } + const cdp = await page.context().newCDPSession(page); + async function swipe(locator, dx, dy) { + await locator.scrollIntoViewIfNeeded(); + const r = await locator.boundingBox(); + const x = r.x + r.width / 2, + y = r.y + r.height / 2; + await cdp.send("Input.dispatchTouchEvent", { + type: "touchStart", + touchPoints: [{ x, y }], + }); + for (const ratio of [0.2, 0.4, 0.6, 0.8, 1]) { + await cdp.send("Input.dispatchTouchEvent", { + type: "touchMove", + touchPoints: [{ x: x + dx * ratio, y: y + dy * ratio }], + }); + await page.waitForTimeout(35); + } + await cdp.send("Input.dispatchTouchEvent", { + type: "touchEnd", + touchPoints: [], + }); + await page.waitForTimeout(150); + } + const before = await page.evaluate(() => JSON.stringify(vanuatuDemo.state)); + // The remaining player cards can still be swiped, including over buttons. + await swipe( + page.locator(".player-card").nth(1).locator(".character-owned"), + -180, + 0, + ); + assert.ok( + await page.locator(".players").evaluate((e) => e.scrollLeft > 30), + ); + assert.equal(await page.locator("dialog[open]").count(), 0); + // Vertical gestures starting on enabled and disabled action buttons scroll + // the document; they must not select an action or submit a move. + for (const disabled of [false, true]) { + if (disabled) await page.evaluate(() => vanuatuDemo.ui.setEnabled(false)); + await page.locator('[data-action="rest"]').scrollIntoViewIfNeeded(); + const beforeY = await page.evaluate(() => scrollY); + await swipe(page.locator('[data-action="rest"]'), 0, -90); + assert.ok(await page.evaluate((y) => scrollY > y + 20, beforeY)); + } + assert.equal( + await page.evaluate(() => JSON.stringify(vanuatuDemo.state)), + before, + ); + await page.close(); + console.log( + `${width}px: nine actions, two visible player cards, full stocks, color-blind markers and touch scrolling passed`, + ); + } + assert.deepEqual(errors, []); +} finally { + await browser.close(); + server.close(); +} diff --git a/test/redraw-browser.mjs b/test/redraw-browser.mjs new file mode 100644 index 0000000..7525ecf --- /dev/null +++ b/test/redraw-browser.mjs @@ -0,0 +1,216 @@ +import assert from "node:assert/strict"; +import { chromium } from "playwright"; +import { createServer } from "node:http"; +import { readFile } from "node:fs/promises"; +import { resolve, extname } from "node:path"; +import * as E from "../engine/index.js"; + +const dist = resolve("dist"); +const server = createServer(async (req, res) => { + try { + const pathname = new URL(req.url, "http://localhost").pathname; + if (pathname === "/") { + res.setHeader("Content-Type", "text/html; charset=utf-8"); + res.end( + '
', + ); + return; + } + const path = resolve(dist, "." + pathname); + if (!path.startsWith(dist + "/")) throw Error("Invalid path"); + res.setHeader( + "Content-Type", + { + ".js": "text/javascript", + ".css": "text/css", + ".json": "application/json", + ".webp": "image/webp", + }[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 browser = await chromium.launch(); +try { + for (const width of [390, 1400]) { + const page = await browser.newPage({ + viewport: { width, height: 844 }, + isMobile: width < 700, + hasTouch: width < 700, + reducedMotion: "reduce", + }); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const game = E.init(3, [], {}, "redraws"); + game.phase = "actions"; + game.actor = 0; + game.first = 0; + game.players[0].boat = "1,0"; + game.players[0].character = null; + game.players[0].markers.sail = 1; + game.players[0].markers.fish = 1; + game.board["1,0"] = E.tileState("startFish"); + const state = E.stripSecret(game, 0); + await page.goto(`http://127.0.0.1:${server.address().port}/`); + await page.evaluate((s) => { + window.fixture = s; + window.host = vanuatu.launch("#app"); + host.emit("player", { index: 0 }); + host.emit("preferences", { locale: "fr", sound: false }); + host.emit("state", s); + window.settle = () => + new Promise((r) => + requestAnimationFrame(() => requestAnimationFrame(r)), + ); + }, state); + await page.waitForSelector(".archipelago"); + await page.waitForFunction( + () => + document.querySelector(".vanuatu").lang === "fr" || + document.querySelector("#app").lang === "fr", + ); + await page.waitForTimeout(100); + // Repeated server/preference events must leave the visible game untouched. + assert.deepEqual( + await page.evaluate(async () => { + const records = []; + const observer = new MutationObserver((rs) => records.push(...rs)); + observer.observe(document.querySelector(".play"), { + childList: true, + attributes: true, + characterData: true, + subtree: true, + }); + for (let i = 0; i < 3; i++) { + host.emit("state", structuredClone(fixture)); + host.emit("player", { index: 0 }); + host.emit("preferences", { locale: "fr", sound: !!(i % 2) }); + await settle(); + } + observer.disconnect(); + return records.map((r) => r.type); + }), + [], + "duplicate state/player events and sound toggles do not patch the board or controls", + ); + + await page.locator("[data-zoom-in]").click(); + const before = await page.evaluate(() => { + const map = document.querySelector(".map-scroll"); + map.scrollLeft = 60; + map.scrollTop = 40; + return { x: map.scrollLeft, y: map.scrollTop, zoom: map.dataset.zoom }; + }); + // An opponent's marker affects the dock, but not the SVG or map layout. + assert.equal( + await page.evaluate(async () => { + let mutations = 0; + const observer = new MutationObserver((rs) => (mutations += rs.length)); + observer.observe(document.querySelector(".map-scroll"), { + childList: true, + attributes: true, + characterData: true, + subtree: true, + }); + fixture.players[1].markers.rest = 2; + host.emit("state", structuredClone(fixture)); + await settle(); + observer.disconnect(); + return mutations; + }), + 0, + ); + assert.equal( + await page.locator('[data-action="rest"] .marker-stack').textContent(), + "2", + ); + assert.deepEqual( + await page.locator(".map-scroll").evaluate((map) => ({ + x: map.scrollLeft, + y: map.scrollTop, + zoom: map.dataset.zoom, + })), + before, + ); + + // Selection highlights are transient. The next real move must clear them, + // even when it changes no boat position or other board artwork. + for (let i = 0; i < 3; i++) { + await page.locator('[data-action="sail"]').click(); + assert.ok(await page.locator(".map-cell.legal").count()); + assert.equal(await page.locator(".turn-tray [data-cancel]").count(), 1); + await page.evaluate(async () => { + fixture.historyLength++; + fixture.players[1].money++; + host.emit("state", structuredClone(fixture)); + await settle(); + }); + assert.equal(await page.locator(".map-cell.legal").count(), 0); + assert.equal(await page.locator(".cell-highlight.legal").count(), 0); + assert.equal(await page.locator(".turn-tray [data-cancel]").count(), 0); + } + + const fish = page.locator('[data-cell="1,0"] .resource-n').first(); + assert.equal(await fish.textContent(), "2"); + await page.evaluate(async () => { + fixture.board["1,0"].fish = 1; + host.emit("state", structuredClone(fixture)); + await settle(); + }); + assert.equal( + await fish.textContent(), + "1", + "real resource changes still reach the board", + ); + + // New history is appended without removing the rows a player is reading. + assert.deepEqual( + await page.evaluate(async () => { + const list = document.querySelector(".event-list"); + const rows = [...list.children]; + let removed = 0; + const observer = new MutationObserver( + (rs) => + (removed += rs.reduce((n, r) => n + r.removedNodes.length, 0)), + ); + observer.observe(list, { childList: true, subtree: true }); + fixture.events.push({ + type: "beg", + p: 0, + amount: 2, + round: 1, + step: ++fixture.historyLength, + }); + host.emit("state", structuredClone(fixture)); + await settle(); + observer.disconnect(); + return { + removed, + kept: rows.every((row, i) => row === list.children[i]), + }; + }), + { removed: 0, kept: true }, + ); + assert.equal(await page.locator(".event-beg").count(), 1); + // Switching back to an earlier state (as replay does) removes stale rows + // and updates resources; it must not hit an obsolete render cache. + await page.evaluate(async (s) => { + host.emit("state", s); + await settle(); + }, state); + assert.equal(await page.locator(".event-beg").count(), 0); + assert.equal(await fish.textContent(), "2"); + assert.deepEqual(errors, []); + console.log( + `${width}px: duplicate updates, sound, marker-only changes, selection reset, resources and retained journal rows passed`, + ); + await page.close(); + } +} finally { + await browser.close(); + server.close(); +} diff --git a/viewer/activity.js b/viewer/activity.js index 0aad2fd..1f965d9 100644 --- a/viewer/activity.js +++ b/viewer/activity.js @@ -1,4 +1,5 @@ import { assets } from "./assets.js"; +import { createRenderer } from "./dom.js"; import { tilePreviewSvg } from "./board.js"; import { blockingHtml } from "./blocking.js"; import { translateText } from "./localization/index.js"; @@ -46,11 +47,16 @@ export function mountActivity( journal = root.querySelector(".journal-panel"), panel = root.querySelector(".chat-panel"); const wide = window.matchMedia("(min-width: 1100px)"); + const patch = createRenderer("li"); let mode = "journal", analysis = false, state, t = translator(lang), following = true, + followFrame, + unreadKey, + labelsLanguage, + rowSources = [], key = ""; const view = chat ? mountChat(panel, { @@ -365,9 +371,19 @@ export function mountActivity( state.boardLayout; if (next === key) return; key = next; - list.innerHTML = journalRows(state).map(rowHtml).join(""); + const rows = journalRows(state).map(rowHtml).filter(Boolean); + const mounted = [...list.children]; + for (let i = 0; i < Math.min(mounted.length, rows.length); i++) + if (rowSources[i] !== rows[i]) patch(mounted[i], rows[i]); + for (const row of mounted.slice(rows.length)) row.remove(); + if (rows.length > mounted.length) + list.insertAdjacentHTML("beforeend", rows.slice(mounted.length).join("")); + rowSources = rows; + cancelAnimationFrame(followFrame); if (following) - requestAnimationFrame(() => (list.scrollTop = list.scrollHeight)); + followFrame = requestAnimationFrame(() => { + if (following) list.scrollTop = list.scrollHeight; + }); } root.addEventListener("click", (e) => { const b = e.target.closest("button"); @@ -395,6 +411,9 @@ export function mountActivity( view?.refresh(); }, setUnread(n, notifications = true) { + const next = `${n}:${notifications}:${analysis}:${lang}:${colorBlind}`; + if (unreadKey === next) return; + unreadKey = next; const badge = root.querySelector(".unread"); badge.textContent = n; badge.hidden = !n; @@ -403,6 +422,8 @@ export function mountActivity( shortcut.setAttribute("aria-label", `${t("chat")}: ${n}`); }, setLanguage(l) { + if (labelsLanguage === l) return; + labelsLanguage = l; lang = l; t = translator(l); root.querySelector("[data-back] span").textContent = t("board"); @@ -412,6 +433,7 @@ export function mountActivity( refresh(); }, destroy() { + cancelAnimationFrame(followFrame); wide.removeEventListener("change", resize); view?.destroy(); root.remove(); diff --git a/viewer/dom.js b/viewer/dom.js new file mode 100644 index 0000000..c7ef200 --- /dev/null +++ b/viewer/dom.js @@ -0,0 +1,35 @@ +import morphdom from "morphdom"; + +// Compare the generated source, not just the live DOM: localization and zoom +// legitimately alter mounted nodes. Reapplying unchanged source would undo +// those changes and make their observers translate/resize the same content again. +export function createRenderer(regions, beforeUpdate) { + const source = new WeakMap(); + const remember = (node) => { + if (node.nodeType === 1 && node.matches(regions)) + source.set(node, node.outerHTML); + }; + const invalidate = (node) => { + for (let current = node; current; current = current.parentElement) { + source.delete(current); + } + }; + const patch = (node, html, childrenOnly = false) => { + invalidate(node.parentElement); + morphdom(node, html, { + childrenOnly, + onNodeAdded: remember, + onBeforeElUpdated(from, to) { + if (from.matches(regions)) { + const next = to.outerHTML; + if (source.get(from) === next) return false; + source.set(from, next); + } + beforeUpdate?.(from, to); + return !from.isEqualNode(to); + }, + }); + }; + patch.invalidate = invalidate; + return patch; +} diff --git a/viewer/map-zoom.js b/viewer/map-zoom.js index 2fef323..c4bddc9 100644 --- a/viewer/map-zoom.js +++ b/viewer/map-zoom.js @@ -7,6 +7,9 @@ export function mountMapZoom(root) { let zoom, observed, pinch, + mapEvents, + pinchEvents, + layoutKey, suppressClick = false; const events = new AbortController(); const observer = new ResizeObserver(() => update(capture())); @@ -59,12 +62,34 @@ export function mountMapZoom(root) { const scale = Math.min(f.width / box.width, f.height / box.height) * zoom; const width = box.width * scale, height = box.height * scale; - canvas.style.width = `${Math.max(f.width, width)}px`; - canvas.style.height = `${Math.max(f.height, height)}px`; - svg.style.width = `${width}px`; - svg.style.height = `${height}px`; - map.dataset.zoom = String(zoom); - if (anchor) { + let resized = false; + for (const [node, property, value] of [ + [canvas, "width", Math.max(f.width, width)], + [canvas, "height", Math.max(f.height, height)], + [svg, "width", width], + [svg, "height", height], + ]) { + // CSSOM rounds fractional pixels; comparing the serialized strings can + // otherwise rewrite the same size after every state update. + if ( + !node.style[property] || + Math.abs(parseFloat(node.style[property]) - value) > 0.01 + ) { + node.style[property] = `${value}px`; + resized = true; + } + } + const nextLayout = [ + box.x, + box.y, + box.width, + box.height, + f.width, + f.height, + zoom, + ].join(); + if (map.dataset.zoom !== String(zoom)) map.dataset.zoom = String(zoom); + if (anchor && (resized || layoutKey !== nextLayout)) { const client = anchor.client ?? center(map); const actual = anchor.world.matrixTransform(svg.getScreenCTM()); map.scrollLeft += actual.x - client.x; @@ -73,14 +98,32 @@ export function mountMapZoom(root) { map.scrollLeft = (canvas.clientWidth - f.width) / 2; map.scrollTop = (canvas.clientHeight - f.height) / 2; } - root - .querySelector("[data-zoom-out]") - ?.setAttribute("aria-disabled", String(zoom <= MIN_ZOOM)); - root - .querySelector("[data-zoom-in]") - ?.setAttribute("aria-disabled", String(zoom >= MAX_ZOOM)); + layoutKey = nextLayout; + for (const [selector, disabled] of [ + ["[data-zoom-out]", zoom <= MIN_ZOOM], + ["[data-zoom-in]", zoom >= MAX_ZOOM], + ]) { + const button = root.querySelector(selector); + if (button?.getAttribute("aria-disabled") !== String(disabled)) + button?.setAttribute("aria-disabled", String(disabled)); + } if (observed !== map) { observer.disconnect(); + mapEvents?.abort(); + endPinch(); + mapEvents = new AbortController(); + map.addEventListener("touchstart", startPinch, { + passive: true, + signal: mapEvents.signal, + }); + for (const type of ["touchend", "touchcancel"]) + map.addEventListener( + type, + (event) => { + if (event.touches.length < 2) endPinch(); + }, + { passive: true, signal: mapEvents.signal }, + ); observer.observe(map, { box: "border-box" }); observed = map; } @@ -96,26 +139,42 @@ export function mountMapZoom(root) { point: { x: (a.clientX + b.clientX) / 2, y: (a.clientY + b.clientY) / 2 }, }; }; - root.addEventListener( - "touchstart", - (event) => { - if (event.touches.length === 1) suppressClick = false; - const el = elements(); - if ( - !el || - event.touches.length !== 2 || - ![...event.touches].every((t) => el.map.contains(t.target)) - ) - return; - const { distance, point } = geometry(event.touches); - const anchor = capture(point); - if (!distance || !anchor) return; - pinch = { distance, zoom, anchor }; - suppressClick = true; - if (event.cancelable) event.preventDefault(); - }, - { passive: false, signal: events.signal }, - ); + function endPinch() { + pinch = null; + pinchEvents?.abort(); + pinchEvents = null; + } + function startPinch(event) { + if (event.touches.length === 1) suppressClick = false; + const map = event.currentTarget; + if ( + event.touches.length !== 2 || + ![...event.touches].every((t) => map.contains(t.target)) + ) + return; + const { distance, point } = geometry(event.touches); + const anchor = capture(point); + if (!distance || !anchor) return; + endPinch(); + pinch = { distance, zoom, anchor }; + suppressClick = true; + // Ordinary swipes stay native. Only a two-finger map gesture needs a + // cancellable move listener; do not make all page scrolling wait for JS. + pinchEvents = new AbortController(); + map.addEventListener("touchmove", movePinch, { + passive: false, + signal: pinchEvents.signal, + }); + } + function movePinch(event) { + if (!pinch || event.touches.length !== 2) return; + if (event.cancelable) event.preventDefault(); + const { distance, point } = geometry(event.touches); + setZoom((pinch.zoom * distance) / pinch.distance, { + ...pinch.anchor, + client: point, + }); + } root.addEventListener( "pointerdown", (event) => { @@ -123,29 +182,6 @@ export function mountMapZoom(root) { }, { signal: events.signal }, ); - root.addEventListener( - "touchmove", - (event) => { - if (!pinch || event.touches.length !== 2) return; - if (event.cancelable) event.preventDefault(); - const { distance, point } = geometry(event.touches); - setZoom((pinch.zoom * distance) / pinch.distance, { - ...pinch.anchor, - client: point, - }); - }, - { passive: false, signal: events.signal }, - ); - for (const type of ["touchend", "touchcancel"]) - root.addEventListener( - type, - (event) => { - if (!pinch || event.touches.length >= 2) return; - pinch = null; - if (event.cancelable) event.preventDefault(); - }, - { passive: false, signal: events.signal }, - ); root.addEventListener( "click", (event) => { @@ -168,6 +204,8 @@ export function mountMapZoom(root) { setZoom((zoom ?? 1) * STEP ** direction); }, destroy() { + endPinch(); + mapEvents?.abort(); events.abort(); observer.disconnect(); }, diff --git a/viewer/style.css b/viewer/style.css index 43e65b1..d7c6eac 100644 --- a/viewer/style.css +++ b/viewer/style.css @@ -1241,26 +1241,27 @@ body:has(.vanuatu) { display: none; } .vanuatu .action-dock { - flex-direction: row; - justify-content: stretch; - gap: 4px; + display: grid; + grid-template-columns: repeat(9, minmax(0, 1fr)); + gap: 2px; padding: 0; - overflow: auto; - scrollbar-width: thin; order: 0; } .vanuatu .action-dock > button { - flex: 1 0 58px; display: flex; align-items: center; flex-direction: column; justify-content: center; - min-height: 74px; - padding: 4px; + min-width: 0; + min-height: 44px; + gap: 2px; + padding: 2px 1px; box-shadow: inset 0 3px #a2b6a4; } .vanuatu .action-content { align-items: center; + width: 100%; + gap: 0; } .vanuatu .action-dock .action-symbol { flex-basis: auto; @@ -1277,19 +1278,46 @@ body:has(.vanuatu) { 0 0 0 1px #a16a28; } .vanuatu .action-label { - font-size: 9px; - white-space: nowrap; + /* Keep the translated name accessible; the pictogram identifies the + action visually without requiring a sideways swipe. */ + position: absolute; + width: 1px; + height: 1px; + overflow: hidden; + clip-path: inset(50%); } .vanuatu .action-stacks { - gap: 2px; - min-height: 14px; - max-width: 60px; - flex-wrap: wrap; + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 1px 2px; + min-height: 0; + width: 100%; + max-width: 42px; } .vanuatu .marker-stack { - min-width: 13px; + min-width: 0; height: 13px; font-size: 8px; + white-space: nowrap; + } + .vanuatu .action-stacks:not(:has(> :nth-child(2))) { + grid-template-columns: minmax(0, 20px); + justify-content: center; + } + .vanuatu .action-dock .draft-marker { + height: 13px; + line-height: 13px; + font-size: 10px; + text-align: center; + } + .vanuatu .action-dock .retrieve-only-icon { + position: absolute; + top: 3px; + right: 1px; + } + .vanuatu .action-dock .retrieve-only-icon .icon { + width: 12px; + height: 12px; } .vanuatu .sea-board { border-radius: 12px; @@ -1360,13 +1388,79 @@ body:has(.vanuatu) { } .vanuatu .players { margin-top: 10px; - gap: 8px; + gap: 6px; scroll-snap-type: x proximity; } .vanuatu .player-card { - flex: 0 0 215px; + flex: 0 0 min(190px, calc((100% - 6px) / 2)); + min-width: 0; + padding: 7px 6px 6px; scroll-snap-align: start; } + .vanuatu .player-name { + gap: 3px; + } + .vanuatu .player-card .profile { + gap: 3px; + min-height: 24px; + } + .vanuatu .player-card .player-avatar { + width: 18px; + height: 18px; + } + .vanuatu .player-name .icon-button { + width: 24px; + height: 24px; + min-width: 24px; + min-height: 24px; + padding: 2px; + } + .vanuatu .player-name .icon-button .icon { + width: 17px; + height: 17px; + } + .vanuatu .score { + font-size: 14px; + } + .vanuatu .score .icon, + .vanuatu .player-supplies .icon { + width: 17px; + height: 17px; + } + .vanuatu .player-supplies { + gap: 4px; + margin-top: 4px; + font-size: 11px; + } + .vanuatu .player-supplies .token { + gap: 1px; + } + .vanuatu .hand { + flex-wrap: wrap; + gap: 2px; + } + .vanuatu .hand .token + .token { + border-left: 1px solid #bbc8b7; + padding-left: 2px; + } + .vanuatu .hand .token + .token .icon { + display: none; + } + .vanuatu .character-owned { + margin-top: 5px; + gap: 4px; + padding-right: 4px; + } + .vanuatu .character-owned > span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + .vanuatu .character-owned img { + width: 22px; + height: 22px; + } .vanuatu .play-footer { margin: 6px auto 12px; } @@ -1748,7 +1842,9 @@ body:has(.vanuatu) { .vanuatu .water-shimmer { opacity: 0.2; } -@media (prefers-reduced-motion: no-preference) { +/* An animated SVG pattern repaints every tile, including while scrolling. + Keep the water still on touch screens and compact layouts. */ +@media (min-width: 701px) and (hover: hover) and (pointer: fine) and (prefers-reduced-motion: no-preference) { .vanuatu .archipelago .water-shimmer { animation: vanuatu-water-shimmer 14s ease-in-out infinite alternate; } diff --git a/viewer/ui.js b/viewer/ui.js index e880bff..9f074ff 100644 --- a/viewer/ui.js +++ b/viewer/ui.js @@ -1,7 +1,7 @@ import { blockingHtml, blockingText } from "./blocking.js"; import { FIRST_HELP, RETRIEVE_HELP } from "./learning.js"; import { EXTEND_WHO, EXTEND_HOW, REMAINING_TILES } from "./learning.js"; -import morphdom from "morphdom"; +import { createRenderer } from "./dom.js"; import { ACTIONS, CHARACTERS, @@ -76,7 +76,23 @@ export function mountGame(target, options = {}) { colorBlind = false, sound = false, revision, + stateKey, focusReturn; + const patch = createRenderer( + ".game-header, .action-dock, .market-info, .demand-ships, .map-scroll, .map-tools, .upcoming, .turn-tray, .player-card, .play-footer", + (from, to) => { + // These attributes belong to the layout/zoom controllers, not the state. + const attr = from.matches(".sea-board, .map-canvas, .archipelago") + ? "style" + : from.matches(".map-scroll") + ? "data-zoom" + : from.matches("[data-zoom-in], [data-zoom-out]") + ? "aria-disabled" + : null; + if (attr && from.hasAttribute(attr)) + to.setAttribute(attr, from.getAttribute(attr)); + }, + ); const icon = (name, label) => renderIcon( name, @@ -92,15 +108,18 @@ export function mountGame(target, options = {}) { const listener = { signal: events.signal }; const mapZoom = mountMapZoom(play); const trayObserver = new ResizeObserver(([entry]) => { - entry.target.parentElement?.style.setProperty( - "--tray-height", - `${entry.target.getBoundingClientRect().height}px`, - ); + const parent = entry.target.parentElement; + const height = `${entry.borderBoxSize?.[0]?.blockSize ?? entry.target.getBoundingClientRect().height}px`; + if (parent && parent.style.getPropertyValue("--tray-height") !== height) + parent.style.setProperty("--tray-height", height); }); + let observedTray; function observeTray() { - trayObserver.disconnect(); const tray = play.querySelector(".turn-tray"); - if (tray) trayObserver.observe(tray); + if (tray === observedTray) return; + trayObserver.disconnect(); + if (tray) trayObserver.observe(tray, { box: "border-box" }); + observedTray = tray; } const activity = mountActivity(root.querySelector(".activity-root"), { chat: options.chat, @@ -221,7 +240,7 @@ export function mountGame(target, options = {}) { } function playerCard(p, i) { const c = CHARACTERS[p.character]; - return `${t("connected")}
`; @@ -409,13 +458,10 @@ export function mountGame(target, options = {}) { .map((m) => m.cell) : actualTargets(); const html = `