diff --git a/PROGRESS.md b/PROGRESS.md index 9ec2f1f..3fdf5fb 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 | Keep Wren’s Light, Slice A on `feat/keep-wrens-light-onboarding`: coherent Tide Run journey from landing to repair, a shared keyboard-scroll handler for reading regions, and deterministic browser fixtures that abort and assert unexpected requests | Fresh local run: `bun run typecheck` pass; `bun run test` 522 pass/0 fail/41078 assertions across 72 files; `bun run build` pass (existing large-chunk warning). `bun scripts/test-tide-run-browser.ts` passed 3 of 3 consecutive runs, Chromium and WebKit each time. Also pass: routing (Chromium/WebKit), Tide (412×860, 390×844, 844×390, 1280×800, 1440×900), expedition harbor, Season (390×844, 1440×900), passage (Chromium/WebKit), expedition, compiled expedition QA (`failures: []`), expedition touch and expedition lifecycle. An earlier run of this branch before the keyboard-scroll handler failed WebKit 3 of 3 times in the tide-run guidance keyboard-scroll check. Rust suite not run; `contracts/` unchanged. | The fixture-backed suites call `assertClean`, and it recorded no unexpected requests. Browser emulation only: physical devices, screen readers and player comprehension remain unverified. No push, deployment or live calls; `A-pocket-harbor.png` untouched. | | 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. | diff --git a/README.md b/README.md index e9b5e71..f7f3f1e 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,11 @@ ![Familiar: a little adventure with Mochi. A felt-miniature harbor at sunset: Mochi, an orange kitten in a red bandana, leaps between spiral stepping stones past a teal wave and a glowing wind-moth, while the stone-crab Tidekeeper watches and Bram the badger waves from the quay below the lighthouse.](docs/readme-banner.jpg) -A cozy turn-based Phaser puzzle adventure with Mochi and a coastal harbor to restore. The introduction at `/` leads to `/outing/`. Recover the Beacon Lens, route the tide through Wind Gate, help at Bell/Reed Steps, and follow Mochi's later shore-bell discovery. Three story chapters are tide runs: twelve waves on a small board, where Mochi picks up what each wave leaves and banks it at the dock before the water lands. Once the beacon is lit, today's tide run is the daily, played and saved on this device: its three stamps (come home with something, match or beat Bram's guess, keep dry paws) are the day's asks, the first tide each day is the one that counts, and later sails are practice. The Home sheet shows the result, Bram's tide log keeps a page for each day, and Bram shelves the reed and glass Mochi brings home, to trade for Shells toward Mochi's wish. Saved harbors keep the Tidekeeper's three-ask court on Beacon Court, which device harbors can still open from the Chart. +A cozy turn-based Phaser puzzle adventure: guide Mochi as a volunteer harbor helper and restore the light. The introduction at `/` leads to `/outing/`. Three device story chapters recover the Beacon Lens, Signal Vane and wind-moth. Chapter 1 has eight calm waves; the later chapters have twelve. Each step or wait spends one move; a wave lands after every third move. Mochi collects finds by stepping onto them and banks cargo on arrival at the center dock. + +The harbor prioritizes an open outing or unfinished filing, then a recovered repair, then the next story chapter. Once the beacon is lit, **Today’s tide · optional** opens daily preparation alongside the remaining story. The first finished daily outing sets that day’s score and stamps, including a zero-score, rescued or tide-turned outing; later sails are practice. Pausing leaves the outing open on its original day. Story outings use no daily result. The Home sheet and Log keep daily results; Bram shelves eligible reed and glass. Bell/Reed Steps, the later shore-bell discovery and optional courts remain on the Chart under their existing discovery requirements. Saved harbors keep the Tidekeeper’s three-ask court; each selected activity teaches its own rules and tools. + +**Carried** means in Mochi’s pack; **banked safe** means secured for this outing. Banking does not finish it. **Finish and return** ends it without spending a move, then files the return; **filed in the harbor** means that save succeeded. A filed lens or vane still needs deliberate **installation**. Story prizes add no score. A failed filing keeps the finished outing available for retry, including when the prize write succeeded but closing the outing failed. ## Run @@ -11,7 +15,7 @@ bun install --frozen-lockfile make dev ``` -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. +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 **Finish** at the Tide Run 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 and retain their Home action. 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/scripts/browser-controls.test.ts b/scripts/browser-controls.test.ts new file mode 100644 index 0000000..9259728 --- /dev/null +++ b/scripts/browser-controls.test.ts @@ -0,0 +1,16 @@ +import { expect, test } from "bun:test"; +import type { Page } from "@playwright/test"; +import { guide } from "./browser-controls"; + +test("keyboard guidance waits for the new playfield before its first command",async()=>{ + const calls:string[]=[]; + let ready!:()=>void; + const opening=new Promise(resolve=>{ready=resolve;}); + const game={last:()=>game,locator:()=>({waitFor:async()=>{await opening;}}),focus:async()=>{calls.push("focus");}}; + const page={locator:()=>game,keyboard:{press:async(key:string)=>{calls.push(key);}}} as unknown as Page; + const command=guide(page,"north"); + await Promise.resolve(); + expect(calls).toEqual([]); + ready();await command; + expect(calls).toEqual(["focus","ArrowUp"]); +}); diff --git a/scripts/browser-controls.ts b/scripts/browser-controls.ts index 81b6663..b88ad85 100644 --- a/scripts/browser-controls.ts +++ b/scripts/browser-controls.ts @@ -4,6 +4,7 @@ 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(); + await game.locator('[data-testid="expedition-world"][data-ready="true"],[data-testid="tide-world"][data-ready="true"]').waitFor(); 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:")){ @@ -44,3 +45,9 @@ export async function departCourt(page:Page){ 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(); } + +/** Story departures are prepared; resuming an existing trace deliberately bypasses this. */ +export async function sailStory(page:Page){ + await page.getByRole("button",{name:/^Prepare Chapter \d+$/}).click(); + await page.getByRole("button",{name:"Sail with Mochi",exact:true}).click(); +} diff --git a/scripts/browser-fixtures.test.ts b/scripts/browser-fixtures.test.ts new file mode 100644 index 0000000..231d2ee --- /dev/null +++ b/scripts/browser-fixtures.test.ts @@ -0,0 +1,86 @@ +import { expect, test } from "bun:test"; +import type { Page, Route } from "@playwright/test"; +import { runInNewContext } from "node:vm"; +import { BROWSER_DAY, prepareBrowser, seasonRpcFixture } from "./browser-fixtures"; + +const rpc=(method:string,args:unknown={},receiver="season.familiar-game.testnet")=>JSON.stringify({jsonrpc:"2.0",id:"season",method:"query",params:{request_type:"call_function",finality:"final",account_id:receiver,method_name:method,args_base64:btoa(JSON.stringify(args))}}); +test("browser RPC fixtures match endpoint, receiver, method and exact arguments",()=>{ + expect(seasonRpcFixture("https://test.rpc.fastnear.com","POST",rpc("get_shelf"),BROWSER_DAY)).toMatchObject({day:BROWSER_DAY}); + expect(seasonRpcFixture("https://test.rpc.fastnear.com","POST",rpc("get_today",{account_id:null}),BROWSER_DAY)).toMatchObject({day:BROWSER_DAY,content_version:"first_light_v2"}); + for(const [method,args] of [["get_account",{account_id:"alice.familiar-game.testnet"}],["get_wish",{pet:"mochi.familiar-game.testnet"}],["get_postcard",{pet:"mochi.familiar-game.testnet"}]] as const) + expect(seasonRpcFixture("https://test.rpc.fastnear.com","POST",rpc(method,args),BROWSER_DAY)).toBeNull(); + for(const [url,verb,body] of [["https://test.rpc.fastnear.com.evil/","POST",rpc("get_shelf")],["https://test.rpc.fastnear.com/other","POST",rpc("get_shelf")],["https://test.rpc.fastnear.com","GET",rpc("get_shelf")],["https://test.rpc.fastnear.com","POST",rpc("get_shelf",{},"other.testnet")],["https://test.rpc.fastnear.com","POST",rpc("unknown")],["https://test.rpc.fastnear.com","POST",rpc("get_shelf",{unexpected:true})],["https://test.rpc.fastnear.com","POST",rpc("get_today",{account_id:null,extra:true})],["https://test.rpc.fastnear.com","POST",rpc("get_today",{account_id:"unknown.testnet"})]]) + expect(()=>seasonRpcFixture(url!,verb!,body!,BROWSER_DAY)).toThrow(); +}); + +for(const origin of ["http://localhost:3000","http://127.0.0.1:3000","http://[::1]:3000","https://familiar-two.vercel.app"]) +test(`browser preparation shifts only the running wall clock and validates every request at ${origin}`,async()=>{ + const calls:unknown[]=[]; + let dateScript!:(time:number)=>void; + let handle!:(route:Route)=>Promise; + const page={clock:{install:async(value:unknown)=>{calls.push(["install",value]);}},addInitScript:async(callback:typeof dateScript,time:number)=>{dateScript=callback;calls.push(["date",time]);},evaluate:async(callback:typeof dateScript,time:number)=>{dateScript=callback;calls.push(["shift",time]);},route:async(pattern:string,callback:typeof handle)=>{calls.push(["route",pattern]);handle=callback;}} as unknown as Page; + const network=await prepareBrowser(page,origin,BROWSER_DAY); + const noon=BROWSER_DAY*86_400_000+43_200_000; + expect(calls).toEqual([["date",noon],["route","**/*"]]); + let elapsed=10_000; + class WallDate extends Date { static now(){return elapsed;} } + const native={performance:{now:()=>elapsed},setTimeout,requestAnimationFrame:()=>1}; + const context={Date:WallDate,...native,time:noon}; + runInNewContext(`(${dateScript.toString()})(time)`,context); + expect(context.Date.now()).toBe(noon); + elapsed+=16; + expect(context.Date.now()).toBe(noon+16); + expect(new context.Date().getTime()).toBe(noon+16); + expect(new context.Date(123).getTime()).toBe(123); + expect(new context.Date("2026-11-14T00:00:00Z").getTime()).toBe(BROWSER_DAY*86_400_000); + expect(context.Date.parse("2026-11-14T00:00:00Z")).toBe(BROWSER_DAY*86_400_000); + expect(context.Date.UTC(2026,10,14)).toBe(BROWSER_DAY*86_400_000); + expect((context.Date as unknown as ()=>string)()).toBe(new Date(noon+16).toString()); + expect(context.performance).toBe(native.performance); + expect(context.setTimeout).toBe(native.setTimeout); + expect(context.requestAnimationFrame).toBe(native.requestAnimationFrame); + expect(new context.Date()).toBeInstanceOf(WallDate); + runInNewContext(`class SavedDate extends Date {}; globalThis.savedDate = new SavedDate(); globalThis.SavedDate = SavedDate;`,context); + expect((context as any).savedDate).toBeInstanceOf((context as any).SavedDate); + expect((context as any).savedDate.getTime()).toBe(noon+16); + await network.setTime(noon+86_400_000); + context.time=noon+86_400_000; + runInNewContext(`(${dateScript.toString()})(time)`,context); + elapsed+=16; + expect(context.Date.now()).toBe(noon+86_400_000+16); + expect(new context.Date().getTime()).toBe(noon+86_400_000+16); + const request=async(url:string,method="GET",body:string|null=null)=>{ + const actions:{kind:string;body?:string}[]=[]; + await handle({request:()=>({url:()=>url,method:()=>method,postData:()=>body}),continue:async()=>{actions.push({kind:"continue"});},abort:async()=>{actions.push({kind:"abort"});},fulfill:async(response:{body:string})=>{actions.push({kind:"fulfill",body:response.body});}} as unknown as Route); + return actions; + }; + expect(await request(`${origin}/assets/harbor.webp`)).toEqual([{kind:"continue"}]); + const fulfilled=await request("https://test.rpc.fastnear.com/","POST",rpc("get_shelf")); + expect(fulfilled[0]?.kind).toBe("fulfill"); + const response=JSON.parse(fulfilled[0]!.body!); + expect(JSON.parse(new TextDecoder().decode(Uint8Array.from(response.result.result)))).toMatchObject({day:BROWSER_DAY}); + expect(network.rpc).toEqual(["get_shelf"]);expect(()=>network.assertClean()).not.toThrow(); + expect(await request("https://unexpected.example/telemetry")).toEqual([{kind:"abort"}]); + expect(await request(`${origin}/api/player`)).toEqual([{kind:"abort"}]); + expect(await request(`${origin}/npc-api/note`)).toEqual([{kind:"abort"}]); + expect(await request(`${origin}/assets/harbor.webp`,"POST")).toEqual([{kind:"abort"}]); + expect(await request("https://test.rpc.fastnear.com/","POST",rpc("unknown"))).toEqual([{kind:"abort"}]); + expect(()=>network.assertClean()).toThrow("Unexpected browser requests"); +}); + +test("only deliberate timer-control scenarios install Playwright's full clock",async()=>{ + const calls:unknown[]=[]; + const page={clock:{install:async(value:unknown)=>{calls.push(["manual",value]);}},addInitScript:async()=>{calls.push(["date"]);},route:async()=>{}} as unknown as Page; + const manual=await prepareBrowser(page,"http://localhost:3000",BROWSER_DAY,{clock:"manual"}); + expect(calls).toEqual([["manual",{time:new Date(BROWSER_DAY*86_400_000+43_200_000)}]]); + calls.length=0; + const unclocked=await prepareBrowser(page,"http://localhost:3000",BROWSER_DAY,{clock:false}); + expect(calls).toEqual([]); + await expect(manual.setTime(0)).rejects.toThrow("Date shifts require"); + await expect(unclocked.setTime(0)).rejects.toThrow("Date shifts require"); +}); + +test("browser fixtures reject every hosted origin except the existing QA deployment",async()=>{ + for(const origin of ["https://unexpected.example","http://familiar-two.vercel.app","https://familiar-two.vercel.app:444","https://familiar-two.vercel.app.evil"]) + await expect(prepareBrowser({} as Page,origin)).rejects.toThrow("Browser fixtures require a local server or the existing hosted QA origin"); +}); diff --git a/scripts/browser-fixtures.ts b/scripts/browser-fixtures.ts new file mode 100644 index 0000000..56aab5b --- /dev/null +++ b/scripts/browser-fixtures.ts @@ -0,0 +1,67 @@ +import assert from "node:assert/strict"; +import type { Page } from "@playwright/test"; +import type { ShelfView, TodayView } from "../web/src/season/model"; + +export const BROWSER_DAY=20771; +const RPC="https://test.rpc.fastnear.com/",ROOT="familiar-game.testnet"; +const accounts=new Set([`alice.${ROOT}`,`bob.${ROOT}`,`harness.${ROOT}`]); +const pets=new Set([`mochi.${ROOT}`,`mochi-harness.${ROOT}`]); + +/** Public reads only. A mismatched envelope is an unexpected request, never a live fallback. */ +export function seasonRpcFixture(url:string,verb:string,body:string,day:number):unknown { + assert.equal(new URL(url).href,RPC,"fixture RPC endpoint");assert.equal(verb,"POST","fixture RPC verb"); + const request=JSON.parse(body),p=request.params; + assert.equal(request.jsonrpc,"2.0");assert.equal(request.method,"query"); + assert.equal(p?.request_type,"call_function");assert.equal(p.finality,"final");assert.equal(p.account_id,`season.${ROOT}`); + const args=JSON.parse(Buffer.from(p.args_base64,"base64").toString("utf8")); + switch(p.method_name){ + case "get_shelf":{ + assert.deepEqual(args,{}); + return {day,till:300,till_cap:300,till_refill:60,commission:12,goods:[ + {good:"glass",stock:40,target:40,base:8,heat_fp:0,price_fp:8_000_000,buyback_fp:6_400_000,buy_price:8,sell_price:6,waiting_wishes:0}, + {good:"reed",stock:40,target:40,base:4,heat_fp:0,price_fp:4_000_000,buyback_fp:3_200_000,buy_price:4,sell_price:3,waiting_wishes:0}, + ],shells_minted:0,goods_minted:[0,0],trade_seq:0} satisfies ShelfView; + } + case "get_today":{ + assert.deepEqual(Object.keys(args),["account_id"]);assert(args.account_id===null||accounts.has(args.account_id)); + const beacon=day%2===1; + return {day,next_day_ns:(day+1)*86_400_000_000_000,rules_version:"tidebound_h1_v1",content_version:beacon?"first_light_v2":"first_light_v1",area:"beacon",command_limit:beacon?24:15, + mapping:[["lens","glass"],["moth","reed"],["chart","reed"],["salvage","reed"],["vane",null]], + best_haul:beacon?[{tool:"rope",hauls:[[1,1]]},{tool:"lantern",hauls:[[1,1]]}]:[{tool:"rope",hauls:[[1,1],[0,2]]},{tool:"lantern",hauls:[[1,2]]}],best_fp:beacon?12_000_000:16_000_000,minted_today:null,traded_today:null} satisfies TodayView; + } + case "get_account":assert.deepEqual(Object.keys(args),["account_id"]);assert(accounts.has(args.account_id));return null; + case "get_wish":case "get_postcard":assert.deepEqual(Object.keys(args),["pet"]);assert(pets.has(args.pet));return null; + default:throw Error(`Unknown fixture RPC method: ${String(p.method_name)}`); + } +} + +function shiftBrowserDate(time:number) { + const OriginalDate=Date,offset=time-OriginalDate.now(); + globalThis.Date=new Proxy(OriginalDate,{ + apply:()=>new OriginalDate(OriginalDate.now()+offset).toString(), + construct:(target,args,newTarget)=>Reflect.construct(target,args.length?args:[target.now()+offset],newTarget), + get:(target,key)=>key==="now"?()=>target.now()+offset:Reflect.get(target,key), + }); +} + +/** Date drives the UTC day; native frame/timer clocks must keep driving Phaser. */ +export async function prepareBrowser(page:Page,origin:string|URL,day=BROWSER_DAY,{clock=true}: {clock?:boolean|"manual"}={}) { + const resourceUrl=new URL(origin),local=resourceUrl.origin,unexpected:string[]=[],rpc:string[]=[]; + assert(["localhost","127.0.0.1","[::1]"].includes(resourceUrl.hostname)||local==="https://familiar-two.vercel.app","Browser fixtures require a local server or the existing hosted QA origin"); + if(clock==="manual")await page.clock.install({time:new Date(day*86_400_000+43_200_000)}); + else if(clock)await page.addInitScript(shiftBrowserDate,day*86_400_000+43_200_000); + await page.route("**/*",async route=>{ + const request=route.request(),url=new URL(request.url()); + if(url.origin===local&&!/^\/(?:api|npc-api)(?:\/|$)/.test(url.pathname)&&["GET","HEAD"].includes(request.method()))return route.continue(); + try{ + const value=seasonRpcFixture(request.url(),request.method(),request.postData()??"",day); + rpc.push(JSON.parse(request.postData()!).params.method_name); + return route.fulfill({contentType:"application/json",body:JSON.stringify({jsonrpc:"2.0",id:JSON.parse(request.postData()!).id,result:{result:[...new TextEncoder().encode(JSON.stringify(value))]}})}); + }catch(error){unexpected.push(`${request.method()} ${request.url()}: ${String(error)}`);return route.abort();} + }); + // Date shifts affect this document only; navigation and RPC fixtures retain their explicit starting day. + return {rpc,setTime:async(time:number)=>{ + assert.equal(clock,true,"Date shifts require the native-frame fixture clock"); + await page.evaluate(shiftBrowserDate,time); + },assertClean:()=>assert.deepEqual(unexpected,[],"Unexpected browser requests must be explicitly fixture-backed")}; +} diff --git a/scripts/test-expedition-browser.ts b/scripts/test-expedition-browser.ts index bb434c1..9ce9303 100644 --- a/scripts/test-expedition-browser.ts +++ b/scripts/test-expedition-browser.ts @@ -1,4 +1,5 @@ import { guide, departCourt } from "./browser-controls"; +import { prepareBrowser } from "./browser-fixtures"; import assert from "node:assert/strict"; import { mkdtemp, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -13,6 +14,8 @@ const captures=await mkdtemp(join(tmpdir(),"familiar-expedition-browser-")); const server=await createServer({root:resolve(import.meta.dir,"../web"),cacheDir:join(captures,"vite-cache"),envDir:false,envPrefix:[],logLevel:"error",server:{host:"127.0.0.1",port:0,hmr:false,watch:null}}); await server.listen();const origin=server.resolvedUrls!.local[0]!.replace(/\/$/,""); const browser=await chromium.launch({headless:true}); +const networks:Awaited>[]=[]; +async function fixture(page:Page){networks.push(await prepareBrowser(page,origin));} const results:unknown[]=[]; const saveKey="familiar.expedition.local.v2"; async function settled(page:Page){await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-busy","false");} @@ -84,7 +87,7 @@ try{ for(const [width,height]of (quick?[[390,844],[1280,800]]:[[320,568],[390,844],[768,1024],[1280,800],[1920,1080],[2560,1080],[844,390]]).filter(([w])=>!process.argv.some(a=>a.startsWith("--only="))||Number(process.argv.find(a=>a.startsWith("--only="))!.slice(7))===w)){ const context=await browser.newContext({viewport:{width,height},reducedMotion:"reduce"}),page=await context.newPage(),errors:string[]=[]; page.on("pageerror",error=>errors.push(error.message)); - await page.route("**/api/**",route=>route.abort()); + await fixture(page); await page.goto(`${origin}/outing/?play`);await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true"); await record(page,`${width}-harbor`); if(width===390) { @@ -111,18 +114,18 @@ try{ 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 record(page,`${width}-returned`);await expect(page.locator('[data-action="home-next"]')).toHaveText("Fit the Beacon Lens");await page.locator('[data-action="home-next"]').click();await page.getByRole("button",{name:"Fit the Beacon Lens",exact:true}).click(); 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){ - await page.getByRole("button",{name:/Change preparation/}).click();await page.getByRole("radio",{name:"Wind Gate",exact:true}).check();await page.getByRole("button",{name:"Sail to Wind Gate",exact:true}).click(); + await page.getByRole("button",{name:"Harbor chart",exact:true}).and(page.locator(":visible")).click();await page.locator('.harbor-routes > li').filter({hasText:"Wind Gate"}).getByRole("button").click();await page.getByRole("button",{name:"Sail to Wind Gate",exact:true}).click(); const wind=startCourt({area:"wind",tool:"rope",banked:["lens","moth"]}),route=solveCourt(wind,["vane"],{dry:true})!; await playRoute(page,route.commands,wind,`${width}-wind`);await record(page,`${width}-wind-returned`); 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.locator(".exp-departure h1")).toHaveText(/^Today’s tide:/); + await page.getByRole("button",{name:"Fit the Signal Vane",exact:true}).click(); + await expect(page.locator(".exp-departure h1")).toHaveText("Today’s Tide Run."); 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"); } @@ -132,7 +135,7 @@ 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}/outing/?play`);await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await departCourt(page); + await fixture(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"); @@ -143,7 +146,7 @@ try{ 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}/outing/?play`);await expect(pickup.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await departCourt(pickup); + await fixture(pickup);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 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); @@ -153,13 +156,14 @@ try{ 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}/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); + const shared=await browser.newContext({viewport:{width:390,height:844},reducedMotion:"reduce"}),first=await shared.newPage();await fixture(first);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 fixture(second);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 fixture(saving);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}/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(); + 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:"Fit the Beacon Lens",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:"Fit the Beacon Lens",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}/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(); + const failed=await browser.newContext({viewport:{width:390,height:844}}),failure=await failed.newPage();await fixture(failure);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(); } + for(const network of networks)network.assertClean(); 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 019b1b8..25b1864 100644 --- a/scripts/test-expedition-harbor-browser.ts +++ b/scripts/test-expedition-harbor-browser.ts @@ -13,12 +13,11 @@ import {previewDock,seedPreview} from "../web/src/season/data"; import {VALUE,applyMove,legalMoves,startTide,type Move,type TideState} from "../web/src/run/engine"; import {cautiousMove} from "../web/src/run/bot"; import {dayResult} from "../web/src/run/save"; +import {BROWSER_DAY,prepareBrowser} from "./browser-fixtures"; // Actual React controller/provider/panel; all account/RPC ports below are isolated synthetic fixtures. const id="\0expedition-harbor-fixture.tsx",dir=await mkdtemp(join(tmpdir(),"familiar-expedition-harbor-")); const fixturePublicKey=KeyPair.fromRandom("ed25519").getPublicKey().toString(); -// Bram's shelf reads the season contract's public views over testnet RPC; nothing else may leave the page. -const publicView=(request:import("@playwright/test").Request)=>request.url().startsWith("https://test.rpc.fastnear.com")&&request.method()==="POST"&&JSON.parse(request.postData()??"{}")?.params?.request_type==="call_function"; let publicViews=0; const captureRoutes=courtFixtures.cases.filter(row=>["beacon-rope-objective","beacon-rope-rescue"].includes(row.id)).map(row=>({id:row.id,start:row.start,commands:row.commands})); async function checkHarborLayout(page:Page,width:number,height:number){ @@ -51,7 +50,8 @@ async function checkHarborLayout(page:Page,width:number,height:number){ assert(geometry.card.x>=0&&geometry.card.right<=width+.5&&geometry.card.bottom<=height+.5,`${tag}: harbor card stays inside the viewport`); assert(!geometry.heading.overflow&&geometry.heading.x>=geometry.card.x&&geometry.heading.right<=geometry.card.right&&geometry.heading.y>=geometry.card.y&&geometry.heading.bottom<=geometry.card.bottom,`${tag}: longest harbor heading stays inside the card without overflowing`); for(const stamp of geometry.stamp)assert(!overlaps(stamp,geometry.heading),`${tag}: stamp stays clear of the harbor heading`); - await expect(page.locator(".exp-departure-heading .exp-preparation")).toHaveCount(1); + const saved=await page.evaluate(()=>(window as any).__harbor?.port?.state.mode==="saved"); + await expect(page.locator(".exp-departure-heading .exp-preparation")).toHaveCount(saved?1:0); await expect(page.locator(".exp-departure").getByRole("button",{name:"Open the tide log",exact:true})).toHaveCount(0); for(const action of geometry.actions)assert(action.nowrap==="nowrap"&&!action.overflow,`${tag}: harbor button text never wraps or overflows`); if(width>=900||height<=500)for(const action of geometry.actions)assert(Math.abs(action.y-geometry.actions[0]!.y)<3,`${tag}: harbor actions share one row`); @@ -69,18 +69,17 @@ async function checkReturnLayouts(browser:import("@playwright/test").Browser,ori assert.equal(resultTitle(dayResult(early)),"1 of 3 kept.");assert.equal(rescued.outcome,"rescued");assert.equal(resultTitle(dayResult(rescued)),"Nothing kept this time."); const shelvedDay=day-3,shelvedTide=sail(shelvedDay,state=>cautiousMove(state,VALUE)); const scenarios:{name:string;day:number;moves:readonly Move[]|null;title:string;buttons:number;shelved:boolean}[]=[ - {name:"before",day,moves:null,title:`Today’s tide: ${cardForDay(day).name}.`,buttons:1,shelved:false}, + {name:"before",day,moves:null,title:"Today’s Tide Run.",buttons:1,shelved:false}, {name:"all-three",day,moves:cautious.moves,title:"All three kept.",buttons:2,shelved:false}, {name:"home-early",day,moves:early.moves,title:"1 of 3 kept.",buttons:1,shelved:false}, {name:"rescued",day,moves:rescued.moves,title:"Nothing kept this time.",buttons:1,shelved:false}, - {name:"shelved",day:shelvedDay,moves:shelvedTide.moves,title:`Tomorrow: ${cardForDay(shelvedDay+1).name}.`,buttons:1,shelved:true}]; + {name:"shelved",day:shelvedDay,moves:shelvedTide.moves,title:"Tomorrow’s Tide Run.",buttons:1,shelved:true}]; for(const scenario of scenarios){ const shelf=previewDock(seedPreview(null,scenario.day),[1,0],scenario.day);assert("market" in shelf); const context=await browser.newContext({viewport:{width:412,height:860},reducedMotion:"reduce"}),page=await context.newPage(); try{ const errors:string[]=[];page.on("pageerror",error=>errors.push(error.message)); - await page.route("**/*",route=>route.request().url().startsWith(origin)?route.continue():route.abort()); - await page.clock.install({time:new Date(scenario.day*86_400_000+43_200_000)});await page.clock.setFixedTime(new Date(scenario.day*86_400_000+43_200_000)); + const network=await prepareBrowser(page,origin,scenario.day); await page.addInitScript(({day,moves,market})=>{ localStorage.setItem("familiar.expedition.local.v2",JSON.stringify({version:2,home:{banked:["lens","vane","moth"],lit:true,signaled:true,lantern:null},active:null,last:null})); if(moves)localStorage.setItem("familiar.expedition.local.v2:tide-run.v1",JSON.stringify({version:1,active:{seed:day,moves:moves.slice(0,-1)},days:[]})); @@ -100,7 +99,7 @@ async function checkReturnLayouts(browser:import("@playwright/test").Browser,ori await expect(page.locator(".tide-departure-stamp")).toBeVisible();if(scenario.moves)await expect(page.getByTestId("expedition-feedback"),scenario.name).not.toHaveText(""); await expect(page.locator(".exp-departure-buttons>button"),scenario.name).toHaveCount(scenario.buttons); for(const [width,height] of [[412,860],[390,844],[844,390],[900,800],[1280,800],[1440,900]])await checkHarborLayout(page,width!,height!); - assert.equal(await page.evaluate(()=>(window as any).__harbor.sends.length),0,"layout checks send no account action");assert.deepEqual(errors,[],scenario.name); + assert.equal(await page.evaluate(()=>(window as any).__harbor.sends.length),0,"layout checks send no account action");assert.deepEqual(errors,[],scenario.name);network.assertClean();publicViews+=network.rpc.length; }finally{await context.close();} } } @@ -137,7 +136,7 @@ const server=await createServer({configFile:false,root:resolve(import.meta.dir," await server.listen();const origin=server.resolvedUrls!.local[0]!.replace(/\/$/,""),browser=await chromium.launch({headless:true}); try{ const context=await browser.newContext({viewport:{width:390,height:844}}),page=await context.newPage(),external:string[]=[],errors:string[]=[]; - page.on("request",request=>{if(!request.url().startsWith(origin)&&!request.url().startsWith("blob:")&&!request.url().startsWith("data:"))external.push(request.url());});page.on("pageerror",error=>{errors.push(error.message);console.error("Synthetic browser error:",error.message);}); + const network=await prepareBrowser(page,origin,BROWSER_DAY);page.on("pageerror",error=>{errors.push(error.message);console.error("Synthetic browser error:",error.message);}); await page.goto(origin+"/__harbor");await expect(page.getByTestId("authority")).toHaveText("preview");await expect(page.getByText(/alice.familiar-game.testnet · NEAR testnet/)).toBeVisible(); assert.equal(await page.evaluate(()=>(window as any).__harbor.sends.length),0); await page.getByRole("button",{name:"Use saved harbor",exact:true}).click();await expect(page.getByTestId("authority")).toHaveText("saved");await expect(page.getByTestId("motifs")).toHaveText("crest");await expect(page.getByTestId("owned")).toContainText("lantern:"); @@ -148,18 +147,18 @@ try{ assert.equal(await page.evaluate(()=>(window as any).__harbor.sends.length),1,"one explicit in-world confirmation"); await page.getByRole("button",{name:"Keep fixture memory",exact:true}).click();await expect.poll(()=>page.evaluate(()=>(window as any).__harbor.port.state.returns.length)).toBe(1);await page.getByText("Return memories",{exact:true}).click();const downloadEvent=page.waitForEvent("download");await page.getByRole("button",{name:"Download return memories",exact:true}).click();const download=await downloadEvent,exported=await Bun.file((await download.path())!).json(); assert.equal(exported.records.length,1);assert(!JSON.stringify(exported).includes("PRIVATE_IDENTITY_MARKER"));assert(!JSON.stringify(exported).includes("signedTransaction")); - const second=await page.context().newPage();await second.goto(origin+"/__harbor");await expect(second.getByText(/alice.familiar-game.testnet · NEAR testnet/)).toBeVisible(); + const second=await page.context().newPage(),secondNetwork=await prepareBrowser(second,origin,BROWSER_DAY);await second.goto(origin+"/__harbor");await expect(second.getByText(/alice.familiar-game.testnet · NEAR testnet/)).toBeVisible(); const captured=await Promise.all([page.evaluate(()=>(window as any).__harbor.captureRoute('beacon-rope-objective')),second.evaluate(()=>(window as any).__harbor.captureRoute('beacon-rope-rescue'))]); assert.notEqual(captured[0].id,captured[1].id); for(const tab of [page,second]){const records=await tab.evaluate(()=>JSON.parse((window as any).__harbor.port.exportReturns()).records);assert.equal(records.length,3);assert(records.some((r:any)=>r.cargo.includes('moth')));assert(records.some((r:any)=>r.cargo.length===1&&r.cargo[0]==='lens'));} - await second.close(); + secondNetwork.assertClean();await second.close(); await page.evaluate(()=>{const f=(window as any).__harbor;f.hold=true;f.oldPort=f.port;localStorage.setItem('fixture-original-pending','EXACT_ORIGINAL_BYTES');});await page.getByRole("button",{name:"Refresh fixture",exact:true}).click();await expect.poll(()=>page.evaluate(()=>!!(window as any).__harbor.release)).toBe(true); await page.evaluate(()=>(window as any).__harbor.close());await expect(page.getByText("Controller closed",{exact:true})).toBeVisible();await page.evaluate(()=>(window as any).__harbor.release()); const closed=await page.evaluate(async()=>{const f=(window as any).__harbor,reads=f.reads,result=await f.oldPort.review({kind:'commission'}).then(()=>"unexpected-success",()=>"closed");return {result,reads,after:f.reads,binding:f.oldPort.state.binding,pending:localStorage.getItem('fixture-original-pending')};}); assert.equal(closed.result,"closed");assert.equal(closed.reads,closed.after);assert.equal(closed.binding,null);assert.equal(closed.pending,"EXACT_ORIGINAL_BYTES"); await page.evaluate(()=>{const f=(window as any).__harbor;f.hold=false;f.owner={...f.owner,nearAccountId:'bob.familiar-game.testnet',playerId:'bob'};f.reopen();});await expect(page.getByText(/bob.familiar-game.testnet · NEAR testnet/)).toBeVisible();await expect(page.getByTestId("authority")).toHaveText("preview"); const gameContext=await browser.newContext({viewport:{width:390,height:844},reducedMotion:"reduce"}),game=await gameContext.newPage(); - game.on("pageerror",error=>errors.push(error.message));game.on("request",request=>{if(!request.url().startsWith(origin)&&!request.url().startsWith("blob:")&&!request.url().startsWith("data:")){if(publicView(request))publicViews++;else external.push(request.url());}}); + const gameNetwork=await prepareBrowser(game,origin,BROWSER_DAY);game.on("pageerror",error=>errors.push(error.message)); await game.goto(origin+"/__harbor-game");await game.bringToFront();await expect(game.getByTestId("expedition-world")).toHaveAttribute("data-ready","true",{timeout:20000}); await game.getByRole("button",{name:"Game menu",exact:true}).click();await game.getByRole("button",{name:"Account & recovery",exact:true}).click();await expect(game.getByText(/alice.familiar-game.testnet · NEAR testnet/)).toBeVisible(); await game.getByRole("button",{name:"Use saved harbor",exact:true}).click();await expect.poll(()=>game.evaluate(()=>(window as any).__harbor.port.state.mode)).toBe("saved");await game.getByRole("button",{name:"Close panel",exact:true}).click(); @@ -193,5 +192,5 @@ try{ await game.evaluate(async()=>{const f=(window as any).__harbor;f.displayLantern('moth',true);await f.port.refresh();});await expect(game.getByTestId('expedition-world')).toHaveAttribute('data-lantern-motif','moth'); await game.evaluate(async()=>{const f=(window as any).__harbor;f.removeHeldLantern();await f.port.refresh();});await expect(game.getByTestId('expedition-world')).not.toHaveAttribute('data-lantern-motif',/.+/);await expect(game.getByTestId('expedition-world')).not.toHaveAttribute('data-lantern-finish',/.+/);assert.equal(await game.evaluate(()=>(window as any).__harbor.sends.length),1); const geometry=await game.evaluate(()=>({x:scrollX,y:scrollY,scroll:document.documentElement.scrollHeight,height:innerHeight}));assert.equal(geometry.x,0);assert.equal(geometry.y,0);assert(geometry.scroll<=geometry.height+1); - await gameContext.close();await checkReturnLayouts(browser,origin);assert.deepEqual(external,[]);assert.deepEqual(errors,[]);console.log(JSON.stringify({status:"passed",actualReactController:true,actualGameAndPhaser:true,freshDeviceCanonicalMotifAndItem:true,canonicalAppearance:"Crest/original to Moth/polish; hidden after current holding disappears; no achievement inheritance",rememberedExplicitSelectionReload:true,explicitBramReview:true,busyReviewDismissalFenced:true,workingMemoryDownload:true,twoTabDistinctReturns:"both retained through actual Web Locks",lateOwnerFenced:true,harborLayouts:"fresh, before today’s tide, all three kept, one kept, rescued, longest Tomorrow; six viewports",externalRequests:0,publicRpcViews:publicViews,chainActions:0,captures:dir,limits:"Synthetic account/RPC ports only; no physical-device, provider-recovery or human-playtest claim."},null,2)); + network.assertClean();gameNetwork.assertClean();publicViews+=network.rpc.length+gameNetwork.rpc.length;await gameContext.close();await checkReturnLayouts(browser,origin);assert.deepEqual(external,[]);assert.deepEqual(errors,[]);console.log(JSON.stringify({status:"passed",actualReactController:true,actualGameAndPhaser:true,freshDeviceCanonicalMotifAndItem:true,canonicalAppearance:"Crest/original to Moth/polish; hidden after current holding disappears; no achievement inheritance",rememberedExplicitSelectionReload:true,explicitBramReview:true,busyReviewDismissalFenced:true,workingMemoryDownload:true,twoTabDistinctReturns:"both retained through actual Web Locks",lateOwnerFenced:true,harborLayouts:"fresh, before today’s tide, all three kept, one kept, rescued, longest Tomorrow; six viewports",externalRequests:0,mockedRpcViews:publicViews,chainActions:0,captures:dir,limits:"Synthetic account/RPC ports only; no physical-device, provider-recovery or human-playtest claim."},null,2)); }finally{await browser.close();await server.close();} diff --git a/scripts/test-expedition-qa-browser.ts b/scripts/test-expedition-qa-browser.ts index 9efb6a2..00ba5a3 100644 --- a/scripts/test-expedition-qa-browser.ts +++ b/scripts/test-expedition-qa-browser.ts @@ -4,6 +4,7 @@ import { mkdir,mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; import { extname,join,resolve,sep } from "node:path"; import { chromium,webkit,expect,type Page } from "@playwright/test"; +import { prepareBrowser } from "./browser-fixtures"; // Compiled static files only: no account server, identity input, signing or chain writes. const supplied=resolve(process.argv[2]??"web/dist"),staticRoot=await Bun.file(join(supplied,"index.html")).exists()?supplied:join(supplied,".vercel/output/static"); @@ -35,8 +36,8 @@ async function bounds(page:Page,label:string){ } try{ if(!networkOnly)for(const [width,height,touch]of (quick?[[390,844,true],[1280,800,false]]:[[320,480,true],[390,480,true],[320,568,true],[360,640,true],[390,844,true],[430,932,true],[768,1024,true],[1024,768,true],[844,390,true],[667,375,true],[1280,800,false],[1920,1080,false],[2560,1080,false]]) as [number,number,boolean][]){ - const context=await browser.newContext({viewport:{width,height},hasTouch:touch,isMobile:touch,deviceScaleFactor:touch?2:1,reducedMotion:"reduce"}),page=await context.newPage(),errors:string[]=[],mutations:string[]=[]; - 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();}); + const context=await browser.newContext({viewport:{width,height},hasTouch:touch,isMobile:touch,deviceScaleFactor:touch?2:1,reducedMotion:"reduce"}),page=await context.newPage(),errors:string[]=[]; + const network=await prepareBrowser(page,origin);page.on("pageerror",e=>errors.push(e.message)); 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`); await departCourt(page);await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-mode","court"); @@ -48,29 +49,31 @@ try{ await expect(page.getByRole("dialog")).toBeVisible();await capture(page,`${width}x${height}-menu`);await page.keyboard.press("ArrowUp");assert.equal(await page.evaluate(k=>localStorage.getItem(k),key),beforeMenu,"menu blocks game commands"); await page.keyboard.press("Tab");assert(await page.getByRole("dialog").evaluate(node=>node.contains(document.activeElement)),"dialog contains keyboard focus"); await page.getByRole("button",{name:"Close panel",exact:true}).click();await page.reload();await ready(page);assert.equal(await page.evaluate(k=>localStorage.getItem(k),key),beforeMenu,"reload preserves exact transcript"); - assert.deepEqual(errors,[]);assert(!mutations.some(path=>/\/(?:wallet|player|relay)(?:\/|$)/.test(path)),"no native identity/signing action");results.push({width,height,touch,geometry,blockedSdkTelemetry:mutations.length,status:"pass"}); + assert.deepEqual(errors,[]);network.assertClean();results.push({width,height,touch,geometry,status:"pass"}); }catch(e){failures.push(`${width}x${height}: ${String(e)}`);await capture(page,`${width}x${height}-failure`);} finally{await context.close();} } if(!baseline){ const failuresContext=await browser.newContext({viewport:{width:390,height:844},reducedMotion:"reduce"}),failed=await failuresContext.newPage(); + const failureNetwork=await prepareBrowser(failed,origin); await failed.route("**/assets/Game-*.js",route=>route.abort());await failed.goto(origin+"/outing/?play"); await expect(failed.locator("[data-boot-status]")).toContainText("could not download");await expect(failed.getByRole("link",{name:"Reload Familiar"})).toBeVisible();await capture(failed,"after-entry-download-failure"); - await failuresContext.close(); + failureNetwork.assertClean();await failuresContext.close(); const sdkContext=await browser.newContext({viewport:{width:390,height:844},reducedMotion:"reduce"}),sdkFailure=await sdkContext.newPage(); - await sdkContext.route("**/*",route=>["GET","HEAD","OPTIONS"].includes(route.request().method())?route.continue():route.abort()); + const sdkNetwork=await prepareBrowser(sdkFailure,origin); let blockedSdk=false;await sdkFailure.route("**/assets/PrivyProvider-*.js",route=>{blockedSdk=true;return route.abort();});await sdkFailure.goto(origin+"/outing/?play"); await expect.poll(async()=>blockedSdk||await sdkFailure.getByTestId("expedition-game").count()>0).toBe(true); // A configured release mounts this lazy module after entry() has already returned. if(blockedSdk){await expect(sdkFailure.getByRole("alert")).toContainText("original requests are unchanged");await expect(sdkFailure.getByRole("link",{name:"Reload Familiar"})).toBeVisible();await capture(sdkFailure,"after-lazy-account-download-failure");} - await sdkContext.close(); + sdkNetwork.assertClean();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;}); + const loadingNetwork=await prepareBrowser(loading,origin); 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="story"]')).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();loadingNetwork.assertClean();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); - await context.route("**/*",route=>["GET","HEAD","OPTIONS"].includes(route.request().method())?route.continue():route.abort()); + const network=await prepareBrowser(page,origin); await cdp.send("Network.enable");await cdp.send("Network.setCacheDisabled",{cacheDisabled:true});await cdp.send("Network.emulateNetworkConditions",{offline:false,latency:400,downloadThroughput:50000,uploadThroughput:50000,connectionType:"cellular3g"});await cdp.send("Emulation.setCPUThrottlingRate",{rate:4}); 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"); @@ -78,7 +81,7 @@ try{ 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(); + network.assertClean();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(); } console.log(JSON.stringify({captures,origin,engine:engine.name(),browser:browser.version(),results,failures,scope:"Browser emulation; no physical device or personal identity/signing actions."},null,2)); assert.deepEqual(failures,[],"All viewport profiles pass"); diff --git a/scripts/test-passage-browser.ts b/scripts/test-passage-browser.ts index a743725..a333982 100644 --- a/scripts/test-passage-browser.ts +++ b/scripts/test-passage-browser.ts @@ -1,4 +1,5 @@ import { guide, worldAction, buttonControls } from "./browser-controls"; +import { prepareBrowser } from "./browser-fixtures"; import assert from "node:assert/strict"; import { mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -18,7 +19,7 @@ try { const phone=engine===webkit; const record=process.argv.includes("--record")&&!phone; const page=await browser.newPage({...(record?{recordVideo:{dir:output,size:{width:1280,height:800}}}:{}),viewport:phone?{width:390,height:844}:{width:1280,height:800},hasTouch:phone,reducedMotion:phone?"reduce":"no-preference"}); - await page.route("**/api/**",r=>r.abort()); + const network=await prepareBrowser(page,origin); const errors:string[]=[]; page.on("console",msg=>{if(msg.type()==="error"&&msg.text().includes("Failed to process file"))errors.push(msg.text());}); await page.addInitScript(key=>{ @@ -58,7 +59,7 @@ try { await expect(game).toHaveAttribute("data-stage","delivered"); if(job==="reed")await expect(game).toHaveAttribute("data-watched","true"); await page.getByTestId("passage-finish").click(); - await expect(page.locator(".exp-departure h1")).toHaveText(/^Today’s tide:/); + await expect(page.locator('[data-action="story"]')).toHaveText("Prepare Chapter 3"); 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(); @@ -186,6 +187,7 @@ try { assert.equal(await page.evaluate(key=>localStorage.getItem(key),key),original,"companion and discovery never rewrite the H1 save"); assert.equal(await page.evaluate(k=>JSON.parse(localStorage.getItem(k)!).heardBell,passageKey),true); assert.deepEqual(errors,[],"all court and harbor textures decode"); + network.assertClean(); if(record){const video=page.video()!;await page.close();await video.saveAs(join(output,"both-crossings.webm"));} console.info(engine.name(),"Bell and Reed deliveries, discovery, bell routes, touch/keyboard, interrupted runs, companion and independent save passed"); }finally{await browser.close();} diff --git a/scripts/test-routing-browser.ts b/scripts/test-routing-browser.ts index e3e8b56..47f0a79 100644 --- a/scripts/test-routing-browser.ts +++ b/scripts/test-routing-browser.ts @@ -1,4 +1,5 @@ import { guide } from "./browser-controls"; +import { prepareBrowser } from "./browser-fixtures"; import assert from "node:assert/strict"; import { mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -44,19 +45,63 @@ const returnDay=20771,returned=cautiousTide(returnDay),beforeReturn=replayTide({ assert(beforeReturn?.outcome==="active"); const returnHaul=shelfHaul(dayResult(returned)); assert(returnHaul.reed+returnHaul.glass>0,"focus fixture brings a haul to Bram's shelf"); + +async function checkTitleEntry(browser: Awaited>, origin: URL, reducedMotion: "reduce" | "no-preference", hasSave: boolean) { + const page = await browser.newPage({ viewport: { width: 390, height: 844 }, hasTouch: true, reducedMotion }); + const network = await prepareBrowser(page, origin, returnDay, { clock: "manual" }); + try { + if (hasSave) await page.addInitScript(key => { + localStorage.setItem(key, JSON.stringify({ version: 2, home: { banked: [], lit: false, signaled: false, lantern: null }, active: null, last: null })); + }, saveKey); + await page.goto(new URL("/outing/", origin).href); + const opening = page.getByTestId("opening"), begin = opening.locator('[data-el="begin"]'); + const label = hasSave ? "Continue" : "Begin"; + await expect(opening).toHaveAttribute("data-mode", "title", { timeout: 30000 }); + await expect(begin).toHaveText(label); + await expect(begin).toHaveJSProperty("hidden", false); + await expect(begin).toHaveCSS("display", "flex"); + await begin.focus(); + await expect(begin).toBeFocused(); + await page.keyboard.press("Enter"); + await expect(opening).toHaveAttribute("data-mode", "menu"); + const hiddenEntry = async () => { + await expect(begin).toHaveCSS("display", "none"); + await expect(begin).toBeHidden(); + await begin.evaluate(button => (button as HTMLButtonElement).focus()); + await expect(begin).not.toBeFocused(); + }; + await hiddenEntry(); + const plank = opening.locator(hasSave ? '[data-plank="continue"]' : '[data-plank="new"]'); + await expect(plank).toBeFocused(); + await opening.getByRole("menuitem", { name: "Today’s Tide", exact: true }).click(); + const paper = opening.getByRole("dialog", { name: "Today’s Tide", exact: true }); + await expect(paper).toBeVisible(); + await hiddenEntry(); + const enter = paper.getByRole("button", { name: "Enter the harbor", exact: true }); + await enter.focus(); + await expect(enter).toBeFocused(); + await page.clock.pauseAt(await page.evaluate(() => Date.now() + 100)); + await page.keyboard.press("Enter"); + await page.clock.runFor(32); + await expect(opening).toHaveAttribute("data-mode", "travel"); + await hiddenEntry(); + await page.clock.resume(); + await expect(opening).toHaveCount(0, { timeout: 30000 }); + network.assertClean(); + } finally { await page.close(); } +} try { await server?.listen(); const origin = new URL(compiled?`http://127.0.0.1:${compiled.port}`:server!.resolvedUrls!.local[0]!); for (const engine of [chromium, webkit]) { const browser = await engine.launch(); try { + for (const reducedMotion of ["reduce", "no-preference"] as const) { + for (const hasSave of [false, true]) await checkTitleEntry(browser, origin, reducedMotion, hasSave); + } const mobile = engine === webkit; const page = await browser.newPage({ viewport: mobile ? { width: 390, height: 844 } : { width: 1280, height: 800 }, hasTouch: mobile, reducedMotion: "reduce" }); - await page.route("**/*", route => { - const url = new URL(route.request().url()); - if (url.origin !== origin.origin || /^\/(?:api|npc-api)\//.test(url.pathname)) return route.abort(); - return route.continue(); - }); + const network=await prepareBrowser(page,origin,returnDay); await page.goto(origin.href); await expect(page.getByRole("heading", { level: 1 })).toContainText("A small friend."); await page.evaluate(records => { for (const [key, value] of Object.entries(records)) localStorage.setItem(key, value); }, oldRecords); @@ -88,6 +133,11 @@ 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(); + const preparation = page.locator('.exp-panel[data-surface="sail"]'); + await expect(preparation.getByRole("radio", { name: "Beacon Court", exact: true })).toBeChecked(); + await preparation.getByRole("radio", { name: /^Lantern/ }).check(); + await expect(preparation.getByRole("radio", { name: /^Lantern/ })).toBeChecked(); + await preparation.getByRole("radio", { name: /^Rope/ }).check(); await page.locator('.exp-panel[data-surface="sail"] .exp-primary').click(); await guide(page,"step:west"); await expect(game).toHaveAttribute("data-busy", "false"); @@ -111,8 +161,6 @@ try { await page.reload(); await passTitle("reload"); await expect(world).toHaveAttribute("data-turn", "1"); - await page.clock.install({time:new Date(returnDay*86_400_000+43_200_000)}); - await page.clock.setFixedTime(new Date(returnDay*86_400_000+43_200_000)); await page.evaluate(({saveKey,bookKey,state})=>{ localStorage.setItem(saveKey,JSON.stringify({version:2,home:{banked:["lens"],lit:true,signaled:false,lantern:null},last:null,active:null})); localStorage.setItem(bookKey,JSON.stringify({version:1,active:{seed:state.seed,moves:state.moves},days:[]})); @@ -132,10 +180,11 @@ try { await expect(page.locator('.exp-panel[data-surface="log"] .tide-log-run')).toBeVisible(); await page.keyboard.press("Escape"); const harborPrimary=page.locator(".exp-departure .exp-primary"); - await expect(harborPrimary).toHaveAttribute("data-action","tide");await expect(harborPrimary).toBeFocused(); - await harborPrimary.click();await expect(page.locator('.exp-panel[data-surface="bram"]')).toBeVisible(); + await expect(harborPrimary).toHaveText("Prepare Chapter 2");await expect(harborPrimary).toBeFocused(); + await harborPrimary.click();await expect(page.getByRole("button",{name:"Sail with Mochi",exact:true})).toBeVisible(); await page.keyboard.press("Escape");await expect(harborPrimary).toBeFocused(); assert.deepEqual(await page.evaluate(keys=>Object.fromEntries(keys.map(key=>[key,localStorage.getItem(key)])),Object.keys(oldRecords)),oldRecords); + network.assertClean(); console.info(`${engine.name()}: introduction, account boundary, ${paths.length} game entry URLs, saved-run resume and preserved original records passed`); } finally { await browser.close(); } } diff --git a/scripts/test-season-browser.ts b/scripts/test-season-browser.ts index 2fba89f..74909e9 100644 --- a/scripts/test-season-browser.ts +++ b/scripts/test-season-browser.ts @@ -9,8 +9,9 @@ import { cautiousMove } from "../web/src/run/bot"; import { dayResult } from "../web/src/run/save"; import { shelfGoods } from "../web/src/tide/run-day"; import { haulLine } from "../web/src/season/model"; +import { BROWSER_DAY, prepareBrowser } from "./browser-fixtures"; -// Bram's shelf panels, against the live season. views (public RPC). +// Bram's shelf panels use deterministic public-view responses; no network leaves the fixtures. // Signed out uses the real game; signed in uses the dev-only harness, whose signing is mocked. const shots=resolve(process.argv[2]??await mkdtemp(join(tmpdir(),"season-shots-")));await mkdir(shots,{recursive:true}); const server=await createServer({root:resolve(import.meta.dir,"../web"),envDir:false,envPrefix:[],cacheDir:await mkdtemp(join(tmpdir(),"familiar-season-")),logLevel:"error", @@ -18,7 +19,7 @@ const server=await createServer({root:resolve(import.meta.dir,"../web"),envDir:f const bookKey="familiar.expedition.local.v2:tide-run.v1"; /** Today's daily tide as the cautious bot sails it; it banks reed or glass on the days probed, and the suite fails loudly if not. */ function dailyTide() { - let daily=startTide({seed:Math.floor(Date.now()/86_400_000)}); + let daily=startTide({seed:BROWSER_DAY}); while(daily.outcome==="active")daily=applyMove(daily,cautiousMove(daily,VALUE))!.after; const goods=shelfGoods(dayResult(daily)); assert.ok(goods[0]+goods[1]>0,"today's cautious tide brings reed or glass home"); @@ -37,6 +38,7 @@ try{ try{ for(const viewport of [{width:390,height:844},{width:1440,height:900}]){ const tag=`${viewport.width}x${viewport.height}`,page=await browser.newPage({viewport}); + const network=await prepareBrowser(page,origin,BROWSER_DAY); await page.goto(new URL("/outing/?play",origin).href); await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true",{timeout:30000}); await page.locator(".exp-place-bram").click(); @@ -157,7 +159,7 @@ try{ await expect(page.locator(".ss-status")).toContainText("Shelved 1 glass and 1 reed bundle: 100% of the best haul",{timeout:10000}); await page.screenshot({path:join(shots,`harness-docked-${tag}.png`)}); } - await page.close(); + network.assertClean();await page.close(); console.info(`${tag}: preview shelf/sell/run haul/shelve/wish and harness ledger/refusal/sale/wish/postcard passed`); } }finally{await browser.close();} diff --git a/scripts/test-tide-browser.ts b/scripts/test-tide-browser.ts index e0cdf07..25af743 100644 --- a/scripts/test-tide-browser.ts +++ b/scripts/test-tide-browser.ts @@ -1,7 +1,9 @@ import { guide } from "./browser-controls"; +import { BROWSER_DAY, prepareBrowser } from "./browser-fixtures"; import assert from "node:assert/strict"; import { mkdir, mkdtemp } from "node:fs/promises"; import { join, resolve } from "node:path"; +import { tmpdir } from "node:os"; import { chromium, expect, type Page } from "@playwright/test"; import { createServer } from "vite"; import { TURN_LIMIT, type Command } from "../web/src/expedition/types"; @@ -16,7 +18,7 @@ import { haulLine } from "../web/src/season/model"; declare global { interface Window { tidePops: number[]; restartBusySeen: boolean } } -const day = 20771, card = cardForDay(day), route = solve(card.tool, card.asks, card.best); +const day = BROWSER_DAY, card = cardForDay(day), route = solve(card.tool, card.asks, card.best); assert.ok(route, "today’s card has a solution"); assert.equal(route.length, card.best, "the route uses the card’s best decision count"); const slipRoute = Array.from({ length: TURN_LIMIT }, (_, index) => Array(index + 1).fill("wait")).find(commands => { @@ -29,8 +31,7 @@ const saveKey = "familiar.expedition.local.v2"; const passageKey = `${saveKey}:shore-passages.v1`; const logKey = "familiar.tide.log.v1:preview", pendingKey = "familiar.tide.pending.v1:preview"; const viewport = { width: 412, height: 860 }, tag = "412x860"; -const artifacts = resolve(import.meta.dir, "../test-results/tide-browser"); -await mkdir(artifacts, { recursive: true }); +const artifacts = await mkdtemp(join(tmpdir(), "familiar-tide-browser-")); const shots = resolve(process.argv[2] ?? await mkdtemp(join(artifacts, "shots-"))); await mkdir(shots, { recursive: true }); const server = await createServer({ @@ -110,7 +111,8 @@ async function checkHarborStamp(page: Page) { const card = await harbor.boundingBox(), dock = await navigation.boundingBox(); assert.ok(card && dock && card.y + card.height <= dock.y + 1, "phone harbor card stays above its dock"); } - await expect(harbor.getByRole("button", { name: "Change preparation", exact: true })).toBeVisible(); + await expect(harbor.locator(".exp-preparation")).toHaveCount(0); + await expect(harbor.getByRole("button", { name: "Change preparation", exact: true })).toHaveCount(0); } async function checkStickyPanel(page: Page, label: string) { @@ -200,8 +202,8 @@ 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 today = BROWSER_DAY; + const guardDay = async () => assert.equal(await page.evaluate(() => Math.floor(Date.now() / 86_400_000)), today, "the browser uses the explicit fixture day"); let final = startTide({ seed: today }); while (final.outcome === "active") final = applyMove(final, cautiousMove(final))!.after; const result = dayResult(final), goods = shelfGoods(result); @@ -220,19 +222,21 @@ async function checkDaily(page: Page, origin: string) { await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready", "true", { timeout: 30000 }); const harbor = page.locator(".exp-departure"), panel = page.locator(".exp-panel"); const before = await page.evaluate(key => JSON.parse(localStorage.getItem(key)!).home, saveKey); - await expect(harbor.getByRole("heading", { name: `Today’s tide: ${todayCard.name}.`, exact: true })).toBeVisible(); + await expect(harbor.getByRole("heading", { name: "Today’s Tide Run.", exact: true })).toBeVisible(); await expect(harbor.locator(".exp-primary")).toHaveCount(1); await expect(harbor.locator(".exp-primary")).toHaveText("See today’s tide"); await captureLayouts(page, "daily-harbor", () => checkHarborStamp(page)); await harbor.getByRole("button", { name: "See today’s tide", exact: true }).click(); - await expect(page.getByRole("dialog", { name: "Today’s tide", exact: true })).toBeVisible(); - await expect(panel.getByRole("heading", { name: todayCard.name, exact: true })).toBeVisible(); + await expect(page.getByRole("dialog", { name: "Today’s Tide Run", exact: true })).toBeVisible(); + await expect(panel.getByRole("heading", { name: "Today’s Tide Run", exact: true })).toBeVisible(); + await expect(panel.getByText("Your first finished daily outing sets that day’s score and stamps, even if the tide turns or Bram brings Mochi home. Later sails are practice. Pausing does not finish an outing.", { exact: true })).toBeVisible(); + await expect(panel.getByText("A paused outing keeps its original day.", { exact: true })).toBeVisible(); await expect(panel.locator(".tide-list > li")).toHaveCount(3); for (const stamp of STAMPS) await expect(panel.getByText(stamp.ask(result.guess), { exact: true })).toBeVisible(); await expect(panel.locator(".exp-primary")).toHaveCount(1); await expect(panel.locator(".exp-primary")).toHaveText("Sail today’s tide"); await captureLayouts(page, "daily-ask"); - guardDay(); + await guardDay(); await panel.getByRole("button", { name: "Sail today’s tide", exact: true }).click(); const run = page.getByTestId("tide-run"); await expect(run).toHaveAttribute("data-seed", String(today)); @@ -242,7 +246,7 @@ async function checkDaily(page: Page, origin: string) { await guide(page,move); } await expect(page.getByRole("dialog", { name: "Home", exact: true })).toBeVisible({ timeout: 15000 }); - guardDay(); + await guardDay(); await expect(panel.getByRole("heading", { name: resultTitle(result), exact: true })).toBeVisible(); await expect(panel.locator(".tide-home-sub")).toHaveText(resultLine(result)); const checkStamps = async () => { @@ -273,9 +277,8 @@ async function checkDaily(page: Page, origin: string) { assert.deepEqual(book.days[0], final, "the saved daily trace reproduces the engine result"); await panel.getByRole("button", { name: "See the tide log", exact: true }).click(); await expect(panel.locator(".tide-log-run")).toBeVisible(); - await expect(panel.getByRole("heading", { name: todayCard.name, exact: true })).toBeVisible(); - await expect(panel.getByText(`${dayLabel(today)} · tide run`, { exact: true })).toBeVisible(); - for (const [name, value] of [["Banked", result.score], ["Bram’s guess", result.guess], ["Splashes", result.splashes]] as const) { + await expect(panel.getByRole("heading", { name: `Tide Run · ${dayLabel(today)}`, exact: true })).toBeVisible(); + for (const [name, value] of [["Score", result.score], ["Bram’s guess", result.guess], ["Splashes", result.splashes]] as const) { await expect(panel.locator(".tide-facts > div").filter({ has: page.getByText(name, { exact: true }) }).locator("dd")).toHaveText(String(value)); } await checkStamps(); @@ -291,24 +294,23 @@ async function checkDaily(page: Page, origin: string) { await expect(shelve).toBeVisible({ timeout: 15000 }); await expect(panel.locator(".ss-run-haul")).toContainText(`From today’s tide run: ${resultLine(result)}.`); await captureLayouts(page, "daily-bram"); - guardDay(); + await guardDay(); await shelve.click(); await expect(panel.locator('.ss-docked[data-docked="true"]')).toContainText("Today’s haul is on Bram’s shelf."); await captureLayouts(page, "daily-shelved"); await panel.getByRole("button", { name: "Close panel", exact: true }).click(); - await expect(harbor.getByRole("heading", { name: `Tomorrow: ${tomorrow.name}.`, exact: true })).toBeVisible(); + await expect(harbor.getByRole("heading", { name: "Tomorrow’s Tide Run.", exact: true })).toBeVisible(); await captureLayouts(page, "daily-tomorrow", () => checkHarborStamp(page)); assert.deepEqual(await page.evaluate(key => JSON.parse(localStorage.getItem(key)!).home, saveKey), before, "the daily run and shelving leave story progress unchanged"); - guardDay(); + await guardDay(); } async function checkMidnight(page: Page, origin: string, mode: "harbor" | "wake" | "outing" | "unmarked-outing" | "override") { const midnight = nextDay * 86_400_000; const outing = mode === "outing" || mode === "unmarked-outing"; const expectedPending = mode === "unmarked-outing" ? null : { day, late: false }; - await page.clock.install({ time: new Date(midnight - 10_000) }); - // Keep a slow asset load from crossing midnight before the scenario starts. - await page.clock.setFixedTime(new Date(midnight - 10_000)); + // Load within the fixture day, then move near midnight once the scene is ready. + await page.clock.install({ time: new Date(day * 86_400_000 + 43_200_000) }); await page.emulateMedia({ reducedMotion: "reduce" }); await page.addInitScript(({ saveKey, passageKey, pendingKey, blockPending }) => { localStorage.setItem(saveKey, JSON.stringify({ @@ -328,9 +330,10 @@ async function checkMidnight(page: Page, origin: string, mode: "harbor" | "wake" await page.goto(new URL(`/outing/?play${mode === "override" ? `&tide-day=${day}` : ""}`, origin).href); await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready", "true", { timeout: 30000 }); await page.clock.setSystemTime(new Date(midnight - 10_000)); + await page.evaluate(() => document.dispatchEvent(new Event("visibilitychange"))); await page.clock.pauseAt(new Date(midnight - 1_000)); const harbor = page.locator(".exp-departure"), panel = page.locator(".exp-panel"); - await expect(harbor).toContainText(card.name); + await expect(harbor).toContainText("Today’s Tide Run."); await openClassic(page); await expect(panel.getByRole("heading", { name: card.name, exact: true })).toBeVisible(); const asks = page.locator(".tide-asks"); @@ -365,7 +368,7 @@ async function checkMidnight(page: Page, origin: string, mode: "harbor" | "wake" const expectedDay = mode === "override" ? day : nextDay, expectedCard = cardForDay(expectedDay); await expect(panel.getByRole("heading", { name: expectedCard.name, exact: true })).toBeVisible(); await panel.getByRole("button", { name: "Close panel", exact: true }).click(); - await expect(harbor).toContainText(expectedCard.name); + await expect(harbor).toContainText("Today’s Tide Run."); await openClassic(page); await panel.getByRole("button", { name: "Sail today’s tide", exact: true }).click(); assert.deepEqual(await page.evaluate(key => JSON.parse(localStorage.getItem(key)!), pendingKey), { day: expectedDay, late: false }, "the first Sail after midnight uses the displayed day"); @@ -377,13 +380,17 @@ try { const origin = server.resolvedUrls!.local[0]!; const browser = await chromium.launch(); const errors: string[] = []; + const networks: Awaited>[] = []; try { const dailyPage = await browser.newPage({ viewport }); + const dailyNetwork = await prepareBrowser(dailyPage, origin, day); + networks.push(dailyNetwork); dailyPage.on("pageerror", error => errors.push(error.message)); try { await checkDaily(dailyPage, origin); } - finally { await dailyPage.close(); } + finally { dailyNetwork.assertClean(); await dailyPage.close(); } const page = await browser.newPage({ viewport }); - await page.clock.install({ time: new Date(day * 86_400_000 + 43_200_000) }); + const network = await prepareBrowser(page, origin, day); + networks.push(network); page.on("pageerror", error => errors.push(error.message)); const game = page.getByTestId("expedition-game"), world = page.getByTestId("expedition-world"); const harbor = page.locator(".exp-departure"), panel = page.locator(".exp-panel"); @@ -417,6 +424,15 @@ try { await expect(chartOpener).toBeFocused(); } await page.setViewportSize(viewport); + await page.getByRole("button", { name: "Harbor chart", exact: true }).and(page.locator(":visible")).click(); + await panel.locator(".harbor-routes > li").filter({ hasText: "Wind Gate" }).getByRole("button").click(); + await expect(panel.getByRole("heading", { name: "What shall we bring?", exact: true })).toBeVisible(); + await expect(panel.getByRole("radio", { name: "Wind Gate", exact: true })).toBeChecked(); + await expect(panel.locator(".exp-wind-brief")).toHaveText("The wheel on the far bank steers the tide. Charge the left and center outlets to free the harbor’s signal vane."); + await panel.getByRole("radio", { name: /^Lantern/ }).check(); + await expect(panel.getByRole("radio", { name: /^Lantern/ })).toBeChecked(); + await panel.getByRole("radio", { name: /^Rope/ }).check(); + await panel.getByRole("button", { name: "Close panel", exact: true }).click(); for (const place of await page.locator(".exp-home-places button:visible").all()) { await place.hover(); assert.ok(await place.evaluate(button => { @@ -772,12 +788,15 @@ try { await expect(panel.locator(".tide-page-stamp .tide-stamp")).not.toHaveAttribute("data-press", "true"); for (const mode of ["harbor", "wake", "outing", "unmarked-outing", "override"] as const) { const midnightPage = await browser.newPage({ viewport }); + const midnightNetwork = await prepareBrowser(midnightPage, origin, day, { clock: false }); + networks.push(midnightNetwork); midnightPage.on("pageerror", error => errors.push(error.message)); try { await checkMidnight(midnightPage, origin, mode); } - finally { await midnightPage.close(); } + finally { midnightNetwork.assertClean(); await midnightPage.close(); } } } finally { - await browser.close(); + try { for (const network of networks) network.assertClean(); } + finally { await browser.close(); } assert.deepEqual(errors, [], "uncaught browser errors"); } console.info(`${tag}, 390x844, 844x390, 1280x800, 1440x900: daily harbor/ask, cautious run, engine-matched Home/haul/stamps, run log, Bram shelving/tomorrow; classic Chart court, tray/holding layouts, solved/best log, earlier-day range, both restarts, UTC midnight rollover; 44px panels/no sideways overflow passed`); diff --git a/scripts/test-tide-run-browser.ts b/scripts/test-tide-run-browser.ts index bac5976..fb79355 100644 --- a/scripts/test-tide-run-browser.ts +++ b/scripts/test-tide-run-browser.ts @@ -1,14 +1,16 @@ /** 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 { guide, worldAction, buttonControls, sailStory } from "./browser-controls"; +import { BROWSER_DAY, prepareBrowser } from "./browser-fixtures"; import { mkdtemp } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; -import { chromium, webkit, expect } from "@playwright/test"; +import { chromium, webkit, expect, type Locator, type Page } from "@playwright/test"; import { createServer } from "vite"; -import { VALUE, applyMove, startTide, type Move, type TideStart } from "../web/src/run/engine"; +import { VALUE, applyMove, replayTide, startTide, type Move, type TideStart } from "../web/src/run/engine"; import { cautiousMove } from "../web/src/run/bot"; import { storyStart } from "../web/src/run/story"; +import { dayLabel } from "../web/src/tide/cards"; const KEY: Record = { north: "ArrowUp", south: "ArrowDown", west: "ArrowLeft", east: "ArrowRight", wait: "Space", home: "r" }; /** The cautious bot's route. In a story tide it wants the chapter's prize above everything. */ @@ -28,6 +30,99 @@ const server = await createServer({ server: { host: "127.0.0.1", port: 0, hmr: false, watch: null }, }); const bookKey = "familiar.expedition.local.v2:tide-run.v1"; +const zeroLens:Move[]=["north","north","north","south","north","west","north","south","south","south","east"]; +const zeroLensState=replayTide(storyStart("lens"),zeroLens)!; +assert.equal(zeroLensState.outcome,"active");assert.equal(zeroLensState.score,0);assert(zeroLensState.banked.includes("lens")); + +/** Visibility alone permits clipped text and controls covered by their siblings. */ +async function readable(locator:Locator) { + await expect(locator).toBeVisible(); + await expect.poll(()=>locator.evaluate(node=>{ + const rect=node.getBoundingClientRect(),issues:string[]=[]; + if(rect.left<0||rect.top<0||rect.right>innerWidth+1||rect.bottom>innerHeight+1)issues.push("outside viewport"); + for(let parent=node.parentElement;parent;parent=parent.parentElement){ + const style=getComputedStyle(parent),clip=parent.getBoundingClientRect(); + if(/auto|scroll|hidden|clip/.test(style.overflowY)&&(rect.topclip.top+parent.clientTop+parent.clientHeight+1))issues.push(`clipped vertically by ${parent.className}`); + if(/auto|scroll|hidden|clip/.test(style.overflowX)&&(rect.leftclip.left+parent.clientLeft+parent.clientWidth+1))issues.push(`clipped horizontally by ${parent.className}`); + } + for(const y of [rect.top+2,rect.top+rect.height/2,rect.bottom-2]){ + const hit=document.elementFromPoint(rect.left+rect.width/2,y); + if(!hit||!node.contains(hit))issues.push(`covered at y=${y}`); + } + return issues; + })).toEqual([]); +} + +async function scrolledRules(panel:Locator) { + const header=panel.locator(".exp-panel-header"),body=panel.locator(".exp-panel-body"); + await expect.poll(()=>body.evaluate(node=>node.scrollHeight>node.clientHeight)).toBe(true); + await body.focus();await body.press("End"); + await expect(body).toHaveCSS("outline-offset","-3px"); + await expect.poll(()=>body.evaluate(node=>node.scrollTop)).toBeGreaterThan(0); + for(const position of [0.5,1]){ + await body.evaluate((node,position)=>{node.scrollTop=(node.scrollHeight-node.clientHeight)*position;},position); + await readable(header.getByRole("heading")); + await readable(header.getByRole("button",{name:"Close panel",exact:true})); + const geometry=await header.evaluate(node=>{ + const rect=node.getBoundingClientRect(),panel=node.parentElement!,bounds=panel.getBoundingClientRect(); + return {fullWidth:rect.left<=bounds.left+panel.clientLeft+1&&rect.right>=bounds.left+panel.clientLeft+panel.clientWidth-1, + atTop:Math.abs(rect.top-bounds.top-panel.clientTop)<2,background:getComputedStyle(node).backgroundColor, + uncovered:[rect.left+2,rect.right-2].filter(x=>!node.contains(document.elementFromPoint(x,rect.top+rect.height/2)))}; + }); + assert(geometry.fullWidth&&geometry.atTop,`rules header covers the full scrolled panel: ${JSON.stringify(geometry)}`); + assert.match(geometry.background,/^rgb\(/,"rules header is opaque"); + assert.deepEqual(geometry.uncovered,[],"scrolled rules cannot show through beside the heading and close control"); + assert.equal(await panel.evaluate(node=>node.scrollTop),0,"only rules scroll; the full-width heading stays outside their scrollbar"); + } + await body.evaluate(node=>{node.scrollTop=0;}); +} + +async function trayExplanations(page:Page) { + await page.locator(".tide-controls .exp-input-reading").evaluate(node=>{node.scrollTop=0;}); + for(const selector of [".tide-dock-instruction",".tide-pause-explanation"]){ + const explanation=page.locator(selector); + await readable(explanation); + } +} + +async function guidanceOverflow(page:Page) { + const reading=page.getByRole("region",{name:"Outing guidance",exact:true}),more=page.getByRole("button",{name:"Read more outing guidance",exact:true}); + const scrollState=()=>reading.evaluate(node=>({top:node.scrollTop,remaining:Math.max(0,node.scrollHeight-node.clientHeight-node.scrollTop),more:!!node.parentElement?.querySelector(".exp-input-more")})); + const settled=async()=>{ + let previous:Awaited>|undefined; + await expect.poll(async()=>{ + const state=await scrollState(),stable=previous!==undefined&&state.top===previous.top&&state.remaining===previous.remaining; + previous=state; + return stable&&state.more===(state.remaining>1); + },{intervals:[100]}).toBe(true); + return previous!; + }; + await reading.evaluate(node=>{node.scrollTop=0;}); + const overflows=(await settled()).remaining>1; + await expect(more).toHaveCount(overflows?1:0); + if(!overflows)return; + await readable(more); + await readable(page.locator(".exp-button-controls summary")); + await readable(page.getByTestId("tide-guide")); + const saved=await page.evaluate(key=>localStorage.getItem(key),bookKey); + await reading.focus();await page.keyboard.press("ArrowDown"); + await expect.poll(()=>reading.evaluate(node=>node.scrollTop>0||node.scrollHeight<=node.clientHeight+1)).toBe(true); + let position=await settled(); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),saved,"scrolling guidance with arrow keys never moves Mochi"); + while(position.remaining>1){ + const before=position.top; + await readable(more); + await more.click(); + await expect.poll(()=>reading.evaluate(node=>node.scrollTop)).toBeGreaterThan(before); + position=await settled(); + } + await expect(more).toHaveCount(0); + await expect(reading).toBeFocused(); + await page.locator(".tide-pause-explanation").scrollIntoViewIfNeeded(); + await readable(page.locator(".tide-pause-explanation")); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),saved,"revealing all guidance preserves the exact outing trace"); + await reading.evaluate(node=>{node.scrollTop=0;}); +} try { await server.listen(); const origin = new URL(server.resolvedUrls!.local[0]!); @@ -35,24 +130,117 @@ try { 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()); + const probeNetwork=await prepareBrowser(probe,origin,BROWSER_DAY); 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"); + await sailStory(probe);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(); + for(const failFiling of [false,true]){ + await probe.evaluate(()=>localStorage.clear());await probe.reload();await expect(probe.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await sailStory(probe); + await expect(probe.getByTestId("tide-world")).toHaveAttribute("data-ready","true"); + for(const [index,move] of zeroLens.entries()){ + await expect(probeRun).toHaveAttribute("data-busy","false"); + await guide(probe,move); + await expect(probeRun).toHaveAttribute("data-beat",String(index+1)); + assert.deepEqual(await probe.evaluate(key=>JSON.parse(localStorage.getItem(key)!).active.moves,bookKey),zeroLens.slice(0,index+1),"each ready command saves the canonical zero-score route exactly once"); + } + await expect(probeRun).toHaveAttribute("data-busy","false"); + await expect(probe.getByTestId("tide-score")).toHaveText("0");await expect(probe.getByText("Lens safe",{exact:true})).toBeVisible(); + await readable(probe.getByTestId("tide-prize-status")); + await readable(probe.getByTestId("tide-finish-return")); + await trayExplanations(probe); + if(!failFiling)for(const size of [{width:320,height:480},{width:390,height:844},{width:844,height:390}]){ + await probe.setViewportSize(size); + await readable(probe.getByTestId("tide-prize-status")); + await readable(probe.getByTestId("tide-finish-return")); + await guidanceOverflow(probe); + await buttonControls(probe);await readable(probe.locator(".exp-button-controls-body"));await buttonControls(probe,false); + await probe.screenshot({path:join(cacheDir,`${engine.name()}-lens-safe-zero-score-${size.width}x${size.height}.png`)}); + } + await probe.setViewportSize({width:390,height:844}); + await probe.evaluate(({bookKey,failFiling})=>{ + const write=Storage.prototype.setItem,events:(Record)[]=[];(window as any).__filingEvents=events;let refused=false; + Storage.prototype.setItem=function(key,value){ + if(key===bookKey||key==="familiar.expedition.local.v2"){ + const parsed=JSON.parse(value);events.push({key,lastMove:parsed.active?.moves?.at(-1)??null,closed:key===bookKey&&parsed.active===null,busy:document.querySelector('[data-testid="tide-run"]')?.getAttribute("data-busy")??null}); + if(failFiling&&key==="familiar.expedition.local.v2"&&!refused){refused=true;throw new DOMException("Saving is blocked","QuotaExceededError");} + } + return write.call(this,key,value); + }; + },{bookKey,failFiling}); + await probe.getByTestId("tide-finish-return").click(); + if(failFiling){ + await expect(probeRun.getByRole("alert")).toHaveText("This return could not be saved. Keep this finished outing open and try again when this browser can save."); + await probe.waitForTimeout(150); + const failed=await probe.evaluate(key=>({events:(window as any).__filingEvents,trace:JSON.parse(localStorage.getItem(key)!).active}),bookKey); + assert.equal(failed.events.filter((event:{key:string})=>event.key==="familiar.expedition.local.v2").length,1,"failed explicit filing is not automatically retried"); + assert.equal(replayTide(failed.trace,failed.trace.moves)?.outcome,"home");assert.deepEqual(failed.trace.moves,[...zeroLens,"home"]); + await expect(probe.locator('[data-action="home-next"]')).toHaveCount(0); + await probe.getByTestId("tide-finish").click(); + } + await expect(probe.getByTestId("expedition-world")).toHaveAttribute("data-ready","true"); + await expect(probe.getByRole("button",{name:"Fit the Beacon Lens",exact:true})).toBeVisible(); + const filed=await probe.evaluate(key=>({events:(window as any).__filingEvents,book:JSON.parse(localStorage.getItem(key)!)}),bookKey); + assert.equal(filed.events[0].key,bookKey);assert.equal(filed.events[0].lastMove,"home","finish transition is saved before filing"); + assert(filed.events.filter((event:{key:string})=>event.key==="familiar.expedition.local.v2").every((event:{busy:string})=>event.busy==="false"),"harbor filing follows settled presentation"); + assert.equal(filed.events.filter((event:{closed:boolean})=>event.closed).length,1,"the accepted return closes once");assert.equal(filed.book.active,null); + } + const finishedTrace={...storyStart("lens"),moves:[...zeroLens,"home"] as Move[]}; + assert.equal(replayTide(finishedTrace,finishedTrace.moves)?.outcome,"home"); + await probe.evaluate(({bookKey,trace})=>{ + localStorage.clear();localStorage.setItem(bookKey,JSON.stringify({version:1,active:trace,days:[]})); + },{bookKey,trace:finishedTrace}); + await probe.reload(); + await expect(probeRun).toHaveAttribute("data-outcome","home"); + await expect(probe.getByTestId("tide-world")).toHaveAttribute("data-ready","true"); + const restored=await probe.evaluate(key=>localStorage.getItem(key),bookKey); + await probe.locator('[data-testid="tide-world"] canvas').evaluate(canvas=>canvas.dispatchEvent(new Event("webglcontextlost",{cancelable:true}))); + await expect(probeRun.locator(".exp-fault")).toContainText("The drawing surface stopped."); + assert.equal(await probe.evaluate(key=>localStorage.getItem(key),bookKey),restored,"renderer failure preserves the restored finished trace"); + await expect(probe.getByTestId("tide-leave")).toBeEnabled(); + await expect(probe.getByTestId("tide-finish")).toBeEnabled(); + await readable(probe.getByTestId("tide-leave")); + await probe.evaluate(bookKey=>{ + const write=Storage.prototype.setItem,events:{key:string;closed:boolean;refused:boolean}[]=[];(window as any).__faultFilingEvents=events;let refused=false; + Storage.prototype.setItem=function(key,value){ + if(key===bookKey||key==="familiar.expedition.local.v2"){ + const closed=key===bookKey&&JSON.parse(value).active===null,fail=closed&&!refused; + events.push({key,closed,refused:fail}); + if(fail){refused=true;throw new DOMException("Saving is blocked","QuotaExceededError");} + } + return write.call(this,key,value); + }; + },bookKey); + await probe.getByTestId("tide-leave").click(); + await expect(probeRun.locator(".tide-finish [role=alert]")).toHaveText("This return could not be saved. Keep this finished outing open and try again when this browser can save."); + await probe.waitForTimeout(150); + const failedFaultReturn=await probe.evaluate(key=>({events:(window as any).__faultFilingEvents,raw:localStorage.getItem(key),home:JSON.parse(localStorage.getItem("familiar.expedition.local.v2")!).home}),bookKey); + assert.deepEqual(failedFaultReturn.events,[{key:"familiar.expedition.local.v2",closed:false,refused:false},{key:bookKey,closed:true,refused:true}],"a faulted renderer permits one explicit filing attempt without automatic retry"); + assert.equal(failedFaultReturn.raw,restored,"a failed close preserves the exact finished trace for retry"); + assert.deepEqual(failedFaultReturn.home.banked,["lens"],"the harbor prize survives a failed TideBook close"); + await expect(probeRun.locator(".exp-fault")).toBeVisible(); + await expect(probe.locator('[data-action="home-next"]')).toHaveCount(0); + await probe.getByTestId("tide-leave").click(); + await expect(probe.getByTestId("expedition-world")).toHaveAttribute("data-ready","true"); + await expect(probe.getByRole("button",{name:"Fit the Beacon Lens",exact:true})).toBeVisible(); + const filedFaultReturn=await probe.evaluate(key=>({events:(window as any).__faultFilingEvents,book:JSON.parse(localStorage.getItem(key)!),home:JSON.parse(localStorage.getItem("familiar.expedition.local.v2")!).home}),bookKey); + assert.equal(filedFaultReturn.events.length,4,"retry makes exactly one further filing attempt"); + assert.equal(filedFaultReturn.events.filter((event:{closed:boolean;refused:boolean})=>event.closed&&!event.refused).length,1,"the faulted story return closes exactly once"); + assert.deepEqual(filedFaultReturn.home.banked,["lens"],"retry does not duplicate the recovered prize"); + assert.equal(filedFaultReturn.book.active,null);assert.deepEqual(filedFaultReturn.book.days,[]); + probeNetwork.assertClean();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()); + const network=await prepareBrowser(page,origin,BROWSER_DAY); - const run = page.getByTestId("tide-run"), link = page.locator('[data-action="tide-run"]'), title = page.locator(".exp-departure h1"); + const run = page.getByTestId("tide-run"), title = page.locator(".exp-departure h1"); const harbor = () => expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready", "true"); const passTitle = async (tide = false) => { await expect(page.getByTestId("opening")).toHaveAttribute("data-mode", "title"); @@ -112,12 +300,13 @@ try { for (const key of ["familiar.expedition.local.v2", bookKey]) { await failNextWrite(key); await page.getByTestId("tide-finish").click(); - await expect(run.getByRole("alert")).toHaveText("This tide could not be saved. Try it again when this browser can save."); + await expect(run.getByRole("alert")).toHaveText("This return could not be saved. Keep this finished outing open and try again when this browser can save."); await expect(page.getByTestId("tide-finish")).toBeEnabled(); assert.deepEqual((await home()).banked, key === bookKey ? ["lens"] : []); + await expect(page.locator('[data-action="home-next"]')).toHaveCount(0); } } else if (!start.story) { - await expect(run.getByRole("alert")).toHaveText("This tide could not be saved. Try it again when this browser can save."); + await expect(run.getByRole("alert")).toHaveText("This return could not be saved. Keep this finished outing open and try again when this browser can save."); await expect(page.getByTestId("tide-finish")).toBeEnabled(); } await page.getByTestId("tide-finish").click(); @@ -129,6 +318,13 @@ try { await passTitle(); await harbor(); await expect(title).toHaveText("First light."); await page.locator('[data-action="story"]').click(); + const storyPreparation=page.locator('.exp-panel[data-surface="story"]'); + await expect(storyPreparation).toContainText("Chapter 1: First light"); + await expect(storyPreparation).toContainText("Eight waves. Only moving or waiting advances the water."); + await storyPreparation.locator("summary").click(); + await scrolledRules(storyPreparation); + await page.screenshot({path:join(cacheDir,`${engine.name()}-chapter-1-preparation-390x844.png`)}); + await storyPreparation.getByRole("button",{name:"Sail with Mochi",exact:true}).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); @@ -143,6 +339,8 @@ try { }); 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 guidanceOverflow(page); + await buttonControls(page);await readable(page.locator(".exp-button-controls-body"));await buttonControls(page,false); await page.screenshot({path:join(cacheDir,`${engine.name()}-hints-${size.width}x${size.height}.png`)}); } await page.setViewportSize({width:390,height:844}); @@ -152,7 +350,9 @@ try { 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"); + await trayExplanations(page); const guideButton=page.getByTestId("tide-guide");await guideButton.tap();await expect(page.getByRole("dialog")).toBeVisible(); + await scrolledRules(page.getByRole("dialog")); 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"); @@ -173,57 +373,76 @@ try { await expect(title).toHaveText("The lens is home."); assert.deepEqual((await home()).banked, ["lens"]); await page.locator('[data-action="home-next"]').click(); - await page.getByRole("button", { name: "Restore the beacon" }).click(); + await page.getByRole("button", { name: "Fit the Beacon Lens" }).click(); - await expect(page.locator('[data-action="tide"]')).toBeVisible(); - await expect(link).toHaveAttribute("title", "Chapter 2: What the tide brings"); - await link.click(); + await expect(page.locator(".exp-departure-heading p")).toHaveText("The beacon is lit. Bram needs the Signal Vane to read the wind. Bring it home from the right shell."); + await expect(page.getByRole("button",{name:"Today’s tide · optional",exact:true})).toBeVisible(); + const beforeOptional=await page.evaluate(key=>localStorage.getItem(key),bookKey); + await page.getByRole("button",{name:"Today’s tide · optional",exact:true}).click(); + await expect(page.getByRole("heading",{name:"Today’s Tide Run",exact:true})).toBeVisible(); + await expect(page.getByRole("dialog")).toContainText("Your first finished daily outing sets that day’s score and stamps, even if the tide turns or Bram brings Mochi home. Later sails are practice. Pausing does not finish an outing."); + await page.screenshot({path:join(cacheDir,`${engine.name()}-optional-daily-390x844.png`)}); + await page.keyboard.press("Escape"); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),beforeOptional,"opening optional daily preparation does not start or score an outing"); + await sailStory(page); + await expect(page.getByTestId("tide-feedback")).toHaveText("The beacon is lit. Bram needs the Signal Vane to read the wind. Bring it home from the right shell."); await press(route(storyStart("vane")).keys.slice(0, 3)); + await trayExplanations(page); + await page.screenshot({path:join(cacheDir,`${engine.name()}-vane-beat-3-readable-390x844.png`)}); await page.reload(); await passTitle(true); await expect(run).toHaveAttribute("data-beat", "3"); await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready", "true"); + await trayExplanations(page); await page.getByTestId("tide-leave").click(); - const waitingAsk = page.locator('.exp-panel[data-surface="tide"]'); - await expect(waitingAsk).toBeVisible(); - await waitingAsk.locator(".exp-primary").click(); + const pausedVane=await page.evaluate(key=>localStorage.getItem(key),bookKey); + await expect(page.locator('[data-action="resume"]')).toBeVisible(); + await page.locator('[data-action="resume"]').click(); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),pausedVane,"resume bypasses preparation without rewriting the original trace"); await expect(run).toHaveAttribute("data-story", "vane"); await expect(run).toHaveAttribute("data-beat", "3"); await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready", "true"); await page.getByTestId("tide-leave").click(); await harbor(); - await expect(link).toHaveAttribute("title", "Return to the tide Mochi left"); - await expect(title).toHaveText("The tide is waiting."); + await expect(title).toHaveText("The outing is waiting."); await page.locator('[data-action="resume"]').click(); await expect(run).toHaveAttribute("data-story", "vane"); await expect(run).toHaveAttribute("data-beat", "3"); await sail(storyStart("vane"), 3); - await expect(link).toHaveAttribute("title", "Fit the Signal Vane"); - await link.click(); - await page.getByRole("button", { name: "Repair the signal post" }).click(); + await page.getByRole("button",{name:"Fit the Signal Vane",exact:true}).click(); + await page.getByRole("button", { name: "Fit the Signal Vane" }).click(); - await expect(link).toHaveAttribute("title", "Chapter 3: The last thing"); - await link.click(); + await sailStory(page); await sail(storyStart("moth")); assert.deepEqual((await home()).banked, ["lens", "vane", "moth"]); await page.locator('[data-action="tide"]').click(); const ask = page.locator('.exp-panel[data-surface="tide"]'); await expect(ask).toBeVisible(); + await expect(ask.locator(".tide-day")).toHaveText(dayLabel(BROWSER_DAY)); + await network.setTime((BROWSER_DAY+1)*86_400_000+43_200_000); + await page.evaluate(()=>document.dispatchEvent(new Event("visibilitychange"))); + await expect(ask.locator(".tide-day")).toHaveText(dayLabel(BROWSER_DAY+1)); await ask.locator(".exp-primary").click(); + await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready", "true"); + await trayExplanations(page); + await page.screenshot({path:join(cacheDir,`${engine.name()}-daily-guidance-390x844.png`)}); const day = Number(await run.getAttribute("data-seed")); assert.equal(day, await page.evaluate(() => Math.floor(Date.now() / 86_400_000))); const daily = await sail({ seed: day }); const sheet = page.locator('.exp-panel[data-surface="home"]'); await expect(sheet).toBeVisible(); await expect(sheet.locator(".tide-home-note")).toHaveCount(0); + await page.screenshot({path:join(cacheDir,`${engine.name()}-daily-home-390x844.png`)}); const book = await page.evaluate(key => JSON.parse(localStorage.getItem(key)!), bookKey); assert.equal(book.active, null); assert.deepEqual(book.days.map((entry: { seed: number; moves: string[] }) => [entry.seed, entry.moves.length]), [[day, daily.moves.length]]); await sheet.locator(".exp-secondary").click(); await expect(page.locator('.exp-panel[data-surface="log"] .tide-log-run')).toBeVisible(); + await page.screenshot({path:join(cacheDir,`${engine.name()}-daily-log-390x844.png`)}); await page.keyboard.press("Escape"); await page.locator(".exp-departure-buttons > .exp-secondary").click(); + await expect(ask).toBeVisible();await ask.locator(".exp-primary").click(); await expect(run).toHaveAttribute("data-seed", String(day)); await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready", "true"); await buttonControls(page);await page.locator('[data-move="wait"]').tap();await buttonControls(page,false); @@ -233,7 +452,11 @@ try { await expect(run).toHaveAttribute("data-beat", "1"); await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready", "true"); await page.getByTestId("tide-leave").click(); - await waitingAsk.locator(".exp-primary").click(); + const pausedDaily=await page.evaluate(key=>localStorage.getItem(key),bookKey); + await network.setTime((day+1)*86_400_000+43_200_000); + await page.evaluate(()=>document.dispatchEvent(new Event("visibilitychange"))); + await page.locator('[data-action="resume"]').click(); + assert.equal(await page.evaluate(key=>localStorage.getItem(key),bookKey),pausedDaily,"resuming after UTC rollover preserves the original day and moves"); 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"); @@ -245,6 +468,7 @@ try { assert.deepEqual(practiced.days, book.days); assert.notEqual(daily.moves.length, 2); assert.deepEqual(errors, []); + network.assertClean(); 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(); } } diff --git a/web/DESIGN.md b/web/DESIGN.md index 67d11d9..821a146 100644 --- a/web/DESIGN.md +++ b/web/DESIGN.md @@ -10,7 +10,7 @@ Portrait keeps all three columns and both banks visible. Organic sandstone platf 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. -At home, Beacon, Bram, Workbench and Satchel are places in the scene. The primary action follows the returned cargo, then restoration, then an earned light, then Wind Gate. Account lives in the menu. The origin diorama distinguishes a validated device memory from an actual maker's accepted NEAR event. Familiar has one playable edition. Old routes and invitation flags open the current game without modifying their original saved records. +At home, Beacon, Bram, Workbench and Satchel are places in the scene. In the device harbor, the primary action follows an open outing or pending finished return, then lens/vane installation, then the next story chapter. After the moth is home, it follows the daily card. Account lives in the menu. The origin diorama distinguishes a validated device memory from an actual maker's accepted NEAR event. Old routes and invitation flags open the current game without modifying their original saved records. Local previews, confirmed NEAR testnet ownership and uncertain operations retain explicit truthful labels. An immersive visual treatment cannot replace recovery, canonical state or receipt verification. Device and human playtest evidence belongs in `../PROGRESS.md` and `../JUDGES.md`. @@ -24,7 +24,9 @@ The painted world already matches the Pocket Harbor concept; the interface layer - **Focus and hover.** Focus is a 3px `#2b5f4d` outline on cream and a 3px `#fff5ce` outline over the scene; painted objects (title planks, place signs) get a shape-following glow instead. Generic hover rules sit inside `:where()` so a component's own colors always win; hover never erases a label. - **Motion.** One authored moment per screen: the stamp pressing onto the Home sheet, the asks ticking in after it. Everything else is still, and reduced motion shows the final state. -**Harbor home** shows the loop's next step and nothing else: Take it to Bram when a find came home today and is not yet shelved, See today's ask before the day's tide, the result with Sail again after it, and Tomorrow's card once Bram has shelved the haul. Desktop uses a bottom-centre bar with the Chart and Log pills top right; phones use a card above a four-item dock (Chart, Log, Satchel, Menu); landscape phones use the bar and the top-right pills. Beacon, Bram, Workbench and Satchel are painted standing signs planted on visible ground, never over a character or under a card. +**Harbor home** foregrounds the next story step: Resume outing or Return to the harbor for an unfinished filing; Fit the Beacon Lens/Signal Vane after filing; Prepare Chapter 1/2/3 next. Once lit, Today’s tide · optional is secondary while story work remains. The device card has no unrelated court/tool preparation row. After the moth is home it follows the existing daily result/shelving loop. Desktop uses a bottom-centre bar with the Chart and Log pills top right; phones preserve 12px margins and a four-item dock (Chart, Log, Satchel, Menu); landscape phones use the bar and top-right pills. Painted signs remain on visible ground. + +**Tide Run preparation and return** name the chapter objective, outing length (eight calm waves in Chapter 1; twelve later), reassurance and story/daily result boundary before Sail. Complete rules remain in How Tide Run works; courts retain their own tools and instructions. Reading and native disclosures spend no moves. The active view distinguishes Pause outing, automatic banking on center-dock arrival, Finish and return, successful filing and later installation. Lens/Vane/Moth carried or safe comes from displayed pack/banked state, independently of Score. The prominent finish action stays outside closed Button controls after banking the story prize. Natural endings keep a result card and explicit Return to the harbor; a filing error leaves that action available without automatic retries. Preparation and result prose use contained scrolling with reachable native actions and visible focus. **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. @@ -36,4 +38,4 @@ Swipes resolve only on release and produce one canonical step. A qualifying swip ## Introduction and current entry -The homepage remains the introduction with its Play Familiar action to `/outing/`. `/outing/` opens on a title screen inside the game: the living harbor, the wordmark, one prompt, and a signpost menu. Choosing Continue or New Harbor carries the camera to the dock and a tide wipe hands off to play. `?play` skips the title. Keep the warm coastal imagery and self-hosted Fraunces/Figtree typography. The retired town, motion lab and recovery demo have no navigation links or build entries. Shared Mochi poses and the lantern/origin artwork remain part of Familiar, with essential meaning available through DOM controls and text. +The homepage remains the introduction with its Play Familiar action to `/outing/`. `/outing/` opens on a title screen inside the game: the living harbor, wordmark, native Begin/Continue control and signpost menu. Choosing Begin or Continue carries the camera to the dock and hands off with sound preferences intact. The daily paper enters the harbor without selecting an activity; the public retained-court attract demonstration is disabled. `?play` skips the title. Keep the warm coastal imagery and self-hosted Fraunces/Figtree typography. The retired town, motion lab and recovery demo have no navigation links or build entries. Shared Mochi poses and lantern/origin artwork remain available with essential meaning in DOM controls and text. diff --git a/web/PRODUCT.md b/web/PRODUCT.md index 61f2f2e..d003848 100644 --- a/web/PRODUCT.md +++ b/web/PRODUCT.md @@ -16,7 +16,11 @@ First Light is Familiar's current adventure: guide Mochi through tide decisions, Bell Steps and Reed Steps connect the restored harbor to supply and skiff crossings. After the signal and both services are safely restored, Bram clears the Bell arch. Following Mochi's attention there at low tide reveals a bell. A safe return rigs a single-use pull for future Bell/Reed outings, changing the next surge and bridge route. These side outings and shared discoveries remain device-local, separate from accepted H1 progress. Mochi's contextual idle attention and optional hand greeting spend no decisions and earn no currency or affection points. -The introduction remains the homepage. Play Familiar opens `/outing/`, which starts on a title screen inside the game; Continue or New Harbor hands off to the spatial game and never erases a save. Once the beacon is lit, the harbor card leads to today’s tide run: Today’s tide shows the day’s card, Bram’s guess and the three stamps, and a finished tide opens the Home sheet with its result. Saved harbors keep the Tidekeeper’s three-ask court as their daily; on device harbors it stays reachable from the Chart. Retired town, motion-preview, recovery-demo and classic-game entry points no longer offer separate games. Historical rules and signing/ownership code remain where required to verify old earned returns and original operations; their presence does not expose an old playable edition. +The introduction remains the homepage. Play Familiar opens `/outing/`, which starts on a title screen inside the game; Begin or Continue hands off to the harbor and never erases a save or selects an activity. Public title idle play does not demonstrate the retained court. The player guides Mochi as a volunteer harbor helper. The device story retrieves the Beacon Lens in eight calm waves, then the Signal Vane and wind-moth in twelve waves each. The primary action resumes an outing or retries its unfinished filing, offers a filed lens/vane repair, then prepares the next chapter. Once the beacon is lit, Today’s tide · optional offers daily preparation while story work remains. After the moth is home, the existing daily card leads the harbor. + +Story preparation names the objective and outing length, with complete Tide Run rules in a native disclosure. All new device daily/practice outings also show preparation: twelve waves, rough waves from the seventh, Bram’s guess, and the first-finished-result disclosure. A rescued, tide-turned or voluntary zero-score daily still sets that day’s result; later sails are practice. A paused outing keeps its original day. Story outings do not consume a daily result. A finished daily opens the Home sheet; the Log preserves its result. Saved harbors keep the Tidekeeper’s three-ask court as their daily; device harbors can select it from the Chart. Rope/Lantern and Wind Gate teaching belong to their selected court activity. Bell/Reed access and discovery requirements do not depend on finishing the moth chapter. Retired entry points no longer offer separate games; historical verification and original-operation code remains preserved. + +Carried, banked safe, finished, filed in the harbor and installed are distinct states. Arrival at the center dock banks cargo and leaves the outing open. Pause also leaves it open. Finish ends it without advancing the water; an explicit Finish settles before filing. Failed filing retains the finished trace for deliberate retry. Filing writes the harbor prize before closing the TideBook, so a partial save must continue to offer the pending return ahead of repair. A banked story prize is safe even at zero score; installation remains deliberate after successful filing. Bram’s shelf joins the same daily loop: bring reed or glass home from today’s tide run (up to three of each; pearls stay with Mochi), shelve it, then trade for Shells to fill Mochi’s wish. On saved harbors Bram shelves Beacon Court hauls every other day; a find kept on this device can wait until tomorrow. Signed out, shelving and trades are a labelled device preview; wishes need a saved harbor. diff --git a/web/src/expedition/ControlHints.test.tsx b/web/src/expedition/ControlHints.test.tsx index c11ef8e..f97d17b 100644 --- a/web/src/expedition/ControlHints.test.tsx +++ b/web/src/expedition/ControlHints.test.tsx @@ -23,3 +23,10 @@ test("desktop hints explain movement and the remaining shortcuts as text", () => expect(html).not.toContain('role="application"'); expect(html).not.toContain('aria-live'); }); + +test("outing guidance shares the hint reading area while native controls remain outside it", () => { + const html=renderToStaticMarkup(Banking keeps the outing open.

}>
); + expect(html).toContain('class="exp-input-reading" tabindex="0" role="region" aria-label="Outing guidance"'); + expect(html).toContain('

Banking keeps the outing open.

'); + expect(html).toContain('
'); +}); diff --git a/web/src/expedition/ControlHints.tsx b/web/src/expedition/ControlHints.tsx index cefcd2a..c7c3f69 100644 --- a/web/src/expedition/ControlHints.tsx +++ b/web/src/expedition/ControlHints.tsx @@ -1,11 +1,14 @@ import { useEffect, useRef, useState, type ReactNode } from "react"; +import { scrollReadingRegion } from "./keyboard-scroll"; 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; +export default function ControlHints({id,context="Tap Wait beside Mochi · tap a find to collect it.",children,reading,initialMode,keyboardContext="Space waits · E interacts · R returns at the dock · I inspects"}:{ + id:string; context?:string; children:ReactNode; reading?:ReactNode; initialMode?:InputMode; keyboardContext?:string; }) { const root=useRef(null); + const readingArea=useRef(null); + const [moreReading,setMoreReading]=useState(false); const [mode,setMode]=useState(()=>initialMode??(typeof matchMedia!=="undefined"&&matchMedia("(any-pointer: coarse)").matches?"touch":"keyboard")); useEffect(()=>{ const game=root.current?.closest(".exp-game"); @@ -18,11 +21,22 @@ export default function ControlHints({id,context="Tap Wait beside Mochi · tap a game.addEventListener("pointerup",pointer,true);game.addEventListener("keydown",keyboard,true); return()=>{cancelAnimationFrame(frame);game.removeEventListener("pointerup",pointer,true);game.removeEventListener("keydown",keyboard,true);}; },[]); - return
-
+ useEffect(()=>{ + const area=readingArea.current; + if(!area)return; + const update=()=>setMoreReading(area.scrollTop+area.clientHeight{observer.disconnect();area.removeEventListener("scroll",update);}; + },[reading,mode]); + const help=

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

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

-
+
; + return
+ {reading?
{reading}{help}
:help}
Button controls
{children}
+ {moreReading&&}
; } diff --git a/web/src/expedition/Game.tsx b/web/src/expedition/Game.tsx index 1a6e73b..a78a47e 100644 --- a/web/src/expedition/Game.tsx +++ b/web/src/expedition/Game.tsx @@ -11,6 +11,7 @@ import Inspect, { commandName, forecast } from "./Inspect"; import { applyCommand, findPosition, legalCommands, packSlots, phaseOf, replayCourt, startCourt } from "./engine"; import { commandAt, movementKey } from "./input"; import ControlHints from "./ControlHints"; +import { scrollReadingRegion } from "./keyboard-scroll"; 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"; @@ -32,8 +33,8 @@ import TideLog from "../tide/TideLog"; import TideHome from "../tide/TideHome"; import TideStamp from "../tide/TideStamp"; import { tideSailReason } from "../tide/sailing"; -import TideRunGame from "../run/TideRunGame"; -import { startTide, type TideStart, type TideState } from "../run/engine"; +import TideRunGame, { TideRunRules } from "../run/TideRunGame"; +import { startTide, tideShape, type TideStart, type TideState } from "../run/engine"; import { bramsGuess } from "../run/bot"; import { CHAPTERS, chapterFor, storyStart } from "../run/story"; import { closeTide, dayResults, emptyBook, readBook, shelfHaul, todayResult, writeBook, type DayResult, type TideBook } from "../run/save"; @@ -86,10 +87,10 @@ function Icon({kind}:{kind:"menu"|"close"|"bag"|"sound"|"silent"|"north"|"south" return ; } -/** `audio`, `initialSound` and `initialMix` carry the title screen's sound choice; `initialSurface` carries its “Continue to today’s ask”. */ -export interface ExpeditionGameProps {session?:HarborSession;accountPanel?:ReactNode;audio?:HarborAudio;initialSound?:boolean;initialMix?:readonly [number,number];initialSurface?:"tide"} -export default function ExpeditionGame({session,accountPanel,audio:titleAudio,initialSound=false,initialMix=[0.8,1],initialSurface}:ExpeditionGameProps={}){ - const [initial]=useState(readLocal),[save,setSave]=useState(initial.save),[surface,setSurface]=useState(initialSurface??null); +/** `audio`, `initialSound` and `initialMix` carry the title screen's sound choice. */ +export interface ExpeditionGameProps {session?:HarborSession;accountPanel?:ReactNode;audio?:HarborAudio;initialSound?:boolean;initialMix?:readonly [number,number]} +export default function ExpeditionGame({session,accountPanel,audio:titleAudio,initialSound=false,initialMix=[0.8,1]}:ExpeditionGameProps={}){ + const [initial]=useState(readLocal),[save,setSave]=useState(initial.save),[surface,setSurface]=useState(null); const [problem,setProblem]=useState(initial.problem),[corrupt,setCorrupt]=useState(!!initial.problem),[notice,setNotice]=useState(""),[transition,setTransition]=useState(null),[presentationId,setPresentationId]=useState(0),[busy,setBusy]=useState(false),[finishing,setFinishing]=useState(false),[focused,setFocused]=useState(null); const [lease,setLease]=useState<"waiting"|"held"|"blocked"|"unavailable">("waiting"),[leaseAttempt,setLeaseAttempt]=useState(0); const [tool,setTool]=useState("rope"),[area,setArea]=useState(()=>initial.save.home.lit&&!initial.save.home.banked.includes("vane")?"wind":"beacon"),[reduced,setReduced]=useState(()=>matchMedia("(prefers-reduced-motion: reduce)").matches),[hidden,setHidden]=useState(document.hidden),[unfocused,setUnfocused]=useState(false),[fault,setFault]=useState(""),[sceneKey,setSceneKey]=useState(0),[sound,setSound]=useState(initialSound),[motif,setMotif]=useState<"crest"|"moth">("crest"),[recipient,setRecipient]=useState(""),[lastBeat,setLastBeat]=useState(""); @@ -223,7 +224,7 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in if(keyRef.current===desiredKey)return; repairRequest.current=null;setResting(false); const branch=readLocal(desiredKey);keyRef.current=desiredKey;saveRef.current=branch.save;setSave(branch.save);setProblem(branch.problem);setCorrupt(!!branch.problem);corruptRef.current=!!branch.problem; - buffer.current=null;if(queuedFrame.current!==null)cancelAnimationFrame(queuedFrame.current);queuedFrame.current=null;busyRef.current=false;setBusy(false);finishEpoch.current++;finishBusy.current=false;setFinishing(false);setTransition(null);presentation.current++;setPresentationId(presentation.current);setSceneKey(k=>k+1);setNotice("");setArrival(null);setSurface(current=>current==="home"?null:current);setFocused(null); + buffer.current=null;if(queuedFrame.current!==null)cancelAnimationFrame(queuedFrame.current);queuedFrame.current=null;busyRef.current=false;setBusy(false);finishEpoch.current++;finishBusy.current=false;setFinishing(false);setTransition(null);presentation.current++;setPresentationId(presentation.current);setSceneKey(k=>k+1);setNotice("");setArrival(null);setSurface(current=>current==="home"||current==="story"?null:current);setFocused(null); sessionRef.current?.setActiveRun(branch.save.active?.context??null); },[desiredKey]); useEffect(()=>{ @@ -349,7 +350,7 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in 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!==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 open(place:HomePlace|"menu"|"guide"|"lantern"|"inspect"|"crossings"|"chart"|"story"|"tide"|"court-tide"|"log"|"home"){if(!panelOpen.current)trigger.current=opener();if(place==="mochi"){setResting(true);setGreeting(n=>n+1);return;}if(place==="tide"&&!savedMode&&tideResume){setTideAway(false);setSurface(null);return;}if(place==="tide")setCurrentTideDay(tideDay());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"){ @@ -394,8 +395,8 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in if(won&&!persist({...saveRef.current,home:{...saveRef.current.home,banked:[...new Set([...saveRef.current.home.banked,prize])]}})){setProblem("");return false;} const first=!prize&&!tideBook.days.some(day=>day.seed===state.seed); const closed=closeTide(tideBook,state); - if(!storeTideBook(again?{...closed,active:startTide(prize?storyStart(prize):{seed:state.seed})}:closed))return false; - if(again){setTideRound(n=>n+1);return true;} + if(!storeTideBook(closed))return false; + if(again){setReadySceneKey(-1);setSceneKey(k=>k+1);open(prize?"story":"tide");return true;} setReadySceneKey(-1);setSceneKey(k=>k+1); if(prize)setNotice(won?`Mochi brought the ${names[prize]} home.${prize==="moth"?` Bram: “${CHAPTERS.moth.after.join(" ")}”`:""}`:`The ${names[prize]} is back in its shell. The tide will open it again.`); else{ @@ -426,10 +427,13 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in const canPreviewCrest=!savedMode&&home.banked.includes("lens")||previewReturns.some(record=>record.outcome==="returned"&&record.cargo.includes("lens")); const canPreviewMoth=!savedMode&&home.banked.includes("moth")||previewReturns.some(record=>record.outcome==="returned"&&record.cargo.includes("moth")); const needsLantern=savedMode?!!session?.state.workshop.creditAvailable:home.lit&&!home.lantern&&canPreviewCrest; - const nextPlace:HomePlace|"crossings"|"chart"|null=tideResume||storyNext?null:recordReturns.length?"satchel":needLens||needVane?"beacon":chapterComplete?"chart":home.signaled?"crossings":needsLantern?"workbench":null; - const homeTitle=tideResume?"The tide is waiting.":storyNext?`${CHAPTERS[storyNext].title}.`:recordReturns.length?"A full satchel. A safe harbor.":needLens?"The lens is home.":needVane?"The vane is home.":chapterComplete?"A harbor connected.":lastService==="bell"?"Supplies at Bell Steps.":lastService==="reed"?"The reed skiff is home.":home.signaled?"The harbor finds its bearings.":needsLantern?"A little light of your own.":home.lit?"A light worth coming home to.":"A little help for the harbor."; - const homeIntent=tideResume?"Mochi’s tide is saved where she stopped.":storyNext?`Bram: “${CHAPTERS[storyNext].before}”`:recordReturns.length?"Bring the original returned satchel to Bram. Review what can be saved before unpacking.":needLens?"Mochi kept it safe. Carry the lens up to the beacon.":needVane?"Bram steadies the bare post. Mochi has brought back the missing arrow.":chapterComplete?(harbor.heardBell?"The bell pull is rigged. Try a different crossing with Mochi, or sit together by the quay.":"Bram has cleared the old arch at Bell Steps. Mochi keeps turning toward it. What does she hear when the water falls?"):lastService==="bell"?"Across the water, Bram’s crates stand on the receiving steps.":lastService==="reed"?"The skiff rocks at its mooring on the near bank.":home.signaled?"Bram has a load for Bell Steps. Mochi is watching a skiff across at Reed.":needsLantern?"Your returned adventure can become one light for home.":home.lit?`Wind Gate has a different tide to understand.${home.banked.includes("moth")?"":" You can also return for the wind-moth."}`:"The beacon’s lens is across the tide. Mochi is ready to help."; - const primaryLabel=tideResume?"Return to the tide":storyNext?"Set out with Mochi":recordReturns.length?"Unpack the satchel":needLens?"Bring the lens to the beacon":needVane?"Fit the Signal Vane":chapterComplete?"Look over the harbor":home.signaled?"Choose a crossing":needsLantern?"Make a little light":area==="wind"?"Sail to Wind Gate":"Set out with Mochi"; + const pendingTideReturn=tideResume&&tideBook.active?.outcome!=="active"; + const storyWork=!savedMode&&(needLens||needVane||!!storyNext); + const savedReturnFirst=savedMode&&recordReturns.length>0; + const nextPlace:HomePlace|"crossings"|"chart"|null=tideResume?null:savedReturnFirst?"satchel":needLens||needVane?"beacon":storyNext?null:recordReturns.length?"satchel":chapterComplete?"chart":home.signaled?"crossings":needsLantern?"workbench":null; + const homeTitle=tideResume?pendingTideReturn?"The return is waiting.":"The outing is waiting.":savedReturnFirst?"A full satchel. A safe harbor.":needLens?"The lens is home.":needVane?"The vane is home.":storyNext?`${CHAPTERS[storyNext].title}.`:recordReturns.length?"A full satchel. A safe harbor.":chapterComplete?"A harbor connected.":lastService==="bell"?"Supplies at Bell Steps.":lastService==="reed"?"The reed skiff is home.":home.signaled?"The harbor finds its bearings.":needsLantern?"A little light of your own.":home.lit?"A light worth coming home to.":"A little help for the harbor."; + const homeIntent=tideResume?pendingTideReturn?"Mochi’s outing has ended. Her return still needs to be saved.":"Mochi’s outing is saved where she stopped.":savedReturnFirst?"Bring the original returned satchel to Bram. Review what can be saved before unpacking.":needLens?"Mochi kept it safe. Carry the lens up to the beacon.":needVane?"Bram steadies the bare post. Mochi has brought back the missing arrow.":storyNext?CHAPTERS[storyNext].before:recordReturns.length?"Bring the original returned satchel to Bram. Review what can be saved before unpacking.":chapterComplete?(harbor.heardBell?"The bell pull is rigged. Try a different crossing with Mochi, or sit together by the quay.":"Bram has cleared the old arch at Bell Steps. Mochi keeps turning toward it. What does she hear when the water falls?"):lastService==="bell"?"Across the water, Bram’s crates stand on the receiving steps.":lastService==="reed"?"The skiff rocks at its mooring on the near bank.":home.signaled?"Bram has a load for Bell Steps. Mochi is watching a skiff across at Reed.":needsLantern?"Your returned adventure can become one light for home.":home.lit?`Wind Gate has a different tide to understand.${home.banked.includes("moth")?"":" You can also return for the wind-moth."}`:"The beacon’s lens is across the tide. Mochi is ready to help."; + const primaryLabel=tideResume?pendingTideReturn?"Return to the harbor":"Resume outing":savedReturnFirst?"Unpack the satchel":needLens?"Fit the Beacon Lens":needVane?"Fit the Signal Vane":storyNext?`Prepare Chapter ${CHAPTERS[storyNext].number}`:recordReturns.length?"Unpack the satchel":chapterComplete?"Look over the harbor":home.signaled?"Choose a crossing":needsLantern?"Make a little light":area==="wind"?"Sail to Wind Gate":"Set out with Mochi"; const shelved=savedMode?shelvedDay?.scope===tideScope&&shelvedDay.day===today:readPreview(undefined,today)?.docked===today; const todayHaul=todayTide?shelfHaul(todayTide):null; const arrivalHaul=!savedMode&&arrival&&"result" in arrival?shelfHaul(arrival.result):null; @@ -438,9 +442,13 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in const outing=replayRun(record.tool,record.commands); return outing?.state.outcome==="returned"&&outing.state.cargo.length>0; }):!!todayHaul&&todayHaul.reed+todayHaul.glass>0; - const tideHome=resting||tideResume?null:harborTide(savedMode?{lit:home.lit,card:cardForDay(today),next:cardForDay(today+1),entry:todayView(today,tideEntries).entry,returnedToday,shelved}:{lit:home.lit,card:cardForDay(today),next:cardForDay(today+1),guess:todayGuess,result:todayTide,returnedToday,shelved}),tidePanel=tideHome?.kind==="panel"?tideHome:null; - const tideExtra=savedMode||!home.lit||resting?null:needVane?{label:"Fit the vane",hint:"Fit the Signal Vane",go:()=>open("beacon")}:tideResume?{label:"Resume tide",hint:"Return to the tide Mochi left",go:()=>setTideAway(false)}:storyNext?{label:`Chapter ${CHAPTERS[storyNext].number}`,hint:`Chapter ${CHAPTERS[storyNext].number}: ${CHAPTERS[storyNext].title}`,go:()=>departTide(storyStart(storyNext))}:null; - function tideAction(action:"tide"|"log"|"sail"|"bram"){if(action==="sail"){if(savedMode)sailTide(today);else departTide({seed:today});}else if(action==="log")openLog(today);else open(action);} + const tideHome=resting||tideResume||storyWork?null:harborTide(savedMode?{lit:home.lit,card:cardForDay(today),next:cardForDay(today+1),entry:todayView(today,tideEntries).entry,returnedToday,shelved}:{lit:home.lit,card:cardForDay(today),next:cardForDay(today+1),guess:todayGuess,result:todayTide,returnedToday,shelved}),tidePanel=tideHome?.kind==="panel"?tideHome:null; + function tideAction(action:"tide"|"log"|"sail"|"bram"){if(action==="sail"){if(savedMode)sailTide(today);else open("tide");}else if(action==="log")openLog(today);else open(action);} + function sailDeviceTide(day:number){ + const current=import.meta.env.DEV?devTideDay(location.search)??tideDay():tideDay(); + if(day!==current){setCurrentTideDay(current);return;} + departTide({seed:day}); + } const feedback=
{notice}
; const beatParts=lastBeat.split(":"),currentBeat=busy&&transition&&Number(beatParts[0])===presentationId?transition.events[Number(beatParts[1])]:null; const shownForecast=busy?currentBeat?`Resolving: ${eventDescription(currentBeat,run?.area)}`:"Mochi is acting. The tide will follow.":run?forecast(run,focused):""; @@ -481,9 +489,10 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in
-
{tidePanel&&}

{resting?"A moment together.":tidePanel?tidePanel.title:homeTitle}

{resting?(greeting?"Mochi rests a paw against your hand, then settles beside you.":harbor.moth?"Mochi tucks a paw under and watches the moth at its perch.":harbor.watchedReeds?"Mochi tucks a paw under, just as at the sheltered reeds.":"Mochi settles beside you. The water moves below the quay."):tidePanel?tidePanel.body:homeIntent}

{COURTS[area].title} · {title(tool)}{tideExtra&&}
+
{tidePanel&&}

{resting?"A moment together.":tidePanel?tidePanel.title:homeTitle}

{resting?(greeting?"Mochi rests a paw against your hand, then settles beside you.":harbor.moth?"Mochi tucks a paw under and watches the moth at its perch.":harbor.watchedReeds?"Mochi tucks a paw under, just as at the sheltered reeds.":"Mochi settles beside you. The water moves below the quay."):tidePanel?tidePanel.body:homeIntent}

{savedMode&&!tidePanel&&
{COURTS[area].title} · {title(tool)}
}
- {(!tidePanel||tidePanel.primary)&&} + {(!tidePanel||tidePanel.primary)&&} + {!savedMode&&home.lit&&storyWork&&!tideResume&&!resting&&} {tideHome?.links.filter(link=>link.action!=="log").slice(0,1).map(link=>)}
@@ -495,8 +504,8 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in {(!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.

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"?
{(surface!=="story"||savedMode||!storyNext||!!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"&&!savedMode&&!run?<>

How Tide Run works

: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

@@ -506,7 +515,18 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in

{passageError||"These crossings and their harbor changes are saved on this device."}

- :surface==="sail"?<>

What shall we bring?

{home.lit&&}
Outing{(["beacon","wind"] as const).map(choice=>)}
{area==="wind"&&

The wheel on the far bank steers the tide. Charge the left and center outlets to free the harbor’s signal vane.

}
One tool{(["rope","lantern"] as const).map(choice=>)}
:surface==="beacon"?<>{(needVane||home.signaled)&&}

{needVane?"One missing piece.":home.signaled?"Wind on the quay.":home.lit?"The beacon knows the way.":"A light for everyone."}

{needVane?"Bram holds the post while Mochi raises the brass arrow to its spindle.":home.signaled?"The signal arrow swings free above the quay. The beacon lights the way home.":home.lit?"The lens is safe in its lantern. Its light belongs to the whole harbor.":home.banked.includes("lens")?"The recovered lens fits the empty lantern. Mochi is ready to lift it into place.":"The missing lens waits in Beacon Court’s left shell. The Tidekeeper can open it."}

{!home.lit&&home.banked.includes("lens")&&}{home.lit&&!home.signaled&&home.banked.includes("vane")&&}:surface==="satchel"?<>

What came home.

{home.banked.length?home.banked.map(i=>i in names?names[i as keyof typeof names]:title(i)).join(" · "):"An empty satchel. There’s room for a small adventure."}

{recordReturns.map(record=>)}{earlierReturns.map(record=>
Earlier {COURTS[record.area].title} memory

This return began at another saved checkpoint. Its original memory is preserved; it cannot be merged into the current harbor.

{record.id}

)}{sealedNoteEnabled()&&savedMode&&session?.noteToken&&session.noteToken!()}/>}{save.last&&

{save.last.outcome==="returned"?`Mochi came home after ${save.last.turn} decisions with ${save.last.resolve}/3 Resolve.`:"Bram brought Mochi home. Only the unbanked cargo was lost."}

}

{authority}. {savedMode?"Only accepted returns change the saved harbor.":"Device saves are not backed up or transferable. Signing in does not replace this preview."}

:surface==="bram"?<>

“You’re back.”

{lastService==="bell"?"Bram shades his eyes. Across the channel his crates are stacked high and dry.":lastService==="reed"?"Bram loops the skiff’s painter around the mooring and checks Mochi’s knot.":home.signaled?"Bram watches the arrow swing. “An easterly. I can tell before I untie a single rope.”":home.banked.includes("moth")?"The little wings sound rather like a kettle beginning to sing. Bram makes room beside the hearth.":home.lit?"Bram puts the kettle on. A harbor looks different when everyone can find it.":"Bram looks across the bay. “A lighthouse shouldn’t have to guess where it’s pointing.”"}

{harbor.heardBell&&

“There’s your bell,” Bram says. “I’ve run a pull to the far-center landing at both crossings. One good tug calls the Tidekeeper’s surge left. Choose when to use it.”

}{passage.watchedReeds&&passageScope===passageKey&&

Mochi settles beside you, one paw tucked under, just as at the reeds.

}{home.lit&&}{session?.state.workshop.commissionAvailable&&}{recordReturns.length>0&&}{(waitingCraft||waitingPolish)&&
Original job details

Bram keeps the original job. An uncertain result never authorizes another lantern, payment or refund.

{session?.state.pending?:<>{waitingPolish&&}}
}{!savedMode&&

The personal Shell commission belongs to an accepted saved return. This preview does not issue currency.

}{Bram is setting out his shelf…

}>open("tide")} tideScope={savedMode?session!.state.snapshot!.binding.nearAccountId:"preview"} {...(!savedMode?{run:todayTide}:{})}/>
}:surface==="home"&&arrival?(!savedMode&&"result" in arrival?0&&!shelved} reduced={reduced} notice={arrivalNotice} sailBlockedReason={sailBlockedReason} onBram={()=>open("bram")} onSail={()=>departTide({seed:today})} onOpenLog={()=>openLog(arrival.day)}/>:"run" in arrival?0&&!shelved&&shelvesBeaconCourt(today)} reduced={reduced} notice={arrivalNotice} sailBlockedReason={sailBlockedReason} onBram={()=>open("bram")} onSail={()=>sailTide(arrival.day)} onOpenLog={()=>openLog(arrival.day)}/>:null):surface==="tide"&&!savedMode?departTide({seed:today})} onOpenLog={openLog}/>:surface==="tide"||surface==="court-tide"?:surface==="log"?:surface==="workbench"?<>

A little light of your own.

{savedMode?<>{session?.state.workshop.creditAvailable?<>

Choose an earned motif for one First Light lantern.

{session.state.workshop.motifs.map(m=>)}:

{session?.state.workshop.items.length?"Your owned lantern keeps the maker’s actual accepted story.":"Bring an accepted Beacon Lens return home to earn the first craft."}

}{!!session?.state.workshop.items.length&&
Give a lantern

Gifting moves the owned item. The maker’s achievement stays with its maker. Storage, if needed, is a separate reviewed action.

}{session?.state.workshop.items.map(item=>

{title(item.mint.motif)} lantern · {item.finish==="harbor_polish"?"Harbor polish":"Original finish"}

Origin and maker

Illustrated {item.mint.motif==="moth"?"wind-moth rescue":"Beacon Lens return"}, from the maker’s actual accepted event. This is not a recorded screenshot.

Maker: {item.mint.maker}
Accepted claim: {item.mint.origin_claim_id}
Content: {item.mint.content_version}
Rules: {item.mint.rules_version}

{!item.finish_used&&}
)}:home.lantern?<>

One {title(home.lantern.motif)} lantern. Local preview only; not backed up or transferable.

Light’s origin{previewOrigin?<>

Mochi returned with the {home.lantern.motif==="moth"?"wind-moth":"Beacon Lens"}. {previewOrigin.commands.length} choices with the {title(previewOrigin.tool)}.

Static illustration of this device’s validated return, not a recorded screenshot or an accepted NEAR claim.

Content: {previewOrigin.contentVersion} · memory {previewOrigin.id}

:

The original return is unavailable. This device preview is not proof of an earned event.

}
{(["porch","dock"] as const).map(socket=>)}:canPreviewCrest?<>
{title(motif)} motif

The lens return earned a Crest. A rescued wind-moth earns its own motif.

Motif{(["crest","moth"] as const).map(m=>)}
:

Bring the Beacon Lens home first. A lantern should remember something you actually did.

}:null} + :surface==="story"&&!savedMode&&storyNext?<> +

Chapter {CHAPTERS[storyNext].number}: {CHAPTERS[storyNext].title}

+
+

Tide Run · {tideShape({story:storyNext}).waves} waves

+

{CHAPTERS[storyNext].before}

+

{CHAPTERS[storyNext].goal}

+

{storyNext==="lens"?"Eight waves. Only moving or waiting advances the water.":"Twelve waves. Only moving or waiting advances the water."}

+

Story outings do not use your daily result.

+
How Tide Run works
+ +
+ :surface==="sail"?<>

What shall we bring?

{home.lit&&}
Outing{(["beacon","wind"] as const).map(choice=>)}
{area==="wind"&&

The wheel on the far bank steers the tide. Charge the left and center outlets to free the harbor’s signal vane.

}
One tool{(["rope","lantern"] as const).map(choice=>)}
:surface==="beacon"?<>{(needVane||home.signaled)&&}

{needVane?"One missing piece.":home.signaled?"Wind on the quay.":home.lit?"The beacon knows the way.":"A light for everyone."}

{needVane?"Bram holds the post while Mochi raises the brass arrow to its spindle.":home.signaled?"The signal arrow swings free above the quay. The beacon lights the way home.":home.lit?"The lens is safe in its lantern. Its light belongs to the whole harbor.":home.banked.includes("lens")?"The recovered lens fits the empty lantern. Mochi is ready to lift it into place.":"The missing lens waits in Beacon Court’s left shell. The Tidekeeper can open it."}

{!home.lit&&home.banked.includes("lens")&&}{home.lit&&!home.signaled&&home.banked.includes("vane")&&}:surface==="satchel"?<>

What came home.

{home.banked.length?home.banked.map(i=>i in names?names[i as keyof typeof names]:title(i)).join(" · "):"An empty satchel. There’s room for a small adventure."}

{recordReturns.map(record=>)}{earlierReturns.map(record=>
Earlier {COURTS[record.area].title} memory

This return began at another saved checkpoint. Its original memory is preserved; it cannot be merged into the current harbor.

{record.id}

)}{sealedNoteEnabled()&&savedMode&&session?.noteToken&&session.noteToken!()}/>}{save.last&&

{save.last.outcome==="returned"?`Mochi came home after ${save.last.turn} decisions with ${save.last.resolve}/3 Resolve.`:"Bram brought Mochi home. Only the unbanked cargo was lost."}

}

{authority}. {savedMode?"Only accepted returns change the saved harbor.":"Device saves are not backed up or transferable. Signing in does not replace this preview."}

:surface==="bram"?<>

“You’re back.”

{lastService==="bell"?"Bram shades his eyes. Across the channel his crates are stacked high and dry.":lastService==="reed"?"Bram loops the skiff’s painter around the mooring and checks Mochi’s knot.":home.signaled?"Bram watches the arrow swing. “An easterly. I can tell before I untie a single rope.”":home.banked.includes("moth")?"The little wings sound rather like a kettle beginning to sing. Bram makes room beside the hearth.":home.lit?"Bram puts the kettle on. A harbor looks different when everyone can find it.":"Bram looks across the bay. “A lighthouse shouldn’t have to guess where it’s pointing.”"}

{harbor.heardBell&&

“There’s your bell,” Bram says. “I’ve run a pull to the far-center landing at both crossings. One good tug calls the Tidekeeper’s surge left. Choose when to use it.”

}{passage.watchedReeds&&passageScope===passageKey&&

Mochi settles beside you, one paw tucked under, just as at the reeds.

}{home.lit&&}{session?.state.workshop.commissionAvailable&&}{recordReturns.length>0&&}{(waitingCraft||waitingPolish)&&
Original job details

Bram keeps the original job. An uncertain result never authorizes another lantern, payment or refund.

{session?.state.pending?:<>{waitingPolish&&}}
}{!savedMode&&

The personal Shell commission belongs to an accepted saved return. This preview does not issue currency.

}{Bram is setting out his shelf…

}>open("tide")} tideScope={savedMode?session!.state.snapshot!.binding.nearAccountId:"preview"} {...(!savedMode?{run:todayTide}:{})}/>
}:surface==="home"&&arrival?(!savedMode&&"result" in arrival?0&&!shelved} reduced={reduced} notice={arrivalNotice} sailBlockedReason={sailBlockedReason} onBram={()=>open("bram")} onSail={()=>open("tide")} onOpenLog={()=>openLog(arrival.day)}/>:"run" in arrival?0&&!shelved&&shelvesBeaconCourt(today)} reduced={reduced} notice={arrivalNotice} sailBlockedReason={sailBlockedReason} onBram={()=>open("bram")} onSail={()=>sailTide(arrival.day)} onOpenLog={()=>openLog(arrival.day)}/>:null):surface==="tide"&&!savedMode?:surface==="tide"||surface==="court-tide"?:surface==="log"?:surface==="workbench"?<>

A little light of your own.

{savedMode?<>{session?.state.workshop.creditAvailable?<>

Choose an earned motif for one First Light lantern.

{session.state.workshop.motifs.map(m=>)}:

{session?.state.workshop.items.length?"Your owned lantern keeps the maker’s actual accepted story.":"Bring an accepted Beacon Lens return home to earn the first craft."}

}{!!session?.state.workshop.items.length&&
Give a lantern

Gifting moves the owned item. The maker’s achievement stays with its maker. Storage, if needed, is a separate reviewed action.

}{session?.state.workshop.items.map(item=>

{title(item.mint.motif)} lantern · {item.finish==="harbor_polish"?"Harbor polish":"Original finish"}

Origin and maker

Illustrated {item.mint.motif==="moth"?"wind-moth rescue":"Beacon Lens return"}, from the maker’s actual accepted event. This is not a recorded screenshot.

Maker: {item.mint.maker}
Accepted claim: {item.mint.origin_claim_id}
Content: {item.mint.content_version}
Rules: {item.mint.rules_version}

{!item.finish_used&&}
)}:home.lantern?<>

One {title(home.lantern.motif)} lantern. Local preview only; not backed up or transferable.

Light’s origin{previewOrigin?<>

Mochi returned with the {home.lantern.motif==="moth"?"wind-moth":"Beacon Lens"}. {previewOrigin.commands.length} choices with the {title(previewOrigin.tool)}.

Static illustration of this device’s validated return, not a recorded screenshot or an accepted NEAR claim.

Content: {previewOrigin.contentVersion} · memory {previewOrigin.id}

:

The original return is unavailable. This device preview is not proof of an earned event.

}
{(["porch","dock"] as const).map(socket=>)}:canPreviewCrest?<>
{title(motif)} motif

The lens return earned a Crest. A rescued wind-moth earns its own motif.

Motif{(["crest","moth"] as const).map(m=>)}
:

Bring the Beacon Lens home first. A lantern should remember something you actually did.

}:null} {session?.state.message&&

{session.state.message}

}
} } diff --git a/web/src/expedition/game.css b/web/src/expedition/game.css index 3481e8f..d0fbb64 100644 --- a/web/src/expedition/game.css +++ b/web/src/expedition/game.css @@ -168,6 +168,13 @@ html:has(.exp-game),body:has(.exp-game){margin:0;width:100%;height:100%;overflow .exp-panel>h2,.exp-panel>.harbor-chart>h2,.exp-panel>.exp-inspect>h2{min-height:44px;margin-right:52px} .exp-panel>.tide>h3{margin-right:52px} .exp-panel .tide-log-header{margin-right:52px} +.exp-game .exp-panel:has(>.exp-panel-header){display:flex;flex-direction:column;overflow:hidden;padding:0} +.exp-panel-header{position:relative;flex:none;z-index:6;display:flex;align-items:flex-start;gap:12px;margin:0;padding:var(--exp-panel-pad);background:var(--exp-card)} +.exp-game .exp-panel .exp-panel-header>h2{flex:1;min-width:0;margin:0} +.exp-panel-header>.exp-close{flex:none;width:44px;min-width:44px;min-height:44px;margin:0;padding:10px;background:var(--exp-card)} +.exp-panel-body{min-height:0;overflow-y:auto;overscroll-behavior:contain;padding:0 var(--exp-panel-pad) var(--exp-panel-pad);scrollbar-color:#8b734c var(--exp-card);scrollbar-width:thin;scroll-padding:8px} +.exp-panel-body:focus-visible{outline-offset:-3px} +.exp-panel-body>.exp-primary{width:100%} .exp-panel :focus-visible{outline-color:#2b5f4d;box-shadow:none} .exp-panel-shade:has(.tide-home){justify-content:center} .exp-panel:has(.tide-home){width:min(540px,100%)} diff --git a/web/src/expedition/keyboard-scroll.test.ts b/web/src/expedition/keyboard-scroll.test.ts new file mode 100644 index 0000000..554dfb1 --- /dev/null +++ b/web/src/expedition/keyboard-scroll.test.ts @@ -0,0 +1,124 @@ +import { expect, test } from "bun:test"; +import type { KeyboardEvent } from "react"; +import { scrollReadingRegion } from "./keyboard-scroll"; + +function readingRegion({ top = 100, height = 200, content = 1000, lineHeight = "24px", fontSize = "20px", scrollPaddingTop = "auto", scrollPaddingBottom = "auto" } = {}) { + const calls: ScrollToOptions[] = []; + const document = { + activeElement: null as unknown, + defaultView: { getComputedStyle: () => ({ lineHeight, fontSize, scrollPaddingTop, scrollPaddingBottom }) }, + }; + const region = { + scrollTop: top, clientHeight: height, scrollHeight: content, ownerDocument: document, + scrollTo(options: ScrollToOptions) { calls.push(options); region.scrollTop = options.top!; }, + } as unknown as HTMLElement; + document.activeElement = region; + const press = (key: string, options: Partial> = {}) => { + let prevented = 0; + const event = { + key, target: region, currentTarget: region, defaultPrevented: false, + altKey: false, ctrlKey: false, metaKey: false, shiftKey: false, + nativeEvent: { isComposing: false }, preventDefault: () => { prevented++; event.defaultPrevented = true; }, + ...options, + } as KeyboardEvent; + scrollReadingRegion(event); + return prevented; + }; + return { region, document, calls, press }; +} + +test("a focused reading region scrolls one text line on ArrowDown and cancels native scrolling", () => { + const { region, calls, press } = readingRegion(); + expect(press("ArrowDown")).toBe(1); + expect(region.scrollTop).toBe(124); + expect(calls).toEqual([{ top: 124, behavior: "instant" }]); +}); + +test("line, page, Space and endpoint keys scroll the reading region in both directions", () => { + for (const [key, shiftKey, expected] of [ + ["ArrowUp", false, 376], ["ArrowDown", false, 424], + ["PageUp", false, 224], ["PageDown", false, 576], + [" ", false, 576], [" ", true, 224], + ["Home", false, 0], ["End", false, 800], + ] as const) { + const { region, calls, press } = readingRegion({ top: 400 }); + expect(press(key, { shiftKey })).toBe(1); + expect(region.scrollTop).toBe(expected); + expect(calls).toEqual([{ top: expected, behavior: "instant" }]); + } +}); + +test("repeated keys advance from the current position and clamp at both scroll boundaries", () => { + const { region, calls, press } = readingRegion({ top: 780 }); + expect(press("ArrowDown")).toBe(1); + expect(press("ArrowDown", { repeat: true })).toBe(1); + expect(region.scrollTop).toBe(800); + expect(press("ArrowUp")).toBe(1); + expect(press("ArrowUp", { repeat: true })).toBe(1); + expect(region.scrollTop).toBe(752); + expect(press("Home")).toBe(1); + expect(press("PageUp")).toBe(1); + expect(calls.map(call => call.top)).toEqual([800, 800, 776, 752, 0, 0]); +}); + +test("handled keys stay contained even when the region has no overflowing content", () => { + for (const content of [100, 200]) { + const { region, press } = readingRegion({ top: 0, content }); + for (const key of ["ArrowUp", "ArrowDown", "PageUp", "PageDown", " ", "Home", "End"]) { + expect(press(key)).toBe(1); + expect(region.scrollTop).toBe(0); + } + } +}); + +test("line and page steps follow enlarged text, including a normal line-height", () => { + for (const lineHeight of ["normal", "48px"]) { + const { region, calls, press } = readingRegion({ lineHeight, fontSize: "40px" }); + press("ArrowDown"); + press("PageDown"); + expect(region.scrollTop).toBe(300); + expect(calls.map(call => call.top)).toEqual([148, 300]); + } + const small = readingRegion({ height: 12 }); + small.press("PageDown"); + expect(small.region.scrollTop).toBe(124); +}); + +test("paging preserves a line of overlap below the panel's sticky heading", () => { + const { region, press } = readingRegion({ scrollPaddingTop: "78px", scrollPaddingBottom: "8px" }); + press("PageDown"); + expect(region.scrollTop).toBe(190); + press("PageUp"); + expect(region.scrollTop).toBe(100); +}); + +test("descendant controls and an unfocused region keep their own keyboard behavior", () => { + const { region, document, calls, press } = readingRegion(); + const control = {} as HTMLElement; + document.activeElement = control; + expect(press(" ", { target: control })).toBe(0); + expect(press("End")).toBe(0); + document.activeElement = region; + expect(press("ArrowDown", { target: control })).toBe(0); + expect(calls).toEqual([]); +}); + +test("a focused nested reading region never scrolls its ancestor too", () => { + const inner = readingRegion(); + const outer = readingRegion(); + outer.document.activeElement = inner.region; + expect(inner.press("ArrowDown")).toBe(1); + expect(outer.press("ArrowDown", { target: inner.region })).toBe(0); + expect(inner.region.scrollTop).toBe(124); + expect(outer.calls).toEqual([]); +}); + +test("modified, composing, already handled and unrelated keys are left alone", () => { + const { calls, press } = readingRegion(); + for (const options of [ + { altKey: true }, { ctrlKey: true }, { metaKey: true }, { defaultPrevented: true }, + { nativeEvent: { isComposing: true } as globalThis.KeyboardEvent }, + ]) expect(press("ArrowDown", options)).toBe(0); + for (const key of ["Tab", "Enter", "Escape", "ArrowLeft", "ArrowRight", "w"]) expect(press(key)).toBe(0); + expect(calls).toEqual([]); +}); diff --git a/web/src/expedition/keyboard-scroll.ts b/web/src/expedition/keyboard-scroll.ts new file mode 100644 index 0000000..75e888b --- /dev/null +++ b/web/src/expedition/keyboard-scroll.ts @@ -0,0 +1,25 @@ +import type { KeyboardEvent } from "react"; + +export function scrollReadingRegion(event: KeyboardEvent): void { + const region = event.currentTarget; + if (event.target !== region || region.ownerDocument.activeElement !== region || event.defaultPrevented || + event.nativeEvent.isComposing || event.altKey || event.ctrlKey || event.metaKey) return; + + const style = region.ownerDocument.defaultView!.getComputedStyle(region); + const line = Number.parseFloat(style.lineHeight) || Number.parseFloat(style.fontSize) * 1.2; + const page = Math.max(line, region.clientHeight - line - (Number.parseFloat(style.scrollPaddingTop) || 0) - (Number.parseFloat(style.scrollPaddingBottom) || 0)); + let top = region.scrollTop; + switch (event.key) { + case "ArrowUp": top -= line; break; + case "ArrowDown": top += line; break; + case "PageUp": top -= page; break; + case "PageDown": top += page; break; + case " ": top += event.shiftKey ? -page : page; break; + case "Home": top = 0; break; + case "End": top = region.scrollHeight; break; + default: return; + } + // Instant scrolling also respects reduced motion and overrides CSS smooth scrolling. + region.scrollTo({ top: Math.max(0, Math.min(top, region.scrollHeight - region.clientHeight)), behavior: "instant" }); + event.preventDefault(); +} diff --git a/web/src/landing/Landing.test.tsx b/web/src/landing/Landing.test.tsx new file mode 100644 index 0000000..05ec479 --- /dev/null +++ b/web/src/landing/Landing.test.tsx @@ -0,0 +1,14 @@ +import { expect, test } from "bun:test"; +import { renderToStaticMarkup } from "react-dom/server"; +import { Landing } from "./Landing"; + +test("the landing explains Mochi’s first Tide Run without court tools or story spoilers", () => { + const html = renderToStaticMarkup(); + for (const copy of [ + "Guide Mochi as a volunteer harbor helper. Bring home the missing Beacon Lens and help the harbor find its light again.", + "Read the water. Bring the light home.", "One clear errand.", "Your first outing has eight calm waves.", + "Banking keeps the outing open; finishing returns you to the harbor.", "Make the return matter.", + "A harbor worth helping.", "Begin with Mochi", "
Beacon Court concept art.
", + ]) expect(html).toContain(copy); + for (const spoiler of ["Rope", "Lantern to redirect", "Signal Vane", "wind-moth", "Wren", "Begin with Beacon Court", "In the game, Mochi crosses connected platforms."]) expect(html).not.toContain(spoiler); +}); diff --git a/web/src/landing/Landing.tsx b/web/src/landing/Landing.tsx index d9304ff..53376da 100644 --- a/web/src/landing/Landing.tsx +++ b/web/src/landing/Landing.tsx @@ -18,7 +18,7 @@ export function Landing() {

A small friend.
A light to
bring home.

-

Meet Mochi. A curious little companion with a very big job. Read the tide, recover what the storm scattered, and bring a sleepy harbor back to life.

+

Guide Mochi as a volunteer harbor helper. Bring home the missing Beacon Lens and help the harbor find its light again.

Play Familiar

In your browser. At your pace. No sign-up.

See how the tide turns @@ -34,8 +34,8 @@ export function Landing() {
-

Sometimes the wave
is the way forward.

-

The Tidekeeper marks a source, then sends a wave. Cross the connected platforms and it might open the shell you needed. Stay a little longer and you might bring someone home.

+

Read the water. Bring the light home.

+

Each step or wait advances the water. A wave arrives after every third move. Read its lanes, cross the moving bridge, and carry your finds back to the center dock.

@@ -43,20 +43,20 @@ export function Landing() {
-
Beacon Court concept art. In the game, Mochi crosses connected platforms.
+
Beacon Court concept art.
-
Bring a little ingenuity.
-
Choose Rope to reel in an exposed find, or Lantern to redirect a marked source. Two uses. Your call.
+
One clear errand.
+
Bring the Beacon Lens home from the left shell. Your first outing has eight calm waves.
-
Make room for a detour.
-
A lens takes one pack slot. A wind-moth takes two. Decide what’s worth one more turn, then carry your finds back to the dock.
+
Keep what you bank.
+
Step onto the center dock to bank cargo. Banking keeps the outing open; finishing returns you to the harbor.
-
Come home with a story.
-
Install what you recover. Watch the lighthouse glow. Mochi remembers a moment from the trip you actually took.
+
Make the return matter.
+
Fit the lens into the beacon. Each repair uncovers another piece of the harbor’s story.
@@ -64,13 +64,12 @@ export function Landing() {
Wind Gate concept illustration, where stone channels route the tide through a turning wheel. -
Wind Gate concept art. This outing opens after you restore the lighthouse.
+
Wind Gate concept art. Optional outings have their own rules on the Harbor chart.
-

You know the tide.
Now turn it.

-

Beyond the beacon, the channel sends a familiar wave somewhere new. Align the wheel, trace the exit, and charge Left and Center to recover the harbor’s Signal Vane.

-

Rope or Lantern. A different route. Something else to bring home.

- Begin with Beacon Court +

A harbor worth helping.

+

Once the beacon shines, the Harbor chart opens other ways to help. Bell Steps, Reed Steps, and the optional courts each explain their own outing.

+ Begin with Mochi
diff --git a/web/src/main.tsx b/web/src/main.tsx index bfdcaab..f6ee139 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -31,7 +31,7 @@ async function entry() { let screen:React.ReactNode=null; if(play){ const [{default:Game},{HarborSessionBoundary,HarborAccountPanel}]=play.mods; - screen={session=>} audio={audio} initialSound={play.start.sound} initialMix={[play.start.music,play.start.effects]} initialSurface={play.start.surface}/>}; + screen={session=>} audio={audio} initialSound={play.start.sound} initialMix={[play.start.music,play.start.effects]}/>}; } return <> {screen} diff --git a/web/src/opening/Opening.test.tsx b/web/src/opening/Opening.test.tsx index 047b1b5..684ede7 100644 --- a/web/src/opening/Opening.test.tsx +++ b/web/src/opening/Opening.test.tsx @@ -3,7 +3,46 @@ import { renderToStaticMarkup } from "react-dom/server"; import { HarborAudio } from "../expedition/audio"; import Opening from "./Opening"; -test("painted boards survive frame updates and the bell keeps its pivot and touch target", () => { +test("fresh title has native Begin and daily paper enters without selecting an activity", async () => { + const starts: unknown[] = []; + const opening = new Opening({ audio: new HarborAudio(), hasSave: false, onStart: async start => { starts.push(start); }, onDone() {} }); + expect(renderToStaticMarkup(opening.render())).toContain('data-el="begin"'); + expect(renderToStaticMarkup(opening.render())).not.toContain("New Harbor"); + opening.state = { ...opening.state, scroll: "tide" }; + const html = renderToStaticMarkup(opening.render()); + expect(html).toContain("Daily outings begin once the beacon is lit. Enter the harbor to see this harbor’s outing and rules."); + expect(html).toContain("Enter the harbor"); + opening.tw = async () => {}; + opening.wait = async () => {}; + opening.s = {}; + await opening.travel("new"); + expect(starts).toEqual([{ sound: false, music: .8, effects: 1 }]); + const entries: unknown[][] = []; + opening.travel = async (...args) => { entries.push(args); }; + opening.setState = () => {}; + opening.onTide(); + expect(entries).toEqual([["new"]]); + const saved = new Opening({ audio: new HarborAudio(), hasSave: true, onStart: async () => {}, onDone() {} }); + expect(renderToStaticMarkup(saved.render())).toMatch(/data-el="begin"[^>]*>Continue<\/button>/); + saved.tw = async () => {}; + saved.setState = () => {}; + saved.travel = async (...args) => { entries.push(args); }; + saved.onTide(); + expect(entries).toEqual([["new"], ["continue"]]); +}); + +test("public title idle never starts the retained court demonstration", () => { + const opening = new Opening({ audio: new HarborAudio(), hasSave: false, onStart: async () => {}, onDone() {} }); + let demonstrations = 0; + opening.attract = async () => { demonstrations++; }; + opening.draw = () => {}; + const previous = globalThis.requestAnimationFrame; + globalThis.requestAnimationFrame = () => 0; + try { opening.mode = "title"; opening.t = 30_000; opening.tick(30_000); expect(demonstrations).toBe(0); } + finally { globalThis.requestAnimationFrame = previous; } +}); + +test("painted menu targets settle between frames and the bell keeps its pivot and touch target", () => { for (const [width, height] of [[320, 480], [390, 844], [844, 390], [1280, 800], [1536, 1024]]) { const opening = new Opening({ audio: new HarborAudio(), hasSave: false, onStart: async () => {}, onDone() {} }); const bell = { style: {} as Record, isConnected: true }; @@ -29,6 +68,13 @@ test("painted boards survive frame updates and the bell keeps its pivot and touc for (const board of Object.values(boards)) expect(board.style.background).toBe("painted board"); expect(boards.new.style.filter).toContain("brightness(1.06)"); expect(boards.tide.style.filter).toBe("drop-shadow(0 3px 3px #2a1d1166)"); + opening.landed = true; + const settled = { world: world.style.transform, boards: Object.values(boards).map(board => board.style.transform) }; + for (const time of [10_000, 13_000, 17_000]) { + opening.t = time; + opening.draw(); + expect({ world: world.style.transform, boards: Object.values(boards).map(board => board.style.transform) }).toEqual(settled); + } } }); diff --git a/web/src/opening/Opening.tsx b/web/src/opening/Opening.tsx index 0d6b896..466b614 100644 --- a/web/src/opening/Opening.tsx +++ b/web/src/opening/Opening.tsx @@ -25,8 +25,7 @@ export function sx(text: string): CSSProperties { } export type OpeningBeat = "live" | "boot" | "title" | "bell" | "attract" | "menu" | "travel"; -export interface OpeningStart { sound: boolean; music: number; effects: number; surface?: "tide" } -function litHarbor(): boolean { try { return Object.keys(localStorage).some(key => key.startsWith("familiar.expedition.") && (() => { try { return JSON.parse(localStorage.getItem(key) ?? "null")?.home?.lit === true; } catch { return false; } })()); } catch { return false; } } +export interface OpeningStart { sound: boolean; music: number; effects: number } interface Props { audio: HarborAudio; hasSave: boolean; @@ -35,11 +34,10 @@ interface Props { /** The tide has drawn back over the game: unmount the opening. */ onDone(): void; beat?: OpeningBeat; - attractDelay?: number; /** Fill the parent box instead of the viewport (storyboard frames). */ framed?: boolean; } -interface State { prompt: string; sound: boolean; scroll: "" | "tide" | "options" | "credits"; music: number; effects: number; cap1: string; cap2: string; lane: string } +interface State { sound: boolean; scroll: "" | "tide" | "options" | "credits"; music: number; effects: number; cap1: string; cap2: string; lane: string } type Ease = "lin" | "io" | "out" | "in" | "back"; interface Tween { o: Record; k: string; to: number; d: number; e: Ease; dl: number; el: number; from?: number; done?: boolean; res(): void } type Plank = "continue" | "new" | "tide" | "options" | "credits"; @@ -56,7 +54,7 @@ const E: Record number> = { }; const COLS = ["Left", "Center", "Right"]; const PLANK = "position:relative;height:56px;width:236px;box-sizing:border-box;padding:0 12px 0 30px;border:0;color:#fff0ce;filter:drop-shadow(0 3px 3px #2a1d1166);text-shadow:0 1px 2px #2a1d11cc;font:650 23px/1 'Fraunces Variable',serif;letter-spacing:-.02em;text-align:left;cursor:pointer;transform-origin:0 50%;opacity:0;pointer-events:none"; -const LABEL: Record = { continue: "Continue", new: "New Harbor", tide: "Today’s Tide", options: "Options", credits: "Credits" }; +const LABEL: Record = { continue: "Continue", new: "Begin", tide: "Today’s Tide", options: "Options", credits: "Credits" }; const col = (x: number) => 126.67 + x * 253.33, row = (y: number) => 800 - y * 140; const GEO = { @@ -68,9 +66,8 @@ const GEO = { }; export default class Opening extends Component { - state: State = { prompt: "Press any key", sound: false, scroll: "", music: 4, effects: 5, cap1: "", cap2: "", lane: "" }; + state: State = { sound: false, scroll: "", music: 4, effects: 5, cap1: "", cap2: "", lane: "" }; root: HTMLDivElement | null = null; - readonly hasLitHarbor = litHarbor(); t = 0; dt = 16; last = 0; raf = 0; seq = 0; dead = false; frozen = false; rm = false; soundOn = false; landed = false; handedOff = false; tweens: Tween[] = []; els: Record = {}; @@ -96,7 +93,6 @@ export default class Opening extends Component { componentDidMount() { this.dead = false; this.t = 0; this.moth = { x: 852, y: 444 }; this.rm = matchMedia("(prefers-reduced-motion: reduce)").matches; - if (matchMedia("(pointer: coarse)").matches) this.setState({ prompt: "Tap to begin" }); window.addEventListener("keydown", this.onKey); this.ro = new ResizeObserver(() => { if (this.frozen) this.draw(); }); if (this.root) this.ro.observe(this.root); @@ -137,7 +133,6 @@ export default class Opening extends Component { if (p >= 1) { w.done = true; w.res(); } } this.tweens = this.tweens.filter(w => !w.done); - if (this.mode === "title" && this.t - this.idleAt > (this.props.attractDelay ?? 20) * 1000) void this.attract(); this.draw(); this.raf = requestAnimationFrame(this.tick); }; tw(o: Record, k: string, to: number, d: number, e: Ease = "io", dl = 0): Promise { @@ -174,7 +169,8 @@ export default class Opening extends Component { this.setState(st => bus === "music" ? { ...st, music: level } : { ...st, effects: level }, () => { this.props.audio.setMix(this.state.music / 5, this.state.effects / 5); this.sfx("step"); }); }; onBack = () => this.closeScroll(); - onTide = () => { if (this.frozen) return; void this.tw(this.s, "scrollP", 0, 200, "in").then(() => this.setState({ scroll: "" })); void this.travel("continue", "tide"); }; + onTide = () => { if (this.frozen) return; void this.tw(this.s, "scrollP", 0, 200, "in").then(() => this.setState({ scroll: "" })); void this.travel(this.props.hasSave ? "continue" : "new"); }; + onBegin = (e: SyntheticEvent) => { e.stopPropagation(); if (!this.frozen && this.mode === "title") this.openMenu(); }; onPlankEnter = (e: SyntheticEvent) => { if (!this.frozen && this.mode === "menu" && !this.state.scroll) this.select(e.currentTarget.dataset.plank as Plank); }; onPlankClick = (e: SyntheticEvent) => { e.stopPropagation(); if (this.frozen || this.mode !== "menu") return; const id = e.currentTarget.dataset.plank as Plank; this.select(id); this.choose(id); }; onKey = (e: KeyboardEvent) => { @@ -222,7 +218,7 @@ export default class Opening extends Component { this.items().forEach((i, j) => void this.tw(this.mp, i, 1, 460, "back", 120 + j * 50)); if (this.sel) this.root?.querySelector(`[data-plank="${this.sel}"]`)?.focus({ preventScroll: true }); } - async travel(id: Plank, surface?: "tide") { + async travel(id: Plank) { const k = ++this.seq, s = this.s, ids = this.items(); this.mode = "travel"; this.dip[id] = this.t; this.sfx("pick"); this.poses(["reach-ready", 420]); await this.wait(260); if (k !== this.seq) return; if (this.soundOn) this.props.audio.playMusic("departure"); this.mothTo = "board"; ids.forEach((i, j) => void this.tw(this.mp, i, 0, 300, "in", j * 40)); this.sel = null; @@ -232,7 +228,7 @@ export default class Opening extends Component { // The camera has reached the dock: the tide rises, holds until the game is mounted beneath it, then draws back. this.mode = "wipe"; s.tideA = 1; s.tide = 0; await this.tw(s, "tide", 1.06, 620, "in"); if (k !== this.seq) return; this.handedOff = true; - await this.props.onStart({ sound: this.soundOn, music: this.state.music / 5, effects: this.state.effects / 5, ...(surface ? { surface } : {}) }); + await this.props.onStart({ sound: this.soundOn, music: this.state.music / 5, effects: this.state.effects / 5 }); await this.wait(140); await this.tw(s, "tideA", 0, 520, "out"); if (k === this.seq && !this.dead) this.props.onDone(); } @@ -307,7 +303,7 @@ export default class Opening extends Component { if (port) { PW = Math.max(170, Math.min(236, (visW - 2 * m - 198 - 8 * k) / k - 10)); const G = 198 + 8 * k + (10 + PW) * k, left = 1110.5 - G / 2; mx = left + 95; postX = left + 198 + 8 * k; cxT = 1110.5; } const gx = (x: number) => postX + (x - 890) * k, gy = (y: number) => 858 + (y - 858) * k; const clampT = (Sx: number, x: number, y: number) => [Math.min(0, Math.max(W - 1536 * Sx, x)), Math.min(0, Math.max(H - 1024 * Sx, y))] as const; - const Sa = s0 * (zt + s.zoomAdd!), [txa, tya] = clampT(Sa, W / 2 - (cxT + (live ? Math.sin(t / 7000) * 6 : 0)) * Sa, H - 905 * Sa); + const Sa = s0 * (zt + s.zoomAdd!), [txa, tya] = clampT(Sa, W / 2 - cxT * Sa, H - 905 * Sa); const rightLimit = Math.min(1536, (W - txa) / Sa) - m; // Title size and centre that fit between the bakery roof (x 470) and R, in world units. const fit = (R: number) => { const F = Math.min(.105 * W, .21 * H, (R - 470) * Sa / 4.3), c = (470 + R) / 2 * Sa + txa; return { F, c, bot: (short ? .06 : .08) * H + F + (fz ? .2 * F : Math.max(.2 * F, 17)) * 1.7, right: c + F * 2.15 }; }; @@ -350,7 +346,7 @@ export default class Opening extends Component { e = $("veil"); if (e) { e.style.opacity = String(s.veil); e.style.display = s.veil! > 0 ? "block" : "none"; } e = $("tide"); if (e) { e.style.display = s.tide! > 0 ? "block" : "none"; e.style.height = (s.tide! * H) + "px"; e.style.opacity = String(s.tideA); } e = $("chap"); if (e) { e.style.opacity = String(s.chapA); const rl = e.lastElementChild; if (rl && rl.children.length === 3) { (rl.children[0] as HTMLElement).style.width = (rl.children[2] as HTMLElement).style.width = port || tucked ? "1em" : "2.4em"; (rl as HTMLElement).style.fontSize = fz ? ".2em" : "max(.2em,17px)"; } } - e = $("prompt"); if (e) { e.style.fontSize = fz ? (port ? "3.1cqw" : "1.25cqw") : "clamp(12px,1.25cqw,18px)"; e.style.opacity = String((s.courtA! > 0 ? 0 : 1) * s.promptA!); } + e = $("begin"); if (e) { const available = this.mode === "title" && s.promptA! > .9; e.hidden = !available; e.inert = !available; } e = $("cap"); if (e) { e.style.opacity = String(s.capA); @@ -389,8 +385,8 @@ export default class Opening extends Component { const ids = this.items(), inMenu = this.mode === "menu"; ids.forEach((id, i) => { const el = r.querySelector(`[data-plank="${id}"]`); if (!el) return; - const p = this.mp[id]!, seld = inMenu && this.sel === id, dt2 = t - (this.dip[id] ?? -1e9), dip = dt2 < 900 && live ? 3.2 * Math.exp(-dt2 / 260) * Math.cos(dt2 / 90) : 0, sway = live ? Math.sin(st / 1000 * 1.3 + i * 1.7) * .7 : 0; - el.style.transform = "rotate(" + ((1 - p) * -22 + p * ([-1.6, 1.2, -.8, 1.5, -1.1][i % 5]! + sway) + (seld ? 1.6 : 0) + dip) + "deg) scaleX(" + Math.max(.001, p) + ")"; + const p = this.mp[id]!, seld = inMenu && this.sel === id, dt2 = t - (this.dip[id] ?? -1e9), dip = dt2 < 900 && live ? 3.2 * Math.exp(-dt2 / 260) * Math.cos(dt2 / 90) : 0; + el.style.transform = "rotate(" + ((1 - p) * -22 + p * [-1.6, 1.2, -.8, 1.5, -1.1][i % 5]! + (seld ? 1.6 : 0) + dip) + "deg) scaleX(" + Math.max(.001, p) + ")"; el.style.width = PW + "px"; el.style.fontSize = tight ? Math.max(17, Math.min(21, PW / 10.6)) + "px" : "23px"; el.style.paddingRight = port ? "8px" : "12px"; el.style.opacity = String(Math.min(1, p * 1.6)); el.style.pointerEvents = p > .9 && inMenu && !this.frozen ? "auto" : "none"; el.style.filter = seld ? "drop-shadow(0 0 1.5px #ffe1a1) drop-shadow(0 0 7px #ffd58acc) brightness(1.06)" : "drop-shadow(0 3px 3px #2a1d1166)"; el.style.color = seld ? "#fff5d8" : "#fff0ce"; el.style.zIndex = seld ? "2" : "1"; }); @@ -486,8 +482,8 @@ export default class Opening extends Component {
{st.scroll === "tide" && <> -

One ask a day from the Tidekeeper, on a fresh Beacon Court.

- {this.hasLitHarbor ? :

The asks begin once the beacon is lit.

} +

Daily outings begin once the beacon is lit. Enter the harbor to see this harbor’s outing and rules.

+ } {st.scroll === "options" && <> @@ -546,7 +542,7 @@ export default class Opening extends Component {
{st.cap1}
{st.cap2}
-
{st.prompt}
+
); diff --git a/web/src/opening/opening.css b/web/src/opening/opening.css index 35e8fa0..81ac1a0 100644 --- a/web/src/opening/opening.css +++ b/web/src/opening/opening.css @@ -7,6 +7,7 @@ html:has(.familiar-opening:not(.framed)),body:has(.familiar-opening:not(.framed) .familiar-opening .fo-bell:focus-visible{border-radius:8px} .familiar-opening .fo-paper button:focus-visible{outline-color:#2b5f4d} .familiar-opening .fo-primary,.familiar-opening .fo-secondary{display:flex;align-items:center;justify-content:center;gap:10px;box-sizing:border-box;border-radius:999px;cursor:pointer;text-wrap:balance} +.familiar-opening [data-el="begin"][hidden]{display:none} .familiar-opening .fo-primary{min-height:52px;padding:10px 26px;border:0;background:#2b5f4d;color:#fff6e2;box-shadow:inset 0 1px 0 #5f9a83,inset 0 -3px 0 #1d4436,0 6px 14px rgba(31,68,54,.28);font:650 18px/1.2 'Fraunces Variable',serif} .familiar-opening .fo-primary:active{transform:translateY(1px);box-shadow:inset 0 1px 0 #5f9a83,inset 0 -1px 0 #1d4436,0 6px 14px rgba(31,68,54,.28)} .familiar-opening .fo-secondary{min-height:48px;padding:9px 18px;border:1.5px solid #d6c29b;background:#fffaf0;color:var(--fo-ink);font:600 17px/1.2 'Fraunces Variable',serif} diff --git a/web/src/run/TideRunGame.test.tsx b/web/src/run/TideRunGame.test.tsx index 82144db..2c6c580 100644 --- a/web/src/run/TideRunGame.test.tsx +++ b/web/src/run/TideRunGame.test.tsx @@ -1,6 +1,6 @@ import { expect, mock, test } from "bun:test"; import { renderToStaticMarkup } from "react-dom/server"; -import TideRunGame from "./TideRunGame"; +import TideRunGame, { TideRunRules } from "./TideRunGame"; import { applyMove, startTide, type TideState } from "./engine"; import { CHAPTERS, itemName, storyStart } from "./story"; @@ -37,9 +37,9 @@ test("all three story chapters keep their end card and retry button", () => { expect(html).toContain(CHAPTERS[prize].title); expect(html).toContain('aria-label="The tide is over"'); expect(html).toContain("Home for the day."); - expect(html).toContain(`The ${itemName(prize)} is still in its shell. The same tide comes again.`); + expect(html).toContain(`The ${itemName(prize)} is back in its shell. You can try the same tide again.`); expect(html).toContain('data-testid="tide-finish"'); - expect(html).toContain("Back to the harbor"); + expect(html).toContain("Return to the harbor"); expect(html).toContain('data-testid="tide-again"'); expect(html).toContain("Try this tide again"); expect(onFinish).not.toHaveBeenCalled(); @@ -50,7 +50,7 @@ test("a story prize brought home keeps the return card without offering a retry" for (const prize of ["lens", "vane", "moth"] as const) { const finished = applyMove(startTide(storyStart(prize)), "home")!.after; const { html } = render({ ...finished, banked: [prize], score: 3 }); - expect(html).toContain(`The ${itemName(prize)} is home. Banked 3 besides.`); + expect(html).toContain(`The ${itemName(prize)} is safe. Score: 3. Return to the harbor to continue.`); expect(html).toContain('data-testid="tide-finish"'); expect(html).not.toContain('data-testid="tide-again"'); } @@ -60,8 +60,8 @@ test("the tide run teaches direct play and keeps a closed native button alternat 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).toContain("R finishes at the dock"); + expect(html).toContain("I opens the guide"); expect(html).not.toContain("E interacts"); expect(html).not.toContain("tap a find to collect it"); expect(html).toContain('Button controls'); @@ -69,3 +69,50 @@ test("the tide run teaches direct play and keeps a closed native button alternat expect(html).not.toContain('
{ + for (const prize of ["lens", "vane", "moth"] as const) { + const label = prize === "lens" ? "Lens" : prize === "vane" ? "Vane" : "Moth"; + const active = { ...startTide(storyStart(prize)), moves: ["wait"] as const }; + const carried = render({ ...active, pack: [prize] }).html; + expect(carried).toContain(`${label} carried`); + expect(carried).not.toContain(`${label} safe`); + const banked = render({ ...active, banked: [prize] }).html; + expect(banked).toContain(`${label} safe`); + expect(banked).toContain('data-testid="tide-score">0'); + expect(banked).toContain("Pause outing"); + expect(banked).toContain("Pause returns you to the harbor with this outing still open."); + expect(banked).toContain("Step onto the center dock to bank cargo. Banking keeps the outing open."); + expect(banked).toContain('data-testid="tide-finish-return"'); + expect(banked).toContain("Finish and return"); + expect(banked).toContain("Keep gathering"); + expect(banked.indexOf('data-testid="tide-prize-status"')).toBeLessThan(banked.indexOf('class="tide-tray-reading"')); + expect(banked.indexOf('data-testid="tide-finish-return"')).toBeLessThan(banked.indexOf('Button controls')); + const finished = render({ ...active, banked: [prize], outcome: "home" }).html; + expect(finished).toContain(`The ${itemName(prize)} is safe. Score: 0. Return to the harbor to continue.`); + } +}); + +test("chapter briefings are narration without inventing Bram dialogue", () => { + for (const prize of ["lens", "vane", "moth"] as const) { + const { html } = render(startTide(storyStart(prize))); + expect(html).toContain(`aria-live="polite">${CHAPTERS[prize].before}`); + expect(html).not.toContain(`Bram: “${CHAPTERS[prize].before}”`); + } +}); + +test("the named objective remains visible beside last-wave advice", () => { + const { html } = render({ ...startTide(storyStart("lens")), wave: 7, beat: 21 }); + expect(html).toContain(CHAPTERS.lens.goal); + expect(html).toContain("The last wave. Get to the dock."); +}); + +test("shared Tide Run rules explain timing, cargo and activity length", () => { + for (const story of [undefined, "lens", "vane", "moth"] as const) { + const html = renderToStaticMarkup(); + expect(html).toContain("Every step or wait advances the water by one move. A wave arrives after every third move. Mochi moves first, then the wave lands."); + expect(html).toContain("Pause outing keeps the outing open. Reading, inspection, and menus spend no moves."); + expect(html).toContain("Story finds restore the harbor and add no points."); + expect(html).toContain(story === "lens" ? "This outing is 8 waves." : "This outing is 12 waves. From wave 7, each wave takes two lanes."); + } +}); diff --git a/web/src/run/TideRunGame.tsx b/web/src/run/TideRunGame.tsx index efddba6..5376d4c 100644 --- a/web/src/run/TideRunGame.tsx +++ b/web/src/run/TideRunGame.tsx @@ -1,8 +1,9 @@ import { useEffect, useMemo, useRef, useState } from "react"; import TideWorld from "./TideWorld"; import ControlHints from "../expedition/ControlHints"; +import { scrollReadingRegion } from "../expedition/keyboard-scroll"; import type { TideSnapshot } from "./scene"; -import { HEARTS, PACK_SLOTS, SLOTS, applyMove, countdown, legalMoves, stepDestination, tideShape, type Move, type Position, type TideEvent, type TideState, type TideTransition } from "./engine"; +import { HEARTS, PACK_SLOTS, SLOTS, applyMove, countdown, legalMoves, stepDestination, tideShape, type Move, type Position, type StoryPrize, type TideEvent, type TideState, type TideTransition } from "./engine"; import { bramsGuess } from "./bot"; import { CHAPTERS, aPrize, consequence, itemName, laneNames } from "./story"; import { STAMPS } from "../tide/run-day"; @@ -65,21 +66,39 @@ function sound(event: TideEvent): CourtEvent | null { } } +export function TideRunRules({ story }: { story?: StoryPrize }) { + const { waves, roughFrom } = tideShape({ story }); + return <> +
    +
  • {icon(WAVE)}Every step or wait advances the water by one move. A wave arrives after every third move. Mochi moves first, then the wave lands.
  • +
  • {icon(WAVE)}Read the tinted lanes and the moves left. The quay is safe from waves.
  • +
  • {icon(HEART)}A splash costs a heart and the last item Mochi picked up, and washes her toward the quay.
  • +
  • {icon(BAG)}Prizes are collected when Mochi steps onto them. The pack holds three slots; the wind-moth needs two.
  • +
  • {icon(BAG)}Reed scores 1, sea glass 3, and a pearl 6. Story finds restore the harbor and add no points.
  • +
  • {icon(HOME)}Step onto the center dock to bank cargo. Choose Finish and return there to end the outing.
  • +
  • {icon(HOME)}Pause outing keeps the outing open. Reading, inspection, and menus spend no moves.
  • +
  • {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(WAVE)}This outing 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.
  • +
+

Swipe or tap a neighboring platform to move. Tap Wait beside Mochi to let one move pass. WASD or arrow keys to move. Space waits · R finishes at the dock · I opens the guide. Optional Button controls offer the same decisions without gestures.

+ ; +} + export default function TideRunGame({ initial, reduced, sound: soundOn, audio, blocked, onSave, onFinish, onLeave, onToggleSound }: Props) { const [state, setState] = useState(initial), [result, setResult] = useState(null); const current = useRef(initial), pending = useRef(null), serial = useRef(0); const [ready, setReady] = useState(false), [fault, setFault] = useState(""), [sceneKey, setSceneKey] = useState(0); const [away, setAway] = useState(document.hidden), [guide, setGuide] = useState(false); const [finishError, setFinishError] = useState(false); - const finishAttempted = useRef(false), filed = useRef(false); + const finishAttempted = useRef(false), filed = useRef(false), explicitFinish = useRef(false); const chapter = initial.story ? CHAPTERS[initial.story] : null; - const [notice, setNotice] = useState(() => initial.outcome !== "active" || initial.moves.length ? "" : chapter ? `Bram: “${chapter.before}”` : `The Tidekeeper turns to the ${laneNames(initial.next.lanes).toLowerCase()} lane.`); + const [notice, setNotice] = useState(() => initial.outcome !== "active" || initial.moves.length ? "" : chapter ? chapter.before : `The Tidekeeper turns to the ${laneNames(initial.next.lanes).toLowerCase()} lane.`); 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 { waves } = tideShape(initial), legal = legalMoves(state); const used = seen.pack.reduce((sum, item) => sum + SLOTS[item], 0); 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]); @@ -125,16 +144,15 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b // The last thing that happened stays up until something else does. const line = consequence(accepted); if (line) setNotice(line); + if (accepted.after.moves.at(-1) === "home") explicitFinish.current = true; pending.current = null; setResult(null); } function target(position: Position) { const move = moveToward(current.current, position); if (move) take(move); } function finish(again: boolean) { - if (!current.current.story) { - if (!over || !ready || blocked || filed.current) return; - finishAttempted.current = true; - } + if (current.current.outcome === "active" || pending.current || (!ready && !current.current.story) || blocked || filed.current) return; + finishAttempted.current = true; const saved = onFinish(current.current, again); - if (!current.current.story && saved) filed.current = true; + if (saved) filed.current = true; setFinishError(!saved); } function leave() { @@ -142,14 +160,14 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b if (current.current.outcome !== "active") finish(false); else onLeave(); } useEffect(() => { - if (!state.story && over && ready && !blocked && !finishAttempted.current) finish(false); + if ((!state.story || explicitFinish.current) && over && ready && !blocked && !finishAttempted.current) finish(false); }, [state.story, over, ready, blocked, onFinish]); useEffect(() => { function keys(event: KeyboardEvent) { 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; + if (target.closest("button,a,summary,input,textarea,select,[contenteditable]:not([contenteditable=false]),dialog,[role=dialog],[role=slider],[role=tablist],.exp-input-reading")) return; const key = event.key.toLowerCase(), move = KEYS[key]; if (!move && key !== "i") return; event.preventDefault(); @@ -159,8 +177,9 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b }); const prizeHome = !!state.story && state.banked.includes(state.story); + const prizeSafety = seen.story && (seen.banked.includes(seen.story) ? "safe" : seen.pack.includes(seen.story) ? "carried" : null); + const prizeLabel = seen.story === "lens" ? "Lens" : seen.story === "vane" ? "Vane" : "Moth"; const lastWave = state.outcome === "active" && state.wave === waves - 1; - const objective = lastWave ? "The last wave. Get to the dock." : chapter ? (prizeHome ? "The rest of the tide is yours. Bank what you can." : chapter.goal) : ""; const title = state.outcome === "rescued" ? "Bram wades out for Mochi." : state.outcome === "turned" ? "The tide turns." : "Home for the day."; const lockControls = !ready || paused || busy; const feedback =
{notice}
; @@ -171,10 +190,10 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b onReady={() => setReady(true)} onFault={message => { setFault(message); setReady(false); pending.current = null; setResult(null); }} onBeat={beat} onSettled={settle} onTarget={target} onMove={take} onInspect={openGuide} />
familiar.Played and saved on this device
-

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

+

{chapter ? chapter.title : "Today’s Tide Run"}

- +
@@ -182,21 +201,21 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b {Array.from({ length: HEARTS }, (_, i) => {icon(HEART)})} {icon(BAG)}Pack {used}/{PACK_SLOTS} - {icon(HOME)}Banked {seen.score} - Mochi: wave {Math.min(seen.wave + 1, waves)} of {waves}, {seen.hearts} of {HEARTS} hearts, pack {used} of {PACK_SLOTS} slots, banked {seen.score} points, {seen.splashes === 0 ? "dry paws" : `splashed ${seen.splashes} ${seen.splashes === 1 ? "time" : "times"}`}. + {icon(HOME)}Score {seen.score} + Mochi: wave {Math.min(seen.wave + 1, waves)} of {waves}, {seen.hearts} of {HEARTS} hearts, pack {used} of {PACK_SLOTS} slots, score {seen.score}, {seen.splashes === 0 ? "dry paws" : `splashed ${seen.splashes} ${seen.splashes === 1 ? "time" : "times"}`}.
{fault ?

{fault}

: !ready && !over ?
Opening the tide…
: null} {blocked ?

This tide is paused while another view holds the harbor.

: away && !guide ?

Mochi is waiting. Return to this window to continue.

: null} {over && (state.story || finishError) &&

{title}

- {state.story ?

{prizeHome ? `The ${itemName(state.story)} is home. Banked ${state.score} besides.` : `The ${itemName(state.story)} is still in its shell. The same tide comes again.`}

- :

Banked {state.score}. Bram guessed {guess}.

} + {state.story ?

{prizeHome ? `The ${itemName(state.story)} is safe. Score: ${state.score}. Return to the harbor to continue.` : `The ${itemName(state.story)} is back in its shell. You can try the same tide again.`}

+ :

Score: {state.score}. Bram guessed {guess}.

} {feedback} - {finishError &&

This tide could not be saved. Try it again when this browser can save.

} + {finishError &&

This return could not be saved. Keep this finished outing open and try again when this browser can save.

}
- + {state.story && !prizeHome && }
} @@ -212,36 +231,31 @@ export default function TideRunGame({ initial, reduced, sound: soundOn, audio, b {stamp.ask(guess)} {status === "kept" ? "Kept." : status === "slipped" ? "Slipped." : "Still open."} ; })}} -
- {chapter &&

{objective}

} + {prizeSafety &&

{prizeLabel} {prizeSafety}

} + {prizeSafety === "safe" &&
} +
+ + {chapter &&

{chapter.goal}

} + {lastWave &&

The last wave. Get to the dock.

}

{icon(WAVE)}{state.outcome === "active" ? forecast(seen.outcome === "active" ? seen : state) : ""}

Mochi is at {where(seen.position)}. The bridge is at the {LANES[seen.bridge]} lane. {feedback} -
-
- +

Step onto the center dock to bank cargo. Banking keeps the outing open.

+

Pause returns you to the harbor with this outing still open.

+
} id="tide-input-hints" context={worldActions.includes("home") ? "Tap Finish to end the outing · tap Wait." : "Tap Wait · prizes collect as you step."} keyboardContext="Space waits · R finishes at the dock · I opens the guide">
{STEPS.map(move => )}
- {legal.includes("home") && state.moves.length > 0 && } + {legal.includes("home") && state.moves.length > 0 && prizeSafety !== "safe" && }
} {guide && { event.preventDefault(); setGuide(false); }}> - -

How the tide works

-
    -
  • {icon(WAVE)}Every step or wait is one move. A wave lands after every third move, down the tinted lanes. The number on a lane is the moves left.
  • -
  • {icon(HEART)}Be out of those lanes, or on the quay, when it lands. A splash costs a heart and the last thing Mochi picked up, and washes her one platform toward home.
  • -
  • {icon("m12 3 2.5 6.5L21 12l-6.5 2.5L12 21l-2.5-6.5L3 12l6.5-2.5L12 3Z")}The wave takes loose prizes in its lanes, then leaves the one that shimmers.
  • -
  • {icon(BAG)}A reed is worth 1, sea glass 3, a pearl 6. The pack holds {PACK_SLOTS}. Step on the dock to bank it.
  • -
  • {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.
  • -
-

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.

+

How Tide Run works

+
} ; } diff --git a/web/src/run/scene.ts b/web/src/run/scene.ts index dcaa75f..113a67f 100644 --- a/web/src/run/scene.ts +++ b/web/src/run/scene.ts @@ -321,7 +321,7 @@ export class TideScene extends Phaser.Scene { 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)); + this.keep(this.label(point.x,point.y,action==="wait"?"Wait":"Finish",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(); diff --git a/web/src/run/story.test.ts b/web/src/run/story.test.ts index f4290f2..d292e63 100644 --- a/web/src/run/story.test.ts +++ b/web/src/run/story.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { VALUE, applyMove, replayTide, startTide, tideShape, type StoryPrize, type TideTransition } from "./engine"; +import { STORY_SHELL, VALUE, applyMove, replayTide, startTide, tideShape, type StoryPrize, type TideTransition } from "./engine"; import { bramsGuess, cautiousMove, cautiousTide } from "./bot"; import { CHAPTERS, chapterFor, consequence, storyStart } from "./story"; import { closeTide, dayResult, dayResults, emptyBook, readBook, shelfHaul, todayResult, writeBook, type DayResult } from "./save"; @@ -38,14 +38,41 @@ test("every line said during a tide is about something that happened", () => { const said = (["lens", "vane", "moth"] as const).flatMap(prize => careful(prize).turns.map(consequence)); expect(said.every(line => !line.includes("undefined"))).toBe(true); expect(said.some(line => line.includes("The left shell opens. The lens is inside."))).toBe(true); - expect(said.some(line => line.includes("Mochi cradles the moth."))).toBe(true); - expect(said.some(line => line.includes("The lens is home."))).toBe(true); + expect(said.some(line => line.includes("Mochi cradles the wind-moth."))).toBe(true); + expect(said.some(line => line.includes("Lens safe. Finish and return to fit it into the beacon."))).toBe(true); expect(said).toContain("Banked three pieces of sea glass: +9."); expect(said.some(line => line.includes("The wave takes the sea glass and the reed back."))).toBe(true); const first = applyMove(startTide({ seed: 20771 }), "wait")!; expect(consequence(first)).toBe(""); }); +test("chapter briefings name the errand and preserve its established tide", () => { + expect(CHAPTERS.lens.before).toBe("The storm carried the Beacon Lens into the left shell. Bring it back so we can light the beacon."); + expect(CHAPTERS.vane.before).toBe("The beacon is lit. Bram needs the Signal Vane to read the wind. Bring it home from the right shell."); + expect(CHAPTERS.lens.goal).toBe("Bring the Beacon Lens home from the left shell."); + expect(CHAPTERS.vane.goal).toBe("Bring the Signal Vane home from the right shell."); + expect(CHAPTERS.moth.goal).toBe("Bring the wind-moth home from the right shell. It needs two pack slots."); + expect(Object.values(CHAPTERS).map(chapter => chapter.seed)).toEqual([5, 4, 15]); + expect(CHAPTERS.vane.after).toContain("Reeds from Wren’s garden. Glass from her windows. That’s not flotsam. The crab is bringing her house back."); +}); + +test("consequences describe settled possession instead of an obsolete same-move pickup", () => { + const state = startTide(storyStart("lens")), at = STORY_SHELL.lens; + const pickup = { kind: "pickup", item: "lens", at } as const; + const splash = { kind: "splash", from: at, to: { x: 0, y: 3 }, lost: "lens", hearts: 2 } as const; + const active: TideTransition = { before: state, after: { ...state, items: [{ ...at, kind: "lens" }] }, events: [pickup, splash] }; + expect(consequence(active)).not.toContain("Mochi carries"); + expect(consequence(active)).toContain("goes back to its shell"); + const ended: TideTransition = { before: state, after: { ...state, outcome: "turned" }, events: [pickup, { kind: "end", reason: "turned", lost: ["lens"] }] }; + expect(consequence(ended)).not.toContain("Mochi carries"); + expect(consequence(ended)).toContain("The tide turns and takes what was still in the pack."); + const carried: TideTransition = { before: state, after: { ...state, pack: ["lens"] }, events: [pickup] }; + expect(consequence(carried)).toBe("Mochi carries the Beacon Lens. Bring it to the center dock to bank it."); + const banked: TideTransition = { before: state, after: { ...state, banked: ["lens"] }, events: [pickup, { kind: "bank", items: ["lens"], gained: 0 }] }; + expect(consequence(banked)).toBe("Lens safe. Finish and return to fit it into the beacon."); + expect(consequence({ ...ended, events: [pickup, splash, { kind: "end", reason: "rescued", lost: [] }] })).not.toContain("goes back to its shell"); +}); + function memory() { const data = new Map(); return { data, getItem: (key: string) => data.get(key) ?? null, setItem: (key: string, value: string) => { data.set(key, value); } }; @@ -87,6 +114,29 @@ test("a tide book survives a reload and keeps each day's first tide", () => { }); +test("a rescued or voluntary zero-score first result survives better practice and reload", () => { + const seed = 20771; + let rescued = startTide({ seed }); + while (rescued.outcome === "active") { + const move = rescued.position.y === 0 ? "north" : "wait"; + rescued = applyMove(rescued, move)!.after; + } + expect(rescued.outcome).toBe("rescued"); + expect(rescued.score).toBe(0); + const voluntary = applyMove(startTide({ seed }), "home")!.after; + const better = cautiousTide(seed); + expect(better.score).toBeGreaterThan(0); + for (const first of [rescued, voluntary]) { + const storage = memory(), key = "tide"; + writeBook(storage, key, closeTide({ active: first, days: [] }, first)); + const restored = readBook(storage, key); + const practiced = closeTide({ ...restored, active: better }, better); + writeBook(storage, key, practiced); + expect(readBook(storage, key).days).toEqual([first]); + expect(todayResult(readBook(storage, key), seed)).toEqual(dayResult(first)); + } +}); + test("day results put the newest day first without changing the book", () => { const first = cautiousTide(20771), second = cautiousTide(20772); const book = { active: null, days: [first, second] }; diff --git a/web/src/run/story.ts b/web/src/run/story.ts index ad74261..dd97d69 100644 --- a/web/src/run/story.ts +++ b/web/src/run/story.ts @@ -17,23 +17,24 @@ export interface Chapter { export const CHAPTERS: Readonly> = { lens: { number: 1, title: "First light", seed: 5, - before: "The lens went over the wall in the storm. It’s in the left shell. The old crab won’t let anyone near it.", - goal: "Grab what the tide leaves. Don’t be in a lane when its wave lands. Step on the dock to bank.", + before: "The storm carried the Beacon Lens into the left shell. Bring it back so we can light the beacon.", + goal: "Bring the Beacon Lens home from the left shell.", after: ["Forty years I’ve known that crab. Never once seen it hold still."], }, vane: { number: 2, title: "What the tide brings", seed: 4, - before: "Reeds from Wren’s garden. Glass from her windows. That’s not flotsam. The crab is bringing her house back.", - goal: "The Signal Vane is in the right shell. Bring it home, and anything else the tide leaves.", + before: "The beacon is lit. Bram needs the Signal Vane to read the wind. Bring it home from the right shell.", + goal: "Bring the Signal Vane home from the right shell.", after: [ "Wren kept this light. The night it failed she rowed out to guide the boats in by hand. The boats came home.", + "Reeds from Wren’s garden. Glass from her windows. That’s not flotsam. The crab is bringing her house back.", "The Tidekeeper was her familiar. It has been waiting for her light ever since. And now it’s on.", ], }, moth: { number: 3, title: "The last thing", seed: 15, before: "There’s one thing it never gave up. Her wind-moth. Kept it dry in that shell through the whole storm.", - goal: "The moth is in the right shell. It takes two places in the pack.", + goal: "Bring the wind-moth home from the right shell. It needs two pack slots.", after: ["It knows she isn’t coming. It gave you the moth anyway.", "Two familiars and one light. That’ll do for a harbor."], }, }; @@ -71,33 +72,39 @@ const OPENED: Readonly> = { moth: "The right shell opens. Something inside is glowing.", }; const CARRIED: Readonly> = { - lens: "Mochi has the lens. Home is the dock.", - vane: "Mochi has the vane. Home is the dock.", - moth: "Mochi cradles the moth. It takes two places in her pack.", + lens: "Mochi carries the Beacon Lens. Bring it to the center dock to bank it.", + vane: "Mochi carries the Signal Vane. Bring it to the center dock to bank it.", + moth: "Mochi cradles the wind-moth. Bring it to the center dock to bank it.", }; const HOME: Readonly> = { - lens: "The lens is home. The rest of the tide is yours.", - vane: "The vane is home. The rest of the tide is yours.", - moth: "The moth is home.", + lens: "Lens safe. Finish and return to fit it into the beacon.", + vane: "Vane safe. Finish and return to fit it onto the signal post.", + moth: "Moth safe. Finish and return to bring it into the harbor.", }; const isStory = (item: Item | null): item is StoryPrize => item === "lens" || item === "vane" || item === "moth"; /** One or two sentences about what this move really did, or nothing. Nothing is said that did not happen. */ -export function consequence({ events }: TideTransition): string { +export function consequence({ events, after }: TideTransition): string { const facts: string[] = []; for (const event of events) switch (event.kind) { - case "pickup": facts.push(isStory(event.item) ? CARRIED[event.item] : `Mochi takes the ${itemName(event.item)}.`); break; + case "pickup": + if (after.outcome === "active" && after.pack.includes(event.item) && !events.some(later => later.kind === "splash" && later.lost === event.item)) + facts.push(isStory(event.item) ? CARRIED[event.item] : `Mochi takes the ${itemName(event.item)}.`); + break; case "full": facts.push(`No room for the ${itemName(event.item)}. Bank at the dock first.`); break; case "bank": { const story = event.items.find(isStory); - facts.push(story ? HOME[story] : `Banked ${list(event.items)}: +${event.gained}.`); + if (!story || after.banked.includes(story)) facts.push(story ? HOME[story] : `Banked ${list(event.items)}: +${event.gained}.`); break; } case "sweep": facts.push(`The wave takes ${list(event.items.map(item => item.kind), true)} back.`); break; case "shield": facts.push("The Tidekeeper puts a claw in the water. The wave goes around."); break; - case "splash": facts.push(event.lost - ? `Splashed. The ${itemName(event.lost)} ${isStory(event.lost) ? "goes back to its shell" : "is gone"}.` - : "Splashed. Mochi shakes it off."); break; + case "splash": { + const returned = after.outcome === "active" && after.items.some(item => item.kind === event.lost); + const lost = isStory(event.lost) ? returned ? "goes back to its shell" : "was not banked" : "is gone"; + facts.push(event.lost ? `Splashed. The ${itemName(event.lost)} ${lost}.` : "Splashed. Mochi shakes it off."); + break; + } case "open": facts.push(OPENED[event.item]); break; case "leave": facts.push(`The tide leaves ${list(event.items.map(item => item.kind))}.`); break; case "end": diff --git a/web/src/run/tide-run.css b/web/src/run/tide-run.css index bf8cb17..3a89d40 100644 --- a/web/src/run/tide-run.css +++ b/web/src/run/tide-run.css @@ -22,7 +22,6 @@ .tide-run .tide-asks { flex: none; flex-direction: row; flex-wrap: nowrap; align-items: center; justify-content: space-between; gap: 3px; } .tide-run .tide-asks > li { flex: none; min-height: 32px; gap: 3px; padding: 3px; font: 500 12px/1.25 "Figtree Variable", sans-serif; white-space: nowrap; } .tide-run .tide-asks .tide-ask-icon img { width: 24px; height: 24px; } -.tide-run .tide-tray-reading { min-height: 0; overflow-y: auto; overscroll-behavior: contain; } .tide-run .exp-current-controls { flex: none; } .tide-run .exp-objective-row { gap: 12px; align-items: center; margin-bottom: 10px; } .tide-run .exp-objective { font: 600 17px/1.3 "Fraunces Variable", serif; margin: 0!important; } @@ -53,12 +52,12 @@ .tide-run .tide-stamps li[data-earned=true] .tide-stamp-mark { border: 1px solid #80927b; background: #e6e7cf; } .tide-run .tide-stamps li[data-earned=true] img { opacity: 1; filter: none; } .tide-run .tide-stamps li[data-earned=true] svg { background: var(--exp-sea); color: var(--exp-paper); } -.tide-run .passage-panel { width: min(580px, calc(100% - 24px)); padding: 24px; } +.tide-run .passage-panel { --exp-panel-pad: 24px; width: min(580px, calc(100% - 24px)); padding: var(--exp-panel-pad); } .tide-run .passage-panel h2 { margin-bottom: 6px; font-size: 28px; } -.tide-run .tide-guide { margin: 0; padding: 0; list-style: none; } -.tide-run .tide-guide li { display: flex; gap: 14px; padding: 14px 0; border-bottom: 1px solid var(--exp-hairline); font-size: 15px; line-height: 1.5; } -.tide-run .tide-guide li > svg { flex: none; margin-top: 2px; color: var(--exp-sea); } -.tide-run .tide-guide-keys { margin: 18px 0 0; font-size: 13px; line-height: 1.5; color: var(--exp-secondary-ink); } +.exp-game .tide-guide { margin: 0; padding: 0; list-style: none; } +.exp-game .tide-guide li { display: flex; gap: 14px; padding: 14px 0; border-bottom: 1px solid var(--exp-hairline); font-size: 15px; line-height: 1.5; } +.exp-game .tide-guide li > svg { flex: none; margin-top: 2px; color: var(--exp-sea); } +.exp-game .tide-guide-keys { margin: 18px 0 0; font-size: 13px; line-height: 1.5; color: var(--exp-secondary-ink); } @media (max-width: 899px) and (orientation: portrait) { .tide-run .exp-mast { display: grid; grid-template-columns: 1fr auto; gap: 7px; } .tide-run .exp-brand { justify-self: start; max-width: 182px; padding: 7px 10px; } @@ -85,8 +84,8 @@ .tide-run .tide-finish { padding: 24px 20px; } .tide-run .tide-finish h2 { font-size: 28px; } .tide-run .tide-stamps { gap: 8px; } - .tide-run .passage-panel { padding: 18px; } - .tide-run .tide-guide li { font-size: 14px; gap: 12px; padding: 12px 0; } + .tide-run .passage-panel { --exp-panel-pad: 18px; } + .exp-game .tide-guide li { font-size: 14px; gap: 12px; padding: 12px 0; } } @media (orientation: landscape) and (max-height: 500px) { .tide-run .exp-brand { padding: 6px 12px; } @@ -101,7 +100,6 @@ .tide-run .passage-tray { top: 140px; bottom: 10px; left: auto; right: 10px; width: 260px; max-height: none; padding: 10px; gap: 6px; overflow: hidden; } .tide-run .tide-asks { justify-content: flex-start; gap: 6px; } .tide-run .tide-asks .tide-ask-label { display: none; } - .tide-run .tide-tray-reading { flex: 1; } .tide-run .exp-objective-row { flex-direction: column; align-items: stretch; gap: 0; margin: 0; } .tide-run .exp-objective { font-size: 15px; } .tide-run .exp-forecast { display: block; clear: both; padding: 8px 0; margin: 0 0 6px!important; font-size: 13px; line-height: 1.35; } @@ -128,7 +126,7 @@ .tide-run .tide-stamp-mark { flex: none; width: 36px; height: 36px; } .tide-run .tide-stamp-mark img { width: 28px; height: 28px; } .tide-run .tide-stamp-mark > svg { width: 16px; height: 16px; } - .tide-run .passage-panel { max-height: calc(100dvh - 20px); padding: 16px 22px; } + .tide-run .passage-panel { --exp-panel-pad: 22px; max-height: calc(100dvh - 20px); } } @media (pointer: coarse) { .tide-run .exp-directions { grid-template-columns: repeat(3, 56px); grid-template-rows: repeat(3, 56px); } @@ -145,18 +143,27 @@ /* 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 .tide-controls{position:relative;display:grid;flex:1;min-height:0;grid-template-columns:minmax(0,1fr) auto auto;grid-template-rows:minmax(48px,1fr) auto;gap:4px} +.tide-run .tide-controls .exp-control-hints{display:contents} +.tide-run .tide-controls .exp-input-reading{grid-column:1/-1;grid-row:1;min-height:0;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:#8b734c var(--exp-card);scroll-padding:6px;pointer-events:auto} +.tide-run .exp-input-more{grid-column:2;grid-row:2;width:44px;min-height:44px;padding:8px;pointer-events:auto} +.tide-run .tide-controls .exp-button-controls{position:static;grid-column:1;grid-row:2;align-self:stretch} .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 .tide-guide-control{position:static;grid-column:3;grid-row:2;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} +.tide-run .tide-prize-status{flex:none;margin:0;font:650 17px/1.3 "Fraunces Variable",serif;color:var(--exp-sea)} +.tide-run .tide-return-advice,.tide-run .tide-dock-instruction,.tide-run .tide-pause-explanation{margin:6px 0;font-size:13px;line-height:1.4;white-space:normal} +.tide-run .tide-pause-explanation{color:var(--exp-secondary-ink)} +.tide-run .tide-bank-actions{display:flex;flex:none;align-items:center;gap:8px;margin:0} +.tide-run .tide-bank-actions .exp-primary{min-height:56px;flex:1;white-space:normal;line-height:1.3;padding:10px 14px} +.tide-run .tide-bank-actions .exp-text-button{min-height:44px;max-width:90px;white-space:normal;font-size:13px;line-height:1.3} @media(max-width:899px) and (orientation:portrait){ - .tide-run .passage-tray{max-height:200px;padding:8px 10px;gap:5px} + /* Reserve the HUD, four 44px board intervals and dock clearance before expanding the reading. */ + .tide-run .passage-tray{max-height:clamp(200px,calc(100dvh - 484px),360px);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} @@ -173,9 +180,11 @@ .tide-run .tide-tally>svg{display:none} .tide-run .tide-tally b{font-size:16px} .tide-run .passage-tray{max-height:176px} + .tide-run .passage-tray:has(.tide-bank-actions){max-height:212px} } @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 .tide-guide-control{font-size:13px;padding-inline:0} .tide-run .exp-button-controls-body{max-height:calc(100dvh - 160px)} } diff --git a/web/src/tide/TideAsk.tsx b/web/src/tide/TideAsk.tsx index 8b1c884..3d75943 100644 --- a/web/src/tide/TideAsk.tsx +++ b/web/src/tide/TideAsk.tsx @@ -30,12 +30,12 @@ function RunAsk({ day, card, guess, result, sailBlockedReason, onSail, onOpenLog const canSail = sailBlockedReason === null; return
-

Today’s tide

+

Today’s Tide Run

{dayLabel(day)}

-

{card.name}

Twelve waves, two lanes at a time from the seventh. Each wave leaves a prize; bank it at the dock.

+

Bring finds home before the tide turns.

Twelve waves; two lanes at a time from the seventh. Waves can leave finds. Bring them to the center dock to bank them.

The Tidekeeper asks

    @@ -46,7 +46,9 @@ function RunAsk({ day, card, guess, result, sailBlockedReason, onSail, onOpenLog )}

Bram plays it safe: he never ends a wave in the water. His guess is what that careful tide banks.

- {result &&

Today’s tide: {resultLine(result)}. Another sail is practice; the first tide each day is the one that counts.

} + {result &&

Today’s Tide Run: {resultLine(result)}.

} +

Your first finished daily outing sets that day’s score and stamps, even if the tide turns or Bram brings Mochi home. Later sails are practice. Pausing does not finish an outing.

+

A paused outing keeps its original day.

{!canSail &&

{sailBlockedReason}

}
diff --git a/web/src/tide/TideHome.tsx b/web/src/tide/TideHome.tsx index eb46b9b..5d419d6 100644 --- a/web/src/tide/TideHome.tsx +++ b/web/src/tide/TideHome.tsx @@ -1,6 +1,6 @@ import { useId, type CSSProperties, type JSX } from "react"; import { cardStatus, type Run, type TideCard } from "./asks"; -import { askLine } from "./cards"; +import { askLine, dayLabel } from "./cards"; import { CARD_PICTURE, sealArt } from "./art"; import { homeResult } from "./pages"; import TideStamp from "./TideStamp"; @@ -32,6 +32,7 @@ function RunHome({ card, result, canShelve, reduced, notice, sailBlockedReason, {kept && }

{resultTitle(result)}

+

Tide Run · {dayLabel(result.day)}

{resultLine(result)}

{notice &&

{notice}

} diff --git a/web/src/tide/TideLog.tsx b/web/src/tide/TideLog.tsx index 4d7b768..8f8c66d 100644 --- a/web/src/tide/TideLog.tsx +++ b/web/src/tide/TideLog.tsx @@ -47,7 +47,7 @@ export default function TideLog({ pages, initialPage, reduced, sailBlockedReason : null, [page]); const move = (by: number) => setSelected(Math.max(0, Math.min(last, index + by))); - const title = page?.kind === "story" ? page.title : page?.card.name; + const title = page?.kind === "story" ? page.title : page?.kind === "run" ? `Tide Run · ${dayLabel(page.day)}` : page?.card.name; const pageKey = page?.kind === "story" ? `story:${page.id}` : page?.kind === "run" ? `run:${page.day}` : `tide:${selectedDay}`; return
@@ -62,7 +62,7 @@ export default function TideLog({ pages, initialPage, reduced, sailBlockedReason

{collected} of 14 collected{sealed > 0 ? `, ${sealed} with the brass seal` : ""}

{stamps.map(({ card, entry, result, allThree }) => entry || result - ? : Not collected yet)} @@ -77,7 +77,7 @@ export default function TideLog({ pages, initialPage, reduced, sailBlockedReason

{title}

-

{page.kind === "story" ? page.subtitle : page.kind === "run" ? `${dayLabel(page.day)} · tide run` : `${dayLabel(page.day)}${page.entry.late ? " · sailed late" : ""}`}

+ {page.kind !== "run" &&

{page.kind === "story" ? page.subtitle : `${dayLabel(page.day)}${page.entry.late ? " · sailed late" : ""}`}

} {page.kind === "run" ? :
{frames ? :

This page’s route could not be redrawn on this device.

} @@ -112,7 +112,7 @@ function RunPage({ page }: { page: Extract }): JSX.Ele

Reed and glass go to Bram’s shelf. Pearls stay with Mochi.

-
Banked
{result.score}
+
Score
{result.score}
Bram’s guess
{result.guess}
Splashes
{result.splashes}
diff --git a/web/src/tide/ask-ui.test.tsx b/web/src/tide/ask-ui.test.tsx index 1c6a513..6e5aef2 100644 --- a/web/src/tide/ask-ui.test.tsx +++ b/web/src/tide/ask-ui.test.tsx @@ -1,11 +1,12 @@ import { expect, test } from "bun:test"; import { renderToStaticMarkup } from "react-dom/server"; import { replayRun, solve, startRun, type Ask } from "./asks"; -import { askChip, askLine, cardForDay } from "./cards"; +import { askChip, askLine, cardForDay, TIDE_POOL } from "./cards"; import type { TideEntry } from "./log"; import TideAsk from "./TideAsk"; import TideHud from "./TideHud"; import TideLog from "./TideLog"; +import { CARD_PICTURE } from "./art"; import type { DayResult } from "./run-day"; const day = 20771, card = cardForDay(day); @@ -68,10 +69,10 @@ const runAsk = { day, card, guess: 6, result: null, sailBlockedReason: null, onS test("today’s tide run keeps the card, painted asks and Bram’s guess together", () => { const html = renderToStaticMarkup(); - expect(html).toContain("Today’s tide"); - expect(html).toContain(`

${card.name}

`); + expect(html).toContain("Today’s Tide Run"); + expect(html).toContain("Bring finds home before the tide turns."); expect(html).toContain("Saturday 14 November"); - expect(html).toContain("Twelve waves, two lanes at a time from the seventh. Each wave leaves a prize; bank it at the dock."); + expect(html).toContain("Twelve waves; two lanes at a time from the seventh. Waves can leave finds. Bring them to the center dock to bank them."); expect(html).toContain("The Tidekeeper asks"); for (const line of ["Come home with something.", "Match or beat Bram’s guess of 6.", "Keep Mochi dry the whole tide."]) expect(html).toContain(line); for (const icon of ["/assets/season/purse.webp", "/assets/ui/ask-all-marks.webp", "/assets/ui/ask-dry.webp"]) { @@ -94,13 +95,34 @@ test("a recorded tide run marks the three asks and offers practice", () => { expect(html.match(/class="tide-ask-mark"/g)).toHaveLength(3); expect(html.match(/\(kept\)/g)).toHaveLength(2); expect(html.match(/\(slipped\)/g)).toHaveLength(1); - expect(html).toContain("Today’s tide: Banked 7 · Bram guessed 6. Another sail is practice; the first tide each day is the one that counts."); + expect(html).toContain("Today’s Tide Run: Banked 7 · Bram guessed 6."); expect(html).toContain("Sail again for practice"); expect(html).not.toContain("tide-stamp-seal"); const allThree = renderToStaticMarkup(); expect(allThree).toContain('class="tide-stamp-seal"'); }); +test("all fourteen device cards retain their picture but use neutral Tide Run preparation and disclose first-finished scoring before Sail", () => { + const disclosure = "Your first finished daily outing sets that day’s score and stamps, even if the tide turns or Bram brings Mochi home. Later sails are practice. Pausing does not finish an outing."; + for (const daily of TIDE_POOL) { + const retained = renderToStaticMarkup( {}} onOpenLog={() => {}}/>); + expect(retained).toContain(`

${daily.name}

`); + for (const ask of daily.asks) expect(retained).toContain(askLine(ask, daily.tool)); + for (const result of [null, runResult]) { + const html = renderToStaticMarkup(); + expect(html).toContain("Today’s Tide Run"); + expect(html).toContain(`alt="${CARD_PICTURE[daily.id]}"`); + expect(html).not.toContain(`

${daily.name}

`); + expect(html).toContain(disclosure); + expect(html.indexOf(disclosure)).toBeLessThan(html.indexOf('class="exp-primary"')); + expect(html).toContain("A paused outing keeps its original day."); + expect(html).not.toContain("Each wave leaves a prize"); + expect(html).not.toContain("No waiting"); + expect(html).not.toContain("Surf home"); + } + } +}); + test("a blocked run sail stays focusable and describes its reason", () => { for (const result of [null, runResult]) { const reason = "Finish the outing in progress first."; diff --git a/web/src/tide/home-ui.test.tsx b/web/src/tide/home-ui.test.tsx index 0582ff5..e3359e1 100644 --- a/web/src/tide/home-ui.test.tsx +++ b/web/src/tide/home-ui.test.tsx @@ -1,6 +1,7 @@ import { expect, test } from "bun:test"; import { renderToStaticMarkup } from "react-dom/server"; -import { cardForDay } from "./cards"; +import { cardForDay, dayLabel, TIDE_POOL } from "./cards"; +import { CARD_PICTURE } from "./art"; import { replayRun, solve } from "./asks"; import TideHome from "./TideHome"; import type { DayResult } from "./run-day"; @@ -87,6 +88,17 @@ test("the run Home sheet celebrates all three with one primary and a compact, re expect(html).not.toContain("Sail again for practice"); }); +test("all device Home sheets name Tide Run and preserve the card picture without court constraints", () => { + for (const daily of TIDE_POOL) { + const html = renderToStaticMarkup(); + expect(html).toContain(`Tide Run · ${dayLabel(runResult.day)}`); + expect(html).toContain(`alt="${CARD_PICTURE[daily.id]}"`); + expect(html).not.toContain(`>${daily.name}`); + expect(html).not.toContain("No waiting"); + expect(html).not.toContain("Surf home"); + } +}); + test("partial run results show slipped labels without a proud portrait or all-three seal", () => { const partial = { ...runResult, score: 5, stamps: { home: true, guess: false, dry: false }, splashes: 1 }; const html = renderToStaticMarkup(); diff --git a/web/src/tide/log-ui.test.tsx b/web/src/tide/log-ui.test.tsx index 0fdb6a7..72f2ee3 100644 --- a/web/src/tide/log-ui.test.tsx +++ b/web/src/tide/log-ui.test.tsx @@ -1,7 +1,7 @@ import { expect, test } from "bun:test"; import { renderToStaticMarkup } from "react-dom/server"; import { CARD_PICTURE } from "./art"; -import { cardForDay, dayLabel } from "./cards"; +import { cardForDay, dayLabel, TIDE_POOL } from "./cards"; import { tideSummary, type TideEntry } from "./log"; import { logPages } from "./pages"; import type { DayResult } from "./run-day"; @@ -25,8 +25,7 @@ function render(run = result, entries: readonly TideEntry[] = []) { test("a tide-run page shows its card, paper, haul, facts and three final stamp lines", () => { const html = render(); - expect(html).toContain(`

${card.name}

`); - expect(html).toContain(`${dayLabel(day)} · tide run`); + expect(html).toContain(`

Tide Run · ${dayLabel(day)}

`); expect(html).toContain('class="tide-log-chart tide-log-run"'); expect(html).toContain('--tide-paper:url(/assets/tide/log-page.webp)'); expect(html).toContain('--stamp:84px;--tilt:5deg'); @@ -37,7 +36,7 @@ test("a tide-run page shows its card, paper, haul, facts and three final stamp l expect(html).toContain(`src="${prize}" width="24" height="24" alt="" decoding="async"`); } expect(html).toContain("Reed and glass go to Bram’s shelf. Pearls stay with Mochi."); - expect(html).toContain('
Banked
6
'); + expect(html).toContain('
Score
6
'); expect(html).toContain('
Bram’s guess
6
'); expect(html).toContain('
Splashes
0
'); for (const line of ["Came home with something", "Matched Bram’s guess", "Dry paws"]) expect(html).toContain(line); @@ -55,14 +54,14 @@ test("a tide-run page shows its card, paper, haul, facts and three final stamp l test("a run-only stamp is collected, sealed and labelled with its kept count", () => { const html = render(); - expect(html).toContain('aria-label="Surf home stamp, 3 of 3 kept. Open its page."'); + expect(html).toContain('aria-label="Tide Run stamp, 3 of 3 kept. Open its page."'); expect(html).toContain("1 of 14 collected, 1 with the brass seal"); expect(html.match(/class="tide-stamp-seal"/g)).toHaveLength(2); }); test("an empty run still collects its card and shows slipped stamps without a haul", () => { const html = render({ ...result, score: 0, banked: [], stamps: { home: false, guess: false, dry: false }, splashes: 2 }); - expect(html).toContain('aria-label="Surf home stamp, 0 of 3 kept. Open its page."'); + expect(html).toContain('aria-label="Tide Run stamp, 0 of 3 kept. Open its page."'); expect(html).toContain("1 of 14 collected"); expect(html).not.toContain("brass seal"); expect(html).not.toContain('class="tide-stamp-seal"'); @@ -72,6 +71,17 @@ test("an empty run still collects its card and shows slipped stamps without a ha expect(html.match(/\(slipped\)/g)).toHaveLength(3); }); +test("every device stamp and run page keeps its art without borrowing the retained court name", () => { + for (const daily of TIDE_POOL) { + const date = Array.from({ length: 14 }, (_, i) => day + i).find(value => cardForDay(value).id === daily.id)!; + const html = render({ ...result, day: date }); + expect(html).toContain(`

Tide Run · ${dayLabel(date)}

`); + expect(html).toContain('aria-label="Tide Run stamp, 3 of 3 kept. Open its page."'); + expect(html).toContain(`alt="${CARD_PICTURE[daily.id]}"`); + expect(html).not.toContain(`

${daily.name}

`); + } +}); + test("mixed logs retain the legacy stamp label while crediting a run's brass seal", () => { const html = render(result, [legacy]); expect(html).toContain('aria-label="Surf home stamp, 2 of 3 asks kept. Open its page."'); diff --git a/web/src/tide/pages.test.ts b/web/src/tide/pages.test.ts index 05b7d87..b1dec74 100644 --- a/web/src/tide/pages.test.ts +++ b/web/src/tide/pages.test.ts @@ -464,14 +464,14 @@ describe("tide-run harbor card", () => { test("introduces today's tide and Bram's guess", () => { expect(harborTide({ ...base, result: null })).toEqual({ - kind: "panel", title: "Today’s tide: Surf home.", body: "Twelve waves. Bram guesses 6.", + kind: "panel", title: "Today’s Tide Run.", body: "Twelve waves. Bram guesses 6.", primary: { label: "See today’s tide", target: "tide" }, links: [], }); }); test("a shelved day with a missing result still shows tomorrow", () => { expect(harborTide({ ...base, shelved: true, result: null })).toEqual({ - kind: "panel", title: "Tomorrow: Bram’s bridge.", body: "Today’s haul is on Bram’s shelf.", primary: null, + kind: "panel", title: "Tomorrow’s Tide Run.", body: "Today’s haul is on Bram’s shelf.", primary: null, links: [{ label: "Sail today’s tide", action: "sail" }, { label: "Open the tide log", action: "log" }], }); }); @@ -485,7 +485,7 @@ describe("tide-run harbor card", () => { test("a shelved result shows tomorrow with the day's score", () => { for (const returnedToday of [false, true]) expect(harborTide({ ...base, returnedToday, shelved: true, result: result() })).toEqual({ - kind: "panel", title: "Tomorrow: Bram’s bridge.", + kind: "panel", title: "Tomorrow’s Tide Run.", body: "All three kept. Banked 6 · Bram guessed 6. Today’s haul is on Bram’s shelf.", primary: null, links: practice, }); }); diff --git a/web/src/tide/pages.ts b/web/src/tide/pages.ts index c07fe16..d97d1c2 100644 --- a/web/src/tide/pages.ts +++ b/web/src/tide/pages.ts @@ -142,13 +142,13 @@ type ClassicHarbor = { lit: boolean; card: TideCard; next: TideCard; entry: Tide /** A device harbor's card, driven by today's tide-run result. */ export type RunHarbor = { lit: boolean; card: TideCard; next: TideCard; guess: number; result: DayResult | null; returnedToday: boolean; shelved: boolean }; -function harborRun({ lit, card, next, guess, result, returnedToday, shelved }: RunHarbor): HarborTide | null { +function harborRun({ lit, guess, result, returnedToday, shelved }: RunHarbor): HarborTide | null { if (!lit) return null; const links: TideLink[] = [{ label: result ? "Sail again for practice" : "Sail today’s tide", action: "sail" }, { label: "Open the tide log", action: "log" }]; if (!result) return shelved - ? { kind: "panel", title: `Tomorrow: ${next.name}.`, body: "Today’s haul is on Bram’s shelf.", primary: null, links } - : { kind: "panel", title: `Today’s tide: ${card.name}.`, body: `Twelve waves. Bram guesses ${guess}.`, primary: { label: "See today’s tide", target: "tide" }, links: [] }; - if (shelved) return { kind: "panel", title: `Tomorrow: ${next.name}.`, body: `${resultTitle(result)} ${resultLine(result)}. Today’s haul is on Bram’s shelf.`, primary: null, links }; + ? { kind: "panel", title: "Tomorrow’s Tide Run.", body: "Today’s haul is on Bram’s shelf.", primary: null, links } + : { kind: "panel", title: "Today’s Tide Run.", body: `Twelve waves. Bram guesses ${guess}.`, primary: { label: "See today’s tide", target: "tide" }, links: [] }; + if (shelved) return { kind: "panel", title: "Tomorrow’s Tide Run.", body: `${resultTitle(result)} ${resultLine(result)}. Today’s haul is on Bram’s shelf.`, primary: null, links }; return { kind: "panel", title: resultTitle(result), body: `${resultLine(result)}.`, primary: returnedToday ? { label: "Take it to Bram", target: "bram" } : null, links }; }