diff --git a/package.json b/package.json index ede196c..64c6cb6 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", + "test:browser": "node test/browser.mjs && node test/journal-browser.mjs && node test/map-zoom-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/browser.mjs b/test/browser.mjs index ab15c4e..f91437c 100644 --- a/test/browser.mjs +++ b/test/browser.mjs @@ -160,15 +160,24 @@ await page.waitForFunction((before) => scrollY > before + 20, beforeSwipe); await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: false }); await cdp.detach(); await page.evaluate(() => scrollTo(0, 0)); -// The overview remains reachable above the taller character-selection tray. +// Zoom controls remain reachable above the taller character-selection tray. for (const width of [390, 1440]) { await page.setViewportSize({ width, height: 1000 }); - await page.locator("[data-overview]").click(); - assert.equal( - await page.locator("[data-overview]").getAttribute("aria-pressed"), - "true", + await page.evaluate( + () => + new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(resolve)), + ), ); - await page.locator("[data-overview]").click(); + const before = await page + .locator(".archipelago") + .evaluate((svg) => svg.getBoundingClientRect().width); + await page.locator("[data-zoom-in]").click(); + const after = await page + .locator(".archipelago") + .evaluate((svg) => svg.getBoundingClientRect().width); + assert.ok(Math.abs(after / before - 1.25) < 0.02); + await page.locator("[data-zoom-out]").click(); } // Empty action stacks do not leave labels above their icons or shift columns. const actionLayout = await page @@ -361,7 +370,7 @@ for (const width of [1440, 390]) { poor.players[0].money = 0; poor.players[0].character = null; await page.evaluate((s) => window.vanuatuDemo.setState(s), poor); - await page.locator("[data-zoom]").click(); + await page.locator("[data-zoom-in]").click(); await page.evaluate(() => { const map = document.querySelector(".map-scroll"); map.scrollLeft = 120; @@ -436,7 +445,7 @@ for (const width of [1440, 390]) { }), "Selecting and cancelling actions must not rebuild or scroll the board", ); - await page.locator("[data-zoom]").click(); + await page.locator("[data-zoom-out]").click(); await page.locator(".turn-tray .retrieve-warning").click(); await page.locator('.retrieval-alternatives [data-action="fish"]').click(); assert.equal(await page.locator("dialog[open]").count(), 0); @@ -532,61 +541,58 @@ for (const width of [1440, 390]) { const position = await page.evaluate(() => JSON.stringify(window.vanuatuDemo.state), ); - await page.locator("[data-overview]").click(); + while ( + (await page.locator("[data-zoom-out]").getAttribute("aria-disabled")) !== + "true" + ) + await page.locator("[data-zoom-out]").click(); assert.equal( - await page.locator("[data-overview]").getAttribute("aria-pressed"), + await page.locator("[data-zoom-out]").getAttribute("aria-disabled"), "true", ); assert.ok( await page.locator(".archipelago").evaluate((svg) => { const box = svg.viewBox.baseVal; - return [...svg.querySelectorAll(".cell-surface")].every((path) => { - const cell = path.getBBox(); - return ( - cell.x >= box.x && - cell.y >= box.y && - cell.x + cell.width <= box.x + box.width && - cell.y + cell.height <= box.y + box.height - ); - }); - }), - "Overview must include every empty space", - ); - assert.equal(await page.locator(".map-scroll .map-cell").count(), 16); - assert.ok( - await page.locator(".sea-board").evaluate((board) => { - const upcoming = board.querySelector(".upcoming").getBoundingClientRect(); - return [...board.querySelectorAll(".archipelago .cell-surface")].every( + return [...svg.querySelectorAll(".occupied .cell-surface")].every( (path) => { - const cell = path.getBoundingClientRect(); + const cell = path.getBBox(); return ( - cell.bottom <= upcoming.top || - cell.right <= upcoming.left || - cell.top >= upcoming.bottom || - cell.left >= upcoming.right + cell.x >= box.x && + cell.y >= box.y && + cell.x + cell.width <= box.x + box.width && + cell.y + cell.height <= box.y + box.height ); }, ); }), - "Overview spaces must stay clear of the upcoming tiles", + "Minimum zoom includes all placed tiles", ); + assert.equal(await page.locator(".map-scroll .map-cell").count(), 16); assert.equal( await page.evaluate(() => JSON.stringify(window.vanuatuDemo.state)), position, ); await page.screenshot({ - path: `.local/qa/overview-${width}.png`, + path: `.local/qa/zoom-min-${width}.png`, fullPage: true, }); - await page.locator("[data-overview]").click(); + for (let i = 0; i < 3; i++) await page.locator("[data-zoom-in]").click(); + assert.ok( + Number(await page.locator(".map-scroll").getAttribute("data-zoom")) > 1, + ); assert.equal( await page.locator(".archipelago").getAttribute("viewBox"), closeView, ); - await page.locator("[data-zoom]").click(); - await page.locator("[data-overview]").click(); - assert.equal(await page.locator(".map-scroll.zoomed").count(), 0); - await page.locator("[data-overview]").click(); + await page.screenshot({ + path: `.local/qa/zoom-mid-${width}.png`, + fullPage: true, + }); + while ( + (await page.locator("[data-zoom-out]").getAttribute("aria-disabled")) !== + "true" + ) + await page.locator("[data-zoom-out]").click(); // Upcoming tiles open with the same starting resources and capacities as the board. await page.locator("[data-upcoming]").click(); const upcoming = await page.evaluate(() => window.vanuatuDemo.state.upcoming); diff --git a/test/map-zoom-browser.mjs b/test/map-zoom-browser.mjs new file mode 100644 index 0000000..7291aad --- /dev/null +++ b/test/map-zoom-browser.mjs @@ -0,0 +1,215 @@ +import assert from "node:assert/strict"; +import { chromium } from "playwright"; +import { mkdir, 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 = []; +await mkdir(".local/qa", { recursive: true }); +try { + for (const width of [320, 390]) { + const page = await browser.newPage({ + viewport: { width, height: 844 }, + isMobile: true, + hasTouch: true, + }); + page.on("pageerror", (error) => errors.push(error.message)); + await page.goto(base + "/?new&hotseat&locale=fr"); + await page.waitForSelector(".map-scroll[data-zoom]"); + await page.locator(".sea-board").scrollIntoViewIfNeeded(); + const map = page.locator(".map-scroll"); + const zoom = () => map.evaluate((el) => Number(el.dataset.zoom)); + assert.equal(await zoom(), 1.5); + await page.screenshot({ path: `.local/qa/map-zoom-default-${width}.png` }); + const original = await page.evaluate(() => + JSON.stringify(window.vanuatuDemo.state), + ); + const cdp = await page.context().newCDPSession(page); + const midpoint = await map.evaluate((el) => { + const r = el.getBoundingClientRect(), + css = getComputedStyle(el); + return { + x: r.x + el.clientWidth / 2, + y: + r.y + + parseFloat(css.paddingTop) + + (el.clientHeight - + parseFloat(css.paddingTop) - + parseFloat(css.paddingBottom)) / + 2, + }; + }); + // Use native touch dispatch: the page must not zoom and the map point under + // the fingers must stay anchored throughout the pinch. + const world = await page.locator(".archipelago").evaluate((svg, p) => { + const q = new DOMPoint(p.x, p.y).matrixTransform( + svg.getScreenCTM().inverse(), + ); + return { x: q.x, y: q.y }; + }, midpoint); + const points = (distance) => [ + { id: 1, x: midpoint.x - distance / 2, y: midpoint.y }, + { id: 2, x: midpoint.x + distance / 2, y: midpoint.y }, + ]; + await cdp.send("Input.dispatchTouchEvent", { + type: "touchStart", + touchPoints: points(80), + }); + for (const distance of [90, 100, 110, 120, 130, 140, 150, 160]) { + await cdp.send("Input.dispatchTouchEvent", { + type: "touchMove", + touchPoints: points(distance), + }); + await page.waitForTimeout(20); + } + await cdp.send("Input.dispatchTouchEvent", { + type: "touchEnd", + touchPoints: [], + }); + assert.ok( + Math.abs((await zoom()) - 3) < 0.01, + "Pinching should double the map scale", + ); + assert.equal( + await page.evaluate(() => visualViewport.scale), + 1, + "Only the map should zoom", + ); + const screen = await page.locator(".archipelago").evaluate((svg, p) => { + const q = new DOMPoint(p.x, p.y).matrixTransform(svg.getScreenCTM()); + return { x: q.x, y: q.y }; + }, world); + assert.ok( + Math.hypot(screen.x - midpoint.x, screen.y - midpoint.y) < 3, + "The pinch midpoint stays on the same map location", + ); + assert.equal( + await page.locator("dialog[open]").count(), + 0, + "Pinching must not activate a tile", + ); + await page.screenshot({ path: `.local/qa/map-zoom-pinched-${width}.png` }); + // A regular single-finger swipe still pans the enlarged board natively. + const left = await map.evaluate((el) => el.scrollLeft); + await cdp.send("Input.dispatchTouchEvent", { + type: "touchStart", + touchPoints: [{ x: midpoint.x, y: midpoint.y }], + }); + for (const dx of [20, 40, 60, 80]) { + await cdp.send("Input.dispatchTouchEvent", { + type: "touchMove", + touchPoints: [{ x: midpoint.x - dx, y: midpoint.y }], + }); + await page.waitForTimeout(30); + } + await cdp.send("Input.dispatchTouchEvent", { + type: "touchEnd", + touchPoints: [], + }); + await page.waitForFunction( + (x) => document.querySelector(".map-scroll").scrollLeft > x + 20, + left, + ); + await page.waitForTimeout(300); + // Preference/state refreshes retain the chosen scale, center and SVG nodes. + const preserved = await page.evaluate(() => { + const map = document.querySelector(".map-scroll"); + window.savedBoard = map.querySelector(".archipelago"); + return { x: map.scrollLeft, y: map.scrollTop, zoom: map.dataset.zoom }; + }); + await page.evaluate(() => + window.vanuatuDemo.setState(window.vanuatuDemo.state), + ); + const current = await map.evaluate((el) => ({ + x: el.scrollLeft, + y: el.scrollTop, + zoom: el.dataset.zoom, + })); + assert.deepEqual(current, preserved); + assert.equal( + await page.evaluate( + () => window.savedBoard === document.querySelector(".archipelago"), + ), + true, + ); + // Zoom out reaches a complete overview; the limit button also permits a + // vertical swipe to scroll the page, without changing the game state. + while ( + (await page.locator("[data-zoom-out]").getAttribute("aria-disabled")) !== + "true" + ) + await page.locator("[data-zoom-out]").click(); + assert.equal(await zoom(), 1); + const button = await page.locator("[data-zoom-out]").boundingBox(); + const beforeY = await page.evaluate(() => scrollY); + await cdp.send("Input.dispatchTouchEvent", { + type: "touchStart", + touchPoints: [ + { x: button.x + button.width / 2, y: button.y + button.height / 2 }, + ], + }); + for (const dy of [20, 40, 60, 80, 100]) { + await cdp.send("Input.dispatchTouchEvent", { + type: "touchMove", + touchPoints: [ + { + x: button.x + button.width / 2, + y: button.y + button.height / 2 - dy, + }, + ], + }); + await page.waitForTimeout(30); + } + await cdp.send("Input.dispatchTouchEvent", { + type: "touchEnd", + touchPoints: [], + }); + await page.waitForFunction((y) => scrollY > y + 20, beforeY); + assert.equal( + await page.evaluate(() => JSON.stringify(window.vanuatuDemo.state)), + original, + ); + assert.ok( + await page.evaluate( + () => document.documentElement.scrollWidth <= innerWidth + 1, + ), + ); + await page.close(); + } + assert.deepEqual(errors, []); + console.log( + "Map zoom: progressive controls, native pinch, anchoring, panning and page scrolling passed at 320/390px.", + ); +} finally { + await browser.close(); + server.close(); +} diff --git a/viewer/art.js b/viewer/art.js index cce0c0f..ede67db 100644 --- a/viewer/art.js +++ b/viewer/art.js @@ -52,6 +52,8 @@ const paths = { '', eye: '', zoom: '', + zoomOut: + '', sound: '', }; @@ -87,6 +89,7 @@ const meanings = { check: ["Complete", "Terminé"], eye: ["Overview", "Vue d’ensemble"], zoom: ["Zoom board", "Agrandir le plateau"], + zoomOut: ["Zoom out", "Dézoomer"], sound: ["Game sounds", "Sons du jeu"], }; export const iconLabel = (name, language = "en") => meanings[name]?.[0] ?? name; diff --git a/viewer/localization/da.json b/viewer/localization/da.json index 4be3255..75a4738 100644 --- a/viewer/localization/da.json +++ b/viewer/localization/da.json @@ -867,5 +867,7 @@ "Available now": "Muligt nu", "After free exchanges": "Efter frie bytter", "Free exchanges are optional and do not use markers or end your turn.": "Frie bytter er valgfrie, bruger ingen markører og afslutter ikke din tur.", - "Retrieve this stack without acting?": "Tag denne stak tilbage uden at handle?" + "Retrieve this stack without acting?": "Tag denne stak tilbage uden at handle?", + "Zoom in": "Zoom ind", + "Zoom out": "Zoom ud" } diff --git a/viewer/localization/de.json b/viewer/localization/de.json index f89f0d9..f323b2a 100644 --- a/viewer/localization/de.json +++ b/viewer/localization/de.json @@ -867,5 +867,7 @@ "Available now": "Jetzt möglich", "After free exchanges": "Nach freien Tauschaktionen", "Free exchanges are optional and do not use markers or end your turn.": "Freie Tauschaktionen sind freiwillig, verbrauchen keine Marker und beenden deinen Zug nicht.", - "Retrieve this stack without acting?": "Diesen Stapel ohne Aktion zurücknehmen?" + "Retrieve this stack without acting?": "Diesen Stapel ohne Aktion zurücknehmen?", + "Zoom in": "Vergrößern", + "Zoom out": "Verkleinern" } diff --git a/viewer/localization/el.json b/viewer/localization/el.json index f5a672e..84cf896 100644 --- a/viewer/localization/el.json +++ b/viewer/localization/el.json @@ -867,5 +867,7 @@ "Available now": "Διαθέσιμα τώρα", "After free exchanges": "Μετά από δωρεάν ανταλλαγές", "Free exchanges are optional and do not use markers or end your turn.": "Οι δωρεάν ανταλλαγές είναι προαιρετικές, δεν καταναλώνουν δείκτες και δεν τελειώνουν τη σειρά σου.", - "Retrieve this stack without acting?": "Να πάρεις πίσω αυτή τη στοίβα χωρίς ενέργεια;" + "Retrieve this stack without acting?": "Να πάρεις πίσω αυτή τη στοίβα χωρίς ενέργεια;", + "Zoom in": "Μεγέθυνση", + "Zoom out": "Σμίκρυνση" } diff --git a/viewer/localization/en.json b/viewer/localization/en.json index ba9089c..491ca62 100644 --- a/viewer/localization/en.json +++ b/viewer/localization/en.json @@ -867,5 +867,7 @@ "Available now": "Available now", "After free exchanges": "After free exchanges", "Free exchanges are optional and do not use markers or end your turn.": "Free exchanges are optional and do not use markers or end your turn.", - "Retrieve this stack without acting?": "Retrieve this stack without acting?" + "Retrieve this stack without acting?": "Retrieve this stack without acting?", + "Zoom in": "Zoom in", + "Zoom out": "Zoom out" } diff --git a/viewer/localization/fa.json b/viewer/localization/fa.json index e09d417..e7d61fc 100644 --- a/viewer/localization/fa.json +++ b/viewer/localization/fa.json @@ -867,5 +867,7 @@ "Available now": "اکنون در دسترس", "After free exchanges": "پس از مبادله‌های آزاد", "Free exchanges are optional and do not use markers or end your turn.": "مبادله‌های آزاد اختیاری هستند، نشانگر مصرف نمی‌کنند و نوبت شما را پایان نمی‌دهند.", - "Retrieve this stack without acting?": "این دسته را بدون انجام عمل پس می‌گیرید؟" + "Retrieve this stack without acting?": "این دسته را بدون انجام عمل پس می‌گیرید؟", + "Zoom in": "بزرگ‌نمایی", + "Zoom out": "کوچک‌نمایی" } diff --git a/viewer/localization/fr.json b/viewer/localization/fr.json index 788b635..b7c74c2 100644 --- a/viewer/localization/fr.json +++ b/viewer/localization/fr.json @@ -867,5 +867,7 @@ "Available now": "Disponible maintenant", "After free exchanges": "Après des échanges libres", "Free exchanges are optional and do not use markers or end your turn.": "Les échanges libres sont facultatifs et ne consomment ni marqueurs ni votre tour.", - "Retrieve this stack without acting?": "Retirer cette pile sans agir ?" + "Retrieve this stack without acting?": "Retirer cette pile sans agir ?", + "Zoom in": "Zoomer", + "Zoom out": "Dézoomer" } diff --git a/viewer/localization/hi.json b/viewer/localization/hi.json index e8b166b..60c6fbe 100644 --- a/viewer/localization/hi.json +++ b/viewer/localization/hi.json @@ -867,5 +867,7 @@ "Available now": "अभी उपलब्ध", "After free exchanges": "मुफ़्त विनिमयों के बाद", "Free exchanges are optional and do not use markers or end your turn.": "मुफ़्त विनिमय वैकल्पिक हैं। इनमें मार्कर खर्च नहीं होते और आपकी बारी समाप्त नहीं होती।", - "Retrieve this stack without acting?": "बिना कार्रवाई किए यह ढेर वापस लें?" + "Retrieve this stack without acting?": "बिना कार्रवाई किए यह ढेर वापस लें?", + "Zoom in": "ज़ूम इन", + "Zoom out": "ज़ूम आउट" } diff --git a/viewer/localization/it.json b/viewer/localization/it.json index d114e22..0138b49 100644 --- a/viewer/localization/it.json +++ b/viewer/localization/it.json @@ -867,5 +867,7 @@ "Available now": "Disponibile ora", "After free exchanges": "Dopo scambi liberi", "Free exchanges are optional and do not use markers or end your turn.": "Gli scambi liberi sono facoltativi, non consumano segnalini e non terminano il tuo turno.", - "Retrieve this stack without acting?": "Ritiri questa pila senza agire?" + "Retrieve this stack without acting?": "Ritiri questa pila senza agire?", + "Zoom in": "Ingrandisci", + "Zoom out": "Riduci" } diff --git a/viewer/localization/ko.json b/viewer/localization/ko.json index acfe7f2..70ce7fb 100644 --- a/viewer/localization/ko.json +++ b/viewer/localization/ko.json @@ -867,5 +867,7 @@ "Available now": "지금 가능", "After free exchanges": "자유 교환 후", "Free exchanges are optional and do not use markers or end your turn.": "자유 교환은 선택 사항이며, 마커를 사용하거나 차례를 끝내지 않습니다.", - "Retrieve this stack without acting?": "행동하지 않고 이 더미를 회수할까요?" + "Retrieve this stack without acting?": "행동하지 않고 이 더미를 회수할까요?", + "Zoom in": "확대", + "Zoom out": "축소" } diff --git a/viewer/localization/nl.json b/viewer/localization/nl.json index 70feaaa..25ccddc 100644 --- a/viewer/localization/nl.json +++ b/viewer/localization/nl.json @@ -867,5 +867,7 @@ "Available now": "Nu mogelijk", "After free exchanges": "Na vrije ruilacties", "Free exchanges are optional and do not use markers or end your turn.": "Vrije ruilacties zijn optioneel, gebruiken geen markers en beëindigen je beurt niet.", - "Retrieve this stack without acting?": "Deze stapel terugnemen zonder actie?" + "Retrieve this stack without acting?": "Deze stapel terugnemen zonder actie?", + "Zoom in": "Inzoomen", + "Zoom out": "Uitzoomen" } diff --git a/viewer/localization/pl.json b/viewer/localization/pl.json index 191eea9..f6fe2eb 100644 --- a/viewer/localization/pl.json +++ b/viewer/localization/pl.json @@ -867,5 +867,7 @@ "Available now": "Dostępne teraz", "After free exchanges": "Po wymianach darmowych", "Free exchanges are optional and do not use markers or end your turn.": "Darmowe wymiany są opcjonalne, nie zużywają znaczników i nie kończą twojej tury.", - "Retrieve this stack without acting?": "Zabrać ten stos bez wykonywania akcji?" + "Retrieve this stack without acting?": "Zabrać ten stos bez wykonywania akcji?", + "Zoom in": "Przybliż", + "Zoom out": "Oddal" } diff --git a/viewer/localization/pt-BR.json b/viewer/localization/pt-BR.json index d37dcb3..c238ddd 100644 --- a/viewer/localization/pt-BR.json +++ b/viewer/localization/pt-BR.json @@ -867,5 +867,7 @@ "Available now": "Disponível agora", "After free exchanges": "Após trocas livres", "Free exchanges are optional and do not use markers or end your turn.": "As trocas livres são opcionais, não usam marcadores e não encerram seu turno.", - "Retrieve this stack without acting?": "Recolher esta pilha sem agir?" + "Retrieve this stack without acting?": "Recolher esta pilha sem agir?", + "Zoom in": "Ampliar", + "Zoom out": "Reduzir" } diff --git a/viewer/localization/ro.json b/viewer/localization/ro.json index a9f4d6b..2a435c7 100644 --- a/viewer/localization/ro.json +++ b/viewer/localization/ro.json @@ -867,5 +867,7 @@ "Available now": "Disponibil acum", "After free exchanges": "După schimburi gratuite", "Free exchanges are optional and do not use markers or end your turn.": "Schimburile gratuite sunt opționale, nu consumă marcatori și nu îți încheie tura.", - "Retrieve this stack without acting?": "Retragi această stivă fără să acționezi?" + "Retrieve this stack without acting?": "Retragi această stivă fără să acționezi?", + "Zoom in": "Mărește", + "Zoom out": "Micșorează" } diff --git a/viewer/localization/ru.json b/viewer/localization/ru.json index dc9e4c6..604ffee 100644 --- a/viewer/localization/ru.json +++ b/viewer/localization/ru.json @@ -867,5 +867,7 @@ "Available now": "Доступно сейчас", "After free exchanges": "После свободных обменов", "Free exchanges are optional and do not use markers or end your turn.": "Свободные обмены необязательны, не расходуют маркеры и не завершают ваш ход.", - "Retrieve this stack without acting?": "Забрать эту стопку без выполнения действия?" + "Retrieve this stack without acting?": "Забрать эту стопку без выполнения действия?", + "Zoom in": "Приблизить", + "Zoom out": "Отдалить" } diff --git a/viewer/localization/vi.json b/viewer/localization/vi.json index 412aec9..b79b07e 100644 --- a/viewer/localization/vi.json +++ b/viewer/localization/vi.json @@ -867,5 +867,7 @@ "Available now": "Có thể làm ngay", "After free exchanges": "Sau khi trao đổi tự do", "Free exchanges are optional and do not use markers or end your turn.": "Trao đổi tự do là tùy chọn, không dùng dấu đánh và không kết thúc lượt của bạn.", - "Retrieve this stack without acting?": "Thu lại chồng này mà không thực hiện hành động?" + "Retrieve this stack without acting?": "Thu lại chồng này mà không thực hiện hành động?", + "Zoom in": "Phóng to", + "Zoom out": "Thu nhỏ" } diff --git a/viewer/localization/zh-TW.json b/viewer/localization/zh-TW.json index d9e4fa6..a671ab1 100644 --- a/viewer/localization/zh-TW.json +++ b/viewer/localization/zh-TW.json @@ -867,5 +867,7 @@ "Available now": "目前可執行", "After free exchanges": "自由交換後", "Free exchanges are optional and do not use markers or end your turn.": "自由交換是可選的,不會消耗標記或結束你的回合。", - "Retrieve this stack without acting?": "要收回這疊標記而不執行行動嗎?" + "Retrieve this stack without acting?": "要收回這疊標記而不執行行動嗎?", + "Zoom in": "放大", + "Zoom out": "縮小" } diff --git a/viewer/map-zoom.js b/viewer/map-zoom.js new file mode 100644 index 0000000..2fef323 --- /dev/null +++ b/viewer/map-zoom.js @@ -0,0 +1,175 @@ +const MIN_ZOOM = 1; +const MAX_ZOOM = 4; +const STEP = 1.25; +const clamp = (n, min, max) => Math.max(min, Math.min(max, n)); + +export function mountMapZoom(root) { + let zoom, + observed, + pinch, + suppressClick = false; + const events = new AbortController(); + const observer = new ResizeObserver(() => update(capture())); + const elements = () => { + const map = root.querySelector(".map-scroll"); + const canvas = map?.querySelector(".map-canvas"); + const svg = canvas?.querySelector(".archipelago"); + return svg ? { map, canvas, svg } : null; + }; + function frame(map) { + const css = getComputedStyle(map), + rect = map.getBoundingClientRect(); + const left = parseFloat(css.paddingLeft), + top = parseFloat(css.paddingTop); + const width = map.clientWidth - left - parseFloat(css.paddingRight); + const height = map.clientHeight - top - parseFloat(css.paddingBottom); + return { x: rect.left + left, y: rect.top + top, width, height }; + } + function center(map) { + const f = frame(map); + const left = Math.max(0, f.x), + right = Math.min(innerWidth, f.x + f.width), + top = Math.max(0, f.y), + bottom = Math.min(innerHeight, f.y + f.height); + return { + x: right > left ? (left + right) / 2 : f.x + f.width / 2, + y: bottom > top ? (top + bottom) / 2 : f.y + f.height / 2, + }; + } + function capture(point) { + const el = elements(); + if (!el || zoom === undefined) return null; + const client = point ?? center(el.map), + matrix = el.svg.getScreenCTM(); + if (!matrix) return null; + const world = new DOMPoint(client.x, client.y).matrixTransform( + matrix.inverse(), + ); + return { world, client: point }; + } + function update(anchor) { + const el = elements(); + if (!el) return; + const { map, canvas, svg } = el, + f = frame(map), + box = svg.viewBox.baseVal; + if (f.width <= 0 || f.height <= 0) return; + const initial = zoom === undefined; + zoom ??= map.clientWidth < 700 ? 1.5 : 1; + 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) { + const client = anchor.client ?? center(map); + const actual = anchor.world.matrixTransform(svg.getScreenCTM()); + map.scrollLeft += actual.x - client.x; + map.scrollTop += actual.y - client.y; + } else if (initial) { + 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)); + if (observed !== map) { + observer.disconnect(); + observer.observe(map, { box: "border-box" }); + observed = map; + } + } + function setZoom(value, anchor = capture()) { + zoom = clamp(value, MIN_ZOOM, MAX_ZOOM); + update(anchor); + } + const geometry = (touches) => { + const [a, b] = touches; + return { + distance: Math.hypot(a.clientX - b.clientX, a.clientY - b.clientY), + 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 }, + ); + root.addEventListener( + "pointerdown", + (event) => { + if (event.pointerType !== "touch") suppressClick = false; + }, + { 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) => { + if ( + suppressClick && + event.detail !== 0 && + event.target.closest(".map-scroll") + ) { + event.preventDefault(); + event.stopImmediatePropagation(); + suppressClick = false; + } + }, + { capture: true, signal: events.signal }, + ); + return { + capture, + update, + step(direction) { + setZoom((zoom ?? 1) * STEP ** direction); + }, + destroy() { + events.abort(); + observer.disconnect(); + }, + }; +} diff --git a/viewer/style.css b/viewer/style.css index 4052ad5..43e65b1 100644 --- a/viewer/style.css +++ b/viewer/style.css @@ -311,22 +311,21 @@ width: 100%; overflow: auto; overscroll-behavior: auto; + touch-action: pan-x pan-y; scrollbar-width: thin; min-height: 490px; height: min(69vh, 740px); padding: 65px 10px 83px; } +.vanuatu .map-canvas { + display: grid; + place-items: center; +} .vanuatu .archipelago { display: block; width: 100%; height: 100%; overflow: visible; - min-height: 345px; -} -.vanuatu .map-scroll.zoomed .archipelago { - width: 1450px; - height: 900px; - min-height: 900px; } .vanuatu .cell-surface { fill: #eafcf915; @@ -475,9 +474,9 @@ .vanuatu .map-tools button { background: #fff8dfcf; } -.vanuatu .map-tools button[aria-pressed="true"] { - background: #fff8df; - box-shadow: inset 0 0 0 2px #356658; +.vanuatu .map-tools button[aria-disabled="true"] { + opacity: 0.45; + cursor: default; } .vanuatu .sea-dashboard > * { pointer-events: auto; @@ -1300,9 +1299,6 @@ body:has(.vanuatu) { min-height: 430px; padding: 80px 0 104px; } - .vanuatu .archipelago { - min-height: 245px; - } .vanuatu .sea-dashboard { top: 8px; flex-wrap: wrap; @@ -1438,14 +1434,6 @@ body:has(.vanuatu) { .vanuatu .map-cell:not(.legal) .cell-surface { stroke: #e2fff830; } -.vanuatu .archipelago.overview { - transform: translateY(-28px); -} -.vanuatu .archipelago.overview .map-cell:not(.occupied) .cell-surface { - stroke: #28697388; - stroke-width: 1; - vector-effect: non-scaling-stroke; -} @media (max-width: 700px) { .vanuatu .map-scroll { padding-bottom: 125px; @@ -1453,9 +1441,6 @@ body:has(.vanuatu) { .vanuatu .sea-board:has(.character-tray) .map-scroll { padding-bottom: 166px; } - .vanuatu .archipelago { - min-height: 200px; - } .vanuatu .character-choice { min-height: 84px; } diff --git a/viewer/ui.js b/viewer/ui.js index 82f5259..d8f3c12 100644 --- a/viewer/ui.js +++ b/viewer/ui.js @@ -18,6 +18,7 @@ import { esc, } from "./art.js"; 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 { rulesHtml } from "./rules.js"; @@ -70,8 +71,6 @@ export function mountGame(target, options = {}) { draft = [], tile = null, bonus = true, - zoom = false, - overview = false, lang = resolveLocale(options.language ?? "en"), hostedLocale = false, colorBlind = false, @@ -91,6 +90,7 @@ export function mountGame(target, options = {}) { const moveSound = createMoveSound(); const events = new AbortController(); const listener = { signal: events.signal }; + const mapZoom = mountMapZoom(play); const trayObserver = new ResizeObserver(([entry]) => { entry.target.parentElement?.style.setProperty( "--tray-height", @@ -399,9 +399,7 @@ export function mountGame(target, options = {}) { const focus = play.contains(document.activeElement) ? document.activeElement?.getAttribute("data-action") : null; - const scroll = play.querySelector(".map-scroll"); - const sx = scroll?.scrollLeft ?? 0, - sy = scroll?.scrollTop ?? 0; + const mapAnchor = mapZoom.capture(); const trayHtml = tray(); const marketHelp = `Fish price: ${s.market} vatus per fish value. Falls by 1 after each sale (minimum 1); resets to 3 next round.`; const targets = @@ -411,7 +409,7 @@ export function mountGame(target, options = {}) { .map((m) => m.cell) : actualTargets(); const html = `
${btn("🏝️ Vanuatu", "data-boardgame", "wordmark")}
Designed by Alain EpronPublished by Quined Games
${Array.from({ length: 8 }, (_, i) => `${i + 1}`).join("")}
-
${dock()}
${icon("fish", marketHelp)} = ${token("coin", s.market, marketHelp)}${token("tourist", s.tourists, `${"Tourists available this round"}: ${s.tourists}`)}${s.waterCountdown !== null ? `${token("water", s.waterCountdown, `${t("waterLeft")}: ${s.waterCountdown}`)}` : ""}
${tradeShips()}
${boardSvg(s, { player, colorBlind, overview, language: lang, selected, targets, hoverTile: s.phase === "expand" ? tile : null, t })}
${titled(overview ? "Focus on placed tiles" : "Show full board", icon("overview"), `data-overview aria-pressed="${overview}"`, "icon-button")}${titled(zoom ? t("fit") : t("zoom"), icon(zoom ? "eye" : "zoom"), "data-zoom", "icon-button")}
${s.upcoming.length && s.phase !== "expand" ? titled(t("next"), `${s.upcoming.map((id) => tilePreviewSvg(id, { t, colorBlind, language: lang, prefix: "upcoming-" + id })).join("")}${icon("zoom", t("next"))}`, "data-upcoming", "upcoming") : ""}${trayHtml}
${s.players.map(playerCard).join("")}
${token("coin", 10)} → ${token("point", 5)}${btn(t("help"), "data-help", "text-button")}
`; +
${dock()}
${icon("fish", marketHelp)} = ${token("coin", s.market, marketHelp)}${token("tourist", s.tourists, `${"Tourists available this round"}: ${s.tourists}`)}${s.waterCountdown !== null ? `${token("water", s.waterCountdown, `${t("waterLeft")}: ${s.waterCountdown}`)}` : ""}
${tradeShips()}
${boardSvg(s, { player, colorBlind, language: lang, selected, targets, hoverTile: s.phase === "expand" ? tile : null, t })}
${titled("Zoom out", icon("zoomOut"), "data-zoom-out", "icon-button")}${titled("Zoom in", icon("zoom"), "data-zoom-in", "icon-button")}
${s.upcoming.length && s.phase !== "expand" ? titled(t("next"), `${s.upcoming.map((id) => tilePreviewSvg(id, { t, colorBlind, language: lang, prefix: "upcoming-" + id })).join("")}${icon("zoom", t("next"))}`, "data-upcoming", "upcoming") : ""}${trayHtml}
${s.players.map(playerCard).join("")}
${token("coin", 10)} → ${token("point", 5)}${btn(t("help"), "data-help", "text-button")}
`; // Patch in place so cached SVG tile images and focused controls survive // preference changes and incoming state updates. morphdom(play, `
${html}
`, { @@ -419,11 +417,7 @@ export function mountGame(target, options = {}) { onBeforeElUpdated: (from, to) => !from.isEqualNode(to), }); observeTray(); - const newScroll = play.querySelector(".map-scroll"); - if (newScroll) { - newScroll.scrollLeft = sx; - newScroll.scrollTop = sy; - } + mapZoom.update(mapAnchor); if (focus) play .querySelector(`[data-action="${focus}"]`) @@ -627,18 +621,8 @@ export function mountGame(target, options = {}) { renderControls(); return; } - if ("overview" in d) { - overview = !overview; - zoom = false; - render(); - play.querySelector("[data-overview]").focus({ preventScroll: true }); - return; - } - if ("zoom" in d) { - zoom = !zoom; - if (zoom) overview = false; - render(); - play.querySelector("[data-zoom]").focus({ preventScroll: true }); + if ("zoomIn" in d || "zoomOut" in d) { + mapZoom.step("zoomIn" in d ? 1 : -1); return; } if ("characterChoice" in d) { @@ -851,6 +835,7 @@ export function mountGame(target, options = {}) { }, destroy() { events.abort(); + mapZoom.destroy(); trayObserver.disconnect(); moveSound.destroy(); offChat?.();