From 782694ce2a8224714d5c8c7e807d8c0417d4ad2c Mon Sep 17 00:00:00 2001 From: David Dada Date: Sat, 14 Nov 2026 18:25:12 +0100 Subject: [PATCH 1/2] feat: add swipe and keyboard controls across harbor outings Replace default action pads with input hints and optional native controls across Tide Run, courts and crossings. Preserve legal commands, saves, focus and canceled gestures. Refs #8. --- scripts/browser-controls.ts | 46 +++++ scripts/test-expedition-browser.ts | 42 +++-- scripts/test-expedition-harbor-browser.ts | 4 +- scripts/test-expedition-lifecycle-browser.ts | 7 +- scripts/test-expedition-qa-browser.ts | 9 +- scripts/test-expedition-touch-browser.ts | 117 +++++++++--- scripts/test-passage-browser.ts | 33 ++-- scripts/test-routing-browser.ts | 5 +- scripts/test-tide-browser.ts | 40 ++-- scripts/test-tide-run-browser.ts | 94 +++++++++- web/src/expedition/ControlHints.test.tsx | 25 +++ web/src/expedition/ControlHints.tsx | 28 +++ web/src/expedition/Game.tsx | 43 +++-- web/src/expedition/PassageGame.tsx | 43 +++-- web/src/expedition/World.tsx | 28 ++- web/src/expedition/game.css | 98 ++++++++++ web/src/expedition/input.test.ts | 28 ++- web/src/expedition/input.ts | 18 ++ web/src/expedition/passage-game.css | 9 + web/src/expedition/scene.ts | 183 +++++++++++++++---- web/src/run/TideRunGame.test.tsx | 14 ++ web/src/run/TideRunGame.tsx | 44 +++-- web/src/run/TideWorld.tsx | 27 ++- web/src/run/scene.ts | 155 ++++++++++++++-- web/src/run/tide-run.css | 38 ++++ 25 files changed, 965 insertions(+), 213 deletions(-) create mode 100644 scripts/browser-controls.ts create mode 100644 web/src/expedition/ControlHints.test.tsx create mode 100644 web/src/expedition/ControlHints.tsx diff --git a/scripts/browser-controls.ts b/scripts/browser-controls.ts new file mode 100644 index 0000000..81b6663 --- /dev/null +++ b/scripts/browser-controls.ts @@ -0,0 +1,46 @@ +import assert from "node:assert/strict"; +import type { Page } from "@playwright/test"; + +/** Drive the public play surface, leaving command validation and saving to the game. */ +export async function guide(page:Page,command:string){ + const game=page.locator('[data-testid="expedition-game"],[data-testid="passage-game"],[data-testid="tide-run"]').last(); + const key:Record={"step:north":"ArrowUp","step:south":"ArrowDown","step:west":"ArrowLeft","step:east":"ArrowRight",north:"ArrowUp",south:"ArrowDown",west:"ArrowLeft",east:"ArrowRight",wait:"Space",return:"r",home:"r"}; + if(key[command]){await game.focus();await page.keyboard.press(key[command]);return;} + if(command.startsWith("lure:")){ + await worldAction(page,"lantern"); + const lane=command.slice(5);await page.getByRole("button",{name:`Lure ${lane[0]!.toUpperCase()+lane.slice(1)}`,exact:true}).click();return; + } + if(command.startsWith("take:")||command.startsWith("reel:")){ + const item=command.split(":")[1],x=item==="lens"?0:item==="moth"?2:1; + const tiles=JSON.parse((await page.getByTestId("expedition-world").getAttribute("data-tiles"))!) as {position:{x:number;y:number};x:number;y:number}[]; + const tile=tiles.find(tile=>tile.position.x===x&&tile.position.y===4);assert(tile,`world target for ${command}`); + await page.mouse.click(tile.x,tile.y);return; + } + await worldAction(page,command); +} + +export async function worldAction(page:Page,action:string,touch=false){ + await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve())))); + const world=page.locator('[data-testid="expedition-world"],[data-testid="tide-world"]').last(); + const actions=JSON.parse((await world.getAttribute("data-actions"))??"[]") as {action:string;x:number;y:number}[]; + const target=actions.find(target=>target.action===action);assert(target,`visible world action ${action}; position=${await world.getAttribute("data-position")}; turn=${await world.getAttribute("data-turn")??await world.getAttribute("data-beat")}; available=${JSON.stringify(actions)}`); + const hit=await page.evaluate(({x,y})=>{const node=document.elementFromPoint(x,y);return{tag:node?.tagName,owner:node?.closest(".exp-command-tray,.exp-feedback,.exp-hud")?.className,html:node?.outerHTML.slice(0,180),viewport:[innerWidth,innerHeight],canvas:document.querySelector("canvas")?.getBoundingClientRect().toJSON()};},target); + assert.equal(hit.tag,"CANVAS",`world action ${action} is covered at ${target.x},${target.y}: ${JSON.stringify(hit)}`); + if(touch)await page.touchscreen.tap(target.x,target.y);else await page.mouse.click(target.x,target.y); +} + +export async function buttonControls(page:Page,open=true){ + const controls=page.locator("details.exp-button-controls"); + if(await controls.evaluate(node=>(node as HTMLDetailsElement).open)!==open)await controls.locator("summary").click(); +} + +/** Original courts remain available from the Harbor chart beside the current story/daily tide. */ +export async function departCourt(page:Page){ + const preparation=page.locator('.exp-panel[data-surface="sail"] .exp-primary'); + if(await preparation.isVisible()){await preparation.click();return;} + const depart=page.locator('[data-action="depart"]'); + if(await depart.isVisible()){await depart.click();return;} + await page.getByRole("button",{name:"Harbor chart",exact:true}).and(page.locator(":visible")).click(); + await page.locator('.exp-panel[data-surface="chart"] .harbor-routes > li').first().getByRole("button").click(); + await page.locator('.exp-panel[data-surface="sail"] .exp-primary').click(); +} diff --git a/scripts/test-expedition-browser.ts b/scripts/test-expedition-browser.ts index 1aca140..bb434c1 100644 --- a/scripts/test-expedition-browser.ts +++ b/scripts/test-expedition-browser.ts @@ -1,5 +1,6 @@ +import { guide, departCourt } from "./browser-controls"; import assert from "node:assert/strict"; -import { mkdtemp } from "node:fs/promises"; +import { mkdtemp, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join,resolve } from "node:path"; import { chromium,expect,type Page } from "@playwright/test"; @@ -26,7 +27,11 @@ async function record(page:Page,label:string){ await button.scrollIntoViewIfNeeded(); const r=await button.boundingBox();assert(r&&r.width>=43.5&&r.height>=43.5,`${label}: ${await button.textContent()} has44px target`); assert(r.x>=-.5&&r.y>=-.5&&r.x+r.width<=viewport.width+.5&&r.y+r.height<=viewport.height+.5,`${label}: active control is reachable`); - if(!await page.getByRole("dialog").count())assert(await button.evaluate(node=>{const r=node.getBoundingClientRect();return [[r.x+r.width/2,r.y+r.height/2],[r.x+8,r.y+8],[r.right-8,r.y+8],[r.x+8,r.bottom-8],[r.right-8,r.bottom-8],[r.x+r.width/2,r.y+2],[r.x+r.width/2,r.bottom-2],[r.x+2,r.y+r.height/2],[r.right-2,r.y+r.height/2]].every(([x,y])=>{const top=document.elementFromPoint(x!,y!);return top===node||!!top&&node.contains(top);});}),`${label}: ${await button.textContent()} is actually clickable above the world`); + if(!await page.getByRole("dialog").count()){ + const hits=await button.evaluate(node=>{const r=node.getBoundingClientRect();return [[r.x+r.width/2,r.y+r.height/2],[r.x+8,r.y+8],[r.right-8,r.y+8],[r.x+8,r.bottom-8],[r.right-8,r.bottom-8],[r.x+r.width/2,r.y+2],[r.x+r.width/2,r.bottom-2],[r.x+2,r.y+r.height/2],[r.right-2,r.y+r.height/2]].map(([x,y])=>{const top=document.elementFromPoint(x!,y!);return{x,y,hit:top===node||!!top&&node.contains(top),top:top?.outerHTML.slice(0,220)};});}); + if(hits.some(point=>!point.hit)){await page.screenshot({path:join(captures,`${label}-hit-failure.png`)});await writeFile(join(captures,`${label}-hit-failure.json`),JSON.stringify({label,button:await button.textContent(),bounds:r,hits},null,2));} + assert(hits.every(point=>point.hit),`${label}: ${await button.textContent()} is actually clickable above the world: ${JSON.stringify(hits.filter(point=>!point.hit))}`); + } } if(await page.getByTestId("expedition-game").getAttribute("data-mode")==="court"&&!await page.getByRole("dialog").count()){ const tiles=JSON.parse((await page.getByTestId("expedition-world").getAttribute("data-tiles"))!) as {x:number;y:number}[]; @@ -37,8 +42,7 @@ async function record(page:Page,label:string){ await page.screenshot({path:join(captures,`${label}.png`),fullPage:false}); } async function act(page:Page,command:Command){ - if(command.startsWith("lure:")){await page.getByRole("button",{name:"Lure the wave",exact:true}).click();await page.getByRole("button",{name:`Lure ${command.slice(5,6).toUpperCase()+command.slice(6)}`,exact:true}).click();} - else await page.locator(`[data-command="${command}"]`).click(); + await guide(page,command); await settled(page); } async function pointerCell(page:Page,x:number,y:number){ @@ -87,7 +91,7 @@ try{ await page.getByRole("button",{name:"Enable game audio"}).click(); await expect(page.getByRole("button",{name:"Mute game audio"})).toBeVisible(); } - await page.locator('[data-action="depart"]').click();await record(page,`${width}-court`); + await departCourt(page);await record(page,`${width}-court`); await pointerCell(page,0,0);await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-position","0,0"); await act(page,"wait");await expect(page.getByTestId("expedition-forecast")).toContainText("Left source → Left wave"); await record(page,`${width}-marked`); @@ -104,11 +108,11 @@ try{ if(!quick){ const beforeResize=await page.evaluate(key=>localStorage.getItem(key),saveKey);await page.setViewportSize({width:height,height:width});await record(page,`${width}-rotated`);assert.equal(await page.evaluate(key=>localStorage.getItem(key),saveKey),beforeResize,"resize preserves the exact accepted transcript");await page.setViewportSize({width,height}); await act(page,"return");await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-mode","harbor"); - await page.locator('[data-action="depart"]').click(); + await departCourt(page); const initial=startCourt({area:"beacon",tool:"rope",banked:[]}),route=solveCourt(initial,["lens","moth"],{dry:true})!;assert(route); const returned=await playRoute(page,route.commands,initial,`${width}`);assert.equal(returned.resolve,3);assert.deepEqual(returned.cargo,["lens","moth"]); await record(page,`${width}-returned`);await expect(page.locator('[data-action="home-next"]')).toHaveText("Bring the lens to the beacon");await page.locator('[data-action="home-next"]').click();await page.getByRole("button",{name:"Restore the beacon",exact:true}).click(); - await expect(page.locator('[data-action="home-next"]')).toHaveText("Make a little light");await page.locator('[data-action="home-next"]').click();await page.getByRole("radio",{name:"Moth",exact:true}).check();await expect(page.locator('.exp-lantern-preview .tb-lantern')).toHaveAttribute("data-motif","moth");await page.getByRole("button",{name:"Preview one lantern",exact:true}).click();await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-lantern-motif","moth");await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-lantern-finish","original");await record(page,`${width}-lantern-home`); + await page.getByRole("button",{name:"Workbench",exact:true}).click();await page.getByRole("radio",{name:"Moth",exact:true}).check();await expect(page.locator('.exp-lantern-preview .tb-lantern')).toHaveAttribute("data-motif","moth");await page.getByRole("button",{name:"Preview one lantern",exact:true}).click();await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-lantern-motif","moth");await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-lantern-finish","original");await record(page,`${width}-lantern-home`); await page.getByRole("button",{name:"Workbench",exact:true}).click();await page.getByText("Light’s origin",{exact:true}).click();await expect(page.getByText("Mochi returned with the wind-moth. 17 choices with the Rope.",{exact:true})).toBeVisible();await expect(page.getByText(/Static illustration of this device’s validated return/)).toBeVisible();await record(page,`${width}-local-origin`);await page.getByRole("button",{name:"Place at the dock",exact:true}).click(); const home=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey);assert(home.home.lit);assert.equal(home.home.lantern.motif,"moth");assert.equal(home.home.lantern.socket,"dock");assert.deepEqual(home.home.banked,["lens","moth"]); if(width===390||width===1280){ @@ -118,7 +122,7 @@ try{ await page.getByRole("button",{name:"Fit the Signal Vane",exact:true}).click(); await expect(page.getByRole("heading",{name:"One missing piece."})).toBeVisible(); await page.getByRole("button",{name:"Repair the signal post",exact:true}).click(); - await expect(page.getByRole("heading",{name:"The harbor finds its bearings."})).toBeVisible(); + await expect(page.locator(".exp-departure h1")).toHaveText(/^Today’s tide:/); await record(page,`${width}-wind-repaired`); assert((await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey)).home.signaled,"Wind goal changes the returned harbor"); } @@ -128,34 +132,34 @@ try{ if(!process.argv.includes("--quick")){ // Normal-motion input buffering and keyboard continuity use actual user events. const context=await browser.newContext({viewport:{width:1280,height:800},reducedMotion:"no-preference"}),page=await context.newPage(); - await page.goto(`${origin}/expedition/`);await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await page.locator('[data-action="depart"]').click(); - await page.locator('[data-command="step:north"]').click();await page.keyboard.press("ArrowRight");await page.keyboard.press("ArrowLeft");await settled(page); + await page.goto(`${origin}/outing/?play`);await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await departCourt(page); + await guide(page,"step:north");await page.keyboard.press("ArrowRight");await page.keyboard.press("ArrowLeft");await settled(page); await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-turn","2"); assert.deepEqual((await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey)).active.state.commands,["step:north","step:east"],"one input is buffered; the third cannot skip presentation"); await page.getByRole("button",{name:"Game menu",exact:true}).click();const paused=await page.evaluate(key=>localStorage.getItem(key),saveKey);await page.keyboard.press("ArrowLeft");assert.equal(await page.evaluate(key=>localStorage.getItem(key),saveKey),paused,"menu gates movement"); for(let n=0;n<12;n++){await page.keyboard.press("Tab");assert(await page.evaluate(()=>!!document.activeElement?.closest('[role="dialog"]')),"focus stays in the active menu");} - await page.keyboard.press("Escape");await expect(page.getByRole("dialog")).toHaveCount(0);const waveStarted=nextBeat(page,"wave");await page.keyboard.press("ArrowLeft");await waveStarted; + await page.keyboard.press("Escape");await expect(page.getByRole("dialog")).toHaveCount(0);const waveStarted=nextBeat(page,"wave");await guide(page,"step:west");await waveStarted; const waveState=await page.evaluate(key=>localStorage.getItem(key),saveKey);await page.setViewportSize({width:844,height:390});await settled(page);assert.equal(await page.evaluate(key=>localStorage.getItem(key),saveKey),waveState,"mid-wave resize preserves the accepted command and finishes its presentation");await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-turn","3");await record(page,"normal-motion-wave-resized");await page.setViewportSize({width:1280,height:800}); const accepted=await page.evaluate(key=>localStorage.getItem(key),saveKey);await page.locator("canvas").dispatchEvent("webglcontextlost");await expect(page.getByRole("button",{name:"Reload the scene",exact:true})).toBeVisible();await page.getByRole("button",{name:"Reload the scene",exact:true}).click();await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");assert.equal(await page.evaluate(key=>localStorage.getItem(key),saveKey),accepted,"drawing-surface retry preserves accepted moves without replaying effects"); await record(page,"normal-motion-context-recovery");await context.close(); const pickupContext=await browser.newContext({viewport:{width:390,height:844},reducedMotion:"no-preference"}),pickup=await pickupContext.newPage(); - await pickup.goto(`${origin}/expedition/`);await expect(pickup.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await pickup.locator('[data-action="depart"]').click(); + await pickup.goto(`${origin}/outing/?play`);await expect(pickup.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await departCourt(pickup); const rescue=solveCourt({area:"beacon",tool:"rope",banked:[]},["lens","moth"],{dry:true})!; for(const input of rescue.commands.slice(0,5))await act(pickup,input); - await pickup.locator('[data-command="step:east"]').click();await expect(pickup.getByTestId("expedition-game")).toHaveAttribute("data-busy","true");await expect(pickup.locator('[data-command="reel:lens"]')).toHaveCount(0);await expect(pickup.getByTestId("expedition-forecast")).toContainText(/Resolving|Mochi is acting/);await expect(pickup.getByRole("region",{name:"Expedition status"})).toContainText("Surge tide 6/24");await settled(pickup);await expect(pickup.locator('[data-command="reel:lens"]')).toBeVisible(); - const pickupStarted=nextBeat(pickup,"pickup");await pickup.locator('[data-command="reel:lens"]').click();await pickupStarted; + await guide(pickup,"step:east");await expect(pickup.getByTestId("expedition-game")).toHaveAttribute("data-busy","true");await expect(pickup.locator('[data-command="reel:lens"]')).toHaveCount(0);await expect(pickup.getByTestId("expedition-forecast")).toContainText(/Resolving|Mochi is acting/);await expect(pickup.getByRole("region",{name:"Expedition status"})).toContainText("Surge tide, decision 6 of 24");await settled(pickup);await expect(pickup.locator('[data-command="reel:lens"]')).toHaveCount(1); + const pickupStarted=nextBeat(pickup,"pickup");await guide(pickup,"reel:lens");await pickupStarted; const duringPickup=await pickup.evaluate(key=>localStorage.getItem(key),saveKey);await pickup.setViewportSize({width:844,height:390});await settled(pickup);assert.equal(await pickup.evaluate(key=>localStorage.getItem(key),saveKey),duringPickup,"mid-rope resize never destroys the travelling object or duplicates pickup");assert.deepEqual(JSON.parse(duringPickup!).active.state.cargo,["lens"]);await record(pickup,"normal-motion-rope-resized"); // The visibility handler is driven explicitly; this is not a physical-device backgrounding claim. await pickup.keyboard.press("ArrowRight");await pickup.keyboard.press("ArrowLeft");await pickup.evaluate(()=>{Object.defineProperty(document,"hidden",{configurable:true,get:()=>true});document.dispatchEvent(new Event("visibilitychange"));window.dispatchEvent(new Event("blur"));}); const hiddenState=await pickup.evaluate(key=>localStorage.getItem(key),saveKey);await pickup.waitForTimeout(250);assert.equal(await pickup.evaluate(key=>localStorage.getItem(key),saveKey),hiddenState,"hidden/blur clears the one buffered command"); await pickup.evaluate(()=>{Object.defineProperty(document,"hidden",{configurable:true,get:()=>false});document.dispatchEvent(new Event("visibilitychange"));window.dispatchEvent(new Event("focus"));});await settled(pickup);assert.equal(await pickup.evaluate(key=>localStorage.getItem(key),saveKey),hiddenState,"returning to the page finishes presentation without advancing another turn");await pickupContext.close(); - const shared=await browser.newContext({viewport:{width:390,height:844},reducedMotion:"reduce"}),first=await shared.newPage();await first.goto(`${origin}/expedition/`);await expect(first.getByTestId("expedition-game")).toHaveAttribute("data-lease","held");await first.locator('[data-action="depart"]').click();await act(first,"step:west"); - const second=await shared.newPage();await second.goto(`${origin}/expedition/`);await expect(second.getByTestId("expedition-game")).toHaveAttribute("data-lease","blocked");const owned=await second.evaluate(key=>localStorage.getItem(key),saveKey);await second.keyboard.press("ArrowRight");assert.equal(await second.evaluate(key=>localStorage.getItem(key),saveKey),owned,"second tab cannot overwrite the active branch");await first.close();await second.getByRole("button",{name:"Check this tab again",exact:true}).click();await expect(second.getByTestId("expedition-game")).toHaveAttribute("data-lease","held");await expect(second.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await second.keyboard.press("ArrowRight");await settled(second);assert.deepEqual((await second.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey)).active.state.commands,["step:west","step:east"],"reacquired lease loads the original tab’s latest move");await shared.close(); + const shared=await browser.newContext({viewport:{width:390,height:844},reducedMotion:"reduce"}),first=await shared.newPage();await first.goto(`${origin}/outing/?play`);await expect(first.getByTestId("expedition-game")).toHaveAttribute("data-lease","held");await departCourt(first);await act(first,"step:west"); + const second=await shared.newPage();await second.goto(`${origin}/outing/?play`);await expect(second.getByTestId("expedition-game")).toHaveAttribute("data-lease","blocked");const owned=await second.evaluate(key=>localStorage.getItem(key),saveKey);await second.getByTestId("expedition-game").focus();await second.keyboard.press("ArrowRight");assert.equal(await second.evaluate(key=>localStorage.getItem(key),saveKey),owned,"second tab cannot overwrite the active branch");await first.close();await second.getByRole("button",{name:"Check this tab again",exact:true}).click();await expect(second.getByTestId("expedition-game")).toHaveAttribute("data-lease","held");await expect(second.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await guide(second,"step:east");await settled(second);assert.deepEqual((await second.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey)).active.state.commands,["step:west","step:east"],"reacquired lease loads the original tab’s latest move");await shared.close(); const storage=await browser.newContext({viewport:{width:390,height:844},reducedMotion:"reduce"}),saving=await storage.newPage();await saving.addInitScript(key=>{const original=Storage.prototype.setItem;(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition="active";Storage.prototype.setItem=function(name,value){const mode=(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition;if(mode==="active"&&name===key||mode==="returns"&&name.startsWith("familiar.expedition.returns.v2:"))throw new DOMException("The browser rejected this write.","QuotaExceededError");original.call(this,name,value);};},saveKey); - await saving.goto(`${origin}/expedition/`);await expect(saving.getByTestId("expedition-game")).toHaveAttribute("data-lease","held");await saving.locator('[data-action="depart"]').click();assert.equal(await saving.evaluate(key=>localStorage.getItem(key),saveKey),null,"rejected first save cannot create a phantom expedition");await expect(saving.getByRole("button",{name:"Check device saving again",exact:true})).toBeVisible();await saving.evaluate(()=>{(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition=null;});await saving.getByRole("button",{name:"Check device saving again",exact:true}).click();await saving.locator('[data-action="depart"]').click();await act(saving,"step:north");await act(saving,"step:south");await saving.evaluate(()=>{(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition="returns";});await act(saving,"return");await expect(saving.getByRole("button",{name:"Retry recording this return",exact:true})).toBeVisible();assert.equal((await saving.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey)).active.state.outcome,"returned","failed return write preserves the terminal transcript");await saving.evaluate(()=>{(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition=null;});await saving.getByRole("button",{name:"Retry recording this return",exact:true}).click();await expect(saving.getByTestId("expedition-game")).toHaveAttribute("data-mode","harbor");assert.equal((await saving.evaluate(()=>JSON.parse(localStorage.getItem("familiar.expedition.returns.v2:preview")!))).length,1,"retry records one original return"); - await saving.locator('[data-action="depart"]').click();for(const input of solveCourt({area:"beacon",tool:"rope",banked:[]},["lens"],{dry:true})!.commands)await act(saving,input);await expect(saving.getByTestId("expedition-game")).toHaveAttribute("data-mode","harbor");await saving.locator('[data-action="home-next"]').click();await saving.evaluate(()=>{(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition="active";});await saving.getByRole("button",{name:"Restore the beacon",exact:true}).click();assert.equal((await saving.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey)).home.lit,false,"failed repair keeps the previously saved dark beacon");await expect(saving.getByRole("dialog")).toBeVisible();await expect(saving.getByTestId("expedition-feedback")).not.toContainText("Mochi lifts the lens into place");await saving.evaluate(()=>{(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition=null;});await saving.getByRole("button",{name:"Check device saving again",exact:true}).click();await saving.getByRole("button",{name:"Restore the beacon",exact:true}).click();assert.equal((await saving.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey)).home.lit,true,"repair success appears only after the retry is durable");await saving.locator('[data-action="home-next"]').click();await expect(saving.locator('.exp-lantern-preview .tb-lantern')).toHaveAttribute("data-motif","crest");await expect(saving.getByRole("radio",{name:"Moth",exact:true})).toBeDisabled();await saving.getByRole("button",{name:"Preview one lantern",exact:true}).click();await expect(saving.getByTestId("expedition-world")).toHaveAttribute("data-lantern-motif","crest");await expect(saving.getByTestId("expedition-world")).toHaveAttribute("data-lantern-finish","original");await record(saving,"validated-crest-preview");await storage.close(); + await saving.goto(`${origin}/outing/?play`);await expect(saving.getByTestId("expedition-game")).toHaveAttribute("data-lease","held");await departCourt(saving);assert.equal(await saving.evaluate(key=>localStorage.getItem(key),saveKey),null,"rejected first save cannot create a phantom expedition");await expect(saving.getByRole("button",{name:"Check device saving again",exact:true})).toBeVisible();await saving.evaluate(()=>{(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition=null;});await saving.getByRole("button",{name:"Check device saving again",exact:true}).click();await departCourt(saving);await act(saving,"step:north");await act(saving,"step:south");await saving.evaluate(()=>{(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition="returns";});await act(saving,"return");await expect(saving.getByRole("button",{name:"Retry recording this return",exact:true})).toBeVisible();assert.equal((await saving.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey)).active.state.outcome,"returned","failed return write preserves the terminal transcript");await saving.evaluate(()=>{(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition=null;});await saving.getByRole("button",{name:"Retry recording this return",exact:true}).click();await expect(saving.getByTestId("expedition-game")).toHaveAttribute("data-mode","harbor");assert.equal((await saving.evaluate(()=>JSON.parse(localStorage.getItem("familiar.expedition.returns.v2:preview")!))).length,1,"retry records one original return"); + await departCourt(saving);for(const input of solveCourt({area:"beacon",tool:"rope",banked:[]},["lens"],{dry:true})!.commands)await act(saving,input);await expect(saving.getByTestId("expedition-game")).toHaveAttribute("data-mode","harbor");await saving.locator('[data-action="home-next"]').click();await saving.evaluate(()=>{(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition="active";});await saving.getByRole("button",{name:"Restore the beacon",exact:true}).click();assert.equal((await saving.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey)).home.lit,false,"failed repair keeps the previously saved dark beacon");await expect(saving.getByRole("dialog")).toBeVisible();await expect(saving.getByTestId("expedition-feedback")).not.toContainText("Mochi lifts the lens into place");await saving.evaluate(()=>{(globalThis as unknown as {rejectExpedition:string|null}).rejectExpedition=null;});await saving.getByRole("button",{name:"Check device saving again",exact:true}).click();await saving.getByRole("button",{name:"Restore the beacon",exact:true}).click();assert.equal((await saving.evaluate(key=>JSON.parse(localStorage.getItem(key)!),saveKey)).home.lit,true,"repair success appears only after the retry is durable");await saving.getByRole("button",{name:"Workbench",exact:true}).click();await expect(saving.locator('.exp-lantern-preview .tb-lantern')).toHaveAttribute("data-motif","crest");await expect(saving.getByRole("radio",{name:"Moth",exact:true})).toBeDisabled();await saving.getByRole("button",{name:"Preview one lantern",exact:true}).click();await expect(saving.getByTestId("expedition-world")).toHaveAttribute("data-lantern-motif","crest");await expect(saving.getByTestId("expedition-world")).toHaveAttribute("data-lantern-finish","original");await record(saving,"validated-crest-preview");await storage.close(); // Asset failure is visible and must not silently replace or erase the stored expedition. - const failed=await browser.newContext({viewport:{width:390,height:844}}),failure=await failed.newPage();await failure.route("**/assets/expedition/runtime/stone-island.webp",route=>route.abort());await failure.goto(`${origin}/expedition/`);await expect(failure.getByRole("button",{name:"Reload the scene",exact:true})).toBeVisible();await expect(failure.getByRole("alert")).toContainText("artwork did not load");assert.equal(await failure.evaluate(key=>localStorage.getItem(key),saveKey),null,"failed artwork cannot fabricate a new save");await failed.close(); + const failed=await browser.newContext({viewport:{width:390,height:844}}),failure=await failed.newPage();await failure.route("**/assets/expedition/runtime/stone-island.webp",route=>route.abort());await failure.goto(`${origin}/outing/?play`);await expect(failure.getByRole("button",{name:"Reload the scene",exact:true})).toBeVisible();await expect(failure.getByRole("alert")).toContainText("artwork did not load");assert.equal(await failure.evaluate(key=>localStorage.getItem(key),saveKey),null,"failed artwork cannot fabricate a new save");await failed.close(); } console.log(JSON.stringify({captures,results},null,2)); }finally{await browser.close();await server.close();} diff --git a/scripts/test-expedition-harbor-browser.ts b/scripts/test-expedition-harbor-browser.ts index 6ce5838..019b1b8 100644 --- a/scripts/test-expedition-harbor-browser.ts +++ b/scripts/test-expedition-harbor-browser.ts @@ -1,3 +1,4 @@ +import { guide } from "./browser-controls"; import assert from "node:assert/strict"; import {mkdtemp} from "node:fs/promises"; import {tmpdir} from "node:os"; @@ -59,7 +60,6 @@ async function checkHarborLayout(page:Page,width:number,height:number){ for(const sign of geometry.signs)assert(!overlaps(toast,sign),`${tag}: return toast clears ${sign.name}`); } } -const MOVE_KEY:Record={north:"ArrowUp",south:"ArrowDown",west:"ArrowLeft",east:"ArrowRight",wait:"Space",home:"r"}; /** A device harbor's daily is the tide run: each layout sails today's last move for real, or seeds the day's state, then checks the harbor card. */ async function checkReturnLayouts(browser:import("@playwright/test").Browser,origin:string){ const day=20771; @@ -89,7 +89,7 @@ async function checkReturnLayouts(browser:import("@playwright/test").Browser,ori await page.goto(origin+"/__harbor-game"); if(scenario.moves){ const run=page.getByTestId("tide-run");await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready","true",{timeout:20000}); - await expect(run).toHaveAttribute("data-busy","false");await page.keyboard.press(MOVE_KEY[scenario.moves.at(-1)!]); + await expect(run).toHaveAttribute("data-busy","false");await guide(page,scenario.moves.at(-1)!); // A tide that ends on its own goes straight home; a finish card waits for a press. const finish=page.getByTestId("tide-finish"),homeSheet=page.locator('.exp-panel[data-surface="home"]'); await expect(finish.or(homeSheet)).toBeVisible({timeout:20000});if(await finish.isVisible())await finish.click(); diff --git a/scripts/test-expedition-lifecycle-browser.ts b/scripts/test-expedition-lifecycle-browser.ts index fac3f42..1f0590e 100644 --- a/scripts/test-expedition-lifecycle-browser.ts +++ b/scripts/test-expedition-lifecycle-browser.ts @@ -1,3 +1,4 @@ +import { guide, departCourt } from "./browser-controls"; import assert from 'node:assert/strict'; import {mkdir,mkdtemp,writeFile} from 'node:fs/promises'; import {join,resolve} from 'node:path'; @@ -23,9 +24,9 @@ async function homeGeometry(page:Page){return page.locator('button:visible,a:vis async function homeBounds(page:Page){const controls=await homeGeometry(page),viewport=page.viewportSize()!;for(const control of controls){assert(control.rect.x>=0&&control.rect.y>=0&&control.rect.right<=viewport.width&&control.rect.bottom<=viewport.height&&control.rect.width>=44&&control.rect.height>=44,`Home control fits44px: ${control.label}`);assert(control.hits.every(p=>p.hit),`Home control not obscured at any of9points: ${control.label}`)}return controls} try{ if(!keyboardOnly&&!landscapeOnly){ - {const{page,context}=await open('/__audit');await page.locator(".exp-phone-dock").getByRole("button",{name:"Harbor chart",exact:true}).click();await page.locator('.exp-panel[data-surface="chart"] .harbor-routes > li').first().getByRole("button").click();await page.locator('.exp-panel[data-surface="sail"] .exp-primary').click();await page.evaluate(()=>{(window as unknown as AuditWindow).__audit.hold=true;document.querySelector('[data-command="step:west"]')!.click();window.dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowUp'}))});await expect.poll(()=>page.evaluate(()=>(window as unknown as AuditWindow).__audit.held.length)).toBe(1);const before=await raw(page);await page.screenshot({path:out+'/F10-'+phase+'-queued-before-unmount.png'});await page.evaluate(()=>(window as unknown as AuditWindow).__audit.close());await expect(page.getByTestId('unmounted')).toBeVisible();await expect.poll(()=>page.evaluate(async()=>(await navigator.locks.query()).held!.length)).toBe(0);await page.evaluate(()=>{(window as unknown as AuditWindow).__audit.held.shift()!(performance.now())});await page.waitForTimeout(100);const after=await raw(page);results.push({case:'F10 queued RAF after Game unmount',before:before.active.state,after:after.active.state});await page.screenshot({path:out+'/F10-'+phase+'-after-unmount.png'});await context.close()} + {const{page,context}=await open('/__audit');await page.locator(".exp-phone-dock").getByRole("button",{name:"Harbor chart",exact:true}).click();await page.locator('.exp-panel[data-surface="chart"] .harbor-routes > li').first().getByRole("button").click();await page.locator('.exp-panel[data-surface="sail"] .exp-primary').click();await page.emulateMedia({reducedMotion:"no-preference"});await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve()))));await page.evaluate(()=>{(window as unknown as AuditWindow).__audit.hold=true;});await guide(page,"step:west");await guide(page,"step:north");await expect.poll(()=>page.evaluate(()=>(window as unknown as AuditWindow).__audit.held.length)).toBe(1);const before=await raw(page);await page.screenshot({path:out+'/F10-'+phase+'-queued-before-unmount.png'});await page.evaluate(()=>(window as unknown as AuditWindow).__audit.close());await expect(page.getByTestId('unmounted')).toBeVisible();await expect.poll(()=>page.evaluate(async()=>(await navigator.locks.query()).held!.length)).toBe(0);await page.evaluate(()=>{(window as unknown as AuditWindow).__audit.held.shift()!(performance.now())});await page.waitForTimeout(100);const after=await raw(page);results.push({case:'F10 queued RAF after Game unmount',before:before.active.state,after:after.active.state});await page.screenshot({path:out+'/F10-'+phase+'-after-unmount.png'});await context.close()} {const{page,context}=await open();const menu=page.getByRole('button',{name:'Game menu',exact:true});await menu.focus();await page.keyboard.press('Enter');await page.getByRole('button',{name:'How to guide Mochi',exact:true}).focus();await page.keyboard.press('Enter');await page.getByRole('button',{name:'Back to Mochi',exact:true}).focus();await page.keyboard.press('Enter');const active=await page.evaluate(()=>({tag:document.activeElement?.tagName,label:document.activeElement?.getAttribute('aria-label'),text:document.activeElement?.textContent?.slice(0,50)}));results.push({case:'F11 nested menu restores original focused control',active});await page.screenshot({path:out+'/F11-'+phase+'-nested-focus.png'});await context.close()} - for(const width of [390,320]){const{page,context}=await open('/outing/?play',{width,height:480});await page.screenshot({path:out+`/F09-${phase}-${width}x480-home.png`});const homeControls=await homeBounds(page);await page.locator('[data-action="depart"]').click();await expect.poll(()=>page.getByTestId('expedition-world').getAttribute('data-tiles')).not.toBe('[]');const geometry=await page.evaluate(()=>({tiles:JSON.parse(document.querySelector('[data-testid="expedition-world"]')!.getAttribute('data-tiles')!),controls:[...document.querySelectorAll('.exp-command-tray button')].map(n=>({label:n.getAttribute('aria-label')??n.textContent,rect:n.getBoundingClientRect().toJSON(),hit:n.contains(document.elementFromPoint(n.getBoundingClientRect().x+n.getBoundingClientRect().width/2,n.getBoundingClientRect().y+n.getBoundingClientRect().height/2))})),w:innerWidth,h:innerHeight,scroll:[scrollX,scrollY,document.documentElement.scrollWidth,document.documentElement.scrollHeight]}));results.push({case:'F09 short portrait',homeControls,geometry});await page.screenshot({path:out+`/F09-${phase}-${width}x480.png`});if(phase==='after'){for(const tile of geometry.tiles)assert(tile.x-tile.width/2>=0&&tile.x+tile.width/2<=width&&tile.y-tile.height/2>=0&&tile.y+tile.height/2<=480,'Every actual court hit area fits short portrait');for(const control of geometry.controls){assert(control.rect.x>=0&&control.rect.right<=width&&control.rect.bottom<=480&&control.rect.width>=44&&control.rect.height>=44,`Control fits with44px target: ${control.label}`);assert(control.hit,`No overlay covers ${control.label}`)}assert.deepEqual(geometry.scroll,[0,0,width,480])}await context.close()} + for(const width of [390,320]){const{page,context}=await open('/outing/?play',{width,height:480});await page.screenshot({path:out+`/F09-${phase}-${width}x480-home.png`});const homeControls=await homeBounds(page);await departCourt(page);await expect.poll(()=>page.getByTestId('expedition-world').getAttribute('data-tiles')).not.toBe('[]');const geometry=await page.evaluate(()=>({tiles:JSON.parse(document.querySelector('[data-testid="expedition-world"]')!.getAttribute('data-tiles')!),controls:[...document.querySelectorAll('.exp-command-tray button,.exp-command-tray summary')].filter(n=>{const closed=n.closest("details:not([open])");return n.getBoundingClientRect().width>0&&(!closed||closed.firstElementChild===n)}).map(n=>({label:n.getAttribute('aria-label')??n.textContent,rect:n.getBoundingClientRect().toJSON(),hit:n.contains(document.elementFromPoint(n.getBoundingClientRect().x+n.getBoundingClientRect().width/2,n.getBoundingClientRect().y+n.getBoundingClientRect().height/2))})),w:innerWidth,h:innerHeight,scroll:[scrollX,scrollY,document.documentElement.scrollWidth,document.documentElement.scrollHeight]}));results.push({case:'F09 short portrait',homeControls,geometry});await page.screenshot({path:out+`/F09-${phase}-${width}x480.png`});if(phase==='after'){for(const tile of geometry.tiles)assert(tile.x-tile.width/2>=0&&tile.x+tile.width/2<=width&&tile.y-tile.height/2>=0&&tile.y+tile.height/2<=480,'Every actual court hit area fits short portrait');for(const control of geometry.controls){assert(control.rect.x>=0&&control.rect.right<=width&&control.rect.bottom<=480&&control.rect.width>=44&&control.rect.height>=44,`Control fits with44px target: ${control.label}`);assert(control.hit,`No overlay covers ${control.label}`)}assert.deepEqual(geometry.scroll,[0,0,width,480])}await context.close()} for(const width of [320,390]){const{page,context}=await open('/outing/?play',{width,height:480}); const route=courtFixtures.cases.find(row=>row.id==='beacon-rope-objective')!; await page.evaluate(async({origin,route})=>{const{replayCourt}=await import(origin+'/src/expedition/engine.ts'),{ReturnRecords}=await import(origin+'/src/expedition/return-record.ts');await new ReturnRecords(localStorage).capture(replayCourt(route.start,route.commands),{authority:'local-preview',banked:[],lit:false,signaled:false})},{origin,route}); @@ -33,7 +34,7 @@ try{ await context.close()} {const{page,context}=await open(),errors:string[]=[];page.on('pageerror',e=>errors.push(e.message));const base={version:2,home:{banked:[],lit:false,signaled:false,lantern:null},active:null,last:null,sentinel:'MALFORMED_SAVE_ORIGINAL'}; const variants:Record[]=[{...base,active:false},{...base,last:false},{...base,active:undefined},{...base,home:{...base.home,lantern:false}},{...base,home:{...base.home,lantern:undefined}}]; - for(const[index,value]of variants.entries()){const original=JSON.stringify(value,null,2)+'\n';await page.evaluate(({key,text})=>localStorage.setItem(key,text),{key,text:original});await page.reload();await expect(page.getByTestId('expedition-world')).toHaveAttribute('data-ready','true');const problem=await page.locator('.exp-save-problem').count(),after=await page.evaluate(key=>localStorage.getItem(key),key);results.push({case:'F12 malformed nullable fields',index,problem,errors:[...errors],before:original,after});if(index===0)await page.screenshot({path:out+'/F12-'+phase+'-malformed-save.png'});if(phase==='after'){assert.equal(problem,1,'Invalid nullable fields show the existing corrupt-save recovery view');assert.deepEqual(errors,[]);assert.equal(after,original,'Original malformed bytes remain untouched');await expect(page.locator('[data-action="depart"]')).toBeDisabled();}} + for(const[index,value]of variants.entries()){const original=JSON.stringify(value,null,2)+'\n';await page.evaluate(({key,text})=>localStorage.setItem(key,text),{key,text:original});await page.reload();await expect(page.getByTestId('expedition-world')).toHaveAttribute('data-ready','true');const problem=await page.locator('.exp-save-problem').count(),after=await page.evaluate(key=>localStorage.getItem(key),key);results.push({case:'F12 malformed nullable fields',index,problem,errors:[...errors],before:original,after});if(index===0)await page.screenshot({path:out+'/F12-'+phase+'-malformed-save.png'});if(phase==='after'){assert.equal(problem,1,'Invalid nullable fields show the existing corrupt-save recovery view');assert.deepEqual(errors,[]);assert.equal(after,original,'Original malformed bytes remain untouched');await expect(page.locator('[data-action="story"]')).toBeDisabled();}} await context.close()} } if(!landscapeOnly)for(const prefix of [7,5]){const{page,context}=await open('/outing/?play'),route=courtFixtures.cases.find(row=>row.id==='wind-rope-objective')!; diff --git a/scripts/test-expedition-qa-browser.ts b/scripts/test-expedition-qa-browser.ts index 81dc940..9efb6a2 100644 --- a/scripts/test-expedition-qa-browser.ts +++ b/scripts/test-expedition-qa-browser.ts @@ -1,3 +1,4 @@ +import { guide, worldAction, departCourt } from "./browser-controls"; import assert from "node:assert/strict"; import { mkdir,mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -38,7 +39,7 @@ try{ page.on("pageerror",e=>errors.push(e.message));await context.route("**/*",route=>{if(!["GET","HEAD","OPTIONS"].includes(route.request().method())){mutations.push(new URL(route.request().url()).pathname);return route.abort();}return route.continue();}); try{ await page.goto(origin+"/outing/?play");await ready(page);const geometry=await bounds(page,`${width}x${height}-home`);await capture(page,`${width}x${height}-home`); - const action=page.locator('[data-action="depart"]');if(touch)await action.tap();else await action.click();await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-mode","court"); + await departCourt(page);await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-mode","court"); await bounds(page,`${width}x${height}-court`);await capture(page,`${width}x${height}-court`); const tiles=JSON.parse((await page.getByTestId("expedition-world").getAttribute("data-tiles"))!) as {position:{x:number;y:number};x:number;y:number}[],target=tiles.find(t=>t.position.x===0&&t.position.y===0)!; assert(target);if(touch)await page.touchscreen.tap(target.x,target.y);else await page.mouse.click(target.x,target.y); @@ -65,7 +66,7 @@ try{ await sdkContext.close(); const loadingContext=await browser.newContext({viewport:{width:390,height:844},reducedMotion:"reduce"}),loading=await loadingContext.newPage();let release!:()=>void;const held=new Promise(r=>{release=r;}); await loading.route("**/assets/expedition/runtime/lens.webp",async route=>{await held;await route.continue();});await loading.goto(origin+"/outing/?play"); - await expect(loading.getByRole("heading",{name:"Unpacking the harbor."})).toBeVisible();assert.equal(await loading.locator('[data-action="depart"]').count(),0,"No departure before the scene is ready");assert.equal(await loading.evaluate(k=>localStorage.getItem(k),key),null);await capture(loading,"after-art-loading-gate");release();await ready(loading);await expect(loading.locator('[data-action="depart"]')).toBeEnabled();await loadingContext.close(); + await expect(loading.getByRole("heading",{name:"Unpacking the harbor."})).toBeVisible();assert.equal(await loading.locator('[data-action="depart"]').count(),0,"No departure before the scene is ready");assert.equal(await loading.evaluate(k=>localStorage.getItem(k),key),null);await capture(loading,"after-art-loading-gate");release();await ready(loading);await expect(loading.locator('[data-action="story"]')).toBeEnabled();await loadingContext.close(); } if(engine===chromium){ const context=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true,reducedMotion:"reduce"}),page=await context.newPage(),cdp=await context.newCDPSession(page); @@ -74,8 +75,8 @@ try{ const start=Date.now(),navigation=page.goto(origin+"/outing/?play",{waitUntil:"domcontentloaded",timeout:120000}); await page.waitForTimeout(2000);await capture(page,`${baseline?"before":"after"}-3g-2s`);const early=await page.locator("body").innerText();if(!baseline)assert(early.includes("Familiar")||early.includes("familiar"),"A cold slow3G load has visible content before module download"); await navigation;const domMs=Date.now()-start;await ready(page);const readyMs=Date.now()-start;await capture(page,`${baseline?"before":"after"}-3g-ready`); - await page.locator('[data-action="depart"]').tap();await page.getByRole("button",{name:"Move north",exact:true}).tap();await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-busy","false"); - const beforeOffline=await page.evaluate(k=>localStorage.getItem(k),key);await context.setOffline(true);await page.getByRole("button",{name:"Wait for the tide",exact:true}).tap();await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-busy","false");assert.notEqual(await page.evaluate(k=>localStorage.getItem(k),key),beforeOffline,"accepted local decisions save while offline"); + await departCourt(page);await guide(page,"step:north");await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-busy","false"); + const beforeOffline=await page.evaluate(k=>localStorage.getItem(k),key);await context.setOffline(true);await worldAction(page,"wait",true);await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-busy","false");assert.notEqual(await page.evaluate(k=>localStorage.getItem(k),key),beforeOffline,"accepted local decisions save while offline"); const resources=await page.evaluate(()=>performance.getEntriesByType("resource").map(e=>{const r=e as PerformanceResourceTiming;return {name:new URL(r.name).pathname,bytes:r.encodedBodySize,duration:r.duration};}).sort((a,b)=>b.bytes-a.bytes).slice(0,12)); results.push({profile:"cold slow3G, gzip, touch, CPU4",resources,latencyMs:400,downloadBytesPerSecond:50000,uploadBytesPerSecond:50000,cache:false,domMs,readyMs,early,offlineLocalDecision:"pass"});await context.close(); } diff --git a/scripts/test-expedition-touch-browser.ts b/scripts/test-expedition-touch-browser.ts index a3e2614..7b9a675 100644 --- a/scripts/test-expedition-touch-browser.ts +++ b/scripts/test-expedition-touch-browser.ts @@ -1,9 +1,11 @@ +import { guide, worldAction, buttonControls, departCourt } from "./browser-controls"; import assert from "node:assert/strict"; import {mkdtemp,mkdir,writeFile} from "node:fs/promises"; import {join,resolve} from "node:path"; import {tmpdir} from "node:os"; import {chromium,expect,type Page,type CDPSession} from "@playwright/test"; import {createServer} from "vite"; +import {solveCourt} from "./court-solver"; import {cardForDay} from "../web/src/tide/cards"; import {replayRun,solve} from "../web/src/tide/asks"; @@ -21,10 +23,10 @@ const tideFixtureRun=replayRun(tideFixtureCard.tool,tideFixtureRoute.slice(0,-1) assert(tideFixtureRun&&tideFixtureRun.state.outcome==="active"&&tideFixtureRun.state.resolve<3,"the active tide fixture has taken its one splash"); async function state(page:Page){return page.evaluate(key=>{const raw=localStorage.getItem(key);return raw?JSON.parse(raw).active?.state??null:null;},key);} async function touch(cdp:CDPSession,type:"touchStart"|"touchMove"|"touchEnd"|"touchCancel",point?:{x:number;y:number}){await cdp.send("Input.dispatchTouchEvent",{type,touchPoints:point?[{id:1,x:point.x,y:point.y,radiusX:2,radiusY:2,force:1}]:[]});} -async function open(tide=false){const context=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true,reducedMotion:"reduce"}),page=await context.newPage();await page.route("**/*",route=>route.request().url().startsWith(origin)&&!new URL(route.request().url()).pathname.startsWith("/api/")?route.continue():route.abort());if(tide)await page.addInitScript(({key,day,state})=>{ +async function open(tide=false,freshTide=false){const context=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true,reducedMotion:"reduce"}),page=await context.newPage();await page.route("**/*",route=>route.request().url().startsWith(origin)&&!new URL(route.request().url()).pathname.startsWith("/api/")?route.continue():route.abort());if(tide)await page.addInitScript(({key,day,state})=>{ localStorage.setItem(key,JSON.stringify({version:2,home:{banked:["lens"],lit:true,signaled:false,lantern:null},last:null,active:{context:{authority:"local-preview",banked:[],lit:true,signaled:false},state,season:true}})); localStorage.setItem("familiar.tide.pending.v1:preview",JSON.stringify({day,late:false})); - },{key,day:tideFixtureDay,state:tideFixtureRun!.state});await page.goto(origin+"/outing/?play");await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-lease","held");return {context,page,cdp:await context.newCDPSession(page)};} + },{key,day:tideFixtureDay,state:freshTide?replayRun(tideFixtureCard.tool,[])!.state:tideFixtureRun!.state});await page.goto(origin+"/outing/?play");await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-lease","held");return {context,page,cdp:await context.newCDPSession(page)};} /** A device harbor's daily is the tide run; the classic court is still a route on the Harbor chart. */ async function court(page:Page){await page.locator(".exp-phone-dock").getByRole("button",{name:"Harbor chart",exact:true}).tap();await page.locator('.exp-panel[data-surface="chart"] .harbor-routes > li').first().getByRole("button").tap();await page.locator('.exp-panel[data-surface="sail"] .exp-primary').tap();await expect.poll(async()=>JSON.parse((await page.getByTestId("expedition-world").getAttribute("data-tiles"))!).length).toBe(15);await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve()))));} async function cell(page:Page,x:number,y:number){const tiles=JSON.parse((await page.getByTestId("expedition-world").getAttribute("data-tiles"))!) as {position:{x:number;y:number};x:number;y:number}[];return tiles.find(tile=>tile.position.x===x&&tile.position.y===y)!;} @@ -47,21 +49,29 @@ try{ const tray=page.locator(".exp-command-tray"); assert.equal(await tray.evaluate(node=>getComputedStyle(node).backgroundColor),"rgb(251, 243, 226)","court tray has an opaque card surface"); assert.equal(await tray.evaluate(node=>getComputedStyle(node).backdropFilter),"none","court tray does not blur the board"); - await expect(page.locator('button[data-command="return"]')).toHaveClass(/exp-secondary/); - const trayBounds=await tray.boundingBox(),returnBounds=await page.locator('button[data-command="return"]').boundingBox(); - const directionsBefore=await page.locator(".exp-directions").boundingBox(); - const dockBottom=await page.getByTestId("expedition-world").evaluate(node=>{ - const ys=(JSON.parse(node.getAttribute("data-tiles")!) as {y:number}[]).map(tile=>tile.y),bottom=Math.max(...ys),step=(bottom-Math.min(...ys))/4; - return bottom+Math.max(33,Math.min(step*.65,72))/2; - }); - assert(trayBounds&&returnBounds&&directionsBefore&&trayBounds.y>=dockBottom&&returnBounds.y>=trayBounds.y&&returnBounds.y+returnBounds.height<=844,"phone Return and moves remain visible below the complete dock platform"); - await page.locator(".exp-tray-scroll").evaluate(node=>node.scrollTo({top:node.scrollHeight,behavior:"instant"})); - assert.deepEqual(await page.locator(".exp-directions").boundingBox(),directionsBefore,"reading long feedback never scrolls the movement row away"); + await expect(page.locator(".exp-control-hints")).toContainText("Swipe to move"); + await expect(page.locator(".exp-directions button:visible")).toHaveCount(0); + const summary=page.locator(".exp-button-controls summary"); + const summaryBounds=await summary.boundingBox();assert(summaryBounds&&summaryBounds.height>=44,"optional controls have a reachable 44px summary"); + const beforeControls=await state(page);await summary.focus();await page.keyboard.press("Space"); + await expect(page.locator(".exp-button-controls")).toHaveAttribute("open",""); + for(const button of await page.locator(".exp-directions button:visible").all()){ + const bounds=await button.boundingBox();assert(bounds&&bounds.width>=44&&bounds.height>=44,"optional direction controls retain 44px targets"); + } + assert.equal((await state(page)).turn,beforeControls.turn,"Space on summary only opens controls"); + await page.getByRole("button",{name:"Wait for the tide",exact:true}).tap(); + await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-busy","false"); + assert.deepEqual((await state(page)).commands,["wait"],"native optional Wait accepts exactly one command"); + await buttonControls(page,false); + await worldAction(page,"wait",true);await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-busy","false"); + assert.deepEqual((await state(page)).commands,["wait","wait"],"Mochi tap and optional Wait are equivalent"); + await expect(page.locator(".exp-directions button:visible")).toHaveCount(0); + const beforeInspect=(await state(page)).turn; const inspect=page.getByRole("button",{name:"Inspect",exact:true});await inspect.tap(); const shade=page.locator(".exp-panel-shade"); assert.equal(await shade.evaluate(node=>getComputedStyle(node).backdropFilter),"none","Inspect leaves the court sharp"); assert.equal(await page.locator(".exp-world").evaluate(node=>getComputedStyle(node).filter),"none","Inspect does not blur the world"); - await page.keyboard.press("Escape");await expect(inspect).toBeFocused();assert.equal((await state(page)).turn,0,"Inspect and dismissal spend no decisions"); + await page.keyboard.press("Escape");await expect(inspect).toBeFocused();assert.equal((await state(page)).turn,beforeInspect,"Inspect and dismissal spend no decisions"); await context.close(); } { @@ -71,15 +81,15 @@ try{ assert(await emptyFeedback.evaluate(node=>{const box=node.getBoundingClientRect();return box.width===0&&box.height===0;}),"empty feedback stays in the DOM without painting a box"); await expect(page.locator(".exp-mochi-portrait")).toHaveAttribute("src","/assets/ui/mochi-portrait-splashed.webp"); await expect(page.getByTestId("expedition-objective")).toHaveCount(1); - const asksBefore=await asks.boundingBox(),movesBefore=await page.locator(".exp-directions").boundingBox(); + const asksBefore=await asks.boundingBox(),movesBefore=await page.locator(".exp-control-hints").boundingBox(); const dockBottom=await page.getByTestId("expedition-world").evaluate(node=>Math.max(...(JSON.parse(node.getAttribute("data-tiles")!) as {y:number;height:number}[]).map(tile=>tile.y+tile.height/2))); const trayBounds=await tray.boundingBox();assert(trayBounds&&trayBounds.y>=dockBottom,"phone tide tray clears the dock platform"); await tray.locator(".exp-tray-scroll").evaluate(node=>node.scrollTo({top:node.scrollHeight,behavior:"instant"})); assert.deepEqual(await asks.boundingBox(),asksBefore,"asks stay pinned above the scrolling reading area"); - assert.deepEqual(await page.locator(".exp-directions").boundingBox(),movesBefore,"tide reading never scrolls the movement row away"); + assert.deepEqual(await page.locator(".exp-control-hints").boundingBox(),movesBefore,"tide reading never scrolls the movement row away"); for(const size of [{width:390,height:844},{width:412,height:860},{width:844,height:390}]){ await page.setViewportSize(size);await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve())))); - for(const button of await tray.locator(".exp-tray-actions button:visible").all()){ + for(const button of await tray.locator(".exp-control-hints summary").all()){ const bounds=await button.boundingBox();assert(bounds&&bounds.x>=0&&bounds.y>=0&&bounds.x+bounds.width<=size.width+.5&&bounds.y+bounds.height<=size.height+.5,`${size.width}x${size.height}: movement and context actions stay visible without scrolling`); } if(size.height<=500){ @@ -88,13 +98,13 @@ try{ assert(hud&&tiles.every(tile=>hud.x+hud.width<=tile.x-tile.width/2||hud.x>=tile.x+tile.width/2||hud.y+hud.height<=tile.y-tile.height/2||hud.y>=tile.y+tile.height/2),"landscape status card stays clear of the court platforms"); } } - await page.getByRole("button",{name:"Wait for the tide",exact:true}).click(); + await worldAction(page,"wait",true); await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-busy","false"); await expect(asks.getByRole("button",{name:"Start this tide over",exact:true})).toBeVisible(); for(const size of [{width:390,height:844},{width:412,height:860},{width:844,height:390}]){ await page.setViewportSize(size);await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve())))); const bounds=await tray.boundingBox();assert(bounds); - for(const control of await tray.locator(".tide-asks>li,.tide-restart,.exp-tray-actions button:visible").all()){ + for(const control of await tray.locator(".tide-asks>li,.tide-restart,.exp-control-hints summary").all()){ const box=await control.boundingBox();assert(box&&box.x>=bounds.x&&box.x+box.width<=bounds.x+bounds.width+.5&&box.y>=bounds.y&&box.y+box.height<=bounds.y+bounds.height+.5,`${size.width}x${size.height}: slipped asks, restart and actions fit inside the tray`); } } @@ -120,15 +130,80 @@ try{ const {context,page,cdp}=await open();await court(page);const west=await cell(page,0,0);await touch(cdp,"touchStart",west);await page.waitForTimeout(500);await touch(cdp,"touchEnd");await page.waitForTimeout(120);const held=await state(page);assert.equal(held.turn,0,"holding a destination inspects without spending a decision");await expect(page.getByTestId("expedition-feedback")).toContainText("stone foothold");await page.touchscreen.tap(west.x,west.y);await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-turn","1");results.push({case:"hold inspects; genuine tap walks",held,after:await state(page)});await context.close(); } for(const input of ["mouse","keyboard"] as const){ - const {context,page}=await open();await court(page);const west=await cell(page,0,0);if(input==="mouse")await page.mouse.click(west.x,west.y);else await page.keyboard.press("ArrowLeft");await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-turn","1");assert.deepEqual((await state(page)).commands,["step:west"],`${input} remains equivalent to one genuine touch tap`);results.push({case:`${input} equivalence`,after:await state(page)});await context.close(); + const {context,page}=await open();await court(page);const west=await cell(page,0,0);if(input==="mouse")await page.mouse.click(west.x,west.y);else await guide(page,"step:west");await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-turn","1");assert.deepEqual((await state(page)).commands,["step:west"],`${input} remains equivalent to one genuine touch tap`);results.push({case:`${input} equivalence`,after:await state(page)});await context.close(); } { const {context,page}=await open();await court(page);const west=await cell(page,0,0);await page.mouse.click(west.x,west.y,{button:"right"});assert.equal((await state(page)).turn,0);await expect(page.getByTestId("expedition-feedback")).toContainText("stone foothold");results.push({case:"right-click inspects for free",after:await state(page)});await context.close(); } + { + const {context,page}=await open();await court(page);const game=page.getByTestId("expedition-game"); + await game.focus();await page.keyboard.press("W");await expect(game).toHaveAttribute("data-busy","false"); + assert.deepEqual((await state(page)).commands,["step:north"],"uppercase WASD uses the same canonical movement"); + const summary=page.locator(".exp-button-controls summary");await summary.focus();await page.keyboard.press("a"); + assert.equal((await state(page)).turn,1,"single-letter keys do not move while a native summary is focused"); + await page.evaluate(()=>{document.body.tabIndex=-1;document.body.focus();});await page.keyboard.press("ArrowLeft"); + assert.equal((await state(page)).turn,1,"keyboard movement requires intentional game focus"); + await game.focus();await page.keyboard.press("Control+a"); + await game.evaluate(node=>{node.dispatchEvent(new KeyboardEvent("keydown",{key:"a",repeat:true,bubbles:true}));node.dispatchEvent(new KeyboardEvent("keydown",{key:"d",isComposing:true,bubbles:true}));}); + assert.equal((await state(page)).turn,1,"modifiers, held-key repeat and IME never send commands"); + const beforeInspect=await page.evaluate(k=>localStorage.getItem(k),key);await page.keyboard.press("i"); + await expect(page.getByRole("dialog")).toBeVisible();await page.keyboard.press("ArrowLeft");await page.keyboard.press("Escape"); + assert.equal(await page.evaluate(k=>localStorage.getItem(k),key),beforeInspect,"I and dialog keyboard input preserve the exact saved state"); + results.push({case:"focused keyboard shortcuts and native control isolation",after:await state(page)});await context.close(); + } + for(const gesture of ["short-drag","diagonal","out-and-back","two-fingers","rotate","modal"] as const){ + const {context,page,cdp}=await open();await court(page);const west=await cell(page,0,0); + await touch(cdp,"touchStart",west); + if(gesture==="short-drag")await touch(cdp,"touchMove",{x:west.x+20,y:west.y}); + if(gesture==="diagonal")await touch(cdp,"touchMove",{x:west.x+45,y:west.y-45}); + if(gesture==="out-and-back"){await touch(cdp,"touchMove",{x:west.x+45,y:west.y});await touch(cdp,"touchMove",west);} + if(gesture==="two-fingers")await cdp.send("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[{id:1,x:west.x,y:west.y},{id:2,x:west.x+50,y:west.y}]}); + if(gesture==="rotate")await page.setViewportSize({width:844,height:390}); + if(gesture==="modal")await page.getByRole("button",{name:"Inspect",exact:true}).click(); + await touch(cdp,"touchEnd");await page.waitForTimeout(100); + assert.equal((await state(page)).turn,0,`${gesture}: an unfinished or ambiguous gesture spends no decision`); + if(gesture==="modal"){await page.keyboard.press("Escape");await worldAction(page,"wait",true);await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-turn","1");} + results.push({case:`gesture ${gesture}`,after:await state(page)});await context.close(); + } + for(const [dx,dy,command] of [[0,-70,"step:north"],[-70,0,"step:west"],[70,0,"step:east"]] as const){ + const {context,page,cdp}=await open();await court(page);const from=await cell(page,1,1); + await touch(cdp,"touchStart",from);await touch(cdp,"touchMove",{x:from.x+dx,y:from.y+dy});await touch(cdp,"touchEnd"); + await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-turn","1"); + await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-busy","false"); + assert.deepEqual((await state(page)).commands,[command],`${command}: one true touch release is one step`); + if(command==="step:north"){ + const next=await cell(page,1,1);await touch(cdp,"touchStart",next);await touch(cdp,"touchMove",{x:next.x,y:next.y+70});await touch(cdp,"touchEnd"); + await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-turn","2"); + assert.deepEqual((await state(page)).commands,[command,"step:south"]); + } + results.push({case:`swipe ${command}`,after:await state(page)});await page.screenshot({path:join(captures,`direct-${command.replace(":","-")}.png`)});await context.close(); + } + for(const daily of [false,true]){ + const {context,page,cdp}=await open(daily,true);if(!daily)await court(page); + const route:readonly string[]=daily?tideFixtureRoute!:solveCourt({area:"beacon",tool:"rope",banked:[]},["lens"],{dry:true})!.commands; + for(const [index,command] of route.entries()){ + if(command.startsWith("step:")){ + const from=await cell(page,1,2),direction=command.slice(5),dx=direction==="west"?-60:direction==="east"?60:0,dy=direction==="north"?-60:direction==="south"?60:0; + await touch(cdp,"touchStart",from);await touch(cdp,"touchMove",{x:from.x+dx,y:from.y+dy});await touch(cdp,"touchEnd"); + }else if(command.startsWith("take:")||command.startsWith("reel:")){ + const item=command.split(":")[1],target=await cell(page,item==="lens"?0:item==="moth"?2:1,4);await page.touchscreen.tap(target.x,target.y); + }else await worldAction(page,command,true); + await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-busy","false"); + const saved=await page.evaluate(k=>JSON.parse(localStorage.getItem(k)!),key); + const actual=saved.active?.state??saved.last; + assert.deepEqual(actual.commands,route.slice(0,index+1),"each touch accepts exactly its intended next decision"); + } + await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-mode","harbor"); + const saved=await page.evaluate(k=>JSON.parse(localStorage.getItem(k)!),key);assert.deepEqual(saved.last.commands,route,"full swipe/tap journey preserves the exact route"); + assert(saved.last.cargo.includes("lens"),"the swipe/tap route returns the lens"); + await page.screenshot({path:join(captures,`direct-${daily?"daily":"beacon"}-return.png`)}); + results.push({case:`full ${daily?"legacy daily court":"Beacon"} touch route`,commands:saved.last.commands});await context.close(); + } await writeFile(join(captures,`touch-${phase}-results.json`),JSON.stringify({phase,viewport:[390,844],input:"CDP touch events, not a physical device",results},null,2)+"\n"); console.log(JSON.stringify({phase,captures,cases:results.map(result=>result.case),transcripts:join(captures,`touch-${phase}-results.json`)},null,2)); assert.equal(results[0]!.spentDecision,0,"A browser-canceled touch must never accept a game decision"); - assert.equal(results[1]!.active,null,"A canceled home-button gesture must not start an outing"); - assert.equal((results[2]!.after as {turn:number}).turn,0,"A drag must not masquerade as a destination tap"); + assert.equal(results[1]!.active,null,"A canceled home-button gesture must not start a court"); + assert.equal((results[2]!.after as {turn:number}).turn,1,"A qualifying swipe is one movement decision, without a destination tap"); + assert.deepEqual((results[2]!.after as {commands:string[]}).commands,["step:west"]); assert.equal((results[3]!.after as {turn:number}).turn,0,"Press and release must target the same platform even below the drag threshold"); }finally{await browser.close();await server.close();} diff --git a/scripts/test-passage-browser.ts b/scripts/test-passage-browser.ts index ab0f69a..a743725 100644 --- a/scripts/test-passage-browser.ts +++ b/scripts/test-passage-browser.ts @@ -1,3 +1,4 @@ +import { guide, worldAction, buttonControls } from "./browser-controls"; import assert from "node:assert/strict"; import { mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -29,19 +30,22 @@ try { await expect(page.getByRole("heading",{name:"Wind Gate",exact:true})).toBeVisible(); await page.getByRole("button",{name:"Close panel",exact:true}).click(); for(const job of ["bell","reed"] as const){ - await page.getByRole("button",{name:"Choose a crossing",exact:true}).click(); - await page.getByRole("button",{name:job==="bell"?/Bell Steps · Send supplies/:/Reed Steps · Bring the skiff home/}).click(); + await page.getByRole("button",{name:"Harbor chart",exact:true}).click(); + await page.getByRole("button",{name:job==="bell"?"Send Bram’s supplies":"Follow Mochi to Reed",exact:true}).click(); const game=page.getByTestId("passage-game"); const beforeSound=await game.getAttribute("data-turn"); await page.getByRole("button",{name:"Enable game audio",exact:true}).click(); await expect(page.getByRole("button",{name:"Mute game audio",exact:true})).toBeVisible(); await page.getByRole("button",{name:"Mute game audio",exact:true}).click(); assert.equal(await game.getAttribute("data-turn"),beforeSound,"sound control spends no turn"); + await game.focus();await page.keyboard.press("i"); + await expect(page.getByRole("dialog")).toBeVisible();await page.keyboard.press("Escape"); + await expect(game).toBeFocused(); const steps=job==="bell"?["north","west","ride","south","south","east","return"]:["north","north","west","east","east","west","north","wait","east","wait","south","ride","south","west","return"]; for(const [index,step] of steps.entries()){ const command=["north","west","south","east"].includes(step)?`step:${step}`:step; - const button=page.locator(`[data-command="${command}"]`); - if(phone)await button.tap();else await button.click(); + if(index===0)await page.keyboard.press("ArrowUp"); + else if(phone && !command.startsWith("step:"))await worldAction(page,command,true);else await guide(page,command); await expect(game).toHaveAttribute("data-turn",String(index+1)); await expect(game).toHaveAttribute("data-busy","false"); if(index===2){ @@ -54,8 +58,9 @@ try { await expect(game).toHaveAttribute("data-stage","delivered"); if(job==="reed")await expect(game).toHaveAttribute("data-watched","true"); await page.getByTestId("passage-finish").click(); - const title=job==="bell"?"Supplies at Bell Steps.":"The Tidekeeper has an ask."; - await expect(page.getByRole("heading",{name:title})).toBeVisible(); + await expect(page.locator(".exp-departure h1")).toHaveText(/^Today’s tide:/); + const title=(await page.locator(".exp-departure h1").textContent())!; + await expect(page.getByTestId("expedition-feedback")).toContainText(job==="bell"?"Bram’s supplies are stacked at Bell Steps.":"Mochi’s skiff is tied up at the quay."); await page.reload(); await expect(page.getByRole("heading",{name:title})).toBeVisible(); await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true"); @@ -63,7 +68,7 @@ try { } const passageKey=key+":shore-passages.v1"; const beforeRest=await page.evaluate(k=>localStorage.getItem(k),passageKey); - await page.locator(".exp-harbor-links").getByRole("button",{name:"Harbor chart",exact:true}).click(); + await page.getByRole("button",{name:"Harbor chart",exact:true}).click(); await expect(page.getByRole("heading",{name:"A harbor connected.",exact:true})).toBeVisible(); await expect(page.getByRole("heading",{name:"Bell Steps",exact:true})).toBeVisible(); await expect(page.getByText("Bram’s crates are stacked on the far work platform.",{exact:true})).toBeVisible(); @@ -76,7 +81,8 @@ try { assert.equal(await page.evaluate(k=>localStorage.getItem(k),passageKey),beforeRest); await page.getByRole("button",{name:"Back to the harbor",exact:true}).click(); assert.equal(await page.evaluate(key=>localStorage.getItem(key),key),original); - const actor={x:(phone?390:1280)*.49,y:phone?480:588}; + await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve())))); + const actor={x:(phone?390:1280)*.49,y:phone?302:620}; if(!phone){ await page.mouse.click(actor.x,actor.y,{button:"right"}); await expect(page.getByRole("heading",{name:"A moment together."})).toHaveCount(0); @@ -98,8 +104,7 @@ try { async function move(step:string){ const command=["north","west","south","east"].includes(step)?`step:${step}`:step; const turn=Number(await game.getAttribute("data-turn")); - const button=page.locator(`[data-command="${command}"]`); - if(phone)await button.tap();else await button.click(); + if(phone && !command.startsWith("step:"))await worldAction(page,command,true);else await guide(page,command); await expect(game).toHaveAttribute("data-turn",String(turn+1)); await expect(game).toHaveAttribute("data-busy","false"); } @@ -111,7 +116,7 @@ try { assert.equal(await page.evaluate(k=>localStorage.getItem(k),passageKey),beforeInspect); await page.getByRole("button",{name:"Close panel",exact:true}).click(); if(phone)await move("listen");else{ - await page.keyboard.press("e"); + await game.focus();await page.keyboard.press("e"); await expect(game).toHaveAttribute("data-turn","7"); await expect(game).toHaveAttribute("data-busy","false"); } @@ -142,7 +147,7 @@ try { await expect(page.locator(".exp-inspect-reading")).toContainText("Bridge left. Mochi stays dry."); await expect(game).toHaveAttribute("data-turn","2"); await page.getByRole("button",{name:"Close panel",exact:true}).click(); - await page.locator('[data-command="ring"]').focus(); + await buttonControls(page);await page.locator('[data-command="ring"]').focus(); await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-preview-exit","0"); await expect(game).toHaveAttribute("data-turn","2"); if(!phone&&job==="bell")await page.screenshot({path:join(output,"chromium-bell-preview.png")}); @@ -157,9 +162,9 @@ try { await page.getByRole("button",{name:"Mute game audio",exact:true}).tap(); await expect(game).toHaveAttribute("data-turn","2"); } + await buttonControls(page,false); if(phone){ - const tile=JSON.parse((await page.getByTestId("expedition-world").getAttribute("data-tiles"))!).find((t:any)=>t.position.x===1&&t.position.y===3); - await page.touchscreen.tap(tile.x,tile.y); + await worldAction(page,"ring",true); await expect(game).toHaveAttribute("data-turn","3"); await expect(game).toHaveAttribute("data-busy","false"); }else await move("ring"); diff --git a/scripts/test-routing-browser.ts b/scripts/test-routing-browser.ts index 725de58..e3e8b56 100644 --- a/scripts/test-routing-browser.ts +++ b/scripts/test-routing-browser.ts @@ -1,3 +1,4 @@ +import { guide } from "./browser-controls"; import assert from "node:assert/strict"; import { mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -88,7 +89,7 @@ try { await page.getByRole("button",{name:"Harbor chart",exact:true}).and(page.locator(":visible")).click(); await page.locator('.exp-panel[data-surface="chart"] .harbor-routes > li').first().getByRole("button").click(); await page.locator('.exp-panel[data-surface="sail"] .exp-primary').click(); - await page.locator('[data-command="step:west"]').click(); + await guide(page,"step:west"); await expect(game).toHaveAttribute("data-busy", "false"); const saved = await page.evaluate(key => localStorage.getItem(key), saveKey); assert(saved && JSON.parse(saved).active.state.turn === 1); @@ -122,7 +123,7 @@ try { const tideRun=page.getByTestId("tide-run"); await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready","true"); await expect(tideRun).toHaveAttribute("data-busy","false"); - await page.locator(`button[data-move="${returned.moves.at(-1)!}"]`).click(); + await guide(page,returned.moves.at(-1)!); const home=page.locator('.exp-panel[data-surface="home"]');await expect(home).toBeVisible(); const filed=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),bookKey); assert.equal(filed.active,null); diff --git a/scripts/test-tide-browser.ts b/scripts/test-tide-browser.ts index 2bc2033..e0cdf07 100644 --- a/scripts/test-tide-browser.ts +++ b/scripts/test-tide-browser.ts @@ -1,3 +1,4 @@ +import { guide } from "./browser-controls"; import assert from "node:assert/strict"; import { mkdir, mkdtemp } from "node:fs/promises"; import { join, resolve } from "node:path"; @@ -126,7 +127,7 @@ async function checkTrayAsks(page: Page, label: string) { const tray = page.locator(".exp-command-tray"), asks = tray.locator(".exp-tray-reading > .tide-outing .tide-asks"); await expect(asks).toBeVisible(); await expect(tray.locator(".exp-tray-scroll .tide-outing")).toHaveCount(0); - const bounds = await tray.boundingBox(), strip = await asks.boundingBox(), actions = await tray.locator(".exp-tray-actions").boundingBox(); + const bounds = await tray.boundingBox(), strip = await asks.boundingBox(), actions = await tray.locator(".exp-control-hints").boundingBox(); assert.ok(bounds && strip && actions, `${label}: tray, asks and actions have visible bounds`); assert.ok(strip.x >= bounds.x - 1 && strip.x + strip.width <= bounds.x + bounds.width + 1 && strip.y >= bounds.y - 1 && strip.y + strip.height <= bounds.y + bounds.height + 1, @@ -145,7 +146,7 @@ async function checkTrayAsks(page: Page, label: string) { if (size.width < 900) { const rows = new Set(chips.map(chip => Math.round(chip.top))).size; if (size.height > size.width) assert.equal(rows, 1, `${label}: portrait phone asks use one row`); - else assert.ok(rows <= 2, `${label}: landscape phone asks use at most two rows in the narrow tray`); + else assert.ok(rows <= 3, `${label}: all three landscape asks fit the narrow hint tray`); assert.ok(chips.every(chip => chip.height <= 36), `${label}: phone chips stay at most 36px tall`); } else assert.equal(new Set(chips.map(chip => Math.round(chip.top))).size, 3, `${label}: desktop asks use three stacked rows`); const reading = tray.locator(".exp-tray-scroll"); @@ -161,7 +162,7 @@ async function checkTrayAsks(page: Page, label: string) { async function checkRestartLayout(page: Page, label: string) { const asks = page.locator(".tide-asks"), restart = page.locator(".tide-outing > .tide-restart.exp-text-button"); const strip = await asks.boundingBox(), button = await restart.boundingBox(); - const tray = await page.locator(".exp-command-tray").boundingBox(), actions = await page.locator(".exp-tray-actions").boundingBox(); + const tray = await page.locator(".exp-command-tray").boundingBox(), actions = await page.locator(".exp-control-hints").boundingBox(); assert.ok(strip && button && tray && actions, `${label}: asks, restart, tray and actions have visible bounds`); assert.ok(button.y >= strip.y + strip.height - 1 || button.y + button.height <= strip.y + 1 || button.x >= strip.x + strip.width - 1 || button.x + button.width <= strip.x + 1, @@ -169,7 +170,7 @@ async function checkRestartLayout(page: Page, label: string) { assert.ok(button.x >= tray.x - 1 && button.x + button.width <= tray.x + tray.width + 1 && button.y >= tray.y - 1 && button.y + button.height <= tray.y + tray.height + 1, `${label}: restart stays inside the tray`); assert.ok(button.y + button.height <= actions.y + 1 || button.x + button.width <= actions.x + 1 || button.x >= actions.x + actions.width - 1, - `${label}: restart stays clear of movement and context actions`); + `${label}: restart stays clear of input hints`); assert.ok(button.height >= 44, `${label}: restart has a 44px target`); await expect(restart).toBeInViewport({ ratio: 1 }); await checkTrayAsks(page, label); @@ -201,7 +202,6 @@ async function openClassic(page: Page) { async function checkDaily(page: Page, origin: string) { const today = Math.floor(Date.now() / 86_400_000), todayCard = cardForDay(today), tomorrow = cardForDay(today + 1); const guardDay = () => assert.equal(Math.floor(Date.now() / 86_400_000), today, "UTC midnight crossed during the daily flow; rerun with the new day"); - const keys: Record = { north: "ArrowUp", south: "ArrowDown", west: "ArrowLeft", east: "ArrowRight", wait: "Space", home: "r" }; let final = startTide({ seed: today }); while (final.outcome === "active") final = applyMove(final, cautiousMove(final))!.after; const result = dayResult(final), goods = shelfGoods(result); @@ -239,7 +239,7 @@ async function checkDaily(page: Page, origin: string) { await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready", "true", { timeout: 30000 }); for (const move of final.moves) { await expect(run).toHaveAttribute("data-busy", "false", { timeout: 15000 }); - await page.keyboard.press(keys[move]); + await guide(page,move); } await expect(page.getByRole("dialog", { name: "Home", exact: true })).toBeVisible({ timeout: 15000 }); guardDay(); @@ -352,7 +352,7 @@ async function checkMidnight(page: Page, origin: string, mode: "harbor" | "wake" await panel.getByRole("button", { name: "Start this tide over", exact: true }).click(); assert.deepEqual(await asks.allTextContents(), beforeAsks, "restart after midnight keeps the original card’s asks"); assert.deepEqual(await page.evaluate(key => JSON.parse(localStorage.getItem(key)!), pendingKey), expectedPending, "restart after midnight keeps the outing’s original marker"); - await page.locator('button[data-command="return"]').click(); + await guide(page,"return"); await page.clock.runFor(1_000); await expect(page.getByRole("dialog", { name: "Home", exact: true })).toBeVisible(); await panel.getByRole("button", { name: "See the tide log", exact: true }).click(); @@ -467,7 +467,7 @@ try { } await captureLayouts(page, "court-start", () => checkTrayAsks(page, "outing start")); for (const [index, command] of route.entries()) { - await page.locator(`button[data-command="${command}"]`).click(); + await guide(page,command); await expect(game).toHaveAttribute("data-busy", "false", { timeout: 15000 }); if (index + 1 === Math.ceil(route.length / 2)) { await expect(asks).toBeVisible(); @@ -480,8 +480,8 @@ try { assert.ok(new Set(chips.map(chip => chip.top)).size <= 2, "phone asks use at most two rows"); assert.ok(chips.every(chip => chip.font >= 13), "phone ask text is at least 13px"); const feedback = await page.getByTestId("expedition-feedback").boundingBox(), tray = await page.locator(".exp-command-tray").boundingBox(); - const reading = await page.locator(".exp-tray-scroll").boundingBox(), actions = await page.locator(".exp-tray-actions").boundingBox(); - const directions = await page.locator(".exp-directions").boundingBox(); + const reading = await page.locator(".exp-tray-scroll").boundingBox(), actions = await page.locator(".exp-control-hints").boundingBox(); + const directions = await page.locator(".exp-control-hints").boundingBox(); const dockBottom = await world.evaluate(node => { const ys = (JSON.parse(node.getAttribute("data-tiles")!) as { y: number }[]).map(tile => tile.y); const bottom = Math.max(...ys), step = (bottom - Math.min(...ys)) / 4; @@ -490,9 +490,9 @@ try { assert.ok(tray && tray.y >= dockBottom, "the phone tray clears the complete dock platform"); assert.ok(feedback && reading && directions && Math.max(feedback.y, reading.y) >= tray!.y && Math.min(feedback.y + feedback.height, reading.y + reading.height) <= directions.y, - "visible phone feedback stays inside its scrolling region above the movement controls"); + "visible phone feedback stays inside its scrolling region above the input hints"); assert.ok(actions && actions.y >= tray!.y && actions.y + actions.height <= viewport.height, - "phone movement and context actions stay visible without scrolling the tray"); + "phone input hints stay visible without scrolling the tray"); await page.screenshot({ path: join(shots, `court-mid-outing-${tag}.png`) }); } } @@ -576,7 +576,7 @@ try { assert.deepEqual(await page.evaluate(key => JSON.parse(localStorage.getItem(key)!).home, saveKey), before, "the classic tide outing leaves home progress unchanged"); await panel.getByRole("button", { name: "Sail this tide again", exact: true }).click(); await expect(game).toHaveAttribute("data-mode", "court"); - await page.locator('button[data-command="return"]').click(); + await guide(page,"return"); await expect(page.getByRole("dialog", { name: "Home", exact: true })).toBeVisible(); await expect(panel.getByRole("heading", { name: "An empty satchel keeps no asks.", exact: true })).toBeVisible(); await expect(panel.locator('.tide-list > li[data-kept="true"]')).toHaveCount(0); @@ -610,7 +610,7 @@ try { await expect(restart).toHaveCount(0); await page.emulateMedia({ reducedMotion: "no-preference" }); for (const command of slipRoute) { - await page.locator(`button[data-command="${command}"]`).click(); + await guide(page,command); await expect(game).toHaveAttribute("data-busy", "false", { timeout: 15000 }); } await expect(asks.locator('li[data-status="slipped"]')).not.toHaveCount(0); @@ -623,7 +623,7 @@ try { if (game.getAttribute("data-busy") === "true" && restart?.disabled) window.restartBusySeen = true; }).observe(game, { attributes: true, subtree: true, attributeFilter: ["data-busy", "disabled"] }); }); - await page.locator('button[data-command="wait"]').click(); + await guide(page,"wait"); await expect(game).toHaveAttribute("data-busy", "false", { timeout: 15000 }); await expect(restart).toBeEnabled(); assert.equal(await page.evaluate(() => window.restartBusySeen), true, "restart was disabled during the observed busy window"); @@ -667,7 +667,7 @@ try { assert.equal(await page.evaluate(() => window.tidePops.length), popsBeforeRestart, "restart does not pop the reset strip"); await page.emulateMedia({ reducedMotion: "reduce" }); - await page.locator('button[data-command="wait"]').click(); + await guide(page,"wait"); await expect(game).toHaveAttribute("data-busy", "false", { timeout: 15000 }); await page.getByRole("button", { name: "Game menu", exact: true }).click(); const menuRestart = panel.getByRole("button", { name: "Start this tide over", exact: true }); @@ -723,7 +723,7 @@ try { const bridgeRoute: Command[] = ["step:west", "wait", "step:east", "wait", "wait", "wait", "step:west", "wait", "step:east"]; const bridgeChip = asks.locator("li").nth(1); for (const [index, command] of bridgeRoute.entries()) { - await page.locator(`button[data-command="${command}"]`).click(); + await guide(page,command); await expect(game).toHaveAttribute("data-busy", "false", { timeout: 15000 }); const holding = askHolds(nextCard.asks[1], replayRun(nextCard.tool, bridgeRoute.slice(0, index + 1))!); await expect(bridgeChip).toHaveAttribute("data-holding", String(holding)); @@ -734,13 +734,13 @@ try { await page.emulateMedia({ reducedMotion: "reduce" }); // Another bridge cycle changes the status, with no animation under reduced motion. for (const command of ["wait", "wait", "wait"] as Command[]) { - await page.locator(`button[data-command="${command}"]`).click(); + await guide(page,command); await expect(game).toHaveAttribute("data-busy", "false", { timeout: 15000 }); } await expect(bridgeChip).toHaveAttribute("data-holding", "false"); assert.deepEqual(await asks.locator("li").evaluateAll(chips => chips.map(chip => getComputedStyle(chip).animationName)), ["none", "none", "none"], "reduced motion removes chip animations"); for (const command of ["step:west", "wait", "step:east"] as Command[]) { - await page.locator(`button[data-command="${command}"]`).click(); + await guide(page,command); await expect(game).toHaveAttribute("data-busy", "false", { timeout: 15000 }); } await expect(bridgeChip).toHaveAttribute("data-holding", "true"); @@ -750,7 +750,7 @@ try { await page.evaluate(() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(() => done())))); assert.deepEqual(await page.evaluate(() => window.tidePops), [], "ask status changes stay still; the Home sheet owns the arrival motion"); await page.emulateMedia({ reducedMotion: "reduce" }); - await page.locator('button[data-command="return"]').click(); + await guide(page,"return"); await expect(page.getByRole("dialog", { name: "Home", exact: true })).toBeVisible(); await expect(panel.locator(".tide-list")).toHaveAttribute("data-arrival", "true"); await expect(panel.locator(".tide-home-stamp .tide-stamp")).not.toHaveAttribute("data-press", "true"); diff --git a/scripts/test-tide-run-browser.ts b/scripts/test-tide-run-browser.ts index c67b99e..bac5976 100644 --- a/scripts/test-tide-run-browser.ts +++ b/scripts/test-tide-run-browser.ts @@ -1,9 +1,10 @@ /** A fresh device harbor sails the three story tides and today's tide run, leaving and reloading one of them half way. */ import assert from "node:assert/strict"; +import { guide, worldAction, buttonControls } from "./browser-controls"; import { mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; -import { chromium, expect } from "@playwright/test"; +import { chromium, webkit, expect } from "@playwright/test"; import { createServer } from "vite"; import { VALUE, applyMove, startTide, type Move, type TideStart } from "../web/src/run/engine"; import { cautiousMove } from "../web/src/run/bot"; @@ -30,10 +31,23 @@ const bookKey = "familiar.expedition.local.v2:tide-run.v1"; try { await server.listen(); const origin = new URL(server.resolvedUrls!.local[0]!); - const browser = await chromium.launch(); + for(const engine of [chromium,webkit]) { + const browser = await engine.launch(); try { + const probe=await browser.newPage({viewport:{width:390,height:844},hasTouch:true,reducedMotion:"reduce"}); + await probe.route("**/*",request=>new URL(request.request().url()).origin===origin.origin&&!/^\/(?:api|npc-api)\//.test(new URL(request.request().url()).pathname)?request.continue():request.abort()); + await probe.goto(new URL("/outing/?play",origin).href);await expect(probe.getByTestId("expedition-world")).toHaveAttribute("data-ready","true"); + await probe.locator('[data-action="story"]').click();await expect(probe.getByTestId("tide-world")).toHaveAttribute("data-ready","true"); + const probeRun=probe.getByTestId("tide-run"),tiles=JSON.parse((await probe.getByTestId("tide-world").getAttribute("data-tiles"))!) as {position:{x:number;y:number};x:number;y:number}[]; + const start=tiles.find(tile=>tile.position.x===1&&tile.position.y===2)!; + await probe.mouse.move(start.x,start.y);await probe.mouse.down();await probe.keyboard.press("i");await expect(probe.getByRole("dialog")).toBeVisible(); + await probe.mouse.up();await probe.keyboard.press("Escape");await expect(probeRun).toBeFocused();await worldAction(probe,"wait",true); + await expect(probeRun).toHaveAttribute("data-beat","1"); + assert.deepEqual(await probe.evaluate(key=>JSON.parse(localStorage.getItem(key)!).active.moves,bookKey),["wait"],"a release while the guide is open cannot block the next native touch"); + await probe.close(); const page = await browser.newPage({ viewport: { width: 390, height: 844 }, hasTouch: true, reducedMotion: "reduce" }); const errors: string[] = []; + const cdp=engine===chromium?await page.context().newCDPSession(page):null; page.on("pageerror", error => errors.push(error.message)); page.on("console", message => { if (message.type() === "error") errors.push(message.text()); }); await page.route("**/*", request => new URL(request.request().url()).origin === origin.origin && !/^\/(?:api|npc-api)\//.test(new URL(request.request().url()).pathname) ? request.continue() : request.abort()); @@ -47,9 +61,26 @@ try { if (tide) await page.locator('[data-el="scroll"] .fo-primary').click(); await expect(page.getByTestId("opening")).toHaveCount(0); }; - const press = async (keys: readonly string[]) => { + const press = async (keys: readonly string[], touch=false) => { await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready", "true"); - for (const key of keys) { await expect(run).toHaveAttribute("data-busy", "false"); await page.keyboard.press(key); } + for (const key of keys) { + await expect(run).toHaveAttribute("data-busy", "false"); + const before=Number(await run.getAttribute("data-beat")); + if(touch){ + const move=Object.entries(KEY).find(([,mapped])=>mapped===key)![0] as Move; + if(move==="wait"||move==="home")await worldAction(page,move,true); + else if(cdp) { + const tiles=JSON.parse((await page.getByTestId("tide-world").getAttribute("data-tiles"))!) as {position:{x:number;y:number};x:number;y:number}[]; + const from=tiles.find(tile=>tile.position.x===1&&tile.position.y===2)!; + const dx=move==="west"?-60:move==="east"?60:0,dy=move==="north"?-60:move==="south"?60:0; + await cdp.send("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[{id:1,x:from.x,y:from.y}]}); + await cdp.send("Input.dispatchTouchEvent",{type:"touchMove",touchPoints:[{id:1,x:from.x+dx,y:from.y+dy}]}); + await cdp.send("Input.dispatchTouchEvent",{type:"touchEnd",touchPoints:[]}); + } + else{await run.focus();await page.keyboard.press(key);} + }else{await run.focus();await page.keyboard.press(key);} + await expect(run).toHaveAttribute("data-beat",String(before+1)); + } await expect(run).toHaveAttribute("data-busy", "false"); }; const home = () => page.evaluate(() => (JSON.parse(localStorage.getItem("familiar.expedition.local.v2") ?? "null")?.home ?? { banked: [] }) as { banked: string[] }); @@ -62,14 +93,16 @@ try { }, { key, filing }); async function sail(start: TideStart, from = 0) { const { keys, state } = route(start); - if (start.story) await press(keys.slice(from)); + if (start.story) await press(keys.slice(from),start.story==="lens"); else { - await press(keys.slice(from, -1)); + await press(keys.slice(from, -1),true); await failNextWrite(bookKey, true); - await page.keyboard.press(keys.at(-1)!); + await guide(page,Object.entries(KEY).find(([,key])=>key===keys.at(-1))![0]); } await expect(run).toHaveAttribute("data-outcome", state.outcome); await expect(run).toHaveAttribute("data-score", String(state.score)); + const trace=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!).active,bookKey); + assert.deepEqual(trace.moves,state.moves,"the default input route saves exactly the canonical move history"); if (start.story === "lens") { await page.reload(); await passTitle(); await expect(run).toHaveAttribute("data-outcome", state.outcome); @@ -97,6 +130,45 @@ try { await expect(title).toHaveText("First light."); await page.locator('[data-action="story"]').click(); await expect(run).toHaveAttribute("data-story", "lens"); + await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready","true"); + await expect(page.locator("[data-move]:visible")).toHaveCount(0); + const untouched=await page.evaluate(key=>localStorage.getItem(key),bookKey); + for(const size of [{width:320,height:480},{width:390,height:844},{width:412,height:860},{width:844,height:390},{width:1280,height:800},{width:1440,height:900}]){ + await page.setViewportSize(size); + await expect.poll(()=>page.locator('[data-testid="tide-world"] canvas').evaluate(node=>{const r=node.getBoundingClientRect();return Math.abs(r.width-innerWidth)<1&&Math.abs(r.height-innerHeight)<1;})).toBe(true); + await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve())))); + const geometry=await page.getByTestId("tide-world").evaluate(node=>{ + const targets=[...JSON.parse(node.getAttribute("data-tiles")!),...JSON.parse(node.getAttribute("data-actions")!)]; + return{count:JSON.parse(node.getAttribute("data-tiles")!).length,hidden:targets.filter(target=>target.x<0||target.y<0||target.x>innerWidth||target.y>innerHeight||document.elementFromPoint(target.x,target.y)?.tagName!=="CANVAS"),scroll:[scrollX,scrollY,document.documentElement.scrollWidth-innerWidth,document.documentElement.scrollHeight-innerHeight]}; + }); + assert.equal(geometry.count,15);assert.deepEqual(geometry.hidden,[],`${engine.name()} ${size.width}x${size.height}: all world targets remain exposed`); + assert.deepEqual(geometry.scroll,[0,0,0,0],"the gesture playfield never scrolls the page"); + await page.screenshot({path:join(cacheDir,`${engine.name()}-hints-${size.width}x${size.height}.png`)}); + } + await page.setViewportSize({width:390,height:844}); + await buttonControls(page);await expect(page.locator('[data-move="wait"]')).toBeVisible();await buttonControls(page,false); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),untouched,"optional controls only reveal alternatives"); + const summary=page.locator(".exp-button-controls summary");await summary.focus();await page.keyboard.press("Space");await page.keyboard.press("Space"); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),untouched,"summary Space never waits"); + await page.evaluate(()=>{document.body.tabIndex=-1;document.body.focus();});await page.keyboard.press("ArrowUp"); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),untouched,"letter and direction shortcuts need game focus"); + const guideButton=page.getByTestId("tide-guide");await guideButton.tap();await expect(page.getByRole("dialog")).toBeVisible(); + await page.getByRole("button",{name:"Close panel",exact:true}).tap();await expect(guideButton).toBeFocused(); + await run.focus();await page.keyboard.press("i");await expect(page.getByRole("dialog")).toBeVisible();await page.keyboard.press("Escape");await expect(run).toBeFocused(); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),untouched,"free inspection preserves the story trace"); + if(cdp)for(const cancel of ["cancel","diagonal","short","two-fingers","rotate"] as const){ + const tiles=JSON.parse((await page.getByTestId("tide-world").getAttribute("data-tiles"))!) as {position:{x:number;y:number};x:number;y:number}[]; + const from=tiles.find(tile=>tile.position.x===1&&tile.position.y===2)!; + await cdp.send("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[{id:1,x:from.x,y:from.y}]}); + if(cancel==="diagonal"||cancel==="short")await cdp.send("Input.dispatchTouchEvent",{type:"touchMove",touchPoints:[{id:1,x:from.x+(cancel==="short"?20:45),y:from.y+(cancel==="short"?0:45)}]}); + if(cancel==="two-fingers")await cdp.send("Input.dispatchTouchEvent",{type:"touchStart",touchPoints:[{id:1,x:from.x,y:from.y},{id:2,x:from.x+50,y:from.y}]}); + if(cancel==="rotate")await page.setViewportSize({width:844,height:390}); + await cdp.send("Input.dispatchTouchEvent",{type:cancel==="cancel"?"touchCancel":"touchEnd",touchPoints:[]}); + await expect(run).toHaveAttribute("data-busy","false"); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),untouched,`${cancel} gesture preserves the exact story save`); + if(cancel==="rotate")await page.setViewportSize({width:390,height:844}); + } + await page.screenshot({path:join(cacheDir,"direct-story-hints.png")}); await sail(storyStart("lens")); await expect(title).toHaveText("The lens is home."); assert.deepEqual((await home()).banked, ["lens"]); @@ -154,7 +226,7 @@ try { await page.locator(".exp-departure-buttons > .exp-secondary").click(); await expect(run).toHaveAttribute("data-seed", String(day)); await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready", "true"); - await page.locator('[data-move="wait"]').click(); + await buttonControls(page);await page.locator('[data-move="wait"]').tap();await buttonControls(page,false); await expect(run).toHaveAttribute("data-busy", "false"); await page.reload(); await passTitle(true); @@ -165,7 +237,7 @@ try { await expect(run).toHaveAttribute("data-seed", String(day)); await expect(run).toHaveAttribute("data-beat", "1"); await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready", "true"); - await page.locator('[data-move="home"]').click(); + await worldAction(page,"home",true); await expect(sheet).toBeVisible(); await expect(sheet.locator(".tide-home-note")).toHaveText("A practice tide: banked 0. Today’s first tide is the one that counts."); const practiced = await page.evaluate(key => JSON.parse(localStorage.getItem(key)!), bookKey); @@ -173,6 +245,8 @@ try { assert.deepEqual(practiced.days, book.days); assert.notEqual(daily.moves.length, 2); assert.deepEqual(errors, []); - console.info("tide run: three story tides, finished reload, failed-save retries, leave and resume, daily Home and log, and practice preserving the first tide passed on a device harbor"); + console.info(`${engine.name()} tide run: ${cdp?"native swipe/tap":"native tap/keyboard"} lens and daily routes, ${cdp?"native gesture cancellation":"keyboard/dialog isolation"}, optional controls, keyboard focus isolation, three story tides, finished reload, failed-save retries, leave and resume, daily Home and log, and practice preserving the first tide passed on a device harbor`); } finally { await browser.close(); } + } + console.info("Tide run captures:",cacheDir); } finally { await server.close(); } diff --git a/web/src/expedition/ControlHints.test.tsx b/web/src/expedition/ControlHints.test.tsx new file mode 100644 index 0000000..c11ef8e --- /dev/null +++ b/web/src/expedition/ControlHints.test.tsx @@ -0,0 +1,25 @@ +import { expect, test } from "bun:test"; +import { renderToStaticMarkup } from "react-dom/server"; +import ControlHints from "./ControlHints"; + +test("touch hints retain an optional native button alternative without opening it", () => { + const html=renderToStaticMarkup(); + expect(html).toContain("Swipe to move"); + expect(html).toContain("tap a glowing stone"); + expect(html).toContain("Tap the dock to come home."); + expect(html).toContain('id="input-help"'); + expect(html).toContain("Button controls"); + expect(html).toContain(""); + expect(html).not.toContain(" open"); +}); + +test("desktop hints explain movement and the remaining shortcuts as text", () => { + const html=renderToStaticMarkup(); + expect(html).toContain("WASD or arrow keys to move"); + expect(html).toContain("Space waits"); + expect(html).toContain("E interacts"); + expect(html).toContain("R returns at the dock"); + expect(html).toContain("I inspects"); + expect(html).not.toContain('role="application"'); + expect(html).not.toContain('aria-live'); +}); diff --git a/web/src/expedition/ControlHints.tsx b/web/src/expedition/ControlHints.tsx new file mode 100644 index 0000000..cefcd2a --- /dev/null +++ b/web/src/expedition/ControlHints.tsx @@ -0,0 +1,28 @@ +import { useEffect, useRef, useState, type ReactNode } from "react"; + +type InputMode = "touch" | "keyboard"; + +export default function ControlHints({id,context="Tap Wait beside Mochi · tap a find to collect it.",children,initialMode,keyboardContext="Space waits · E interacts · R returns at the dock · I inspects"}:{ + id:string; context?:string; children:ReactNode; initialMode?:InputMode; keyboardContext?:string; +}) { + const root=useRef(null); + const [mode,setMode]=useState(()=>initialMode??(typeof matchMedia!=="undefined"&&matchMedia("(any-pointer: coarse)").matches?"touch":"keyboard")); + useEffect(()=>{ + const game=root.current?.closest(".exp-game"); + if(!game)return; + let frame=0; + const pointer=(event:Event)=>{const input=event as PointerEvent;cancelAnimationFrame(frame); + // Let Phaser finish the release before new hint text can move its targets. + frame=requestAnimationFrame(()=>setMode(input.pointerType==="touch"||input.pointerType==="pen"?"touch":"keyboard"));}; + const keyboard=(event:Event)=>{const key=event as KeyboardEvent;if(!key.isComposing&&!key.metaKey&&!key.altKey&&!key.ctrlKey){cancelAnimationFrame(frame);setMode("keyboard");}}; + game.addEventListener("pointerup",pointer,true);game.addEventListener("keydown",keyboard,true); + return()=>{cancelAnimationFrame(frame);game.removeEventListener("pointerup",pointer,true);game.removeEventListener("keydown",keyboard,true);}; + },[]); + return
+
+

{mode==="touch"?"Swipe to move · tap a glowing stone":"WASD or arrow keys to move"}

+

{mode==="touch"?context:keyboardContext}

+
+
Button controls
{children}
+
; +} diff --git a/web/src/expedition/Game.tsx b/web/src/expedition/Game.tsx index 4e323e2..1a6e73b 100644 --- a/web/src/expedition/Game.tsx +++ b/web/src/expedition/Game.tsx @@ -9,13 +9,14 @@ import { dockPassage, emptyPassageHome, readPassageHome, writePassageHome, type import HarborChart from "./HarborChart"; import Inspect, { commandName, forecast } from "./Inspect"; import { applyCommand, findPosition, legalCommands, packSlots, phaseOf, replayCourt, startCourt } from "./engine"; -import { commandAt } from "./input"; +import { commandAt, movementKey } from "./input"; +import ControlHints from "./ControlHints"; import { HarborAudio } from "./audio"; import { COURTS } from "./rooms"; import { CONTENT_VERSION, TURN_LIMIT, type Area, type BankedItem, type Command, type CourtEvent, type CourtState, type CourtTransition, type Position, type Tool } from "./types"; import { ReturnRecords, validateRunContext } from "./return-record"; import type { HarborSession, HomeCheckpoint, RunContext, WorldIntent } from "./harbor-port"; -import type { HarborView, HomePlace } from "./scene"; +import type { HarborView, HomePlace, WorldAction } from "./scene"; import { LanternArt, OriginDiorama } from "../tidebound/Storycraft"; import "./game.css"; import { deviceDay, keepTide, readPreview, readTide, seasonView, shelvesBeaconCourt, shelfNote } from "../season/data"; @@ -179,9 +180,10 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in const chapterComplete=home.signaled&&services.includes("bell")&&services.includes("reed"); const placement=session?.state.workshop.placement,placedItem=savedMode&&placement?session!.state.workshop.items.find(item=>item.mint.token_id===placement.item_id):null; const harbor:HarborView={resting,greeting,heardBell:passageScope===passageKey&&passage.heardBell,services,watchedReeds:passageScope===passageKey&&passage.watchedReeds,lit:home.lit,signaled:home.signaled,moth:home.banked.includes("moth"),lantern:!!(savedMode?placedItem:home.lantern),socket:savedMode&&placedItem?placement!.socket:home.lantern?.socket??"porch",motif:savedMode?placedItem?.mint.motif??"crest":home.lantern?.motif??"crest",polished:savedMode&&placedItem?.finish==="harbor_polish",relic:home.banked.includes("lens")&&!home.lit?"lens":home.banked.includes("vane")&&!home.signaled?"vane":null}; - const paused=showPassage||showTideRun||!worldReady||!!surface||hidden||unfocused||!!fault||!!problem||!!session?.state.review; + const paused=showPassage||showTideRun||lease!=="held"||!worldReady||!!surface||hidden||unfocused||!!fault||!!problem||!!session?.state.review; const pausedRef=useRef(paused);pausedRef.current=paused; - const snapshot=useMemo(()=>({court:run,home:harbor,reducedMotion:reduced,previewCommand:focused}),[run,harbor.lit,harbor.signaled,harbor.moth,harbor.lantern,harbor.socket,harbor.motif,harbor.polished,harbor.relic,resting,greeting,passage,passageScope,reduced,focused]); + const worldActions=useMemo(()=>{if(!run)return [];const available=legalCommands(run),actions:WorldAction[]=[];for(const action of ["wait","return","turn:vane"] as const)if(available.includes(action))actions.push(action);if(available.some(action=>action.startsWith("lure:")))actions.push("lantern");return actions;},[run]); + const snapshot=useMemo(()=>({court:run,home:harbor,reducedMotion:reduced,previewCommand:focused,worldActions}),[run,worldActions,harbor.lit,harbor.signaled,harbor.moth,harbor.lantern,harbor.socket,harbor.motif,harbor.polished,harbor.relic,resting,greeting,passage,passageScope,reduced,focused]); const previousHome=useRef({branch:desiredKey,lit:home.lit,signaled:home.signaled}); useEffect(()=>{ const before=previousHome.current; @@ -209,6 +211,7 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in useEffect(()=>{const media=matchMedia("(prefers-reduced-motion: reduce)"),change=()=>setReduced(media.matches),visibility=()=>{setHidden(document.hidden);buffer.current=null;if(document.hidden)muteSound();},blur=()=>{setUnfocused(true);buffer.current=null;muteSound();},focus=()=>setUnfocused(false);media.addEventListener("change",change);document.addEventListener("visibilitychange",visibility);window.addEventListener("blur",blur);window.addEventListener("focus",focus);return()=>{media.removeEventListener("change",change);document.removeEventListener("visibilitychange",visibility);window.removeEventListener("blur",blur);window.removeEventListener("focus",focus);void audio.current?.close().catch(()=>{});};},[]); useEffect(()=>{document.title=run?`${COURTS[run.area].title} · Familiar`:"Pocket Harbor · Familiar";},[run?.area]); + useEffect(()=>{if(!run||!worldReady||showPassage||showTideRun||surface||session?.state.review)return;const frame=requestAnimationFrame(()=>gameRef.current?.focus({preventScroll:true}));return()=>cancelAnimationFrame(frame);},[!!run,worldReady,showPassage,showTideRun]); useEffect(()=>{ const card=departureRef.current,game=gameRef.current;if(!card||!game)return; const measure=()=>{if(card.getClientRects().length)game.style.setProperty("--exp-harbor-feedback-bottom",`${game.getBoundingClientRect().bottom-card.getBoundingClientRect().top+12}px`);}; @@ -248,7 +251,7 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in }); return()=>{current=false;leaseRef.current="waiting";cancelAnimationFrame(frame);release?.();}; },[desiredKey,leaseAttempt]); - useEffect(()=>{if(surface||session?.state.review){if(!panelOpen.current&&!trigger.current)trigger.current=opener();panelOpen.current=true;const frame=requestAnimationFrame(()=>panelRef.current?.focus({preventScroll:true}));return()=>cancelAnimationFrame(frame);}if(panelOpen.current){panelOpen.current=false;const opener=trigger.current;trigger.current=null;if(restoreInspectFocus.current){restoreInspectFocus.current=false;document.querySelector(".exp-inspect-button")?.focus({preventScroll:true});}else if(opener?.isConnected)opener.focus({preventScroll:true});else (document.querySelector(".exp-departure .exp-primary:not(:disabled)")??document.querySelector(".exp-departure-buttons button:not(:disabled)")??document.querySelector(".exp-header-actions button"))?.focus({preventScroll:true});}},[surface,session?.state.review?.id,worldReady]); + useEffect(()=>{if(surface||session?.state.review){if(!panelOpen.current&&!trigger.current)trigger.current=opener();panelOpen.current=true;const frame=requestAnimationFrame(()=>panelRef.current?.focus({preventScroll:true}));return()=>cancelAnimationFrame(frame);}if(panelOpen.current){panelOpen.current=false;const opener=trigger.current;trigger.current=null;if(restoreInspectFocus.current){restoreInspectFocus.current=false;document.querySelector(".exp-inspect-button")?.focus({preventScroll:true});}else if(opener?.isConnected&&(opener!==gameRef.current||run))opener.focus({preventScroll:true});else if(run)gameRef.current?.focus({preventScroll:true});else (document.querySelector(".exp-departure .exp-primary:not(:disabled)")??document.querySelector(".exp-departure-buttons button:not(:disabled)")??gameRef.current)?.focus({preventScroll:true});}},[surface,session?.state.review?.id,worldReady]); useEffect(()=>{if(!surface&&!session?.state.review)return;const trap=(event:KeyboardEvent)=>{if(event.key!=="Tab")return;const panel=panelRef.current;if(!panel)return;const targets=[...panel.querySelectorAll('button:not(:disabled),a[href],input:not(:disabled),select:not(:disabled),[tabindex="0"]')].filter(n=>n.getClientRects().length);if(!targets.length){event.preventDefault();panel.focus();return;}const first=targets[0]!,last=targets.at(-1)!;if(event.shiftKey&&(document.activeElement===first||document.activeElement===panel)){event.preventDefault();last.focus();}else if(!event.shiftKey&&(document.activeElement===last||document.activeElement===panel)){event.preventDefault();first.focus();}};window.addEventListener("keydown",trap);return()=>window.removeEventListener("keydown",trap);},[surface,session?.state.review?.id]); function persist(next:LocalSave){if(leaseRef.current!=="held"){setNotice("This expedition is open in another tab. Finish there, or close that tab and check again.");return false;}try{writeLocal(next,keyRef.current);saveRef.current=next;setSave(next);setProblem("");return true;}catch(error){setProblem(error instanceof Error?error.message:"This browser could not save the move. No new action was taken.");return false;}} @@ -308,13 +311,19 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in useEffect(()=>{const keys=(event:KeyboardEvent)=>{ if(showPassage||showTideRun)return; if(event.key==="Escape"){closePanel();return;} - if(event.repeat||event.isComposing||event.altKey||event.ctrlKey||event.metaKey||event.shiftKey)return; - if(pausedRef.current)return; + if(event.repeat||event.isComposing||event.altKey||event.ctrlKey||event.metaKey||pausedRef.current||!saveRef.current.active)return; const target=event.target instanceof Element?event.target:null; - if(target?.closest("input,textarea,select,[contenteditable]:not([contenteditable=false]),dialog,[role=dialog],[role=slider],[role=tablist]"))return; - if((event.key===" "||event.key==="Enter")&&target?.closest("button,a"))return; - const map:Record={ArrowUp:"step:north",ArrowDown:"step:south",ArrowLeft:"step:west",ArrowRight:"step:east",w:"step:north",s:"step:south",a:"step:west",d:"step:east"," ":"wait",r:"return"}; - let selected:Command|undefined=map[event.key];if(event.key==="e"){const state=saveRef.current.active?.state,available=state?legalCommands(state):[];selected=available.find(c=>/^(take:|reel:)/.test(c))??available.find(c=>c==="turn:vane");} + if(!target||!gameRef.current?.contains(target)||!gameRef.current.contains(document.activeElement))return; + if(target.closest("button,a,summary,input,textarea,select,[contenteditable]:not([contenteditable=false]),dialog,[role=dialog],[role=slider],[role=tablist]"))return; + const key=event.key.toLowerCase(); + pressed.current=null; + let selected:Command|null=movementKey(event.key)??(key===" "?"wait":key==="r"?"return":null); + if(key==="i"){if(!busyRef.current){event.preventDefault();open("inspect");}return;} + if(key==="e"){ + const state=saveRef.current.active?.state,available=state?legalCommands(state):[]; + selected=available.find(c=>/^(take:|reel:)/.test(c))??available.find(c=>c==="turn:vane")??null; + if(!selected&&available.some(c=>c.startsWith("lure:"))&&!busyRef.current){event.preventDefault();open("lantern");return;} + } if(selected){event.preventDefault();command(selected);} };window.addEventListener("keydown",keys);return()=>window.removeEventListener("keydown",keys);},[command,showPassage,showTideRun]); function inspect(position:Position){ @@ -339,8 +348,8 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in function target(position:Position){const state=saveRef.current.active?.state;if(!state)return;const input=commandAt(state,position);if(input)command(input);else inspect(position);} function hover(position:Position|null){if(busyRef.current)return;const state=saveRef.current.active?.state;setFocused(position&&state?commandAt(state,position):null);} /** Safari never focuses a clicked button, so fall back to the last button pressed. */ - function opener(){const active=document.activeElement;return active instanceof HTMLElement&&active!==document.body?active:pressed.current?.isConnected?pressed.current:null;} - function open(place:HomePlace|"menu"|"guide"|"lantern"|"inspect"|"crossings"|"chart"|"tide"|"court-tide"|"log"|"home"){if(!panelOpen.current)trigger.current=opener();if(place==="mochi"){setResting(true);setGreeting(n=>n+1);return;}setResting(false);buffer.current=null;restoreInspectFocus.current=place==="inspect";setSurface(place);} + function opener(){const active=document.activeElement;return active instanceof HTMLElement&&active!==document.body&&active!==gameRef.current?active:pressed.current?.isConnected?pressed.current:active instanceof HTMLElement&&active===gameRef.current?active:null;} + function open(place:HomePlace|"menu"|"guide"|"lantern"|"inspect"|"crossings"|"chart"|"tide"|"court-tide"|"log"|"home"){if(!panelOpen.current)trigger.current=opener();if(place==="mochi"){setResting(true);setGreeting(n=>n+1);return;}setResting(false);buffer.current=null;restoreInspectFocus.current=place==="inspect"&&trigger.current!==gameRef.current;setSurface(place);} function closePanel(){const controller=sessionRef.current;if(controller?.state.review){if(controller.state.busy)return;controller.cancelReview();}setSurface(null);} function request(intent:WorldIntent){void sessionRef.current?.review(intent).catch(()=>{/* The controller keeps the actual failure and original operation visible. */});} function restore(restoration:"beacon"|"signal"){ @@ -446,8 +455,8 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in onFinish={finishPassage} onToggleSound={()=>void toggleSound()} onLeave={()=>backFromPassage({...passage,active:null},"The line is coiled at home. You can choose another crossing.")}/> {passageError&&

{passageError}

} ; - return
{pressed.current=(event.target as Element).closest("button");}} data-testid="expedition-game" data-mode={run?"court":"harbor"} data-busy={busy} data-lease={lease} data-content={CONTENT_VERSION} data-beat={lastBeat}> - {lease!=="waiting"&&{setFault(message);buffer.current=null;}} onReady={()=>setReadySceneKey(sceneKey)}/>} + return
{pressed.current=(event.target as Element).closest("button,summary");if(event.target instanceof HTMLCanvasElement)gameRef.current?.focus({preventScroll:true});}} data-testid="expedition-game" data-mode={run?"court":"harbor"} data-busy={busy} data-lease={lease} data-content={CONTENT_VERSION} data-beat={lastBeat}> + {lease!=="waiting"&&{if(pausedRef.current||!worldActions.includes(action))return;if(action==="lantern"){if(!busyRef.current)open("lantern");}else if(action!=="ride"&&action!=="listen"&&action!=="ring")command(action);}} onCommand={command} onTarget={target} onInspect={inspect} onHover={hover} onHome={open} onSettled={settled} onBeat={beat} onFault={message=>{setFault(message);buffer.current=null;}} onReady={()=>setReadySceneKey(sceneKey)}/>} {!worldReady&&!fault&&

familiar.

Unpacking the harbor.

Opening the artwork. Mochi’s saved moves are safe.

Reload Familiar
} {worldReady&&<>
familiar.{authority}
{run?COURTS[run.area].title:"Pocket Harbor"}
{!run&&}{!run&&!surface&&!session?.state.review&&}
@@ -482,12 +491,12 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in } - {run&&!surface&&!fault&&!session?.state.review&&
{tideCard&&tideRun&&
{cardStatus(tideCard,tideRun).includes("slipped")&&}
}
{feedback}

{objective}

{shownForecast}

{(["north","west","east","south"] as const).map(direction=>)}
{pickups.map(input=>button(input))}{run.tool==="lantern"&&interactionLegal.some(c=>c.startsWith("lure:"))&&}{!pickups.length&&!interactionLegal.includes("return")&&!interactionLegal.some(c=>c.startsWith("lure:"))&&

{busy?"Mochi finishes this moment first. One next direction can wait.":run.cargo.length?`${run.cargo.map(i=>names[i]).join(" + ")} secured. Reach the center dock to return.`:"Route a surge to open a shell and move the bridge."}

}
{interactionLegal.includes("return")&&
{button("return")}
}
} + {run&&!surface&&!fault&&!session?.state.review&&
{tideCard&&tideRun&&
{cardStatus(tideCard,tideRun).includes("slipped")&&}
}

{objective}

{shownForecast}

{feedback}
{(["north","west","east","south"] as const).map(direction=>)}
{pickups.map(input=>button(input))}{run.tool==="lantern"&&interactionLegal.some(c=>c.startsWith("lure:"))&&}{!pickups.length&&!interactionLegal.includes("return")&&!interactionLegal.some(c=>c.startsWith("lure:"))&&

{busy?"Mochi finishes this moment first. One next direction can wait.":run.cargo.length?`${run.cargo.map(i=>names[i]).join(" + ")} secured. Reach the center dock to return.`:"Route a surge to open a shell and move the bridge."}

}
{interactionLegal.includes("return")&&
{button("return")}
}
} {(!run||surface||fault||session?.state.review)&&feedback} {(problem||activeReturn&&!busy)&&

{problem||(finishing?"Keeping the original return safe…":"Mochi’s return is ready to save.")}

{activeReturn&&}{!corrupt&&!activeReturn&&}
} {(lease==="blocked"||lease==="unavailable")&&

{lease==="blocked"?"This expedition is open in another tab. Finish there, or close that tab before continuing here.":"This browser cannot safely coordinate saved expeditions. Web Locks support is required; no move has been taken."}

{lease==="blocked"&&}
} {(surface||session?.state.review)&&
- {session?.state.review?<>

{session.state.review.title}

{session.state.review.description}

{session.state.review.costs.length>0&&
    {session.state.review.costs.map(cost=>
  • {cost}
  • )}
}:surface==="account"?<>

Keep your harbor

{accountPanel??

Recoverable account controls are not connected to this local preview. This visit does not prove ownership or device recovery.

}:surface==="menu"?<>

A moment at the water’s edge.

Play at your own pace. Only accepted decisions advance the tide.

{!run&&}{logBook.length>0&&}{sound&&
Sound mix
}{save.active?.season&&}:surface==="lantern"?<>

A light on the water.

Choose a source. The wind-wheel, when present, determines its exit.

{(["left","center","right"] as const).map(lane=>)}:surface==="inspect"&&run?:surface==="guide"?<>

Read the water.

Tap a glowing neighboring platform, use the arrow keys or W A S D, or use the direction buttons. Crossing the open bridge is one decision.

Low: choose your footing. Rising: your resulting column becomes the source. Surge: act first, then the wave opens that column’s bridge and shell. Standing in the wave washes Mochi down one platform.

Rope retrieves an exposed lens or vane from two steps away. Lantern redirects a marked surge. A living moth needs two pack slots. Reach the center dock to return before 24 decisions.

{run?.area==="wind"&&

Current channels: Left → {columns[run.orientation]}, Center → {columns[(1+run.orientation)%3]}, Right → {columns[(2+run.orientation)%3]}. The cradle needs Left and Center charged and wheel alignment zero.

}

E uses a nearby object; Space waits; R returns at the dock. Right-click or hold a world target to inspect for free. Inspection and menus spend no turns.

:surface==="chart"?

{session.state.review.title}

{session.state.review.description}

{session.state.review.costs.length>0&&
    {session.state.review.costs.map(cost=>
  • {cost}
  • )}
}:surface==="account"?<>

Keep your harbor

{accountPanel??

Recoverable account controls are not connected to this local preview. This visit does not prove ownership or device recovery.

}:surface==="menu"?<>

A moment at the water’s edge.

Play at your own pace. Only accepted decisions advance the tide.

{!run&&}{logBook.length>0&&}{sound&&
Sound mix
}{save.active?.season&&}:surface==="lantern"?<>

A light on the water.

Choose a source. The wind-wheel, when present, determines its exit.

{(["left","center","right"] as const).map(lane=>)}:surface==="inspect"&&run?:surface==="guide"?<>

Read the water.

Swipe on the court or tap a glowing neighboring platform. On a keyboard, use WASD or the arrow keys. Crossing the open bridge is one decision. Optional Button controls keep every action available without gestures.

Low: choose your footing. Rising: your resulting column becomes the source. Surge: act first, then the wave opens that column’s bridge and shell. Standing in the wave washes Mochi down one platform.

Rope retrieves an exposed lens or vane from two steps away. Lantern redirects a marked surge. A living moth needs two pack slots. Reach the center dock to return before 24 decisions.

{run?.area==="wind"&&

Current channels: Left → {columns[run.orientation]}, Center → {columns[(1+run.orientation)%3]}, Right → {columns[(2+run.orientation)%3]}. The cradle needs Left and Center charged and wheel alignment zero.

}

Tap Wait beside Mochi, or Home at the dock to come home. E uses a nearby object or opens the lantern; Space waits; R returns at the dock; I inspects. Right-click or hold a world target to inspect for free. Inspection and menus spend no turns.

:surface==="chart"?{setArea(choice);open(!savedMode&&home.lit&&choice==="beacon"?"court-tide":"sail");}} onCrossing={departPassage} onRepair={()=>open("beacon")} onRest={()=>{setSurface(null);setGreeting(0);setResting(true);if(sound)audio.current?.playMusic("harbor");}}/>:surface==="crossings"?<>

The harbor crossing

diff --git a/web/src/expedition/PassageGame.tsx b/web/src/expedition/PassageGame.tsx index cc847dd..56e7742 100644 --- a/web/src/expedition/PassageGame.tsx +++ b/web/src/expedition/PassageGame.tsx @@ -2,10 +2,11 @@ import { useEffect, useMemo, useRef, useState } from "react"; import World from "./World"; import { commandName, forecast } from "./Inspect"; import { phaseOf } from "./engine"; -import { commandAt } from "./input"; +import { commandAt, movementKey } from "./input"; +import ControlHints from "./ControlHints"; import { applyPassage, canWatchMoth, PASSAGE_LANDINGS, passageCommands, passageDelivered, type PassageCommand, type PassageJob, type PassageState, type PassageTransition } from "./passage"; import type { HarborAudio } from "./audio"; -import type { WorldSnapshot } from "./scene"; +import type { WorldAction, WorldSnapshot } from "./scene"; import { TURN_LIMIT, type CourtEvent, type CourtTransition, type Direction, type Position } from "./types"; import "./passage-game.css"; @@ -62,7 +63,7 @@ export default function PassageGame({job,initial,mothHome,reduced,sound,audio,on const [away,setAway]=useState(document.hidden),[notice,setNotice]=useState(""),[retry,setRetry]=useState(null); const [panel,setPanel]=useState<"inspect"|"leave"|null>(null),[choice,setChoice]=useState(null); const [spot,setSpot]=useState(null),[hover,setHover]=useState(null); - const dialog=useRef(null),opener=useRef(null); + const dialog=useRef(null),opener=useRef(null),gameRef=useRef(null); const inspectButton=useRef(null),harborButton=useRef(null); const busy=!!result,terminal=done(state),paused=away||blocked||!!panel||!!fault; const legal=passageCommands(state),landings=PASSAGE_LANDINGS[job]; @@ -73,7 +74,8 @@ export default function PassageGame({job,initial,mothHome,reduced,sound,audio,on const passage=useMemo(()=>({job,stage:state.stage,watched:state.watched,mothHome,rode:last==="ride", archOpen:state.archOpen,bellRigged:state.bellRigged,heardBell:state.heardBell,pullSpent,listened:last==="listen",rang:last==="ring"}), [job,state.stage,state.watched,mothHome,state.archOpen,state.bellRigged,state.heardBell,pullSpent,last]); - const snapshot=useMemo(()=>({court:state.court,home,reducedMotion:reduced,previewCommand:isPassageAction(hover)?null:hover,previewWave,passage}),[state.court,reduced,hover,previewWave,passage]); + const worldActions=useMemo(()=>{const available=passageCommands(state);return (["wait","return","turn:vane","ride","listen","ring"] as const).filter(action=>available.includes(action));},[state]); + const snapshot=useMemo(()=>({court:state.court,home,reducedMotion:reduced,previewCommand:isPassageAction(hover)?null:hover,previewWave,passage,worldActions}),[state.court,reduced,hover,previewWave,passage,worldActions]); const animation=useMemo(()=>result?{before:result.before.court,after:result.after.court,events:result.events}:null,[result]); const inspection=choice?applyPassage(state,choice):null; @@ -83,11 +85,12 @@ export default function PassageGame({job,initial,mothHome,reduced,sound,audio,on return ()=>{document.removeEventListener("visibilitychange",show);window.removeEventListener("blur",hide);window.removeEventListener("focus",show);}; },[]); useEffect(()=>{ - if(!panel){opener.current?.focus({preventScroll:true});opener.current=null;return;} + if(!panel){if(opener.current){(opener.current.isConnected?opener.current:gameRef.current)?.focus({preventScroll:true});opener.current=null;}return;} const element=dialog.current; element?.showModal(); return ()=>element?.close(); },[panel]); + useEffect(()=>{if(!ready||panel)return;const frame=requestAnimationFrame(()=>gameRef.current?.focus({preventScroll:true}));return()=>cancelAnimationFrame(frame);},[ready]); function take(command:PassageCommand){ if(!ready||paused||pending.current||done(current.current)||document.hidden)return; @@ -116,17 +119,17 @@ export default function PassageGame({job,initial,mothHome,reduced,sound,audio,on } setNotice(consequence(accepted));pending.current=null;setResult(null); } - function inspect(position:Position|null=null){ + function inspect(position:Position|null=null,source:HTMLElement|null=gameRef.current){ if(!ready||paused||pending.current||done(current.current))return; - opener.current=inspectButton.current; + opener.current=source; setChoice(null);setSpot(position);setPanel("inspect"); } const contextAction=legal.find(isPassageAction); function actionAt(position:Position):PassageCommand|null{ if((contextAction==="listen"||contextAction==="ring")&&at(position,state.court.position))return contextAction; + if(contextAction==="ride"&&at(position,landings.arrival))return "ride"; const cmd=commandAt(state.court,position); - if(cmd&&legal.includes(cmd))return cmd; - return contextAction==="ride"&&at(position,landings.arrival)?"ride":null; + return cmd&&legal.includes(cmd)?cmd:null; } function target(position:Position){ const cmd=actionAt(position); @@ -141,12 +144,13 @@ export default function PassageGame({job,initial,mothHome,reduced,sound,audio,on } useEffect(()=>{ function keys(event:KeyboardEvent){ - if(event.isComposing||event.repeat||event.metaKey||event.ctrlKey||event.altKey||event.shiftKey||panel|| - (event.target instanceof Element&&event.target.closest('input,textarea,select,[contenteditable=true],dialog')))return; + if(event.isComposing||event.repeat||event.metaKey||event.ctrlKey||event.altKey||panel)return; + const target=event.target instanceof Element?event.target:null; + if(!target||!gameRef.current?.contains(target)||!gameRef.current.contains(document.activeElement))return; + if(target.closest('button,a,summary,input,textarea,select,[contenteditable]:not([contenteditable=false]),dialog,[role=dialog],[role=slider],[role=tablist]'))return; const key=event.key.toLowerCase(); - if(key===" "&&event.target instanceof Element&&event.target.closest("button,a"))return; - const commands:Partial>={arrowup:"step:north",w:"step:north",arrowdown:"step:south",s:"step:south",arrowleft:"step:west",a:"step:west",arrowright:"step:east",d:"step:east"," ":"wait",e:contextAction,r:"return"}; - const cmd=commands[key];if(!cmd&&key!=="i")return; + const cmd=movementKey(event.key)??(key===" "?"wait":key==="e"?contextAction:key==="r"?"return":null); + if(!cmd&&key!=="i")return; event.preventDefault(); if(cmd)take(cmd);else inspect(); } @@ -161,10 +165,10 @@ export default function PassageGame({job,initial,mothHome,reduced,sound,audio,on else if(watch)invitation="Mochi faces the moth in the still reeds. Wait to watch together."; const placeHint=spot&&at(spot,landings.departure)?"Bram starts this trip here.":spot&&at(spot,landings.arrival)?"This is where Bram’s trip ends.":null; const finishText=state.court.outcome==="rescued"?"Bram has Mochi safe.":passageDelivered(state)?job==="bell"?"The supplies reached the worksite.":"Bram’s skiff is home.":"A safe return."; - return
+ return
{if(event.target instanceof HTMLCanvasElement)gameRef.current?.focus({preventScroll:true});}} className="exp-game passage-game" data-mode="court" data-testid="passage-game" data-job={job} data-stage={state.stage} data-turn={turn} data-outcome={state.court.outcome} data-busy={busy} data-watched={state.watched} data-heard-bell={state.heardBell} data-bell-rigged={state.bellRigged} data-pull-spent={pullSpent}> setReady(true)} onFault={message=>{setFault(message);setReady(false);pending.current=null;setResult(null);}} - onBeat={beat} onSettled={settle} onCommand={take} onTarget={target} onInspect={inspect} onHome={()=>{}} + onBeat={beat} onSettled={settle} onAction={action=>{if(action!=="lantern"&&worldActions.includes(action))take(action);}} onCommand={take} onTarget={target} onInspect={inspect} onHome={()=>{}} onHover={pos=>{if(!busy&&!panel)setHover(pos?actionAt(pos):null);}}/>
familiar.Saved on this device

{places[job]}

@@ -177,9 +181,9 @@ export default function PassageGame({job,initial,mothHome,reduced,sound,audio,on {state.heardBell&&!state.bellRigged&&

{state.court.outcome==="returned"?"Tell Bram what you heard. He can rig a bell pull at the far-center landing before your next outing.":"Bram couldn’t rig a pull on this trip. You can visit the hollow arch again."}

}
:
-

{objective(state)}

-

{!hover&&invitation?invitation:localForecast}

+

{objective(state)}

{!hover&&invitation?invitation:localForecast}

Mochi is at the {where(state.court.position)}. The bridge is at {channels[state.court.bridge]}. +
{directions.map(dir=>{const cmd=`step:${dir}` as const;return ;})} @@ -188,8 +192,9 @@ export default function PassageGame({job,initial,mothHome,reduced,sound,audio,on disabled={!ready||paused||busy} onMouseEnter={()=>setHover(contextAction)} onMouseLeave={()=>setHover(null)} onFocus={()=>setHover(contextAction)} onBlur={()=>setHover(null)} onClick={()=>take(contextAction)}>{name(contextAction)}} {legal.includes("return")&&} - {retry&&}
+
+ {retry&&}
}
{notice}
{panel&&{event.preventDefault();setPanel(null);}}> diff --git a/web/src/expedition/World.tsx b/web/src/expedition/World.tsx index 0274d52..254ba37 100644 --- a/web/src/expedition/World.tsx +++ b/web/src/expedition/World.tsx @@ -1,6 +1,6 @@ import { useEffect, useRef, useState } from "react"; import type { Command, CourtEvent, CourtTransition, Position } from "./types"; -import type { ExpeditionScene, HomePlace, WorldSnapshot } from "./scene"; +import type { ExpeditionScene, HomePlace, WorldSnapshot, WorldAction } from "./scene"; export interface ExpeditionWorldProps { snapshot:WorldSnapshot; @@ -8,6 +8,7 @@ export interface ExpeditionWorldProps { presentationId:number; paused:boolean; onCommand:(command:Command)=>void; + onAction:(action:WorldAction)=>void; onInspect:(position:Position)=>void; onTarget:(position:Position)=>void; onHover:(position:Position|null)=>void; @@ -20,7 +21,7 @@ export interface ExpeditionWorldProps { export default function World(props:ExpeditionWorldProps){ const mount=useRef(null),scene=useRef(null),current=useRef(props); - const [ready,setReady]=useState(false),[tiles,setTiles]=useState([]); + const [ready,setReady]=useState(false),[tiles,setTiles]=useState([]),[actions,setActions]=useState([]); current.current=props; useEffect(()=>{ let alive=true,game:import("phaser").Game|undefined; @@ -28,23 +29,34 @@ export default function World(props:ExpeditionWorldProps){ void Promise.all([import("phaser"),import("./scene")]).then(([{default:Phaser},{ExpeditionScene}])=>{ if(!alive||!mount.current)return; const next=new ExpeditionScene(current.current.snapshot,{ - command:command=>current.current.onCommand(command),target:position=>current.current.onTarget(position),inspect:position=>current.current.onInspect(position),hover:position=>current.current.onHover(position),home:place=>current.current.onHome(place), + command:command=>current.current.onCommand(command),action:action=>current.current.onAction(action),target:position=>current.current.onTarget(position),inspect:position=>current.current.onInspect(position),hover:position=>current.current.onHover(position),home:place=>current.current.onHome(place), ready:()=>{if(!alive)return;setReady(true);current.current.onReady();next.setGated(current.current.paused);},fault:message=>{if(alive)current.current.onFault(message);}, - beat:(event,index)=>{if(alive)current.current.onBeat(event,index);},settled:id=>{if(alive)current.current.onSettled(id);},geometry:geometry=>{if(alive)setTiles([...geometry]);}, + beat:(event,index)=>{if(alive)current.current.onBeat(event,index);},settled:id=>{if(alive)current.current.onSettled(id);},geometry:(geometry,actions=[])=>{if(alive){setTiles([...geometry]);setActions([...actions]);}}, });scene.current=next; - game=new Phaser.Game({type:Phaser.AUTO,parent:mount.current,width:mount.current.clientWidth,height:mount.current.clientHeight,transparent:true,antialias:true,banner:false,audio:{noAudio:true},loader:{imageLoadType:"HTMLImageElement"},scene:next,scale:{mode:Phaser.Scale.RESIZE,autoCenter:Phaser.Scale.CENTER_BOTH},input:{keyboard:false}}); + // CSS touch-action owns scrolling; a cancelled native touch may not be cancelable. + game=new Phaser.Game({type:Phaser.AUTO,parent:mount.current,width:mount.current.clientWidth,height:mount.current.clientHeight,transparent:true,antialias:true,banner:false,audio:{noAudio:true},loader:{imageLoadType:"HTMLImageElement"},scene:next,scale:{mode:Phaser.Scale.RESIZE,autoCenter:Phaser.Scale.CENTER_BOTH},input:{keyboard:false,touch:{capture:false}}}); game.canvas.setAttribute("aria-hidden","true");game.canvas.addEventListener("webglcontextlost",lost); }).catch(()=>{if(alive)current.current.onFault("The playfield could not open. Your saved harbor is safe. Retry the scene.");}); return()=>{alive=false;scene.current=null;if(game){game.canvas.removeEventListener("webglcontextlost",lost);game.destroy(true);}}; },[]); useEffect(()=>{if(ready)scene.current?.setSnapshot(props.snapshot,props.transition,props.presentationId);},[ready,props.snapshot,props.transition,props.presentationId]); useEffect(()=>{scene.current?.setGated(props.paused);},[props.paused]); + useEffect(()=>{ + if(!ready)return; + let frame=0; + const refresh=()=>{cancelAnimationFrame(frame);frame=requestAnimationFrame(()=>scene.current?.refreshLayout());}; + const observer=new ResizeObserver(refresh); + if(mount.current)observer.observe(mount.current); + mount.current?.closest(".exp-game")?.querySelectorAll(".exp-command-tray,.exp-hud,.exp-feedback").forEach(element=>observer.observe(element)); + refresh(); + return()=>{cancelAnimationFrame(frame);observer.disconnect();}; + },[ready,!!props.snapshot.court,props.paused]); const {passage,court,home}=props.snapshot; - let description=court?"Spatial tide court. Equivalent movement and interaction controls follow.":"Mochi and Bram at Pocket Harbor. Choose a place using the harbor controls."; + let description=court?"Spatial tide court. Swipe or tap the world, or use WASD and arrows. Hints and optional Button controls follow.":"Mochi and Bram at Pocket Harbor. Choose a place using the harbor controls."; if(passage&&court){ const delivered=passage.stage==="delivered",bell=passage.job==="bell"; const location=bell?(delivered?"far left work steps":"near left Bell Steps"):(delivered?"near right quay":"far right Reed Steps"); - description=`${bell?"Bram’s supplies":"The empty skiff"} at the ${location}. ${passage.watched?"Mochi and you watched the reeds. ":""}Movement and service controls follow.`; + description=`${bell?"Bram’s supplies":"The empty skiff"} at the ${location}. ${passage.watched?"Mochi and you watched the reeds. ":""}Swipe or tap the world, or use WASD and arrows. Hints and optional Button controls follow.`; if(passage.heardBell)description+=" Mochi heard the old bell in the far-left hollow."; if(passage.bellRigged)description+=` Bell pull at far center, ${passage.pullSpent?"used":"one pull available"}.`; }else if(!court&&home.services?.length){ @@ -52,5 +64,5 @@ export default function World(props:ExpeditionWorldProps){ if(home.services.includes("reed"))description+=" The Reed skiff is moored on the harbor side."; } if(!court&&home.heardBell)description+=" Bram has rigged the shore bell pull for future crossings."; - return
; + return
; } diff --git a/web/src/expedition/game.css b/web/src/expedition/game.css index 2f4642d..3481e8f 100644 --- a/web/src/expedition/game.css +++ b/web/src/expedition/game.css @@ -332,3 +332,101 @@ html:has(.exp-game),body:has(.exp-game){margin:0;width:100%;height:100%;overflow .exp-tray-reading{min-height:0;flex:1} .exp-tray-actions{flex:none} } + + +/* Hints leave the court to Mochi; the familiar buttons remain an explicit alternative. */ +.exp-control-hints{position:relative;display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:8px;pointer-events:none} +.exp-input-help{min-width:0} +.exp-game .exp-input-primary{margin:0;font-size:13px;line-height:1.35;font-weight:750} +.exp-game .exp-input-context{margin:3px 0 0;font-size:12px;line-height:1.3;color:var(--exp-secondary-ink)} +.exp-button-controls{pointer-events:auto;align-self:start} +.exp-button-controls>summary{min-height:44px;display:flex;align-items:center;padding:8px 4px;cursor:pointer;font-size:13px;font-weight:650;text-decoration:underline;text-underline-offset:3px;white-space:nowrap;list-style:none;touch-action:manipulation} +.exp-button-controls>summary::-webkit-details-marker{display:none} +.exp-button-controls>summary:focus-visible{outline:3px solid #2b5f4d;outline-offset:2px;border-radius:5px} +.exp-button-controls[open]>summary{color:#2b5f4d} +.exp-button-controls-body{position:absolute;bottom:calc(100% + 10px);right:0;width:320px;max-width:calc(100vw - 44px);max-height:min(340px,calc(100dvh - 200px));overflow-y:auto;overscroll-behavior:contain;padding:14px;border-radius:var(--exp-card-radius);background:var(--exp-card);box-shadow:var(--exp-card-shadow);scrollbar-color:#8b734c var(--exp-card);scroll-padding:8px;z-index:20;pointer-events:auto} +.exp-button-controls-body .exp-current-controls{display:flex;flex-direction:column;gap:10px} +.exp-button-controls-body .exp-directions{display:flex;justify-content:space-between;gap:5px;width:100%} +.exp-button-controls-body .exp-directions button{width:44px;height:44px;min-height:44px;flex:none} +.exp-button-controls-body .exp-context-actions{width:100%;min-height:0} +.exp-game .exp-button-controls-body .exp-context-actions button{min-height:44px} +.exp-button-controls-body .exp-context-actions>p{margin:0;font-size:12px;line-height:1.35} +.exp-game:not(.passage-game) .exp-command-tray{width:320px;padding:12px} +.exp-command-tray .exp-tray-actions{flex:none;padding-top:4px} +.exp-command-tray .exp-tray-scroll{max-height:112px} +.exp-command-tray .exp-feedback{margin-bottom:6px;padding-bottom:6px} +.exp-command-tray .exp-forecast{min-height:0;margin-bottom:6px!important} +.exp-game:focus{outline:none} +.exp-game:focus-visible::after{content:"";position:absolute;inset:5px;border:2px solid #fff5ce;border-radius:8px;pointer-events:none} +@media(max-width:899px) and (orientation:portrait){ + .exp-game:not(.passage-game) .exp-command-tray,.passage-game .exp-command-tray{left:max(10px,env(safe-area-inset-left));right:max(10px,env(safe-area-inset-right));width:auto;padding:8px 10px;gap:3px} + .exp-game:not(.passage-game) .exp-command-tray{max-height:156px} + .exp-command-tray .exp-tray-scroll{max-height:76px} + .exp-command-tray .exp-forecast{font-size:12px;line-height:1.3} + .exp-command-tray .exp-feedback{font-size:12px;line-height:1.3} + .exp-command-tray .exp-tray-reading>.tide-outing{margin-bottom:2px} + .exp-control-hints{gap:6px} + .exp-game .exp-input-primary{font-size:12px} + .exp-game .exp-input-context{font-size:12px;margin-top:2px} + .exp-button-controls>summary{font-size:12px;padding-inline:0} +} +@media(orientation:landscape) and (max-height:500px){ + .exp-game:not(.passage-game) .exp-command-tray,.passage-game .exp-command-tray{width:250px;padding:8px;overflow:visible} + .exp-command-tray .exp-tray-scroll{max-height:58px} + .exp-control-hints{display:block} + .exp-button-controls>summary{padding-block:4px;justify-content:flex-end} + .exp-button-controls-body{width:270px;max-height:calc(100dvh - 160px)} +} + +.exp-mast{z-index:12} +.exp-reading-copy{min-width:0;flex:1} +.exp-command-tray .exp-objective-row{align-items:center;gap:8px} +.exp-command-tray .exp-objective-row>.exp-inspect-button{flex:none} +@media(max-width:599px) and (max-height:600px) and (orientation:portrait){ + .exp-hud{top:72px;padding:6px 8px;gap:7px} + .exp-mochi-portrait{width:32px;height:32px;flex-basis:32px} + .exp-hud .exp-mochi-status h2{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)} + .exp-hud .exp-mochi-status>p{font-size:12px;margin-bottom:3px} + .exp-status-pips{gap:8px} +} + +@media(max-width:599px) and (max-height:550px) and (orientation:portrait){ + .exp-game .exp-home-places button{width:80px;min-height:44px;--exp-sign-y:114px} + .exp-home-places button>span{left:0;right:0;font-size:12px} + .exp-home-places small{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)} +} + +@media(max-width:599px) and (min-height:551px) and (max-height:650px) and (orientation:portrait){ + .exp-game .exp-home-places button{top:max(var(--exp-sign-y),144px)} +} +.exp-game .exp-phone-dock button{border-radius:12px} +@media(hover:none){ + .exp-game .exp-primary{border-radius:26px} +} +@media(max-width:899px) and (orientation:portrait){ + .exp-game .exp-home-places button{max-width:calc((100vw - 24px)/3)} +} +@media(max-width:359px) and (orientation:portrait){ + .exp-home-places button>span{font-size:12px} +} +@media(max-width:899px) and (orientation:portrait){ + .exp-game[data-mode=harbor] .exp-departure{min-width:0} + .exp-departure-heading>div{flex:1} + .exp-preparation{flex-wrap:wrap;white-space:normal} + .exp-preparation>span{white-space:nowrap} + .exp-departure-heading:has(>.tide-departure-stamp){display:grid;grid-template-columns:72px minmax(0,1fr);gap:4px 12px;margin-bottom:8px} + .exp-departure-heading:has(>.tide-departure-stamp)>div{display:contents} + .exp-departure-heading:has(>.tide-departure-stamp)>div>h1{grid-column:2;grid-row:1;margin:0} + .exp-departure-heading:has(>.tide-departure-stamp)>div>p{grid-column:2;grid-row:2} + .exp-departure-heading:has(>.tide-departure-stamp)>.tide-departure-stamp{grid-column:1;grid-row:1/3;align-self:center} + .exp-departure-heading:has(>.tide-departure-stamp) .exp-preparation{grid-column:1/-1;grid-row:3;width:100%;margin:0} +} + +.exp-harbor-home{pointer-events:none} +.exp-harbor-home>.exp-departure{pointer-events:auto} +.exp-command-tray .exp-objective-row>.exp-tray-scroll{flex:1;min-width:0} +@media(orientation:landscape) and (max-height:500px){ + .exp-game:not(.tide-run) .exp-control-hints{display:grid;grid-template-columns:minmax(0,1fr) auto} + .exp-game:not(.tide-run) .exp-command-tray .exp-tray-reading,.exp-game:not(.tide-run) .exp-command-tray .exp-objective-row{min-height:44px} + .exp-game:not(.tide-run) .exp-command-tray .exp-tray-scroll{max-height:44px} +} diff --git a/web/src/expedition/input.test.ts b/web/src/expedition/input.test.ts index 42d8ad5..30176e2 100644 --- a/web/src/expedition/input.test.ts +++ b/web/src/expedition/input.test.ts @@ -1,8 +1,34 @@ import { expect,test } from "bun:test"; import { applyCommand,startCourt } from "./engine"; -import { commandAt } from "./input"; +import { commandAt, movementKey, swipeCommand } from "./input"; import type { CourtState } from "./types"; +test("swipes resolve one dominant screen-axis step and reject noise or diagonals",()=>{ + expect(swipeCommand(0,-32)).toBe("step:north"); + expect(swipeCommand(0,32)).toBe("step:south"); + expect(swipeCommand(-32,0)).toBe("step:west"); + expect(swipeCommand(32,0)).toBe("step:east"); + expect(swipeCommand(31,0)).toBeNull(); + expect(swipeCommand(40,40)).toBeNull(); + expect(swipeCommand(48,32)).toBe("step:east"); + expect(swipeCommand(1000,0)).toBe("step:east"); + expect(swipeCommand(NaN,0)).toBeNull(); + expect(swipeCommand(0,Infinity)).toBeNull(); +}); +test("movement keys normalize letter case without taking native or interaction keys",()=>{ + for(const key of ["w","W","ArrowUp"])expect(movementKey(key)).toBe("step:north"); + for(const key of ["a","A","ArrowLeft"])expect(movementKey(key)).toBe("step:west"); + for(const key of ["s","S","ArrowDown"])expect(movementKey(key)).toBe("step:south"); + for(const key of ["d","D","ArrowRight"])expect(movementKey(key)).toBe("step:east"); + for(const key of ["Enter","Tab","Escape","e"," "])expect(movementKey(key)).toBeNull(); +}); +test("dock taps return only when already at the dock",()=>{ + const state=startCourt({area:"beacon",tool:"rope",banked:[]}); + expect(commandAt(state,{x:1,y:0})).toBe("return"); + expect(commandAt({...state,position:{x:1,y:1}},{x:1,y:0})).toBe("step:south"); + expect(commandAt({...state,outcome:"returned"},{x:1,y:0})).toBeNull(); +}); + test("clicking the open bridge or its far landing crosses in one canonical decision",()=>{ const state:CourtState={...startCourt({area:"beacon",tool:"rope",banked:[]}),position:{x:1,y:1}}; expect(commandAt(state,{x:1,y:2})).toBe("step:north"); diff --git a/web/src/expedition/input.ts b/web/src/expedition/input.ts index 055a4d9..42f8738 100644 --- a/web/src/expedition/input.ts +++ b/web/src/expedition/input.ts @@ -1,8 +1,26 @@ import { findPosition,legalCommands,stepDestination } from "./engine"; import type { Command,CourtState,Position } from "./types"; +export function swipeCommand(dx:number,dy:number):Command|null { + if(!Number.isFinite(dx)||!Number.isFinite(dy))return null; + const x=Math.abs(dx),y=Math.abs(dy); + if(Math.max(x,y)<32||Math.max(x,y)y?(dx>0?"step:east":"step:west"):(dy>0?"step:south":"step:north"); +} + +export function movementKey(key:string):Command|null { + switch(key.toLowerCase()){ + case "w":case "arrowup":return "step:north"; + case "s":case "arrowdown":return "step:south"; + case "a":case "arrowleft":return "step:west"; + case "d":case "arrowright":return "step:east"; + default:return null; + } +} + /** Pointer and accessible object controls resolve the same target, without pathfinding or state mutation. */ export function commandAt(state:CourtState,target:Position):Command|null { + if(target.x===1&&target.y===0&&legalCommands(state).includes("return"))return "return"; if(state.area==="wind"&&target.x===1&&target.y===3&&legalCommands(state).includes("turn:vane"))return "turn:vane"; for(const item of ["lens","moth","vane"] as const){ const position=findPosition(state,item);if(position?.x!==target.x||position.y!==target.y)continue; diff --git a/web/src/expedition/passage-game.css b/web/src/expedition/passage-game.css index 52594d0..875b64c 100644 --- a/web/src/expedition/passage-game.css +++ b/web/src/expedition/passage-game.css @@ -24,3 +24,12 @@ .passage-game .passage-header-actions button{font-size:12px;padding:7px;min-height:44px} .passage-game .exp-brand small{display:block;font:10px/1.3 "Figtree Variable",sans-serif;margin-top:3px} @media(max-width:420px){.passage-game h1.exp-place{max-width:61px;font-size:11px}.passage-game .exp-mast{gap:5px}.passage-game .exp-brand{font-size:22px!important;padding:6px 8px}.passage-game .passage-header-actions button{font-size:11px;padding:6px}} + +.passage-game .passage-tray{overflow:visible} +.passage-tray .exp-objective-row{margin-bottom:0} +.passage-tray .exp-forecast{font-size:12px;line-height:1.3;margin-bottom:4px!important} +.passage-tray .exp-button-controls-body .exp-context-actions{flex-direction:column;align-items:stretch} +@media(max-width:899px) and (orientation:portrait){ + .passage-game .passage-tray{max-height:156px} + .passage-tray .exp-objective{font-size:12px} +} diff --git a/web/src/expedition/scene.ts b/web/src/expedition/scene.ts index 360f8f4..1d81072 100644 --- a/web/src/expedition/scene.ts +++ b/web/src/expedition/scene.ts @@ -1,7 +1,7 @@ import Phaser from "phaser"; import { applyCommand, waveExit, walkable, findPosition } from "./engine"; import { COURTS } from "./rooms"; -import { commandAt } from "./input"; +import { commandAt, swipeCommand } from "./input"; import { PASSAGE_LANDINGS, type PassageJob, type PassageState } from "./passage"; import { MOCHI_GROUND, MOCHI_POSES, walkingPose, type MochiPoseName } from "../motion/mochi"; import { companionIdle, type Attention } from "./companion"; @@ -10,12 +10,15 @@ import type { Column, Command, CourtEvent, CourtState, CourtTransition, Find, Po const ART = "/assets/expedition/runtime/"; const ASSETS = { harbor:"harbor", mochi:"mochi-poses", keeper:"tidekeeper", shell:"shell", lens:"lens", moth:"moth", wave:"wave", bram:"bram" } as const; export type HomePlace = "sail" | "beacon" | "bram" | "workbench" | "satchel" | "account" | "mochi"; +export type WorldAction="wait"|"return"|"turn:vane"|"lantern"|"ride"|"listen"|"ring"; +export interface ActionAnchor {action:WorldAction;x:number;y:number;width:number;height:number} export type PassageView=Pick&{rode?:boolean;listened?:boolean;rang?:boolean;pullSpent?:boolean}; export interface HarborView { lit:boolean; signaled:boolean; moth:boolean; lantern:boolean; socket:"porch"|"dock";motif:"crest"|"moth";polished:boolean;relic:"lens"|"vane"|null;resting?:boolean;services?:readonly PassageJob[];watchedReeds?:boolean;heardBell?:boolean;greeting?:number } -export interface WorldSnapshot { court:CourtState|null; home:HarborView; reducedMotion:boolean;previewCommand:Command|null;previewWave?:{source:Column;exit:Column};passage?:PassageView|null } +export interface WorldSnapshot { court:CourtState|null; home:HarborView; reducedMotion:boolean;previewCommand:Command|null;previewWave?:{source:Column;exit:Column};passage?:PassageView|null;worldActions?:readonly WorldAction[] } export interface WorldHooks { command:(command:Command)=>void; target:(position:Position)=>void; + action:(action:WorldAction)=>void; inspect:(position:Position)=>void; hover:(position:Position|null)=>void; home:(place:HomePlace)=>void; @@ -23,7 +26,7 @@ export interface WorldHooks { fault:(message:string)=>void; beat:(event:CourtEvent, index:number)=>void; settled:(id:number)=>void; - geometry:(tiles:readonly {position:Position;x:number;y:number;width:number;height:number}[])=>void; + geometry:(tiles:readonly {position:Position;x:number;y:number;width:number;height:number}[],actions?:readonly ActionAnchor[])=>void; } export class ExpeditionScene extends Phaser.Scene { @@ -55,8 +58,10 @@ export class ExpeditionScene extends Phaser.Scene { private labels:Phaser.GameObjects.Text[]=[]; private cargo:Phaser.GameObjects.Image[]=[]; private surfaces:Phaser.GameObjects.Image[]=[]; - private hitAreas:Phaser.GameObjects.Zone[]=[]; - private presses=new Map(); + private hitAreas=new Map(); + private presses=new Map(); + private contacts=new Set(); + private multipleContacts=false; private epoch=0; private lastPresentation=0; private playing=false; @@ -65,6 +70,9 @@ export class ExpeditionScene extends Phaser.Scene { private idleElapsed=0; private idleScale={x:1,y:1}; private presentationSize:{w:number;h:number}|null=null; + private readingTop:number|null=null; + private layoutRequested=false; + private geometryFrame:number|null=null; private get w(){return this.presentationSize?.w??this.scale.width;} private get h(){return this.presentationSize?.h??this.scale.height;} @@ -115,34 +123,50 @@ export class ExpeditionScene extends Phaser.Scene { this.signalVane=this.add.image(0,0,"exp-vane").setOrigin(31/64,54/64).setDepth(7).setVisible(false); this.actorShadow=this.add.ellipse(0,0,50,13,0x342719,.25).setDepth(7); this.actor=this.add.sprite(0,0,"exp-mochi",12).setOrigin(.5,MOCHI_GROUND).setDepth(10); - this.actor.setInteractive({useHandCursor:true}).on("pointerdown",(pointer:Phaser.Input.Pointer)=>{ - if(!this.visual&&!this.gated&&this.onCanvas(pointer))this.presses.set(pointer.id,{target:"mochi",x:pointer.x,y:pointer.y,dragged:false}); - }).on("pointerup",(pointer:Phaser.Input.Pointer)=>{ - const press=this.presses.get(pointer.id);this.presses.delete(pointer.id); - if(!this.visual&&!this.gated&&!pointer.wasCanceled&&press?.target==="mochi"&&!press.dragged&& - Math.hypot(pointer.x-press.x,pointer.y-press.y)<=12&&(pointer.wasTouch||pointer.leftButtonReleased()))this.hooks.home("mochi"); - }); + this.actor.setInteractive({useHandCursor:true}).setData("homeTarget","mochi"); this.scale.on("resize",()=>{ + this.presses.clear(); if(this.playing&&this.presentationSize){const zoom=Math.min(this.scale.width/this.presentationSize.w,this.scale.height/this.presentationSize.h);this.cameras.main.setZoom(zoom).centerOn(this.presentationSize.w/2,this.presentationSize.h/2);} else{this.cameras.main.setZoom(1).setScroll(0,0);this.layout();} }); - this.events.once("shutdown",()=>{this.stopped=true;this.epoch++;}); this.visual=this.snapshot.court;this.shownPassage=this.snapshot.passage??null; this.input.mouse?.disableContextMenu(); - this.input.on("pointermove",(pointer:Phaser.Input.Pointer)=>{const press=this.presses.get(pointer.id);if(press&&Math.hypot(pointer.x-press.x,pointer.y-press.y)>12)press.dragged=true;}); - const release=(pointer:Phaser.Input.Pointer)=>this.presses.delete(pointer.id); - this.input.on("pointerup",release);this.input.on("pointerupoutside",release); + this.input.addPointer(1); + this.input.on("pointerdown",(pointer:Phaser.Input.Pointer,over:Phaser.GameObjects.GameObject[])=>this.press(pointer,over)); + this.input.on("pointerdownoutside",(pointer:Phaser.Input.Pointer)=>this.press(pointer,[])); + this.input.on("pointermove",(pointer:Phaser.Input.Pointer)=>{ + const press=this.presses.get(pointer.id),point=this.clientPoint(pointer); + if(press)press.excursion=Math.max(press.excursion,Math.hypot(point.x-press.x,point.y-press.y)); + }); + this.input.on("pointerup",(pointer:Phaser.Input.Pointer,over:Phaser.GameObjects.GameObject[])=>this.release(pointer,over)); + this.input.on("pointerupoutside",(pointer:Phaser.Input.Pointer)=>{this.presses.delete(pointer.id);this.contacts.delete(pointer.id);if(!this.contacts.size)this.multipleContacts=false;this.afterRelease();}); + const cancel=()=>{this.presses.clear();this.contacts.clear();this.multipleContacts=false;}; + const touchContacts=(event:TouchEvent)=>{if(event.touches.length>1||event.type==="touchcancel"){cancel();this.multipleContacts=event.touches.length>0;}else if(!event.touches.length){this.multipleContacts=false;this.contacts.clear();}}; + // Run after Phaser's touch listener; prevent its compatibility mouse click from repeating a hold or tap. + const preventMouse=(event:TouchEvent)=>{if(event.cancelable)event.preventDefault();}; + this.game.canvas.addEventListener("touchstart",preventMouse,{passive:false}); + window.addEventListener("blur",cancel);document.addEventListener("visibilitychange",cancel);this.game.canvas.addEventListener("pointercancel",cancel); + window.addEventListener("touchstart",touchContacts,true);window.addEventListener("touchend",touchContacts,true);window.addEventListener("touchcancel",touchContacts,true); + let cleaned=false; + const cleanup=()=>{ + if(cleaned)return;cleaned=true; + this.stopped=true;this.epoch++;cancel();this.contacts.clear();if(this.geometryFrame!==null)cancelAnimationFrame(this.geometryFrame); + this.game.canvas.removeEventListener("touchstart",preventMouse); + window.removeEventListener("blur",cancel);document.removeEventListener("visibilitychange",cancel);this.game.canvas.removeEventListener("pointercancel",cancel); + window.removeEventListener("touchstart",touchContacts,true);window.removeEventListener("touchend",touchContacts,true);window.removeEventListener("touchcancel",touchContacts,true); + }; + this.events.once("shutdown",cleanup);this.events.once("destroy",cleanup); this.layout();this.hooks.ready(); } /** Presentation coordinates are responsive. Logical cells and accepted state never resize. */ private field(){ const portrait=this.w<=900&&this.h>this.w; - if(portrait&&this.h<500){const top=144,bottom=this.h-166,width=this.w*.82;return{cx:this.w/2,width,top,bottom,dy:(bottom-top)/4,dx:width/3};} + if(portrait&&this.h<500){const top=144,bottom=Math.min(this.h-150,this.readingTop===null?Infinity:this.readingTop-24),width=this.w*.72;return{cx:this.w/2,width,top,bottom,dy:(bottom-top)/4,dx:width/3};} if(this.h<=500){const available=this.w-280,width=Math.max(240,Math.min(available*.91,760)),top=98,bottom=this.h-34;return{cx:available/2,width,top,bottom,dy:(bottom-top)/4,dx:width/3};} const top=portrait?(this.h<650?151:Math.max(200,this.h*.29)):this.h<500?122:Math.max(190,this.h*.31); - const bottom=portrait?this.h-264:this.h-72; - const width=Math.min(portrait?this.w*.84:this.h<500?this.w*.45:this.w*.50,760); + const bottom=portrait?Math.min(this.h-170,this.readingTop===null?Infinity:this.readingTop-48):this.h-72; + const width=Math.min(portrait?this.w*.72:this.h<500?this.w*.45:this.w*.50,760); return {cx:portrait?this.w*.5:this.h<500?this.w*.40:this.w*.45,width,top,bottom,dy:(bottom-top)/4,dx:width/3}; } point(position:Position){const f=this.field();return{x:f.cx+(position.x-1)*f.dx,y:f.bottom-position.y*f.dy};} @@ -209,10 +233,21 @@ export class ExpeditionScene extends Phaser.Scene { } } } - setGated(gated:boolean){this.gated=gated;if(gated)this.presses.clear();if(!this.actor)return;this.input.enabled=!gated;this.time.paused=gated;if(gated)this.tweens.pauseAll();else this.tweens.resumeAll();} + refreshLayout(){ + const parent=this.game.canvas.parentElement; + if(parent&&(this.scale.width!==parent.clientWidth||this.scale.height!==parent.clientHeight)){this.scale.setParentSize(parent.clientWidth,parent.clientHeight);return;} + if(this.scale.getParentBounds()){this.scale.refresh();return;} + if(this.playing||this.presses.size){this.layoutRequested=true;return;} + this.layoutRequested=false;this.layout(); + } + private afterRelease(){ + if(!this.layoutRequested||this.presses.size||this.geometryFrame!==null)return; + this.geometryFrame=requestAnimationFrame(()=>{this.geometryFrame=null;if(!this.stopped)this.refreshLayout();}); + } + setGated(gated:boolean){this.gated=gated;if(gated){this.presses.clear();this.contacts.clear();this.multipleContacts=false;}if(!this.actor)return;this.input.enabled=!gated;this.time.paused=gated;if(gated)this.tweens.pauseAll();else this.tweens.resumeAll();} private clearParts(){ for(const label of this.labels)label.destroy();this.labels=[]; - for(const zone of this.hitAreas)zone.destroy();this.hitAreas=[]; + for(const zone of this.hitAreas.values())zone.disableInteractive(); for(const find of this.finds.values())find.destroy();this.finds.clear(); for(const shell of this.shells.values())shell.destroy();this.shells.clear(); for(const item of this.cargo)item.destroy();this.cargo=[]; @@ -221,6 +256,11 @@ export class ExpeditionScene extends Phaser.Scene { private layout(){ if(!this.actor||this.stopped)return; this.presses.clear(); + if(!this.playing){ + this.layoutRequested=false; + const reading=this.game.canvas.closest(".exp-game")?.querySelector(".exp-command-tray"); + this.readingTop=reading?.getClientRects().length?reading.getBoundingClientRect().top-this.game.canvas.getBoundingClientRect().top:null; + } this.skiff.clear().setVisible(false);this.shoreBell.clear().setAngle(0); this.clearParts();this.ground.clear();this.shoreMarks.clear();this.homeProps.clear();this.bridgeArt.setAlpha(1);this.wheel.clear();this.forecast.clear();this.forecastLabel.setVisible(false);this.neighbors.clear();this.beam.clear().setAlpha(1); const court=this.visual; @@ -228,7 +268,7 @@ export class ExpeditionScene extends Phaser.Scene { this.backdrop.setPosition(this.w/2,this.h/2);this.fit(this.backdrop,this.w,this.h); this.keeper.setVisible(!!court);this.bram.setVisible(!court);this.bridgeArt.setVisible(!!court); this.signalVane.setVisible(!court&&this.snapshot.home.signaled); - if(!court){this.hooks.geometry([]);this.harbor();this.resetIdle();return;} + if(!court){this.actor.setData("worldAction",null);this.hooks.geometry([]);this.harbor();this.resetIdle();return;} const f=this.field(),tile=this.tileSize(); // Fixed short walks connect each bank. Only the long middle crossing changes with a surge. for(const y of [0,3])for(const x of [0,1,2] as const){const from=this.point({x,y}),to=this.point({x,y:y+1}),length=f.dy*1.35;const link=this.add.image(from.x,(from.y+to.y)/2,"exp-bridge").setDisplaySize(length/3,length).setDepth(.4);this.surfaces.push(link);} @@ -239,19 +279,16 @@ export class ExpeditionScene extends Phaser.Scene { else if(available)this.drawBridge(p.x,p.y,tile.width*.58,f.dy*1.65); else {this.ground.lineStyle(2,0xa8c8bd,.4);this.ground.strokeEllipse(p.x,p.y+6,tile.width*.6,tile.height*.45);} const hitHeight=Math.max(44,Math.min(tile.height+15,f.dy-2)); - const zone=this.add.zone(p.x,p.y,Math.max(44,tile.width),hitHeight).setInteractive({useHandCursor:true}).setDepth(16); - const target=`${x},${y}`; - zone.on("pointerdown",(pointer:Phaser.Input.Pointer)=>{if(!this.gated&&this.onCanvas(pointer))this.presses.set(pointer.id,{target,x:pointer.x,y:pointer.y,dragged:false});}); - zone.on("pointerup",(pointer:Phaser.Input.Pointer)=>{ - const press=this.presses.get(pointer.id);this.presses.delete(pointer.id); - if(this.gated||pointer.wasCanceled||!press||press.target!==target||press.dragged||Math.hypot(pointer.x-press.x,pointer.y-press.y)>12)return; - if(pointer.rightButtonReleased()||pointer.getDuration()>450)this.hooks.inspect(position); - else if(pointer.wasTouch||pointer.leftButtonReleased())this.hooks.target(position); - });this.hitAreas.push(zone); - zone.on("pointerover",()=>{if(!this.gated&&!this.playing)this.hooks.hover(position);});zone.on("pointerout",()=>this.hooks.hover(null)); + const key=`cell:${x},${y}`; + let zone=this.hitAreas.get(key); + if(!zone){ + zone=this.add.zone(p.x,p.y,Math.max(44,tile.width),hitHeight).setInteractive({useHandCursor:true}).setDepth(16).setData("cellTarget",position);this.hitAreas.set(key,zone); + zone.on("pointerover",()=>{if(!this.gated&&!this.playing)this.hooks.hover(position);});zone.on("pointerout",()=>this.hooks.hover(null)); + } + zone.setPosition(p.x,p.y).setSize(Math.max(44,tile.width),hitHeight).setInteractive(); + if(court.position.x===position.x&&court.position.y===position.y&&this.snapshot.worldActions?.includes("wait")&&!/^(take:|reel:)/.test(commandAt(court,position)??""))zone.disableInteractive(); targets.push({position,x:p.x,y:p.y,width:Math.max(44,tile.width),height:hitHeight}); } - this.hooks.geometry(targets); const portrait=this.w<=900&&this.h>this.w; const dock=this.point({x:1,y:0});if(!(portrait&&this.h<500&&court.position.x===1&&court.position.y===0))this.text(dock.x,dock.y+(this.h<500?-tile.height*.45:portrait?tile.height*.42:tile.height*.72),"DOCK",Math.min(14,this.w/28)); const keeperHeight=Math.min(this.h<500?f.top-(portrait?78:15):230,this.h*.26,portrait?this.w*(this.h<650?.38:.45):this.w*.52,portrait?f.top-(this.h<650?15:80):Infinity);this.keeper.setPosition(this.h<500&&!portrait?f.cx+Math.min(60,f.width*.18):portrait&&this.h<650?this.w*.72:f.cx,f.top-8).setDisplaySize(keeperHeight*1.32,keeperHeight); @@ -281,12 +318,90 @@ export class ExpeditionScene extends Phaser.Scene { if(court.area==="wind")this.windGate(court); if(this.shownPassage)this.passageCourt(court,this.shownPassage); const p=this.point(court.position); - this.actor.setPosition(p.x,p.y).setDisplaySize(this.actorSize(),this.actorSize()).setFlipX(false); + this.actor.setPosition(p.x,p.y).setDisplaySize(this.actorSize(),this.actorSize()).setFlipX(false).setData("worldAction",this.snapshot.worldActions?.includes("wait")?"wait":null); this.actorShadow.setPosition(p.x,p.y+2).setSize(this.actorSize()*.55,Math.max(4,this.actorSize()*.10)); const mothNearby=court.position.y>=3&&findPosition(court,"moth")!==null&&!this.shownPassage?.mothHome; const watching=this.shownPassage?.watched&&mothNearby&&court.position.x===1&&court.position.y===4; this.pose(watching?"relieved":court.locked!==null?"brace":mothNearby?"look-right":"curious"); this.drawCargo(court);this.paintHints(court);this.resetIdle(); + this.hooks.geometry(targets,this.actionTargets(court,targets)); + } + private clientPoint(pointer:Phaser.Input.Pointer){ + const event=pointer.event; + if("changedTouches" in event){ + const touch=Array.from(event.changedTouches).find(t=>t.identifier===pointer.identifier); + if(touch)return{x:touch.clientX,y:touch.clientY}; + } + return {x:(event as MouseEvent).clientX,y:(event as MouseEvent).clientY}; + } + private press(pointer:Phaser.Input.Pointer,over:Phaser.GameObjects.GameObject[]){ + this.contacts.add(pointer.id); + if(this.contacts.size>1){this.multipleContacts=true;this.presses.clear();} + if(this.gated||this.stopped||this.multipleContacts||!this.onCanvas(pointer))return; + const event=pointer.event,point=this.clientPoint(pointer),rect=this.game.canvas.getBoundingClientRect(); + const touch=pointer.wasTouch||("pointerType" in event&&event.pointerType==="pen"); + if(!touch&&!pointer.leftButtonDown()&&!pointer.rightButtonDown())return; + const target=over.find(object=>object.getData("cellTarget")||object.getData("worldAction")||!this.visual&&object.getData("homeTarget"))??null; + this.presses.set(pointer.id,{target,x:point.x,y:point.y,excursion:0,touch,edge:point.x-rect.left<24||rect.right-point.x<24}); + } + private release(pointer:Phaser.Input.Pointer,over:Phaser.GameObjects.GameObject[]){ + const press=this.presses.get(pointer.id);this.presses.delete(pointer.id);this.contacts.delete(pointer.id);this.afterRelease(); + const multiple=this.multipleContacts;if(!this.contacts.size)this.multipleContacts=false; + const point=this.clientPoint(pointer),canvas=this.game.canvas,rect=canvas.getBoundingClientRect(); + if(!press||this.gated||this.stopped||multiple||pointer.wasCanceled||!this.onCanvas(pointer)||document.hidden|| + point.xrect.right||point.yrect.bottom||document.elementFromPoint(point.x,point.y)!==canvas)return; + const excursion=Math.max(press.excursion,Math.hypot(point.x-press.x,point.y-press.y)); + if(press.touch&&this.visual?.outcome==="active"&&!press.edge){ + const command=swipeCommand(point.x-press.x,point.y-press.y); + if(command){this.hooks.command(command);return;} + } + if(excursion>12||!press.target||!over.includes(press.target))return; + const cell=press.target.getData("cellTarget") as Position|undefined; + const action=press.target.getData("worldAction") as WorldAction|undefined; + if(pointer.rightButtonReleased()||pointer.getDuration()>450){ + const position=cell??this.visual?.position; + if(position)this.hooks.inspect(position); + }else if(press.touch||pointer.leftButtonReleased()){ + if(action)this.hooks.action(action); + else if(cell)this.hooks.target(cell); + else if(!this.visual&&press.target.getData("homeTarget")==="mochi")this.hooks.home("mochi"); + } + } + private actionTargets(court:CourtState,tiles:Parameters[0]):ActionAnchor[]{ + const actions=this.snapshot.worldActions??[],anchors:ActionAnchor[]=[],f=this.field(),tile=this.tileSize(); + const labels:Record={wait:"Wait",return:"Home","turn:vane":"Turn",lantern:"Lure",ride:"Ride",listen:"Listen",ring:"Ring"}; + const canvas=this.game.canvas.getBoundingClientRect(); + const blocked=Array.from(this.game.canvas.closest(".exp-game")?.querySelectorAll(".exp-command-tray,.exp-hud,.exp-mast,.exp-feedback")??[]) + .filter(element=>element.getClientRects().length&&getComputedStyle(element).visibility!=="hidden") + .map(element=>{const rect=element.getBoundingClientRect();return{x:rect.left-canvas.left+rect.width/2,y:rect.top-canvas.top+rect.height/2,width:rect.width,height:rect.height};}); + const overlaps=(a:{x:number;y:number;width:number;height:number},b:typeof a)=>Math.abs(a.x-b.x)<(a.width+b.width)/2+2&&Math.abs(a.y-b.y)<(a.height+b.height)/2+2; + const cells=tiles.filter(target=>{const command=commandAt(court,target.position),self=target.position.x===court.position.x&&target.position.y===court.position.y;return command&&(!self||/^(take:|reel:)/.test(command));}); + for(const action of actions){ + let origin=this.point(court.position); + if(action==="return")origin=this.point({x:1,y:0}); + else if(action==="turn:vane")origin={x:this.wheel.x,y:this.wheel.y}; + else if(action==="lantern")origin={x:this.keeper.x,y:this.keeper.y}; + else if(action==="ride")origin={x:this.skiff.x,y:this.skiff.y}; + else if(action==="listen")origin={x:this.shoreBell.x,y:this.shoreBell.y}; + else if(action==="ring"){const p=this.point({x:1,y:3});origin={x:p.x-tile.width*.24,y:p.y-8};} + const preferred=action==="wait"?{x:origin.x,y:origin.y+20}:origin; + const candidates=[preferred]; + for(let y=Math.max(88,f.top-20);yMath.hypot(a.x-preferred.x,a.y-preferred.y)-Math.hypot(b.x-preferred.x,b.y-preferred.y)); + const point=candidates.find(point=>{ + const box={...point,width:44,height:44}; + return point.x>=24&&point.x<=this.w-24&&point.y>=24&&point.y<=this.h-24&&!cells.some(cell=>!(action==="wait"&&cell.position.x===court.position.x&&cell.position.y===court.position.y)&&overlaps(box,cell))&&!anchors.some(anchor=>overlaps(box,anchor))&&!blocked.some(region=>overlaps(box,region)); + }); + if(!point)continue; + const anchor={...point,action,width:44,height:44};anchors.push(anchor); + this.shoreMarks.lineStyle(1.5,0xf5db9c,.85).lineBetween(origin.x,origin.y,point.x,point.y); + this.text(point.x,point.y,labels[action],12).setDepth(23); + const key=`action:${action}`; + let zone=this.hitAreas.get(key); + if(!zone){zone=this.add.zone(point.x,point.y,44,44).setInteractive({useHandCursor:true}).setDepth(24).setData("worldAction",action);this.hitAreas.set(key,zone);} + zone.setPosition(point.x,point.y).setInteractive(); + } + return anchors; } private drawBridge(x:number,y:number,w:number,h:number){ // Native3:1 bridge stays undistorted; transparent ends overlap the two landing stones. diff --git a/web/src/run/TideRunGame.test.tsx b/web/src/run/TideRunGame.test.tsx index 7f1a2b5..82144db 100644 --- a/web/src/run/TideRunGame.test.tsx +++ b/web/src/run/TideRunGame.test.tsx @@ -55,3 +55,17 @@ test("a story prize brought home keeps the return card without offering a retry" expect(html).not.toContain('data-testid="tide-again"'); } }); + +test("the tide run teaches direct play and keeps a closed native button alternative", () => { + const { html } = render(startTide({ seed: 20771 })); + expect(html).toContain("WASD or arrow keys to move"); + expect(html).toContain("Space waits"); + expect(html).toContain("R ends the tide at the dock"); + expect(html).toContain("I explains the tide"); + expect(html).not.toContain("E interacts"); + expect(html).not.toContain("tap a find to collect it"); + expect(html).toContain('Button controls'); + expect(html).toContain('aria-describedby="tide-input-hints"'); + expect(html).not.toContain('
initial.outcome !== "active" || initial.moves.length ? "" : chapter ? `Bram: “${chapter.before}”` : `The Tidekeeper turns to the ${laneNames(initial.next.lanes).toLowerCase()} lane.`); - const dialog = useRef(null), guideButton = useRef(null); + const dialog = useRef(null), guideButton = useRef(null), gameRef = useRef(null), guideOpener = useRef(null); const guess = useMemo(() => initial.story ? null : bramsGuess(initial.seed), [initial.seed, initial.story]); const busy = !!result, paused = away || blocked || guide || !!fault; // The board catches up before the numbers do: the status shows the tide as drawn. const seen = result ? result.before : state, over = state.outcome !== "active" && !busy; const { waves, roughFrom } = tideShape(initial), legal = legalMoves(state); const used = seen.pack.reduce((sum, item) => sum + SLOTS[item], 0); - const snapshot = useMemo(() => ({ tide: state, reducedMotion: reduced }), [state, reduced]); + const worldActions = useMemo(() => legalMoves(state).filter((move): move is "wait" | "home" => move === "wait" || move === "home" && state.moves.length > 0), [state]); + const snapshot = useMemo(() => ({ tide: state, reducedMotion: reduced, worldActions }), [state, reduced, worldActions]); useEffect(() => { const hide = () => setAway(true), show = () => setAway(document.hidden); @@ -87,11 +90,22 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b return () => { document.removeEventListener("visibilitychange", show); window.removeEventListener("blur", hide); window.removeEventListener("focus", show); }; }, []); useEffect(() => { - if (!guide) { guideButton.current?.focus({ preventScroll: true }); return; } + if (!guide) { if (guideOpener.current) { (guideOpener.current.isConnected ? guideOpener.current : gameRef.current)?.focus({ preventScroll: true }); guideOpener.current = null; } return; } const element = dialog.current; element?.showModal(); return () => element?.close(); }, [guide]); + useEffect(() => { + if (!ready || guide || current.current.outcome !== "active") return; + const frame = requestAnimationFrame(() => gameRef.current?.focus({ preventScroll: true })); + return () => cancelAnimationFrame(frame); + }, [ready]); + + function openGuide(source: HTMLElement | null = gameRef.current) { + if (!ready || paused || pending.current || current.current.outcome !== "active") return; + guideOpener.current = source; + setGuide(true); + } function take(move: Move) { if (!ready || paused || pending.current || current.current.outcome !== "active" || document.hidden) return; @@ -132,14 +146,14 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b }, [state.story, over, ready, blocked, onFinish]); useEffect(() => { function keys(event: KeyboardEvent) { - if (event.isComposing || event.repeat || event.metaKey || event.ctrlKey || event.altKey || event.shiftKey || guide || - (event.target instanceof Element && event.target.closest("input,textarea,select,[contenteditable=true],dialog"))) return; - const key = event.key.toLowerCase(); - if (key === " " && event.target instanceof Element && event.target.closest("button,a")) return; - const move = KEYS[key]; + if (event.isComposing || event.repeat || event.metaKey || event.ctrlKey || event.altKey || guide || current.current.outcome !== "active") return; + const target = event.target instanceof Element ? event.target : null; + if (!target || !gameRef.current?.contains(target) || !gameRef.current.contains(document.activeElement)) return; + if (target.closest("button,a,summary,input,textarea,select,[contenteditable]:not([contenteditable=false]),dialog,[role=dialog],[role=slider],[role=tablist]")) return; + const key = event.key.toLowerCase(), move = KEYS[key]; if (!move && key !== "i") return; event.preventDefault(); - if (move) take(move); else setGuide(true); + if (move) take(move); else openGuide(); } window.addEventListener("keydown", keys); return () => window.removeEventListener("keydown", keys); }); @@ -151,11 +165,11 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b const lockControls = !ready || paused || busy; const feedback =
{notice}
; - return
{ if (event.target instanceof HTMLCanvasElement) gameRef.current?.focus({ preventScroll: true }); }} className="exp-game passage-game tide-run" data-mode="court" data-testid="tide-run" data-story={state.story} data-seed={state.seed} data-beat={state.beat} data-wave={state.wave} data-outcome={state.outcome} data-busy={busy} data-score={state.score} data-hearts={state.hearts}> setReady(true)} onFault={message => { setFault(message); setReady(false); pending.current = null; setResult(null); }} - onBeat={beat} onSettled={settle} onTarget={target} /> + onBeat={beat} onSettled={settle} onTarget={target} onMove={take} onInspect={openGuide} />
familiar.Played and saved on this device

{chapter ? chapter.title : "Today’s tide"}

@@ -204,13 +218,17 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b Mochi is at {where(seen.position)}. The bridge is at the {LANES[seen.bridge]} lane. {feedback}
+
+
{STEPS.map(move => )}
- {legal.includes("home") && state.moves.length > 0 && }
+
+ +
} {guide && { event.preventDefault(); setGuide(false); }}> @@ -223,7 +241,7 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b
  • {icon("M3 18V6m18 12V6M3 8c4 6 14 6 18 0M3 18h18M7 12v6m5-5v5m5-6v6")}The bridge moves to the wave’s lane. The channel can only be crossed there.
  • {icon("M20 12a8 8 0 1 1-16 0 8 8 0 1 1 16 0M12 7v5l3 2")}This tide is {waves} waves.{roughFrom < waves ? ` From wave ${roughFrom + 1}, each wave takes two lanes.` : ""} What is still in the pack when it ends is lost.
  • -

    Arrow keys or WASD move, Space waits, R calls it a day on the dock.

    +

    Swipe or tap a neighboring platform to move. Prizes are collected as Mochi steps onto them; reaching the dock banks the pack. Tap Wait beside Mochi to let one move pass, or Home to call it a day. Arrow keys or WASD move, Space waits, R calls it a day on the dock, and I opens this guide. Optional Button controls offer the same decisions without gestures.

    }
    ; } diff --git a/web/src/run/TideWorld.tsx b/web/src/run/TideWorld.tsx index d4274cd..ac09f3a 100644 --- a/web/src/run/TideWorld.tsx +++ b/web/src/run/TideWorld.tsx @@ -1,7 +1,7 @@ import { useEffect, useRef, useState } from "react"; -import { countdown, type Position, type TideEvent, type TideTransition } from "./engine"; +import { countdown, type Move, type Position, type TideEvent, type TideTransition } from "./engine"; import { itemName, laneNames } from "./story"; -import type { TideScene, TideSnapshot } from "./scene"; +import type { TideScene, TideSnapshot, TideTile, TideActionAnchor } from "./scene"; export interface TideWorldProps { snapshot: TideSnapshot; @@ -9,6 +9,8 @@ export interface TideWorldProps { presentationId: number; paused: boolean; onTarget: (position: Position) => void; + onMove:(move:Move)=>void; + onInspect:()=>void; onSettled: (id: number) => void; onBeat: (event: TideEvent) => void; onFault: (message: string) => void; @@ -17,7 +19,7 @@ export interface TideWorldProps { export default function TideWorld(props: TideWorldProps) { const mount = useRef(null), scene = useRef(null), current = useRef(props); - const [ready, setReady] = useState(false); + const [ready, setReady] = useState(false),[tiles,setTiles]=useState([]),[actions,setActions]=useState([]); current.current = props; useEffect(() => { let alive = true, game: import("phaser").Game | undefined; @@ -26,21 +28,34 @@ export default function TideWorld(props: TideWorldProps) { if (!alive || !mount.current) return; const next = new TideScene(current.current.snapshot, { target: position => current.current.onTarget(position), + move:move=>current.current.onMove(move),inspect:()=>current.current.onInspect(), + geometry:(tiles,actions)=>{if(alive){setTiles(tiles);setActions(actions);}}, ready: () => { if (!alive) return; setReady(true); current.current.onReady(); next.setGated(current.current.paused); }, fault: message => { if (alive) current.current.onFault(message); }, beat: event => { if (alive) current.current.onBeat(event); }, settled: id => { if (alive) current.current.onSettled(id); }, }); scene.current = next; - game = new Phaser.Game({ type: Phaser.AUTO, parent: mount.current, width: mount.current.clientWidth, height: mount.current.clientHeight, transparent: true, antialias: true, banner: false, audio: { noAudio: true }, loader: { imageLoadType: "HTMLImageElement" }, scene: next, scale: { mode: Phaser.Scale.RESIZE, autoCenter: Phaser.Scale.CENTER_BOTH }, input: { keyboard: false } }); + // CSS touch-action owns scrolling; a cancelled native touch may not be cancelable. + game = new Phaser.Game({ type: Phaser.AUTO, parent: mount.current, width: mount.current.clientWidth, height: mount.current.clientHeight, transparent: true, antialias: true, banner: false, audio: { noAudio: true }, loader: { imageLoadType: "HTMLImageElement" }, scene: next, scale: { mode: Phaser.Scale.RESIZE, autoCenter: Phaser.Scale.CENTER_BOTH }, input: { keyboard: false, touch: { capture: false } } }); game.canvas.setAttribute("aria-hidden", "true"); game.canvas.addEventListener("webglcontextlost", lost); }).catch(() => { if (alive) current.current.onFault("The playfield could not open. Your saved harbor is safe. Retry the scene."); }); return () => { alive = false; scene.current = null; if (game) { game.canvas.removeEventListener("webglcontextlost", lost); game.destroy(true); } }; }, []); useEffect(() => { if (ready) scene.current?.setSnapshot(props.snapshot, props.transition, props.presentationId); }, [ready, props.snapshot, props.transition, props.presentationId]); useEffect(() => { scene.current?.setGated(props.paused); }, [props.paused]); + useEffect(()=>{ + if(!ready)return; + let frame=0; + const refresh=()=>{cancelAnimationFrame(frame);frame=requestAnimationFrame(()=>scene.current?.refreshLayout());}; + const observer=new ResizeObserver(refresh); + if(mount.current)observer.observe(mount.current); + mount.current?.closest(".exp-game")?.querySelectorAll(".exp-command-tray,.exp-hud,.exp-feedback").forEach(element=>observer.observe(element)); + refresh(); + return()=>{cancelAnimationFrame(frame);observer.disconnect();}; + },[ready,props.paused]); const { tide } = props.snapshot; const coming = tide.outcome === "active" ? ` The next wave takes ${laneNames(tide.next.lanes)} in ${countdown(tide)}${tide.next.drops.length ? ` and leaves ${tide.next.drops.map(drop => itemName(drop.kind)).join(" and ")}` : ""}.` : ""; - return
    ; + return
    ; } diff --git a/web/src/run/scene.ts b/web/src/run/scene.ts index 43acc0c..dcaa75f 100644 --- a/web/src/run/scene.ts +++ b/web/src/run/scene.ts @@ -1,8 +1,9 @@ /** Draws a tide run. The board is redrawn from `shown`; each accepted move plays its events, then shows the state after. */ import Phaser from "phaser"; +import { swipeCommand } from "../expedition/input"; import { MOCHI_GROUND, MOCHI_POSES, walkingPose, type MochiPoseName } from "../motion/mochi"; import { companionIdle } from "../expedition/companion"; -import { DOCK, STORY_SHELL, applyMove, countdown, legalMoves, stepDestination, type Item, type Lane, type Position, type TideEvent, type TideState, type TideTransition } from "./engine"; +import { DOCK, STORY_SHELL, applyMove, countdown, legalMoves, stepDestination, type Item, type Lane, type Position, type TideEvent, type TideState, type TideTransition, type Move } from "./engine"; const ART = "/assets/expedition/runtime/"; const IMAGES: Readonly> = { @@ -15,8 +16,14 @@ const FONT = "Figtree Variable, sans-serif"; const LANES = [0, 1, 2] as const; const same = (a: Position, b: Position) => a.x === b.x && a.y === b.y; -export interface TideSnapshot { readonly tide: TideState; readonly reducedMotion: boolean } +export type TideAction="wait"|"home"; +export interface TideActionAnchor {action:TideAction;x:number;y:number;width:number;height:number} +export interface TideTile {position:Position;x:number;y:number;width:number;height:number} +export interface TideSnapshot { readonly tide: TideState; readonly reducedMotion: boolean; readonly worldActions?:readonly TideAction[] } export interface TideHooks { + move:(move:Move)=>void; + inspect:()=>void; + geometry:(tiles:readonly TideTile[],actions:readonly TideActionAnchor[])=>void; target: (position: Position) => void; ready: () => void; fault: (message: string) => void; @@ -41,12 +48,19 @@ export class TideScene extends Phaser.Scene { private actorPose: MochiPoseName = "curious"; private parts: Phaser.GameObjects.GameObject[] = []; private prizes = new Map(); + private tileZones:Phaser.GameObjects.Zone[]=[]; + private actionZones=new Map(); private ghosts: Phaser.GameObjects.Image[] = []; /** Everything `forecast` draws, so it can be redrawn without a full layout. */ private marks: Phaser.GameObjects.GameObject[] = []; private shell: Phaser.GameObjects.Image | null = null; private pack: Phaser.GameObjects.Image[] = []; - private presses = new Map(); + private presses=new Map(); + private contacts=new Set(); + private multipleContacts=false; + private readingTop:number|null=null; + private layoutRequested=false; + private geometryFrame:number|null=null; private epoch = 0; private lastPresentation = 0; private playing = false; @@ -85,32 +99,55 @@ export class TideScene extends Phaser.Scene { this.hints = this.add.graphics().setDepth(2.1); this.keeper = this.add.image(0, 0, "tide-keeper").setOrigin(.5, 1).setDepth(3); this.actorShadow = this.add.ellipse(0, 0, 50, 13, 0x342719, .25).setDepth(7); - this.actor = this.add.sprite(0, 0, "tide-mochi", 12).setOrigin(.5, MOCHI_GROUND).setDepth(10); + this.actor = this.add.sprite(0, 0, "tide-mochi", 12).setOrigin(.5, MOCHI_GROUND).setDepth(10).setInteractive({useHandCursor:true}); this.scale.on("resize", () => { + this.presses.clear(); if (this.playing && this.presentationSize) { const zoom = Math.min(this.scale.width / this.presentationSize.w, this.scale.height / this.presentationSize.h); this.cameras.main.setZoom(zoom).centerOn(this.presentationSize.w / 2, this.presentationSize.h / 2); } else { this.cameras.main.setZoom(1).setScroll(0, 0); this.layout(); } }); - this.events.once("shutdown", () => { this.stopped = true; this.epoch++; }); this.input.mouse?.disableContextMenu(); - const release = (pointer: Phaser.Input.Pointer) => this.presses.delete(pointer.id); - this.input.on("pointerup", release); this.input.on("pointerupoutside", release); + this.input.addPointer(1); + this.input.on("pointerdown",(pointer:Phaser.Input.Pointer,over:Phaser.GameObjects.GameObject[])=>this.press(pointer,over)); + this.input.on("pointerdownoutside",(pointer:Phaser.Input.Pointer)=>this.press(pointer,[])); + this.input.on("pointermove",(pointer:Phaser.Input.Pointer)=>{ + const press=this.presses.get(pointer.id),point=this.clientPoint(pointer); + if(press)press.excursion=Math.max(press.excursion,Math.hypot(point.x-press.x,point.y-press.y)); + }); + this.input.on("pointerup",(pointer:Phaser.Input.Pointer,over:Phaser.GameObjects.GameObject[])=>this.release(pointer,over)); + this.input.on("pointerupoutside",(pointer:Phaser.Input.Pointer)=>{this.presses.delete(pointer.id);this.contacts.delete(pointer.id);if(!this.contacts.size)this.multipleContacts=false;this.afterRelease();}); + const cancel=()=>{this.presses.clear();this.contacts.clear();this.multipleContacts=false;}; + const touchContacts=(event:TouchEvent)=>{if(event.touches.length>1||event.type==="touchcancel"){cancel();this.multipleContacts=event.touches.length>0;}else if(!event.touches.length){this.multipleContacts=false;this.contacts.clear();}}; + // Run after Phaser's touch listener; prevent its compatibility mouse click from repeating a hold or tap. + const preventMouse=(event:TouchEvent)=>{if(event.cancelable)event.preventDefault();}; + this.game.canvas.addEventListener("touchstart",preventMouse,{passive:false}); + window.addEventListener("blur",cancel);document.addEventListener("visibilitychange",cancel);this.game.canvas.addEventListener("pointercancel",cancel); + window.addEventListener("touchstart",touchContacts,true);window.addEventListener("touchend",touchContacts,true);window.addEventListener("touchcancel",touchContacts,true); + let cleaned=false; + const cleanup=()=>{ + if(cleaned)return;cleaned=true; + this.stopped=true;this.epoch++;cancel();if(this.geometryFrame!==null)cancelAnimationFrame(this.geometryFrame); + this.game.canvas.removeEventListener("touchstart",preventMouse); + window.removeEventListener("blur",cancel);document.removeEventListener("visibilitychange",cancel);this.game.canvas.removeEventListener("pointercancel",cancel); + window.removeEventListener("touchstart",touchContacts,true);window.removeEventListener("touchend",touchContacts,true);window.removeEventListener("touchcancel",touchContacts,true); + }; + this.events.once("shutdown",cleanup);this.events.once("destroy",cleanup); this.layout(); this.hooks.ready(); } /** Presentation coordinates are responsive. Logical cells and accepted state never resize. */ private field() { const portrait = this.w <= 900 && this.h > this.w; - if (portrait && this.h < 500) { const top = 144, bottom = this.h - 166, width = this.w * .82; return { cx: this.w / 2, width, top, bottom, dy: (bottom - top) / 4, dx: width / 3 }; } + if (portrait && this.h < 500) { const top = 144, bottom = Math.min(this.h-150,this.readingTop===null?Infinity:this.readingTop-24), width = this.w * .72; return { cx: this.w / 2, width, top, bottom, dy: (bottom - top) / 4, dx: width / 3 }; } if (this.h <= 500) { // The painted island and its rings extend below the dock anchor. const available = this.w - 280, width = Math.max(240, Math.min(available * .91, 760)), top = 98, bottom = this.h - (portrait ? 34 : 56); return { cx: available / 2, width, top, bottom, dy: (bottom - top) / 4, dx: width / 3 }; } const top = portrait ? (this.h < 650 ? 151 : Math.max(200, this.h * .29)) : Math.max(190, this.h * .31); - const bottom = portrait ? this.h - 276 : this.h - 72; - const width = Math.min(portrait ? this.w * .84 : this.w * .50, 760); + const bottom = portrait ? Math.min(this.h-170,this.readingTop===null?Infinity:this.readingTop-48) : this.h - 72; + const width = Math.min(portrait ? this.w * .72 : this.w * .50, 760); return { cx: portrait ? this.w * .5 : this.w * .45, width, top, bottom, dy: (bottom - top) / 4, dx: width / 3 }; } private point(position: Position) { const f = this.field(); return { x: f.cx + (position.x - 1) * f.dx, y: f.bottom - position.y * f.dy }; } @@ -150,8 +187,19 @@ export class TideScene extends Phaser.Scene { if (transition && id !== this.lastPresentation) { this.lastPresentation = id; void this.present(transition, id); } else if (!this.playing) { this.shown = snapshot.tide; this.shut = this.shellShut(snapshot.tide); this.layout(); } } + refreshLayout(){ + const parent=this.game.canvas.parentElement; + if(parent&&(this.scale.width!==parent.clientWidth||this.scale.height!==parent.clientHeight)){this.scale.setParentSize(parent.clientWidth,parent.clientHeight);return;} + if(this.scale.getParentBounds()){this.scale.refresh();return;} + if(this.playing||this.presses.size){this.layoutRequested=true;return;} + this.layoutRequested=false;this.layout(); + } + private afterRelease(){ + if(!this.layoutRequested||this.presses.size||this.geometryFrame!==null)return; + this.geometryFrame=requestAnimationFrame(()=>{this.geometryFrame=null;if(!this.stopped)this.refreshLayout();}); + } setGated(gated: boolean) { - this.gated = gated; if (gated) this.presses.clear(); if (!this.actor) return; + this.gated = gated; if (gated) { this.presses.clear(); this.contacts.clear(); this.multipleContacts=false; } if (!this.actor) return; this.input.enabled = !gated; this.time.paused = gated; if (gated) this.tweens.pauseAll(); else this.tweens.resumeAll(); } @@ -159,6 +207,12 @@ export class TideScene extends Phaser.Scene { private layout() { if (!this.actor || this.stopped) return; this.presses.clear(); + if(!this.playing){ + this.layoutRequested=false; + const reading=this.game.canvas.closest(".exp-game")?.querySelector(".exp-command-tray"); + this.readingTop=reading?.getClientRects().length?reading.getBoundingClientRect().top-this.game.canvas.getBoundingClientRect().top:null; + } + for(const zone of [...this.tileZones,...this.actionZones.values()])zone.disableInteractive(); for (const part of this.parts) part.destroy(); this.parts = []; this.prizes.clear(); this.pack = []; this.shell = null; this.ground.clear(); @@ -170,6 +224,7 @@ export class TideScene extends Phaser.Scene { const from = this.point({ x, y }), to = this.point({ x, y: y + 1 }), length = f.dy * 1.35; this.keep(this.add.image(from.x, (from.y + to.y) / 2, "tide-bridge").setDisplaySize(length / 3, length).setDepth(.4)); } + const targets:TideTile[]=[]; const island = this.textures.get("tide-island").getSourceImage() as HTMLImageElement; for (let y = 0; y < 5; y++) for (const x of LANES) { const position = { x, y }, p = this.point(position); @@ -178,14 +233,13 @@ export class TideScene extends Phaser.Scene { this.ground.lineStyle(1, 0xe5edce, .35).strokeEllipse(p.x, p.y + tile.width * .1, tile.width * 1.09, tile.width * .24); this.keep(this.add.image(p.x, p.y, "tide-island").setOrigin(.5, .41).setDisplaySize(tile.width, tile.width * island.height / island.width).setDepth(1)); } else if (x !== tide.bridge) this.ground.lineStyle(2, 0xa8c8bd, .4).strokeEllipse(p.x, p.y + 6, tile.width * .6, tile.height * .45); - const zone = this.keep(this.add.zone(p.x, p.y, Math.max(44, tile.width), Math.max(44, Math.min(tile.height + 15, f.dy - 2))).setInteractive({ useHandCursor: true }).setDepth(16)); - const target = `${x},${y}`; - zone.on("pointerdown", (pointer: Phaser.Input.Pointer) => { if (!this.gated && this.onCanvas(pointer)) this.presses.set(pointer.id, { target, x: pointer.x, y: pointer.y }); }); - zone.on("pointerup", (pointer: Phaser.Input.Pointer) => { - const press = this.presses.get(pointer.id); this.presses.delete(pointer.id); - if (this.gated || this.playing || pointer.wasCanceled || press?.target !== target || Math.hypot(pointer.x - press.x, pointer.y - press.y) > 12) return; - if (pointer.wasTouch || pointer.leftButtonReleased()) this.hooks.target(position); - }); + const width=Math.max(44,tile.width),height=Math.max(44,Math.min(tile.height+15,f.dy-2)); + const index=y*3+x; + let zone=this.tileZones[index]; + if(!zone){zone=this.add.zone(p.x,p.y,width,height).setInteractive({useHandCursor:true}).setDepth(16).setData("cellTarget",position);this.tileZones[index]=zone;} + zone.setPosition(p.x,p.y).setSize(width,height).setInteractive(); + if(same(position,tide.position))zone.disableInteractive(); + targets.push({position,...p,width,height}); } const crossing = this.point({ x: tide.bridge, y: 2 }), span = f.dy * 1.65 * 1.36; this.bridgeArt.setPosition(crossing.x, crossing.y).setDisplaySize(span / 3, span).setAngle(0).setAlpha(1); @@ -206,12 +260,73 @@ export class TideScene extends Phaser.Scene { this.prizes.set(`${item.x},${item.y}`, this.keep(this.add.image(p.x + beside, p.y - size * .36, `tide-${item.kind}`).setDisplaySize(size, size).setDepth(6))); } const p = this.point(tide.position), size = this.actorSize(); - this.actor.setPosition(p.x, p.y).setDisplaySize(size, size).setFlipX(false); + this.actor.setPosition(p.x, p.y).setDisplaySize(size, size).setFlipX(false).setData("worldAction",this.snapshot.worldActions?.includes("wait")?"wait":null); this.actorShadow.setPosition(p.x, p.y + 2).setSize(size * .55, Math.max(4, size * .1)); this.pose(tide.outcome === "rescued" ? "startled" : tide.outcome !== "active" ? "relieved" : "curious"); this.drawPack(tide.pack); this.forecast(); this.resetIdle(); + this.hooks.geometry(targets,this.actionTargets(tide,targets)); + } + + private clientPoint(pointer:Phaser.Input.Pointer){ + const event=pointer.event; + if("changedTouches" in event){ + const touch=Array.from(event.changedTouches).find(t=>t.identifier===pointer.identifier); + if(touch)return{x:touch.clientX,y:touch.clientY}; + } + return{x:(event as MouseEvent).clientX,y:(event as MouseEvent).clientY}; + } + private press(pointer:Phaser.Input.Pointer,over:Phaser.GameObjects.GameObject[]){ + this.contacts.add(pointer.id); + if(this.contacts.size>1){this.multipleContacts=true;this.presses.clear();} + if(this.gated||this.playing||this.stopped||this.multipleContacts||!this.onCanvas(pointer))return; + const event=pointer.event,point=this.clientPoint(pointer),rect=this.game.canvas.getBoundingClientRect(); + const touch=pointer.wasTouch||("pointerType" in event&&event.pointerType==="pen"); + if(!touch&&!pointer.leftButtonDown()&&!pointer.rightButtonDown())return; + const target=over.find(object=>object.getData("cellTarget")||object.getData("worldAction"))??null; + this.presses.set(pointer.id,{target,x:point.x,y:point.y,excursion:0,touch,edge:point.x-rect.left<24||rect.right-point.x<24}); + } + private release(pointer:Phaser.Input.Pointer,over:Phaser.GameObjects.GameObject[]){ + const press=this.presses.get(pointer.id);this.presses.delete(pointer.id);this.contacts.delete(pointer.id);this.afterRelease(); + const multiple=this.multipleContacts;if(!this.contacts.size)this.multipleContacts=false; + const point=this.clientPoint(pointer),canvas=this.game.canvas,rect=canvas.getBoundingClientRect(); + if(!press||this.gated||this.playing||this.stopped||multiple||pointer.wasCanceled||!this.onCanvas(pointer)||document.hidden|| + point.xrect.right||point.yrect.bottom||document.elementFromPoint(point.x,point.y)!==canvas)return; + const excursion=Math.max(press.excursion,Math.hypot(point.x-press.x,point.y-press.y)); + if(press.touch&&this.shown.outcome==="active"&&!press.edge){ + const command=swipeCommand(point.x-press.x,point.y-press.y); + if(command){this.hooks.move(command.slice(5) as Move);return;} + } + if(excursion>12||!press.target||!over.includes(press.target))return; + if(pointer.rightButtonReleased()||pointer.getDuration()>450){this.hooks.inspect();return;} + if(!press.touch&&!pointer.leftButtonReleased())return; + const action=press.target.getData("worldAction") as TideAction|undefined; + const target=press.target.getData("cellTarget") as Position|undefined; + if(action)this.hooks.move(action);else if(target)this.hooks.target(target); + } + private actionTargets(tide:TideState,tiles:readonly TideTile[]):TideActionAnchor[]{ + const anchors:TideActionAnchor[]=[],canvas=this.game.canvas.getBoundingClientRect(),f=this.field(); + const blocked=Array.from(this.game.canvas.closest(".exp-game")?.querySelectorAll(".exp-command-tray,.exp-hud,.exp-mast,.exp-feedback")??[]) + .filter(element=>element.getClientRects().length&&getComputedStyle(element).visibility!=="hidden") + .map(element=>{const r=element.getBoundingClientRect();return{x:r.left-canvas.left+r.width/2,y:r.top-canvas.top+r.height/2,width:r.width,height:r.height};}); + const overlaps=(a:{x:number;y:number;width:number;height:number},b:typeof a)=>Math.abs(a.x-b.x)<(a.width+b.width)/2+2&&Math.abs(a.y-b.y)<(a.height+b.height)/2+2; + const moves=legalMoves(tide),cells=tiles.filter(cell=>moves.some(move=>{const to=stepDestination(tide,move);return to&&same(to,cell.position);})); + for(const action of this.snapshot.worldActions??[]){ + const origin=this.point(action==="home"?DOCK:tide.position),preferred=action==="wait"?{x:origin.x,y:origin.y+20}:origin; + const candidates=[preferred]; + for(let y=Math.max(88,f.top-20);yMath.hypot(a.x-preferred.x,a.y-preferred.y)-Math.hypot(b.x-preferred.x,b.y-preferred.y)); + const point=candidates.find(point=>{const box={...point,width:44,height:44};return point.x>=24&&point.x<=this.w-24&&point.y>=24&&point.y<=this.h-24&&!cells.some(cell=>overlaps(box,cell))&&!anchors.some(anchor=>overlaps(box,anchor))&&!blocked.some(region=>overlaps(box,region));}); + if(!point)continue; + anchors.push({...point,action,width:44,height:44}); + this.ground.lineStyle(1.5,0xf5db9c,.85).lineBetween(origin.x,origin.y,point.x,point.y); + this.keep(this.label(point.x,point.y,action==="wait"?"Wait":"Home",12).setDepth(23)); + let zone=this.actionZones.get(action); + if(!zone){zone=this.add.zone(point.x,point.y,44,44).setInteractive({useHandCursor:true}).setDepth(24).setData("worldAction",action);this.actionZones.set(action,zone);} + zone.setPosition(point.x,point.y).setInteractive(); + } + return anchors; } /** The lanes the next wave takes, its countdown, the prize it will leave, and which steps are safe. */ diff --git a/web/src/run/tide-run.css b/web/src/run/tide-run.css index 3b24702..bf8cb17 100644 --- a/web/src/run/tide-run.css +++ b/web/src/run/tide-run.css @@ -141,3 +141,41 @@ .tide-run .exp-directions .exp-wait { grid-column: 1; grid-row: 2; } .tide-run .exp-context-actions { grid-column: 2 / -1; grid-row: 2; gap: 4px; } } + + +/* Direct play keeps only guidance visible; the full pad opens on request. */ +.tide-run .passage-tray{gap:8px;overflow:visible} +.tide-run .tide-controls{position:relative;flex:none} +.tide-run .tide-controls .exp-control-hints{display:block} +.tide-run .exp-button-controls>summary{justify-content:flex-start;width:max-content} +.tide-run .tide-guide-control{position:absolute;bottom:0;right:0;min-height:44px;min-width:44px;margin:0;white-space:nowrap} +.tide-run .exp-button-controls-body .exp-current-controls{display:flex;flex-direction:column;gap:8px} +.tide-run .exp-button-controls-body .exp-directions{display:flex;justify-content:space-between;width:100%;gap:4px} +.tide-run .exp-button-controls-body .exp-directions button{width:44px;height:44px;min-height:44px;flex:none} +.tide-run .exp-button-controls-body .exp-context-actions{display:flex;flex-direction:column;align-items:stretch;min-height:0} +.tide-run .exp-button-controls-body .exp-context-actions button{min-height:44px} +.tide-run .tide-tray-reading{scrollbar-color:#8b734c var(--exp-card);scroll-padding:6px} +@media(max-width:899px) and (orientation:portrait){ + .tide-run .passage-tray{max-height:200px;padding:8px 10px;gap:5px} + .tide-run .exp-forecast{padding:5px 0;margin-bottom:5px!important;font-size:13px;line-height:1.35} + .tide-run .exp-objective{font-size:14px} + .tide-run .tide-asks{gap:3px} +} +@media(max-width:599px) and (max-height:600px) and (orientation:portrait){ + .tide-run .exp-brand small{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%)} + .tide-run h1.exp-place{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);padding:0} + .tide-run .tide-hud{top:68px;padding:6px 8px;gap:8px} + .tide-run .tide-portrait{width:30px;height:30px} + .tide-run .tide-vitals strong{font-size:14px} + .tide-run .tide-vitals{gap:3px} + .tide-run .tide-hearts svg{width:12px;height:12px} + .tide-run .tide-tally{padding-left:7px;gap:5px;font-size:12px} + .tide-run .tide-tally>svg{display:none} + .tide-run .tide-tally b{font-size:16px} + .tide-run .passage-tray{max-height:176px} +} +@media(orientation:landscape) and (max-height:500px){ + .tide-run .passage-tray{overflow:visible;gap:5px} + .tide-run .tide-controls .exp-input-context{font-size:12px} + .tide-run .exp-button-controls-body{max-height:calc(100dvh - 160px)} +} From a4f4bdf4a715ba0b97e2531731ed89ee9fe6509f Mon Sep 17 00:00:00 2001 From: David Dada Date: Sat, 14 Nov 2026 18:26:56 +0100 Subject: [PATCH 2/2] docs: record current-main control behavior and verification --- PROGRESS.md | 1 + README.md | 2 +- web/DESIGN.md | 6 ++++-- web/PRODUCT.md | 2 ++ 4 files changed, 8 insertions(+), 3 deletions(-) diff --git a/PROGRESS.md b/PROGRESS.md index 97187bb..9ec2f1f 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -6,6 +6,7 @@ Full earlier progress and acceptance records are preserved in the [archive](docs | Date | Change | Evidence | Result and limits | | --- | --- | --- | --- | +| 2026-11-14 | Issue [#8](https://github.com/dadadave80/familiar/issues/8): swipe/tap and focused keyboard controls across the current Tide Run, retained courts and Bell/Reed crossings, on local branch `feat/direct-play-controls-current` | Source `782694c`, based on fetched `main` `91b5194` including merged #9; GitHub main rechecked at the same revision. `bun run test`: 491 pass/0 fail/40289 assertions; `cargo test --manifest-path contracts/Cargo.toml --workspace`: 182 pass/0 fail/3 ignored; typecheck/build, `make evidence` (15 canonical hashes/signatures and FINAL receipt graphs), `make break`, all eight gameplay/routing browser suites, records/season/Privy browser checks pass. Tide Run, passages and routing pass Chromium/WebKit; retained courts pass seven viewport journeys plus the complete normal-motion/recovery/save-failure tail; native touch suite passes 20 cases. Compiled QA passes 13 viewport profiles plus cold slow3G/gzip/touch/CPU4, with no failures and an offline local decision. [Logs and SHA256 inventory](/Users/dadadave/.codex/visualizations/2026/11/13/01a1d587-c1b9-7802-967f-8d1cf80455b9/issue-8-controls/logs/inventory.json) | Compact hints follow actual input; the native Button controls disclosure starts closed. Distinct 44px world actions, one-step swipes, free inspection and focused WASD/arrows preserve canonical action histories. Cancellation, multitouch, modal focus, resize/rotation, touch compatibility clicks and resumed hit targets are covered. No engine, save-format, contract, reward or account-authorization change. The full Bun suite needs loopback permission; a restricted repeat refused nine HTTP fixtures, then all 491 passed with it allowed. Mocked dev-harness warm-up emits Invalid hook call warnings; steady assertions and isolated guest/compiled console checks pass. Existing large-chunk build warning remains. No push, deployment or signing; physical-device comfort, pen and native Safari swipes remain unverified (WebKit covers taps/keyboard; Chromium covers native swipe sequences). | | 2026-11-13 | Audited unused source and superseded reports retired locally | User authorized audited cleanup; independent cross-review of all65 changed/removed/replacement paths | Retired six-file dynamic NPC worker, unused IBM font/license, six redundant contract ignores, old guest/Google helper implementations and dead example settings. Live Google/Privy provider and native pending/recovery validators untouched; exact formatter/type and relevant security tests moved to current owners. Fresh setup omits retired worker settings while exact prior generated tuples validate unchanged. Eight superseded reports/585796 bytes plus old architecture/security descriptions and unused Mochi pose archived outside Git with exact-byte/SHA256 inventories. Archive index preserves historical references; current architecture/threat descriptions refreshed. No ledger/state migration, stored-key rewrite or source-history rewrite. | | 2026-11-13 | Artwork delivery and cleaned build verified | Full233 Bun tests/15490 assertions,123 Rust passes, build/typecheck/fmt; offline15 signatures/58 receipt graphs | Six generator-only WebPs/1536100 bytes moved outside public delivery; all19 shipped WebPs unchanged; all11 optimized outputs reproduce exact bytes. Original pose1123042 bytes archived. Source and prepared Chromium/WebKit routes preserve intro-first, nine entry URLs and original saves;390px Beacon/Wind/lantern origin/save/art-failure journey and both Bell/Reed/discovery browser routes pass. Prepared574iax has367 static files,370 output files;10 actual local secret values absent and private H1 handler remains SHA256e3cc0335191ce63946bcdf9fe772fed2ee5db2678f7c193a12c86cfb64800e03. Relayer Docker COPY set passes isolated frozen offline production install and runtime bundling; actual Docker daemon unavailable. Existing Phaser size warning persists. User image and protected environment/journals/Wasm untouched. No push or deployment; physical-device sound/full two-device recovery/human enjoyment unverified. | | 2026-11-13 | Documentation trimmed; Make shortcuts added | `make check`, `make typecheck`, `make browser`, `make evidence` | Full233 Bun tests/15490 assertions,123 Rust passes, typecheck/build and Chromium/WebKit route/save checks pass. Ten remaining historical JSONs/535460 bytes and full earlier JUDGES/PROGRESS snapshots archived byte-for-byte outside Git. Only gameplay proof and original-deployment guard JSONs remain. Make forwards to Bun/Cargo without deploy/signing recipes. Game, contract, recovery and original-operation implementations unchanged. No push/deployment or history rewrite; prior physical/human validation gaps remain. | diff --git a/README.md b/README.md index 2f3f9b8..e9b5e71 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ bun install --frozen-lockfile make dev ``` -No account is needed for the device preview. Use neighboring-platform taps, WASD/arrows or accessible buttons. Inspect is free. Sound is opt-in; reduced motion keeps the same outcomes. Device saves stay on that browser and never silently merge into a signed-in harbor. +No account is needed for the device preview. On touch screens, swipe once to move or tap a glowing neighboring platform. Tap **Wait** beside Mochi to wait and **Home** at the dock to finish the outing. On desktop, use WASD/arrows, Space to wait, R to finish at the dock and I for the free guide while the game has focus. Tide Run collects finds and banks cargo when Mochi steps onto them; the three-ask courts also use E for nearby objects. Mouse targeting still works; optional **Button controls** expose the same actions. Sound is opt-in; reduced motion keeps the same outcomes. Device saves stay on that browser and never silently merge into a signed-in harbor. ## Commands diff --git a/web/DESIGN.md b/web/DESIGN.md index 3c200da..67d11d9 100644 --- a/web/DESIGN.md +++ b/web/DESIGN.md @@ -6,7 +6,7 @@ The harbor and expedition artwork form the full browser viewport. Navigation and The desktop playfield has no exterior page frame, permanent cream sidebar or letterbox. Keep the center clear and expose the current decision first. Preparation, memory, discoveries, Workshop, Account and longer explanations use bounded menu states. The whole game page stays fixed; contained detail/account panels may scroll where useful, with reachable Back/Close controls. -Portrait keeps all three columns and both banks visible. Organic sandstone platforms and a single moving wooden bridge sit directly in the coastal world. Mochi walks to adjacent platforms, crosses an open bridge in one decision, reaches for discoveries, and carries them back to the dock. The Tidekeeper, source markers and ordered wave/bridge animation explain cause and effect. Hover and keyboard focus preview the exact accepted outcome; touch controls retain the same labels and risk symbols. +Portrait keeps all three columns and both banks visible. Organic sandstone platforms and a single moving wooden bridge sit directly in the coastal world. Mochi walks to adjacent platforms, crosses an open bridge in one decision, reaches for discoveries, and carries them back to the dock. The Tidekeeper, source markers and ordered wave/bridge animation explain cause and effect. Hover and keyboard focus preview the exact accepted outcome; world-tap targets and optional Button controls retain equivalent actions. Resizing changes presentation only. DOM buttons and labels preserve keyboard access, 44px targets, visible focus, contrast and reduced-motion outcomes. Browser viewport filling does not require forcing OS fullscreen. The engine saves an accepted decision before animation; one next direction may queue while Mochi completes it. Hidden tabs clear that queue. A single browser tab owns the active preview branch, preventing competing tabs from replacing moves. @@ -28,7 +28,9 @@ The painted world already matches the Pocket Harbor concept; the interface layer **Coming home** is the peak of the loop: a centred Home sheet with the day's stamp, the three asks, a large result line and the next action (Take it to Bram, or Sail again). All three kept shows Mochi's proud portrait. Closing any panel returns focus to whatever opened it. -**The court** keeps the board clear: a Mochi status card (portrait, tide line, pips for Resolve, satchel and tool, plus one hidden sentence that reads the whole status), the surge forecast in plain words ("Next wave: left lane"), and the Tidekeeper's asks as painted-icon chips inside the move tray beside the controls. +**The court** keeps the board clear: a Mochi status card (portrait, tide line, pips for Resolve, satchel and tool, plus one hidden sentence that reads the whole status), the surge forecast in plain words ("Next wave: left lane"), and the Tidekeeper's asks as painted-icon chips beside compact input hints. The default direction/action pad is replaced by swipe/tap guidance on touch screens and WASD/arrows on desktop. Hint mode follows actual input, not viewport width. Button controls remain in a closed-by-default native disclosure; the world retains distinct, at-least-44px targets for Wait, return and contextual objects. Menus, Sound, Inspect and confirmations remain ordinary controls. + +Swipes resolve only on release and produce one canonical step. A qualifying swipe travels at least 32 CSS pixels on its dominant axis with a 1.5 axis ratio; ambiguous drags do nothing. A stationary hold still inspects for free. Cancellation, multitouch, resize and modal changes discard unfinished gestures. Keyboard shortcuts act only with intentional game focus and leave native controls and text fields alone. These thresholds require physical-device comfort checks before mobile validation is claimed. **Painted UI art** (gpt-6-astra masters in `assets/source/ui/`) shares the felt-and-clay world's light and materials: four driftwood signs, three Mochi portraits (default, splashed after a splash, proud) and twelve ask icons. Text stays code-native on every sign and chip. diff --git a/web/PRODUCT.md b/web/PRODUCT.md index 48a05a9..61f2f2e 100644 --- a/web/PRODUCT.md +++ b/web/PRODUCT.md @@ -23,6 +23,8 @@ Bram’s shelf joins the same daily loop: bring reed or glass home from today’ ## Operating Context First Light fills the desktop viewport and fits mobile portrait/landscape. Keep the whole page from scrolling; useful contained menus may scroll. The current court connects three columns of platforms across two banks. Each decision advances the tide; the marked source predicts the next wave, which moves the bridge and exposes discoveries. Retrieved cargo must reach the dock. Wind Gate adds a wheel that changes source-to-exit routing. Testnet only; public RPC, no indexer, no paid infrastructure. Hundreds of players and tens concurrently are a design target, not measured capacity. +Outings use discrete swipe and world-tap controls on touch screens, and WASD/arrow keys on a focused desktop game. Quiet hints follow the most recent input. Wait, dock return and contextual objects have distinct world targets; a closed-by-default Button controls disclosure keeps equivalent named native controls available. Menus, Inspect, recovery and transaction confirmations remain explicit native controls. A gesture never bypasses the existing legal-command and save boundaries. + ## Capabilities and Constraints First Light starts with a local preview before sign-in. Canonical actions use the recovered player's browser-authorized key, the compatible testnet registry and current ownership. Mac Privy signing and Mochi adoption are independently verified; Android same-wallet signing is user-reported. Same Mochi, earned items and progress on two physical devices remain unverified. The original operator H1 acceptance ran on testnet; it is separate from the new spatial-content acceptance. Retained signing modules include historical player-signed actions and the optional NEAR Auth recovery path; their live recovery is unverified and the earlier pet interface is retired. Receipts describe only confirmed actions. A stopped service pauses account actions without replacing the player or claiming completion.