diff --git a/PROGRESS.md b/PROGRESS.md index b965df5..97187bb 100644 --- a/PROGRESS.md +++ b/PROGRESS.md @@ -22,6 +22,9 @@ Full earlier progress and acceptance records are preserved in the [archive](docs | 2026-11-13 | Season 2 game screens built locally behind `VITE_SEASON2_ENABLED` (`feat/season-two-ui`), not deployed | `bun run test` 259 pass; `cargo test --workspace` 175 passed/3 ignored; `make build`, `make browser` (Chromium/WebKit), `make evidence`; `bun run test:season-browser` at 390×844 and 1440×900 on day 20770 (`first_light_v1`) and day 20771 (`first_light_v2`: the 17-step rope route was played through the real controls, kept as a tide return, First Light home and return memories unchanged) | Bram's shelf and till read live `get_shelf`/`get_today` from `season.familiar-game.testnet`; quotes simulate unit by unit and match the live one-unit `buy_price`/`sell_price`; trades send `max_price`/`min_price` from the shown quote. Signed out, the market is a labelled device preview using `pricing.ts`. Today's tide starts a fresh Beacon Court outing kept apart from First Light progress and docks it with `claim_daily`. Mochi's wish sets/cancels and shows the postcard. Signer allowlist now admits exactly `claim_daily`, `buy`, `sell`, `set_wish`, `cancel_wish` and `storage_deposit` (0.0125 NEAR exactly) on `season.`. Browser check: views live, signed-in ledger and signing mocked in a dev-only harness. **No signed-in trade, claim, wish or registration has run on testnet.** Under the production Privy provider the hosted relayer signs nothing native; season calls are checked by `validateNativeIntent` in the browser (`privy-adapter.ts`), so the allowlist and receiver gates go live on merge even with the flag off (no UI calls them then). The near-auth relayer path uses the same validator but its deployed copy is unchanged. Discrepancy: `web/PRODUCT.md` says Today's Tide is coming soon and not playable; with the flag on it is playable (product docs not edited). Even (`first_light_v1`) days cannot be sailed from the current game. Icons generated with gpt-6-astra via Codex CLI; provenance in `web/public/assets/season/provenance.json`. | | 2026-11-14 | First live Season 2 day on testnet (day 20771, Beacon Court) | `bun --env-file=.env.tidebound scripts/season-live.ts` (faucet rate-limited, so root created `qa-season-mwfncbhi.familiar-game.testnet` with 0.3 NEAR): storage_deposit `H2JB6GcoiaHURYESUFqbbg6bkLAx8UzTm3AXDsZe6koE` 2.159 Tgas; claim_daily `BPH4quoUi5CnKmkwRoZZExCfs4mZ2zgMFUoKL8Lmayk5` 3.699 Tgas; sell glass `4KZnGDNJV7Hf6PP7MXfxUgqcdG25EYPnq22GM9XgXA5A`, sell reed `DVckVNtfN8cHACkCGCc5QaKJKxbCvyfU7Jw59rPFWecY`, buy reed `4XUZB8QnFvoKBzJMZqXWmGxsB9xzNTYbS2txLPiU9aMZ`, 2.536 Tgas each | The 17-step rope route minted 1 glass + 1 reed with score 10000 (value equals the best haul at docking prices); after two sales and one buy the account holds 5 Shells and 1 reed, matching the contract arithmetic. 100 Tgas prepaid needs about 0.1 NEAR of balance (a 0.1 NEAR account was refused), so the UI's trade gas was lowered to 30 Tgas. Earlier faucet runs also recorded storage `GLhCCAWEA5Nd7Q7m8iUaGsik4UVcbCv2wKs8pLXBZm8k`, claim `FfPPx4LpARtMzk7eXGGHKYvo4uFJpCrSy4aG9K6TKX79`, sell `59PzZGPQ8mJf11edrpfqK3gZkE8dRNcdWmvi2qr2TmYu`, then a script buy refused with ERR_SHELLS (3 Shells could not pay 4). No wish yet: the test account owns no pet. | | 2026-11-14 | Season 2 UI review fixes; rebased onto `main` (#3–#5); release build carries `VITE_SEASON2_ENABLED` | `bun run typecheck`; `bun run test` 289 pass/17104 assertions; `cargo test --workspace` 182 passed/0 failed/3 ignored; `make build`, `make browser`, `make evidence`, `make break` (now also `familiar-season`: 27 season `break_` tests) ok; `bun run test:season-browser` passed at 390×844 and 1440×900 on 14 Nov UTC (a Beacon Court day); `test:records-browser` passed (one earlier run exited 1 with every check printed as passed and no error; four reruns exited 0). `VERCEL_ENV=production PRIVY_APP_ID=localcheck bun --no-env-file scripts/build-release.ts` with `VITE_SEASON2_ENABLED=true` emits `SeasonBram-*.js` containing the season screens; without the flag, or with `yes`, no season chunk or season strings are in `.vercel/output/static/assets` | Second ledger deposit refused before sending (`get_account` read at final); refusals before sending show the controller's own words (`SeasonNotSent`); wish form hidden without Mochi; buttons stay focusable with `aria-disabled` and focus returns to the status line; the device preview rolls over each day like the contract. Release flag follows the sealed note: production only, Privy app present, exactly `true`. The lazy season import is now behind the flag, so builds without it leave the screens out. The key line's signer-action list names the six season calls. Not deployed; no Vercel env change; nothing signed. | +| 2026-11-14 | The Tidekeeper's ask and Bram's tide log, with Bram's shelf joined into the same daily loop (`VITE_SEASON2_ENABLED` removed), on local branch `feat/tidekeepers-ask`; not pushed or deployed | At `eb9ed0c`: `bun run typecheck`; `bun run test` 393 pass/0 fail/18157 assertions (HTTP tests included); `bun run build`; `bun run test:tide-browser` (412×860 and 1280×800, incl. Playwright-clock UTC-midnight rollover), `test:season-browser`, `test:expedition-harbor-browser`, `test:expedition-touch-browser`, `test:routing-browser`, `test:records-browser` all pass. At `956ffe0`: `bun --no-env-file run build:release` ships 22 `assets/tide` and 7 `assets/season` files; `cargo test --workspace` 182 passed/0 failed/3 ignored (contracts unchanged since); `make evidence` (15 verified); `make break` (27 season `break_` + 13 signer tests) | Chromium only for the new browser checks. `test:expedition-browser`, `test:expedition-qa-browser` and `test:expedition-lifecycle-browser` fail identically on clean `origin/main` (320×480 departure panel covers Workbench/Satchel). With the flag gone, opening Bram's dialog sends read-only `call_function` views to `test.rpc.fastnear.com` for signed-out players too, and signed-in shelf actions sign on testnet after a labelled storage deposit; there is no off switch short of a revert. The signed-in shelf was not exercised live this session. | +| 2026-11-14 | Visual pass toward the Pocket Harbor concept: painted UI art (gpt-6-astra: 4 place signs, 3 Mochi portraits, 12 ask icons; 8 title signpost pieces) and one interface system for the harbor, Home sheet, court, Bram's shelf and title, on local branch `feat/tidekeepers-ask` (`0fbefee`–`4bef31a`); not pushed or deployed | At `d15088a`: `bun run typecheck`; `bun run test` 414 pass/0 fail/18513 assertions; `bun --no-env-file run build:release` ships 21 `assets/ui` and 10 `assets/title` files; `test:season-browser`, `test:expedition-harbor-browser`, `test:routing-browser` (Chromium and WebKit), `test:records-browser` pass. At `4bef31a`: typecheck, `bun run test` 414 pass/0 fail, `test:tide-browser` (412×860, 390×844, 844×390, 1280×800, 1440×900) and `test:expedition-touch-browser` pass; `cargo test --workspace` 182 passed/0 failed/3 ignored (contracts unchanged). UI optimizer reruns byte-identical; 19 WebPs total 174,340 bytes | Running the suites caught two real bugs: Phaser hit-tested Mochi through the harbor card, so "Take it to Bram" also sat Mochi down and cancelled itself (scene presses now require `pointer.downElement` to be the canvas); and WebKit never focuses a clicked button, so closing a panel lost the opener (the last pressed button is remembered). Ask chips moved into the move tray on every size because portrait phones have no free band above the board. Not verified: real devices, Firefox, human playtest; the desktop signs stand as a cluster on the quay rather than beside each character; the landscape title hides the left rule beside "First Light". `test:expedition-browser`, `-qa-browser` and `-lifecycle-browser` were not rerun (they failed identically on `origin/main` before this pass) | +| 2026-11-14 | Tide run (`tide_run_v1`): three story tides (lens, vane, moth) and a daily tide scored against Bram's guess, on device harbors only, on local branch `feat/tide-run` (off `a4dc430`); the lit harbor keeps the Tidekeeper's ask as its main button; signed-in harbors and the season contract are unchanged; painted pearl and Signal Vane (gpt-6-astra, provenance in `web/public/assets/run/provenance.json`); not pushed or deployed | At `2e31e1b`: `bun run typecheck`; `bun run test` 439 pass/0 fail/39864 assertions; `bun run build`; `bun run test:tide-run-browser` (Chromium 390×844, reduced motion: three story tides, reload on the end card, failed-save retries, leave and resume, today's tide), `test:routing-browser` (Chromium and WebKit), `test:tide-browser`, `test:season-browser`, `test:expedition-harbor-browser`, `test:expedition-touch-browser`, `test:records-browser` all pass. `cargo test --workspace` 182 passed/0 failed/3 ignored at `70b5d6f`; no file under `contracts/` differs from `a4dc430`. `test:tide-browser` failed “the phone tray clears the complete dock platform” once at `70b5d6f` (a cargo build ran alongside) and once at `2e31e1b` (other headless browsers ran alongside); it passed both times when re-run alone. `test:expedition-browser`, `test:expedition-lifecycle-browser`, `test:expedition-qa-browser` and `test:passage-browser` fail, with the same errors at `a4dc430`. A gpt-6.1 sol review found three defects (a finished tide lost on reload, a silent failed save, reduced motion ignored mid-move); all three are fixed in `04bc998`. Played through by script at 1280×800, 390×844 and 844×390 with no page errors. At 844×390 the dock row was clipped and the DOCK label covered Mochi; `2e31e1b` (gpt-6-astra layout pass) fixes that and fits the daily end card without scrolling, checked in Chromium screenshots. The tide run is played and saved on the device only: no contract referees it and nothing from it reaches Bram's shelf or a token. | ## Recorded discrepancies (NEAR AI, 2026-11-13) @@ -31,3 +34,4 @@ Full earlier progress and acceptance records are preserved in the [archive](docs - **Signature URL.** The skill shows `/v1/signature/{id}?model=…&signing_algo=…`; the SDK and Familiar omit `model`, and the signature was found on the first try. - **Model tier.** `/v1/models` has no explicit tier field (`owned_by:"nearai"`). The SDK's attestation criterion (`/v1/model/{id}`: `providerType:"vllm"`, `attestationSupported:true`) is what Familiar checks. - **Brief vs repository.** The handoff said `.env.example` already had a `NEAR_AI_API_KEY` placeholder; it did not. The placeholder was added (empty). +| 2026-11-14 | One tide: the tide run and the Tidekeeper's ask as one game, on local branch `feat/one-tide` (merges `feat/one-tide-ui` `e7b29fe` into familiar-bb's `f5643c5`). On device harbors the daily is the tide run: Today's tide shows the day's card, Bram's guess and three stamps (home, guess, dry); the Home sheet celebrates the result; the tide log keeps run pages beside old three-ask pages; Bram's shelf offers today's reed and glass, up to 3 each, and pearls stay with Mochi. Signed-in harbors keep the three-ask court. Not pushed or deployed | At `f67d9fe`: `bun run typecheck`; `bun run test` 485 pass/0 fail/40232 assertions; `bun --no-env-file run build:release`; `cargo test --manifest-path contracts/Cargo.toml --workspace`; `test:tide-browser` (390×844, 412×860, 844×390, 1280×800, 1440×900), `test:tide-run-browser`, `test:season-browser`, `test:expedition-harbor-browser`, `test:expedition-touch-browser`, `test:routing-browser`, `test:records-browser` all pass. `test:expedition-browser` (320 harbor brand clickable) and `test:expedition-qa-browser` (home controls obscured at 9 sizes, 667×375 court) fail with the same messages at the base `57d8565`. At `b95ae9d`, `test:expedition-lifecycle-browser` reaches the court through the Chart and then fails at the same "Familiar home" obscured assertion as the base. Chromium screenshots from a fresh harbor through chapter one, the lit harbor, today's tide, the Home sheet, the log, Bram's shelf and the harbor after at 390×844, 844×390 and 1280×800, with no page errors. Browser emulation only: no real device, no human playtest, signed-in shelf not exercised | diff --git a/README.md b/README.md index 9e3797e..2f3f9b8 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # Familiar -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. +![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. ## Run @@ -39,6 +41,9 @@ Live stack: root `familiar-game.testnet`, items `items.familiar-game.testnet`. ` ## Source - `web/src/expedition/`: rules, Phaser presentation, Mochi, sound and harbor. +- `web/src/run/`: the tide run (`tide_run_v1`): rules, Bram's guess, the story chapters and the device tide book. +- `web/src/tide/`: Today's tide, the Home sheet, Bram's tide log and the Tidekeeper's three-ask court with its solver. +- `web/src/season/`: Bram's shelf, till and Mochi's wish over the testnet `season` contract. - `web/src/account/`, `web/src/tidebound/`: recoverable identity, original transactions and item provenance. - `web/src/compatibility/`: frozen historical return validation. - `contracts/`, `services/relayer/`: Rust testnet contracts and account HTTP service. diff --git a/docs/readme-banner.jpg b/docs/readme-banner.jpg new file mode 100644 index 0000000..5ede34d Binary files /dev/null and b/docs/readme-banner.jpg differ diff --git a/docs/readme-banner.provenance.json b/docs/readme-banner.provenance.json new file mode 100644 index 0000000..9d0c3d9 --- /dev/null +++ b/docs/readme-banner.provenance.json @@ -0,0 +1,43 @@ +{ + "created": "2026-11-14", + "purpose": "README banner for Familiar", + "file": "docs/readme-banner.jpg", + "art": { + "generator": { + "tool": "Codex CLI (`codex exec`, image_gen.imagegen built-in tool)", + "model": "gpt-6-astra", + "reasoningEffort": "ultra", + "cliVersion": "0.169.0", + "session": "01a1d8c7-7ebb-71d3-812b-71c645b3d08e", + "note": "The image tool does not expose its backend model or a quality setting; model and effort above are the orchestrating Codex model." + }, + "prompt": "Create one premium illustration-story key-art photograph of a handmade felt miniature set for Familiar. Highest available image quality and resolution. COMPOSITION A, wide establishing view.\n\nOUTPUT AN UNCROPPED LANDSCAPE MASTER IN 3:2 ASPECT RATIO. The final 2.5:1 banner will be cut from the CENTRAL 60% of this master afterwards. DO NOT generate an already-cropped 2.5:1 banner. Use the largest supported 3:2 landscape size. This mathematically preserves the requested crop.\n\nCRITICAL FRAMING: Imagine a thin horizontal miniature theatre set across ONLY the RIGHT 60% and MIDDLE HALF of the image. Every story element is wholly contained in the rectangle x=40–97%, y=26–74%. EVERYTHING ABOVE y=20% is ONLY open pink/violet sky or soft dark leaves; no roof, lighthouse cap, moth or animal goes there. EVERYTHING BELOW y=80% is ONLY empty turquoise water, soft stones or foreground flowers; no feet, claws or bridge goes there. The entire LEFT 36% is extremely calm, almost uniformly dark forest-green foliage with barely perceptible out-of-focus leaves; no lit edges, characters, wave or water reflections anywhere in this title area. A few muted pink hydrangeas at its very bottom edge. Transition from dark foliage to scene happens around x=38%. Do not fill the blank space with anything.\n\nFive references: 1 establishes the Familiar harbor miniature style, warm sunset, cottage and lighthouse designs; IGNORE AND OMIT ALL SOURCE LETTERING. 2 is Mochi; 3 is Bram; 4 is Tidekeeper; 5 is the wind-moth. Match their designs and physical material exactly.\n\nThe story takes place on the right, in shallow turquoise tide-court water beneath a golden-hour pink/violet sky. One round orange felt tabby kitten Mochi hops happily RIGHTWARD between two flat round spiral-carved sandstone footholds toward a small rope bridge. Mochi occupies x=53–65%, y=43–68%, including her entire raised tail and ears and all paws. She has the same round large head and short round body as reference 2, cream muzzle/chest/paws and tail tip, dark bead eyes, orange forehead stripes, a red tied bandana, small stitched brown satchel. A small brass lens peeks out of the satchel. She is visibly airborne above the gap, brave and delighted. Exactly one tiny softly glowing cream/gold wind-moth flutters just ahead at x=67%, y=43%, with fine four-wing golden spiral veins and feathery antennae matching reference 5. Keep it genuinely small compared to Mochi.\n\nBeside the stepping stones at x=76%, y=60%, ONE Tidekeeper is half out of the water, one stone claw raised a little, kindly watching Mochi. Match reference 4 exactly: broad low crab shape, grey rounded porous stone carapace, cream carved spiral relief, warm amber eyes, pink coral and olive-green kelp on its back, chunky rounded rock claws. Entire crab INCLUDING coral is within x=69–84%, y=48–73%. Friendly old guardian, no threat.\n\nExactly ONE modest curling teal sea-glass wave behind Mochi, wholly within x=42–52%, y=49–66%, with soft white wool foam. No part of wave enters x<40%. Two or three low flat sandstone circular footholds have broad raised spiral tops and warm rounded block edges. They sit wholly between y=65–74%, not tall pillars.\n\nA SMALL wooden rope bridge connects the stones to the sandstone quay on the far right, all between x=83–98%, y=59–73%. Its shape matches a real miniature plank bridge: warm wood, chunky cylindrical posts, thick cream rope rails.\nOn the quay stands exactly ONE Bram, small but readable, x=89%, y=50–64%, waving one paw: stocky grey/cream badger, pale center stripe, round brass wire glasses, rust jumper, cream flour-dusted apron, brown boots, same as reference 3.\nBehind him a small cozy sandstone cottage with terracotta roof and striped pink/cream awning, its ENTIRE roof and chimney below y=30%, footprint x=88–98%, y=32–58%.\nIn the distant harbor at x=80%, exactly ONE lighthouse on a rock, FULL tower INCLUDING red cap contained y=29–49%, miniature cream stone, red base and cap, tiny lit lantern. A restrained warm beam shines across water and into sky WITHIN the middle band. A few small distant sandstone coral arches suggest the tide court, safely within middle band.\n\nPhotograph an actual handcrafted stop-motion miniature: needle-felted wool with visible individual fine fibers on animals, hand stitching, soft chunky rounded shapes, felt leaves, real wood, gently glinting dull brass, porous sandstone, teal glass water/wave with wool foam. Reference-exact orange cat and grey badger colors and proportions. Soft warm low sunlight with long gentle shadows. Crisp characters, slightly soft foreground flowers/stones, gently hazy distant harbor. Beautiful rich turquoise, warm peach/gold and pink/violet against a deep dark green title area. No shiny plastic fur, no glossy CGI character rendering, no flat vector.\nEXACT COUNTS: one Mochi, one Bram, one Tidekeeper, one moth, one lighthouse, one wave. No extra animals, people or birds. NO text, letters, numbers, pseudo-writing, logos, signatures, watermark, UI, border or frame. Keep all important objects comfortably within the middle 60% and all action to the right of 40%.", + "attempts": 3, + "selectedAttempt": 2, + "original": { + "pixelSize": [ + 1536, + 1024 + ], + "sha256": "3b2f0dc52178fda4656af7bf379ce9734533d30edd83caacd3bc95d169673a34", + "bytes": 2176650 + }, + "styleReferences": "Existing Familiar game art (Mochi, Bram, the Tidekeeper, the harbor backdrops); at most five per generation." + }, + "composition": { + "method": "The art has no text. The wordmark and lines are live type (Fraunces and Figtree, the game's own fonts) over a left-hand shade, rendered at 1000x400 CSS px, device scale 2, with Playwright Chromium, then saved as JPEG quality 90.", + "text": [ + "familiar.", + "A little adventure with Mochi.", + "Read the tide. Bring wonder home." + ], + "output": { + "pixelSize": [ + 2000, + 800 + ], + "sha256": "3ab115d304ba65f912773c2fdd0a2b474b2ecef691b8d8419d5f8b90a2b602d1", + "bytes": 403271 + } + } +} \ No newline at end of file diff --git a/package.json b/package.json index 5206188..7608bf9 100644 --- a/package.json +++ b/package.json @@ -35,7 +35,9 @@ "package:tidebound-review": "bun --env-file=.env.privy.local scripts/package-tidebound-review.ts", "test:routing-browser": "bun scripts/test-routing-browser.ts", "test:records-browser": "bun scripts/test-records-browser.ts", - "test:season-browser": "bun scripts/test-season-browser.ts" + "test:season-browser": "bun scripts/test-season-browser.ts", + "test:tide-browser": "bun scripts/test-tide-browser.ts", + "test:tide-run-browser": "bun scripts/test-tide-run-browser.ts" }, "dependencies": { "@fontsource-variable/figtree": "5.3.0", diff --git a/scripts/build-release.test.ts b/scripts/build-release.test.ts index ba6f1f2..641de6d 100644 --- a/scripts/build-release.test.ts +++ b/scripts/build-release.test.ts @@ -6,19 +6,15 @@ import { releaseSettings } from "./build-release"; import { buildAccountFunction,currentRouting,HTTP_PATHS } from "./package-tidebound-review"; test("only production builds receive explicitly allowlisted public account settings",()=>{ - expect(releaseSettings({})).toEqual({appId:"",clientId:"",sealedNote:false,records:false,season:false}); - expect(releaseSettings({VERCEL_ENV:"preview",PRIVY_APP_ID:"prod-app",VITE_PRIVY_CLIENT_ID:"prod-client",VITE_SEALED_NOTE_ENABLED:"true"})).toEqual({appId:"",clientId:"",sealedNote:false,records:false,season:false}); - expect(releaseSettings({VERCEL_ENV:"production",PRIVY_APP_ID:"existing-app"})).toEqual({appId:"existing-app",clientId:"",sealedNote:false,records:false,season:false}); + expect(releaseSettings({})).toEqual({appId:"",clientId:"",sealedNote:false,records:false}); + expect(releaseSettings({VERCEL_ENV:"preview",PRIVY_APP_ID:"prod-app",VITE_PRIVY_CLIENT_ID:"prod-client",VITE_SEALED_NOTE_ENABLED:"true"})).toEqual({appId:"",clientId:"",sealedNote:false,records:false}); + expect(releaseSettings({VERCEL_ENV:"production",PRIVY_APP_ID:"existing-app"})).toEqual({appId:"existing-app",clientId:"",sealedNote:false,records:false}); expect(releaseSettings({VERCEL_ENV:"production",PRIVY_APP_ID:"existing-app",VITE_SEALED_NOTE_ENABLED:"1"}).sealedNote).toBe(false); expect(releaseSettings({VERCEL_ENV:"production",PRIVY_APP_ID:"existing-app",VITE_SEALED_NOTE_ENABLED:"true"}).sealedNote).toBe(true); expect(releaseSettings({VERCEL_ENV:"production",PRIVY_APP_ID:"existing-app",VITE_RECORDS_ENABLED:"true"}).records).toBe(true); expect(releaseSettings({VERCEL_ENV:"production",PRIVY_APP_ID:"existing-app",VITE_RECORDS_ENABLED:"yes"}).records).toBe(false); expect(releaseSettings({VERCEL_ENV:"preview",PRIVY_APP_ID:"existing-app",VITE_RECORDS_ENABLED:"true"}).records).toBe(false); - expect(releaseSettings({VERCEL_ENV:"production",PRIVY_APP_ID:"existing-app",VITE_SEASON2_ENABLED:"true"}).season).toBe(true); - for(const flag of ["1","TRUE","yes",""," true"])expect(releaseSettings({VERCEL_ENV:"production",PRIVY_APP_ID:"existing-app",VITE_SEASON2_ENABLED:flag}).season).toBe(false); - expect(releaseSettings({VERCEL_ENV:"preview",PRIVY_APP_ID:"existing-app",VITE_SEASON2_ENABLED:"true"}).season).toBe(false); - expect(()=>releaseSettings({VERCEL_ENV:"production",VITE_SEASON2_ENABLED:"true"})).toThrow(); - expect(releaseSettings({VERCEL_ENV:"production",VITE_PRIVY_APP_ID:"public-app",PRIVY_APP_ID:"fallback",VITE_PRIVY_CLIENT_ID:"public-client"})).toEqual({appId:"public-app",clientId:"public-client",sealedNote:false,records:false,season:false}); + expect(releaseSettings({VERCEL_ENV:"production",VITE_PRIVY_APP_ID:"public-app",PRIVY_APP_ID:"fallback",VITE_PRIVY_CLIENT_ID:"public-client"})).toEqual({appId:"public-app",clientId:"public-client",sealedNote:false,records:false}); for(const id of ["","invalid id", "a".repeat(129)]) expect(()=>releaseSettings({VERCEL_ENV:"production",PRIVY_APP_ID:id})).toThrow(); expect(()=>releaseSettings({VERCEL_ENV:"production",PRIVY_APP_SECRET:"never-an-app-id"})).toThrow(); diff --git a/scripts/build-release.ts b/scripts/build-release.ts index 400d837..a5fdd11 100644 --- a/scripts/build-release.ts +++ b/scripts/build-release.ts @@ -3,13 +3,13 @@ import { join,resolve } from "node:path"; import { buildAccountFunction,buildGameSite,currentRouting } from "./package-tidebound-review"; export function releaseSettings(env:Record){ - if(env.VERCEL_ENV!=="production")return {appId:"",clientId:"",sealedNote:false,records:false,season:false}; + if(env.VERCEL_ENV!=="production")return {appId:"",clientId:"",sealedNote:false,records:false}; const appId=env.VITE_PRIVY_APP_ID??env.PRIVY_APP_ID??"",clientId=env.VITE_PRIVY_CLIENT_ID??""; const id=/^[A-Za-z0-9_-]{1,128}$/; if(!id.test(appId)||(clientId&&!id.test(clientId)))throw Error("Production requires a valid public Privy app ID and, if supplied, a valid public client ID."); // Mochi's sealed note needs the account endpoints, so it is off unless production explicitly opts in. - // Harbor records read public chain state for a signed-in player; Season 2 signs season calls. Both are explicit opt-ins. - return {appId,clientId,sealedNote:env.VITE_SEALED_NOTE_ENABLED==="true",records:env.VITE_RECORDS_ENABLED==="true",season:env.VITE_SEASON2_ENABLED==="true"}; + // Harbor records read public chain state for a signed-in player and remain an explicit opt-in. + return {appId,clientId,sealedNote:env.VITE_SEALED_NOTE_ENABLED==="true",records:env.VITE_RECORDS_ENABLED==="true"}; } export async function buildRelease(source:string,settings:ReturnType){ @@ -20,7 +20,7 @@ export async function buildRelease(source:string,settings:ReturnType createHash("sha256").update(bytes).digest("hex"); +const files = []; +await mkdir(target, { recursive: true }); +for (const name of ["pearl", "vane"]) { + const source = `assets/source/run/${name}.png`, output = `assets/run/${name}.webp`; + const before = await Bun.file(join(web, source)).bytes(); + const scaled = Bun.spawnSync(["magick", join(web, source), "-trim", "+repage", "-resize", "168x168", "-gravity", "center", "-background", "none", "-extent", "192x192", "png:-"]); + assert.equal(scaled.exitCode, 0, scaled.stderr.toString()); + const temporary = join(target, `.${name}.png`); + await Bun.write(temporary, scaled.stdout); + try { + const encoded = Bun.spawnSync(["cwebp", "-quiet", "-q", "85", "-m", "6", "-alpha_q", "100", temporary, "-o", join(web, "public", output)]); + assert.equal(encoded.exitCode, 0, encoded.stderr.toString()); + } finally { await rm(temporary, { force: true }); } + const after = await Bun.file(join(web, "public", output)).bytes(); + assert(after.length < before.length, `${name}: optimized derivative must be smaller`); + assert.equal(hash(await Bun.file(join(web, source)).bytes()), hash(before), "Master must remain byte-identical"); + const alpha = Bun.spawnSync(["magick", join(web, "public", output), "-format", "%[opaque] %[fx:p{0,0}.a] %[fx:mean.a]", "info:"]); + assert.equal(alpha.exitCode, 0, alpha.stderr.toString()); + const [opaque, corner, coverage] = alpha.stdout.toString().trim().split(" "); + assert.equal(opaque?.toLowerCase(), "false", `${name}: real alpha required`); + assert.equal(Number(corner), 0, `${name}: transparent corner required`); + assert(Number(coverage) > .1 && Number(coverage) < .8, `${name}: visible object with clear margins required`); + files.push({ source, output, sourceSha256: hash(before), sha256: hash(after), sourceBytes: before.length, bytes: after.length, width: 192, height: 192 }); +} +const report = { purpose: "Tide-run prize derivatives; generated transparent alpha preserved", encoder: "ImageMagick trim, fit168 in transparent192; cwebp quality85 method6 alpha100", files }; +await Bun.write(join(target, "manifest.json"), JSON.stringify(report, null, 2) + "\n"); +console.log(JSON.stringify(report, null, 2)); diff --git a/scripts/optimize-tide-assets.ts b/scripts/optimize-tide-assets.ts new file mode 100644 index 0000000..432132f --- /dev/null +++ b/scripts/optimize-tide-assets.ts @@ -0,0 +1,69 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, readdir, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { TIDE_POOL } from "../web/src/tide/cards"; + +// Offline regeneration; builds use these derivatives and leave the PNG masters untouched. +const webRoot = resolve(import.meta.dir, "../web"); +const sourceRoot = join(webRoot, "assets/source/tide"), target = join(webRoot, "public/assets/tide"); +type Rule = { resize: string; fuzz?: number; erode?: number; center?: boolean; trim?: boolean }; +const rules: Record = Object.fromEntries(TIDE_POOL.map(({ id }) => [`card-${id}`, { resize: "480x480" }])); +Object.assign(rules, { + "keeper-ask": { resize: "960x", fuzz: 6, erode: 2 }, + "log-cover": { resize: "384x384", fuzz: 6, erode: 2 }, + "seal-kept": { resize: "168x168", fuzz: 10, erode: 2 }, + "seal-all-three": { resize: "168x168", fuzz: 10, erode: 2 }, + "seal-slipped": { resize: "168x168", fuzz: 10, erode: 2, center: true }, + "log-page": { resize: "900x", fuzz: 12, erode: 3, trim: true }, +}); +const names = (await readdir(sourceRoot)).filter(name => name.endsWith(".png")).map(name => name.slice(0, -4)).sort(); +for (const name of names) assert(Object.hasOwn(rules, name), `Unknown tide master: ${name}.png`); +const hash = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex"); +function run(command: string[]) { + const result = Bun.spawnSync(command); + assert.equal(result.exitCode, 0, `${command[0]} failed: ${result.stderr.toString()}`); + return result.stdout.toString().trim(); +} +function pixelSize(path: string) { + const [width, height] = run(["magick", "identify", "-format", "%w %h", path]).split(" ").map(Number); + assert(Number.isInteger(width) && width > 0 && Number.isInteger(height) && height > 0, `Invalid image size: ${path}`); + return { width, height }; +} + +await mkdir(target, { recursive: true }); +const work = await mkdtemp(join(tmpdir(), "tide-art-")), files = []; +try { + for (const name of names) { + const master = join(sourceRoot, name + ".png"), cut = join(work, name + ".png"), output = join(target, name + ".webp"); + const before = await Bun.file(master).bytes(), rule = rules[name]; + try { + const treatment: string[] = []; + if (rule.fuzz) { + const { width, height } = pixelSize(master); + const seeds = [[0, 0], [width - 1, 0], [0, height - 1], [width - 1, height - 1]]; + if (rule.center) seeds.push([Math.floor(width / 2), Math.floor(height / 2)]); + treatment.push("-alpha", "set", "-fuzz", `${rule.fuzz}%`, "-fill", "none", + ...seeds.flatMap(([x, y]) => ["-draw", `alpha ${x} ${y} floodfill`]), + "-channel", "A", "-morphology", "Erode", `Disk:${rule.erode}`, "-blur", "0x1", "+channel"); + if (rule.trim) treatment.push("-trim", "+repage"); + } else treatment.push("-alpha", "off"); + run(["magick", master, ...treatment, "-filter", "Lanczos", "-resize", rule.resize, cut]); + run(["cwebp", "-quiet", "-q", "88", "-m", "6", "-alpha_q", "100", "-sharp_yuv", + ...(!rule.fuzz ? ["-noalpha"] : []), cut, "-o", output]); + const after = await Bun.file(output).bytes(); + files.push({ source: `assets/source/tide/${name}.png`, output: `assets/tide/${name}.webp`, + sourceSha256: hash(before), sha256: hash(after), sourceBytes: before.length, bytes: after.length, + resizedTo: pixelSize(output) }); + } finally { + assert.equal(hash(await Bun.file(master).bytes()), hash(before), `Master must stay byte-identical: ${name}.png`); + } + } + const report = { purpose: "Tide runtime artwork; opaque card pictures and alpha cut-outs with original masters preserved", + encoder: "magick Lanczos + cwebp quality88 method6 alpha100 sharp_yuv", files }; + await Bun.write(join(target, "manifest.json"), JSON.stringify(report, null, 2) + "\n"); + console.log(JSON.stringify(report, null, 2)); +} finally { + await rm(work, { recursive: true, force: true }); +} diff --git a/scripts/optimize-title-assets.ts b/scripts/optimize-title-assets.ts new file mode 100644 index 0000000..5ec3d27 --- /dev/null +++ b/scripts/optimize-title-assets.ts @@ -0,0 +1,65 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, readdir, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; + +// Offline regeneration; builds use these derivatives and leave the PNG masters untouched. +const webRoot = resolve(import.meta.dir, "../web"); +const sourceRoot = join(webRoot, "assets/source/title"), target = join(webRoot, "public/assets/title"); +type Rule = { resize: string; fuzz: number; erode: number }; +const rules: Record = { + "title-plank-1": { resize: "720x", fuzz: 8, erode: 2 }, + "title-plank-2": { resize: "720x", fuzz: 8, erode: 2 }, + "title-plank-3": { resize: "720x", fuzz: 8, erode: 2 }, + "title-plank-4": { resize: "720x", fuzz: 8, erode: 2 }, + "title-post": { resize: "x1240", fuzz: 8, erode: 2 }, + "title-bell": { resize: "x330", fuzz: 8, erode: 2 }, + "title-tag": { resize: "260x", fuzz: 8, erode: 2 }, + "title-paper": { resize: "780x", fuzz: 8, erode: 2 }, +}; +const names = (await readdir(sourceRoot)).filter(name => name.endsWith(".png")).map(name => name.slice(0, -4)).sort(); +assert.deepEqual(names, Object.keys(rules).sort(), "Title masters must match the eight runtime assets"); +const hash = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex"); +function run(command: string[]) { + const result = Bun.spawnSync(command); + assert.equal(result.exitCode, 0, `${command[0]} failed: ${result.stderr.toString()}`); + return result.stdout.toString().trim(); +} +function pixelSize(path: string) { + const [width, height] = run(["magick", "identify", "-format", "%w %h", path]).split(" ").map(Number); + assert(Number.isInteger(width) && width > 0 && Number.isInteger(height) && height > 0, `Invalid image size: ${path}`); + return { width, height }; +} + +await mkdir(target, { recursive: true }); +const work = await mkdtemp(join(tmpdir(), "title-art-")), files = []; +try { + for (const name of names) { + const master = join(sourceRoot, name + ".png"), cut = join(work, name + ".png"), output = join(target, name + ".webp"); + const before = await Bun.file(master).bytes(), rule = rules[name]; + try { + const { width, height } = pixelSize(master); + const seeds = [[0, 0], [width - 1, 0], [0, height - 1], [width - 1, height - 1]]; + run(["magick", master, "-alpha", "set", "-fuzz", `${rule.fuzz}%`, "-fill", "none", + ...seeds.flatMap(([x, y]) => ["-draw", `alpha ${x} ${y} floodfill`]), + "-channel", "A", "-morphology", "Erode", `Disk:${rule.erode}`, "-blur", "0x1", "+channel", + "-trim", "+repage", "-filter", "Lanczos", "-resize", rule.resize, cut]); + run(["cwebp", "-quiet", "-q", "88", "-m", "6", "-alpha_q", "100", "-sharp_yuv", cut, "-o", output]); + const after = await Bun.file(output).bytes(); + assert.equal(run(["magick", output, "-format", "%[opaque]", "info:"]).toLowerCase(), "false", `Title asset must have alpha: ${name}`); + const resizedTo = pixelSize(output), expected = Number(rule.resize.replace("x", "")); + assert.equal(rule.resize.startsWith("x") ? resizedTo.height : resizedTo.width, expected, `Unexpected runtime size: ${name}`); + files.push({ source: `assets/source/title/${name}.png`, output: `assets/title/${name}.webp`, + sourceSha256: hash(before), sha256: hash(after), sourceBytes: before.length, bytes: after.length, resizedTo }); + } finally { + assert.equal(hash(await Bun.file(master).bytes()), hash(before), `Master must stay byte-identical: ${name}.png`); + } + } + const report = { purpose: "Title signpost runtime artwork; trimmed alpha cut-outs with original masters preserved", + encoder: "magick corner floodfill alpha erode2 blur0x1 trim Lanczos + cwebp quality88 method6 alpha100 sharp_yuv", files }; + await Bun.write(join(target, "manifest.json"), JSON.stringify(report, null, 2) + "\n"); + console.log(JSON.stringify(report, null, 2)); +} finally { + await rm(work, { recursive: true, force: true }); +} diff --git a/scripts/optimize-ui-assets.ts b/scripts/optimize-ui-assets.ts new file mode 100644 index 0000000..2b15391 --- /dev/null +++ b/scripts/optimize-ui-assets.ts @@ -0,0 +1,101 @@ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { mkdir, mkdtemp, readdir, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; + +// Offline regeneration; builds use these derivatives and leave the PNG masters untouched. +const webRoot = resolve(import.meta.dir, "../web"); +const sourceRoot = join(webRoot, "assets/source/ui"), target = join(webRoot, "public/assets/ui"); +type Rule = { family: "sign" | "portrait" | "ask"; fuzz: number; erode: number }; +const rules: Record = { + "sign-beacon": { family: "sign", fuzz: 4, erode: 1 }, + "sign-bram": { family: "sign", fuzz: 4, erode: 1 }, + "sign-workbench": { family: "sign", fuzz: 4, erode: 1 }, + "sign-satchel": { family: "sign", fuzz: 4, erode: 1 }, + "mochi-portrait": { family: "portrait", fuzz: 4, erode: 1 }, + "mochi-portrait-splashed": { family: "portrait", fuzz: 4, erode: 1 }, + "mochi-portrait-proud": { family: "portrait", fuzz: 4, erode: 1 }, + "ask-lens": { family: "ask", fuzz: 8, erode: 1 }, + "ask-moth": { family: "ask", fuzz: 8, erode: 1 }, + "ask-dry": { family: "ask", fuzz: 8, erode: 1 }, + "ask-splash": { family: "ask", fuzz: 8, erode: 1 }, + "ask-coiled": { family: "ask", fuzz: 8, erode: 1 }, + "ask-no-wait": { family: "ask", fuzz: 8, erode: 1 }, + "ask-all-marks": { family: "ask", fuzz: 8, erode: 1 }, + "ask-one-crossing": { family: "ask", fuzz: 8, erode: 1 }, + "ask-both-shells": { family: "ask", fuzz: 8, erode: 1 }, + "ask-bridge": { family: "ask", fuzz: 8, erode: 1 }, + "ask-shut-shell": { family: "ask", fuzz: 8, erode: 1 }, + "ask-within": { family: "ask", fuzz: 8, erode: 1 }, +}; +const names = (await readdir(sourceRoot)).filter(name => name.endsWith(".png")).map(name => name.slice(0, -4)).sort(); +assert.deepEqual(names, Object.keys(rules).sort(), "UI masters must match the nineteen runtime assets"); +const hash = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex"); +function run(command: string[]) { + const result = Bun.spawnSync(command); + assert.equal(result.exitCode, 0, `${command[0]} failed: ${result.stderr.toString()}`); + return result.stdout.toString().trim(); +} +function pixelSize(path: string) { + const [width, height] = run(["magick", "identify", "-format", "%w %h", path]).split(" ").map(Number); + assert(Number.isInteger(width) && width > 0 && Number.isInteger(height) && height > 0, `Invalid image size: ${path}`); + return { width, height }; +} +function alphaBounds(path: string) { + const bounds = run(["magick", path, "-alpha", "extract", "-threshold", "0", "-format", "%@", "info:"]); + const match = /^(\d+)x(\d+)\+(\d+)\+(\d+)$/.exec(bounds); + assert(match, `Invalid alpha bounds: ${path}: ${bounds}`); + const [, width, height, x, y] = match.map(Number); + assert(width > 0 && height > 0, `Empty cut-out: ${path}`); + return { x, y, width, height }; +} + +await mkdir(target, { recursive: true }); +const work = await mkdtemp(join(tmpdir(), "ui-art-")), files = []; +const originals = new Map(await Promise.all(names.map(async name => [name, await Bun.file(join(sourceRoot, name + ".png")).bytes()] as const))); +try { + for (const name of names) { + const master = join(sourceRoot, name + ".png"), rule = rules[name]; + const { width, height } = pixelSize(master); + assert.deepEqual({ width, height }, rule.family === "sign" ? { width: 1536, height: 1024 } : { width: 1254, height: 1254 }, `Unexpected master size: ${name}`); + const seeds = [[0, 0], [width - 1, 0], [0, height - 1], [width - 1, height - 1]]; + run(["magick", master, "-alpha", "set", "-fuzz", `${rule.fuzz}%`, "-fill", "none", + ...seeds.flatMap(([x, y]) => ["-draw", `alpha ${x} ${y} floodfill`]), + "-channel", "A", "-morphology", "Erode", `Disk:${rule.erode}`, "-blur", "0x1", "+channel", join(work, name + ".png")]); + } + const portraits = names.filter(name => rules[name].family === "portrait").map(name => alphaBounds(join(work, name + ".png"))); + const x = Math.min(...portraits.map(box => box.x)), y = Math.min(...portraits.map(box => box.y)); + const sharedPortraitCrop = { x, y, width: Math.max(...portraits.map(box => box.x + box.width)) - x, height: Math.max(...portraits.map(box => box.y + box.height)) - y }; + assert(sharedPortraitCrop.width <= 1254 && sharedPortraitCrop.height <= 1254, "Portrait crop must fit the masters"); + for (const name of names) { + const rule = rules[name], cut = join(work, name + ".png"), resized = join(work, name + "-runtime.png"), output = join(target, name + ".webp"); + const crop = sharedPortraitCrop; + const framing = rule.family === "portrait" ? ["-crop", `${crop.width}x${crop.height}+${crop.x}+${crop.y}`, "+repage"] : ["-trim", "+repage"]; + const sizing = rule.family === "sign" ? ["-resize", "480x"] : ["-resize", rule.family === "portrait" ? "256x256" : "84x84", "-background", "none", "-gravity", "center", "-extent", rule.family === "portrait" ? "256x256" : "96x96"]; + run(["magick", cut, ...framing, "-filter", "Lanczos", ...sizing, resized]); + run(["cwebp", "-quiet", "-q", "88", "-m", "6", "-alpha_q", "100", "-sharp_yuv", resized, "-o", output]); + const before = originals.get(name)!, after = await Bun.file(output).bytes(), resizedTo = pixelSize(output); + assert.equal(run(["magick", output, "-format", "%[opaque]", "info:"]).toLowerCase(), "false", `UI asset must have alpha: ${name}`); + if (rule.family === "sign") assert.equal(resizedTo.width, 480, `Unexpected sign width: ${name}`); + else assert.deepEqual(resizedTo, rule.family === "portrait" ? { width: 256, height: 256 } : { width: 96, height: 96 }, `Unexpected runtime size: ${name}`); + if (rule.family === "ask") { + const bounds = alphaBounds(output); + assert.equal(Math.max(bounds.width, bounds.height), 84, `Ask must have a common visual size: ${name}`); + assert(bounds.x >= 6 && bounds.y >= 6 && bounds.x + bounds.width <= 90 && bounds.y + bounds.height <= 90, `Ask must have six-pixel minimum margins: ${name}`); + } + files.push({ source: `assets/source/ui/${name}.png`, output: `assets/ui/${name}.webp`, + sourceSha256: hash(before), sha256: hash(after), sourceBytes: before.length, bytes: after.length, resizedTo, ...rule }); + } + const report = { purpose: "Painted UI runtime artwork; transparent cut-outs with original masters preserved", + encoder: "magick four-corner floodfill per-asset fuzz/erode blur0x1 Lanczos + cwebp quality88 method6 alpha100 sharp_yuv", + sharedPortraitCrop, askContentSize: 84, askMargin: 6, files }; + await Bun.write(join(target, "manifest.json"), JSON.stringify(report, null, 2) + "\n"); + console.log(JSON.stringify(report, null, 2)); +} finally { + try { + for (const [name, before] of originals) assert.equal(hash(await Bun.file(join(sourceRoot, name + ".png")).bytes()), hash(before), `Master must stay byte-identical: ${name}.png`); + } finally { + await rm(work, { recursive: true, force: true }); + } +} diff --git a/scripts/package-tidebound-review.test.ts b/scripts/package-tidebound-review.test.ts index 3aa73aa..f4e2ca5 100644 --- a/scripts/package-tidebound-review.test.ts +++ b/scripts/package-tidebound-review.test.ts @@ -93,14 +93,20 @@ async function runtimeFixture() { for(const path of [...RUNTIME_WEBPS,...RUNTIME_METADATA,...BRAND_ASSETS]){await mkdir(dirname(join(source,path)),{recursive:true});await writeFile(join(source,path),/\.(?:json|webmanifest)$/.test(path)?'{}':`committed bytes for ${path}`);} return {...f,source}; } -test("the public package ships the optimized sprites while their full-size inputs stay in source",()=>{ - expect(RUNTIME_WEBPS).toHaveLength(19); +test("the public package ships the optimized sprites while their full-size inputs stay in source",async()=>{ + expect(RUNTIME_WEBPS).toHaveLength(71); + expect(RUNTIME_METADATA).toHaveLength(12); for(const name of ["tide-court","stone-island","wooden-bridge","bram","shell","wave"]){ expect(RUNTIME_WEBPS).toContain(`assets/expedition/runtime/${name}.webp`); expect(RUNTIME_WEBPS).not.toContain(`assets/expedition/${name}.webp`); expect(RUNTIME_WEBPS).not.toContain(`assets/first-light-motion/${name}.webp`); } expect(RUNTIME_METADATA).toContain("assets/expedition/provenance.json"); + for(const directory of ["tide","season","title","ui"]){ + const prefix=`assets/${directory}/`; + expect([...RUNTIME_WEBPS,...RUNTIME_METADATA].filter(path=>path.startsWith(prefix)).sort()).toEqual( + (await staticFiles(join(import.meta.dir,"../web/public/assets",directory))).map(path=>prefix+path)); + } }); test("current art, complete provenance and Wind Gate receipt are copied with hashes",async()=>{ const f=await runtimeFixture(),harbor=RUNTIME_WEBPS[0]!; @@ -116,7 +122,7 @@ test("current art, complete provenance and Wind Gate receipt are copied with has expect((await staticFiles(f.baseline)).some(path=>path.endsWith("unapproved.png"))).toBe(false); }); test("a symlinked new-art directory cannot turn the publication allowlist into an arbitrary file read",async()=>{ - for(const relative of ["assets/expedition","assets/expedition/runtime","icons","social"]){ + for(const relative of ["assets/expedition","assets/expedition/runtime","assets/tide","assets/season","assets/title","assets/ui","icons","social"]){ const f=await runtimeFixture(),directory=join(f.source,relative),outside=join(f.root,"outside-art"); await rename(directory,outside);await symlink(outside,directory,"dir"); const before=await staticFiles(f.baseline); diff --git a/scripts/package-tidebound-review.ts b/scripts/package-tidebound-review.ts index 387046a..7b6212b 100644 --- a/scripts/package-tidebound-review.ts +++ b/scripts/package-tidebound-review.ts @@ -12,8 +12,12 @@ const BASELINE_HTTP_PATHS=HTTP_PATHS.slice(0,3); export const RUNTIME_WEBPS=[ ...["harbor","arena","wind-gate","mochi","mochi-poses","tidekeeper","lens","moth"].map(name=>`assets/first-light-motion/${name}.webp`), ...["harbor","mochi-poses","tidekeeper","shell","lens","moth","wave","bram","tide-court","stone-island","wooden-bridge"].map(name=>`assets/expedition/runtime/${name}.webp`), + ...["card-brams-bridge","card-coiled-rope","card-dry-and-tidy","card-dry-paws","card-every-source","card-full-satchel","card-lantern-haul","card-left-for-bram","card-no-waiting","card-once-across","card-quiet-shell","card-surf-home","card-tidy-tide","card-wake-both-shells","keeper-ask","log-cover","log-page","seal-all-three","seal-kept","seal-slipped"].map(name=>`assets/tide/${name}.webp`), + ...["glass","purse","reed","shelf-till","wish-token"].map(name=>`assets/season/${name}.webp`), + ...["plank-1","plank-2","plank-3","plank-4","post","bell","tag","paper"].map(name=>`assets/title/title-${name}.webp`), + ...["sign-beacon","sign-bram","sign-workbench","sign-satchel","mochi-portrait","mochi-portrait-splashed","mochi-portrait-proud","ask-lens","ask-moth","ask-dry","ask-splash","ask-coiled","ask-no-wait","ask-all-marks","ask-one-crossing","ask-both-shells","ask-bridge","ask-shut-shell","ask-within"].map(name=>`assets/ui/${name}.webp`), ]; -export const RUNTIME_METADATA=["assets/first-light-motion/provenance.json","assets/first-light-motion/wind-gate.webp.json","assets/expedition/provenance.json","assets/expedition/runtime/manifest.json"] as const; +export const RUNTIME_METADATA=["assets/first-light-motion/provenance.json","assets/first-light-motion/wind-gate.webp.json","assets/expedition/provenance.json","assets/expedition/runtime/manifest.json","assets/tide/manifest.json","assets/tide/provenance.json","assets/season/manifest.json","assets/season/provenance.json","assets/title/manifest.json","assets/title/provenance.json","assets/ui/manifest.json","assets/ui/provenance.json"] as const; export const BRAND_ASSETS=["icons/mochi.ico",...[32,180,192,512].map(size=>`icons/mochi-${size}.png`),"social/familiar-harbor.jpg","familiar.webmanifest"]; const primaryFunction="api/v1/privy/wallet.func"; const aliases=["api/health.func","api/v1/privy/player.func","api/v1/privy/note.func"] as const; @@ -49,7 +53,7 @@ function publicBytes(bytes:Uint8Array,path:string) { /** Add only approved art and branding that the baseline lacks; never replace its assets. */ export async function copyRuntimeAssets(sourcePublic:string,destination:string) { await physicalDirectory(sourcePublic);await physicalDirectory(join(sourcePublic,"assets")); - for(const directory of ["first-light-motion","expedition","expedition/runtime"])await physicalDirectory(join(sourcePublic,"assets",directory)); + for(const directory of ["first-light-motion","expedition","expedition/runtime","tide","season","title","ui"])await physicalDirectory(join(sourcePublic,"assets",directory)); for(const directory of ["icons","social"])await physicalDirectory(join(sourcePublic,directory)); await staticFiles(destination); const added:{path:string;sha256:string}[]=[],reused:{path:string;sha256:string}[]=[],writes:{path:string;bytes:Uint8Array}[]=[]; @@ -131,7 +135,7 @@ export async function buildAccountFunction(source:string,output:string){ return installFunctionAliases(output); } -export async function buildGameSite(source:string,site:string,appId:string,clientId:string,sealedNote=false,records=false,season=false){ +export async function buildGameSite(source:string,site:string,appId:string,clientId:string,sealedNote=false,records=false){ const overlay=await mkdtemp(join(tmpdir(),"familiar-game-static-")); try{ await build({configFile:false,plugins:[react()],root:join(source,"web"),envDir:false,envPrefix:[],publicDir:false,define:{ @@ -141,7 +145,6 @@ export async function buildGameSite(source:string,site:string,appId:string,clien "import.meta.env.VITE_TIDEBOUND_ENABLED":JSON.stringify(appId?"true":"false"), "import.meta.env.VITE_SEALED_NOTE_ENABLED":JSON.stringify(appId&&sealedNote?"true":"false"), "import.meta.env.VITE_RECORDS_ENABLED":JSON.stringify(appId&&records?"true":"false"), - "import.meta.env.VITE_SEASON2_ENABLED":JSON.stringify(appId&&season?"true":"false"), },build:{outDir:overlay,rollupOptions:{input:{home:join(source,"web/index.html"),outing:join(source,"web/outing/index.html")},output:{manualChunks:id=>id.includes("/phaser/")?"phaser":undefined}}}}); const staticReport=await copyGameStatic(overlay,site); const runtimeAssets=await copyRuntimeAssets(join(source,"web/public"),site); diff --git a/scripts/test-expedition-harbor-browser.ts b/scripts/test-expedition-harbor-browser.ts index 13a2f85..6ce5838 100644 --- a/scripts/test-expedition-harbor-browser.ts +++ b/scripts/test-expedition-harbor-browser.ts @@ -2,15 +2,108 @@ import assert from "node:assert/strict"; import {mkdtemp} from "node:fs/promises"; import {tmpdir} from "node:os"; import {join,resolve} from "node:path"; -import {chromium,expect} from "@playwright/test"; +import {chromium,expect,type Page} from "@playwright/test"; import {createServer,transformWithOxc} from "vite"; import {KeyPair} from "near-api-js"; import courtFixtures from "../contracts/common/fixtures/court.json"; +import {cardForDay} from "../web/src/tide/cards"; +import {resultTitle,shelfGoods} from "../web/src/tide/run-day"; +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"; // 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){ + await page.setViewportSize({width,height}); + await page.evaluate(async()=>{await document.fonts.ready;await new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve())));}); + const places=page.locator(".exp-home-places button:visible"); + await expect(places).toHaveCount(width<900?3:4); + await expect(page.locator(".exp-place-satchel")).toBeVisible({visible:width>=900}); + for(const place of await places.all()){ + const art=place.locator("img");await expect(art).toHaveAttribute("src",/\/assets\/ui\/sign-(beacon|bram|workbench|satchel)\.webp$/);await expect(art).toHaveAttribute("alt","");await expect(art).toHaveAttribute("decoding","async"); + await expect.poll(()=>art.evaluate((image:HTMLImageElement)=>image.complete&&image.naturalWidth>0)).toBe(true); + } + const geometry=await page.evaluate(()=>{ + const visible=(node:Element)=>node.getClientRects().length>0&&getComputedStyle(node).visibility!=="hidden"; + const bounds=(node:Element)=>{const r=node.getBoundingClientRect();return {x:r.x,y:r.y,right:r.right,bottom:r.bottom,width:r.width,height:r.height};}; + return {signs:[...document.querySelectorAll(".exp-home-places button")].filter(visible).map(node=>({name:node.textContent!,...bounds(node)})), + obstacles:[...document.querySelectorAll(".exp-departure,.exp-phone-dock,.exp-brand")].filter(visible).map(node=>({name:node.className,...bounds(node)})), + card:bounds(document.querySelector(".exp-departure")!),heading:(()=>{const node=document.querySelector(".exp-departure h1")!;return {...bounds(node),overflow:node.scrollWidth>node.clientWidth+1};})(), + stamp:[...document.querySelectorAll(".tide-departure-stamp")].map(bounds), + actions:[...document.querySelectorAll(".exp-departure-buttons>button")].map(node=>({...bounds(node),nowrap:getComputedStyle(node).whiteSpace,overflow:node.scrollWidth>node.clientWidth+1})), + toast:[...document.querySelectorAll(".exp-feedback")].filter(node=>visible(node)&&!!node.textContent?.trim()).map(bounds)}; + }); + const tag=`${width}x${height}`,overlaps=(a:{x:number;y:number;right:number;bottom:number},b:{x:number;y:number;right:number;bottom:number})=>a.xb.x+.5&&a.yb.y+.5; + for(const [i,sign] of geometry.signs.entries()){ + assert(sign.x>=0&&sign.y>=0&&sign.right<=width+.5&&sign.bottom<=height+.5,`${tag}: ${sign.name} stays inside the viewport`); + assert(sign.bottom<=geometry.card.y,`${tag}: ${sign.name}'s stake bottom stays above the harbor card`); + for(const other of geometry.signs.slice(i+1))assert(!overlaps(sign,other),`${tag}: ${sign.name} and ${other.name} do not overlap`); + for(const obstacle of geometry.obstacles)assert(!overlaps(sign,obstacle),`${tag}: ${sign.name} clears ${obstacle.name}`); + } + 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); + 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`); + for(const toast of geometry.toast){ + assert(toast.bottom<=geometry.card.y-6,`${tag}: return toast has a gap above the harbor card`); + for(const sign of geometry.signs)assert(!overlaps(toast,sign),`${tag}: return toast clears ${sign.name}`); + } +} +const MOVE_KEY:Record={north:"ArrowUp",south:"ArrowDown",west:"ArrowLeft",east:"ArrowRight",wait:"Space",home:"r"}; +/** A device harbor's daily is the tide run: each layout sails today's last move for real, or seeds the day's state, then checks the harbor card. */ +async function checkReturnLayouts(browser:import("@playwright/test").Browser,origin:string){ + const day=20771; + const sail=(seed:number,pick:(state:TideState)=>Move)=>{let state=startTide({seed});while(state.outcome==="active")state=applyMove(state,pick(state))!.after;return state;}; + const cautious=sail(day,state=>cautiousMove(state,VALUE)),early=sail(day,()=>"home"),rescued=sail(day,state=>legalMoves(state).includes("north")?"north":"wait"); + assert.equal(resultTitle(dayResult(cautious)),"All three kept.");assert(shelfGoods(dayResult(cautious)).some(Boolean),"the cautious tide brings reed or glass for Bram"); + 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:"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}]; + 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)); + 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:[]})); + if(market)localStorage.setItem("familiar.season.preview.v1",JSON.stringify(market)); + },{day:scenario.day,moves:scenario.moves,market:scenario.shelved?shelf.market:null}); + await page.goto(origin+"/__harbor-game"); + if(scenario.moves){ + const run=page.getByTestId("tide-run");await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready","true",{timeout:20000}); + await expect(run).toHaveAttribute("data-busy","false");await page.keyboard.press(MOVE_KEY[scenario.moves.at(-1)!]); + // A tide that ends on its own goes straight home; a finish card waits for a press. + const finish=page.getByTestId("tide-finish"),homeSheet=page.locator('.exp-panel[data-surface="home"]'); + await expect(finish.or(homeSheet)).toBeVisible({timeout:20000});if(await finish.isVisible())await finish.click(); + } + await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-lease","held"); + if(scenario.moves){const home=page.locator('.exp-panel[data-surface="home"]');await expect(home).toBeVisible();await home.getByRole("button",{name:"Close panel",exact:true}).click();} + await expect(page.locator(".exp-departure h1"),scenario.name).toHaveText(scenario.title); + 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); + }finally{await context.close();} + } +} const entry=` import '/src/browser-globals.ts'; import React,{useEffect,useState} from 'react';import{createRoot}from'react-dom/client'; @@ -66,15 +159,27 @@ try{ 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:"))external.push(request.url());}); + 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());}}); 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(); - await game.getByRole("button",{name:"Workbench",exact:true}).click();await expect(game.getByRole("button",{name:"Make the Crest lantern",exact:true})).toBeVisible();await expect(game.getByText("Crest lantern · Original finish",{exact:true})).toBeVisible(); + for(const [width,height] of [[412,860],[390,844],[844,390],[900,800],[1280,800],[1440,900]])await checkHarborLayout(game,width!,height!); + await game.setViewportSize({width:390,height:844}); + const workbench=game.getByRole("button",{name:"Workbench",exact:true}); + const workbenchBounds=await workbench.boundingBox(),bramBounds=await game.getByRole("button",{name:"Bram",exact:true}).boundingBox(); + assert(workbenchBounds&&bramBounds&&(workbenchBounds.x+workbenchBounds.width<=bramBounds.x||workbenchBounds.x>=bramBounds.x+bramBounds.width||workbenchBounds.y+workbenchBounds.height<=bramBounds.y||workbenchBounds.y>=bramBounds.y+bramBounds.height),"phone Workbench and Bram labels do not overlap"); + await workbench.focus();await game.keyboard.press("Enter");await expect(game.getByRole("button",{name:"Make the Crest lantern",exact:true})).toBeVisible();await expect(game.getByText("Crest lantern · Original finish",{exact:true})).toBeVisible(); assert.equal(await game.evaluate(()=>localStorage.getItem('familiar.first-light.beacon.v1')),null);assert.equal(await game.evaluate(()=>localStorage.getItem('familiar.expedition.local.v2')),null,"fresh-device canonical view does not invent or merge a local home"); await expect(game.locator('.exp-owned-item .tb-lantern')).toHaveAttribute('data-motif','crest');await expect(game.locator('.exp-owned-item .tb-lantern')).toHaveAttribute('data-polished','false'); await game.screenshot({path:join(dir,"fresh-device-canonical-workbench-fixture.png")}); - const porchClip={x:390*.72-20,y:844-316-25-50,width:40,height:75}; + const workbenchPanel=game.getByRole("dialog");await workbenchPanel.evaluate(n=>n.scrollTo({top:n.scrollHeight,behavior:"instant"})); + const panelBounds=await workbenchPanel.boundingBox(),closeBounds=await workbenchPanel.getByRole("button",{name:"Close panel",exact:true}).boundingBox(),headingBounds=await workbenchPanel.getByRole("heading").first().boundingBox(); + assert(panelBounds&&closeBounds&&headingBounds&&closeBounds.y>=panelBounds.y&&headingBounds.y>=panelBounds.y,"workbench keeps its heading and close control visible while scrolling"); + await game.keyboard.press("Escape");await expect(workbench).toBeFocused(); + await workbench.click(); + + const lantern=await game.getByTestId("expedition-world").evaluate(node=>JSON.parse(node.getAttribute("data-harbor-anchors")!).landmarks.lantern as {x:number;y:number}); + const porchClip={x:lantern.x-20,y:lantern.y-50,width:40,height:75}; await game.getByRole("button",{name:"Close panel",exact:true}).click();await game.evaluate(async()=>{const f=(window as any).__harbor;f.displayLantern('crest',false);await f.port.refresh();});await expect(game.getByTestId('expedition-world')).toHaveAttribute('data-lantern-motif','crest');await expect(game.getByTestId('expedition-world')).toHaveAttribute('data-lantern-finish','original');await game.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve()))));const crestPixels=await game.screenshot({clip:porchClip}); 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 expect(game.getByTestId('expedition-world')).toHaveAttribute('data-lantern-finish','harbor_polish');await game.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve()))));const mothPixels=await game.screenshot({clip:porchClip});assert(!crestPixels.equals(mothPixels),'Actual rendered canonical motif/finish must differ at the visible porch prop; changing hidden data attributes alone is insufficient');await game.screenshot({path:join(dir,'canonical-moth-polish-placement-fixture.png')}); assert.deepEqual(await game.evaluate(()=>(window as any).__harbor.port.state.workshop.motifs),['crest'],"Receiving or displaying another maker’s Moth lantern does not grant their achievement");assert.equal(await game.evaluate(()=>(window as any).__harbor.sends.length),0,"Canonical appearance refresh does not issue a craft, finish or placement transaction"); @@ -88,5 +193,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();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,externalRequests:0,chainActions:0,captures:dir,limits:"Synthetic account/RPC ports only; no physical-device, provider-recovery or human-playtest claim."},null,2)); + 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)); }finally{await browser.close();await server.close();} diff --git a/scripts/test-expedition-lifecycle-browser.ts b/scripts/test-expedition-lifecycle-browser.ts index cad29f5..fac3f42 100644 --- a/scripts/test-expedition-lifecycle-browser.ts +++ b/scripts/test-expedition-lifecycle-browser.ts @@ -23,7 +23,7 @@ async function homeGeometry(page:Page){return page.locator('button:visible,a:vis async function homeBounds(page:Page){const controls=await homeGeometry(page),viewport=page.viewportSize()!;for(const control of controls){assert(control.rect.x>=0&&control.rect.y>=0&&control.rect.right<=viewport.width&&control.rect.bottom<=viewport.height&&control.rect.width>=44&&control.rect.height>=44,`Home control fits44px: ${control.label}`);assert(control.hits.every(p=>p.hit),`Home control not obscured at any of9points: ${control.label}`)}return controls} try{ if(!keyboardOnly&&!landscapeOnly){ - {const{page,context}=await open('/__audit');await page.locator('[data-action="depart"]').click();await page.evaluate(()=>{(window as unknown as AuditWindow).__audit.hold=true;document.querySelector('[data-command="step:west"]')!.click();window.dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowUp'}))});await expect.poll(()=>page.evaluate(()=>(window as unknown as AuditWindow).__audit.held.length)).toBe(1);const before=await raw(page);await page.screenshot({path:out+'/F10-'+phase+'-queued-before-unmount.png'});await page.evaluate(()=>(window as unknown as AuditWindow).__audit.close());await expect(page.getByTestId('unmounted')).toBeVisible();await expect.poll(()=>page.evaluate(async()=>(await navigator.locks.query()).held!.length)).toBe(0);await page.evaluate(()=>{(window as unknown as AuditWindow).__audit.held.shift()!(performance.now())});await page.waitForTimeout(100);const after=await raw(page);results.push({case:'F10 queued RAF after Game unmount',before:before.active.state,after:after.active.state});await page.screenshot({path:out+'/F10-'+phase+'-after-unmount.png'});await context.close()} + {const{page,context}=await open('/__audit');await page.locator(".exp-phone-dock").getByRole("button",{name:"Harbor chart",exact:true}).click();await page.locator('.exp-panel[data-surface="chart"] .harbor-routes > li').first().getByRole("button").click();await page.locator('.exp-panel[data-surface="sail"] .exp-primary').click();await page.evaluate(()=>{(window as unknown as AuditWindow).__audit.hold=true;document.querySelector('[data-command="step:west"]')!.click();window.dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowUp'}))});await expect.poll(()=>page.evaluate(()=>(window as unknown as AuditWindow).__audit.held.length)).toBe(1);const before=await raw(page);await page.screenshot({path:out+'/F10-'+phase+'-queued-before-unmount.png'});await page.evaluate(()=>(window as unknown as AuditWindow).__audit.close());await expect(page.getByTestId('unmounted')).toBeVisible();await expect.poll(()=>page.evaluate(async()=>(await navigator.locks.query()).held!.length)).toBe(0);await page.evaluate(()=>{(window as unknown as AuditWindow).__audit.held.shift()!(performance.now())});await page.waitForTimeout(100);const after=await raw(page);results.push({case:'F10 queued RAF after Game unmount',before:before.active.state,after:after.active.state});await page.screenshot({path:out+'/F10-'+phase+'-after-unmount.png'});await context.close()} {const{page,context}=await open();const menu=page.getByRole('button',{name:'Game menu',exact:true});await menu.focus();await page.keyboard.press('Enter');await page.getByRole('button',{name:'How to guide Mochi',exact:true}).focus();await page.keyboard.press('Enter');await page.getByRole('button',{name:'Back to Mochi',exact:true}).focus();await page.keyboard.press('Enter');const active=await page.evaluate(()=>({tag:document.activeElement?.tagName,label:document.activeElement?.getAttribute('aria-label'),text:document.activeElement?.textContent?.slice(0,50)}));results.push({case:'F11 nested menu restores original focused control',active});await page.screenshot({path:out+'/F11-'+phase+'-nested-focus.png'});await context.close()} for(const width of [390,320]){const{page,context}=await open('/outing/?play',{width,height:480});await page.screenshot({path:out+`/F09-${phase}-${width}x480-home.png`});const homeControls=await homeBounds(page);await page.locator('[data-action="depart"]').click();await expect.poll(()=>page.getByTestId('expedition-world').getAttribute('data-tiles')).not.toBe('[]');const geometry=await page.evaluate(()=>({tiles:JSON.parse(document.querySelector('[data-testid="expedition-world"]')!.getAttribute('data-tiles')!),controls:[...document.querySelectorAll('.exp-command-tray button')].map(n=>({label:n.getAttribute('aria-label')??n.textContent,rect:n.getBoundingClientRect().toJSON(),hit:n.contains(document.elementFromPoint(n.getBoundingClientRect().x+n.getBoundingClientRect().width/2,n.getBoundingClientRect().y+n.getBoundingClientRect().height/2))})),w:innerWidth,h:innerHeight,scroll:[scrollX,scrollY,document.documentElement.scrollWidth,document.documentElement.scrollHeight]}));results.push({case:'F09 short portrait',homeControls,geometry});await page.screenshot({path:out+`/F09-${phase}-${width}x480.png`});if(phase==='after'){for(const tile of geometry.tiles)assert(tile.x-tile.width/2>=0&&tile.x+tile.width/2<=width&&tile.y-tile.height/2>=0&&tile.y+tile.height/2<=480,'Every actual court hit area fits short portrait');for(const control of geometry.controls){assert(control.rect.x>=0&&control.rect.right<=width&&control.rect.bottom<=480&&control.rect.width>=44&&control.rect.height>=44,`Control fits with44px target: ${control.label}`);assert(control.hit,`No overlay covers ${control.label}`)}assert.deepEqual(geometry.scroll,[0,0,width,480])}await context.close()} for(const width of [320,390]){const{page,context}=await open('/outing/?play',{width,height:480}); diff --git a/scripts/test-expedition-touch-browser.ts b/scripts/test-expedition-touch-browser.ts index f95aa92..a3e2614 100644 --- a/scripts/test-expedition-touch-browser.ts +++ b/scripts/test-expedition-touch-browser.ts @@ -4,6 +4,8 @@ import {join,resolve} from "node:path"; import {tmpdir} from "node:os"; import {chromium,expect,type Page,type CDPSession} from "@playwright/test"; import {createServer} from "vite"; +import {cardForDay} from "../web/src/tide/cards"; +import {replayRun,solve} from "../web/src/tide/asks"; const phase=process.argv.find(arg=>arg.startsWith("--phase="))?.slice(8)??"after"; const captureArg=process.argv.find(arg=>arg.startsWith("--captures="))?.slice(11); @@ -13,19 +15,100 @@ const server=await createServer({root:resolve(import.meta.dir,"../web"),cacheDir await server.listen();const origin=server.resolvedUrls!.local[0]!.replace(/\/$/,""); const browser=await chromium.launch({headless:true}),key="familiar.expedition.local.v2"; const results:Record[]=[]; +const tideFixtureDay=20771,tideFixtureCard=cardForDay(tideFixtureDay),tideFixtureRoute=solve(tideFixtureCard.tool,tideFixtureCard.asks,tideFixtureCard.best); +assert(tideFixtureRoute?.at(-1)==="return","the tide fixture ends with a real dock return"); +const tideFixtureRun=replayRun(tideFixtureCard.tool,tideFixtureRoute.slice(0,-1)); +assert(tideFixtureRun&&tideFixtureRun.state.outcome==="active"&&tideFixtureRun.state.resolve<3,"the active tide fixture has taken its one splash"); async function state(page:Page){return page.evaluate(key=>{const raw=localStorage.getItem(key);return raw?JSON.parse(raw).active?.state??null:null;},key);} async function touch(cdp:CDPSession,type:"touchStart"|"touchMove"|"touchEnd"|"touchCancel",point?:{x:number;y:number}){await cdp.send("Input.dispatchTouchEvent",{type,touchPoints:point?[{id:1,x:point.x,y:point.y,radiusX:2,radiusY:2,force:1}]:[]});} -async function open(){const context=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true,reducedMotion:"reduce"}),page=await context.newPage();await page.route("**/*",route=>route.request().url().startsWith(origin)&&!new URL(route.request().url()).pathname.startsWith("/api/")?route.continue():route.abort());await page.goto(origin+"/outing/?play");await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-lease","held");return {context,page,cdp:await context.newCDPSession(page)};} -async function court(page:Page){await page.locator('[data-action="depart"]').tap();await expect.poll(async()=>JSON.parse((await page.getByTestId("expedition-world").getAttribute("data-tiles"))!).length).toBe(15);await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve()))));} +async function open(tide=false){const context=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true,reducedMotion:"reduce"}),page=await context.newPage();await page.route("**/*",route=>route.request().url().startsWith(origin)&&!new URL(route.request().url()).pathname.startsWith("/api/")?route.continue():route.abort());if(tide)await page.addInitScript(({key,day,state})=>{ + localStorage.setItem(key,JSON.stringify({version:2,home:{banked:["lens"],lit:true,signaled:false,lantern:null},last:null,active:{context:{authority:"local-preview",banked:[],lit:true,signaled:false},state,season:true}})); + localStorage.setItem("familiar.tide.pending.v1:preview",JSON.stringify({day,late:false})); + },{key,day:tideFixtureDay,state:tideFixtureRun!.state});await page.goto(origin+"/outing/?play");await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true");await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-lease","held");return {context,page,cdp:await context.newCDPSession(page)};} +/** A device harbor's daily is the tide run; the classic court is still a route on the Harbor chart. */ +async function court(page:Page){await page.locator(".exp-phone-dock").getByRole("button",{name:"Harbor chart",exact:true}).tap();await page.locator('.exp-panel[data-surface="chart"] .harbor-routes > li').first().getByRole("button").tap();await page.locator('.exp-panel[data-surface="sail"] .exp-primary').tap();await expect.poll(async()=>JSON.parse((await page.getByTestId("expedition-world").getAttribute("data-tiles"))!).length).toBe(15);await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve()))));} async function cell(page:Page,x:number,y:number){const tiles=JSON.parse((await page.getByTestId("expedition-world").getAttribute("data-tiles"))!) as {position:{x:number;y:number};x:number;y:number}[];return tiles.find(tile=>tile.position.x===x&&tile.position.y===y)!;} try{ + { + const {context,page}=await open(); + const dock=page.locator(".exp-phone-dock"); + await expect(dock.getByRole("button")).toHaveCount(4); + for(const name of ["Harbor chart","Open the tide log","Game menu"]) + await expect(dock.getByRole("button",{name,exact:true})).toBeVisible(); + await expect(dock.getByRole("button",{name:/Satchel/})).toBeVisible(); + await page.setViewportSize({width:844,height:390}); + await expect(dock).toBeHidden(); + await page.getByRole("button",{name:"Game menu",exact:true}).click(); + await page.getByRole("dialog").getByRole("button",{name:"Satchel",exact:true}).click(); + await expect(page.getByRole("heading",{name:"What came home.",exact:true})).toBeVisible(); + await page.keyboard.press("Escape"); + await page.setViewportSize({width:390,height:844}); + await court(page); + const tray=page.locator(".exp-command-tray"); + assert.equal(await tray.evaluate(node=>getComputedStyle(node).backgroundColor),"rgb(251, 243, 226)","court tray has an opaque card surface"); + assert.equal(await tray.evaluate(node=>getComputedStyle(node).backdropFilter),"none","court tray does not blur the board"); + await expect(page.locator('button[data-command="return"]')).toHaveClass(/exp-secondary/); + const trayBounds=await tray.boundingBox(),returnBounds=await page.locator('button[data-command="return"]').boundingBox(); + const directionsBefore=await page.locator(".exp-directions").boundingBox(); + const dockBottom=await page.getByTestId("expedition-world").evaluate(node=>{ + const ys=(JSON.parse(node.getAttribute("data-tiles")!) as {y:number}[]).map(tile=>tile.y),bottom=Math.max(...ys),step=(bottom-Math.min(...ys))/4; + return bottom+Math.max(33,Math.min(step*.65,72))/2; + }); + assert(trayBounds&&returnBounds&&directionsBefore&&trayBounds.y>=dockBottom&&returnBounds.y>=trayBounds.y&&returnBounds.y+returnBounds.height<=844,"phone Return and moves remain visible below the complete dock platform"); + await page.locator(".exp-tray-scroll").evaluate(node=>node.scrollTo({top:node.scrollHeight,behavior:"instant"})); + assert.deepEqual(await page.locator(".exp-directions").boundingBox(),directionsBefore,"reading long feedback never scrolls the movement row away"); + const inspect=page.getByRole("button",{name:"Inspect",exact:true});await inspect.tap(); + const shade=page.locator(".exp-panel-shade"); + assert.equal(await shade.evaluate(node=>getComputedStyle(node).backdropFilter),"none","Inspect leaves the court sharp"); + assert.equal(await page.locator(".exp-world").evaluate(node=>getComputedStyle(node).filter),"none","Inspect does not blur the world"); + await page.keyboard.press("Escape");await expect(inspect).toBeFocused();assert.equal((await state(page)).turn,0,"Inspect and dismissal spend no decisions"); + await context.close(); + } + { + const {context,page}=await open(true),tray=page.locator(".exp-command-tray"),asks=tray.locator(".exp-tray-reading > .tide-outing"); + await expect(asks.locator(".tide-asks>li")).toHaveCount(3); + const emptyFeedback=page.getByTestId("expedition-feedback");await expect(emptyFeedback).toHaveText(""); + assert(await emptyFeedback.evaluate(node=>{const box=node.getBoundingClientRect();return box.width===0&&box.height===0;}),"empty feedback stays in the DOM without painting a box"); + await expect(page.locator(".exp-mochi-portrait")).toHaveAttribute("src","/assets/ui/mochi-portrait-splashed.webp"); + await expect(page.getByTestId("expedition-objective")).toHaveCount(1); + const asksBefore=await asks.boundingBox(),movesBefore=await page.locator(".exp-directions").boundingBox(); + const dockBottom=await page.getByTestId("expedition-world").evaluate(node=>Math.max(...(JSON.parse(node.getAttribute("data-tiles")!) as {y:number;height:number}[]).map(tile=>tile.y+tile.height/2))); + const trayBounds=await tray.boundingBox();assert(trayBounds&&trayBounds.y>=dockBottom,"phone tide tray clears the dock platform"); + await tray.locator(".exp-tray-scroll").evaluate(node=>node.scrollTo({top:node.scrollHeight,behavior:"instant"})); + assert.deepEqual(await asks.boundingBox(),asksBefore,"asks stay pinned above the scrolling reading area"); + assert.deepEqual(await page.locator(".exp-directions").boundingBox(),movesBefore,"tide reading never scrolls the movement row away"); + for(const size of [{width:390,height:844},{width:412,height:860},{width:844,height:390}]){ + await page.setViewportSize(size);await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve())))); + for(const button of await tray.locator(".exp-tray-actions button:visible").all()){ + const bounds=await button.boundingBox();assert(bounds&&bounds.x>=0&&bounds.y>=0&&bounds.x+bounds.width<=size.width+.5&&bounds.y+bounds.height<=size.height+.5,`${size.width}x${size.height}: movement and context actions stay visible without scrolling`); + } + if(size.height<=500){ + await expect(page.locator(".exp-phone-dock")).toBeHidden(); + const hud=await page.locator(".exp-hud").boundingBox(),tiles=JSON.parse((await page.getByTestId("expedition-world").getAttribute("data-tiles"))!) as {x:number;y:number;width:number;height:number}[]; + assert(hud&&tiles.every(tile=>hud.x+hud.width<=tile.x-tile.width/2||hud.x>=tile.x+tile.width/2||hud.y+hud.height<=tile.y-tile.height/2||hud.y>=tile.y+tile.height/2),"landscape status card stays clear of the court platforms"); + } + } + await page.getByRole("button",{name:"Wait for the tide",exact:true}).click(); + await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-busy","false"); + await expect(asks.getByRole("button",{name:"Start this tide over",exact:true})).toBeVisible(); + for(const size of [{width:390,height:844},{width:412,height:860},{width:844,height:390}]){ + await page.setViewportSize(size);await page.evaluate(()=>new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve())))); + const bounds=await tray.boundingBox();assert(bounds); + for(const control of await tray.locator(".tide-asks>li,.tide-restart,.exp-tray-actions button:visible").all()){ + const box=await control.boundingBox();assert(box&&box.x>=bounds.x&&box.x+box.width<=bounds.x+bounds.width+.5&&box.y>=bounds.y&&box.y+box.height<=bounds.y+bounds.height+.5,`${size.width}x${size.height}: slipped asks, restart and actions fit inside the tray`); + } + } + await context.close(); + } { const {context,page,cdp}=await open();await court(page);const before=await state(page),west=await cell(page,0,0);await touch(cdp,"touchStart",west);await touch(cdp,"touchCancel");await page.waitForTimeout(350);const after=await state(page); const result={case:"browser-canceled world touch",before,after,spentDecision:after.turn-before.turn};results.push(result); await page.screenshot({path:join(captures,`F02-${phase}-touch-cancel.png`),fullPage:false});await writeFile(join(captures,`F02-${phase}-transcript.json`),JSON.stringify(result,null,2)+"\n");await context.close(); } { - const {context,page,cdp}=await open(),depart=await page.locator('[data-action="depart"]').boundingBox();assert(depart);await touch(cdp,"touchStart",{x:depart.x+depart.width/2,y:depart.y+depart.height/2});await touch(cdp,"touchCancel");await page.waitForTimeout(200);results.push({case:"browser-canceled home button touch",active:await state(page)});await context.close(); + const {context,page,cdp}=await open(),depart=await page.locator(".exp-departure-buttons > .exp-primary").boundingBox();assert(depart);await touch(cdp,"touchStart",{x:depart.x+depart.width/2,y:depart.y+depart.height/2});await touch(cdp,"touchCancel");await page.waitForTimeout(200); + await expect(page.getByTestId("tide-run")).toHaveCount(0);const tideRun=await page.evaluate(key=>JSON.parse(localStorage.getItem(key+":tide-run.v1")??"null")?.active??null,key); + results.push({case:"browser-canceled home button touch",active:await state(page)??tideRun});await context.close(); } { const {context,page,cdp}=await open();await court(page);const before=await state(page),center=await cell(page,1,0),west=await cell(page,0,0);await touch(cdp,"touchStart",center);await touch(cdp,"touchMove",west);await touch(cdp,"touchEnd");await page.waitForTimeout(350);results.push({case:"drag ending over neighbor",before,after:await state(page)});await page.screenshot({path:join(captures,`${phase}-drag-to-neighbor.png`),fullPage:false});await context.close(); diff --git a/scripts/test-passage-browser.ts b/scripts/test-passage-browser.ts index dd32cba..ab0f69a 100644 --- a/scripts/test-passage-browser.ts +++ b/scripts/test-passage-browser.ts @@ -54,7 +54,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(); - const title=job==="bell"?"Supplies at Bell Steps.":"A harbor connected."; + const title=job==="bell"?"Supplies at Bell Steps.":"The Tidekeeper has an ask."; await expect(page.getByRole("heading",{name:title})).toBeVisible(); await page.reload(); await expect(page.getByRole("heading",{name:title})).toBeVisible(); @@ -63,7 +63,7 @@ try { } const passageKey=key+":shore-passages.v1"; const beforeRest=await page.evaluate(k=>localStorage.getItem(k),passageKey); - await page.getByRole("button",{name:"Look over the harbor",exact:true}).click(); + await page.locator(".exp-harbor-links").getByRole("button",{name:"Harbor chart",exact:true}).click(); await expect(page.getByRole("heading",{name:"A harbor connected.",exact:true})).toBeVisible(); await expect(page.getByRole("heading",{name:"Bell Steps",exact:true})).toBeVisible(); await expect(page.getByText("Bram’s crates are stacked on the far work platform.",{exact:true})).toBeVisible(); diff --git a/scripts/test-records-browser.ts b/scripts/test-records-browser.ts index f12f1aa..6982d6a 100644 --- a/scripts/test-records-browser.ts +++ b/scripts/test-records-browser.ts @@ -83,6 +83,11 @@ try { assert(await panel.evaluate(n=>n.contains(document.activeElement)),"focus stays in the panel after checking again");await expect(again).toBeFocused(); const scroll=await panel.evaluate(n=>n.scrollWidth<=n.clientWidth);assert(scroll,"no horizontal scroll in the panel"); if(shots)for(const [name,at] of [["top",0],["middle",.5],["end",1]] as const){await panel.evaluate((n,f)=>n.scrollTo(0,(n.scrollHeight-n.clientHeight)*f),at);await page.waitForTimeout(250);await page.screenshot({path:join(shots,`records-${width}x${height}-${name}.png`)});} + await panel.evaluate(n=>n.scrollTo({top:n.scrollHeight,behavior:"instant"})); + const panelBounds=await panel.boundingBox(),closeBounds=await panel.getByRole("button",{name:"Close panel",exact:true}).boundingBox(),headingBounds=await panel.getByRole("heading").first().boundingBox(); + assert(panelBounds&&closeBounds&&headingBounds&&closeBounds.y>=panelBounds.y&&headingBounds.y>=panelBounds.y,"records heading and Close stay in view at the bottom"); + await page.keyboard.press("Escape");await expect(panel).toHaveCount(0); + await expect(page.getByRole("button",{name:"Game menu",exact:true}).and(page.locator(":visible"))).toBeFocused(); assert.deepEqual(errors,[]);assert.deepEqual(external,[]);await page.close(); console.log(`records ${width}x${height}: live-shape records, keyboard path, 44px targets passed`); } diff --git a/scripts/test-routing-browser.ts b/scripts/test-routing-browser.ts index 760227f..725de58 100644 --- a/scripts/test-routing-browser.ts +++ b/scripts/test-routing-browser.ts @@ -4,6 +4,9 @@ import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { chromium, expect, webkit } from "@playwright/test"; import { createServer } from "vite"; +import { cautiousTide } from "../web/src/run/bot"; +import { replayTide } from "../web/src/run/engine"; +import { dayResult, shelfHaul } from "../web/src/run/save"; const cacheDir = await mkdtemp(join(tmpdir(), "familiar-routing-")); const artifact=process.argv[2]?resolve(process.argv[2],".vercel/output"):null; @@ -35,6 +38,11 @@ const oldRecords = { "familiar.tidebound.pending.v1:earlier.testnet:player.testnet": '{"original":"operation"}', }; const saveKey = "familiar.expedition.local.v2"; +const bookKey = `${saveKey}:tide-run.v1`; +const returnDay=20771,returned=cautiousTide(returnDay),beforeReturn=replayTide({seed:returnDay},returned.moves.slice(0,-1)); +assert(beforeReturn?.outcome==="active"); +const returnHaul=shelfHaul(dayResult(returned)); +assert(returnHaul.reed+returnHaul.glass>0,"focus fixture brings a haul to Bram's shelf"); try { await server?.listen(); const origin = new URL(compiled?`http://127.0.0.1:${compiled.port}`:server!.resolvedUrls!.local[0]!); @@ -65,8 +73,21 @@ try { await page.getByRole("button", { name: "Game menu" }).click(); await page.getByRole("button", { name: "Account & recovery" }).click(); await expect(page.getByRole("heading", { name: "Your saved harbor" })).toBeVisible(); + const menuOpener=page.getByRole("button",{name:"Game menu",exact:true}).and(page.locator(":visible")); await page.getByRole("button", { name: "Close panel" }).click(); - await page.locator('[data-action="depart"]').click(); + await expect(menuOpener).toBeFocused(); + if(mobile){ + const dock=page.locator(".exp-phone-dock"); + await expect(dock.getByRole("button")).toHaveCount(4); + const logOpener=dock.getByRole("button",{name:"Open the tide log",exact:true}); + await logOpener.click();await expect(page.getByRole("dialog",{name:"Bram’s tide log",exact:true})).toBeVisible(); + await page.keyboard.press("Escape");await expect(logOpener).toBeFocused(); + }else{ + await expect(page.locator(".exp-harbor-tools").getByRole("button",{name:"Harbor chart",exact:true})).toBeVisible(); + } + await page.getByRole("button",{name:"Harbor chart",exact:true}).and(page.locator(":visible")).click(); + await page.locator('.exp-panel[data-surface="chart"] .harbor-routes > li').first().getByRole("button").click(); + await page.locator('.exp-panel[data-surface="sail"] .exp-primary').click(); await page.locator('[data-command="step:west"]').click(); await expect(game).toHaveAttribute("data-busy", "false"); const saved = await page.evaluate(key => localStorage.getItem(key), saveKey); @@ -89,6 +110,31 @@ 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:[]})); + localStorage.removeItem("familiar.tide.pending.v1:preview"); + localStorage.removeItem("familiar.tide.log.v1:preview");localStorage.removeItem("familiar.season.preview.v1"); + },{saveKey,bookKey,state:beforeReturn}); + await page.goto(new URL("/outing/?play",origin).href); + const tideRun=page.getByTestId("tide-run"); + await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready","true"); + await expect(tideRun).toHaveAttribute("data-busy","false"); + await page.locator(`button[data-move="${returned.moves.at(-1)!}"]`).click(); + const home=page.locator('.exp-panel[data-surface="home"]');await expect(home).toBeVisible(); + const filed=await page.evaluate(key=>JSON.parse(localStorage.getItem(key)!),bookKey); + assert.equal(filed.active,null); + assert.deepEqual(filed.days.map((entry:{seed:number;moves:string[]})=>[entry.seed,entry.moves.length]),[[returnDay,returned.moves.length]]); + await home.locator(".exp-secondary").click(); + 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 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); 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 5dfe321..2fba89f 100644 --- a/scripts/test-season-browser.ts +++ b/scripts/test-season-browser.ts @@ -4,15 +4,29 @@ import { tmpdir } from "node:os"; import { join, resolve } from "node:path"; import { chromium, expect, type Page } from "@playwright/test"; import { createServer } from "vite"; +import { VALUE, applyMove, startTide } from "../web/src/run/engine"; +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"; -// Season 2 panels with VITE_SEASON2_ENABLED on, against the live season. views (public RPC). +// Bram's shelf panels, against the live season. views (public RPC). // 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", - define:{"import.meta.env.VITE_SEASON2_ENABLED":JSON.stringify("true")},server:{host:"127.0.0.1",port:0,hmr:false,watch:null}}); + server:{host:"127.0.0.1",port:0,hmr:false,watch:null}}); +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)}); + 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"); + return {daily,goods,shelveName:`Shelve ${haulLine(goods)}`}; +} async function checkTargets(page:Page,label:string) { - const small=await page.locator(".ss button:visible").evaluateAll(els=>els.filter(e=>{const r=e.getBoundingClientRect();return r.height<44||r.width<44;}).map(e=>e.textContent)); - assert.deepEqual(small,[],`${label}: buttons under 44px`); + const small=await page.locator(".ss button:visible, .ss summary:visible").evaluateAll(els=>els.filter(e=>{const r=e.getBoundingClientRect();return r.height<44||r.width<44;}).map(e=>e.textContent)); + assert.deepEqual(small,[],`${label}: controls under 44px`); const overflow=await page.locator(".exp-panel").evaluate(e=>e.scrollWidth>e.clientWidth+1);assert.equal(overflow,false,`${label}: panel scrolls sideways`); const priced=await page.locator(".ss button:visible").evaluateAll(els=>els.map(e=>e.textContent??"").filter(t=>/\d+\s*Shell|NEAR/i.test(t))); assert.deepEqual(priced,[],`${label}: prices on pressables`); @@ -26,8 +40,24 @@ try{ 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(); - await expect(page.locator(".ss-mode")).toContainText("Device preview"); + await expect(page.locator(".ss-mode")).toHaveText("Device preview · not recorded"); await expect(page.locator(".ss-good").first()).toContainText("on the shelf",{timeout:15000}); + await expect(page.locator(".ss-mode[data-mode=preview]")).toHaveCount(1); + await expect(page.locator(".ss-trade-card")).toHaveCount(4); + for(const card of await page.locator(".ss-trade-card").all()){ + await expect(card.getByRole("button",{name:/^(Buy|Sell) \d+$/})).toHaveCount(1); + await expect(card.locator("img")).toBeVisible(); + } + const pricing=page.locator(".ss-good").first().locator("details.ss-pricing"); + await expect(pricing).not.toHaveAttribute("open",""); + await expect(pricing.locator(".ss-reason")).toBeHidden(); + const pricingToggle=pricing.locator("summary"); + await expect(pricingToggle).toHaveText("How Bram prices this"); + await pricingToggle.focus();await page.keyboard.press("Enter"); + await expect(pricing.locator(".ss-reason")).toBeVisible(); + await expect(pricing.locator(".ss-reason")).toContainText("base 8"); + await pricingToggle.press("Space"); + await expect(pricing.locator(".ss-reason")).toBeHidden(); await checkTargets(page,`${tag} shelf`); await page.screenshot({path:join(shots,`preview-shelf-${tag}.png`)}); const reed=page.locator(".ss-good").nth(1); @@ -36,56 +66,70 @@ try{ await expect(page.locator(".ss-holdings")).toContainText("Shells"); await page.screenshot({path:join(shots,`preview-sold-${tag}.png`)}); const tabs=page.getByRole("tab");await tabs.first().focus();await page.keyboard.press("ArrowRight"); - await expect(page.getByRole("tab",{name:"Today’s tide"})).toHaveAttribute("aria-selected","true"); - await expect(page.locator(".ss-court")).toBeVisible(); - await checkTargets(page,`${tag} tide`); - await page.screenshot({path:join(shots,`preview-tide-${tag}.png`)}); - const v2Day=(await page.locator(".ss-court").textContent())==="Beacon Court"; - // The season sandbox's v2 rope route (lens + moth); it docks only on a Beacon Court day. - const route=["step:north","step:north","step:west","wait","wait","step:east","reel:lens","step:east","step:west","step:east","take:moth","step:west","step:east","step:south","step:west","step:south","return"]; - await page.evaluate(commands=>localStorage.setItem("familiar.season.tide.v1:preview",JSON.stringify([{id:"route",contentVersion:"first_light_v2",tool:"rope",commands,cargo:["lens","moth"],outcome:"returned",savedAt:"test"}])),route); - await page.getByRole("tab",{name:"Shelf & till"}).click();await page.getByRole("tab",{name:"Today’s tide"}).click(); - if(v2Day){ - await expect(page.locator(".ss-returns")).toContainText("Rope outing · 1 glass and 1 reed bundle"); - await expect(page.getByRole("button",{name:"Dock this haul"})).toHaveAttribute("aria-disabled","true"); - await page.evaluate(()=>localStorage.removeItem("familiar.season.tide.v1:preview")); - const before=await page.evaluate(()=>({home:JSON.parse(localStorage.getItem("familiar.expedition.local.v2")??"null")?.home??null,returns:localStorage.getItem("familiar.expedition.returns.v2:preview")})); - await page.getByRole("button",{name:"Sail today’s tide"}).click(); - await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-mode","court"); - const save=await page.evaluate(()=>JSON.parse(localStorage.getItem("familiar.expedition.local.v2")!)); - assert.equal(save.active.season,true);assert.deepEqual(save.active.state.banked,[]);assert.equal(save.active.state.area,"beacon"); - await page.screenshot({path:join(shots,`preview-tide-sailing-${tag}.png`)}); - for(const command of route){ - await page.locator(`[data-command="${command}"]`).click(); - await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-busy","false",{timeout:15000}); - } - await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-mode","harbor",{timeout:15000}); - await expect(page.getByTestId("expedition-feedback")).toContainText("Dock today’s haul at Bram’s shelf"); - const after=await page.evaluate(()=>({home:JSON.parse(localStorage.getItem("familiar.expedition.local.v2")!).home,returns:localStorage.getItem("familiar.expedition.returns.v2:preview"),tide:JSON.parse(localStorage.getItem("familiar.season.tide.v1:preview")??"[]")})); - if(before.home)assert.deepEqual(after.home,before.home,"First Light home unchanged by a tide outing");else assert.deepEqual(after.home.banked,[],"tide cargo is not banked"); - assert.equal(after.returns,before.returns,"First Light return memories unchanged"); - assert.equal(after.tide.length,1);assert.deepEqual(after.tide[0].commands,route);assert.deepEqual(after.tide[0].cargo,["lens","moth"]); - await page.locator(".exp-place-bram").click();await page.getByRole("tab",{name:"Today’s tide"}).click(); - await expect(page.locator(".ss-returns")).toContainText("Rope outing · 1 glass and 1 reed bundle"); - await page.screenshot({path:join(shots,`preview-tide-ready-${tag}.png`)}); - await page.evaluate(()=>{localStorage.removeItem("familiar.expedition.local.v2");}); - 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();await page.getByRole("tab",{name:"Today’s tide"}).click(); - }else{ - await expect(page.locator(".ss-panel")).toContainText("would not dock today"); - await expect(page.getByRole("button",{name:"Sail today’s tide"})).toHaveCount(0); - } + await expect(page.getByRole("tab",{name:"Mochi’s wish"})).toHaveAttribute("aria-selected","true"); + await expect(tabs).toHaveCount(2); + await expect(page.getByRole("tab",{name:"Today’s tide"})).toHaveCount(0); + await expect(page.locator(".ss-haul")).toContainText("Today’s haul"); + await checkTargets(page,`${tag} haul`); + await page.screenshot({path:join(shots,`preview-haul-${tag}.png`)}); + // A device harbor's daily is the tide run: before today's tide Bram only points at it. + await expect(page.locator(".ss-haul")).toContainText("Sail today’s tide and bring something home. Bram shelves reed and glass, up to three of each a day."); + await expect(page.locator(".ss-haul").getByRole("button",{name:"See today’s tide",exact:true})).toBeVisible(); + await expect(page.getByRole("button",{name:/^Shelve /})).toHaveCount(0); + // Sailing is checked by test-tide-run-browser; this suite seeds today's finished tide run. + const {daily,goods,shelveName}=dailyTide(); + await page.evaluate(({key,seed,moves})=>localStorage.setItem(key,JSON.stringify({version:1,active:null,days:[{seed,moves}]})),{key:bookKey,seed:daily.seed,moves:daily.moves}); + const before=await page.evaluate(key=>({home:JSON.parse(localStorage.getItem("familiar.expedition.local.v2")??"null")?.home??null,returns:localStorage.getItem("familiar.expedition.returns.v2:preview"),book:localStorage.getItem(key)}),bookKey); + const held=await page.evaluate(()=>JSON.parse(localStorage.getItem("familiar.season.preview.v1")!).goods as [number,number]); + await page.reload(); + await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true",{timeout:30000}); + await page.locator(".exp-place-bram").click(); + await expect(page.locator(".ss-haul")).toContainText(`From today’s tide run: Banked ${daily.score} · Bram guessed `); + const shelve=page.getByRole("button",{name:shelveName,exact:true}); + await expect(shelve).toHaveAttribute("aria-disabled","false"); + await expect(shelve).toHaveClass(/ss-primary/); + await expect(page.locator(".ss .ss-primary")).toHaveCount(1); + await expect(page.locator(".ss-haul-art img")).toHaveCount(goods.filter(Boolean).length); + await checkTargets(page,`${tag} run haul`); + await shelve.click(); + await expect(page.locator(".ss-status")).toContainText(`Shelved on this device: ${haulLine(goods)}. Not recorded.`); + await expect.poll(()=>page.evaluate(()=>!!document.activeElement?.closest(".ss")),{message:"focus stays in the panel after shelving removes its button"}).toBe(true); + assert.deepEqual(await page.evaluate(()=>JSON.parse(localStorage.getItem("familiar.season.preview.v1")!).goods),[held[0]+goods[0],held[1]+goods[1]]); + const docked="Today’s haul is on Bram’s shelf. He takes one a day; bring another find tomorrow."; + await expect(page.locator(".ss-haul")).toContainText(docked); + await expect(shelve).toHaveCount(0); + await page.screenshot({path:join(shots,`preview-shelved-${tag}.png`)}); + await page.getByRole("button",{name:"Start the preview again"}).click(); + await expect(page.locator(".ss-haul")).toContainText(docked); + await page.reload(); + await expect(page.getByTestId("expedition-world")).toHaveAttribute("data-ready","true",{timeout:30000}); + await page.locator(".exp-place-bram").click(); + await expect(page.locator(".ss-haul")).toContainText(docked); + await expect(page.getByRole("button",{name:/^Shelve /})).toHaveCount(0); + const after=await page.evaluate(key=>({home:JSON.parse(localStorage.getItem("familiar.expedition.local.v2")??"null")?.home??null,returns:localStorage.getItem("familiar.expedition.returns.v2:preview"),book:localStorage.getItem(key)}),bookKey); + assert.deepEqual(after.home,before.home,"First Light home unchanged by shelving"); + assert.equal(after.returns,before.returns,"First Light return memories unchanged"); + assert.equal(after.book,before.book,"today's tide run unchanged by shelving"); + await page.getByRole("tab",{name:"Shelf & till"}).focus(); await page.keyboard.press("ArrowRight"); await expect(page.getByRole("tab",{name:"Mochi’s wish"})).toHaveAttribute("aria-selected","true"); - await expect(page.locator(".ss-panel")).toContainText("Sign in from the menu"); + await expect(page.locator(".ss-panel")).toContainText("Mochi’s wishes need a saved harbor."); + await expect(page.locator(".ss-panel")).not.toContainText("Sign in from the menu"); await page.screenshot({path:join(shots,`preview-wish-${tag}.png`)}); await page.goto(new URL("/outing/?season-harness",origin).href); await expect(page.getByRole("note")).toContainText("signing are mocked"); await expect(page.getByRole("button",{name:"Open my ledger page"})).toBeVisible({timeout:15000}); + await expect(page.getByRole("button",{name:"Open my ledger page"})).toHaveClass(/ss-primary/); + await expect(page.locator(".ss .ss-primary")).toHaveCount(1); + // The signed-in harbor keeps the refereed Beacon Court haul, shelved on odd days. + await expect(page.locator(".ss-haul")).toContainText(/See today’s ask|today isn’t one/,{timeout:15000}); + const v2Day=await page.getByRole("button",{name:"See today’s ask",exact:true}).isVisible(); + if(v2Day){await page.getByRole("button",{name:"See today’s ask",exact:true}).click();await expect(page.getByText("Would open today’s ask.")).toBeVisible();} await checkTargets(page,`${tag} harness`); await page.screenshot({path:join(shots,`harness-ledger-${tag}.png`)}); + const route=["step:north","step:north","step:west","wait","wait","step:east","reel:lens","step:east","step:west","step:east","take:moth","step:west","step:east","step:south","step:west","step:south","return"]; + await page.evaluate(commands=>localStorage.setItem("familiar.season.tide.v1:harness",JSON.stringify([{id:"route",contentVersion:"first_light_v2",tool:"rope",commands,cargo:["lens","moth"],outcome:"returned",savedAt:new Date().toISOString()}])),route); await page.getByRole("button",{name:"Open my ledger page"}).click(); await expect(page.locator(".ss-status")).toHaveAttribute("data-state","pending"); await expect(page.locator(".ss-status")).not.toContainText("Recorded"); @@ -98,6 +142,7 @@ try{ await page.locator(".ss-good").nth(1).getByRole("button",{name:"Sell 1"}).click(); await expect(page.locator(".ss-status")).toContainText("Sold 1 reed bundle",{timeout:10000}); await page.getByRole("tab",{name:"Mochi’s wish"}).click(); + await expect(page.locator(".ss .ss-primary")).toHaveCount(1); await page.getByRole("button",{name:"Set Mochi’s wish"}).click(); await expect(page.locator(".ss-status")).toContainText("waiting",{timeout:10000}); await expect(page.locator(".ss-wish-head")).toContainText("Mochi is waiting for"); @@ -108,13 +153,12 @@ try{ await expect.poll(focusInside,{message:"focus stays in the panel after the wish is taken back"}).toBe(true); await page.screenshot({path:join(shots,`harness-postcard-${tag}.png`),fullPage:true}); if(v2Day){ - await page.getByRole("tab",{name:"Today’s tide"}).click(); - await page.getByRole("button",{name:"Dock this haul"}).first().click(); - await expect(page.locator(".ss-status")).toContainText("Docked 1 glass and 1 reed bundle: 100% of the best haul",{timeout:10000}); + await page.getByRole("button",{name:"Shelve 1 glass and 1 reed bundle",exact:true}).first().click(); + 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(); - console.info(`${tag}: preview shelf/sell/tide/wish and harness ledger/refusal/sale/wish/postcard passed`); + console.info(`${tag}: preview shelf/sell/run haul/shelve/wish and harness ledger/refusal/sale/wish/postcard passed`); } }finally{await browser.close();} console.info(`Screenshots: ${shots}`); diff --git a/scripts/test-tide-browser.ts b/scripts/test-tide-browser.ts new file mode 100644 index 0000000..2bc2033 --- /dev/null +++ b/scripts/test-tide-browser.ts @@ -0,0 +1,787 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp } from "node:fs/promises"; +import { join, resolve } from "node:path"; +import { chromium, expect, type Page } from "@playwright/test"; +import { createServer } from "vite"; +import { TURN_LIMIT, type Command } from "../web/src/expedition/types"; +import { askHolds, cardStatus, replayRun, solve } from "../web/src/tide/asks"; +import { askLine, cardForDay, dayLabel, TOOL_NOTE } from "../web/src/tide/cards"; +import type { TideEntry } from "../web/src/tide/log"; +import { bramsGuess, cautiousMove } from "../web/src/run/bot"; +import { applyMove, startTide, type Move } from "../web/src/run/engine"; +import { dayResult, readBook } from "../web/src/run/save"; +import { STAMPS, haulWords, resultLine, resultTitle, shelfGoods } from "../web/src/tide/run-day"; +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); +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 => { + const run = replayRun(card.tool, commands); + return run?.state.outcome === "active" && cardStatus(card, run).includes("slipped"); +}); +assert.ok(slipRoute, "the real engine finds an active outing with a slipped ask"); +const nextDay = day + 1, nextCard = cardForDay(nextDay); +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 shots = resolve(process.argv[2] ?? await mkdtemp(join(artifacts, "shots-"))); +await mkdir(shots, { recursive: true }); +const server = await createServer({ + root: resolve(import.meta.dir, "../web"), envDir: false, envPrefix: [], + cacheDir: await mkdtemp(join(artifacts, "vite-")), logLevel: "error", + server: { host: "127.0.0.1", port: 0, hmr: false, watch: null }, +}); + +function entryFor(tideDay: number, commands: Command[]): TideEntry { + const tideCard = cardForDay(tideDay), run = replayRun(tideCard.tool, commands); + assert.ok(run && run.state.outcome !== "active", "screenshot fixtures are legal finished outings"); + return { day: tideDay, cardId: tideCard.id, tool: tideCard.tool, commands, + kept: cardStatus(tideCard, run).map(status => status === "kept") as TideEntry["kept"], + decisions: run.state.turn, outcome: run.state.outcome, late: false, attempts: 1, savedAt: "" }; +} + +async function captureLayouts(page: Page, label: string, check?: () => Promise) { + const resize = async (size: { width: number; height: number }) => { + await page.setViewportSize(size); + // Phaser's resize arrives after the DOM layout, so wait before measuring its tiles. + await expect.poll(() => page.locator(".exp-world canvas").evaluate((canvas: HTMLCanvasElement) => + canvas.width === canvas.parentElement!.clientWidth && canvas.height === canvas.parentElement!.clientHeight), + { message: `${label}: canvas catches up with the viewport`, timeout: 15000 }).toBe(true); + }; + for (const size of [viewport, { width: 390, height: 844 }, { width: 844, height: 390 }, { width: 1280, height: 800 }, { width: 1440, height: 900 }]) { + await resize(size); + if (await page.locator(".exp-panel").count()) await checkPanel(page, `${label} ${size.width}x${size.height}`); + await check?.(); + await page.screenshot({ path: join(shots, `rev-${label}-${size.width}x${size.height}.png`) }); + } + await resize(viewport); +} + +async function observePops(page: Page) { + await page.evaluate(() => { + window.tidePops = []; + document.addEventListener("animationstart", event => { + if ((event as AnimationEvent).animationName !== "tide-chip-pop") return; + const chip = event.target as HTMLElement; + window.tidePops.push([...chip.parentElement!.children].indexOf(chip)); + }); + }); +} + +async function checkPanel(page: Page, label: string) { + const small = await page.locator(".exp-panel button:visible").evaluateAll(buttons => buttons.flatMap(button => { + const { width, height } = button.getBoundingClientRect(); + return width < 44 || height < 44 ? [{ name: button.getAttribute("aria-label") ?? button.textContent, width, height }] : []; + })); + assert.deepEqual(small, [], `${label}: buttons under 44px`); + const overflow = await page.locator(".exp-panel").evaluate(panel => panel.scrollWidth > panel.clientWidth + 1); + assert.equal(overflow, false, `${label}: panel scrolls sideways`); +} + +async function checkHarborStamp(page: Page) { + const harbor = page.locator(".exp-departure"); + await expect(harbor.locator(".tide-stamp-paper > img")).toHaveAttribute("alt", ""); + assert.ok(await harbor.evaluate(node => { + const stamp = node.querySelector(".tide-stamp")!, bounds = stamp.getBoundingClientRect(); + const heading = node.querySelector("h1")!, action = node.querySelector(".exp-primary,.exp-secondary")!.getBoundingClientRect(); + const text = [heading, node.querySelector("p")!].flatMap(element => { + const range = document.createRange(); range.selectNodeContents(element); return [...range.getClientRects()]; + }); + return getComputedStyle(stamp).getPropertyValue("--stamp") === "88px" + && text.every(rect => rect.right <= bounds.left || rect.left >= bounds.right || rect.bottom <= bounds.top || rect.top >= bounds.bottom) + && (bounds.bottom <= action.top || bounds.right <= action.left) + && node.getBoundingClientRect().left >= 0 && node.getBoundingClientRect().right <= innerWidth; + }), "harbor stamp is 88px and overlaps neither text nor an action at every viewport"); + assert.ok(await harbor.locator(".exp-primary").count() <= 1, "one primary per harbor card"); + assert.ok(await harbor.locator(".exp-secondary").count() <= 2, "at most two secondary actions per harbor card"); + const size = page.viewportSize()!, dockActive = size.width < 900 && (size.height >= size.width || size.height > 500); + const navigation = page.locator(dockActive ? ".exp-phone-dock" : ".exp-harbor-tools"); + await expect(navigation.getByRole("button", { name: "Harbor chart", exact: true })).toBeVisible(); + await expect(navigation.getByRole("button", { name: "Open the tide log", exact: true })).toBeVisible(); + if (dockActive) { + await expect(navigation.getByRole("button")).toHaveCount(4); + 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(); +} + +async function checkStickyPanel(page: Page, label: string) { + const panel = page.locator(".exp-panel"); + await panel.evaluate(node => node.scrollTo({ top: node.scrollHeight, behavior: "instant" })); + const bounds = await panel.boundingBox(), close = await panel.getByRole("button", { name: "Close panel", exact: true }).boundingBox(); + const heading = await panel.getByRole("heading").first().boundingBox(); + assert.ok(bounds && close && heading && close.y >= bounds.y && close.y + close.height <= bounds.y + bounds.height + && heading.y >= bounds.y && heading.y + heading.height <= bounds.y + bounds.height, `${label}: close and heading stay in view after scrolling`); + await panel.evaluate(node => node.scrollTo({ top: 0, behavior: "instant" })); +} + +async function checkTrayAsks(page: Page, label: string) { + const tray = page.locator(".exp-command-tray"), asks = tray.locator(".exp-tray-reading > .tide-outing .tide-asks"); + await expect(asks).toBeVisible(); + await expect(tray.locator(".exp-tray-scroll .tide-outing")).toHaveCount(0); + const bounds = await tray.boundingBox(), strip = await asks.boundingBox(), actions = await tray.locator(".exp-tray-actions").boundingBox(); + assert.ok(bounds && strip && actions, `${label}: tray, asks and actions have visible bounds`); + assert.ok(strip.x >= bounds.x - 1 && strip.x + strip.width <= bounds.x + bounds.width + 1 + && strip.y >= bounds.y - 1 && strip.y + strip.height <= bounds.y + bounds.height + 1, + `${label}: asks lie inside the move tray`); + assert.ok(strip.y + strip.height <= actions.y + 1 || strip.x + strip.width <= actions.x + 1 || strip.x >= actions.x + actions.width - 1, + `${label}: asks do not overlap movement or context actions`); + const chips = await asks.locator("li").evaluateAll(nodes => nodes.map(node => { + const bounds = node.getBoundingClientRect(); + return { top: bounds.top, left: bounds.left, right: bounds.right, height: bounds.height, + font: parseFloat(getComputedStyle(node).fontSize), fits: node.scrollWidth <= node.clientWidth + 1 }; + })); + assert.ok(chips.every(chip => chip.left >= strip.x - 1 && chip.right <= strip.x + strip.width + 1 && chip.fits), + `${label}: every chip fits without clipping its status words at ${page.viewportSize()!.width}x${page.viewportSize()!.height}: ${JSON.stringify(await asks.locator("li").allInnerTexts())}`); + assert.ok(chips.every(chip => chip.font >= 13), `${label}: ask text is at least 13px`); + const size = page.viewportSize()!; + if (size.width < 900) { + const rows = new Set(chips.map(chip => Math.round(chip.top))).size; + if (size.height > size.width) assert.equal(rows, 1, `${label}: portrait phone asks use one row`); + else assert.ok(rows <= 2, `${label}: landscape phone asks use at most two rows in the narrow tray`); + assert.ok(chips.every(chip => chip.height <= 36), `${label}: phone chips stay at most 36px tall`); + } else assert.equal(new Set(chips.map(chip => Math.round(chip.top))).size, 3, `${label}: desktop asks use three stacked rows`); + const reading = tray.locator(".exp-tray-scroll"); + assert.ok(await reading.evaluate(node => { + node.scrollTo({ top: node.scrollHeight, behavior: "instant" }); + return node.scrollHeight <= node.clientHeight + 1 || node.scrollTop > 0; + }), `${label}: overflowing reading text actually scrolls`); + const afterScroll = await asks.boundingBox(); + assert.ok(afterScroll && Math.abs(afterScroll.y - strip.y) <= 1, `${label}: scrolling the reading text leaves the asks in place`); + await reading.evaluate(node => node.scrollTo({ top: 0, behavior: "instant" })); +} + +async function checkRestartLayout(page: Page, label: string) { + const asks = page.locator(".tide-asks"), restart = page.locator(".tide-outing > .tide-restart.exp-text-button"); + const strip = await asks.boundingBox(), button = await restart.boundingBox(); + const tray = await page.locator(".exp-command-tray").boundingBox(), actions = await page.locator(".exp-tray-actions").boundingBox(); + assert.ok(strip && button && tray && actions, `${label}: asks, restart, tray and actions have visible bounds`); + assert.ok(button.y >= strip.y + strip.height - 1 || button.y + button.height <= strip.y + 1 + || button.x >= strip.x + strip.width - 1 || button.x + button.width <= strip.x + 1, + `${label}: restart and ask chips do not overlap`); + assert.ok(button.x >= tray.x - 1 && button.x + button.width <= tray.x + tray.width + 1 + && button.y >= tray.y - 1 && button.y + button.height <= tray.y + tray.height + 1, `${label}: restart stays inside the tray`); + assert.ok(button.y + button.height <= actions.y + 1 || button.x + button.width <= actions.x + 1 || button.x >= actions.x + actions.width - 1, + `${label}: restart stays clear of movement and context actions`); + assert.ok(button.height >= 44, `${label}: restart has a 44px target`); + await expect(restart).toBeInViewport({ ratio: 1 }); + await checkTrayAsks(page, label); + await page.locator(".exp-tray-scroll").evaluate(node => node.scrollTo({ top: node.scrollHeight, behavior: "instant" })); + const afterScroll = await restart.boundingBox(); + assert.ok(afterScroll && Math.abs(afterScroll.y - button.y) <= 1, `${label}: scrolling the reading text leaves restart in place`); + await expect(restart).toBeInViewport({ ratio: 1 }); + await page.locator(".exp-tray-scroll").evaluate(node => node.scrollTo({ top: 0, behavior: "instant" })); + assert.equal(await asks.evaluate(node => getComputedStyle(node).pointerEvents), "none"); + assert.equal(await restart.evaluate(node => getComputedStyle(node).pointerEvents), "auto"); + await restart.focus(); + await page.keyboard.press("Tab"); + await page.keyboard.press("Shift+Tab"); + await expect(restart).toBeFocused(); + assert.ok(await restart.evaluate(node => { + const style = getComputedStyle(node); + return style.outlineStyle !== "none" && parseFloat(style.outlineWidth) > 0; + }), `${label}: keyboard focus is visible`); +} + +async function openClassic(page: Page) { + await page.getByRole("button", { name: "Harbor chart", exact: true }).and(page.locator(":visible")).click(); + const beacon = page.locator('.exp-panel[data-surface="chart"] .harbor-routes > li').filter({ hasText: "Beacon Court" }); + await expect(beacon).toHaveCount(1); + await beacon.getByRole("button").click(); + await expect(page.locator('.exp-panel[data-surface="court-tide"]')).toBeVisible(); +} + +async function checkDaily(page: Page, origin: string) { + const today = Math.floor(Date.now() / 86_400_000), todayCard = cardForDay(today), tomorrow = cardForDay(today + 1); + const guardDay = () => assert.equal(Math.floor(Date.now() / 86_400_000), today, "UTC midnight crossed during the daily flow; rerun with the new day"); + const keys: Record = { north: "ArrowUp", south: "ArrowDown", west: "ArrowLeft", east: "ArrowRight", wait: "Space", home: "r" }; + let final = startTide({ seed: today }); + while (final.outcome === "active") final = applyMove(final, cautiousMove(final))!.after; + const result = dayResult(final), goods = shelfGoods(result); + assert.equal(result.guess, bramsGuess(today)); + assert.ok(goods[0] + goods[1] > 0, "the cautious daily route brings reed or glass to Bram"); + await page.emulateMedia({ reducedMotion: "reduce" }); + await page.addInitScript(({ saveKey, passageKey }) => { + localStorage.setItem(saveKey, JSON.stringify({ + version: 2, home: { banked: ["lens", "moth", "vane"], lit: true, signaled: true, lantern: null }, active: null, last: null, + })); + localStorage.setItem(passageKey, JSON.stringify({ + version: 1, services: ["bell", "reed"], watchedReeds: true, heardBell: false, active: null, + })); + }, { saveKey, passageKey }); + await page.goto(new URL("/outing/?play", origin).href); + 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.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(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 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)); + await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready", "true", { timeout: 30000 }); + for (const move of final.moves) { + await expect(run).toHaveAttribute("data-busy", "false", { timeout: 15000 }); + await page.keyboard.press(keys[move]); + } + await expect(page.getByRole("dialog", { name: "Home", exact: true })).toBeVisible({ timeout: 15000 }); + 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 () => { + await expect(panel.locator(".tide-list > li")).toHaveCount(3); + for (const [index, stamp] of STAMPS.entries()) { + const kept = result.stamps[stamp.key], row = panel.locator(".tide-list > li").nth(index); + await expect(row).toHaveAttribute("data-kept", String(kept)); + await expect(row).toHaveText(`${stamp.label(result)} (${kept ? "kept" : "slipped"})`); + } + await expect(panel.locator(".tide-haul .tide-sr")).toHaveText(`Haul: ${haulWords(result)}.`); + }; + await checkStamps(); + await expect(panel.getByRole("button", { name: "Take it to Bram", exact: true })).toHaveClass(/exp-primary/); + await expect(panel.getByRole("button", { name: "See the tide log", exact: true })).toHaveClass(/exp-secondary/); + await captureLayouts(page, "daily-home", async () => { + if (page.viewportSize()!.height === 390) { + assert.equal(await panel.evaluate(node => node.scrollHeight > node.clientHeight + 1), false, "landscape daily Home needs no scrolling"); + for (const name of ["Take it to Bram", "See the tide log"]) { + await expect(panel.getByRole("button", { name, exact: true })).toBeInViewport({ ratio: 1 }); + } + } + await checkStickyPanel(page, "daily Home"); + }); + const bookKey = `${saveKey}:tide-run.v1`, raw = await page.evaluate(key => localStorage.getItem(key), bookKey); + const book = readBook({ getItem: () => raw }, bookKey); + assert.equal(book.active, null); + assert.equal(book.days.length, 1); + 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.locator(".tide-facts > div").filter({ has: page.getByText(name, { exact: true }) }).locator("dd")).toHaveText(String(value)); + } + await checkStamps(); + await captureLayouts(page, "daily-log", () => checkStickyPanel(page, "daily log")); + await panel.getByRole("button", { name: "Close panel", exact: true }).click(); + await expect(harbor.getByRole("heading", { name: resultTitle(result), exact: true })).toBeVisible(); + await expect(harbor.locator("p").first()).toHaveText(`${resultLine(result)}.`); + await expect(harbor.locator(".exp-primary")).toHaveCount(1); + await expect(harbor.locator(".exp-primary")).toHaveText("Take it to Bram"); + await captureLayouts(page, "daily-result", () => checkHarborStamp(page)); + await harbor.getByRole("button", { name: "Take it to Bram", exact: true }).click(); + const shelve = panel.getByRole("button", { name: `Shelve ${haulLine(goods)}`, exact: true }); + 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 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 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(); +} + +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)); + await page.emulateMedia({ reducedMotion: "reduce" }); + await page.addInitScript(({ saveKey, passageKey, pendingKey, blockPending }) => { + localStorage.setItem(saveKey, JSON.stringify({ + version: 2, home: { banked: ["lens", "moth", "vane"], lit: true, signaled: true, lantern: null }, active: null, last: null, + })); + localStorage.setItem(passageKey, JSON.stringify({ + version: 1, services: ["bell", "reed"], watchedReeds: true, heardBell: false, active: null, + })); + if (blockPending) { + const setItem = Storage.prototype.setItem; + Storage.prototype.setItem = function (key: string, value: string) { + if (key === pendingKey) throw new DOMException("Site data is blocked", "QuotaExceededError"); + setItem.call(this, key, value); + }; + } + }, { saveKey, passageKey, pendingKey, blockPending: mode === "unmarked-outing" }); + 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.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 openClassic(page); + await expect(panel.getByRole("heading", { name: card.name, exact: true })).toBeVisible(); + const asks = page.locator(".tide-asks"); + if (outing) { + await panel.getByRole("button", { name: "Sail today’s tide", exact: true }).click(); + await expect(page.getByTestId("expedition-game")).toHaveAttribute("data-mode", "court"); + await expect(asks).toBeVisible(); + await expect(asks.locator("li[data-status]")).toHaveCount(3); + } + const beforeAsks = await asks.allTextContents(); + if (mode === "wake") { + await page.clock.setSystemTime(new Date(midnight + 1_000)); + await page.evaluate(() => document.dispatchEvent(new Event("visibilitychange"))); + } else await page.clock.fastForward(2_000); + if (outing) { + assert.deepEqual(await asks.allTextContents(), beforeAsks, "midnight keeps the active card’s asks"); + assert.deepEqual(await page.evaluate(key => JSON.parse(localStorage.getItem(key)!), pendingKey), expectedPending, "midnight keeps the outing’s original marker"); + await page.getByRole("button", { name: "Game menu", exact: true }).click(); + await panel.getByRole("button", { name: "Start this tide over", exact: true }).click(); + assert.deepEqual(await asks.allTextContents(), beforeAsks, "restart after midnight keeps the original card’s asks"); + assert.deepEqual(await page.evaluate(key => JSON.parse(localStorage.getItem(key)!), pendingKey), expectedPending, "restart after midnight keeps the outing’s original marker"); + await page.locator('button[data-command="return"]').click(); + await page.clock.runFor(1_000); + await expect(page.getByRole("dialog", { name: "Home", exact: true })).toBeVisible(); + await panel.getByRole("button", { name: "See the tide log", exact: true }).click(); + await expect(panel.getByRole("heading", { name: card.name, exact: true })).toBeVisible(); + const entries = await page.evaluate(key => JSON.parse(localStorage.getItem(key) ?? "[]"), logKey); + assert.equal(entries.length, 1); + assert.equal(entries[0].day, day, "a return after midnight is logged on the day it started"); + assert.equal(entries[0].cardId, card.id); + } else { + 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 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"); + } +} + +try { + await server.listen(); + const origin = server.resolvedUrls!.local[0]!; + const browser = await chromium.launch(); + const errors: string[] = []; + try { + const dailyPage = await browser.newPage({ viewport }); + dailyPage.on("pageerror", error => errors.push(error.message)); + try { await checkDaily(dailyPage, origin); } + finally { await dailyPage.close(); } + const page = await browser.newPage({ viewport }); + await page.clock.install({ time: new Date(day * 86_400_000 + 43_200_000) }); + 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"); + await page.goto(new URL("/outing/?play", origin).href); + await expect(world).toHaveAttribute("data-ready", "true", { timeout: 30000 }); + const before = await page.evaluate(({ saveKey, passageKey }) => { + localStorage.clear(); + localStorage.setItem(saveKey, JSON.stringify({ + version: 2, home: { banked: ["lens", "moth", "vane"], lit: true, signaled: true, lantern: null }, active: null, last: null, + })); + localStorage.setItem(passageKey, JSON.stringify({ + version: 1, services: ["bell", "reed"], watchedReeds: true, heardBell: false, active: null, + })); + return JSON.parse(localStorage.getItem(saveKey)!).home; + }, { saveKey, passageKey }); + + await page.goto(new URL(`/outing/?play&tide-day=${day}`, origin).href); + await expect(world).toHaveAttribute("data-ready", "true", { timeout: 30000 }); + for (const size of [viewport, { width: 1280, height: 800 }]) { + await page.setViewportSize(size); + const chartOpener = page.getByRole("button", { name: "Harbor chart", exact: true }).and(page.locator(":visible")).first(); + await chartOpener.focus(); + await page.keyboard.press("Enter"); + await expect(page.getByRole("dialog", { name: "Chart", exact: true })).toBeVisible(); + await captureLayouts(page, "harbor-chart", () => checkStickyPanel(page, "harbor chart")); + await page.setViewportSize(size); + await page.keyboard.press("Escape"); + await expect(chartOpener).toBeFocused(); + await chartOpener.click(); + await panel.getByRole("button", { name: "Close panel", exact: true }).click(); + await expect(chartOpener).toBeFocused(); + } + await page.setViewportSize(viewport); + for (const place of await page.locator(".exp-home-places button:visible").all()) { + await place.hover(); + assert.ok(await place.evaluate(button => { + const style = getComputedStyle(button), text = style.color.match(/[\d.]+/g)!.map(Number), surface = style.backgroundColor.match(/[\d.]+/g)!.map(Number); + const luminance = (rgb: number[]) => rgb.slice(0, 3).map(channel => { const value = channel / 255; return value <= .04045 ? value / 12.92 : ((value + .055) / 1.055) ** 2.4; }).reduce((sum, value, i) => sum + value * [.2126, .7152, .0722][i]!, 0); + const alpha = surface[3] ?? 1, backdrop = surface.slice(0, 3).map(channel => channel * alpha + 255 * (1 - alpha)); + const light = luminance(text), dark = luminance(backdrop); + return (Math.max(light, dark) + .05) / (Math.min(light, dark) + .05) >= 4.5; + }), "hover keeps every harbor place label readable, even over the lightest scene background"); + } + await page.screenshot({ path: join(shots, `harbor-ask-${tag}.png`) }); + await page.setViewportSize({ width: 1280, height: 800 }); + await checkHarborStamp(page); + await page.screenshot({ path: join(shots, "harbor-ask-1280x800.png") }); + await page.setViewportSize(viewport); + + await openClassic(page); + await expect(panel.getByRole("heading", { name: "Today’s tide", exact: true })).toBeVisible(); + await expect(panel.getByRole("heading", { name: card.name, exact: true })).toBeVisible(); + await expect(panel).toContainText(TOOL_NOTE[card.tool]); + for (const ask of card.asks) await expect(panel.getByText(askLine(ask, card.tool), { exact: true })).toBeVisible(); + await expect(panel.locator(".tide-earlier")).toHaveCount(0); + await captureLayouts(page, "classic-ask"); + assert.ok(await panel.locator(".tide-card").evaluate(card => { + const bounds = card.getBoundingClientRect(), primary = card.querySelector(".exp-primary")!.getBoundingClientRect(); + return Math.abs(primary.left - bounds.left) <= 1 && Math.abs(primary.right - bounds.right) <= 1; + }), "Today’s tide primary pill fills the phone card width"); + await page.screenshot({ path: join(shots, `ask-card-${tag}.png`) }); + + await observePops(page); + await panel.getByRole("button", { name: "Sail today’s tide", exact: true }).click(); + await expect(game).toHaveAttribute("data-mode", "court"); + const active = await page.evaluate(key => JSON.parse(localStorage.getItem(key)!), saveKey); + assert.equal(active.active.season, true); + assert.deepEqual(active.active.state.banked, []); + assert.deepEqual(await page.evaluate(key => JSON.parse(localStorage.getItem(key) ?? "null"), pendingKey), { day, late: false }); + const asks = page.locator(".tide-asks"); + await expect(asks).toBeVisible(); + await expect(asks.locator("li[data-status]")).toHaveCount(3); + assert.deepEqual(await page.evaluate(() => window.tidePops), [], "first render does not pop asks already holding"); + await expect(asks.locator("[data-motion]")).toHaveCount(0); + const initialRun = replayRun(card.tool, [])!; + for (let index = 0; index < 3; index++) { + const holding = askHolds(card.asks[index]!, initialRun), chip = asks.locator("li").nth(index); + await expect(chip).toHaveAttribute("data-holding", String(holding)); + await expect(chip.locator(".tide-sr")).toHaveText(holding ? " (holding)" : " (not yet)"); + await expect(chip.locator("svg path")).toHaveCount(holding ? 1 : 0); + } + await captureLayouts(page, "court-start", () => checkTrayAsks(page, "outing start")); + for (const [index, command] of route.entries()) { + await page.locator(`button[data-command="${command}"]`).click(); + await expect(game).toHaveAttribute("data-busy", "false", { timeout: 15000 }); + if (index + 1 === Math.ceil(route.length / 2)) { + await expect(asks).toBeVisible(); + const strip = await asks.boundingBox(), hud = await page.locator('.exp-hud[aria-label="Expedition status"]').boundingBox(); + assert.ok(strip && hud, "the asks and status HUD have visible bounds"); + assert.ok(strip.y >= hud.y + hud.height, "the asks do not overlap the status HUD"); + assert.ok(strip.x >= 0 && strip.x + strip.width <= viewport.width + 1, "the asks fit the viewport width"); + await captureLayouts(page, "court-mid-outing", () => checkTrayAsks(page, "mid-outing")); + const chips = await asks.locator("li").evaluateAll(nodes => nodes.map(node => ({ top: Math.round(node.getBoundingClientRect().top), font: parseFloat(getComputedStyle(node).fontSize) }))); + assert.ok(new Set(chips.map(chip => chip.top)).size <= 2, "phone asks use at most two rows"); + assert.ok(chips.every(chip => chip.font >= 13), "phone ask text is at least 13px"); + const feedback = await page.getByTestId("expedition-feedback").boundingBox(), tray = await page.locator(".exp-command-tray").boundingBox(); + const reading = await page.locator(".exp-tray-scroll").boundingBox(), actions = await page.locator(".exp-tray-actions").boundingBox(); + const directions = await page.locator(".exp-directions").boundingBox(); + const dockBottom = await world.evaluate(node => { + const ys = (JSON.parse(node.getAttribute("data-tiles")!) as { y: number }[]).map(tile => tile.y); + const bottom = Math.max(...ys), step = (bottom - Math.min(...ys)) / 4; + return bottom + Math.max(33, Math.min(step * .65, 72)) / 2; + }); + assert.ok(tray && tray.y >= dockBottom, "the phone tray clears the complete dock platform"); + assert.ok(feedback && reading && directions && Math.max(feedback.y, reading.y) >= tray!.y + && Math.min(feedback.y + feedback.height, reading.y + reading.height) <= directions.y, + "visible phone feedback stays inside its scrolling region above the movement controls"); + assert.ok(actions && actions.y >= tray!.y && actions.y + actions.height <= viewport.height, + "phone movement and context actions stay visible without scrolling the tray"); + await page.screenshot({ path: join(shots, `court-mid-outing-${tag}.png`) }); + } + } + + await expect(game).toHaveAttribute("data-mode", "harbor", { timeout: 15000 }); + await expect(page.getByRole("dialog", { name: "Home", exact: true })).toBeVisible(); + await expect(panel.getByRole("heading", { name: "All three asks kept.", exact: true })).toBeVisible(); + await expect(panel.locator('.tide-list > li[data-kept="true"]')).toHaveCount(3); + await expect(panel.locator(".tide-home-stamp .tide-stamp")).toHaveAttribute("data-press", "true"); + await expect(panel.locator(".tide-home-sub")).toHaveText(`${route.length} decisions · the Tidekeeper’s way`); + await expect(panel.getByRole("button", { name: "Take it to Bram", exact: true })).toHaveClass(/exp-primary/); + await expect(panel.getByRole("button", { name: "See the tide log", exact: true })).toHaveClass(/exp-secondary/); + await expect(page.getByTestId("expedition-feedback")).toHaveClass(/exp-sr-only/); + await expect(panel.locator(".tide-home-note")).toHaveText("Home with Beacon Lens. Bram can shelve it today."); + assert.ok(await panel.evaluate(panel => { + const viewport = panel.getBoundingClientRect(); + return [...panel.querySelectorAll(".tide-list .tide-ask-mark, .tide-home-stamp .tide-stamp")].every(marker => { + const bounds = marker.getBoundingClientRect(); + return bounds.top >= viewport.top && bounds.bottom <= viewport.bottom && bounds.left >= viewport.left && bounds.right <= viewport.right; + }); + }), "automatic return shows every arrival marker and the stamp"); + await expect(panel.locator(".tide-list")).toHaveAttribute("data-arrival", "true"); + assert.deepEqual(await panel.locator(".tide-list .tide-ask-mark").evaluateAll(markers => markers.map(marker => getComputedStyle(marker).animationDelay)), ["0.36s", "0.48s", "0.6s"]); + await checkPanel(page, "Home sheet"); + await captureLayouts(page, "coming-home", async () => { + await checkPanel(page, "Home sheet"); + if (page.viewportSize()!.height <= 500) { + assert.equal(await panel.evaluate(node => node.scrollHeight > node.clientHeight + 1), false, "landscape Home sheet needs no scrolling"); + await expect(panel.getByRole("button", { name: "Take it to Bram", exact: true })).toBeInViewport({ ratio: 1 }); + await expect(panel.getByRole("button", { name: "See the tide log", exact: true })).toBeInViewport({ ratio: 1 }); + assert.ok(await panel.evaluate(node => { + const bounds = node.getBoundingClientRect(); + return [...node.querySelectorAll(".tide-home button")].every(button => { + const action = button.getBoundingClientRect(); + return action.top >= bounds.top && action.bottom <= bounds.bottom && action.left >= bounds.left && action.right <= bounds.right; + }); + }), "landscape Home actions fit inside the panel without clipping"); + } + await checkStickyPanel(page, "Home sheet"); + }); + await page.emulateMedia({ reducedMotion: "reduce" }); + assert.deepEqual(await panel.locator(".tide-list .tide-ask-mark, .tide-home-stamp .tide-stamp").evaluateAll(markers => markers.map(marker => getComputedStyle(marker).animationName)), ["none", "none", "none", "none"], "reduced motion shows the complete Home result without arrival animations"); + await page.emulateMedia({ reducedMotion: "no-preference" }); + await panel.getByRole("button", { name: "See the tide log", exact: true }).click(); + await expect(panel.getByRole("heading", { name: "Bram’s tide log", exact: true })).toBeVisible(); + await expect(panel.getByRole("heading", { name: card.name, exact: true })).toBeVisible(); + await expect.poll(() => panel.evaluate(node => node.scrollTop)).toBe(0); + const disabledPages = panel.locator('.tide-pages button[aria-disabled="true"]'); + await expect(disabledPages).not.toHaveCount(0); + assert.ok(await disabledPages.evaluateAll(buttons => buttons.every(button => { + const style = getComputedStyle(button); + const luminance = (color: string) => color.match(/[\d.]+/g)!.slice(0, 3).map(Number).map(channel => { + const value = channel / 255; + return value <= .04045 ? value / 12.92 : ((value + .055) / 1.055) ** 2.4; + }).reduce((sum, value, index) => sum + value * [.2126, .7152, .0722][index]!, 0); + const ink = luminance(style.color), surface = luminance(style.backgroundColor); + return Number(style.opacity) === 1 && (Math.max(ink, surface) + .05) / (Math.min(ink, surface) + .05) >= 3; + })), "disabled page pills keep at least 3:1 text contrast without opacity fading"); + await expect(panel.locator(".tide-sub").first()).toHaveText("1 tide sailed · 3 asks kept · 1 with all three"); + await expect(panel.locator(".tide-facts > div").filter({ has: page.locator("dt", { hasText: /^Decisions$/ }) }).locator("dd")).toHaveText(String(route.length)); + await expect(panel.getByText("Mochi matched the Tidekeeper’s way.", { exact: true })).toBeVisible(); + await expect(panel.locator(".tide-list")).not.toHaveAttribute("data-arrival", "true"); + await expect(panel.locator(".tide-page-stamp .tide-stamp")).not.toHaveAttribute("data-press", "true"); + await checkStickyPanel(page, "tide log"); + let entries = await page.evaluate(key => JSON.parse(localStorage.getItem(key) ?? "[]"), logKey); + assert.equal(entries.length, 1); + assert.equal(entries[0].day, day); + assert.equal(entries[0].cardId, card.id); + assert.deepEqual(entries[0].kept, [true, true, true]); + assert.equal(entries[0].decisions, route.length); + assert.equal(entries[0].outcome, "returned"); + assert.deepEqual(entries[0].commands, route); + assert.equal(await page.evaluate(key => localStorage.getItem(key), pendingKey), null); + await checkPanel(page, "log page"); + await page.screenshot({ path: join(shots, `log-page-${tag}.png`) }); + await captureLayouts(page, "log-three-kept", async () => { + await panel.locator(".tide-list").evaluate(asks => asks.scrollIntoView({ block: "end", behavior: "instant" })); + await checkPanel(page, "three-kept log"); + }); + + assert.deepEqual(await page.evaluate(key => JSON.parse(localStorage.getItem(key)!).home, saveKey), before, "the classic tide outing leaves home progress unchanged"); + await panel.getByRole("button", { name: "Sail this tide again", exact: true }).click(); + await expect(game).toHaveAttribute("data-mode", "court"); + await page.locator('button[data-command="return"]').click(); + await expect(page.getByRole("dialog", { name: "Home", exact: true })).toBeVisible(); + await expect(panel.getByRole("heading", { name: "An empty satchel keeps no asks.", exact: true })).toBeVisible(); + await expect(panel.locator('.tide-list > li[data-kept="true"]')).toHaveCount(0); + await captureLayouts(page, "classic-empty-home"); + await panel.getByRole("button", { name: "See the tide log", exact: true }).click(); + await expect(panel.locator('.tide-list > li[data-kept="true"]')).toHaveCount(3); + entries = await page.evaluate(key => JSON.parse(localStorage.getItem(key)!), logKey); + assert.equal(entries[0].attempts, 2, "a weaker replay gets its own Home result while the log retains the best"); + + await page.goto(new URL(`/outing/?play&tide-day=${nextDay}`, origin).href); + await expect(world).toHaveAttribute("data-ready", "true", { timeout: 30000 }); + await openClassic(page); + await expect(panel.getByRole("heading", { name: nextCard.name, exact: true })).toBeVisible(); + await expect(panel).toContainText(TOOL_NOTE[nextCard.tool]); + for (const ask of nextCard.asks) await expect(panel.getByText(askLine(ask, nextCard.tool), { exact: true })).toBeVisible(); + await expect(panel.locator(".tide-earlier > ul > li")).toHaveCount(1); + await captureLayouts(page, "classic-next-day"); + assert.deepEqual(await page.evaluate(key => JSON.parse(localStorage.getItem(key)!).home, saveKey), before, "next day leaves home progress unchanged"); + await panel.getByText("Earlier tides", { exact: true }).click(); + await observePops(page); + await panel.locator(".tide-earlier > ul > li").filter({ has: page.getByRole("heading", { name: card.name, exact: true }) }).getByRole("button", { name: "Sail again", exact: true }).click(); + await expect(game).toHaveAttribute("data-mode", "court"); + const restartBefore = await page.evaluate(({ logKey, pendingKey, saveKey }) => ({ + log: localStorage.getItem(logKey), pending: localStorage.getItem(pendingKey), + returns: localStorage.getItem("familiar.expedition.returns.v2:preview"), + tideReturns: localStorage.getItem("familiar.season.tide.v1:preview"), + home: JSON.parse(localStorage.getItem(saveKey)!).home, + }), { logKey, pendingKey, saveKey }); + assert.deepEqual(JSON.parse(restartBefore.pending!), { day, late: true }, "a late sailing keeps its original day"); + const restart = page.locator(".tide-outing > .tide-restart.exp-text-button"); + await expect(restart).toHaveCount(0); + await page.emulateMedia({ reducedMotion: "no-preference" }); + for (const command of slipRoute) { + await page.locator(`button[data-command="${command}"]`).click(); + await expect(game).toHaveAttribute("data-busy", "false", { timeout: 15000 }); + } + await expect(asks.locator('li[data-status="slipped"]')).not.toHaveCount(0); + await expect(restart).toHaveText("Start this tide over"); + await page.evaluate(() => { + window.restartBusySeen = false; + const game = document.querySelector('[data-testid="expedition-game"]')!; + new MutationObserver(() => { + const restart = document.querySelector(".tide-outing > .tide-restart"); + if (game.getAttribute("data-busy") === "true" && restart?.disabled) window.restartBusySeen = true; + }).observe(game, { attributes: true, subtree: true, attributeFilter: ["data-busy", "disabled"] }); + }); + await page.locator('button[data-command="wait"]').click(); + await expect(game).toHaveAttribute("data-busy", "false", { timeout: 15000 }); + await expect(restart).toBeEnabled(); + assert.equal(await page.evaluate(() => window.restartBusySeen), true, "restart was disabled during the observed busy window"); + await expect(asks.locator('[data-holding="true"]')).not.toHaveCount(0); + await expect(asks.locator('[data-status="slipped"] .tide-sr').first()).toHaveText(" (slipped)"); + await captureLayouts(page, "holding-slipped", () => checkRestartLayout(page, "holding/slipped strip")); + await checkRestartLayout(page, tag); + await page.screenshot({ path: join(shots, `restart-${tag}.png`) }); + await page.setViewportSize({ width: 1280, height: 800 }); + await checkRestartLayout(page, "1280x800"); + await page.screenshot({ path: join(shots, "restart-1280x800.png") }); + await page.setViewportSize(viewport); + const popsBeforeRestart = await page.evaluate(() => window.tidePops.length); + await restart.click(); + + const assertRestarted = async (label: string) => { + await expect(game).toHaveAttribute("data-mode", "court"); + await expect(game).toHaveAttribute("data-busy", "false"); + await expect(asks.locator('li[data-status="open"]')).toHaveCount(3); + // The HUD names the next decision, so an untouched outing shows 1 of 24. + await expect(page.locator('.exp-hud[aria-label="Expedition status"]')).toContainText(`Low tide · 1 of ${TURN_LIMIT}`); + await expect(page.getByTestId("expedition-feedback")).toHaveText("Mochi sets out again. The asks are open."); + await expect(restart).toHaveCount(0); + const after = await page.evaluate(({ logKey, pendingKey, saveKey }) => ({ + log: localStorage.getItem(logKey), pending: localStorage.getItem(pendingKey), + returns: localStorage.getItem("familiar.expedition.returns.v2:preview"), + tideReturns: localStorage.getItem("familiar.season.tide.v1:preview"), + home: JSON.parse(localStorage.getItem(saveKey)!).home, + active: JSON.parse(localStorage.getItem(saveKey)!).active, + }), { logKey, pendingKey, saveKey }); + const { active, ...unchanged } = after; + assert.deepEqual(unchanged, restartBefore, `${label}: log, pending marker, both return records and home are unchanged`); + assert.equal(JSON.parse(after.log!).length, entries.length, `${label}: no log entry was added`); + assert.deepEqual(JSON.parse(after.log!), entries, `${label}: log contents are unchanged`); + assert.equal(active.state.turn, 0); + assert.deepEqual(active.state.commands, []); + assert.equal(active.state.tool, card.tool); + }; + await assertRestarted("text restart"); + await expect(asks.locator("[data-motion]")).toHaveCount(0); + assert.equal(await page.evaluate(() => window.tidePops.length), popsBeforeRestart, "restart does not pop the reset strip"); + + await page.emulateMedia({ reducedMotion: "reduce" }); + await page.locator('button[data-command="wait"]').click(); + await expect(game).toHaveAttribute("data-busy", "false", { timeout: 15000 }); + await page.getByRole("button", { name: "Game menu", exact: true }).click(); + const menuRestart = panel.getByRole("button", { name: "Start this tide over", exact: true }); + const back = panel.getByRole("button", { name: "Back to Mochi", exact: true }); + await expect(menuRestart).toBeVisible(); + await captureLayouts(page, "classic-restart-menu"); + const menuButton = await menuRestart.boundingBox(), backButton = await back.boundingBox(); + assert.ok(menuButton && backButton && menuButton.y + menuButton.height <= backButton.y, "menu restart is above Back to Mochi"); + await menuRestart.click(); + await expect(panel).toHaveCount(0); + await assertRestarted("menu restart"); + + const seedHarbor = async (tideDay: number, log: TideEntry[]) => { + await page.evaluate(({ saveKey, logKey, pendingKey, log }) => { + const save = JSON.parse(localStorage.getItem(saveKey)!); + localStorage.setItem(saveKey, JSON.stringify({ ...save, active: null, last: null })); + localStorage.setItem(logKey, JSON.stringify(log)); + localStorage.removeItem(pendingKey); + localStorage.removeItem("familiar.season.tide.v1:preview"); + localStorage.removeItem("familiar.season.preview.v1"); + }, { saveKey, logKey, pendingKey, log }); + await page.goto(new URL(`/outing/?play&tide-day=${tideDay}`, origin).href); + await expect(world).toHaveAttribute("data-ready", "true", { timeout: 30000 }); + await expect(game).toHaveAttribute("data-mode", "harbor"); + }; + const partialRoute = solve(card.tool, [card.asks[0]])!; + const partial = entryFor(day, partialRoute); + assert.deepEqual(partial.kept, [true, false, true]); + + const oldDay = day - 2, oldCard = cardForDay(oldDay); + await seedHarbor(nextDay, [entryFor(oldDay, solve(oldCard.tool, oldCard.asks)!), partial]); + await openClassic(page); + await panel.getByText("Earlier tides", { exact: true }).click(); + const rows = panel.locator(".tide-earlier > ul > li"); + await expect(rows).toHaveCount(3); + const missed = rows.filter({ hasText: "Not sailed" }); + await expect(missed).toHaveCount(1); + const sailLate = missed.getByRole("button", { name: "Sail late", exact: true }); + await expect(sailLate).toHaveClass("exp-text-button"); + assert.ok(await sailLate.evaluate(button => button.getBoundingClientRect().width < button.closest("li")!.getBoundingClientRect().width / 2), "missed tide's sail action is a small row button"); + await captureLayouts(page, "classic-earlier-gap"); + await sailLate.click(); + assert.deepEqual(await page.evaluate(key => JSON.parse(localStorage.getItem(key)!), pendingKey), { day: day - 1, late: true }, "missed day sails with its own late marker"); + + await seedHarbor(nextDay, [partial]); + await page.emulateMedia({ reducedMotion: "no-preference" }); + await openClassic(page); + await observePops(page); + await panel.getByRole("button", { name: "Sail today’s tide", exact: true }).click(); + await expect(game).toHaveAttribute("data-mode", "court"); + await expect(asks.locator("[data-motion]")).toHaveCount(0); + assert.deepEqual(await page.evaluate(() => window.tidePops), [], "holding on first render has no pop"); + const bridgeRoute: Command[] = ["step:west", "wait", "step:east", "wait", "wait", "wait", "step:west", "wait", "step:east"]; + const bridgeChip = asks.locator("li").nth(1); + for (const [index, command] of bridgeRoute.entries()) { + await page.locator(`button[data-command="${command}"]`).click(); + await expect(game).toHaveAttribute("data-busy", "false", { timeout: 15000 }); + const holding = askHolds(nextCard.asks[1], replayRun(nextCard.tool, bridgeRoute.slice(0, index + 1))!); + await expect(bridgeChip).toHaveAttribute("data-holding", String(holding)); + await expect(bridgeChip.locator(".tide-sr")).toHaveText(holding ? " (holding)" : " (not yet)"); + await expect(bridgeChip.locator("svg path")).toHaveCount(holding ? 1 : 0); + await expect.poll(() => page.evaluate(() => window.tidePops)).toEqual([]); + } + await page.emulateMedia({ reducedMotion: "reduce" }); + // Another bridge cycle changes the status, with no animation under reduced motion. + for (const command of ["wait", "wait", "wait"] as Command[]) { + await page.locator(`button[data-command="${command}"]`).click(); + await expect(game).toHaveAttribute("data-busy", "false", { timeout: 15000 }); + } + await expect(bridgeChip).toHaveAttribute("data-holding", "false"); + assert.deepEqual(await asks.locator("li").evaluateAll(chips => chips.map(chip => getComputedStyle(chip).animationName)), ["none", "none", "none"], "reduced motion removes chip animations"); + for (const command of ["step:west", "wait", "step:east"] as Command[]) { + await page.locator(`button[data-command="${command}"]`).click(); + await expect(game).toHaveAttribute("data-busy", "false", { timeout: 15000 }); + } + await expect(bridgeChip).toHaveAttribute("data-holding", "true"); + await expect(asks.locator("[data-motion]")).toHaveCount(0); + await page.emulateMedia({ reducedMotion: "no-preference" }); + await expect(asks.locator("[data-motion]")).toHaveCount(0); + await page.evaluate(() => new Promise(done => requestAnimationFrame(() => requestAnimationFrame(() => done())))); + assert.deepEqual(await page.evaluate(() => window.tidePops), [], "ask status changes stay still; the Home sheet owns the arrival motion"); + await page.emulateMedia({ reducedMotion: "reduce" }); + await page.locator('button[data-command="return"]').click(); + await expect(page.getByRole("dialog", { name: "Home", exact: true })).toBeVisible(); + await expect(panel.locator(".tide-list")).toHaveAttribute("data-arrival", "true"); + await expect(panel.locator(".tide-home-stamp .tide-stamp")).not.toHaveAttribute("data-press", "true"); + assert.deepEqual(await panel.locator(".tide-list .tide-ask-mark, .tide-home-stamp .tide-stamp").evaluateAll(markers => markers.map(marker => getComputedStyle(marker).animationName)), ["none", "none", "none", "none"], "reduced-motion return is present without stamping animations"); + await captureLayouts(page, "classic-reduced-home"); + await panel.getByRole("button", { name: "See the tide log", exact: true }).click(); + await expect(panel.getByRole("heading", { name: "Bram’s tide log", exact: true })).toBeVisible(); + await expect.poll(() => panel.evaluate(node => node.scrollTop)).toBe(0); + await panel.getByRole("button", { name: "Earlier page", exact: true }).click(); + await expect(panel.getByRole("heading", { name: card.name, exact: true })).toBeVisible(); + await expect(panel.locator(".tide-list")).not.toHaveAttribute("data-arrival", "true"); + await panel.getByRole("button", { name: "Later page", exact: true }).click(); + await expect(panel.getByRole("heading", { name: nextCard.name, exact: true })).toBeVisible(); + await expect(panel.locator(".tide-list")).not.toHaveAttribute("data-arrival", "true"); + await expect(panel.locator(".tide-page-stamp .tide-stamp")).not.toHaveAttribute("data-press", "true"); + await panel.getByRole("button", { name: "Close panel", exact: true }).click(); + await page.getByRole("button", { name: "Open the tide log", exact: true }).and(page.locator(":visible")).click(); + await expect(panel.locator(".tide-list")).not.toHaveAttribute("data-arrival", "true"); + 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 }); + midnightPage.on("pageerror", error => errors.push(error.message)); + try { await checkMidnight(midnightPage, origin, mode); } + finally { await midnightPage.close(); } + } + } 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`); +} finally { + await server.close(); + console.info(`Screenshots: ${shots}`); +} diff --git a/scripts/test-tide-run-browser.ts b/scripts/test-tide-run-browser.ts new file mode 100644 index 0000000..c67b99e --- /dev/null +++ b/scripts/test-tide-run-browser.ts @@ -0,0 +1,178 @@ +/** 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 { mkdtemp } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { chromium, expect } from "@playwright/test"; +import { createServer } from "vite"; +import { VALUE, applyMove, startTide, type Move, type TideStart } from "../web/src/run/engine"; +import { cautiousMove } from "../web/src/run/bot"; +import { storyStart } from "../web/src/run/story"; + +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. */ +function route(start: TideStart) { + let state = startTide(start); + const keys: string[] = []; + while (state.outcome === "active") { + const move = cautiousMove(state, start.story ? { ...VALUE, [start.story]: 60 } : VALUE); + keys.push(KEY[move]); state = applyMove(state, move)!.after; + } + return { keys, state }; +} + +const cacheDir = await mkdtemp(join(tmpdir(), "familiar-tide-run-")); +const server = await createServer({ + root: resolve(import.meta.dir, "../web"), envDir: false, envPrefix: [], cacheDir, logLevel: "error", + server: { host: "127.0.0.1", port: 0, hmr: false, watch: null }, +}); +const bookKey = "familiar.expedition.local.v2:tide-run.v1"; +try { + await server.listen(); + const origin = new URL(server.resolvedUrls!.local[0]!); + const browser = await chromium.launch(); + try { + const page = await browser.newPage({ viewport: { width: 390, height: 844 }, hasTouch: true, reducedMotion: "reduce" }); + const errors: string[] = []; + 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 run = page.getByTestId("tide-run"), link = page.locator('[data-action="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"); + await page.keyboard.press("Enter"); + await page.locator(tide ? '[data-plank="tide"]' : '[data-plank="continue"],[data-plank="new"]').click(); + if (tide) await page.locator('[data-el="scroll"] .fo-primary').click(); + await expect(page.getByTestId("opening")).toHaveCount(0); + }; + const press = async (keys: readonly string[]) => { + await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready", "true"); + for (const key of keys) { await expect(run).toHaveAttribute("data-busy", "false"); await page.keyboard.press(key); } + await expect(run).toHaveAttribute("data-busy", "false"); + }; + const home = () => page.evaluate(() => (JSON.parse(localStorage.getItem("familiar.expedition.local.v2") ?? "null")?.home ?? { banked: [] }) as { banked: string[] }); + const failNextWrite = (key: string, filing = false) => page.evaluate(({ key, filing }) => { + const setItem = Storage.prototype.setItem; + Storage.prototype.setItem = function (name, value) { + if (name === key && (!filing || JSON.parse(value).active === null)) { Storage.prototype.setItem = setItem; throw new DOMException("Saving is blocked", "QuotaExceededError"); } + setItem.call(this, name, value); + }; + }, { key, filing }); + async function sail(start: TideStart, from = 0) { + const { keys, state } = route(start); + if (start.story) await press(keys.slice(from)); + else { + await press(keys.slice(from, -1)); + await failNextWrite(bookKey, true); + await page.keyboard.press(keys.at(-1)!); + } + await expect(run).toHaveAttribute("data-outcome", state.outcome); + await expect(run).toHaveAttribute("data-score", String(state.score)); + if (start.story === "lens") { + await page.reload(); await passTitle(); + await expect(run).toHaveAttribute("data-outcome", state.outcome); + await expect(page.getByTestId("tide-finish")).toBeVisible(); + await expect(page.locator("[data-move]")).toHaveCount(0); + await expect(page.getByTestId("tide-feedback")).toBeEmpty(); + 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(page.getByTestId("tide-finish")).toBeEnabled(); + assert.deepEqual((await home()).banked, key === bookKey ? ["lens"] : []); + } + } 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(page.getByTestId("tide-finish")).toBeEnabled(); + } + await page.getByTestId("tide-finish").click(); + await harbor(); + return state; + } + + await page.goto(new URL("/outing/", origin).href); + await passTitle(); await harbor(); + await expect(title).toHaveText("First light."); + await page.locator('[data-action="story"]').click(); + await expect(run).toHaveAttribute("data-story", "lens"); + await sail(storyStart("lens")); + 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 expect(page.locator('[data-action="tide"]')).toBeVisible(); + await expect(link).toHaveAttribute("title", "Chapter 2: What the tide brings"); + await link.click(); + await press(route(storyStart("vane")).keys.slice(0, 3)); + await page.reload(); + await passTitle(true); + await expect(run).toHaveAttribute("data-beat", "3"); + await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready", "true"); + 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(); + 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 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 expect(link).toHaveAttribute("title", "Chapter 3: The last thing"); + await link.click(); + 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 ask.locator(".exp-primary").click(); + 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); + 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.keyboard.press("Escape"); + await page.locator(".exp-departure-buttons > .exp-secondary").click(); + await expect(run).toHaveAttribute("data-seed", String(day)); + await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready", "true"); + await page.locator('[data-move="wait"]').click(); + await expect(run).toHaveAttribute("data-busy", "false"); + await page.reload(); + await passTitle(true); + 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(); + await expect(run).toHaveAttribute("data-seed", String(day)); + await expect(run).toHaveAttribute("data-beat", "1"); + await expect(page.getByTestId("tide-world")).toHaveAttribute("data-ready", "true"); + await page.locator('[data-move="home"]').click(); + await expect(sheet).toBeVisible(); + await expect(sheet.locator(".tide-home-note")).toHaveText("A practice tide: banked 0. Today’s first tide is the one that counts."); + const practiced = await page.evaluate(key => JSON.parse(localStorage.getItem(key)!), bookKey); + assert.equal(practiced.active, null); + assert.deepEqual(practiced.days, book.days); + assert.notEqual(daily.moves.length, 2); + assert.deepEqual(errors, []); + console.info("tide run: three story tides, finished reload, failed-save retries, leave and resume, daily Home and log, and practice preserving the first tide passed on a device harbor"); + } finally { await browser.close(); } +} finally { await server.close(); } diff --git a/web/DESIGN.md b/web/DESIGN.md index 74ec543..3c200da 100644 --- a/web/DESIGN.md +++ b/web/DESIGN.md @@ -14,6 +14,24 @@ At home, Beacon, Bram, Workbench and Satchel are places in the scene. The primar 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`. +## Interface system — November 14 + +The painted world already matches the Pocket Harbor concept; the interface layer on top follows one system so it reads as part of the same object. + +- **Surfaces.** Cards are `#fbf3e2` with ink `#263e32`, secondary ink `#4f5d52` and hairlines `#e6d6b4`; radius 22px (20px under 480px), no border, one shadow (`0 14px 34px rgba(64,40,18,.20), 0 2px 6px rgba(64,40,18,.12)`). Panels, Today's tide, the tide log, the Home sheet, the harbor card and the move tray are all this card, opaque, never frosted. +- **Buttons.** One primary per surface: a deep-green pill (`#2b5f4d`, light top edge, darker bevel, cream Fraunces 650 18px, 20px leading line icon, 52px tall, 56px on touch). At most two secondaries: cream pills with a 1.5px tan border, Fraunces 600 17px. Quiet actions are Figtree 600 15px underlined links. Nothing interactive is smaller than 44×44; no text is smaller than 12px. Button text never wraps. +- **Icons.** One inline SVG line family (24 viewBox, 1.8 stroke, round caps, `currentColor`) for controls; painted art for things in the world. No Unicode glyphs or emoji as icons. +- **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. + +**Coming home** is the peak of the loop: a centred Home sheet with the day's stamp, the three asks, a large result line and the next action (Take it to Bram, or Sail again). All three kept shows Mochi's proud portrait. Closing any panel returns focus to whatever opened it. + +**The court** keeps the board clear: a Mochi status card (portrait, tide line, pips for Resolve, satchel and tool, plus one hidden sentence that reads the whole status), the surge forecast in plain words ("Next wave: left lane"), and the Tidekeeper's asks as painted-icon chips inside the move tray beside the controls. + +**Painted UI art** (gpt-6-astra masters in `assets/source/ui/`) shares the felt-and-clay world's light and materials: four driftwood signs, three Mochi portraits (default, splashed after a splash, proud) and twelve ask icons. Text stays code-native on every sign and chip. + ## 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. diff --git a/web/PRODUCT.md b/web/PRODUCT.md index 16d6184..48a05a9 100644 --- a/web/PRODUCT.md +++ b/web/PRODUCT.md @@ -16,7 +16,9 @@ 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. Today’s Tide is shown as coming soon and is not playable. 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; 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. + +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. ## Operating Context First Light fills the desktop viewport and fits mobile portrait/landscape. Keep the whole page from scrolling; useful contained menus may scroll. The current court connects three columns of platforms across two banks. Each decision advances the tide; the marked source predicts the next wave, which moves the bridge and exposes discoveries. Retrieved cargo must reach the dock. Wind Gate adds a wheel that changes source-to-exit routing. Testnet only; public RPC, no indexer, no paid infrastructure. Hundreds of players and tens concurrently are a design target, not measured capacity. diff --git a/web/assets/source/README.md b/web/assets/source/README.md index 5647729..fd2c1ab 100644 --- a/web/assets/source/README.md +++ b/web/assets/source/README.md @@ -9,3 +9,11 @@ The [First Light provenance record](../../public/assets/first-light-motion/prove Run `bun scripts/optimize-expedition-assets.ts` to regenerate the eleven WebPs in `web/public/assets/expedition/runtime/` using cwebp. In the [encoding manifest](../../public/assets/expedition/runtime/manifest.json), source paths are relative to `web/` and output paths to `web/public/`. Five inputs also appear at full size in the game or introduction. `season/` holds the five Season 2 icon masters (glass, reed, Bram's shelf and till, Mochi's purse, the wish token), generated with gpt-6-astra through the Codex CLI; prompts and original paths are in the [season provenance record](../../public/assets/season/provenance.json). Run `bun scripts/optimize-season-assets.ts` to regenerate the WebPs and manifest in `web/public/assets/season/`; it removes the cream backdrop by corner flood fill and needs ImageMagick and cwebp. + +`tide/` holds twenty PNG masters (the Tidekeeper's ask header, Bram's log cover and page, three seals, and fourteen card pictures), generated with gpt-6-astra through the Codex CLI; prompts and original paths are in the [tide provenance record](../../public/assets/tide/provenance.json). Run `bun scripts/optimize-tide-assets.ts` to regenerate the WebPs and manifest in `web/public/assets/tide/` using ImageMagick and cwebp; the header, log assets and seals get transparent backdrops, while card pictures keep their cream backdrop. + +`title/` holds eight title signpost PNG masters: four walnut menu planks, the post, bell, sound tag and parchment sheet. Prompts, references and source paths are in the [title provenance record](../../public/assets/title/provenance.json). Run `bun --no-env-file scripts/optimize-title-assets.ts` to regenerate the eight WebPs and manifest in `web/public/assets/title/` using ImageMagick and cwebp; four-corner flood fill removes the cream backdrop, then alpha erosion and blur clean the edges before trimming and resizing. Masters remain byte-identical. + +`ui/` holds nineteen PNG masters: four harbor place signs, three interchangeable Mochi portraits and twelve Tidekeeper ask icons. Prompts, references and source hashes are in the [UI provenance record](../../public/assets/ui/provenance.json). Run `bun --no-env-file scripts/optimize-ui-assets.ts` to regenerate the WebPs and manifest in `web/public/assets/ui/` using ImageMagick and cwebp; four-corner flood fill and tuned alpha cleanup remove the cream backdrop. Signs are trimmed to 480 px wide; portraits share one crop from the union of all three alpha bounds and fit into 256x256 transparent squares; ask icons fit into 96x96 transparent squares with a six-pixel minimum margin. Masters remain byte-identical. + +`run/` holds the original transparent PNG masters for the tide-run pearl and brass Signal Vane. Full prompts are in `run/prompts.json`; the generation session and file names are in the [run provenance record](../../public/assets/run/provenance.json). Run `bun --no-env-file scripts/optimize-run-assets.ts` to trim and fit them into 192×192 WebPs in `web/public/assets/run/` using ImageMagick and cwebp. It preserves the generated alpha, verifies transparency and source hashes, and writes the encoding manifest; masters remain byte-identical. diff --git a/web/assets/source/run/pearl.png b/web/assets/source/run/pearl.png new file mode 100644 index 0000000..f4edd4e Binary files /dev/null and b/web/assets/source/run/pearl.png differ diff --git a/web/assets/source/run/prompts.json b/web/assets/source/run/prompts.json new file mode 100644 index 0000000..2d3f46f --- /dev/null +++ b/web/assets/source/run/prompts.json @@ -0,0 +1,4 @@ +{ + "pearl": "Use case: stylized-concept. Asset type: one collectible prize sprite for Familiar, a cozy painted miniature harbor game. Create a single small pearl on real transparent alpha. Subject: one plump slightly irregular ivory pearl, softly luminous nacre with gentle sea-glass green and blush-pink reflected color in the lower shadow, warm cream upper-left highlight, tactile fine handmade felt-and-clay surface, rounded and simple. Match the existing Familiar sea-glass and tied reed art described here: soft woolly edges, fine visible fibers, muted warm coastal palette, soft golden light from upper left, chunky handmade stop-motion miniature, no hard outlines. Composition: square 1024x1024, single pearl centered with about 15 percent clear margin, three-quarter view, silhouette clear when displayed at 40px. A small faint contact shadow is allowed immediately under the pearl on transparent alpha. No shell, pedestal, scenery, letters, numbers, logos, border, background color, checkerboard or glow surrounding the object. Real transparent pixels outside the object.", + "vane": "Use case: stylized-concept. Asset type: a single collectible prize sprite for Familiar, a cozy painted miniature harbor game. Paint the brass Signal Vane: a small handcrafted nautical weather vane pointing right, chunky horizontal warm brass arrow with a broad triangular arrow head on the right, two simple soft verdigris teal feather fins at the left, rounded central brass rivet, a short stout brass vertical spindle below, ending in a small foot. Silhouette akin to a tiny recovered weathervane, simple and believable, no compass letters. Match Familiar's existing sea-glass and tied reeds: handmade felt-and-clay stop-motion miniature with tactile fine fibers and subtly brushed aged brass, softly rounded edges, muted warm coastal colors, soft golden upper-left light, gentle shadow to lower right. Square composition 1024x1024. Center the complete single object, about 75 percent frame width and 65 percent height, generous transparent margin; three-quarter frontal view, shaft almost horizontal, silhouette clear at 45px. Background must be true transparent alpha, empty transparent pixels around the cutout. No scenery, floating particles, extra objects, typography, numbers, frame, border, checkerboard or painted background." +} diff --git a/web/assets/source/run/vane.png b/web/assets/source/run/vane.png new file mode 100644 index 0000000..3ac022d Binary files /dev/null and b/web/assets/source/run/vane.png differ diff --git a/web/assets/source/tide/card-brams-bridge.png b/web/assets/source/tide/card-brams-bridge.png new file mode 100644 index 0000000..0feb000 Binary files /dev/null and b/web/assets/source/tide/card-brams-bridge.png differ diff --git a/web/assets/source/tide/card-coiled-rope.png b/web/assets/source/tide/card-coiled-rope.png new file mode 100644 index 0000000..69aa72b Binary files /dev/null and b/web/assets/source/tide/card-coiled-rope.png differ diff --git a/web/assets/source/tide/card-dry-and-tidy.png b/web/assets/source/tide/card-dry-and-tidy.png new file mode 100644 index 0000000..4c684a0 Binary files /dev/null and b/web/assets/source/tide/card-dry-and-tidy.png differ diff --git a/web/assets/source/tide/card-dry-paws.png b/web/assets/source/tide/card-dry-paws.png new file mode 100644 index 0000000..32616ca Binary files /dev/null and b/web/assets/source/tide/card-dry-paws.png differ diff --git a/web/assets/source/tide/card-every-source.png b/web/assets/source/tide/card-every-source.png new file mode 100644 index 0000000..e41e8b4 Binary files /dev/null and b/web/assets/source/tide/card-every-source.png differ diff --git a/web/assets/source/tide/card-full-satchel.png b/web/assets/source/tide/card-full-satchel.png new file mode 100644 index 0000000..287c27b Binary files /dev/null and b/web/assets/source/tide/card-full-satchel.png differ diff --git a/web/assets/source/tide/card-lantern-haul.png b/web/assets/source/tide/card-lantern-haul.png new file mode 100644 index 0000000..31513ea Binary files /dev/null and b/web/assets/source/tide/card-lantern-haul.png differ diff --git a/web/assets/source/tide/card-left-for-bram.png b/web/assets/source/tide/card-left-for-bram.png new file mode 100644 index 0000000..9c13002 Binary files /dev/null and b/web/assets/source/tide/card-left-for-bram.png differ diff --git a/web/assets/source/tide/card-no-waiting.png b/web/assets/source/tide/card-no-waiting.png new file mode 100644 index 0000000..b19980e Binary files /dev/null and b/web/assets/source/tide/card-no-waiting.png differ diff --git a/web/assets/source/tide/card-once-across.png b/web/assets/source/tide/card-once-across.png new file mode 100644 index 0000000..d6227ec Binary files /dev/null and b/web/assets/source/tide/card-once-across.png differ diff --git a/web/assets/source/tide/card-quiet-shell.png b/web/assets/source/tide/card-quiet-shell.png new file mode 100644 index 0000000..cafab03 Binary files /dev/null and b/web/assets/source/tide/card-quiet-shell.png differ diff --git a/web/assets/source/tide/card-surf-home.png b/web/assets/source/tide/card-surf-home.png new file mode 100644 index 0000000..a37c77f Binary files /dev/null and b/web/assets/source/tide/card-surf-home.png differ diff --git a/web/assets/source/tide/card-tidy-tide.png b/web/assets/source/tide/card-tidy-tide.png new file mode 100644 index 0000000..a1d85e6 Binary files /dev/null and b/web/assets/source/tide/card-tidy-tide.png differ diff --git a/web/assets/source/tide/card-wake-both-shells.png b/web/assets/source/tide/card-wake-both-shells.png new file mode 100644 index 0000000..a4494b9 Binary files /dev/null and b/web/assets/source/tide/card-wake-both-shells.png differ diff --git a/web/assets/source/tide/keeper-ask.png b/web/assets/source/tide/keeper-ask.png new file mode 100644 index 0000000..b3cb784 Binary files /dev/null and b/web/assets/source/tide/keeper-ask.png differ diff --git a/web/assets/source/tide/log-cover.png b/web/assets/source/tide/log-cover.png new file mode 100644 index 0000000..95f470a Binary files /dev/null and b/web/assets/source/tide/log-cover.png differ diff --git a/web/assets/source/tide/log-page.png b/web/assets/source/tide/log-page.png new file mode 100644 index 0000000..511f6e4 Binary files /dev/null and b/web/assets/source/tide/log-page.png differ diff --git a/web/assets/source/tide/seal-all-three.png b/web/assets/source/tide/seal-all-three.png new file mode 100644 index 0000000..7742fda Binary files /dev/null and b/web/assets/source/tide/seal-all-three.png differ diff --git a/web/assets/source/tide/seal-kept.png b/web/assets/source/tide/seal-kept.png new file mode 100644 index 0000000..6f672a0 Binary files /dev/null and b/web/assets/source/tide/seal-kept.png differ diff --git a/web/assets/source/tide/seal-slipped.png b/web/assets/source/tide/seal-slipped.png new file mode 100644 index 0000000..b8e84bd Binary files /dev/null and b/web/assets/source/tide/seal-slipped.png differ diff --git a/web/assets/source/title/title-bell.png b/web/assets/source/title/title-bell.png new file mode 100644 index 0000000..5295ccb Binary files /dev/null and b/web/assets/source/title/title-bell.png differ diff --git a/web/assets/source/title/title-paper.png b/web/assets/source/title/title-paper.png new file mode 100644 index 0000000..02c240b Binary files /dev/null and b/web/assets/source/title/title-paper.png differ diff --git a/web/assets/source/title/title-plank-1.png b/web/assets/source/title/title-plank-1.png new file mode 100644 index 0000000..1630a82 Binary files /dev/null and b/web/assets/source/title/title-plank-1.png differ diff --git a/web/assets/source/title/title-plank-2.png b/web/assets/source/title/title-plank-2.png new file mode 100644 index 0000000..d1fe43b Binary files /dev/null and b/web/assets/source/title/title-plank-2.png differ diff --git a/web/assets/source/title/title-plank-3.png b/web/assets/source/title/title-plank-3.png new file mode 100644 index 0000000..3e5bd4d Binary files /dev/null and b/web/assets/source/title/title-plank-3.png differ diff --git a/web/assets/source/title/title-plank-4.png b/web/assets/source/title/title-plank-4.png new file mode 100644 index 0000000..7c81355 Binary files /dev/null and b/web/assets/source/title/title-plank-4.png differ diff --git a/web/assets/source/title/title-post.png b/web/assets/source/title/title-post.png new file mode 100644 index 0000000..39d2e03 Binary files /dev/null and b/web/assets/source/title/title-post.png differ diff --git a/web/assets/source/title/title-tag.png b/web/assets/source/title/title-tag.png new file mode 100644 index 0000000..c333f53 Binary files /dev/null and b/web/assets/source/title/title-tag.png differ diff --git a/web/assets/source/ui/ask-all-marks.png b/web/assets/source/ui/ask-all-marks.png new file mode 100644 index 0000000..579596d Binary files /dev/null and b/web/assets/source/ui/ask-all-marks.png differ diff --git a/web/assets/source/ui/ask-both-shells.png b/web/assets/source/ui/ask-both-shells.png new file mode 100644 index 0000000..38c3d5b Binary files /dev/null and b/web/assets/source/ui/ask-both-shells.png differ diff --git a/web/assets/source/ui/ask-bridge.png b/web/assets/source/ui/ask-bridge.png new file mode 100644 index 0000000..179c42f Binary files /dev/null and b/web/assets/source/ui/ask-bridge.png differ diff --git a/web/assets/source/ui/ask-coiled.png b/web/assets/source/ui/ask-coiled.png new file mode 100644 index 0000000..c5f022e Binary files /dev/null and b/web/assets/source/ui/ask-coiled.png differ diff --git a/web/assets/source/ui/ask-dry.png b/web/assets/source/ui/ask-dry.png new file mode 100644 index 0000000..8eae149 Binary files /dev/null and b/web/assets/source/ui/ask-dry.png differ diff --git a/web/assets/source/ui/ask-lens.png b/web/assets/source/ui/ask-lens.png new file mode 100644 index 0000000..907d02c Binary files /dev/null and b/web/assets/source/ui/ask-lens.png differ diff --git a/web/assets/source/ui/ask-moth.png b/web/assets/source/ui/ask-moth.png new file mode 100644 index 0000000..5c76d69 Binary files /dev/null and b/web/assets/source/ui/ask-moth.png differ diff --git a/web/assets/source/ui/ask-no-wait.png b/web/assets/source/ui/ask-no-wait.png new file mode 100644 index 0000000..3797750 Binary files /dev/null and b/web/assets/source/ui/ask-no-wait.png differ diff --git a/web/assets/source/ui/ask-one-crossing.png b/web/assets/source/ui/ask-one-crossing.png new file mode 100644 index 0000000..b80e59f Binary files /dev/null and b/web/assets/source/ui/ask-one-crossing.png differ diff --git a/web/assets/source/ui/ask-shut-shell.png b/web/assets/source/ui/ask-shut-shell.png new file mode 100644 index 0000000..a1d74b1 Binary files /dev/null and b/web/assets/source/ui/ask-shut-shell.png differ diff --git a/web/assets/source/ui/ask-splash.png b/web/assets/source/ui/ask-splash.png new file mode 100644 index 0000000..5b16331 Binary files /dev/null and b/web/assets/source/ui/ask-splash.png differ diff --git a/web/assets/source/ui/ask-within.png b/web/assets/source/ui/ask-within.png new file mode 100644 index 0000000..39d4582 Binary files /dev/null and b/web/assets/source/ui/ask-within.png differ diff --git a/web/assets/source/ui/mochi-portrait-proud.png b/web/assets/source/ui/mochi-portrait-proud.png new file mode 100644 index 0000000..a68bfb2 Binary files /dev/null and b/web/assets/source/ui/mochi-portrait-proud.png differ diff --git a/web/assets/source/ui/mochi-portrait-splashed.png b/web/assets/source/ui/mochi-portrait-splashed.png new file mode 100644 index 0000000..8da0d1a Binary files /dev/null and b/web/assets/source/ui/mochi-portrait-splashed.png differ diff --git a/web/assets/source/ui/mochi-portrait.png b/web/assets/source/ui/mochi-portrait.png new file mode 100644 index 0000000..bd205d2 Binary files /dev/null and b/web/assets/source/ui/mochi-portrait.png differ diff --git a/web/assets/source/ui/sign-beacon.png b/web/assets/source/ui/sign-beacon.png new file mode 100644 index 0000000..ca05447 Binary files /dev/null and b/web/assets/source/ui/sign-beacon.png differ diff --git a/web/assets/source/ui/sign-bram.png b/web/assets/source/ui/sign-bram.png new file mode 100644 index 0000000..3d765bb Binary files /dev/null and b/web/assets/source/ui/sign-bram.png differ diff --git a/web/assets/source/ui/sign-satchel.png b/web/assets/source/ui/sign-satchel.png new file mode 100644 index 0000000..1a20988 Binary files /dev/null and b/web/assets/source/ui/sign-satchel.png differ diff --git a/web/assets/source/ui/sign-workbench.png b/web/assets/source/ui/sign-workbench.png new file mode 100644 index 0000000..2ed6fef Binary files /dev/null and b/web/assets/source/ui/sign-workbench.png differ diff --git a/web/public/assets/run/manifest.json b/web/public/assets/run/manifest.json new file mode 100644 index 0000000..188e36f --- /dev/null +++ b/web/public/assets/run/manifest.json @@ -0,0 +1,26 @@ +{ + "purpose": "Tide-run prize derivatives; generated transparent alpha preserved", + "encoder": "ImageMagick trim, fit168 in transparent192; cwebp quality85 method6 alpha100", + "files": [ + { + "source": "assets/source/run/pearl.png", + "output": "assets/run/pearl.webp", + "sourceSha256": "c5e7d222e3183d2e819b3803a41c590f31b2392550658150b0f4f3dc45509c72", + "sha256": "fc051c55e3f807609714f71fc3d57ca9d8fc88c59d5323c8a4e53fe6dc9db6ba", + "sourceBytes": 1007738, + "bytes": 4634, + "width": 192, + "height": 192 + }, + { + "source": "assets/source/run/vane.png", + "output": "assets/run/vane.webp", + "sourceSha256": "0e823f929980bbbdb0b53aae3f5cc39c9b723379eea7bcb1b636f55fec91593c", + "sha256": "5ec1725419db2c9550851e8b185c0739fff24e7059ac301e87de268255e93609", + "sourceBytes": 831545, + "bytes": 5392, + "width": 192, + "height": 192 + } + ] +} diff --git a/web/public/assets/run/pearl.webp b/web/public/assets/run/pearl.webp new file mode 100644 index 0000000..79894d8 Binary files /dev/null and b/web/public/assets/run/pearl.webp differ diff --git a/web/public/assets/run/provenance.json b/web/public/assets/run/provenance.json new file mode 100644 index 0000000..b0289c3 --- /dev/null +++ b/web/public/assets/run/provenance.json @@ -0,0 +1,29 @@ +{ + "created": "2026-11-14", + "purpose": "Familiar tide-run pearl and brass Signal Vane prize sprites", + "generator": { + "tool": "Codex CLI codex-cli 0.169.0 (`codex exec`, image generation tool)", + "model": "gpt-6-astra", + "session": "01a1d9e7-6ab4-7400-9ef0-bd2f2a6b59f5", + "transparent_background": true + }, + "styleReferences": [ + "web/public/assets/season/glass.webp", + "web/public/assets/season/reed.webp" + ], + "referenceUse": "References visually inspected and described in the prompts; no reference file uploaded. Pocket Harbor concept viewed only, never copied or modified.", + "delivery": "Original transparent PNG masters preserved byte-for-byte; trimmed and fitted into 192px WebP derivatives with original alpha. See manifest.json and scripts/optimize-run-assets.ts.", + "prompts": "web/assets/source/run/prompts.json", + "files": { + "pearl.webp": { + "master": "web/assets/source/run/pearl.png", + "promptKey": "pearl", + "generatedFile": "exec-38e02d31-94a2-4883-91bf-537c97af66c2.png" + }, + "vane.webp": { + "master": "web/assets/source/run/vane.png", + "promptKey": "vane", + "generatedFile": "exec-653e41da-a764-474e-a48b-08f38797a17e.png" + } + } +} diff --git a/web/public/assets/run/vane.webp b/web/public/assets/run/vane.webp new file mode 100644 index 0000000..d71a10c Binary files /dev/null and b/web/public/assets/run/vane.webp differ diff --git a/web/public/assets/tide/card-brams-bridge.webp b/web/public/assets/tide/card-brams-bridge.webp new file mode 100644 index 0000000..dfb78c1 Binary files /dev/null and b/web/public/assets/tide/card-brams-bridge.webp differ diff --git a/web/public/assets/tide/card-coiled-rope.webp b/web/public/assets/tide/card-coiled-rope.webp new file mode 100644 index 0000000..b862d5d Binary files /dev/null and b/web/public/assets/tide/card-coiled-rope.webp differ diff --git a/web/public/assets/tide/card-dry-and-tidy.webp b/web/public/assets/tide/card-dry-and-tidy.webp new file mode 100644 index 0000000..d6e5951 Binary files /dev/null and b/web/public/assets/tide/card-dry-and-tidy.webp differ diff --git a/web/public/assets/tide/card-dry-paws.webp b/web/public/assets/tide/card-dry-paws.webp new file mode 100644 index 0000000..9164647 Binary files /dev/null and b/web/public/assets/tide/card-dry-paws.webp differ diff --git a/web/public/assets/tide/card-every-source.webp b/web/public/assets/tide/card-every-source.webp new file mode 100644 index 0000000..9af6a85 Binary files /dev/null and b/web/public/assets/tide/card-every-source.webp differ diff --git a/web/public/assets/tide/card-full-satchel.webp b/web/public/assets/tide/card-full-satchel.webp new file mode 100644 index 0000000..0f81de3 Binary files /dev/null and b/web/public/assets/tide/card-full-satchel.webp differ diff --git a/web/public/assets/tide/card-lantern-haul.webp b/web/public/assets/tide/card-lantern-haul.webp new file mode 100644 index 0000000..a0dcc77 Binary files /dev/null and b/web/public/assets/tide/card-lantern-haul.webp differ diff --git a/web/public/assets/tide/card-left-for-bram.webp b/web/public/assets/tide/card-left-for-bram.webp new file mode 100644 index 0000000..98d18c0 Binary files /dev/null and b/web/public/assets/tide/card-left-for-bram.webp differ diff --git a/web/public/assets/tide/card-no-waiting.webp b/web/public/assets/tide/card-no-waiting.webp new file mode 100644 index 0000000..5ad8870 Binary files /dev/null and b/web/public/assets/tide/card-no-waiting.webp differ diff --git a/web/public/assets/tide/card-once-across.webp b/web/public/assets/tide/card-once-across.webp new file mode 100644 index 0000000..8856c20 Binary files /dev/null and b/web/public/assets/tide/card-once-across.webp differ diff --git a/web/public/assets/tide/card-quiet-shell.webp b/web/public/assets/tide/card-quiet-shell.webp new file mode 100644 index 0000000..5cefe8a Binary files /dev/null and b/web/public/assets/tide/card-quiet-shell.webp differ diff --git a/web/public/assets/tide/card-surf-home.webp b/web/public/assets/tide/card-surf-home.webp new file mode 100644 index 0000000..aa701c7 Binary files /dev/null and b/web/public/assets/tide/card-surf-home.webp differ diff --git a/web/public/assets/tide/card-tidy-tide.webp b/web/public/assets/tide/card-tidy-tide.webp new file mode 100644 index 0000000..663195f Binary files /dev/null and b/web/public/assets/tide/card-tidy-tide.webp differ diff --git a/web/public/assets/tide/card-wake-both-shells.webp b/web/public/assets/tide/card-wake-both-shells.webp new file mode 100644 index 0000000..4f004f3 Binary files /dev/null and b/web/public/assets/tide/card-wake-both-shells.webp differ diff --git a/web/public/assets/tide/keeper-ask.webp b/web/public/assets/tide/keeper-ask.webp new file mode 100644 index 0000000..d25996c Binary files /dev/null and b/web/public/assets/tide/keeper-ask.webp differ diff --git a/web/public/assets/tide/log-cover.webp b/web/public/assets/tide/log-cover.webp new file mode 100644 index 0000000..a2db257 Binary files /dev/null and b/web/public/assets/tide/log-cover.webp differ diff --git a/web/public/assets/tide/log-page.webp b/web/public/assets/tide/log-page.webp new file mode 100644 index 0000000..f19677f Binary files /dev/null and b/web/public/assets/tide/log-page.webp differ diff --git a/web/public/assets/tide/manifest.json b/web/public/assets/tide/manifest.json new file mode 100644 index 0000000..5de6f76 --- /dev/null +++ b/web/public/assets/tide/manifest.json @@ -0,0 +1,246 @@ +{ + "purpose": "Tide runtime artwork; opaque card pictures and alpha cut-outs with original masters preserved", + "encoder": "magick Lanczos + cwebp quality88 method6 alpha100 sharp_yuv", + "files": [ + { + "source": "assets/source/tide/card-brams-bridge.png", + "output": "assets/tide/card-brams-bridge.webp", + "sourceSha256": "491e1e0f763713d140c93aa2cb8ab7917d4e4c6422685177255010ba40934e14", + "sha256": "87abbdba0f54b797ce678e844d8739f594f8d98ac7c8e1db1e67e3de4ea700de", + "sourceBytes": 1173108, + "bytes": 24754, + "resizedTo": { + "width": 480, + "height": 480 + } + }, + { + "source": "assets/source/tide/card-coiled-rope.png", + "output": "assets/tide/card-coiled-rope.webp", + "sourceSha256": "eb9100170b2b92160559ea96659998b5d97e2a44c87a484e62121a66d8fccabb", + "sha256": "5ac25f9187b11456633b2b098fa9e8a0df2899eb4939ab6b8d588d6e34388fcc", + "sourceBytes": 1171455, + "bytes": 21120, + "resizedTo": { + "width": 480, + "height": 480 + } + }, + { + "source": "assets/source/tide/card-dry-and-tidy.png", + "output": "assets/tide/card-dry-and-tidy.webp", + "sourceSha256": "6cc3efc1c094a770eac5290e630db23a815be90316abc8ab69ca1416748cb1f7", + "sha256": "5cb27e4e4225af4ba0ed35f757d8333fd4a34c48161a46b995aee6745d37c54d", + "sourceBytes": 1211846, + "bytes": 22918, + "resizedTo": { + "width": 480, + "height": 480 + } + }, + { + "source": "assets/source/tide/card-dry-paws.png", + "output": "assets/tide/card-dry-paws.webp", + "sourceSha256": "8be8ae175a28fb947a35fce49cd1ad4885fce137ad952a6394d4433da078f871", + "sha256": "e0d3c28444736e009b925472c91d072df8f8fa00aefef11c2afd57a3e16f86d8", + "sourceBytes": 1216077, + "bytes": 24030, + "resizedTo": { + "width": 480, + "height": 480 + } + }, + { + "source": "assets/source/tide/card-every-source.png", + "output": "assets/tide/card-every-source.webp", + "sourceSha256": "5184a277dfd1de409b1980b1b55279ff7aba13713752aed3aa953882bb8960c9", + "sha256": "6334d1d3b2c5b4fca098cd97a3c635a80219122479bce9e3959ab7666efe7327", + "sourceBytes": 1190539, + "bytes": 21904, + "resizedTo": { + "width": 480, + "height": 480 + } + }, + { + "source": "assets/source/tide/card-full-satchel.png", + "output": "assets/tide/card-full-satchel.webp", + "sourceSha256": "712186f4396ae09fb88b19eff361d6a4979258f0ef4cb159ab99a3b3665c0e0d", + "sha256": "c6bf3165fbd5ed1666a89e162f3c879f21789a67a707501cc9511ab66e92f66f", + "sourceBytes": 1433834, + "bytes": 34152, + "resizedTo": { + "width": 480, + "height": 480 + } + }, + { + "source": "assets/source/tide/card-lantern-haul.png", + "output": "assets/tide/card-lantern-haul.webp", + "sourceSha256": "048c67fc6e1ccbc80bda4186e8bf48ddaee06e5160ab15d550439d81402b186d", + "sha256": "95c3fb1b3d2b5490dd876d868411edeade9d1a7eb8fdbb51594dfea2c0c3f05b", + "sourceBytes": 1404258, + "bytes": 36648, + "resizedTo": { + "width": 480, + "height": 480 + } + }, + { + "source": "assets/source/tide/card-left-for-bram.png", + "output": "assets/tide/card-left-for-bram.webp", + "sourceSha256": "80ff332f5e6aba55332d8745374ff3829c8fda0c970c312b508810be324088b8", + "sha256": "e8253681252cf033dfc7419cbb29fd443f5aed9870479c523542f14ab84ea90f", + "sourceBytes": 1207381, + "bytes": 20204, + "resizedTo": { + "width": 480, + "height": 480 + } + }, + { + "source": "assets/source/tide/card-no-waiting.png", + "output": "assets/tide/card-no-waiting.webp", + "sourceSha256": "f1a3be1be0bca425e76f81423bbcfdd755b5ed88689323ab19e73b9f8a474aba", + "sha256": "17c49fa356802aa256a1c79576289c29ae0c0685132f8e01e07c7b93cd3ccde5", + "sourceBytes": 1201643, + "bytes": 23874, + "resizedTo": { + "width": 480, + "height": 480 + } + }, + { + "source": "assets/source/tide/card-once-across.png", + "output": "assets/tide/card-once-across.webp", + "sourceSha256": "6cb501ec52341f527a0bcaea273964553d108e59224b435ca08bb71ecff2f2cb", + "sha256": "4e024f4d711c5301575058ba33ee900a5af8844e7eed01d44e58308477cfabfa", + "sourceBytes": 1215052, + "bytes": 25388, + "resizedTo": { + "width": 480, + "height": 480 + } + }, + { + "source": "assets/source/tide/card-quiet-shell.png", + "output": "assets/tide/card-quiet-shell.webp", + "sourceSha256": "64a4350d0ed723085e58cb11757037d026c7db5bab59a62e8c9c5996af92886c", + "sha256": "2dd4c5ae4fb4679994bf55a094edc08cb8b88241b72230b751366806bd261afd", + "sourceBytes": 1212642, + "bytes": 22364, + "resizedTo": { + "width": 480, + "height": 480 + } + }, + { + "source": "assets/source/tide/card-surf-home.png", + "output": "assets/tide/card-surf-home.webp", + "sourceSha256": "911dacdfc689778cc53069b97f41e3b0dd0ff3b6c6fb2a018cdb01aa3d3dd0be", + "sha256": "a023b18401da65fac17df8642f2f7abf2331474b732fd170c892985a1365f210", + "sourceBytes": 1416185, + "bytes": 29804, + "resizedTo": { + "width": 480, + "height": 480 + } + }, + { + "source": "assets/source/tide/card-tidy-tide.png", + "output": "assets/tide/card-tidy-tide.webp", + "sourceSha256": "ca7118607a175b3d59cb443ac4adefd1a3f60aad21e00de4d9b293d4b3d05284", + "sha256": "aeaa3948bf38dff20d575c1a8dd41088885dadeddf237be5cc519f2af7157d41", + "sourceBytes": 1200555, + "bytes": 21966, + "resizedTo": { + "width": 480, + "height": 480 + } + }, + { + "source": "assets/source/tide/card-wake-both-shells.png", + "output": "assets/tide/card-wake-both-shells.webp", + "sourceSha256": "2d777a705a0512c927f855d5d29d6e551c32910d1278c95d08ecf2a6fbdac3a7", + "sha256": "41aa1cf519bbf5b3562da49d0a14fa37a34c501966879efa2979133740e8f9ec", + "sourceBytes": 1442867, + "bytes": 33908, + "resizedTo": { + "width": 480, + "height": 480 + } + }, + { + "source": "assets/source/tide/keeper-ask.png", + "output": "assets/tide/keeper-ask.webp", + "sourceSha256": "9a9ab752c4781420b6f11a6c367056bd55d52db8813eef61de62d8a2a9320485", + "sha256": "43346946bb8f34741d90f7ec797fb923df5d80a8284b429a839a16489511e0fb", + "sourceBytes": 1028457, + "bytes": 114792, + "resizedTo": { + "width": 960, + "height": 640 + } + }, + { + "source": "assets/source/tide/log-cover.png", + "output": "assets/tide/log-cover.webp", + "sourceSha256": "e7b3d6ac87bfd557cde0ffca0335ab89e555f79f47896afbdaa24dbf23812549", + "sha256": "4cc7fbb7eab29c35e5613351b11612ed69b1786015f1d16f112a5387ee83899c", + "sourceBytes": 1592022, + "bytes": 32954, + "resizedTo": { + "width": 384, + "height": 384 + } + }, + { + "source": "assets/source/tide/log-page.png", + "output": "assets/tide/log-page.webp", + "sourceSha256": "d5644fc3845dd106da3ae9853147d7a0b38a73a4ed1f214423ed20764b8964bf", + "sha256": "b846179d2e048e68bbbba5149b45fb09a133022257be94800a11461f28838907", + "sourceBytes": 1139080, + "bytes": 41618, + "resizedTo": { + "width": 900, + "height": 905 + } + }, + { + "source": "assets/source/tide/seal-all-three.png", + "output": "assets/tide/seal-all-three.webp", + "sourceSha256": "81e4d06194c726b3832948a4ed38f28c11aefdb8b59881198c60390ce7bddc4d", + "sha256": "bb5d94f932d85b9e51eeb64c923ba4fc5535fcdbf0658f4e32fb75c2fa270d88", + "sourceBytes": 1134008, + "bytes": 5722, + "resizedTo": { + "width": 168, + "height": 168 + } + }, + { + "source": "assets/source/tide/seal-kept.png", + "output": "assets/tide/seal-kept.webp", + "sourceSha256": "32e110f10fb92de976a928d7644b3c0b80c36ad675613fa171a819bbee39fab0", + "sha256": "d000367fc1c1d2a937628814cc254bc68f56630816b21ad0a149b216e40a68e8", + "sourceBytes": 1116912, + "bytes": 4748, + "resizedTo": { + "width": 168, + "height": 168 + } + }, + { + "source": "assets/source/tide/seal-slipped.png", + "output": "assets/tide/seal-slipped.webp", + "sourceSha256": "e5d651ead47ce1589d407499784a5d2a9f2396140dcb7e8015e60059081a589c", + "sha256": "475f077e10ecb3f8ba0cb505396632df642240adde88a7f5be7ed10d1dc5a192", + "sourceBytes": 1083960, + "bytes": 6122, + "resizedTo": { + "width": 168, + "height": 168 + } + } + ] +} diff --git a/web/public/assets/tide/provenance.json b/web/public/assets/tide/provenance.json new file mode 100644 index 0000000..f2f101a --- /dev/null +++ b/web/public/assets/tide/provenance.json @@ -0,0 +1,221 @@ +{ + "created": "2026-11-14", + "purpose": "Familiar tide artwork: the Tidekeeper's ask header, Bram's log cover and page, three seals and fourteen card pictures", + "generator": { + "tool": "Codex CLI (`codex exec`, image_gen.imagegen built-in tool)", + "model": "gpt-6-astra", + "reasoningEffort": "ultra", + "cliVersion": "0.169.0", + "sessions": [ + { + "id": "01a1d8b2-0b79-7580-acf8-887eafdc0889", + "files": [ + "card-surf-home.webp", + "keeper-ask.webp" + ] + }, + { + "id": "01a1d8b2-0c2b-7523-8372-b9afa50d2b3c", + "files": [ + "log-cover.webp", + "log-page.webp" + ] + }, + { + "id": "01a1d8bb-0b73-79d0-8e15-aa74d82bab41", + "files": [ + "card-dry-paws.webp", + "card-every-source.webp", + "card-full-satchel.webp", + "card-no-waiting.webp", + "card-wake-both-shells.webp" + ] + }, + { + "id": "01a1d8bb-0ce3-7671-95b6-07da902eaf0d", + "files": [ + "card-coiled-rope.webp", + "card-once-across.webp", + "card-quiet-shell.webp", + "card-tidy-tide.webp" + ] + }, + { + "id": "01a1d8bb-0dae-7a02-832a-dfae246e6652", + "files": [ + "card-brams-bridge.webp", + "card-dry-and-tidy.webp", + "card-lantern-haul.webp", + "card-left-for-bram.webp" + ] + }, + { + "id": "01a1d8bb-0e6d-71e3-926a-db26acdd5ffc", + "files": [ + "seal-all-three.webp", + "seal-kept.webp", + "seal-slipped.webp" + ] + } + ] + }, + "styleReferences": [ + "web/assets/source/expedition/stone-island.png", + "web/assets/source/expedition/wooden-bridge.png", + "web/assets/source/first-light-motion/bram.png", + "web/assets/source/first-light-motion/lens.png", + "web/assets/source/first-light-motion/mochi.png", + "web/assets/source/first-light-motion/moth.png", + "web/assets/source/first-light-motion/shell.png", + "web/assets/source/first-light-motion/tidekeeper.png", + "web/assets/source/first-light-motion/wave.png", + "web/assets/source/season/purse.png", + "web/assets/source/season/shelf-till.png", + "web/assets/source/season/wish-token.png", + "web/assets/source/tide/card-surf-home.png", + "web/assets/source/tide/log-cover.png" + ], + "delivery": "The generated originals were 1254x1254 PNGs (keeper-ask: 1536x1024); masters were resized to 1024 px with `sips -z`. Runtime WebPs are produced by scripts/optimize-tide-assets.ts (see manifest.json); card pictures keep their cream backdrop, while the header, log assets and seals use alpha cut-outs.", + "files": { + "card-brams-bridge.webp": { + "master": "web/assets/source/tide/card-brams-bridge.png", + "prompt": "Use case: precise-object-edit. Output ONE square PNG at highest available quality. The FIRST IMAGE is the current card to correct; remaining images are supporting subject/material references only.\nThe exposed beige background of image 1 MUST CHANGE VISIBLY. It is currently too dark/yellow. Replace it with a noticeably LIGHTER, COOLER, SMOOTHER PALE CREAM FLAT FILL: EXACT #EFE4CC, sRGB RGB red239 green228 blue204. Treat this as a clean cutout of the entire diorama placed over a digital solid-color layer, NOT a studio photograph of cream paper. All open background at the top, bottom and sides must be this SAME UNVARYING FLAT PALE CREAM, without any texture, noise, grain, shadows, vignettes, warm grading, color variation or gradients. Preserve ONLY the soft small contact shadow immediately underneath the disc. Do not copy the old yellow-tinted textured background from any reference.\nKeep the entire diorama and sandstone disc's geometry and position exactly unchanged, square format, complete at x10%-90% width, disc bottom at y89%, camera slightly above at three-quarter view. Preserve all subject colors and soft upper-left light. Do NOT add surface texture or sharpen detail: preserve the fine soft reference finish rather than exaggerated grooves, embossing or glossy CGI. Handmade wool/felt where appropriate, tiny tactile details, miniature natural wood, brass and sandstone.\nNo text, letters, numbers, letterlike marks, logos, watermarks, signatures, UI, borders, scenery, extra objects, cats, ocean waves or unrequested characters.\nPRESERVE: short chunky weathered wooden rope bridge arching low left-to-right; one brown enamel mug with white wool steam curl and one pair of Bram's round gold wire spectacles, both resting at the LEFT end. All the current wood planks, four corner posts and chunky rope wraps remain.\nSMALL BRIDGE CORRECTION: complete the missing FRONT rope handrail, a natural rope joining the two front posts in a shallow sag. Position that rope so the brown mug and both round spectacle lenses remain clearly visible above it. Do not otherwise move the subjects. No Bram or characters.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8bb-0dae-7a02-832a-dfae246e6652/exec-90055182-3b7e-4e4b-a057-e4d459488401.png", + "session": "01a1d8bb-0dae-7a02-832a-dfae246e6652", + "attempts": 3 + }, + "card-coiled-rope.webp": { + "master": "web/assets/source/tide/card-coiled-rope.png", + "prompt": "Create a final shipped square Familiar game card picture as a sibling of reference image 1. Use the highest available image quality. Reference 1 is the APPROVED family template: preserve its exact camera angle, slightly elevated three-quarter view, stone foothold scale and position, lighting, tactile materials, miniature finish, and detail. Replace ONLY the cat and wave diorama with the subject below. NO cat, wave, or other inherited objects.\n\nFAMILY COMPOSITION: One tiny diorama on the same complete round spiral-carved sandstone foothold shown in references 1 and 2. The stone is horizontally centered, spans approximately x=10.5% to 89.5% of the square, and occupies approximately y=63.5% to 88.8%; its whole front wall and its entire outline must remain within frame. Its bottom margin is about 11%. Match the approved first card's base geometry and two chunky masonry layers, warm peach sandstone, broad carved spiral and sparse tiny moss tufts. Do not move the stone up or enlarge it to fill empty space. Let the new subject rise naturally above it. Keep generous empty margin on all four sides. Plain FLAT SOLID backdrop EXACT sRGB #efe4cc (239,228,204), constant uniform color everywhere away from the one soft contact shadow beneath the stone; no vignette, no gradient, no horizon.\n\nSTYLE: Cozy handmade felt-and-wool stop-motion miniature. Fine visible wool fibres, delicate hand stitching when relevant, chunky gentle rounded shapes, weathered miniature wood, natural hemp, matte sandstone. Match the references rather than glossy computer rendering. Soft warm studio light from upper left, soft shadows, no harsh speculars, no dramatic rim light. Restrained sea-glass teal, sand, cream, wood brown, brass, moss, coral pink; saturated red only where explicitly requested.\n\nREADABILITY: Few chunky forms, unmistakable silhouette at 120px and 64px. No text, letters, numbers, letter-like runes, logos, signatures, watermarks, UI frames, borders, mock-up chrome, extra objects, characters, or scenery.\n\nSUBJECT — THE ROPE STAYS COILED: On the stone is exactly ONE neat FLAT coil of natural tan hemp rope. It is perfectly wound as a single-layer planar spiral, concentric rope turns lying beside one another, never a vertical stack of loops, echoing the spiral carved in the stone. Use thick tactile twisted natural hemp with fine fibres and gentle rounded miniature proportions. A small soft red ribbon wraps around one radial section to hold the coil closed and is tied into a single modest bow, the exact warm saturated red of Mochi's bandana in reference 1. Bow has two short loops and two short tails; keep it small in proportion to the coil yet clear at stamp size. Coil centered on the back-middle of the foothold, resting flat directly on it; approximately half the full picture width, enough to read clearly while leaving the stone visible all around and its front spiral partly visible. No dangling loose rope ends, no extra coils, no posts, no animal. Strong clean read: one tan flat spiral rope coil with one red bow.\n\nBACKGROUND PRIORITY: remove any backdrop texture inherited from references and use a perfectly solid, uniform digital #efe4cc backdrop, exact RGB(239,228,204), with only the soft contact shadow beneath the stone.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8bb-0ce3-7671-95b6-07da902eaf0d/exec-8cbca955-dc01-45ee-a9bd-c41c96640b85.png", + "session": "01a1d8bb-0ce3-7671-95b6-07da902eaf0d", + "attempts": 3 + }, + "card-dry-and-tidy.webp": { + "master": "web/assets/source/tide/card-dry-and-tidy.png", + "prompt": "Use case: precise-object-edit. Output ONE square PNG at highest available quality. The FIRST IMAGE is the current card to correct; remaining images are supporting subject/material references only.\nThe exposed beige background of image 1 MUST CHANGE VISIBLY. It is currently too dark/yellow. Replace it with a noticeably LIGHTER, COOLER, SMOOTHER PALE CREAM FLAT FILL: EXACT #EFE4CC, sRGB RGB red239 green228 blue204. Treat this as a clean cutout of the entire diorama placed over a digital solid-color layer, NOT a studio photograph of cream paper. All open background at the top, bottom and sides must be this SAME UNVARYING FLAT PALE CREAM, without any texture, noise, grain, shadows, vignettes, warm grading, color variation or gradients. Preserve ONLY the soft small contact shadow immediately underneath the disc. Do not copy the old yellow-tinted textured background from any reference.\nKeep the entire diorama and sandstone disc's geometry and position exactly unchanged, square format, complete at x10%-90% width, disc bottom at y89%, camera slightly above at three-quarter view. Preserve all subject colors and soft upper-left light. Do NOT add surface texture or sharpen detail: preserve the fine soft reference finish rather than exaggerated grooves, embossing or glossy CGI. Handmade wool/felt where appropriate, tiny tactile details, miniature natural wood, brass and sandstone.\nNo text, letters, numbers, letterlike marks, logos, watermarks, signatures, UI, borders, scenery, extra objects, cats, ocean waves or unrequested characters.\nPRESERVE SUBJECT EXACTLY: two neatly folded thick cream wool-felt towels with one aligned sea-glass teal stripe design, stacked on the original sandstone disc. One wooden clothes-peg lies on top. Keep their soft fibres, squared rounded folds, stripe width, clear silhouette, scale and arrangement. No extra laundry, no changes to objects. Only the background should change.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8bb-0dae-7a02-832a-dfae246e6652/exec-cd703155-0dca-4662-acd7-7d16a3c3c586.png", + "session": "01a1d8bb-0dae-7a02-832a-dfae246e6652", + "attempts": 3 + }, + "card-dry-paws.webp": { + "master": "web/assets/source/tide/card-dry-paws.png", + "prompt": "Use case: precise-object-edit. Highest available rendering quality. Square final shipped game card PNG.\nThe FIRST reference image is the target image to correct. All other images are supporting composition/material references. Preserve the first image's objects, counts, handmade textures, colors, tiny detail, camera angle, lighting and complete framing except the explicitly stated corrections. Preserve the centered round spiral-carved sandstone base at approximately 80% canvas width, with its front bottom edge at y=89%. Keep real tactile material detail and soft warm upper-left light on the objects.\nMANDATORY BACKDROP COLOR CORRECTION: the target backdrop is too yellow and dark. Replace ONLY the exposed background with a perfectly uniform DIGITAL FLAT COLOR FILL, exact sRGB HEX #EFE4CC, RGB (239,228,204). Use this constant value everywhere outside the diorama and its immediate soft contact shadow. No photographic color grade or warmth on the backdrop. No texture, noise, grain, gradients, vignette, mottling, horizon, lighting falloff or background glow. This is a composited flat cream color layer, not a photographed beige surface. The subject lighting stays warm, the backdrop stays the exact unlit color swatch #EFE4CC. Only a small soft contact shadow directly under the stone.\nNo text, letters, numbers, runes, logos, watermarks, borders, extra objects, scenery or characters beyond the ones already specified. Keep generous clear margins and all objects complete.\n\nKeep exactly two dry felt Wellington boots, one small teal curl with white wool foam, and a clearly visible dry sandstone gap between water and BOTH boots. Slightly mute the boots' bright red toward a warm earthy RUST-RED as requested, retaining wool fibers and cream stitching. Do not add water anywhere else.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8bb-0b73-79d0-8e15-aa74d82bab41/exec-cdbcb462-65b6-4383-b56e-149c7bbc7854.png", + "session": "01a1d8bb-0b73-79d0-8e15-aa74d82bab41", + "attempts": 3 + }, + "card-every-source.webp": { + "master": "web/assets/source/tide/card-every-source.png", + "prompt": "Use case: precise-object-edit. Highest available rendering quality. Square final shipped game card PNG.\nThe FIRST reference image is the target image to correct. All other images are supporting composition/material references. Preserve the first image's objects, counts, handmade textures, colors, tiny detail, camera angle, lighting and complete framing except the explicitly stated corrections. Preserve the centered round spiral-carved sandstone base at approximately 80% canvas width, with its front bottom edge at y=89%. Keep real tactile material detail and soft warm upper-left light on the objects.\nMANDATORY BACKDROP COLOR CORRECTION: the target backdrop is too yellow and dark. Replace ONLY the exposed background with a perfectly uniform DIGITAL FLAT COLOR FILL, exact sRGB HEX #EFE4CC, RGB (239,228,204). Use this constant value everywhere outside the diorama and its immediate soft contact shadow. No photographic color grade or warmth on the backdrop. No texture, noise, grain, gradients, vignette, mottling, horizon, lighting falloff or background glow. This is a composited flat cream color layer, not a photographed beige surface. The subject lighting stays warm, the backdrop stays the exact unlit color swatch #EFE4CC. Only a small soft contact shadow directly under the stone.\nNo text, letters, numbers, runes, logos, watermarks, borders, extra objects, scenery or characters beyond the ones already specified. Keep generous clear margins and all objects complete.\n\nKeep exactly THREE identical separated teal glass curls in one evenly spaced left-to-right row, all topped with white wool foam. Nothing else.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8bb-0b73-79d0-8e15-aa74d82bab41/exec-02383f36-2141-4dc5-ae18-e2957c83b1a7.png", + "session": "01a1d8bb-0b73-79d0-8e15-aa74d82bab41", + "attempts": 3 + }, + "card-full-satchel.webp": { + "master": "web/assets/source/tide/card-full-satchel.png", + "prompt": "Use case: style-transfer. Create ONE square final shipped game card picture, highest available image rendering quality, PNG. The FIRST reference is the APPROVED FAMILY CARD, used as a composition/template to change only the little diorama subject. The SECOND reference is the same sandstone foothold, a geometry/material reference. Other references supply ONLY specified subject identities.\nFAMILY CAMERA AND BASE MUST MATCH FIRST REFERENCE: same three-quarter view slightly above, same lens/perspective, same warm upper-left studio illumination, same tiny handmade stop-motion miniature materials and level of detail. Reproduce the entire round peach-sandstone stone disc, irregular two courses of chunky rounded stone, sparse tiny moss in joints, large spiral carved into its flat top. Its outline spans x=10.5% to 89.5% of the square, top rear edge about y=64%, bottom front edge y=89%; centered at x=50%, all complete. Do not enlarge or shift it. Subject stands on the base and rises into the clear space above. Keep generous margins on all sides. The design must read immediately at 120 px and 64 px. Match family overall scale and tactile finish.\nMATERIALS AND COLOR: Familiar cozy coastal harbor game, real-looking handmade miniature, needle-felted wool with visible fine fibres, little hand stitches, chunky gently rounded shapes, weathered wood, matte aged brass, sea glass, sandstone. Sea-glass teal, sand, cream, wood brown, brass, moss, coral pink. Mochi's red bandana is the single saturated accent in the world. Reference images are authoritative, do not drift to glossy synthetic CGI, flat vector, or plastic.\nBACKDROP CRITICAL: perfectly plain FLAT SOLID sRGB #efe4cc, RGB(239,228,204), edge to edge. Treat the backdrop as a constant digital color fill, not a lit or textured surface. Absolutely NO gradient, vignette, grain, mottling, horizon or lighting falloff on background. Warm soft light affects ONLY the miniature. Only one soft contact shadow immediately under the stone.\nNEVER INCLUDE text, letters, numbers, letter-like runes, logos, signatures, watermarks, UI frames, borders, mock-up chrome, unrelated objects, scenery, character unless explicitly named in SUBJECT. Do not copy the kitten or surf diorama from first reference. Soft gentle shadows, no harsh speculars or dramatic rim light.\n\nSUBJECT: Mochi's SMALL BROWN LEATHER SATCHEL, exactly the warm weathered stitched satchel with rounded square flap and brass clasp worn by the kitten in THIRD reference, sits OPEN on the stone, with NO KITTEN present. Chunky bag centered, same stitching and leather finish, shoulder strap tucked beside the bag as part of it, flap folded open so opening is readable. TWO objects snug together peek out of its top: the recognizable circular BRASS FRESNEL LENS from FOURTH reference, showing its concentric clear glass lens, aged brass circular rim and tiny mounting brackets, with its lower support hidden INSIDE the bag; and the GOLDEN WIND-MOTH from FIFTH reference, awake with two black bead eyes and a tiny smiling mouth, cream wool head/body, little feathery golden antennae, beautiful pale gold wings with simple luminous curling filigree matching reference. Moth has all FOUR wings visible enough to recognize, lower body snug in the bag. Soft contained warm golden glow from the moth, not a big aura across background. Lens and moth are small enough to fit together within the satchel, partially tucked inside, not two loose objects beside it. Bag top around y=45%, lens/moth tops around y=22%, bag sits near y=72%. Brown bag with brass and golden glow peeking out. No additional objects, no kitten or other character.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8bb-0b73-79d0-8e15-aa74d82bab41/exec-c2edd8e7-17a8-4f05-83d3-4cd551e6f1c3.png", + "session": "01a1d8bb-0b73-79d0-8e15-aa74d82bab41", + "attempts": 3 + }, + "card-lantern-haul.webp": { + "master": "web/assets/source/tide/card-lantern-haul.png", + "prompt": "Use case: precise-object-edit. Output ONE square PNG at highest available quality. The FIRST IMAGE is the current card to correct; remaining images are supporting subject/material references only.\nThe exposed beige background of image 1 MUST CHANGE VISIBLY. It is currently too dark/yellow. Replace it with a noticeably LIGHTER, COOLER, SMOOTHER PALE CREAM FLAT FILL: EXACT #EFE4CC, sRGB RGB red239 green228 blue204. Treat this as a clean cutout of the entire diorama placed over a digital solid-color layer, NOT a studio photograph of cream paper. All open background at the top, bottom and sides must be this SAME UNVARYING FLAT PALE CREAM, without any texture, noise, grain, shadows, vignettes, warm grading, color variation or gradients. Preserve ONLY the soft small contact shadow immediately underneath the disc. Do not copy the old yellow-tinted textured background from any reference.\nKeep the entire diorama and sandstone disc's geometry and position exactly unchanged, square format, complete at x10%-90% width, disc bottom at y89%, camera slightly above at three-quarter view. Preserve all subject colors and soft upper-left light. Do NOT add surface texture or sharpen detail: preserve the fine soft reference finish rather than exaggerated grooves, embossing or glossy CGI. Handmade wool/felt where appropriate, tiny tactile details, miniature natural wood, brass and sandstone.\nNo text, letters, numbers, letterlike marks, logos, watermarks, signatures, UI, borders, scenery, extra objects, cats, ocean waves or unrequested characters.\nPRESERVE SUBJECT EXACTLY: lit rounded brass harbor hand-lantern in the middle, smaller concentric brass Fresnel lens leaning diagonally against its base on the LEFT, and one golden wool wind-moth hovering close on the RIGHT. Preserve lens tilt and physical contact with lantern, teal-patina brass foot, concentric clear rings; preserve moth's cream head, black bead eyes, tiny smile, coral cheeks, gold feathered antennae and four cream translucent gold-patterned wings. Local amber light stays soft and close to the lantern glass and moth, with no broad glow or darkening of background. Keep all reference identities. Do not make metal shinier or more orange. No additional items.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8bb-0dae-7a02-832a-dfae246e6652/exec-105b11d7-09ea-4e3e-87d5-fa1b71ee78e2.png", + "session": "01a1d8bb-0dae-7a02-832a-dfae246e6652", + "attempts": 3 + }, + "card-left-for-bram.webp": { + "master": "web/assets/source/tide/card-left-for-bram.png", + "prompt": "Use case: precise-object-edit. Output ONE square PNG at highest available quality. The FIRST IMAGE is the current card to correct; remaining images are supporting subject/material references only.\nThe exposed beige background of image 1 MUST CHANGE VISIBLY. It is currently too dark/yellow. Replace it with a noticeably LIGHTER, COOLER, SMOOTHER PALE CREAM FLAT FILL: EXACT #EFE4CC, sRGB RGB red239 green228 blue204. Treat this as a clean cutout of the entire diorama placed over a digital solid-color layer, NOT a studio photograph of cream paper. All open background at the top, bottom and sides must be this SAME UNVARYING FLAT PALE CREAM, without any texture, noise, grain, shadows, vignettes, warm grading, color variation or gradients. Preserve ONLY the soft small contact shadow immediately underneath the disc. Do not copy the old yellow-tinted textured background from any reference.\nKeep the entire diorama and sandstone disc's geometry and position exactly unchanged, square format, complete at x10%-90% width, disc bottom at y89%, camera slightly above at three-quarter view. Preserve all subject colors and soft upper-left light. Do NOT add surface texture or sharpen detail: preserve the fine soft reference finish rather than exaggerated grooves, embossing or glossy CGI. Handmade wool/felt where appropriate, tiny tactile details, miniature natural wood, brass and sandstone.\nNo text, letters, numbers, letterlike marks, logos, watermarks, signatures, UI, borders, scenery, extra objects, cats, ocean waves or unrequested characters.\nPRESERVE SUBJECT EXACTLY: one small parcel wrapped in cream felt cloth sits toward the LEFT of the round stone, tied crosswise with natural twine, one simple knot and one round cream felt tag facing us, embroidered with a single coral-pink pictorial scallop shell. Preserve the soft neatly folded cream cloth, fine wool fibres, twine, clear tag design and the stone spiral visible to the right of the parcel. No lettering, no star or wave, no person, no extra objects. Only the background changes.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8bb-0dae-7a02-832a-dfae246e6652/exec-caf6b0a7-4129-4b1d-8524-aa7e1f9cb5e1.png", + "session": "01a1d8bb-0dae-7a02-832a-dfae246e6652", + "attempts": 3 + }, + "card-no-waiting.webp": { + "master": "web/assets/source/tide/card-no-waiting.png", + "prompt": "Use case: precise-object-edit. Highest available rendering quality. Square final shipped game card PNG.\nThe FIRST reference image is the target image to correct. All other images are supporting composition/material references. Preserve the first image's objects, counts, handmade textures, colors, tiny detail, camera angle, lighting and complete framing except the explicitly stated corrections. Preserve the centered round spiral-carved sandstone base at approximately 80% canvas width, with its front bottom edge at y=89%. Keep real tactile material detail and soft warm upper-left light on the objects.\nMANDATORY BACKDROP COLOR CORRECTION: the target backdrop is too yellow and dark. Replace ONLY the exposed background with a perfectly uniform DIGITAL FLAT COLOR FILL, exact sRGB HEX #EFE4CC, RGB (239,228,204). Use this constant value everywhere outside the diorama and its immediate soft contact shadow. No photographic color grade or warmth on the backdrop. No texture, noise, grain, gradients, vignette, mottling, horizon, lighting falloff or background glow. This is a composited flat cream color layer, not a photographed beige surface. The subject lighting stays warm, the backdrop stays the exact unlit color swatch #EFE4CC. Only a small soft contact shadow directly under the stone.\nNo text, letters, numbers, runes, logos, watermarks, borders, extra objects, scenery or characters beyond the ones already specified. Keep generous clear margins and all objects complete.\n\nAdditional correction: rotate EACH of the three orange felt pawprints by 180 degrees on the stone so its four little TOE PADS point toward the FRONT EDGE of the disc, toward the bottom of the image/viewer. Each central big pad is behind its toes. The trail travels past the hourglass toward the viewer, not toward the back. Keep exactly THREE prints, same locations. Keep hourglass fully horizontal on its side, pale sand settled along bottom sides of bulbs, no running stream. Match the approved base's bottom at 89% canvas height.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8bb-0b73-79d0-8e15-aa74d82bab41/exec-a17ad616-6c96-47fe-bbe1-a361aba94ea0.png", + "session": "01a1d8bb-0b73-79d0-8e15-aa74d82bab41", + "attempts": 3 + }, + "card-once-across.webp": { + "master": "web/assets/source/tide/card-once-across.png", + "prompt": "Create a final shipped square Familiar game card picture as a sibling of reference image 1. Use the highest available image quality. Reference 1 is the APPROVED family template: preserve its exact camera angle, slightly elevated three-quarter view, stone foothold scale and position, lighting, tactile materials, miniature finish, and detail. Replace ONLY the cat and wave diorama with the subject below. NO cat, wave, or other inherited objects.\n\nFAMILY COMPOSITION: One tiny diorama on the same complete round spiral-carved sandstone foothold shown in references 1 and 2. The stone is horizontally centered, spans approximately x=10.5% to 89.5% of the square, and occupies approximately y=63.5% to 88.8%; its whole front wall and its entire outline must remain within frame. Its bottom margin is about 11%. Match the approved first card's base geometry and two chunky masonry layers, warm peach sandstone, broad carved spiral and sparse tiny moss tufts. Do not move the stone up or enlarge it to fill empty space. Let the new subject rise naturally above it. Keep generous empty margin on all four sides. Plain FLAT SOLID backdrop EXACT sRGB #efe4cc (239,228,204), constant uniform color everywhere away from the one soft contact shadow beneath the stone; no vignette, no gradient, no horizon.\n\nSTYLE: Cozy handmade felt-and-wool stop-motion miniature. Fine visible wool fibres, delicate hand stitching when relevant, chunky gentle rounded shapes, weathered miniature wood, natural hemp, matte sandstone. Match the references rather than glossy computer rendering. Soft warm studio light from upper left, soft shadows, no harsh speculars, no dramatic rim light. Restrained sea-glass teal, sand, cream, wood brown, brass, moss, coral pink; saturated red only where explicitly requested.\n\nREADABILITY: Few chunky forms, unmistakable silhouette at 120px and 64px. No text, letters, numbers, letter-like runes, logos, signatures, watermarks, UI frames, borders, mock-up chrome, extra objects, characters, or scenery.\n\nSUBJECT — ONCE ACROSS: A short chunky wooden rope bridge standing directly on the sandstone disc, arching LOW from LEFT TO RIGHT across it. Reference image 3 supplies the exact weathered wood planks, rounded posts, small iron peg heads and thick rope rails; shorten that bridge into a little low arch, seen sufficiently from above to see the middle plank. Roughly five to seven broad planks and four chunky corner posts, continuous rope handrails on both sides. Both ends rest on the stone. On its middle plank is ONE SINGLE orange felt paw-print impression, one central pad and four little toe pads forming one clear paw. The orange paw mark is the only orange felt decoration. No animal attached to it. No other paw prints. The entire little bridge is visible and centered on the disc. Strong simple read: little wooden bridge with one orange paw print.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8bb-0ce3-7671-95b6-07da902eaf0d/exec-9009f0bf-bfce-4308-8893-df0edde0ed74.png", + "session": "01a1d8bb-0ce3-7671-95b6-07da902eaf0d", + "attempts": 3 + }, + "card-quiet-shell.webp": { + "master": "web/assets/source/tide/card-quiet-shell.png", + "prompt": "Correct image 1 for the final square Familiar card. Image 2 is the APPROVED family camera, sandstone foothold, lighting and material reference. Image 3 is the scallop shell design. Image 4 is the golden moth character design.\n\nKeep the sandstone disc exactly as in image 1: complete and centered, about 80% picture width, bottom at 89% picture height, three-quarter view slightly from above, broad carved spiral, chunky two-layer peach sandstone masonry, tiny moss tufts and soft contact shadow. Keep the warm soft upper-left lighting and meticulous handmade miniature finish.\n\nNECESSARY SUBJECT CORRECTION: The shell in image 1 looks propped up. Lay it completely FLAT on its lower valve, horizontal and parallel to the stone's top surface, with its closed upper ribbed valve facing upward toward the ceiling. It must be a low, foreshortened shell viewed obliquely from above, NOT an upright fan or cushion. Both valves are firmly shut with a fine visible closed seam. Preserve reference 3's distinctive coral-pink and cream scalloped ribs, tiny teal hinge ornament, matte finely textured handmade surface. The shell should be approximately 55% of frame width with a low profile; no vertical display stand. Shell rests directly on the back-middle of the stone, leaving front stone visible.\n\nPlace the sleeping golden wind-moth on top, lying on the shell, and make it smaller than in image 1: moth body plus folded wings is about ONE THIRD the shell width, with shell visible on all sides. Preserve the reference moth's cream wool head, coral cheeks, feathered golden antennae, golden abdomen, small rounded cream paws and wing scrolls. Both eyes are two simple CLOSED curves. Its wings remain folded together over its back like a compact tent, never spread wide. Only faint local warm glow, no bright halo or rays.\n\nBackground must be plain FLAT SOLID EXACT #efe4cc, RGB(239,228,204), with no grain, gradient or vignette. Only soft contact shadow below the stone. Highest available quality. No text, letters, numbers, letter-like runes, logo, watermark, frame, border, UI, extra object, scenery, or additional character. All objects whole, generous clear margins.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8bb-0ce3-7671-95b6-07da902eaf0d/exec-2591a8d9-5e8a-4534-81c4-fb589b44837b.png", + "session": "01a1d8bb-0ce3-7671-95b6-07da902eaf0d", + "attempts": 3 + }, + "card-surf-home.webp": { + "master": "web/assets/source/tide/card-surf-home.png", + "prompt": "Revise the fifth input image, the generated surfing-kitten diorama, into final shipped art. Output ONE square 1:1 PNG at the highest available quality. The first four input images are authoritative identity/material references (Mochi kitten, teal glass/wool wave, spiral sandstone island, brass lens). The fifth input image is the composition to correct. Preserve its excellent handmade miniature detail, Mochi identity, happy prone pose, red scarf, satchel and peeking brass lens.\n\nTHREE REQUIRED CORRECTIONS:\n1. BACKGROUND must be a truly FLAT SOLID digital color fill exactly #efe4cc, sRGB RGB(239,228,204). Every empty background pixel away from the small contact shadow must have this identical value. No paper texture, noise, gradient, vignette, yellow cast, studio sweep or horizon. The subject retains realistic miniature materials and soft upper-left warm lighting, but the background is a uniform graphic color field with no lighting variation. Only a restrained soft contact shadow immediately underneath the base.\n2. ZOOM OUT: the sandstone disc is 80% of the canvas width, with 10% clear margins at BOTH left and right. The entire diorama is visible, centered, with at least 9% clear space above the raised tail and below the base. Keep same slightly-above three-quarter camera and entire elliptical disc outline visible. Current disc is too wide; reduce the complete diorama proportionately. Preserve clearly visible spiral on the top of the warm sandstone foothold.\n3. WAVE DIRECTION: the SINGLE wave must curl toward LEFT, carrying Mochi from right to left. The overhanging curling lip is on the LEFT, the low trailing slope flows back to the RIGHT. Mochi remains facing LEFT, front paws stretched to the left on top of the crest, belly down, hindquarters to the right, tail up. Do not reverse Mochi. Her head and forward paws ride directly above the left-facing curling lip.\n\nKeep one orange Mochi, one teal glass wave with white wool foam, one warm sandstone disc. A few small felt spray droplets close to the crest, no other objects. Mochi must keep huge round head, tiny chunky body, orange stripes, cream muzzle/chest/paws, curved dark whiskers and dark oval eyes as original reference. Delight with tiny open grin, not exaggerated mouth. Fine felt fibres and hand stitches, glassy translucent teal water and thick wool foam, textured warm sandstone with spiral. Brass lens tucked INSIDE satchel with rim and glass peeking out; no separate lens stand or surfboard. Three clear orange/teal/sand color masses readable as a 64-pixel stamp. Red bandana only saturated accent.\n\nNever include text, letters, numbers, letterlike runes, logos, signatures, watermark, borders, UI frame, scenery, extra objects, extra animals, extra waves, cropped parts, glossy plastic style or vector illustration. The stone spiral is a decorative spiral only. Preserve handmade reference finish exactly.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8b2-0b79-7580-acf8-887eafdc0889/exec-3c27ee1f-d9d2-4532-82a8-bbd688811b82.png", + "session": "01a1d8b2-0b79-7580-acf8-887eafdc0889", + "attempts": 3 + }, + "card-tidy-tide.webp": { + "master": "web/assets/source/tide/card-tidy-tide.png", + "prompt": "Create a final shipped square Familiar game card picture as a sibling of reference image 1. Use the highest available image quality. Reference 1 is the APPROVED family template: preserve its exact camera angle, slightly elevated three-quarter view, stone foothold scale and position, lighting, tactile materials, miniature finish, and detail. Replace ONLY the cat and wave diorama with the subject below. NO cat, wave, or other inherited objects.\n\nFAMILY COMPOSITION: One tiny diorama on the same complete round spiral-carved sandstone foothold shown in references 1 and 2. The stone is horizontally centered, spans approximately x=10.5% to 89.5% of the square, and occupies approximately y=63.5% to 88.8%; its whole front wall and its entire outline must remain within frame. Its bottom margin is about 11%. Match the approved first card's base geometry and two chunky masonry layers, warm peach sandstone, broad carved spiral and sparse tiny moss tufts. Do not move the stone up or enlarge it to fill empty space. Let the new subject rise naturally above it. Keep generous empty margin on all four sides. Plain FLAT SOLID backdrop EXACT sRGB #efe4cc (239,228,204), constant uniform color everywhere away from the one soft contact shadow beneath the stone; no vignette, no gradient, no horizon.\n\nSTYLE: Cozy handmade felt-and-wool stop-motion miniature. Fine visible wool fibres, delicate hand stitching when relevant, chunky gentle rounded shapes, weathered miniature wood, natural hemp, matte sandstone. Match the references rather than glossy computer rendering. Soft warm studio light from upper left, soft shadows, no harsh speculars, no dramatic rim light. Restrained sea-glass teal, sand, cream, wood brown, brass, moss, coral pink; saturated red only where explicitly requested.\n\nREADABILITY: Few chunky forms, unmistakable silhouette at 120px and 64px. No text, letters, numbers, letter-like runes, logos, signatures, watermarks, UI frames, borders, mock-up chrome, extra objects, characters, or scenery.\n\nSUBJECT — A TIDY TIDE: A tiny handmade straw besom broom stands upright, bristles down in direct contact with the stone. Rounded weathered wooden handle, a compact chunky fan-shaped bundle of natural golden straw, bound neatly with plain natural twine; tactile wool-fine fibres and handmade miniature detail. Beside it, on the stone, is ONE small neat swept-up mound of WHITE WOOL sea-foam: one compact rounded softly scalloped heap of needle-felted white foam, not individual bubbles or stones, plainly separate from the bristles. Only these two objects, no other props, debris, bucket, dustpan, splash, or character. Strong clean silhouette: little upright broom beside tidy white mound. Let the upright broom be the main tall element, from the stone to approximately y=25% of the canvas; the white mound is much shorter, beside its base. Keep the stone exactly where it is in the family template.\n\nBACKGROUND PRIORITY: use a clean solid digital #efe4cc field behind this handmade diorama. No photographed paper texture or mottling, no cream gradient. All unshadowed empty background pixels must be RGB(239,228,204).", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8bb-0ce3-7671-95b6-07da902eaf0d/exec-816eec33-55c6-40ba-9796-944e9031964c.png", + "session": "01a1d8bb-0ce3-7671-95b6-07da902eaf0d", + "attempts": 3 + }, + "card-wake-both-shells.webp": { + "master": "web/assets/source/tide/card-wake-both-shells.png", + "prompt": "Use case: precise-object-edit. Highest available rendering quality. Square final shipped game card PNG.\nThe FIRST reference image is the target image to correct. All other images are supporting composition/material references. Preserve the first image's objects, counts, handmade textures, colors, tiny detail, camera angle, lighting and complete framing except the explicitly stated corrections. Preserve the centered round spiral-carved sandstone base at approximately 80% canvas width, with its front bottom edge at y=89%. Keep real tactile material detail and soft warm upper-left light on the objects.\nMANDATORY BACKDROP COLOR CORRECTION: the target backdrop is too yellow and dark. Replace ONLY the exposed background with a perfectly uniform DIGITAL FLAT COLOR FILL, exact sRGB HEX #EFE4CC, RGB (239,228,204). Use this constant value everywhere outside the diorama and its immediate soft contact shadow. No photographic color grade or warmth on the backdrop. No texture, noise, grain, gradients, vignette, mottling, horizon, lighting falloff or background glow. This is a composited flat cream color layer, not a photographed beige surface. The subject lighting stays warm, the backdrop stays the exact unlit color swatch #EFE4CC. Only a small soft contact shadow directly under the stone.\nNo text, letters, numbers, runes, logos, watermarks, borders, extra objects, scenery or characters beyond the ones already specified. Keep generous clear margins and all objects complete.\n\nKeep exactly TWO open coral-pink scallop shells with golden light inside each. Both hinged back and front valves remain visible. Nothing else.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8bb-0b73-79d0-8e15-aa74d82bab41/exec-daae5798-ca02-4e2d-8327-dfd124a8ab2c.png", + "session": "01a1d8bb-0b73-79d0-8e15-aa74d82bab41", + "attempts": 3 + }, + "keeper-ask.webp": { + "master": "web/assets/source/tide/keeper-ask.png", + "prompt": "Create the corrected final version of image 3 as ONE landscape 3:2 PNG, highest available quality. Image 1 is the shipped Tidekeeper character authority; image 2 is cream felt/twine/embroidery material reference only; image 3 is the illustration to revise. Preserve image 3's very faithful Tidekeeper identity, stone material, coral, kelp, moss, sandy barnacles, amber eyes, and rectangular felt card with embroidered coral scallop above teal wave. Do not redesign him.\n\nREQUIRED COMPOSITION CORRECTIONS:\n- Reduce the complete crab-and-card grouping so its entire width is 80% of canvas width, with generous 10% empty margins left and right and clear margin above all coral and below every foot/card. Keep same slightly-above three-quarter front view. All body parts complete and centered.\n- Raise and extend the viewer-right claw toward viewer, bringing the little cream rectangular card HIGHER so its entire pale face overlaps the darker grey stone body of that raised claw. The card must be visually backed by grey stone, not hanging in empty beige space beneath the claw. Pincer tips gently pinch a SHORT natural-twine loop just above card. Card hangs directly in front of the middle of that claw, with enough stone visible around the card to show contrast. Keep both amber eyes unobscured. Offered card faces viewer. It should read instantly when whole illustration is displayed at 280px wide. Card about 16% of canvas width. Other claw remains resting. No extra claws or legs.\n- Make background a completely flat featureless digital fill of EXACT sRGB #efe4cc RGB(239,228,204), uniformly in all empty areas to every edge. No paper/felt texture, no noise, no gradient, no vignette, no photographic backdrop lighting variation. Only a small soft contact shadow under crab's feet. Do not copy the photographic background texture or color variation from any reference.\n\nCARD has thick cream needle-felted wool, visible fibres, simple stitched perimeter and short twine loop. Exactly ONE simple embroidered picture: small coral-pink fan-shaped scallop shell ABOVE a teal wave curl. This is pictorial only. No stars, round token, wooden rim, text or letterlike shapes. Keep design simple and large within card.\n\nThe SAME old wide low stone crab as image 1: heavy rounded gray carved shell with big pale spiral, pale porous stone segments and claws with spiral decoration, warm small amber eyes, pink coral on upper left, long green kelp on upper right, sandy barnacles and moss. Patient kind expression with only faint natural smile. Only one claw pose changes; body proportions and ornament distribution stay faithful.\n\nExact handmade stop-motion miniature finish; physical stone and coral, felt/wool card, twine. Soft warm studio upper-left lighting and gentle shadows on subject. No harsh specular or rim light, glossy plastic, generic cartoon CGI or vector style. No platform, scenery or extra objects. No text, letters, numbers, letterlike runes, logos, signatures, watermarks, UI frames, borders or mockup chrome. Single complete crab with single offered card, no cropping.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8b2-0b79-7580-acf8-887eafdc0889/exec-52c35760-8217-499b-aa7e-24d8e187509e.png", + "session": "01a1d8b2-0b79-7580-acf8-887eafdc0889", + "attempts": 3 + }, + "log-cover.webp": { + "master": "web/assets/source/tide/log-cover.png", + "prompt": "Use case: precise-object-edit. Square final game-art PNG, highest quality.\nFirst image is the TARGET. Other images are authoritative material references.\nPreserve the target's complete teal handmade logbook: same shape, camera angle slightly above, cream deckled page edges, pencil attached in left spine loop, pale coral scallop embroidery over teal yarn wave on the cover, small brass corner caps, cream edge stitches and red bookmark. Keep it tactile, matte needle-felted wool with fine fibres and warm soft upper-left lighting, as in the original reference assets. No glossy gold reflections. No changes to subject composition or added details.\n\nThis is a FLAT BACKGROUND COLOR CORRECTION ONLY. The current beige background is too dark and too yellow. Replace the entire background with the visibly lighter, slightly cooler CREAM SOLID SWATCH #EFE4CC (sRGB RGB 239,228,204). Use a clean flat digital backdrop, constant RGB all the way to all four image corners. DO NOT photograph or texture this color. NO paper grain, noise, film texture, mottling, vignette, color grading, warm filter or lighting gradient on the background. Apply warm light to the book only. Background should look like a single uniform bucket fill in a graphics editor, color #EFE4CC. Keep only the immediate small soft contact shadow directly under the book, nowhere else.\n\nOne complete centered book with all pencil, brass corners and ribbon inside frame and clear margins on every side, on that flat #EFE4CC backdrop. No writing, text, letters, numbers, symbols other than shell and wave, logos, watermark, signatures, borders, frames, scenery, characters or unrelated items.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8b2-0c2b-7523-8372-b9afa50d2b3c/exec-9caf1096-1157-408f-b694-4b0bc3ea5273.png", + "session": "01a1d8b2-0c2b-7523-8372-b9afa50d2b3c", + "attempts": 3 + }, + "log-page.webp": { + "master": "web/assets/source/tide/log-page.png", + "prompt": "Use case: precise-object-edit. Highest available quality square PNG.\nEdit ONLY the colors of the FIRST input image, the blank square handmade paper page. Use the other inputs only as handmade material references. Preserve exactly the first image's geometry: true flat top-down orthographic single sheet, no perspective, no curl, centered 90% frame coverage, visible complete softly deckled edges with 5% equal margins. Preserve exactly three tiny left-edge holes connected with a very short fine cream thread at mid-height. Keep the entirely empty and evenly lit center, subtle fine cotton-rag paper fibres and faint ageing only in outer 10%.\n\nCOLOR CORRECTIONS ARE ESSENTIAL:\nBACKGROUND MUST BE A DIGITAL FLAT FILL, sRGB #1F3A2E, RGB(31,58,46), fully opaque. The old green is too bright and mottled: lower green-channel brightness and use the exact deep harbor green value. Every visible background pixel must be IDENTICAL. No texture, grain, noise, blur, lighting, shading, gradients, cast shadow, ambient occlusion, contact shadow, dark halo, vignette or background detail. Think of a perfectly cut-out paper sheet placed on a flat vector color layer. The paper remains natural textured material; only the background is mathematically uniform.\nPAPER MUST BE LIGHT CREAM, sRGB #F6EAD0, RGB(246,234,208), across the center. The old page was yellow parchment; make the sheet distinctly paler and cooler cream, with less orange/yellow. No warm photographic color filter. The center 80% is clean, empty and uniform: no patches, no directional shading, no broad tonal drift, no stains. Keep extremely fine faint paper fibres, no woven or felt textile texture. Outer-edge ageing only barely perceptible.\n\nThe lighting is flat even diffuse illumination. This is a nine-slice stretchable blank game panel background; prioritize clean uniform center and clean cutout edge over photographic effects.\nABSOLUTELY NO text, letters, numbers, runes, lines, charts, grids, drawings, stamps, signatures, logos, symbols, watermark, ornamental border, curl, perspective, shadow, extra objects or scenery.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8b2-0c2b-7523-8372-b9afa50d2b3c/exec-ba64a092-bbfa-4a55-bd94-07e6708159f0.png", + "session": "01a1d8b2-0c2b-7523-8372-b9afa50d2b3c", + "attempts": 3 + }, + "seal-all-three.webp": { + "master": "web/assets/source/tide/seal-all-three.png", + "prompt": "Two precise corrections ONLY to the FIRST input image, the brass scallop medal with two red ribbon tails. Highest available quality square PNG. The second input, a teal wax seal, locks the same scallop design.\n1. Reduce the WHOLE brass medal plus ribbons by ten percent relative to its current image size, leaving it centred as a combined shape. Target total height including ribbon tips is 72% of the canvas (14% margin above and 14% below). Keep all of the image's object proportions and geometry unchanged.\n2. Replace the entire visible backdrop with EXACT solid sRGB #EFE4CC, RGB 239,228,204. Current backdrop is visibly yellow and varied, about RGB239,225,199; increase green and blue to the exact values 228 and 204. The backdrop must be a digitally flat CONSTANT RGB, with no texture, variation, grain, noise, photographic light falloff, yellow tint, gradient, vignette or mottling. Corners, wide margins and gap between tails have the identical solid value. Only a tiny very soft contact shadow immediately under the object is allowed.\nPRESERVE EVERYTHING ELSE: one circular softly edged warm satin brushed brass seal; the raised brighter brass scallop has exactly the same upright broad seven-rib fan, scalloped crown, three-lobed short hinge and curled rounded basal ears as the teal seal. Keep clear relief, handmade miniature metal finish with muted diffuse upper-left lighting, no glossy hot spots. Exactly two short red needle-felted wool swallow-tail ribbon ends with fine visible fibres and tiny cream edge stitches, emerging from behind the disc bottom, separated with a cream gap and each having a clear V notch. Directly overhead orthographic camera, no tilt. Complete object, no cropping.\nForbidden: text, letters, numbers, runes, logos, signatures, watermark, UI frames, borders, mock-up chrome, extra objects, scenery, stone base, additional emblems, stars or waves. This is the final small celebration mark for the cozy coastal handmade game Familiar, readable as gold disc with two red tails.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8bb-0e6d-71e3-926a-db26acdd5ffc/exec-31917cec-6094-49b3-9c2d-1c801f385b5f.png", + "session": "01a1d8bb-0e6d-71e3-926a-db26acdd5ffc", + "attempts": 3 + }, + "seal-kept.webp": { + "master": "web/assets/source/tide/seal-kept.png", + "prompt": "Precisely edit the first reference image, retaining its teal wax seal design. Highest available quality square PNG. Reference two is the original scallop design; reference three supplies handmade material style.\n\nThe cream background is currently too yellow and dark: REPLACE IT with a fully opaque EXACT solid digital RGB(239,228,204), hex #EFE4CC. Raise blue to 204, green to 228, red to 239. This is a flat graphics background with absolutely no grain, texture, variation, vignette, global tint or gradient. All four corners and all clear margins must share that precise RGB value. The lighting applies only to the seal, not the background. Keep only a very faint tight contact shadow at the seal's immediate lower edge.\nScale the entire seal down within the canvas so its full outer diameter is precisely about 72% of the image width and height. Centre it with generous equal 14% margins, not the current close framing.\nOtherwise preserve the reference: ONE solid circular sea-glass teal pressed-wax seal, a soft irregular rounded rim and a lighter pale sea-glass teal embossed raised scallop in the centre. The scallop is upright and broad, with seven large convex radiating ribs, scalloped fan crown, a short rounded hinge and two small rounded basal ears. Keep its design, proportions and orientation. Handmade soft matte WAX with faint fine texture, no holes or pores, not fuzzy felt and not polished shiny plastic. Clear tonal difference between the light shell and darker teal disc.\nStrict top-down orthographic camera, no tilt. Soft warm upper-left studio lighting, tiny soft shadows. Whole object uncropped.\nNo text, letters, numbers, letterlike runes, logo, signature, watermark, UI frame, border, mock-up chrome, extra unrelated objects, scenery, stone base, ribbons, stars or waves. A final shipped Familiar status mark: readable as a solid teal disc with pale raised shell at 16 to 56px.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8bb-0e6d-71e3-926a-db26acdd5ffc/exec-b58a8408-2b22-41bf-8b62-e3beae94d326.png", + "session": "01a1d8bb-0e6d-71e3-926a-db26acdd5ffc", + "attempts": 3 + }, + "seal-slipped.webp": { + "master": "web/assets/source/tide/seal-slipped.png", + "prompt": "Edit only the BACKGROUND COLOUR of the first attached image. Highest available quality square PNG.\nThe object is already correct: preserve the single softly uneven hollow blue-grey needle-felted wool ring, its exact shape, fibres, material, composition, scale, two small teal felt droplets beside the lower right, its large empty centre and true top-down view.\nReplace ALL empty backdrop outside AND inside the ring with a clean digital flat fill of precisely sRGB RGB(239,228,204), hexadecimal #EFE4CC. The previous background was near RGB(238,226,202) but it must instead be the exact requested lighter cream. NO yellow filter. NO background shading or variation at all: no photographic texture, grain, noise, gradient, mottling, vignetting, shadows spanning the background, light falloff or colour grading. Make the background an exact uniform graphics colour layer. Only the extremely faint immediate contact shadow directly below the felt can vary. The ring centre must show the same solid #EFE4CC as the outer corners.\nAll handmade material texture belongs on the felt alone. Keep soft warm upper-left lighting on the wool without altering the background's exact colour. No cropping.\nPreserve the calm gentle status mark for Familiar. One ring and its two droplets, no other objects. Never add text, letters, numbers, runes, logo, signature, watermark, UI frame, border, cross, X, red, stone base, shell, star, wave, scenery or mockup chrome.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d8bb-0e6d-71e3-926a-db26acdd5ffc/exec-0d60e28d-106e-4bf1-9978-097a53894296.png", + "session": "01a1d8bb-0e6d-71e3-926a-db26acdd5ffc", + "attempts": 3 + } + } +} diff --git a/web/public/assets/tide/seal-all-three.webp b/web/public/assets/tide/seal-all-three.webp new file mode 100644 index 0000000..2743ad6 Binary files /dev/null and b/web/public/assets/tide/seal-all-three.webp differ diff --git a/web/public/assets/tide/seal-kept.webp b/web/public/assets/tide/seal-kept.webp new file mode 100644 index 0000000..f8bad3b Binary files /dev/null and b/web/public/assets/tide/seal-kept.webp differ diff --git a/web/public/assets/tide/seal-slipped.webp b/web/public/assets/tide/seal-slipped.webp new file mode 100644 index 0000000..dca6c9a Binary files /dev/null and b/web/public/assets/tide/seal-slipped.webp differ diff --git a/web/public/assets/title/manifest.json b/web/public/assets/title/manifest.json new file mode 100644 index 0000000..5f99c7e --- /dev/null +++ b/web/public/assets/title/manifest.json @@ -0,0 +1,102 @@ +{ + "purpose": "Title signpost runtime artwork; trimmed alpha cut-outs with original masters preserved", + "encoder": "magick corner floodfill alpha erode2 blur0x1 trim Lanczos + cwebp quality88 method6 alpha100 sharp_yuv", + "files": [ + { + "source": "assets/source/title/title-bell.png", + "output": "assets/title/title-bell.webp", + "sourceSha256": "7e765e2b346a56326b3a929065bc4654ae40175dd37d89762c42c5a63d25629b", + "sha256": "cf5fd6a7aedb269442695be971ac282992c6d7c722730f05937c7309ecede908", + "sourceBytes": 348753, + "bytes": 11234, + "resizedTo": { + "width": 137, + "height": 330 + } + }, + { + "source": "assets/source/title/title-paper.png", + "output": "assets/title/title-paper.webp", + "sourceSha256": "343e21d2ae9cb4611887af430d11e51ee5c229fd66b6007b6aec44e9c3070e56", + "sha256": "3bda97e740f7050994bae7b536eba8b2d2f8a533361f32ed452b656c1b98fb0f", + "sourceBytes": 1124301, + "bytes": 56246, + "resizedTo": { + "width": 780, + "height": 952 + } + }, + { + "source": "assets/source/title/title-plank-1.png", + "output": "assets/title/title-plank-1.webp", + "sourceSha256": "9fedf9fac286981708783a8652bb61aeb6866a7f4e6bedff81420b33f51dc5cb", + "sha256": "249b109cbb03c0e05c277497749c6665bb09c94bc56c640285d9bf1230d7e876", + "sourceBytes": 603554, + "bytes": 28290, + "resizedTo": { + "width": 720, + "height": 171 + } + }, + { + "source": "assets/source/title/title-plank-2.png", + "output": "assets/title/title-plank-2.webp", + "sourceSha256": "0b006e00a786198f46f1969b8dd36c40ce16ffb4f613933bbd186a853539a7ce", + "sha256": "51fd8ebe38893f248dac456ba5de98fa1f73b1d698b9c9eaf0ff71289ce9af96", + "sourceBytes": 597560, + "bytes": 30176, + "resizedTo": { + "width": 720, + "height": 164 + } + }, + { + "source": "assets/source/title/title-plank-3.png", + "output": "assets/title/title-plank-3.webp", + "sourceSha256": "3240378b29063a34fd8601df9f96fc631acdb4132e513291081e177f87315d9a", + "sha256": "5a427048e27c352c7bb1edde3a5494aa8a320bd097cadd9f854e6fbfbdb52772", + "sourceBytes": 590010, + "bytes": 27132, + "resizedTo": { + "width": 720, + "height": 169 + } + }, + { + "source": "assets/source/title/title-plank-4.png", + "output": "assets/title/title-plank-4.webp", + "sourceSha256": "99551688cb23844d8135453833e69d85629d844c94c41702011642d46d956169", + "sha256": "701d8c5f7aaca67159489745b88d7e9970681cb7a64d73fc460e2f89cc1a07c1", + "sourceBytes": 607510, + "bytes": 26764, + "resizedTo": { + "width": 720, + "height": 164 + } + }, + { + "source": "assets/source/title/title-post.png", + "output": "assets/title/title-post.webp", + "sourceSha256": "b1b16f79279366c02f44baf29a433ac3009165b10dc448cd053feb24db5ff0ee", + "sha256": "5b2cf27ab8495904697c6d38117ae218eed427fd827b164e05e63b1d355391ed", + "sourceBytes": 176157, + "bytes": 33218, + "resizedTo": { + "width": 281, + "height": 1240 + } + }, + { + "source": "assets/source/title/title-tag.png", + "output": "assets/title/title-tag.webp", + "sourceSha256": "9d6fa122f70b620d232c7ebb393ae3cbaafa98611953cf447c7d2b5e03958062", + "sha256": "eaea1b0547318aa395931cc9483f5d521c3aa0cb8276eac8aa083065c7e0f7a5", + "sourceBytes": 909848, + "bytes": 5210, + "resizedTo": { + "width": 260, + "height": 100 + } + } + ] +} diff --git a/web/public/assets/title/provenance.json b/web/public/assets/title/provenance.json new file mode 100644 index 0000000..ad7d558 --- /dev/null +++ b/web/public/assets/title/provenance.json @@ -0,0 +1,123 @@ +{ + "created": "2026-11-14", + "purpose": "Familiar title signpost artwork: four walnut boards, the post, bell, paper tag and parchment sheet", + "generator": { + "tool": "Codex CLI (`codex exec`, image_gen.imagegen built-in tool)", + "model": "gpt-6-astra", + "reasoningEffort": "ultra", + "cliVersion": "0.169.0", + "sessions": [ + { + "id": "01a1d945-d58a-7ba3-b35c-957915ee230b", + "files": [ + "title-plank-1.webp", + "title-plank-2.webp", + "title-plank-3.webp", + "title-plank-4.webp", + "title-post.webp", + "title-bell.webp", + "title-tag.webp", + "title-paper.webp" + ] + } + ] + }, + "styleReferences": [ + "web/assets/source/expedition/wooden-bridge.png", + "web/assets/source/first-light-motion/bram.png", + "web/assets/source/first-light-motion/harbor.png", + "web/assets/source/first-light-motion/lens.png", + "web/assets/source/first-light-motion/mochi.png" + ], + "delivery": "Original generated dimensions and object pixels are preserved in the PNG masters; only connected exterior cream was normalized to #F4EBD9 before delivery. Runtime WebPs are produced by scripts/optimize-title-assets.ts (see manifest.json): four-corner flood fill, alpha erosion and blur, trimmed object bounds and Lanczos resizing. Masters are never resized or modified by the optimizer.", + "files": { + "title-plank-1.webp": { + "master": "web/assets/source/title/title-plank-1.png", + "prompt": "Refine this single blank walnut board. Preserve exactly its beautiful softly modeled handmade clay-and-wood texture, dark warm walnut center, golden sunset top/right rim, single small iron nail on the far LEFT, worn gently chipped corners, square right end and front-on slight three-quarter camera. Make the board face about 12% TALLER while preserving its current width: its final silhouette width-to-height ratio must be 4.2 to 1, not a thin 4.6:1 strip. Keep it centered, with at least 7% image width clear cream space on both sides, and lots of cream above and below. Middle 80% of the face must remain very calm, low contrast dark brown, no knots/cracks/stains or nail heads. No text or symbols. Output 1536x1024 landscape at highest visual quality. Background must be solid #F4EBD9, perfectly uniform, no noise texture on background, no vignette, gradient, ground plane or shadow on backdrop. Only one solid blank wooden board, no arrow point, no extra objects, no holes, no letters/numbers/logos/watermarks.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d945-d58a-7ba3-b35c-957915ee230b/exec-0d362200-a5e2-4059-beca-c79f6360b0af.png", + "session": "01a1d945-d58a-7ba3-b35c-957915ee230b", + "attempts": 3, + "styleReferences": [ + "/Users/dadadave/.codex/generated_images/01a1d945-d58a-7ba3-b35c-957915ee230b/exec-4bb989fe-896b-47a8-bd68-72b09cf3a3ad.png" + ] + }, + "title-plank-2.webp": { + "master": "web/assets/source/title/title-plank-2.png", + "prompt": "Use case: precise-object-edit. The FIRST image is the individual board to correct, the SECOND is the approved hero for proportions and lighting. Regenerate the first board at highest quality, preserving its one small dark iron nail near the LEFT end, dark warm walnut quiet text face, rounded softly worn left edge and tiny upper-right corner chip. Match the second image's board proportions and canvas layout: output 1536x1024 landscape, NOT an ultrawide canvas. Board silhouette width:height exactly about 4.2:1, not the first image's long narrow 5.4:1 strip. Make board about 1280px wide by 305px tall, centered, with at least 8% image width clear space each side. Wood face around #5d432c, low contrast fine grain across middle80%, no knots/cracks/stains/nails there. Same golden back-right sunset rim, lilac-pink shadows, handmade clay-and-wood miniatures. Keep this board distinct from the hero through its upper-right chip and long fine grain. No arrow point. Perfectly flat uniform solid light cream #F4EBD9 backdrop, no backdrop grain/noise/gradient/vignette, no ground plane or cast shadow. One object only, no text, symbols, letters, logos or holes.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d945-d58a-7ba3-b35c-957915ee230b/exec-65a388e7-ee86-43cb-a34e-6ec21b3f391d.png", + "session": "01a1d945-d58a-7ba3-b35c-957915ee230b", + "attempts": 2, + "styleReferences": [ + "/Users/dadadave/.codex/generated_images/01a1d945-d58a-7ba3-b35c-957915ee230b/exec-efc46fc9-0fcf-4ab0-8995-edfd71ee5217.png", + "/Users/dadadave/.codex/generated_images/01a1d945-d58a-7ba3-b35c-957915ee230b/exec-0d362200-a5e2-4059-beca-c79f6360b0af.png" + ] + }, + "title-plank-3.webp": { + "master": "web/assets/source/title/title-plank-3.png", + "prompt": "Use case: stylized-concept. Highest available visual quality. Create ONE isolated production prop for Familiar. Reference 1 is the approved title hero board: all new props must be siblings of its handmade modeled material, soft edge treatment, warm walnut and sunset lighting. Reference 2 is the authoritative harbor scene, for camera, saturation, low warm sunset from the back RIGHT and soft lilac-pink sky bounce in shadows. Front-on eye level with a very slight three-quarter turn. Soft tactile felt-and-clay miniature diorama, softly worn edges, subtle subsurface warmth, no hard graphic outline, no flat vector/UI sticker look, no plastic gloss.\nBACKGROUND for the entire image: a perfectly flat uniform light cream #F4EBD9, edge to edge. No texture/noise on background, no gradient, no vignette, no ground plane, no cast shadow on backdrop, no scenery, no additional props, no frame. Every part of the object has at least 8% margin from every image edge. Only shading on the object. No enclosed see-through gaps: all holes/loops must be filled with solid material; no backdrop islands. No text, letters, numbers, symbols, emblems, signatures, logos or watermark.\nSUBJECT: one blank horizontal wooden sign board. Output 1536x1024 landscape. Make its silhouette 4.2 times as wide as tall, about 1280x305 pixels, centered, with safe 8% side margins. Match reference 1 closely in size, warm dark walnut face value (around #5d432c), thickness, camera, warm perimeter light, and small dark iron nail near the LEFT end (within the leftmost 7% of the board). This must be a distinct sibling, not a duplicated plank. Individual variation: a barely perceptible natural bow in the top and bottom long edges, a softer upper-left corner, and a different delicate horizontal grain. The bow is only about 1% of board width; broad quiet rectangular face remains.\nThe right end is square or very gently rounded, never an arrow. Soft rounded chipped corners, narrow warm worn edges. Central 80% of the face must be calm and dark for overlaid #FFF0CE text: low-contrast fine grain only, no knots, cracks, stains or nail heads. No text in this generated image. Do not add a border, a second nail or hardware. Reference 3 is only supporting wood family; do not copy the bridge.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d945-d58a-7ba3-b35c-957915ee230b/exec-ce085932-41fc-4c33-bf40-dc89d4b308b2.png", + "session": "01a1d945-d58a-7ba3-b35c-957915ee230b", + "attempts": 1, + "styleReferences": [ + "/Users/dadadave/.codex/generated_images/01a1d945-d58a-7ba3-b35c-957915ee230b/exec-0d362200-a5e2-4059-beca-c79f6360b0af.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/harbor.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/expedition/wooden-bridge.png" + ] + }, + "title-plank-4.webp": { + "master": "web/assets/source/title/title-plank-4.png", + "prompt": "Use case: stylized-concept. Highest available visual quality. Create ONE isolated production prop for Familiar. Reference 1 is the approved title hero board: all new props must be siblings of its handmade modeled material, soft edge treatment, warm walnut and sunset lighting. Reference 2 is the authoritative harbor scene, for camera, saturation, low warm sunset from the back RIGHT and soft lilac-pink sky bounce in shadows. Front-on eye level with a very slight three-quarter turn. Soft tactile felt-and-clay miniature diorama, softly worn edges, subtle subsurface warmth, no hard graphic outline, no flat vector/UI sticker look, no plastic gloss.\nBACKGROUND for the entire image: a perfectly flat uniform light cream #F4EBD9, edge to edge. No texture/noise on background, no gradient, no vignette, no ground plane, no cast shadow on backdrop, no scenery, no additional props, no frame. Every part of the object has at least 8% margin from every image edge. Only shading on the object. No enclosed see-through gaps: all holes/loops must be filled with solid material; no backdrop islands. No text, letters, numbers, symbols, emblems, signatures, logos or watermark.\nSUBJECT: one blank horizontal wooden sign board. Output 1536x1024 landscape. Make its silhouette 4.2 times as wide as tall, about 1280x305 pixels, centered, with safe 8% side margins. Match reference 1 closely in size, warm dark walnut face value (around #5d432c), thickness, camera, warm perimeter light, and small dark iron nail near the LEFT end (within the leftmost 7% of the board). This must be a distinct sibling, not a duplicated plank. Individual variation: a tiny wear notch confined to the bottom-right edge and softly rubbed upper-left corner; grain is finer and straighter than the hero, with a distinct edge chip pattern. Keep the board essentially straight.\nThe right end is square or very gently rounded, never an arrow. Soft rounded chipped corners, narrow warm worn edges. Central 80% of the face must be calm and dark for overlaid #FFF0CE text: low-contrast fine grain only, no knots, cracks, stains or nail heads. No text in this generated image. Do not add a border, a second nail or hardware. Reference 3 is only supporting wood family; do not copy the bridge.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d945-d58a-7ba3-b35c-957915ee230b/exec-e97e6b30-99b0-4f03-a4af-1311d5540252.png", + "session": "01a1d945-d58a-7ba3-b35c-957915ee230b", + "attempts": 1, + "styleReferences": [ + "/Users/dadadave/.codex/generated_images/01a1d945-d58a-7ba3-b35c-957915ee230b/exec-0d362200-a5e2-4059-beca-c79f6360b0af.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/harbor.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/expedition/wooden-bridge.png" + ] + }, + "title-post.webp": { + "master": "web/assets/source/title/title-post.png", + "prompt": "Precise single-object proportion edit, highest quality. Keep the supplied wooden post exactly as shown in all materials, soft sunset lighting, colors, location, full portrait 1024x1536 canvas, generous cream margin, two squat stones, little cap, short left arm and tiny downward iron hook. Change ONLY the narrow vertical shaft: make its width 20% greater while keeping height unchanged, and proportionally widen its cap. Current shaft is too thin; final shaft height to width should be approximately17:1. Keep the horizontal arm's current reach, around three final shaft widths. Preserve handmade warm walnut grain, gold right rim, lilac-pink shadows. No diagonal brace. Perfectly flat uniform #F4EBD9 backdrop with no shadow, floor, gradient, vignette or noise. No writing, text, symbols, other objects, gaps or holes. At least 10% clear top/bottom margin; do not zoom in.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d945-d58a-7ba3-b35c-957915ee230b/exec-01e588a9-19ea-43b6-b060-fcbb5e1fa23e.png", + "session": "01a1d945-d58a-7ba3-b35c-957915ee230b", + "attempts": 3, + "styleReferences": [ + "/Users/dadadave/.codex/generated_images/01a1d945-d58a-7ba3-b35c-957915ee230b/exec-c0359b84-5b31-40ff-900d-bb207d57ec24.png" + ] + }, + "title-bell.webp": { + "master": "web/assets/source/title/title-bell.png", + "prompt": "Precise single-object proportion edit at highest quality. Keep this polished brass miniature harbor bell, tiny simple solid dark iron hanger at top center, round clapper, straight knotted rope, compact soft felt tassel, golden sunset right rim and soft lilac reflections. Change ONLY the bell body's width: make brass bell and lip approximately16% NARROWER, maintaining all current vertical heights. Scale the round clapper down just a little to match narrower bell. Keep centered attachment point, rope and tassel aligned. Final overall connected object width:height approximately1:2.3 (about465px wide,1080px tall). Preserve exact portrait1024x1536 canvas and current generous top/bottom margins. No giant mounting plate, no wings, no loops or see-through holes. Uniform mathematically flat solid #F4EBD9 backdrop, no gradient, vignette, noise, cast shadow or ground plane. One object only, no letters/text/symbols/logos/signature.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d945-d58a-7ba3-b35c-957915ee230b/exec-0ac942d6-30e7-460a-8f46-f799a7fcdeaa.png", + "session": "01a1d945-d58a-7ba3-b35c-957915ee230b", + "attempts": 3, + "styleReferences": [ + "/Users/dadadave/.codex/generated_images/01a1d945-d58a-7ba3-b35c-957915ee230b/exec-0f4d6f72-9398-45f4-aba0-f23cd195fb1c.png" + ] + }, + "title-tag.webp": { + "master": "web/assets/source/title/title-tag.png", + "prompt": "Use case: stylized-concept. Highest available visual quality. Create ONE isolated production prop for Familiar. Reference 1 is the approved title hero board: all new props must be siblings of its handmade modeled material, soft edge treatment, warm walnut and sunset lighting. Reference 2 is the authoritative harbor scene, for camera, saturation, low warm sunset from the back RIGHT and soft lilac-pink sky bounce in shadows. Front-on eye level with a very slight three-quarter turn. Soft tactile felt-and-clay miniature diorama, softly worn edges, subtle subsurface warmth, no hard graphic outline, no flat vector/UI sticker look, no plastic gloss.\nBACKGROUND for the entire image: a perfectly flat uniform light cream #F4EBD9, edge to edge. No texture/noise on background, no gradient, no vignette, no ground plane, no cast shadow on backdrop, no scenery, no additional props, no frame. Every part of the object has at least 8% margin from every image edge. Only shading on the object. No enclosed see-through gaps: all holes/loops must be filled with solid material; no backdrop islands. No text, letters, numbers, symbols, emblems, signatures, logos or watermark.\nOutput LANDSCAPE 1536x1024.\nSUBJECT: one small blank handmade CREAM PAPER TAG, paper body about THREE times as wide as tall, approximately 1200px wide by 400px tall, centered in canvas. Delicate rounded cut corners, very slight curl at lower-right corner, tactile fine paper fibers like a miniature crafted by hand. At exact TOP CENTER a small short flax twine knot wraps over the edge of the paper, completely solid compact knot and short ends pressed together, NO punched hole, NO hanging loop or background gap. This is one connected object. Paper face light warm cream, in #F3E1B8 family. Middle 80% must be very calm, even and light: dark green #2D4637 game text will be drawn there in code. Absolutely NO generated letters or symbols. Thin warm ochre edge thickness and soft edge shading ALL AROUND its perimeter, enough separation from #F4EBD9 backdrop to preserve the silhouette on 8% corner floodfill, but NO ink outline or hard border. Tiny warm golden right edge, soft lilac-pink shadow at curled lower edge. Fine even texture, no stains, writing, decorations, fasteners or strong creases. The approved walnut hero governs light and crafted softness, not the tag's paper material.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d945-d58a-7ba3-b35c-957915ee230b/exec-fc069b7d-d649-4d96-bc84-2b3fb11cbc67.png", + "session": "01a1d945-d58a-7ba3-b35c-957915ee230b", + "attempts": 1, + "styleReferences": [ + "/Users/dadadave/.codex/generated_images/01a1d945-d58a-7ba3-b35c-957915ee230b/exec-0d362200-a5e2-4059-beca-c79f6360b0af.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/harbor.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/mochi.png" + ] + }, + "title-paper.webp": { + "master": "web/assets/source/title/title-paper.png", + "prompt": "Use case: precise-object-edit. Redesign the blank parchment in image1 so it reads as a delicate SHEET OF PAPER, not thick dough or a padded mat. Image2 sets the warm sunset and handmade harbor world. Highest visual quality, output PORTRAIT 1024x1536. Preserve the quiet blank cream face and subtle bottom-corner curls, but reduce edge thickness by 75%, reduce edge waviness, reduce heavy raised rim. Use finely deckled paper edges, not large undulating lobes. Fine subtle fiber texture evenly spread, no fur or wood grain, no stains, no strong creases. Almost-flat central85% in light warm cream #F3E1B8, ready for dark green overlaid code text, but generate absolutely no text. Subtle amber warm shading along the fine edge and lilac-pink underneath small bottom curls, not an outline, with enough edge contrast to separate from backdrop. Sheet silhouette width:height 5:6. Make sheet approximately 760px wide by 912px tall, centered, with at least 12% clear side margins. All corners safely inside canvas. Background perfectly flat solid uniform #F4EBD9 with no texture, gradient, vignette, cast shadow or floor. No marks, symbols, letters, borders, drawings, holes or additional objects. It must be soft tactile handmade thin paper that belongs to the harbor.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d945-d58a-7ba3-b35c-957915ee230b/exec-e44820bd-5232-4496-be8d-77117a4ea891.png", + "session": "01a1d945-d58a-7ba3-b35c-957915ee230b", + "attempts": 2, + "styleReferences": [ + "/Users/dadadave/.codex/generated_images/01a1d945-d58a-7ba3-b35c-957915ee230b/exec-6c1f9736-e11d-4f65-be1c-24a33480ec01.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/harbor.png" + ] + } + } +} diff --git a/web/public/assets/title/title-bell.webp b/web/public/assets/title/title-bell.webp new file mode 100644 index 0000000..68de539 Binary files /dev/null and b/web/public/assets/title/title-bell.webp differ diff --git a/web/public/assets/title/title-paper.webp b/web/public/assets/title/title-paper.webp new file mode 100644 index 0000000..79b03d4 Binary files /dev/null and b/web/public/assets/title/title-paper.webp differ diff --git a/web/public/assets/title/title-plank-1.webp b/web/public/assets/title/title-plank-1.webp new file mode 100644 index 0000000..9f7e399 Binary files /dev/null and b/web/public/assets/title/title-plank-1.webp differ diff --git a/web/public/assets/title/title-plank-2.webp b/web/public/assets/title/title-plank-2.webp new file mode 100644 index 0000000..121d2e9 Binary files /dev/null and b/web/public/assets/title/title-plank-2.webp differ diff --git a/web/public/assets/title/title-plank-3.webp b/web/public/assets/title/title-plank-3.webp new file mode 100644 index 0000000..9fc0857 Binary files /dev/null and b/web/public/assets/title/title-plank-3.webp differ diff --git a/web/public/assets/title/title-plank-4.webp b/web/public/assets/title/title-plank-4.webp new file mode 100644 index 0000000..6e1485a Binary files /dev/null and b/web/public/assets/title/title-plank-4.webp differ diff --git a/web/public/assets/title/title-post.webp b/web/public/assets/title/title-post.webp new file mode 100644 index 0000000..697b347 Binary files /dev/null and b/web/public/assets/title/title-post.webp differ diff --git a/web/public/assets/title/title-tag.webp b/web/public/assets/title/title-tag.webp new file mode 100644 index 0000000..db131c3 Binary files /dev/null and b/web/public/assets/title/title-tag.webp differ diff --git a/web/public/assets/ui/ask-all-marks.webp b/web/public/assets/ui/ask-all-marks.webp new file mode 100644 index 0000000..bb50257 Binary files /dev/null and b/web/public/assets/ui/ask-all-marks.webp differ diff --git a/web/public/assets/ui/ask-both-shells.webp b/web/public/assets/ui/ask-both-shells.webp new file mode 100644 index 0000000..2d12e3c Binary files /dev/null and b/web/public/assets/ui/ask-both-shells.webp differ diff --git a/web/public/assets/ui/ask-bridge.webp b/web/public/assets/ui/ask-bridge.webp new file mode 100644 index 0000000..fa805c5 Binary files /dev/null and b/web/public/assets/ui/ask-bridge.webp differ diff --git a/web/public/assets/ui/ask-coiled.webp b/web/public/assets/ui/ask-coiled.webp new file mode 100644 index 0000000..b482957 Binary files /dev/null and b/web/public/assets/ui/ask-coiled.webp differ diff --git a/web/public/assets/ui/ask-dry.webp b/web/public/assets/ui/ask-dry.webp new file mode 100644 index 0000000..4699d57 Binary files /dev/null and b/web/public/assets/ui/ask-dry.webp differ diff --git a/web/public/assets/ui/ask-lens.webp b/web/public/assets/ui/ask-lens.webp new file mode 100644 index 0000000..aaffc2e Binary files /dev/null and b/web/public/assets/ui/ask-lens.webp differ diff --git a/web/public/assets/ui/ask-moth.webp b/web/public/assets/ui/ask-moth.webp new file mode 100644 index 0000000..fb8f327 Binary files /dev/null and b/web/public/assets/ui/ask-moth.webp differ diff --git a/web/public/assets/ui/ask-no-wait.webp b/web/public/assets/ui/ask-no-wait.webp new file mode 100644 index 0000000..fbf6cd1 Binary files /dev/null and b/web/public/assets/ui/ask-no-wait.webp differ diff --git a/web/public/assets/ui/ask-one-crossing.webp b/web/public/assets/ui/ask-one-crossing.webp new file mode 100644 index 0000000..ad493c3 Binary files /dev/null and b/web/public/assets/ui/ask-one-crossing.webp differ diff --git a/web/public/assets/ui/ask-shut-shell.webp b/web/public/assets/ui/ask-shut-shell.webp new file mode 100644 index 0000000..1ef1ee4 Binary files /dev/null and b/web/public/assets/ui/ask-shut-shell.webp differ diff --git a/web/public/assets/ui/ask-splash.webp b/web/public/assets/ui/ask-splash.webp new file mode 100644 index 0000000..e494727 Binary files /dev/null and b/web/public/assets/ui/ask-splash.webp differ diff --git a/web/public/assets/ui/ask-within.webp b/web/public/assets/ui/ask-within.webp new file mode 100644 index 0000000..548df03 Binary files /dev/null and b/web/public/assets/ui/ask-within.webp differ diff --git a/web/public/assets/ui/manifest.json b/web/public/assets/ui/manifest.json new file mode 100644 index 0000000..8dbc9e1 --- /dev/null +++ b/web/public/assets/ui/manifest.json @@ -0,0 +1,299 @@ +{ + "purpose": "Painted UI runtime artwork; transparent cut-outs with original masters preserved", + "encoder": "magick four-corner floodfill per-asset fuzz/erode blur0x1 Lanczos + cwebp quality88 method6 alpha100 sharp_yuv", + "sharedPortraitCrop": { + "x": 202, + "y": 100, + "width": 852, + "height": 1049 + }, + "askContentSize": 84, + "askMargin": 6, + "files": [ + { + "source": "assets/source/ui/ask-all-marks.png", + "output": "assets/ui/ask-all-marks.webp", + "sourceSha256": "2b6fde1125c309b744ed08272924f00b52379e2b8a4dd8e31b86382a8bff7ddb", + "sha256": "642d8ab9d559cdc5ae6f8a3ee5dc619f71971a689e6cfaa90a8470e08ae9645a", + "sourceBytes": 284405, + "bytes": 1890, + "resizedTo": { + "width": 96, + "height": 96 + }, + "family": "ask", + "fuzz": 8, + "erode": 1 + }, + { + "source": "assets/source/ui/ask-both-shells.png", + "output": "assets/ui/ask-both-shells.webp", + "sourceSha256": "9138fe5fdbad0446ff6e7e766aea2fe36aede3b8b75e2f62abed03071cedf2b7", + "sha256": "9f2cddd44a8d5d8681ee1742ff87cb301e5ce8751bcfb292973832fcdaff2724", + "sourceBytes": 556120, + "bytes": 3626, + "resizedTo": { + "width": 96, + "height": 96 + }, + "family": "ask", + "fuzz": 8, + "erode": 1 + }, + { + "source": "assets/source/ui/ask-bridge.png", + "output": "assets/ui/ask-bridge.webp", + "sourceSha256": "8bec26911363f93fdf0541f3975df804e8ad2cf8b41bc7c7507f8770cfc748c6", + "sha256": "d92f175a44945491f6b43e0a6feff6dd42ebb400f46db33eae993f38ccb75505", + "sourceBytes": 378873, + "bytes": 2780, + "resizedTo": { + "width": 96, + "height": 96 + }, + "family": "ask", + "fuzz": 8, + "erode": 1 + }, + { + "source": "assets/source/ui/ask-coiled.png", + "output": "assets/ui/ask-coiled.webp", + "sourceSha256": "1676b668e8e8c68b8b59a35c08731e51f543a4adc157209ea9615be2cdaf7124", + "sha256": "d1addd7d7787958b79070d31910ed543dcf42a17b5afa856b5d1076b758ae0f1", + "sourceBytes": 679976, + "bytes": 3588, + "resizedTo": { + "width": 96, + "height": 96 + }, + "family": "ask", + "fuzz": 8, + "erode": 1 + }, + { + "source": "assets/source/ui/ask-dry.png", + "output": "assets/ui/ask-dry.webp", + "sourceSha256": "1ec777d2dadcf2b48f77ab32813a92b5df761b10efa2e40c07dbdd2eef01bf81", + "sha256": "52d6a9cbee733e055bbf0c7e78f3dc98f3da4f34d5361efee149a45a7ea6f800", + "sourceBytes": 894268, + "bytes": 3830, + "resizedTo": { + "width": 96, + "height": 96 + }, + "family": "ask", + "fuzz": 8, + "erode": 1 + }, + { + "source": "assets/source/ui/ask-lens.png", + "output": "assets/ui/ask-lens.webp", + "sourceSha256": "5f81289981ede39f3bdcbdfce8612c0c9f4b442500f76ad0cf0894536d9aceb2", + "sha256": "995768cd35d224a366daa1196fbb525c161ab533c82fb08ad95bab2a1e74d0b3", + "sourceBytes": 652931, + "bytes": 3928, + "resizedTo": { + "width": 96, + "height": 96 + }, + "family": "ask", + "fuzz": 8, + "erode": 1 + }, + { + "source": "assets/source/ui/ask-moth.png", + "output": "assets/ui/ask-moth.webp", + "sourceSha256": "28ee1913f12e75ffa880bd97c97d51ba6b3fc4aa6cedae88e57f26f609414f8c", + "sha256": "2940261fc8f92597790057d09d883af11ea87d5a6939940aadb8d1fb8bcbacf3", + "sourceBytes": 654777, + "bytes": 4096, + "resizedTo": { + "width": 96, + "height": 96 + }, + "family": "ask", + "fuzz": 8, + "erode": 1 + }, + { + "source": "assets/source/ui/ask-no-wait.png", + "output": "assets/ui/ask-no-wait.webp", + "sourceSha256": "07f269bffe48bbd4849ff23f678dfa62a4d8151fcf09eaf08ebf1d0472e073a1", + "sha256": "ee22eec578bafbb95b14cfff0606f1fea8c5381a6792165c49caab04a5e4faaf", + "sourceBytes": 372218, + "bytes": 2862, + "resizedTo": { + "width": 96, + "height": 96 + }, + "family": "ask", + "fuzz": 8, + "erode": 1 + }, + { + "source": "assets/source/ui/ask-one-crossing.png", + "output": "assets/ui/ask-one-crossing.webp", + "sourceSha256": "4fea3115c8599b01846448760b63bfb3ecafe98df8c6fdbc8236214cc7bc10ea", + "sha256": "e739889dedcd79bfcbee3ec925883e6fce4b009376e53e022f2b28566f89c439", + "sourceBytes": 520466, + "bytes": 2930, + "resizedTo": { + "width": 96, + "height": 96 + }, + "family": "ask", + "fuzz": 8, + "erode": 1 + }, + { + "source": "assets/source/ui/ask-shut-shell.png", + "output": "assets/ui/ask-shut-shell.webp", + "sourceSha256": "bced80b63cb580dae3f946c9d7185b460fac13f8287d7de74f6e4f96bb11ed2e", + "sha256": "2c16dbaf5dd29299252e0159b80e4127d7dd829fd88d05efdce7bc7443a8ca55", + "sourceBytes": 722134, + "bytes": 2978, + "resizedTo": { + "width": 96, + "height": 96 + }, + "family": "ask", + "fuzz": 8, + "erode": 1 + }, + { + "source": "assets/source/ui/ask-splash.png", + "output": "assets/ui/ask-splash.webp", + "sourceSha256": "444dbc5c65cb5dedb35029d41a91875ff36a030a3e1a3be10adaae759682a015", + "sha256": "661529803f8ad108a47992fa35ba26259dcfe4a49557b0185f2b33b664b89690", + "sourceBytes": 608042, + "bytes": 4248, + "resizedTo": { + "width": 96, + "height": 96 + }, + "family": "ask", + "fuzz": 8, + "erode": 1 + }, + { + "source": "assets/source/ui/ask-within.png", + "output": "assets/ui/ask-within.webp", + "sourceSha256": "4fe81ede5b8df100437460c3c52a0278ff516ef5fa7c58c37f50f01a35da5a0c", + "sha256": "c535215afcbe33895b66c7778f358f78ed9419c176bc57a5bddc06ec7b614e3e", + "sourceBytes": 413362, + "bytes": 2998, + "resizedTo": { + "width": 96, + "height": 96 + }, + "family": "ask", + "fuzz": 8, + "erode": 1 + }, + { + "source": "assets/source/ui/mochi-portrait.png", + "output": "assets/ui/mochi-portrait.webp", + "sourceSha256": "eed2974998310050308ceb9b105653579c85462904ed908b3ca4fb9ffcb9f44b", + "sha256": "cd81992ff446c4daf2cc36a80f788d9950f5957f18243cd2bf82b0dc6dd63d18", + "sourceBytes": 1126529, + "bytes": 15242, + "resizedTo": { + "width": 256, + "height": 256 + }, + "family": "portrait", + "fuzz": 4, + "erode": 1 + }, + { + "source": "assets/source/ui/mochi-portrait-proud.png", + "output": "assets/ui/mochi-portrait-proud.webp", + "sourceSha256": "3d328ae25ef06702e4311b63beb995bc47299434a88e0deb9093bb780c719fef", + "sha256": "700a88a1b408387465efdcc127ad8b6461df10442384e2aa8722120083f6b587", + "sourceBytes": 1085350, + "bytes": 15148, + "resizedTo": { + "width": 256, + "height": 256 + }, + "family": "portrait", + "fuzz": 4, + "erode": 1 + }, + { + "source": "assets/source/ui/mochi-portrait-splashed.png", + "output": "assets/ui/mochi-portrait-splashed.webp", + "sourceSha256": "c125818b1cb6580ee9bf8440f8e3f5a40939cf6020414a05da70d0796c08ac35", + "sha256": "49af4f36145de8eb0e857008494d222095c8d8bbd200600ce439857a47f4ebb7", + "sourceBytes": 1199076, + "bytes": 17396, + "resizedTo": { + "width": 256, + "height": 256 + }, + "family": "portrait", + "fuzz": 4, + "erode": 1 + }, + { + "source": "assets/source/ui/sign-beacon.png", + "output": "assets/ui/sign-beacon.webp", + "sourceSha256": "ce396916579271e73c937042e3511ecd99a2f282501fb4070f1e4d056e56b952", + "sha256": "7d4b864654aca70f470e37144419cd6888df0f1c2108574904a520028b3357d2", + "sourceBytes": 722365, + "bytes": 20738, + "resizedTo": { + "width": 480, + "height": 266 + }, + "family": "sign", + "fuzz": 4, + "erode": 1 + }, + { + "source": "assets/source/ui/sign-bram.png", + "output": "assets/ui/sign-bram.webp", + "sourceSha256": "6a7f6710aa741d273fd2205c3b38c4548cdfa34ec20c0e3ff4de4a1e905aa759", + "sha256": "1fd010597a6f8d96193163d729904e46b69482ee619d5001902d793362fffffb", + "sourceBytes": 734900, + "bytes": 22166, + "resizedTo": { + "width": 480, + "height": 266 + }, + "family": "sign", + "fuzz": 4, + "erode": 1 + }, + { + "source": "assets/source/ui/sign-satchel.png", + "output": "assets/ui/sign-satchel.webp", + "sourceSha256": "a0e762afe28f2e6acabf1b3c1b9fab67d82d2512a023f3c26703ccaf9405392d", + "sha256": "5c489cd845260715763987b5acde322e24320a3eb47f0084d3fcf49cee653311", + "sourceBytes": 730576, + "bytes": 21290, + "resizedTo": { + "width": 480, + "height": 266 + }, + "family": "sign", + "fuzz": 4, + "erode": 1 + }, + { + "source": "assets/source/ui/sign-workbench.png", + "output": "assets/ui/sign-workbench.webp", + "sourceSha256": "2b9382c1877252acd1d8bea959e6c09b48418edf85195de4c04666758541f49f", + "sha256": "494e33bbe660d959137598e3281f3bba888ff9e86ac33c369c53616f529f4ac3", + "sourceBytes": 768612, + "bytes": 22606, + "resizedTo": { + "width": 480, + "height": 265 + }, + "family": "sign", + "fuzz": 4, + "erode": 1 + } + ] +} diff --git a/web/public/assets/ui/mochi-portrait-proud.webp b/web/public/assets/ui/mochi-portrait-proud.webp new file mode 100644 index 0000000..80834df Binary files /dev/null and b/web/public/assets/ui/mochi-portrait-proud.webp differ diff --git a/web/public/assets/ui/mochi-portrait-splashed.webp b/web/public/assets/ui/mochi-portrait-splashed.webp new file mode 100644 index 0000000..dbd1823 Binary files /dev/null and b/web/public/assets/ui/mochi-portrait-splashed.webp differ diff --git a/web/public/assets/ui/mochi-portrait.webp b/web/public/assets/ui/mochi-portrait.webp new file mode 100644 index 0000000..58540d0 Binary files /dev/null and b/web/public/assets/ui/mochi-portrait.webp differ diff --git a/web/public/assets/ui/provenance.json b/web/public/assets/ui/provenance.json new file mode 100644 index 0000000..8f11baf --- /dev/null +++ b/web/public/assets/ui/provenance.json @@ -0,0 +1,624 @@ +{ + "created": "2026-11-14", + "purpose": "Familiar painted UI artwork: four harbor place signs, three interchangeable Mochi portraits and twelve Tidekeeper ask icons", + "generator": { + "tool": "Codex CLI (`codex exec`, image_gen.imagegen built-in tool)", + "model": "gpt-6-astra", + "reasoningEffort": "ultra", + "cliVersion": "0.169.0", + "cliVersionVerification": "Verified with codex --version on 2026-11-14; the supplied UI generation records do not independently record the CLI version.", + "sessions": [ + { + "id": "01a1d965-fc27-7472-bf21-a1199d209111", + "files": [ + "mochi-portrait.webp", + "sign-beacon.webp", + "sign-bram.webp", + "sign-satchel.webp", + "sign-workbench.webp" + ] + }, + { + "id": "01a1d966-102f-70d2-a3ea-f58c3dd8751e", + "files": [ + "ask-lens.webp", + "ask-no-wait.webp", + "ask-within.webp" + ] + }, + { + "id": "01a1d967-6170-7213-9784-0f8403ba32aa", + "files": [ + "ask-dry.webp", + "ask-moth.webp", + "ask-splash.webp" + ] + }, + { + "id": "01a1d96a-1a54-7810-8244-734e97bbe65f", + "files": [ + "ask-all-marks.webp", + "ask-bridge.webp", + "ask-one-crossing.webp" + ] + }, + { + "id": "01a1d96a-528d-7000-a4d3-31aa1cce014d", + "files": [ + "ask-both-shells.webp", + "ask-coiled.webp", + "ask-shut-shell.webp" + ] + }, + { + "id": "01a1d96a-6220-7512-acb3-ea840e2ddd7c", + "files": [ + "mochi-portrait-proud.webp", + "mochi-portrait-splashed.webp" + ] + } + ] + }, + "styleReferences": [ + "/Users/dadadave/.codex/generated_images/01a1d965-fc27-7472-bf21-a1199d209111/exec-b357f08c-c246-4943-a5b3-aea01c65b63f.png", + "/Users/dadadave/.codex/generated_images/01a1d965-fc27-7472-bf21-a1199d209111/exec-c15335cf-2d90-48c3-9f75-2e30c68b370a.png", + "/Users/dadadave/.codex/generated_images/01a1d966-102f-70d2-a3ea-f58c3dd8751e/exec-0270e35e-0472-4658-affd-e570dc8fb62f.png", + "/Users/dadadave/.codex/generated_images/01a1d966-102f-70d2-a3ea-f58c3dd8751e/exec-354e177f-842c-4487-854a-d339a8401013.png", + "/Users/dadadave/.codex/generated_images/01a1d96a-528d-7000-a4d3-31aa1cce014d/exec-6a4f06b6-a00d-45ff-a89a-32645e83b851.png", + "/Users/dadadave/.codex/generated_images/01a1d96a-528d-7000-a4d3-31aa1cce014d/exec-78c92453-375b-4529-bef9-196d77e9b73d.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/expedition/stone-island.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/expedition/wooden-bridge.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/bram.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/harbor.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/mochi-poses-source.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/mochi.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/moth.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/shell.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/wave.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/tide/seal-kept.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-lens.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-within.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/sign-beacon.png" + ], + "delivery": "The delivered cream-backed PNG masters are preserved byte-for-byte. Before delivery, signs and portraits had only their connected exterior backdrop normalized to #F4EBD9 at original dimensions; ask icons were extracted, trimmed and normalized to an 878 px longest object dimension on 1254 px cream squares, as recorded per file. Runtime WebPs are produced by scripts/optimize-ui-assets.ts (see manifest.json): four-corner flood fill and tuned alpha edge cleanup; signs trimmed to 480 px wide; all three portraits use one shared crop from the union of their alpha bounds, fitted into 256x256 transparent squares; ask icons are trimmed, fitted to 84 px and centered on 96x96 transparent squares with a six-pixel minimum margin. The optimizer never resizes or modifies the masters.", + "files": { + "ask-all-marks.webp": { + "master": "web/assets/source/ui/ask-all-marks.png", + "prompt": "Use case: stylized-concept. Create an exquisite finished square game UI icon for Familiar at highest visual quality. One compact arrangement consisting of EXACTLY THREE small round sandstone marker pebbles side by side in one straight HORIZONTAL ROW. Left, middle and right each distinct, with equal small gaps between them. Each is a chubby flattened rounded pebble with gently domed top, chunky bevel and the warm peach sandstone texture of reference 2. Each pebble has its own broad soft inner glow contained entirely INSIDE its stone surface: left sea-teal glow, middle honey-gold glow, right warm coral glow. They remain tactile carved sandstone stones, not glass gems, candy or buttons. The colored luminous center occupies most of each stone top, with subtly darker sandstone side faces. Absolutely NO markings or symbols on any stone: smooth unmarked surfaces. No swirl, carving, letters, numerals.\nReference1 is the approved hero icon: match its tactile hand-shaped clay miniature finish, broad value shapes, warm golden light from upper right, softly lit object rims and gentle saturated palette. Reference2 is the sandstone material authority only; do not copy island, spiral, moss or scene. Slightly top-down three-quarter view, see the round top and lower side thickness of all three. Entire trio centered at x50% y50%, overall width70% of square canvas with generous empty space all around. Readable at24px as three chunky luminous round pebbles, minimal texture/fine detail.\nBackground perfectly flat solid light cream #F4EBD9 edge-to-edge. No ground, cast/contact shadows, vignette, texture, gradient, halo or bloom outside objects. No enclosed see-through gaps. No extra objects. No text, numbers, arrows, slash, checkmark, graphic symbols, frame, badge circle or watermark.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d96a-1a54-7810-8244-734e97bbe65f/exec-4316fdc0-ca50-4f0c-91e0-64e35535c156.png", + "session": "01a1d96a-1a54-7810-8244-734e97bbe65f", + "attempts": 1, + "styleReferences": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-lens.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/expedition/stone-island.png" + ], + "masterSha256": "2b6fde1125c309b744ed08272924f00b52379e2b8a4dd8e31b86382a8bff7ddb", + "masterSize": { + "width": 1254, + "height": 1254 + }, + "masterPreparation": "ImageMagick 8% fuzz corner flood fill removes generated matte; trim; resize longest object dimension to 878 px; center on 1254 px square uniform #F4EBD9. No painted-object retouch.", + "regenerationNote": "First generation accepted after full-size inspection; final backdrop and occupancy normalized using corner fill.", + "rootSession": "01a1d966-102f-70d2-a3ea-f58c3dd8751e" + }, + "ask-both-shells.webp": { + "master": "web/assets/source/ui/ask-both-shells.png", + "prompt": "Use case: precise-object-edit. Refine the supplied TWO OPEN SHELLS icon for production cutout. Keep exactly two open scallop shells side by side, their geometry and separate dark inner bowls, five broad lobes, cute chunky handmade clay material, muted teal hinge nubs, same positions and camera, no extra objects. Reference 1 is approved hero, match its rich saturated values and lighting. Reference 2 is edit target.\nCRITICAL CHANGE: every outer contour pixel of both shells must be saturated CORAL or muted DEEP TEAL, strongly distinct from the flat cream backdrop. Replace the pale yellow-white highlights along shell outer edges with saturated warm coral-peach highlights, still visibly darker and redder than cream. No near-white highlights, especially upper right rims. Use richer burnt-coral shadows inside the cups. The golden upper-right lighting should model the surface WITHOUT bleaching its silhouette. Smooth clean sculpted contours.\nCenter pair within 70% width of square canvas, min15% margin.\nPerfectly uniform flat #F4EBD9 digital matte backdrop edge to edge, no noise/texture/gradient/halo/vignette/ground/shadows. No enclosed see-through holes. No text, numbers, letters, symbols, arrows, badges, watermarks. Highest quality PNG.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d96a-528d-7000-a4d3-31aa1cce014d/exec-6e3a9c9e-9b8b-4014-be39-fcaab1935208.png", + "session": "01a1d96a-528d-7000-a4d3-31aa1cce014d", + "attempts": 2, + "styleReferences": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-lens.png", + "/Users/dadadave/.codex/generated_images/01a1d96a-528d-7000-a4d3-31aa1cce014d/exec-78c92453-375b-4529-bef9-196d77e9b73d.png" + ], + "masterSha256": "9138fe5fdbad0446ff6e7e766aea2fe36aede3b8b75e2f62abed03071cedf2b7", + "masterSize": { + "width": 1254, + "height": 1254 + }, + "masterPreparation": "ImageMagick 8% fuzz corner flood fill removes generated matte; trim; resize longest object dimension to 878 px; center on 1254 px square uniform #F4EBD9. No painted-object retouch.", + "regenerationNote": "Regenerated to deepen coral edge highlights after 8% corner fill nibbled pale edges.", + "rootSession": "01a1d966-102f-70d2-a3ea-f58c3dd8751e", + "rejectedVersions": [ + { + "prompt": "Use case: stylized-concept. Paint one exquisite final UI ask icon for Familiar cozy harbor game, highest visual quality square PNG.\nSubject: TWO small coral-peach scallop shells SIDE BY SIDE, BOTH OPEN, their rounded fan-shaped upper valves lifted enough to expose two unmistakable deep warm coral inner cups. Each shell is a little hinged open clamshell with an upper fan and a lower bowl joined solidly at its hinge. There are exactly TWO complete shells. No pearls. The left shell is subtly smaller and tilted inward; the right shell is beside it, same size family, separated by a slim open background channel. Broad five-lobed scalloped fans, a few broad radial ribs, small muted teal accent at each hinge. Big simple chunky shell shapes, deep rust-coral interiors contrasted with salmon and peach lit edges; retain dark visible open mouths at 24px. No fine edge frills, no tiny decoration.\nReference image 1: approved hero icon, match tactile hand-shaped clay/felt surface, saturated but gentle palette, golden light from upper right, soft rim light ONLY on object, slightly top-down three-quarter camera and quality. Reference image 2: exact shell family shape, coral-peach color, teal hinge accent; transform that shell into two open shell objects. Reference image 3: soft miniature clay modeling only, do NOT copy badge or seal circle.\nComposition: the pair forms a single compact centered grouping filling about 70% canvas width, at least 15% margin all sides. No overlap that hides either opening.\nBackground perfectly flat uniform solid light cream #F4EBD9 edge to edge, digital flat matte. NO ground, cast shadow, contact shadow, halo, bloom, vignette, gradient or backdrop texture. No enclosed see-through gaps; all gaps between shells and around valves must connect to outside backdrop. No text, numbers, letters, symbols, arrows, slash, check marks, frames or watermarks. Objects only.", + "references": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-lens.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/shell.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/tide/seal-kept.png" + ], + "original_generated_path": "/Users/dadadave/.codex/generated_images/01a1d96a-528d-7000-a4d3-31aa1cce014d/exec-78c92453-375b-4529-bef9-196d77e9b73d.png", + "reason": "Pale upper-edge highlights were eaten by 8% corner fill, producing ragged contours." + } + ] + }, + "ask-bridge.webp": { + "master": "web/assets/source/ui/ask-bridge.png", + "prompt": "Use case: stylized-concept. Exquisite finished square game UI icon for Familiar, highest visual quality. A small honey-brown wooden footbridge resting on TWO little peach sandstone piers, one left and one right. Make a clear chunky bridge silhouette: a gently arched thick timber deck spans horizontally left-to-right between two stout rounded sandstone block feet. Each foot is about a quarter of the total width. The open space beneath the span is fully open DOWNWARD to the outer cream background, never an enclosed hole. Four broad transverse deck planks, a low solid wooden side beam, NO railings, posts, ropes, vegetation, water or platform beneath. Bridge must look unmistakably like a tiny complete bridge, different from an isolated flat plank segment.\nReference 1 is the approved hero: match its softly sculpted clay miniature craftsmanship, strong value separation, restrained tactile texture and upper-right warm golden key light. Reference 2 supplies warm wooden material, simplified heavily; reference 3 supplies warm rounded sandstone. No emblem or carved symbols from the stone reference. Slightly top-down three-quarter view with front face visible, deck top visible, left-to-right span; centered object occupies 70% of square canvas width, at least15% clear margins.\nSaturated but gentle amber wood, deeper chestnut underside, peach sandstone with caramel shadow faces. Soft rim light only on object. Strong simple forms remain readable at24px. Background is perfectly flat solid uniform cream #F4EBD9 edge to edge, no ground, cast/contact shadow, gradient, vignette or halo. One object only. No text, letters, numbers, arrows, slashes, checkmarks or symbols, no frame/badge/watermark.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d96a-1a54-7810-8244-734e97bbe65f/exec-20d5e719-8986-466c-8304-d414eda2c122.png", + "session": "01a1d96a-1a54-7810-8244-734e97bbe65f", + "attempts": 1, + "styleReferences": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-lens.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/expedition/wooden-bridge.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/expedition/stone-island.png" + ], + "masterSha256": "8bec26911363f93fdf0541f3975df804e8ad2cf8b41bc7c7507f8770cfc748c6", + "masterSize": { + "width": 1254, + "height": 1254 + }, + "masterPreparation": "ImageMagick 8% fuzz corner flood fill removes generated matte; trim; resize longest object dimension to 878 px; center on 1254 px square uniform #F4EBD9. No painted-object retouch.", + "regenerationNote": "First generation accepted after full-size inspection; final backdrop and occupancy normalized using corner fill.", + "rootSession": "01a1d966-102f-70d2-a3ea-f58c3dd8751e" + }, + "ask-coiled.webp": { + "master": "web/assets/source/ui/ask-coiled.png", + "prompt": "Use case: stylized-concept. Paint one exquisite final UI inventory icon for Familiar, a cozy harbor miniature game, highest visual quality square PNG.\nSubject: ONE neatly coiled harbor rope, low wide oval coil viewed slightly from above in three-quarter view. Three to four chunky honey-tan rope turns neatly nested in a compact low stack, with the short rope end tucked across the filled center. The center is filled by rope, not a background hole. Show the large twisting rope strands clearly but with minimal fine fibre detail. Strong contrast between golden raised strands and warm dark ochre creases. Soft felt-and-clay handmade miniature material. It must instantly read as rope even at 24 pixels, with a low oval silhouette distinct from an upright lens.\nImage 1 is the approved hero icon: match its tactile finish, richness, warm upper-right golden light and restrained rim light, slight top-down three-quarter camera, scale and simple silhouette. Image 2 supplies the harbor rope material and color only; DO NOT paint bridge or wood. Image 3 supplies soft hand-shaped clay texture only; do not paint its badge, shell or circle.\nComposition: centered single object filling about 70% canvas width with at least 15% clear margin, no props. Entire outer silhouette should be very clean, chunky, recognizable.\nBackground MUST be a perfectly flat solid light cream #F4EBD9, edge to edge, like digital matte color, with no texture, no gradient, no vignette, no ground plane, no cast or contact shadow and no halo. No enclosed see-through holes. No text, lettering, numbers, arrows, slash, checkmarks, symbols, frames, badge or watermark.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d96a-528d-7000-a4d3-31aa1cce014d/exec-4a0139e7-8f48-4f98-81ca-d93029a4e0c7.png", + "session": "01a1d96a-528d-7000-a4d3-31aa1cce014d", + "attempts": 1, + "styleReferences": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-lens.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/expedition/wooden-bridge.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/tide/seal-kept.png" + ], + "masterSha256": "1676b668e8e8c68b8b59a35c08731e51f543a4adc157209ea9615be2cdaf7124", + "masterSize": { + "width": 1254, + "height": 1254 + }, + "masterPreparation": "ImageMagick 8% fuzz corner flood fill removes generated matte; trim; resize longest object dimension to 878 px; center on 1254 px square uniform #F4EBD9. No painted-object retouch.", + "regenerationNote": "First generation accepted; normalized to common scale and flat matte using corner flood fill.", + "rootSession": "01a1d966-102f-70d2-a3ea-f58c3dd8751e" + }, + "ask-dry.webp": { + "master": "web/assets/source/ui/ask-dry.png", + "prompt": "Use case: stylized-concept. Paint one final master UI object icon for Familiar, cozy harbor puzzle game, highest available visual quality. Image 1 (ask-lens.png) is the exact set's tactile clay/felt polish, camera, warm light, big rounded forms and cream backdrop authority. Image 2 (mochi.png) supplies the orange kitten fur colour and plush material only. Subject: a single clean dry orange kitten paw, viewed from its soft underside so its rounded peach-pink central paw pad and four small toe pads are visible; a chubby three-dimensional soft felt paw with thick orange furry silhouette and tiny attached rounded wrist stump, NOT a printed paw symbol and NOT separate floating toe beans. Beside the paw at lower right sits one very tiny warm golden sun pebble, a plain plump amber-yellow pebble without rays, face or symbol. Treat this as one compact icon grouping. The paw is dominant, the sun pebble no more than one fifth of its size. Delicate visible felt texture but big simple shape, warm saturated gentle orange, clear shading between pads and fur; silhouette must read instantly at 24 pixels. Slightly top-down three-quarter view matching reference 1. Warm golden illumination from upper right and gentle soft rim light on object only. Center the object grouping; longest dimension about 70 percent of square canvas and at least 10 percent margin on every edge. Perfectly flat uniform cream background #F4EBD9 edge to edge. No ground plane, cast shadow, vignette, gradient, aura or halo. No water, dirt, shell, lens, cat face or full animal. No enclosed see-through gaps. No text, letters, numbers, arrows, slashes, check marks or other symbols, no frame or circular badge.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d967-6170-7213-9784-0f8403ba32aa/exec-5fa6d146-1b76-4f0a-b887-adff3611d8ae.png", + "session": "01a1d967-6170-7213-9784-0f8403ba32aa", + "attempts": 1, + "styleReferences": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-lens.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/mochi.png" + ], + "masterSha256": "1ec777d2dadcf2b48f77ab32813a92b5df761b10efa2e40c07dbdd2eef01bf81", + "masterSize": { + "width": 1254, + "height": 1254 + }, + "masterPreparation": "ImageMagick 8% fuzz corner flood fill removes generated matte; trim; resize longest object dimension to 878 px; center on 1254 px square uniform #F4EBD9. No painted-object retouch.", + "regenerationNote": "First generation retained: dimensional orange plush paw, peach pads, small warm sun pebble, clean silhouette. Inspected generated image and normalized full-size cream master.", + "rootSession": "01a1d966-102f-70d2-a3ea-f58c3dd8751e" + }, + "ask-lens.webp": { + "master": "web/assets/source/ui/ask-lens.png", + "prompt": "Precisely refine this Beacon Lens game icon. Preserve the beautiful chunky amber Fresnel glass, tactile brass, muted teal foot, exact design, same three-quarter view and upper-right warm lighting. Deliver highest-quality square PNG. Make the entire object SMALLER: its bounding box must be 70% of canvas height, from y=15% to y=85%, centered at x=50%, y=50%. It currently is too tall. Leave generous empty margins. Background must be absolutely flat solid #F4EBD9 everywhere with zero texture, no mottling, no vignette, no gradients, no ground, no shadows. Isolated object on a digital flat-color matte. No text or symbols. No enclosed see-through holes. Retain the rich sculpted depth on the OBJECT only, not on the background.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d966-102f-70d2-a3ea-f58c3dd8751e/exec-eee8d422-da02-46d4-9879-99552d719c9d.png", + "session": "01a1d966-102f-70d2-a3ea-f58c3dd8751e", + "attempts": 2, + "styleReferences": [ + "/Users/dadadave/.codex/generated_images/01a1d966-102f-70d2-a3ea-f58c3dd8751e/exec-354e177f-842c-4487-854a-d339a8401013.png" + ], + "masterSha256": "5f81289981ede39f3bdcbdfce8612c0c9f4b442500f76ad0cf0894536d9aceb2", + "masterSize": { + "width": 1254, + "height": 1254 + }, + "masterPreparation": "ImageMagick 8% fuzz corner flood fill removes generated matte; trim; resize longest object dimension to 878 px; center on 1254 px square uniform #F4EBD9. No painted-object retouch.", + "regenerationNote": "Reduced oversized hero to the shared 70% canvas occupancy; requested perfectly flat cream backdrop.", + "rootSession": "01a1d966-102f-70d2-a3ea-f58c3dd8751e", + "rejectedVersions": [ + { + "name": "ask-lens.png", + "prompt": "Use case: stylized-concept. Create one exquisite final game UI icon, square 1024x1024 PNG, highest visual quality.\nSubject: the Beacon Lens from reference 1: a thick round antique warm brass lighthouse Fresnel lens, amber glass with three broad concentric ridges, a chunky little brass cradle and low teal-patinated brass foot. Preserve its identity but simplify drastically for recognition at 24 pixels. No delicate framework: the cradle hugs the lens with no enclosed background holes. The lens glass is opaque luminous honey and smoky teal, never transparent to the backdrop. The large round optic is the hero.\nReferences: image 1 is exact subject identity; image 2 is felt/clay miniature art treatment and warm family palette; image 3 is material/world context only. Do not reproduce their scenes, seal circle or backgrounds.\nComposition: one centered object, slightly top-down three-quarter view, face turned a little to viewer left so its right rim has depth. Entire object fits within a centered 70% by 70% box, all extremities at least 12% from edges. Strong chunky silhouette, broad value separations, minimal ornament, no fine scratches. Rich tactile hand-painted clay and softly worn brass with gentle miniature surface texture. Warm golden key light from upper right, restrained soft rim light only on the object. Deep warm brown and muted teal lower-left recesses.\nBackground: perfectly flat uniform solid light cream #F4EBD9 edge to edge. Treat it as a flat matte cutout color, NOT a photographed surface. No ground plane, NO cast shadow on background, no contact shadow, no vignette, no gradient, no halo, no bloom beyond silhouette.\nOnly the object. No text, letters, numbers, arrows, slash, check marks, pictograms, watermark, frame, badge, circle behind object. This is the hero that will define a cohesive twelve-icon set.", + "references": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/lens.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/tide/seal-kept.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/tide/card-surf-home.png" + ], + "original_generated_path": "/Users/dadadave/.codex/generated_images/01a1d966-102f-70d2-a3ea-f58c3dd8751e/exec-354e177f-842c-4487-854a-d339a8401013.png", + "rejection": "Object too large vertically (about 84%); cream backdrop has slight mottling. Regenerate with smaller object and flat backdrop.", + "codex_session_id": "01a1d966-102f-70d2-a3ea-f58c3dd8751e", + "pixel_size": [ + 1254, + 1254 + ], + "source_part": "/Users/dadadave/.codex/specs/familiar-tidekeepers-ask-2026-11-14/art-provenance/part-lens-hourglasses.json" + } + ] + }, + "ask-moth.webp": { + "master": "web/assets/source/ui/ask-moth.png", + "prompt": "Use case: stylized-concept. Create one final master UI object icon for Familiar, the cozy harbor puzzle game, at highest available visual quality. Image 1 (ask-lens.png) is exact set authority for tactile clay/felt polish, upper-right golden light, camera, scale and backdrop; image 2 (moth.png) supplies subject identity. Subject: one friendly glowing wind-moth with exactly four chunky broad pointed wings, two simple short thick antennae, a round HONEY-TAN FELT HEAD, two shiny dark eyes and a tiny smile, short plush hands and golden abdomen. Crucial extraction requirement: the entire outer silhouette INCLUDING THE TOP OF THE HEAD must have rich medium golden-brown/honey colour, clearly much darker and more saturated than the cream backdrop; absolutely no cream-white pale fur along the outer edge. The head is warm caramel honey felt, bright but never pale ivory. Four wings have rich amber thick edges and softly glowing golden inner surfaces, each with just one broad curved glowing inset; no filigree, no veins. Glow and rim light stay INSIDE the form, no halo. A beautiful dimensional handcrafted felt/clay miniature, not a flat vector or symbol, simplified to big readable shapes at 24 pixels. Slightly top-down three-quarter view. Warm light from upper right. Centered subject fills 70 percent of square canvas at longest extent with minimum 10 percent margin. Uniform flat solid cream #F4EBD9 backdrop edge to edge, no ground, cast shadow, vignette, gradient, aura, frame or badge circle. No enclosed see-through gaps, text, letters, numbers, arrows, slashes, check marks, stars, graphic symbols or additional objects.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d967-6170-7213-9784-0f8403ba32aa/exec-5bb3a18f-18da-4f50-84ff-b2332b3b9802.png", + "session": "01a1d967-6170-7213-9784-0f8403ba32aa", + "attempts": 2, + "styleReferences": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-lens.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/moth.png" + ], + "masterSha256": "28ee1913f12e75ffa880bd97c97d51ba6b3fc4aa6cedae88e57f26f609414f8c", + "masterSize": { + "width": 1254, + "height": 1254 + }, + "masterPreparation": "ImageMagick 8% fuzz corner flood fill removes generated matte; trim; resize longest object dimension to 878 px; center on 1254 px square uniform #F4EBD9. No painted-object retouch.", + "regenerationNote": "Rejected first moth: pale cream outer head highlights connected to backdrop and were eroded by 8% corner flood fill. Regenerated with rich honey-tan head silhouette, preserved dark eyes and plush material. Inspected final cream master and full-size dark-teal cutout; intact.", + "rootSession": "01a1d966-102f-70d2-a3ea-f58c3dd8751e", + "rejectedVersions": [ + { + "original_generated_path": "/Users/dadadave/.codex/generated_images/01a1d967-6170-7213-9784-0f8403ba32aa/exec-1f1267d2-ceb1-469b-b4e3-4e182f284122.png", + "prompt": "Use case: stylized-concept. Create one final master UI object icon for Familiar, the cozy harbor puzzle game, at the highest available visual quality. Image 1 (ask-lens.png) is the exact set style, camera, light, simple chunky sculptural finish, scale and backdrop authority; image 2 (moth.png) is subject identity only. Subject: the glowing wind-moth, one friendly small plush moth with a round cream felt head, two dark shiny eyes, a tiny smile, stout golden abdomen, exactly four broad softly pointed wings, and two simple short thick antennae. Preserve the moth's identity, but simplify all filigree to just one broad curved glow inset per wing; no hairline veins or filigree. Wing edges are thick deep honey amber, wings warm gold/ivory, luminous highlights entirely contained INSIDE the object with absolutely no aura on the background. Warm golden light from upper right, soft rim light contained on its form, tactile felt and softly painted clay miniature materials. Slightly top-down three-quarter view matching image 1. A clear big simple silhouette readable at 24 pixels. Object centered, occupies about 70% of square canvas at longest extent; at least 10% clear margin on every side. Perfectly uniform flat solid light cream #F4EBD9 backdrop edge to edge. No ground plane, no cast shadow, no gradient, no vignette, no halo, no frame, no badge circle. No enclosed see-through gaps. No other objects, no text, letters, numbers, arrows, slashes, check marks, stars or graphic symbols.", + "reason": "8% corner extraction eroded crown highlights." + } + ] + }, + "ask-no-wait.webp": { + "master": "web/assets/source/ui/ask-no-wait.png", + "prompt": "Create a refined final game icon at highest visual quality, square PNG. Reference1 is the approved UPRIGHT brass hourglass; reference2 is the hero material and lighting. Make precisely the same kind of pocket hourglass as reference1, but lying STRICTLY HORIZONTALLY on its side with its axis left to right. It must read as a classic hourglass, NOT candy, a dumbbell, a bow tie, or binoculars.\nUse TWO SIMPLE FLAT BRASS DISK CAPS at the left/right ends, each thin in axial depth and viewed in perspective from a little above. NO extra round knobs, buttons, tiers or protrusions on the end faces. The hourglass glass tube between caps takes up 75% of the object's length and has a dramatic very narrow neck in its center. Its two rounded triangular lobes taper strongly to the neck. Distinctly hourglass-shaped sea-green glass with a golden sand bank resting along the LOWER SIDE of both chambers, sand horizontal and completely still. No sand stream. Glass is opaque sea-glass color with broad highlights and darker teal borders, not transparent to background. No support posts/rods/handle or any enclosed see-through gap. It is a sculpted tactile mini object, never a flat symbol.\nMatch the reference's soft clay-like brushed gold brass, warm upper-right golden light and subtle rim light, slight top-down three-quarter view. Strong simple silhouette at 24px. Center whole object, fill70% of square canvas width and leave generous15% margins. Absolutely uniform flat solid cream #F4EBD9 backdrop edge to edge with zero texture, floor, shadow, ground, vignette, halo or gradient. No text, letters, numbers, arrows, slashes, checkmarks, signs, frame, badge or any other objects.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d966-102f-70d2-a3ea-f58c3dd8751e/exec-919c17c5-14f7-4cf6-9429-49a3ab251ac2.png", + "session": "01a1d966-102f-70d2-a3ea-f58c3dd8751e", + "attempts": 2, + "styleReferences": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-within.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-lens.png" + ], + "masterSha256": "07f269bffe48bbd4849ff23f678dfa62a4d8151fcf09eaf08ebf1d0472e073a1", + "masterSize": { + "width": 1254, + "height": 1254 + }, + "masterPreparation": "ImageMagick 8% fuzz corner flood fill removes generated matte; trim; resize longest object dimension to 878 px; center on 1254 px square uniform #F4EBD9. No painted-object retouch.", + "regenerationNote": "Regenerated after 24px review: removed tiered end knobs, strengthened hourglass waist and settled sand.", + "rootSession": "01a1d966-102f-70d2-a3ea-f58c3dd8751e", + "rejectedVersions": [ + { + "name": "ask-no-wait.png", + "prompt": "Use case: stylized-concept. Create one final exquisite Familiar game ask icon at highest quality, square PNG. Reference 1 is the approved hero: match its tactile hand-painted clay miniature and softly worn rich golden brass, warm golden key light from upper right, shadowed teal lower-left depth, restrained soft rim light and slightly top-down three-quarter viewing angle.\nSubject: ONE tiny brass pocket hourglass lying COMPLETELY HORIZONTAL on its side, long axis left-to-right. This means never wait a turn. Big thick rounded warm brass end caps, a single broad sea-green glass hourglass bulb, pinch in center, sand completely still settled in a continuous low horizontal bank along the lower side of the glass. No pouring sand. The glass is opaque colored sea glass with broad highlights and clearly visible golden sand: not see-through to background. Keep a single continuous solid silhouette, no side rails or support rods creating enclosed see-through gaps. Chunky magical miniature, not a flat pictogram. No stand or ground. 24px recognition must be instantly horizontal hourglass, with unmistakable pinched waist and two large brass end caps.\nOne centered object occupying 70% of canvas width, at least 15% clear margins all around. Broad readable shapes, very little fine detail. Absolutely uniform solid cream #F4EBD9 background edge to edge, digital matte with NO texture or vignette. No ground, cast shadow, contact shadow, gradient or glow on backdrop. No text, letters, numbers, arrows, slashes, checkmarks, symbols, face, clock dial, badge, frame, extra objects.", + "references": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-lens.png" + ], + "original_generated_path": "/Users/dadadave/.codex/generated_images/01a1d966-102f-70d2-a3ea-f58c3dd8751e/exec-0270e35e-0472-4658-affd-e570dc8fb62f.png", + "regeneration_note": "Initial generation; horizontal axis and settled sand distinguish never-wait from upright time limit.", + "rejection": "Independent 24px review read the large tiered end caps as wrapped candy/dumbbell. Regenerated using simpler flat caps and a narrower waist.", + "codex_session_id": "01a1d966-102f-70d2-a3ea-f58c3dd8751e", + "pixel_size": [ + 1254, + 1254 + ], + "source_part": "/Users/dadadave/.codex/specs/familiar-tidekeepers-ask-2026-11-14/art-provenance/part-lens-hourglasses.json" + } + ] + }, + "ask-one-crossing.webp": { + "master": "web/assets/source/ui/ask-one-crossing.png", + "prompt": "Use case: stylized-concept. Paint an exquisite final square game UI icon, highest quality: one short wooden footbridge plank segment for the cozy harbor game Familiar. Reference 1 is the approved hero icon: match its tactile hand-shaped clay miniature polish, rich warm shading, chunky form language and scale. Reference 2 supplies the honey-brown weathered wooden bridge material; simplify it heavily. Subject is only a compact RECTANGULAR SEGMENT of THREE broad adjacent wooden deck planks joined tightly over two little hidden underside crosspieces. Three softly rounded planks with subtly uneven ends; just two dark seams and a few simple broad wood grain lines. No railings, posts, ropes or stone piers. The object must read at 24 pixels as a small flat wooden footbridge segment, not as a whole bridge or a crate. View slightly top-down three-quarter, segment recedes gently toward upper right; long silhouette mostly horizontal, not vertical. Warm golden light from upper right, soft rim highlights ON THE OBJECT only; gentle tactile surface, saturated but soft colors, dark chestnut undersides. Center the entire object within 70% of square canvas width, with at least 15% clear margin on all sides.\nPerfectly flat uniform solid light cream #F4EBD9 backdrop edge to edge. No ground plane, cast shadow, contact shadow, vignette, gradient or halo. No enclosed see-through gaps: planks touch. Only this one object, no decorations. No text, numbers, letters, arrows, slashes, checkmarks, icons, symbols, frame, badge circle, watermark.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d96a-1a54-7810-8244-734e97bbe65f/exec-b1005026-6de5-439e-848f-5e77bcb055f3.png", + "session": "01a1d96a-1a54-7810-8244-734e97bbe65f", + "attempts": 1, + "styleReferences": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-lens.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/expedition/wooden-bridge.png" + ], + "masterSha256": "4fea3115c8599b01846448760b63bfb3ecafe98df8c6fdbc8236214cc7bc10ea", + "masterSize": { + "width": 1254, + "height": 1254 + }, + "masterPreparation": "ImageMagick 8% fuzz corner flood fill removes generated matte; trim; resize longest object dimension to 878 px; center on 1254 px square uniform #F4EBD9. No painted-object retouch.", + "regenerationNote": "First generation accepted after full-size inspection; final backdrop and occupancy normalized using corner fill.", + "rootSession": "01a1d966-102f-70d2-a3ea-f58c3dd8751e" + }, + "ask-shut-shell.webp": { + "master": "web/assets/source/ui/ask-shut-shell.png", + "prompt": "Use case: stylized-concept. Paint one exquisite final game UI icon: ONE firmly CLOSED coral scallop shell, highest quality square PNG.\nReference1 is the approved hero icon; match its tactile miniature clay/felt polish, warm upper-right golden light, soft rim light, slight top-down three-quarter view. Reference2 is the EXACT REQUIRED SILHOUETTE and orientation: classic scallop fan with its NARROW HINGE AT THE BOTTOM, broad scalloped rim SPREADING UPWARD. Reference3 provides the rich coral color and teal hinge values only, not pose.\nCRITICAL: Fan opens its SHAPE upward like reference2, but its two physical shell valves are firmly SHUT together. The five broad ridges radiate from a small teal hinge at the BOTTOM CENTER up to a wide scalloped TOP edge. The outer silhouette must be fan-shaped: widest across upper third, distinctly narrowing toward bottom hinge, NOT round, NOT pumpkin shaped, no stem on top. Show the upper valve angled slightly back so a slim warm dark closed seam and thick lower valve are visible along lower-right side. No open mouth, no visible interior.\nFive broad smooth raised clay ribs and scallops only, minimal ornament, no tiny decorative curls. Rich coral-orange body, salmon highlights, burnt-coral shadows, a muted teal small bottom hinge. Highlights stay saturated darker/redder than cream, never bleach the outer edge. Strong chunky silhouette and broad value masses recognizable at24px.\nCenter shell within a 70% canvas bounding box, minimum15% margin. Perfectly flat uniform solid #F4EBD9 background edge to edge; digital flat matte, no background texture, no gradient, no vignette, NO ground plane, contact shadow, cast shadow, halo or bloom. No enclosed see-through holes. No text, numbers, letters, arrows, symbols, slash, check marks, badge, frame or extra objects.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d96a-528d-7000-a4d3-31aa1cce014d/exec-9b4deef8-a96e-4980-8b04-1e1cead0ee70.png", + "session": "01a1d96a-528d-7000-a4d3-31aa1cce014d", + "attempts": 3, + "styleReferences": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-lens.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/shell.png", + "/Users/dadadave/.codex/generated_images/01a1d96a-528d-7000-a4d3-31aa1cce014d/exec-6a4f06b6-a00d-45ff-a89a-32645e83b851.png" + ], + "masterSha256": "bced80b63cb580dae3f946c9d7185b460fac13f8287d7de74f6e4f96bb11ed2e", + "masterSize": { + "width": 1254, + "height": 1254 + }, + "masterPreparation": "ImageMagick 8% fuzz corner flood fill removes generated matte; trim; resize longest object dimension to 878 px; center on 1254 px square uniform #F4EBD9. No painted-object retouch.", + "regenerationNote": "First corrected pale hinge highlight damaged by 8% corner fill; then changed top-hinge pose to classic upward fan with bottom hinge after review found a pumpkin silhouette at24px.", + "rootSession": "01a1d966-102f-70d2-a3ea-f58c3dd8751e", + "rejectedVersions": [ + { + "prompt": "Use case: stylized-concept. Paint one exquisite final UI ask icon for Familiar cozy harbor game, highest visual quality square PNG.\nSubject: ONE scallop shell firmly CLOSED, a single uninterrupted broad coral-peach fan shape, with five broad softly rounded scallops and deep gentle radial ribs. Show a short thick lower valve tucked tightly against the upper valve, with only a slim warm-dark seam along its forward lower lip, absolutely no open mouth, no visible interior. Small softly worn muted teal hinge nub. The shell is lying down with fan edge toward the viewer and hinge a little farther away, viewed slightly top-down in three-quarter view so its thick clay form reads. Rich coral sides, warm peach highlights, substantial warm-dark underside. Strong simple chunky silhouette with broad value masses, minimal fine detail, readable as a shut scallop at 24 pixels.\nImage 1 is the approved lens hero: match its exquisite tactile hand-painted clay/felt material, saturated gentle color, warm golden key light from upper right and soft rim light only on object, scale and miniature camera. Image 2 is the exact shell family: preserve scallop identity, coral-peach color and muted teal hinge accent, but make it firmly closed with a visible tight seam and chunky proportions. Image 3 is miniature clay texture reference only; do not copy badge/seal circle.\nComposition: only this single shell, centered, fills about 70% canvas width and height bounding box, at least 15% clear margin on all sides.\nBackground: absolutely uniform flat solid light cream #F4EBD9 edge to edge. Digital matte, no backdrop texture, NO ground plane, contact shadow, cast shadow, vignette, gradient, halo, bloom or enclosing badge. No enclosed see-through holes. No text, letters, numbers, symbols, arrows, slash, check marks, frame, watermark or extra objects.", + "references": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-lens.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/shell.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/tide/seal-kept.png" + ], + "original_generated_path": "/Users/dadadave/.codex/generated_images/01a1d96a-528d-7000-a4d3-31aa1cce014d/exec-7bb275ce-fc1e-4bcf-9f1b-df80f535e20a.png", + "reason": "Pale top teal hinge highlights were eaten by 8% corner fill." + }, + { + "prompt": "Use case: precise-object-edit. Final production polish of single CLOSED scallop shell game icon, highest quality square PNG. Reference1 is approved hero style; reference2 is edit target; reference3 shows the matching open shells and their refined coral-teal values.\nPreserve reference2's single firmly shut scallop shape, five broad ribs and scallops, solid thick upper and lower valves, tight dark seam, muted teal hinge at back, centered slightly top-down three-quarter view. Change only the excessive pale edge highlights: the upper teal hinge currently has near-cream highlights that disappear on background removal. Make hinge medium deep teal with rich golden-green lighting that never approaches cream. Give shell outer contour saturated coral-peach edge highlights, darker and redder than cream, NO near-white bleached rim. Match reference3's rich coral family while retaining gentle warm golden modeling. Clay/felt tactile miniature finish, minimal fine details, large broad value shapes for 24px.\nCenter within70% width, min15% margin. Flat uniform solid #F4EBD9 digital matte background edge to edge, NO gradients, texture, ground, shadows, halos, vignette. No enclosed see-through holes, no open mouth/interior, no pearl. No text, letters, numbers, symbols, frame, badge, watermark or extra objects.", + "references": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-lens.png", + "/Users/dadadave/.codex/generated_images/01a1d96a-528d-7000-a4d3-31aa1cce014d/exec-7bb275ce-fc1e-4bcf-9f1b-df80f535e20a.png", + "/Users/dadadave/.codex/generated_images/01a1d96a-528d-7000-a4d3-31aa1cce014d/exec-6e3a9c9e-9b8b-4014-be39-fcaab1935208.png" + ], + "original_generated_path": "/Users/dadadave/.codex/generated_images/01a1d96a-528d-7000-a4d3-31aa1cce014d/exec-6a4f06b6-a00d-45ff-a89a-32645e83b851.png", + "reason": "At24px the top teal hinge and rounded lower lobes read as a pumpkin. Reversed to classic upward fan with hinge at bottom." + } + ] + }, + "ask-splash.webp": { + "master": "web/assets/source/ui/ask-splash.png", + "prompt": "Use case: stylized-concept. Create one gorgeous final master UI object icon for Familiar cozy harbor game, at highest available visual quality. Image 1 ask-lens.png is exact set authority for tactile painted clay, warm golden light from upper right, chunky polished miniature forms, camera and scale. Image 2 wave.png supplies sea-water material and teal hue. Subject: one small lively teal water splash with a compact thick irregular body, three broad upward curling lobes, and exactly three chunky round teal droplets close above the body. Dark rich teal body shaded with broad turquoise inner highlights. A few softly rounded MINT GREEN foam caps on the three tips; ALL FOAM OUTER EDGES must be saturated medium seafoam-green clearly distinct from cream background, NO white or ivory along silhouette. Mint caps feel soft felt/clay, with bright highlights only inset inside the caps. Crucial: background corner flood fill with 8 percent colour tolerance must never eat into the object. Every outside edge including foam must remain sufficiently saturated/dark. No pale white outer highlights. Water feels lustrous and handcrafted. No thin spikes, spray mist, veins or hairline details. A strong simple chunky silhouette that reads as splash at 24 pixels, not a repeated wave pattern. Slightly top-down three-quarter view matching image 1. Compact centered grouping fills 70 percent of square canvas at longest extent; all droplets have 10 percent clear margins. Perfectly flat uniform solid cream #F4EBD9 background edge to edge. No ground, base, sea, platform, lens or other object. No shadow on background, no gradient, vignette, halo, frame or badge circle. No enclosed see-through holes, no text, letters, numbers, arrows, slashes, check marks, stars or graphic symbols.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d967-6170-7213-9784-0f8403ba32aa/exec-394c548d-89f4-4cf9-a32f-914428e451f4.png", + "session": "01a1d967-6170-7213-9784-0f8403ba32aa", + "attempts": 2, + "styleReferences": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-lens.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/wave.png" + ], + "masterSha256": "444dbc5c65cb5dedb35029d41a91875ff36a030a3e1a3be10adaae759682a015", + "masterSize": { + "width": 1254, + "height": 1254 + }, + "masterPreparation": "ImageMagick 8% fuzz corner flood fill removes generated matte; trim; resize longest object dimension to 878 px; center on 1254 px square uniform #F4EBD9. No painted-object retouch.", + "regenerationNote": "Rejected first splash: cream foam caps connected to backdrop and were eroded by 8% corner flood fill. Regenerated with saturated seafoam-green caps over rich teal water; full-size dark-teal cutout verified intact.", + "rootSession": "01a1d966-102f-70d2-a3ea-f58c3dd8751e", + "rejectedVersions": [ + { + "original_generated_path": "/Users/dadadave/.codex/generated_images/01a1d967-6170-7213-9784-0f8403ba32aa/exec-d8d56715-c575-4ef2-84e8-8f3eeb13fcd2.png", + "prompt": "Use case: stylized-concept. Create one beautiful final master UI object icon for Familiar, cozy harbor puzzle game, at highest available visual quality. Image 1 (ask-lens.png) is exact authority for matching the set's tactile painted clay polish, chunky forms, upper-right golden light, slightly top-down three-quarter camera, scale and cream backdrop. Image 2 (wave.png) is water colour and tactile material reference only. Subject: one small lively teal water splash, sculpted like a rounded miniature of sea-glass and soft painted clay: a compact thick irregular splash body with three broad upward curling lobes and just three generous round water droplets closely above it. No circular wave tunnel. Dark saturated teal body with broad mint-turquoise inner highlights and a few creamy foam lobes at tips; lustrous water that still feels handcrafted, no thin spikes or hairline foam. A simple strong graphic silhouette with dimensional material, readable at 24 pixels. No sea, base, ground, platform or other object. Main body and droplets form a centered compact grouping filling about 70 percent of the square canvas at longest extent; keep all marks and droplets at least 10 percent away from edges. Warm golden light from upper right and gentle soft rim light contained on object only. Perfectly flat uniform cream #F4EBD9 backdrop from edge to edge: no ground plane, no cast shadow, no vignette, no gradient, no halo, no frame or badge circle. No enclosed see-through gaps in splash. No text, letters, numbers, arrows, slashes, check marks, stars or symbols.", + "reason": "8% corner extraction erased broad white foam highlights." + } + ] + }, + "ask-within.webp": { + "master": "web/assets/source/ui/ask-within.png", + "prompt": "Use case: stylized-concept. Create one final exquisite Familiar game ask icon at highest quality, square PNG. Image1 is approved hero art style; image2 is the companion sideways brass hourglass. Match their tactile hand-painted clay and softly worn golden brass, warm golden light from upper right and subtle teal depths. Do NOT include lens. Create the matching hourglass standing fully UPRIGHT, vertical axis, viewed slightly from above in three-quarter view. This represents home within a number of decisions.\nSubject: ONE tiny brass pocket hourglass, thick softly rounded golden brass top and bottom caps, a single broad sea-green glass bulb pinched in the middle. Golden sand forms a mound in top half with a clearly visible thin continuous stream through waist into a growing mound in bottom half. Bold contrast between warm sand and deep teal glass. The opaque colored glass contains its own shading and never reveals cream backdrop. No separate support rods: continuous filled silhouette with no enclosed see-through gaps. Keep simple classic hourglass profile with broad top/bottom, narrow waist. Gentle handworked materials, broad highlight, minimal small texture. No numbers or face or decorations.\nCentered object occupies70% canvas height with min15% margins, same visual scale as image1. Absolutely uniform flat solid cream #F4EBD9 backdrop edge to edge. No background texture, gradient, vignette, floor, ground, cast shadow, contact shadow or glow outside object. Only this single upright object, no frame, badge, other props, text, letters, numbers, arrows, slashes, checks or symbols. Must remain unmistakable upright hourglass at24px; companion sideways hourglass must be distinguishable by orientation.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d966-102f-70d2-a3ea-f58c3dd8751e/exec-a36ac423-c119-4605-85ba-90d7c4557760.png", + "session": "01a1d966-102f-70d2-a3ea-f58c3dd8751e", + "attempts": 1, + "styleReferences": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/ask-lens.png", + "/Users/dadadave/.codex/generated_images/01a1d966-102f-70d2-a3ea-f58c3dd8751e/exec-0270e35e-0472-4658-affd-e570dc8fb62f.png" + ], + "masterSha256": "4fe81ede5b8df100437460c3c52a0278ff516ef5fa7c58c37f50f01a35da5a0c", + "masterSize": { + "width": 1254, + "height": 1254 + }, + "masterPreparation": "ImageMagick 8% fuzz corner flood fill removes generated matte; trim; resize longest object dimension to 878 px; center on 1254 px square uniform #F4EBD9. No painted-object retouch.", + "regenerationNote": "Initial generation; upright axis and visible sand stream distinguish decision limit from never-wait.", + "rootSession": "01a1d966-102f-70d2-a3ea-f58c3dd8751e" + }, + "mochi-portrait-proud.webp": { + "master": "web/assets/source/ui/mochi-portrait-proud.png", + "prompt": "Use case: identity-preserve. Asset type: premium cozy harbor game status-card avatar expression variant.\nEdit the supplied finished Mochi portrait. KEEP EXACTLY the same square canvas, framing, camera angle, position, head size and geometry, three-quarter pose looking slightly to viewer's RIGHT, ear positions, bust cutoff, round chubby kitten identity, orange color, THREE broad tapered darker-orange forehead stripes, broad cream muzzle and chest, peach inner ears, small dark brown nose, two thick dark clay whisker marks on each cheek, terracotta-red felt bandana with central-right knot and two rounded tails, warm upper-right rim light, soft tactile felt-and-clay miniature finish. This image will swap directly into the same avatar slot; do not change framing or rescale the subject.\nChange ONLY facial expression to proud after a successful harbor outing: BOTH eyes happily closed as two softly curved dark smile-arcs, a big pleased contented smile with lifted cheeks, chin up just a tiny touch. Warm gentle delighted pride; keep the subtle Mochi mouth design, no human teeth, no tongue sticking out, no blush disks. Keep head position, ears, silhouette and neck knot aligned to input. Fur remains dry and smooth, no droplets.\nHead-and-shoulders only; no arms/hands/paws/body/tail/satchel. Chest silhouette stays softly rounded and connected. At least 8% clear backdrop margin everywhere. Perfectly flat uniform solid light cream #F4EBD9 background edge to edge with identical background color, no texture, gradient, vignette, halo, ground plane, cast shadow on backdrop, props or frame. No see-through holes or gaps. No text, letters, numbers, symbols, logos or watermark. Highest visual quality, production-ready polished art. Preserve input native square resolution 1254x1254.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d96a-6220-7512-acb3-ea840e2ddd7c/exec-e268e619-4d2e-46f5-ba0b-30cac4c49ed2.png", + "session": "01a1d96a-6220-7512-acb3-ea840e2ddd7c", + "attempts": 1, + "styleReferences": [ + "/Users/dadadave/.codex/generated_images/01a1d965-fc27-7472-bf21-a1199d209111/exec-b357f08c-c246-4943-a5b3-aea01c65b63f.png" + ], + "masterSha256": "3d328ae25ef06702e4311b63beb995bc47299434a88e0deb9093bb780c719fef", + "originalGeneratedSha256": "1299c4ca988c92e25ac4ba86f95bae221b02321fce24f3989933f61eb4c3a1db", + "masterSize": { + "width": 1254, + "height": 1254 + }, + "masterPreparation": { + "tool": "ImageMagick", + "operation": "Replace only four-corner-connected backdrop with exact #F4EBD9; fuzz 4%; opaque PNG; no resize/upscale, subject color grading, or geometry edits.", + "reason": "Generated cream backdrop had small pixel variations. Initial 8% background normalization was rejected because it nibbled pale rim highlights; 4% preserves those highlights and gives a uniform backdrop. Review extraction uses requested 8%.", + "corner_pixels": [ + "srgb(244,235,217)", + "srgb(244,235,217)", + "srgb(244,235,217)", + "srgb(244,235,217)" + ] + }, + "regenerationNote": "First generation accepted after full-size inspection by generator and art lead; framing and identity preserve hero.", + "rootSession": "01a1d965-fc27-7472-bf21-a1199d209111" + }, + "mochi-portrait-splashed.webp": { + "master": "web/assets/source/ui/mochi-portrait-splashed.png", + "prompt": "Use case: identity-preserve. Asset type: premium cozy harbor game status-card avatar expression variant.\nEdit the supplied finished Mochi portrait. KEEP EXACTLY the same square canvas, framing, camera angle, position, head size and geometry, three-quarter pose looking slightly to viewer's RIGHT, ear positions, bust cutoff, round chubby kitten identity, orange color, THREE broad tapered darker-orange forehead stripes, broad cream muzzle and chest, peach inner ears, small dark brown nose, two thick dark clay whisker marks on each cheek, terracotta-red felt bandana with central-right knot and two rounded tails, warm upper-right rim light, soft tactile felt-and-clay miniature finish. This image will swap directly into the same avatar slot; do not change framing or rescale the subject.\nChange ONLY expression and surface wetness for a just-splashed state: wet, slightly darker damp fur gathered into small cute soft spiky tufts along cheeks/forehead/ear edges, only a FEW clear dimensional water droplets clinging to Mochi's fur (all attached, no floating droplets). Keep all three forehead stripes fully readable and original face silhouette recognizable. One eye, the eye on viewer's RIGHT, is squinting; the viewer's LEFT eye stays open and dark with its small white catchlight. A small surprised open oval mouth. Mochi remains adorable, relaxed and unbothered, never sad or scared. No extra facial features or blush.\nHead-and-shoulders only; no arms/hands/paws/body/tail/satchel. Chest silhouette stays softly rounded and connected. At least 8% clear backdrop margin everywhere. Perfectly flat uniform solid light cream #F4EBD9 background edge to edge with identical background color, no texture, gradient, vignette, halo, ground plane, cast shadow on backdrop, props or frame. No see-through holes or gaps. No text, letters, numbers, symbols, logos or watermark. Highest visual quality, production-ready polished art. Preserve input native square resolution 1254x1254.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d96a-6220-7512-acb3-ea840e2ddd7c/exec-83c89758-70d4-4c1c-bd8d-5611729b822e.png", + "session": "01a1d96a-6220-7512-acb3-ea840e2ddd7c", + "attempts": 1, + "styleReferences": [ + "/Users/dadadave/.codex/generated_images/01a1d965-fc27-7472-bf21-a1199d209111/exec-b357f08c-c246-4943-a5b3-aea01c65b63f.png" + ], + "masterSha256": "c125818b1cb6580ee9bf8440f8e3f5a40939cf6020414a05da70d0796c08ac35", + "originalGeneratedSha256": "1f4b0f39fb6594b9a1e11aa31300231d5781ebfb13a0deb326929feab6f00ea4", + "masterSize": { + "width": 1254, + "height": 1254 + }, + "masterPreparation": { + "tool": "ImageMagick", + "operation": "Replace only four-corner-connected backdrop with exact #F4EBD9; fuzz 4%; opaque PNG; no resize/upscale, subject color grading, or geometry edits.", + "reason": "Generated cream backdrop had small pixel variations. Initial 8% background normalization was rejected because it nibbled pale rim highlights; 4% preserves those highlights and gives a uniform backdrop. Review extraction uses requested 8%.", + "corner_pixels": [ + "srgb(244,235,217)", + "srgb(244,235,217)", + "srgb(244,235,217)", + "srgb(244,235,217)" + ] + }, + "regenerationNote": "First generation accepted after full-size inspection by generator and art lead; framing and identity preserve hero.", + "rootSession": "01a1d965-fc27-7472-bf21-a1199d209111" + }, + "mochi-portrait.webp": { + "master": "web/assets/source/ui/mochi-portrait.png", + "prompt": "Use case: identity-preserve. Asset type: premium cozy harbor game status-card avatar.\nCreate one isolated head-and-shoulders bust of EXACTLY Mochi from the supplied character references, highest-quality tactile felt-and-clay miniature game art. The first two images are strict identity authorities; harbor image is lighting/material context only. Mochi is an orange tabby kitten with a huge round chubby head, THREE broad tapered darker orange forehead stripes, broad cream muzzle/lower face and cream upper chest, peach inner ears, small rounded dark-brown triangular nose, two thick dark brown clay whisker marks on each cheek, big polished dark eyes with small white catchlights. Red terracotta bandana with its rounded central-right neck knot and both short rounded tails clearly visible. Preserve the reference's exact identity, shapes, palette and handmade microtexture, do not redesign into a generic cat or a realistic animal.\nDefault expression: content and alert, tiny soft closed-mouth smile, ears up. Camera is front three-quarter, looking slightly toward viewer's RIGHT, nearly frontal so both eyes are very readable; same natural gentle uplift as the identity reference. Head-and-shoulders only, softly rounded natural cutoff at upper chest below bandana; no full torso, no arms/hands/paws, no tail, no satchel, no floating accessories. No realistic fine whisker filaments.\nSquare 1024x1024 canvas. Keep all ears, cheeks, bandana and chest fully inside the image with at least 9% margin EVERY side. Head large, comfortably fitting inside a round status avatar. Center head around (512,440); top of ears around y110; bust ends around y890. Soft warm golden light from back upper RIGHT, subtle warm rim, warm gentle front fill, dark eyes readable, no hard edge light.\nBackdrop perfectly uniform flat solid light cream #F4EBD9 edge to edge, identical color at every exterior pixel. NO ground plane, cast shadow on backdrop, gradient, vignette, halo, frame, props or environment. One connected bust silhouette, no enclosed see-through gaps. Chest ends in softly sculpted fur contour, no misty fade into backdrop. No text, letters, numbers, symbols, logos or watermark. Production master illustration, meticulous finish.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d965-fc27-7472-bf21-a1199d209111/exec-b357f08c-c246-4943-a5b3-aea01c65b63f.png", + "session": "01a1d965-fc27-7472-bf21-a1199d209111", + "attempts": 1, + "styleReferences": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/mochi.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/mochi-poses-source.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/harbor.png" + ], + "masterSha256": "eed2974998310050308ceb9b105653579c85462904ed908b3ca4fb9ffcb9f44b", + "originalGeneratedSha256": "508ffc0c665c57924e6b38d015356c362614b9202f47c52d1bd14e16045eef67", + "masterSize": { + "width": 1254, + "height": 1254 + }, + "masterPreparation": { + "tool": "ImageMagick", + "operation": "Replace only four-corner-connected backdrop with exact #F4EBD9; fuzz 4%; opaque PNG; no resize/upscale, subject color grading, or geometry edits.", + "reason": "Generated cream backdrop had small pixel variations. Initial 8% background normalization was rejected because it nibbled pale rim highlights; 4% preserves those highlights and gives a uniform backdrop. Review extraction uses requested 8%.", + "corner_pixels": [ + "srgb(244,235,217)", + "srgb(244,235,217)", + "srgb(244,235,217)", + "srgb(244,235,217)" + ] + }, + "regenerationNote": "First generation accepted after full-size inspection.", + "rootSession": "01a1d965-fc27-7472-bf21-a1199d209111" + }, + "sign-beacon.webp": { + "master": "web/assets/source/ui/sign-beacon.png", + "prompt": "Use case: precise-object-edit. Refine this supplied Beacon sign into the final production master. Preserve its beautiful pale honey-cream driftwood, rounded handmade bevels, calm empty text field, single sturdy short center stake, almost front-facing camera, warm back-upper-right light, tactile felt-and-clay finish, and blank face with absolutely no lettering.\nChange ONLY: simplify the left emblem to a SMALL inset ROUND PAINTED medallion, diameter about 19% of the board width. The medallion has a flat muted seafoam-blue painted ground with a simple ivory lighthouse shape, one terracotta roof, terracotta lower band, and one bright honey lamp window. Use only a few clear shapes so the painting reads at 28px. No landscape, sky, clouds, rocks, sea, railings or tiny details within the medallion. Make it feel hand-painted, slightly textured and flush with the board, not like a photograph inserted into a hole. The right 72% of board stays completely empty pale calm wood for a future nine-letter word.\nSlightly reduce whole object to 80% of canvas width so EVERY extremity is at least 8% from canvas edge. Board itself remains 3:1 and same form; single center stake is lowest point, no ground props.\nAll exterior background pixels must be a single flat uniform solid cream #F4EBD9, including under the stake. No backdrop noise, gradient, vignette, cast shadow, glow spill or ground plane. Keep self-shading only on object. One connected silhouette, no holes. No text, letters, numerals, logos, watermark, or abstract symbols. Only the requested figurative lighthouse painting. Landscape 1536x1024, highest visual quality.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d965-fc27-7472-bf21-a1199d209111/exec-a69b0061-7257-4efd-8146-4abc7b2ff9d4.png", + "session": "01a1d965-fc27-7472-bf21-a1199d209111", + "attempts": 2, + "styleReferences": [ + "/Users/dadadave/.codex/generated_images/01a1d965-fc27-7472-bf21-a1199d209111/exec-c15335cf-2d90-48c3-9f75-2e30c68b370a.png" + ], + "masterSha256": "ce396916579271e73c937042e3511ecd99a2f282501fb4070f1e4d056e56b952", + "originalGeneratedSha256": "b813a7288f38d4e436a4d68d5ed57b5e1ecf797d39cdf305f4096c3166e1db5c", + "masterSize": { + "width": 1536, + "height": 1024 + }, + "masterPreparation": { + "tool": "ImageMagick", + "operation": "Replace only four-corner-connected backdrop with exact #F4EBD9; fuzz 4%; opaque PNG; no resize/upscale, subject color grading, or geometry edits.", + "reason": "Generated cream backdrop had small pixel variations. Initial 8% background normalization was rejected because it nibbled pale rim highlights; 4% preserves those highlights and gives a uniform backdrop. Review extraction uses requested 8%.", + "corner_pixels": [ + "srgb(244,235,217)", + "srgb(244,235,217)", + "srgb(244,235,217)", + "srgb(244,235,217)" + ] + }, + "regenerationNote": "Rejected first generation: medallion contained detailed landscape and was too large for 28 px. Regenerated with a smaller simple painted lighthouse and wider margins.", + "rootSession": "01a1d965-fc27-7472-bf21-a1199d209111", + "rejectedVersions": [ + { + "prompt": "Use case: stylized-concept. Asset type: premium production game prop, a single isolated small standing harbor sign, hero of a four-sign family.\nInput references: harbor.png is the exact world, material and golden-hour lighting authority; title-plank-1.png and title-post.png define softly handmade wood edges and tactile miniature construction (but NOT their dark color); A-pocket-harbor.png shows the light Orchard board and calm lettering area to emulate.\nPaint one beautiful blank Beacon place sign: a sun-bleached PALE HONEY / CREAM driftwood board, roughly 3:1 board width:height, broad nearly front-facing readable face, subtly irregular softly rounded silhouette, restrained fine grain and small worn edges. It is a LIGHTER, SUNNIER cousin of the title wood. Reserve the RIGHT 72% of the board face as completely empty calm pale wood, sufficient for a nine-letter name later; no knots or dark grain across this area. On the LEFT end inset one small round painted medallion about 19% of board width, with a simple tactile miniature painting of the harbor's ivory lighthouse, terracotta cap/base, warm glowing yellow lamp. This is a painted pictorial emblem flush into the wood, NOT a separate figurine. No lettering anywhere.\nBoard mounted centrally on exactly one short sturdy wooden stake, visible below the board for about 60% of the board's height, ending in a blunt subtly tapered bottom which is the object's lowest point. No feet, no rocks, no vegetation, no rope. Entire sign is one connected solid silhouette, no holes or enclosed see-through gaps. Subtle top bevel visible as seen by the harbor camera. Soft felt-and-clay miniature diorama finish, not cartoon vector, not shiny plastic, not photographic lumber. Light from back upper RIGHT gives gentle warm rim along upper/right edge, front filled enough for calm pale face; self-shading only within object.\nLandscape canvas 1536x1024, sign centered and occupying about 82% canvas width; keep at least 8% clean margin each side and generous above/below. Perfectly flat uniform solid light cream #F4EBD9 backdrop edge to edge. No backdrop texture, vignette, gradient, ground plane, cast shadow, halo, props, frame, or background scene. No text, letters, numbers, graphic symbols, logos, watermark or pseudo-writing. Only the requested figurative lighthouse painting on the inset medallion. Highest visual quality, meticulous polished game art.", + "references": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/harbor.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/title/title-plank-1.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/title/title-post.png", + "/Users/dadadave/Dev/projects/familiar/A-pocket-harbor.png" + ], + "original_generated_path": "/Users/dadadave/.codex/generated_images/01a1d965-fc27-7472-bf21-a1199d209111/exec-c15335cf-2d90-48c3-9f75-2e30c68b370a.png", + "rejection": "Over-detailed landscape in oversized medallion; simplified for 28 px and widened side margins." + } + ] + }, + "sign-bram.webp": { + "master": "web/assets/source/ui/sign-bram.png", + "prompt": "Use case: precise-object-edit. Asset: sign-bram, sibling of the supplied Beacon sign. Create ONE isolated standing sign, no scene.\nImage 1 is the exact family master: preserve its board dimensions, overall size and placement on the 1536x1024 landscape canvas, pale honey/cream driftwood face, nearly frontal camera, round left inset medallion size/location, softly rounded handmade edges, short sturdy central stake and lowest-point stake tip. Preserve warm light from back upper RIGHT and quiet pale empty right 72% of face. Materials: highest-quality tactile felt-and-clay miniature, hand-carved sun-bleached wood, gentle grain; same premium finish as reference.\nChange the left painted medallion ONLY to a simple miniature illustration of a small wooden trading crate holding ONE pale turquoise sea-glass pebble and a short bundle of golden reeds. Bram reference is the gentle badger trader who owns this sign: do NOT paint the badger or any portrait. Crate is honey-brown with just two broad slats, sea-glass is a single big readable rounded green-blue shape, reeds are 3-4 thick golden stems with simple tips. All fit inside medallion against muted seafoam teal painted ground matching the Beacon emblem. Broad few hand-painted shapes, readable at 28px; no scene, no detailed objects, no photographic insert. Medallion painted flush onto inset wood, not separate props. Slightly different subtle grain and small edge wear from Beacon so individually handmade, but same family silhouette and proportions.\nKeep right face blank and light for a nine-letter dark-brown name added later. No text, letters, numbers, abstract symbols, logos or watermark. One connected sign silhouette; no holes, see-through gaps, rope loops, extra feet, stones, vegetation or props.\nPerfectly uniform flat solid cream #F4EBD9 backdrop edge to edge with no gradient, noise, vignette, ground plane, cast shadow, glow or frame. At least 8% margin every side, matching first reference composition. Highest visual quality.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d965-fc27-7472-bf21-a1199d209111/exec-233bb744-1774-45e3-9c0a-01db7ba1f44a.png", + "session": "01a1d965-fc27-7472-bf21-a1199d209111", + "attempts": 1, + "styleReferences": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/sign-beacon.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/bram.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/harbor.png" + ], + "masterSha256": "6a7f6710aa741d273fd2205c3b38c4548cdfa34ec20c0e3ff4de4a1e905aa759", + "originalGeneratedSha256": "87f59331656bebbdb7f8fc1e5011cf9afb09b2089057292bb18394e431f4e1ee", + "masterSize": { + "width": 1536, + "height": 1024 + }, + "masterPreparation": { + "tool": "ImageMagick", + "operation": "Replace only four-corner-connected backdrop with exact #F4EBD9; fuzz 4%; opaque PNG; no resize/upscale, subject color grading, or geometry edits.", + "reason": "Generated cream backdrop had small pixel variations. Initial 8% background normalization was rejected because it nibbled pale rim highlights; 4% preserves those highlights and gives a uniform backdrop. Review extraction uses requested 8%.", + "corner_pixels": [ + "srgb(244,235,217)", + "srgb(244,235,217)", + "srgb(244,235,217)", + "srgb(244,235,217)" + ] + }, + "regenerationNote": "First generation accepted after full-size inspection.", + "rootSession": "01a1d965-fc27-7472-bf21-a1199d209111" + }, + "sign-satchel.webp": { + "master": "web/assets/source/ui/sign-satchel.png", + "prompt": "Use case: precise-object-edit. Create sign-satchel, fourth sibling of the supplied Beacon sign, ONE isolated standing prop. First reference strictly defines same family dimensions, 1536x1024 landscape composition, 3:1 rounded light-wood board, nearly front-facing camera, short sturdy central stake, left circular medallion about 19% board width, and blank pale right 72% face. Same warm back-upper-RIGHT rim light, gentle front fill, tactile felt-and-clay miniature rendering.\nReplace lighthouse medallion with a simple painted picture of Mochi's SMALL BROWN SATCHEL, matching the flap and rounded compact pouch in second reference: warm brown pouch, honey stitched edge suggested by only a few big stitches, single round brass fastening, RED strap matching the terracotta-red bandana. Lay the short red strap diagonally across/behind the bag as a solid broad strip, NOT an open floating loop. Bag occupies the small round muted seafoam-teal painted inset. Just a few bold readable hand-painted shapes at 28px; no scene, tiny clutter, text, detached props or photographic insert. Pictorial inset feels painted into wood.\nUse individual wood grain and wear for this sibling: a barely visible low-contrast flowing grain curve on far right, softly worn lower-left edge and tiny softened nick on upper-right edge, while keeping same family shape/scale. Pale sun-bleached honey/cream board face must remain light and calm for dark-brown typography later. Do not add lettering.\nExactly one center stake, tip lowest point. No rocks, feet, rope, decorative extras. At least 8% clean margin EVERY side. Flat perfectly UNIFORM solid #F4EBD9 cream backdrop edge to edge; no gradient, vignette, background texture, ground plane, cast shadow, halo, frame or environment. One connected solid object silhouette without enclosed see-through gaps. No text, letters, numerals, abstract symbols, logos, watermark or pseudo-writing anywhere. Highest-quality polished production art.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d965-fc27-7472-bf21-a1199d209111/exec-fba2d679-e62a-4e0e-86fb-52a5f2d3e95f.png", + "session": "01a1d965-fc27-7472-bf21-a1199d209111", + "attempts": 1, + "styleReferences": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/sign-beacon.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/mochi.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/harbor.png" + ], + "masterSha256": "a0e762afe28f2e6acabf1b3c1b9fab67d82d2512a023f3c26703ccaf9405392d", + "originalGeneratedSha256": "0eb25527cc3a79f007cb65e85dc528268086b371ff99c43d3736beb7432aad8a", + "masterSize": { + "width": 1536, + "height": 1024 + }, + "masterPreparation": { + "tool": "ImageMagick", + "operation": "Replace only four-corner-connected backdrop with exact #F4EBD9; fuzz 4%; opaque PNG; no resize/upscale, subject color grading, or geometry edits.", + "reason": "Generated cream backdrop had small pixel variations. Initial 8% background normalization was rejected because it nibbled pale rim highlights; 4% preserves those highlights and gives a uniform backdrop. Review extraction uses requested 8%.", + "corner_pixels": [ + "srgb(244,235,217)", + "srgb(244,235,217)", + "srgb(244,235,217)", + "srgb(244,235,217)" + ] + }, + "regenerationNote": "First generation accepted after full-size inspection.", + "rootSession": "01a1d965-fc27-7472-bf21-a1199d209111" + }, + "sign-workbench.webp": { + "master": "web/assets/source/ui/sign-workbench.png", + "prompt": "Use case: precise-object-edit. Create the Workbench sibling of the first-reference standing Beacon sign, ONE isolated prop. Use the first image as strict family master for canvas framing (1536x1024 landscape), board size and 3:1 proportion, short sturdy central stake, nearly frontal view, pale honey/cream wood color, rounded softened edges, inset circular LEFT medallion (19% of board width), blank right 72% of face and warm back-upper-right golden light. Preserve the luxurious tactile felt-and-clay harbor-miniature quality. The object's stake tip must remain its lowest point; keep at least 8% clean margin on every side.\nPaint a DIFFERENT piece of sun-bleached driftwood within the same family: subtle low-contrast grain lines along the empty face, a small worn notch on upper-left corner and a gently irregular lower-right edge, NOT an exact copy of reference grain. Still calm and pale for dark lettering.\nReplace lighthouse emblem with a simple painted miniature HAMMER CROSSED DIAGONALLY BEHIND A SMALL LANTERN. Hammer: short honey wooden handle and soft gray iron head, diagonal lower-left to upper-right. Lantern: compact rounded dark bronze shell, one warm yellow glowing window, tilted just slightly opposite the hammer to make an easy-to-read crossed pair. Lantern handle painted solid against teal medallion, no transparent holes; no chains. Few bold hand-painted shapes, readable at 28px, flush painted miniature on muted seafoam teal inset background, not a separate 3D object or busy scene. Keep every part inside medallion. No abstract icons outside the medallion.\nPerfectly flat, UNIFORM single light cream #F4EBD9 backdrop edge to edge. No gradient, vignette, noise, cast shadow, ground plane, glow spill, props, rocks, foot supports, rope, frame or landscape. One connected sign silhouette, no enclosed see-through gaps. Absolutely no text, letters, numbers, logos, watermark or pseudo-writing. No name on board; typography added later. Highest visual quality.", + "originalGeneratedPath": "/Users/dadadave/.codex/generated_images/01a1d965-fc27-7472-bf21-a1199d209111/exec-34029beb-a725-4705-9e56-c5b1817e5eb8.png", + "session": "01a1d965-fc27-7472-bf21-a1199d209111", + "attempts": 1, + "styleReferences": [ + "/Users/dadadave/Dev/projects/familiar/web/assets/source/ui/sign-beacon.png", + "/Users/dadadave/Dev/projects/familiar/web/assets/source/first-light-motion/harbor.png" + ], + "masterSha256": "2b9382c1877252acd1d8bea959e6c09b48418edf85195de4c04666758541f49f", + "originalGeneratedSha256": "088b339356f7544d64c3984da642d4eec5b521115479c6831cd974c9fd63f056", + "masterSize": { + "width": 1536, + "height": 1024 + }, + "masterPreparation": { + "tool": "ImageMagick", + "operation": "Replace only four-corner-connected backdrop with exact #F4EBD9; fuzz 4%; opaque PNG; no resize/upscale, subject color grading, or geometry edits.", + "reason": "Generated cream backdrop had small pixel variations. Initial 8% background normalization was rejected because it nibbled pale rim highlights; 4% preserves those highlights and gives a uniform backdrop. Review extraction uses requested 8%.", + "corner_pixels": [ + "srgb(244,235,217)", + "srgb(244,235,217)", + "srgb(244,235,217)", + "srgb(244,235,217)" + ] + }, + "regenerationNote": "First generation accepted after full-size inspection.", + "rootSession": "01a1d965-fc27-7472-bf21-a1199d209111" + } + } +} diff --git a/web/public/assets/ui/sign-beacon.webp b/web/public/assets/ui/sign-beacon.webp new file mode 100644 index 0000000..2e150c2 Binary files /dev/null and b/web/public/assets/ui/sign-beacon.webp differ diff --git a/web/public/assets/ui/sign-bram.webp b/web/public/assets/ui/sign-bram.webp new file mode 100644 index 0000000..39b60db Binary files /dev/null and b/web/public/assets/ui/sign-bram.webp differ diff --git a/web/public/assets/ui/sign-satchel.webp b/web/public/assets/ui/sign-satchel.webp new file mode 100644 index 0000000..1b87197 Binary files /dev/null and b/web/public/assets/ui/sign-satchel.webp differ diff --git a/web/public/assets/ui/sign-workbench.webp b/web/public/assets/ui/sign-workbench.webp new file mode 100644 index 0000000..d78c30a Binary files /dev/null and b/web/public/assets/ui/sign-workbench.webp differ diff --git a/web/src/expedition/Game.tsx b/web/src/expedition/Game.tsx index 2caf1ff..4e323e2 100644 --- a/web/src/expedition/Game.tsx +++ b/web/src/expedition/Game.tsx @@ -18,11 +18,27 @@ import type { HarborSession, HomeCheckpoint, RunContext, WorldIntent } from "./h import type { HarborView, HomePlace } from "./scene"; import { LanternArt, OriginDiorama } from "../tidebound/Storycraft"; import "./game.css"; -import { keepTide } from "../season/data"; +import { deviceDay, keepTide, readPreview, readTide, seasonView, shelvesBeaconCourt, shelfNote } from "../season/data"; +import type { TodayView } from "../season/model"; +import SeasonBoundary from "../season/SeasonBoundary"; +import { cardForDay, msUntilNextTideDay, tideDay } from "../tide/cards"; +import { cardStatus, replayRun, type Run } from "../tide/asks"; +import { readTideLog, readTidePending, recordTide, tideSummary, writeTidePending, type TidePending } from "../tide/log"; +import { askFlips, devTideDay, earlierDays, harborTide, logPages, outingNotice, pageForDay, restartTide, tideObjective, todayView } from "../tide/pages"; +import TideAsk from "../tide/TideAsk"; +import TideHud from "../tide/TideHud"; +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 { 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"; -const SEASON2=import.meta.env.VITE_SEASON2_ENABLED==="true"; -// Behind the flag so a build without Season 2 leaves the screens out entirely. -const SeasonBram=SEASON2?lazy(()=>import("../season/SeasonBram")):()=>null; +// Bram's shelf loads when his dialog first opens. +const SeasonBram=lazy(()=>import("../season/SeasonBram")); export const EXPEDITION_SAVE_KEY="familiar.expedition.local.v2"; interface LocalHome extends HomeCheckpoint {lantern:null|{motif:"crest"|"moth";socket:"porch"|"dock"}} @@ -33,6 +49,7 @@ const names={lens:"Beacon Lens",moth:"wind-moth",vane:"Signal Vane"}; const columns=["Left","Center","Right"] as const; const title=(word:string)=>word[0]!.toUpperCase()+word.slice(1); const same=(a:unknown,b:unknown)=>JSON.stringify(a)===JSON.stringify(b); +const tideScopeOf=(context:RunContext)=>context.authority==="near-testnet"?context.accountId:"preview"; function readLocal(key=EXPEDITION_SAVE_KEY):{save:LocalSave;problem:string}{ try{ @@ -63,25 +80,28 @@ export function eventDescription(event:CourtEvent,area?:Area):string{ case"rescue":return event.reason==="resolve"?"The last splash used Mochi’s Resolve. Bram brings her home; the unbanked cargo stays behind.":"The tide closed after 24 decisions. Bram brings Mochi home; the unbanked cargo stays behind."; } } -function Icon({kind}:{kind:"menu"|"close"|"bag"|"sound"|"silent"|"north"|"south"|"west"|"east"}){ - const paths={sound:"M3 9h4l5-4v14l-5-4H3z M16 9q4 3 0 6 M19 6q7 6 0 12",silent:"M3 9h4l5-4v14l-5-4H3z M16 9l6 6 M22 9l-6 6",menu:"M4 6h16M4 12h16M4 18h16",close:"m6 6 12 12M18 6 6 18",bag:"M6 8h12l2 12H4L6 8Zm3 0V5a3 3 0 0 1 6 0v3",north:"m5 15 7-7 7 7",south:"m5 9 7 7 7-7",west:"m15 5-7 7 7 7",east:"m9 5 7 7-7 7"}; +function Icon({kind}:{kind:"menu"|"close"|"bag"|"sound"|"silent"|"north"|"south"|"west"|"east"|"chart"|"log"|"pencil"|"sail"|"home"|"check"|"circle"|"restart"}){ + const paths={restart:"M3 11a9 9 0 1 1 2 7M3 4v7h7",sound:"M3 9h4l5-4v14l-5-4H3z M16 9q4 3 0 6 M19 6q7 6 0 12",silent:"M3 9h4l5-4v14l-5-4H3z M16 9l6 6 M22 9l-6 6",menu:"M4 6h16M4 12h16M4 18h16",close:"m6 6 12 12M18 6 6 18",bag:"M6 8h12l2 12H4L6 8Zm3 0V5a3 3 0 0 1 6 0v3",north:"m5 15 7-7 7 7",south:"m5 9 7 7 7-7",west:"m15 5-7 7 7 7",east:"m9 5 7 7-7 7",chart:"m3 5 6-2 6 2 6-2v16l-6 2-6-2-6 2V5Zm6-2v16m6-14v16",log:"M5 3h14v18H5V3Zm4 5h6m-6 4h6m-6 4h3",pencil:"m4 16 12-12 4 4L8 20H4v-4Zm9-9 4 4",sail:"M12 3v13H4L12 3Zm2 3 6 10h-6V6ZM3 19q9 5 18 0",home:"m3 11 9-8 9 8M6 9v12h12V9m-9 12v-7h6v7",check:"m5 12 4 4L19 6",circle:"M20 12a8 8 0 1 1-16 0 8 8 0 1 1 16 0"}; return ; } -/** `audio`, `initialSound` and `initialMix` carry the title screen's sound choice into play. */ -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); +/** `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); 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(""); - const saveRef=useRef(save),keyRef=useRef(EXPEDITION_SAVE_KEY),busyRef=useRef(false),buffer=useRef(null),presentation=useRef(0),sessionRef=useRef(session),audio=useRef(titleAudio??null),panelRef=useRef(null),trigger=useRef(null),corruptRef=useRef(corrupt),finishBusy=useRef(false),finishEpoch=useRef(0),alive=useRef(true); + const saveRef=useRef(save),keyRef=useRef(EXPEDITION_SAVE_KEY),busyRef=useRef(false),buffer=useRef(null),presentation=useRef(0),sessionRef=useRef(session),audio=useRef(titleAudio??null),panelRef=useRef(null),trigger=useRef(null),pressed=useRef(null),corruptRef=useRef(corrupt),finishBusy=useRef(false),finishEpoch=useRef(0),alive=useRef(true); const [resting,setResting]=useState(false),[greeting,setGreeting]=useState(0); + const gameRef=useRef(null),departureRef=useRef(null); const [musicLevel,setMusicLevel]=useState(initialMix[0]),[effectsLevel,setEffectsLevel]=useState(initialMix[1]); const [passage,setPassage]=useState(emptyPassageHome); const [passageScope,setPassageScope]=useState(""); const [passageError,setPassageError]=useState(""); const passageReadable=useRef(false); + const [tideBook,setTideBook]=useState(emptyBook),[tideAway,setTideAway]=useState(false),[tideRound,setTideRound]=useState(0); + const tideBookReadable=useRef(false); const audioRequest=useRef(0); const repairRequest=useRef<{branch:string;kind:"beacon"|"signal"}|null>(null); function muteSound(){ @@ -114,14 +134,52 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in const canonical=savedMode?session!.state.snapshot!.journey:null; const desiredKey=savedMode?`familiar.expedition.game.v2:testnet:${session!.state.snapshot!.binding.nearAccountId}`:EXPEDITION_SAVE_KEY; const home:LocalHome=canonical?{banked:canonical.banked as BankedItem[],lit:canonical.lit,signaled:canonical.signaled,lantern:null}:save.home; + const tideScope=savedMode?session!.state.snapshot!.binding.nearAccountId:"preview"; + const [currentTideDay,setCurrentTideDay]=useState(tideDay); + const today=import.meta.env.DEV?devTideDay(location.search)??currentTideDay:currentTideDay; + useEffect(()=>{ + let timer:ReturnType; + const check=()=>{ + const now=Date.now(); + setCurrentTideDay(tideDay(now)); + clearTimeout(timer); + timer=setTimeout(check,msUntilNextTideDay(now)); + }; + check(); + document.addEventListener("visibilitychange",check); + return()=>{clearTimeout(timer);document.removeEventListener("visibilitychange",check);}; + },[]); + const [tideVersion,setTideVersion]=useState(0),[logDay,setLogDay]=useState(undefined); + const [arrival,setArrival]=useState<{day:number;run:Run}|{day:number;result:DayResult}|null>(null); + const [arrivalNotice,setArrivalNotice]=useState(""); + const [shelvedDay,setShelvedDay]=useState<{scope:string;day:number}|null>(null); + useEffect(()=>{ + if(!savedMode||!home.lit||run){setShelvedDay(null);return;} + let current=true; + void seasonView("get_today",{account_id:tideScope}).then(view=>{ + if(current)setShelvedDay(view.minted_today?{scope:tideScope,day:view.day}:null); + }).catch(()=>{if(current)setShelvedDay(null);}); + return()=>{current=false;}; + },[savedMode,home.lit,!!run,tideScope,today,surface,session?.state.busy]); + const tideEntries=useMemo(()=>readTideLog(tideScope),[tideScope,tideVersion,lease]); + const activeTide=useRef<{context:RunContext;pending:TidePending}|null>(null); + // Keep the outing’s day even if its separate pending marker could not be saved. + if(!save.active?.season)activeTide.current=null; + else if(activeTide.current?.context!==save.active.context)activeTide.current={context:save.active.context,pending:readTidePending(tideScopeOf(save.active.context))??{day:today,late:false}}; + const tideCard=activeTide.current?cardForDay(activeTide.current.pending.day):null; + const tideRun=useMemo(()=>tideCard&&visibleRun?replayRun(visibleRun.tool,visibleRun.commands):null,[tideCard,visibleRun]); const passageKey=desiredKey+":shore-passages.v1"; const showPassage=passageScope===passageKey&&!run&&!!passage.active; + /** Device harbors sail the tide run. Signed-in harbors keep the refereed court until the season contract referees the tide run. */ + const tideRunKey=desiredKey+":tide-run.v1"; + const tideResume=!savedMode&&passageScope===passageKey&&!!tideBook.active; + const showTideRun=tideResume&&!run&&!showPassage&&!tideAway; const services=passageScope===passageKey?passage.services:[]; const lastService=services.at(-1); const chapterComplete=home.signaled&&services.includes("bell")&&services.includes("reed"); const placement=session?.state.workshop.placement,placedItem=savedMode&&placement?session!.state.workshop.items.find(item=>item.mint.token_id===placement.item_id):null; const harbor:HarborView={resting,greeting,heardBell:passageScope===passageKey&&passage.heardBell,services,watchedReeds:passageScope===passageKey&&passage.watchedReeds,lit:home.lit,signaled:home.signaled,moth:home.banked.includes("moth"),lantern:!!(savedMode?placedItem:home.lantern),socket:savedMode&&placedItem?placement!.socket:home.lantern?.socket??"porch",motif:savedMode?placedItem?.mint.motif??"crest":home.lantern?.motif??"crest",polished:savedMode&&placedItem?.finish==="harbor_polish",relic:home.banked.includes("lens")&&!home.lit?"lens":home.banked.includes("vane")&&!home.signaled?"vane":null}; - const paused=showPassage||!worldReady||!!surface||hidden||unfocused||!!fault||!!problem||!!session?.state.review; + const paused=showPassage||showTideRun||!worldReady||!!surface||hidden||unfocused||!!fault||!!problem||!!session?.state.review; const pausedRef=useRef(paused);pausedRef.current=paused; const snapshot=useMemo(()=>({court:run,home:harbor,reducedMotion:reduced,previewCommand:focused}),[run,harbor.lit,harbor.signaled,harbor.moth,harbor.lantern,harbor.socket,harbor.motif,harbor.polished,harbor.relic,resting,greeting,passage,passageScope,reduced,focused]); const previousHome=useRef({branch:desiredKey,lit:home.lit,signaled:home.signaled}); @@ -136,22 +194,39 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in if(completed){repairRequest.current=null;audio.current?.playMusic(repair.kind);} },[home.lit,home.signaled,desiredKey]); const previewReturns=useMemo(()=>{try{return new ReturnRecords(localStorage).read({authority:"local-preview",banked:save.home.banked,lit:save.home.lit,signaled:save.home.signaled});}catch{return[];}},[save.last,save.home.banked]); + const logReturns=savedMode?session!.state.returns:previewReturns; + const dailyResults=useMemo(()=>savedMode?[]:dayResults(tideBook),[savedMode,tideBook.days]); + const todayTide=dailyResults.find(result=>result.day===today)??null; + const todayGuess=useMemo(()=>savedMode?0:bramsGuess(today),[savedMode,today]); + const logBook=useMemo(()=>savedMode?logPages(logReturns,tideEntries):logPages(logReturns,tideEntries,dailyResults),[savedMode,logReturns,tideEntries,dailyResults]); + const logSummary=useMemo(()=>savedMode?tideSummary(tideEntries):tideSummary(tideEntries,dailyResults),[savedMode,tideEntries,dailyResults]); + const sailBlockedReason=tideSailReason({lit:home.lit,lease,problem,run:!!run,worldReady,showPassage,busy:session?.state.busy,pending:!!session?.state.pending}); + const canSailTide=sailBlockedReason===null; + const canRestartTide=!!save.active?.season&&run?.outcome==="active"&&!busy&&!finishing&&!problem&&!fault&&worldReady&&lease==="held"&&!session?.state.busy&&!session?.state.pending; + function sailTide(day:number){begin({tool:cardForDay(day).tool,day});} + function openLog(day?:number){setLogDay(day);open("log");} const previewOrigin=previewReturns.find(record=>record.outcome==="returned"&&record.cargo.includes(home.lantern?.motif==="moth"?"moth":"lens")); useEffect(()=>{const media=matchMedia("(prefers-reduced-motion: reduce)"),change=()=>setReduced(media.matches),visibility=()=>{setHidden(document.hidden);buffer.current=null;if(document.hidden)muteSound();},blur=()=>{setUnfocused(true);buffer.current=null;muteSound();},focus=()=>setUnfocused(false);media.addEventListener("change",change);document.addEventListener("visibilitychange",visibility);window.addEventListener("blur",blur);window.addEventListener("focus",focus);return()=>{media.removeEventListener("change",change);document.removeEventListener("visibilitychange",visibility);window.removeEventListener("blur",blur);window.removeEventListener("focus",focus);void audio.current?.close().catch(()=>{});};},[]); useEffect(()=>{document.title=run?`${COURTS[run.area].title} · Familiar`:"Pocket Harbor · Familiar";},[run?.area]); + useEffect(()=>{ + const card=departureRef.current,game=gameRef.current;if(!card||!game)return; + const measure=()=>{if(card.getClientRects().length)game.style.setProperty("--exp-harbor-feedback-bottom",`${game.getBoundingClientRect().bottom-card.getBoundingClientRect().top+12}px`);}; + const observer=new ResizeObserver(measure);observer.observe(card);window.addEventListener("resize",measure);measure(); + return()=>{observer.disconnect();window.removeEventListener("resize",measure);}; + },[worldReady,!!run,surface]); useEffect(()=>{alive.current=true;return()=>{alive.current=false;finishEpoch.current++;finishBusy.current=false;buffer.current=null;if(queuedFrame.current!==null)cancelAnimationFrame(queuedFrame.current);queuedFrame.current=null;leaseRef.current="waiting";};},[]); useEffect(()=>{ 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("");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"?null:current);setFocused(null); sessionRef.current?.setActiveRun(branch.save.active?.context??null); },[desiredKey]); useEffect(()=>{ // A restored identity must not switch harbors underneath a device-only crossing. - session?.setActiveRun?.(save.active?.context??(showPassage?{authority:"local-preview",banked:[],lit:false,signaled:false}:null)); - },[session,save.active?.context,showPassage]); + session?.setActiveRun?.(save.active?.context??(showPassage||showTideRun?{authority:"local-preview",banked:[],lit:false,signaled:false}:null)); + },[session,save.active?.context,showPassage,showTideRun]); useEffect(()=>{ let current=true,release:(()=>void)|undefined;setLease("waiting");leaseRef.current="waiting"; const frame=requestAnimationFrame(()=>{ @@ -164,6 +239,7 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in }catch{ setPassage(emptyPassageHome());setPassageError("Your crossing record could not be read. The original is preserved on this device.");passageReadable.current=false; } + try{setTideBook(readBook(localStorage,tideRunKey));tideBookReadable.current=true;}catch{setTideBook(emptyBook());tideBookReadable.current=false;} setPassageScope(passageKey); const latest=readLocal(desiredKey);saveRef.current=latest.save;setSave(latest.save);setProblem(latest.problem);setCorrupt(!!latest.problem);corruptRef.current=!!latest.problem;setSceneKey(k=>k+1);sessionRef.current?.setActiveRun(latest.save.active?.context??null); setLease("held");leaseRef.current="held"; @@ -172,19 +248,27 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in }); return()=>{current=false;leaseRef.current="waiting";cancelAnimationFrame(frame);release?.();}; },[desiredKey,leaseAttempt]); - useEffect(()=>{if(surface||session?.state.review){if(!panelOpen.current)trigger.current=document.activeElement as HTMLElement;panelOpen.current=true;const frame=requestAnimationFrame(()=>panelRef.current?.focus({preventScroll:true}));return()=>cancelAnimationFrame(frame);}if(panelOpen.current){panelOpen.current=false;const opener=trigger.current;trigger.current=null;if(restoreInspectFocus.current){restoreInspectFocus.current=false;document.querySelector(".exp-inspect-button")?.focus({preventScroll:true});}else if(opener?.isConnected)opener.focus({preventScroll:true});}},[surface,session?.state.review?.id]); + useEffect(()=>{if(surface||session?.state.review){if(!panelOpen.current&&!trigger.current)trigger.current=opener();panelOpen.current=true;const frame=requestAnimationFrame(()=>panelRef.current?.focus({preventScroll:true}));return()=>cancelAnimationFrame(frame);}if(panelOpen.current){panelOpen.current=false;const opener=trigger.current;trigger.current=null;if(restoreInspectFocus.current){restoreInspectFocus.current=false;document.querySelector(".exp-inspect-button")?.focus({preventScroll:true});}else if(opener?.isConnected)opener.focus({preventScroll:true});else (document.querySelector(".exp-departure .exp-primary:not(:disabled)")??document.querySelector(".exp-departure-buttons button:not(:disabled)")??document.querySelector(".exp-header-actions button"))?.focus({preventScroll:true});}},[surface,session?.state.review?.id,worldReady]); useEffect(()=>{if(!surface&&!session?.state.review)return;const trap=(event:KeyboardEvent)=>{if(event.key!=="Tab")return;const panel=panelRef.current;if(!panel)return;const targets=[...panel.querySelectorAll('button:not(:disabled),a[href],input:not(:disabled),select:not(:disabled),[tabindex="0"]')].filter(n=>n.getClientRects().length);if(!targets.length){event.preventDefault();panel.focus();return;}const first=targets[0]!,last=targets.at(-1)!;if(event.shiftKey&&(document.activeElement===first||document.activeElement===panel)){event.preventDefault();last.focus();}else if(!event.shiftKey&&(document.activeElement===last||document.activeElement===panel)){event.preventDefault();first.focus();}};window.addEventListener("keydown",trap);return()=>window.removeEventListener("keydown",trap);},[surface,session?.state.review?.id]); function persist(next:LocalSave){if(leaseRef.current!=="held"){setNotice("This expedition is open in another tab. Finish there, or close that tab and check again.");return false;}try{writeLocal(next,keyRef.current);saveRef.current=next;setSave(next);setProblem("");return true;}catch(error){setProblem(error instanceof Error?error.message:"This browser could not save the move. No new action was taken.");return false;}} - /** `tide` starts Season 2's daily outing: a fresh Beacon Court with nothing banked, kept apart from First Light progress. */ - function begin(tide?:{tool:Tool}){ + /** `tide` starts Season 2's daily outing: a fresh Beacon Court with nothing banked, kept apart from First Light progress, answering one day's Tidekeeper ask. */ + function begin(tide?:{tool:Tool;day?:number}){ if(showPassage||!worldReady||saveRef.current.active||corruptRef.current||leaseRef.current!=="held")return; + startOuting(tide); + } + function startTideOver(){ + const active=saveRef.current.active;if(!canRestartTide||!active?.season||active.state.outcome!=="active"||busyRef.current||finishBusy.current||corruptRef.current||leaseRef.current!=="held")return; + const pending=activeTide.current?.pending??readTidePending(tideScopeOf(active.context));if(startOuting(restartTide(pending,today,active.state.tool),pending??undefined))setNotice("Mochi sets out again. The asks are open."); + } + function startOuting(tide?:{tool:Tool;day?:number},pending?:TidePending){ try{const harborContext=sessionRef.current?.runContext(saveRef.current.home)??{authority:"local-preview" as const,banked:[...saveRef.current.home.banked],lit:saveRef.current.home.lit,signaled:saveRef.current.home.signaled}; const context:RunContext=tide?{...harborContext,banked:[]}:harborContext,runArea:Area=tide?"beacon":area,runTool:Tool=tide?.tool??tool; if(runArea==="wind"&&!context.lit){setNotice("Restore the beacon before sailing to Wind Gate.");return;} setResting(false); - const state=startCourt({area:runArea,tool:runTool,banked:context.banked});if(!persist({...saveRef.current,active:{context,state,...(tide?{season:true as const}:{})},last:null})){sessionRef.current?.setActiveRun(null);return;} + const state=startCourt({area:runArea,tool:runTool,banked:context.banked});if(!persist({...saveRef.current,active:{context,state,...(tide?{season:true as const}:{})},last:null})){sessionRef.current?.setActiveRun(saveRef.current.active?.context??null);return;}if(tide){const day=tide.day??today,marker=pending??{day,late:day!==today};activeTide.current={context,pending:marker};if(!pending)writeTidePending(tideScopeOf(context),marker);} sessionRef.current?.setActiveRun?.(context);audio.current?.playMusic(runArea==="wind"?"wind-departure":"departure");setSurface(null);setNotice(runArea==="wind"?"Watch the outlet. The wheel bends a marked surge into a different channel.":"Tap a glowing neighbor to move. Water advances only when you decide.");setTransition(null);buffer.current=null; + if(queuedFrame.current!==null)cancelAnimationFrame(queuedFrame.current);queuedFrame.current=null;busyRef.current=false;setBusy(false);setFocused(null);return true; }catch(error){setProblem(error instanceof Error?error.message:"The outing could not start. Your saved harbor is unchanged.");} } async function complete(){ @@ -192,12 +276,12 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in if(finishBusy.current)return;finishBusy.current=true;setFinishing(true); const epoch=++finishEpoch.current,branch=keyRef.current,generation=presentation.current,owner=sessionRef.current; try{ - if(active.season)keepTide(active.context.authority==="near-testnet"?active.context.accountId:"preview",{id:crypto.randomUUID(),contentVersion:CONTENT_VERSION,tool:active.state.tool,commands:[...active.state.commands],cargo:[...active.state.cargo],outcome:active.state.outcome==="returned"?"returned":"rescued",savedAt:new Date().toISOString()}); + if(active.season)keepTide(tideScopeOf(active.context),{id:crypto.randomUUID(),contentVersion:CONTENT_VERSION,tool:active.state.tool,commands:[...active.state.commands],cargo:[...active.state.cargo],outcome:active.state.outcome==="returned"?"returned":"rescued",savedAt:new Date().toISOString()}); else if(owner)await owner.captureReturn(active.state,active.context);else await new ReturnRecords(localStorage).capture(active.state,active.context); if(!alive.current||epoch!==finishEpoch.current||branch!==keyRef.current||generation!==presentation.current||saveRef.current.active!==active||sessionRef.current!==owner)return; const banked=!active.season&&active.context.authority==="local-preview"?[...new Set([...current.home.banked,...(active.state.outcome==="returned"?active.state.cargo:[])])]:current.home.banked; const next={...current,home:{...current.home,banked},active:null,last:active.state}; - if(!persist(next))return;sessionRef.current?.setActiveRun?.(null);setTransition(null);setNotice(active.state.outcome==="returned"?(active.state.cargo.length?`Home with ${active.state.cargo.map(i=>names[i]).join(" and ")}.${active.season?" Dock today’s haul at Bram’s shelf.":active.context.authority==="near-testnet"?" Bring the satchel to Bram.":""}`:"Mochi is home, safe and empty-pawed."):eventDescription({kind:"rescue",reason:active.state.resolve<=0?"resolve":"flood"})); + if(!persist(next))return;sessionRef.current?.setActiveRun?.(null);setTransition(null);let tideNote="";if(active.season){try{const scope=tideScopeOf(active.context),pending=activeTide.current?.context===active.context?activeTide.current.pending:readTidePending(scope),day=pending?.day??today,recorded=recordTide(scope,{day,tool:active.state.tool,commands:active.state.commands,late:pending?.late??false}),outing=replayRun(active.state.tool,active.state.commands);try{writeTidePending(scope,null);}catch{}setTideVersion(n=>n+1);tideNote=active.state.outcome==="rescued"?" The asks slipped this time; the tide log keeps the try.":outing?` ${outingNotice(outing,cardForDay(day),recorded)}`:"";setLogDay(day);if(outing){setArrival({day,run:outing});trigger.current=null;setSurface("home");}}catch{tideNote=" The tide log could not be saved on this device. The outing itself is kept.";}}const returnNotice=active.state.outcome==="returned"?(active.state.cargo.length?`Home with ${active.state.cargo.map(i=>names[i]).join(" and ")}.${active.season?shelfNote({cargo:active.state.cargo,day:today}):active.context.authority==="near-testnet"?" Bring the satchel to Bram.":""}`:"Mochi is home, safe and empty-pawed."):eventDescription({kind:"rescue",reason:active.state.resolve<=0?"resolve":"flood"});setArrivalNotice(returnNotice);setNotice(returnNotice+tideNote); }catch(error){if(alive.current&&epoch===finishEpoch.current&&branch===keyRef.current)setProblem(error instanceof Error?error.message:"The returned outing could not be recorded. Keep it open and retry saving.");} finally{if(alive.current&&epoch===finishEpoch.current){finishBusy.current=false;setFinishing(false);}} } @@ -218,10 +302,11 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in const route=transition.after.area==="wind"?`${columns[wave.source]} source → ${columns[wave.exit]} exit`:`${columns[wave.exit]} surge`; setNotice(`${route}. Bridge at ${columns[wave.exit]}.${discovery}${footing}`); } + if(tideCard&&transition&&transition.after.outcome==="active"){const before=replayRun(transition.before.tool,transition.before.commands),after=replayRun(transition.after.tool,transition.after.commands),flip=before&&after?askFlips(tideCard,before,after):"";if(flip)setNotice(note=>note?`${note} ${flip}`:flip);} busyRef.current=false;setBusy(false);setTransition(null);const queued=buffer.current;buffer.current=null;if(saveRef.current.active?.state.outcome!=="active"){complete();return;}if(queued&&!pausedRef.current){const branch=keyRef.current,generation=presentation.current;const frame=requestAnimationFrame(()=>{if(queuedFrame.current===frame)queuedFrame.current=null;if(!alive.current||branch!==keyRef.current||generation!==presentation.current||leaseRef.current!=="held")return;command(queued);});queuedFrame.current=frame;}} function beat(event:CourtEvent,index:number){setLastBeat(`${presentation.current}:${index}:${event.kind}`);setNotice(eventDescription(event,run?.area));if(sound)audio.current?.play(event,run?.area);} useEffect(()=>{const keys=(event:KeyboardEvent)=>{ - if(showPassage)return; + if(showPassage||showTideRun)return; if(event.key==="Escape"){closePanel();return;} if(event.repeat||event.isComposing||event.altKey||event.ctrlKey||event.metaKey||event.shiftKey)return; if(pausedRef.current)return; @@ -231,7 +316,7 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in const map:Record={ArrowUp:"step:north",ArrowDown:"step:south",ArrowLeft:"step:west",ArrowRight:"step:east",w:"step:north",s:"step:south",a:"step:west",d:"step:east"," ":"wait",r:"return"}; let selected:Command|undefined=map[event.key];if(event.key==="e"){const state=saveRef.current.active?.state,available=state?legalCommands(state):[];selected=available.find(c=>/^(take:|reel:)/.test(c))??available.find(c=>c==="turn:vane");} if(selected){event.preventDefault();command(selected);} - };window.addEventListener("keydown",keys);return()=>window.removeEventListener("keydown",keys);},[command,showPassage]); + };window.addEventListener("keydown",keys);return()=>window.removeEventListener("keydown",keys);},[command,showPassage,showTideRun]); function inspect(position:Position){ const state=saveRef.current.active?.state; if(!state)return; @@ -253,13 +338,15 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in } function target(position:Position){const state=saveRef.current.active?.state;if(!state)return;const input=commandAt(state,position);if(input)command(input);else inspect(position);} function hover(position:Position|null){if(busyRef.current)return;const state=saveRef.current.active?.state;setFocused(position&&state?commandAt(state,position):null);} - function open(place:HomePlace|"menu"|"guide"|"lantern"|"inspect"|"crossings"|"chart"){if(place==="mochi"){setResting(true);setGreeting(n=>n+1);return;}setResting(false);buffer.current=null;restoreInspectFocus.current=place==="inspect";setSurface(place);} + /** Safari never focuses a clicked button, so fall back to the last button pressed. */ + function opener(){const active=document.activeElement;return active instanceof HTMLElement&&active!==document.body?active:pressed.current?.isConnected?pressed.current:null;} + function open(place:HomePlace|"menu"|"guide"|"lantern"|"inspect"|"crossings"|"chart"|"tide"|"court-tide"|"log"|"home"){if(!panelOpen.current)trigger.current=opener();if(place==="mochi"){setResting(true);setGreeting(n=>n+1);return;}setResting(false);buffer.current=null;restoreInspectFocus.current=place==="inspect";setSurface(place);} function 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"){ if(savedMode){request({kind:"restore",restoration});return;} - if(restoration==="beacon"&&home.banked.includes("lens")){if(persist({...saveRef.current,home:{...saveRef.current.home,lit:true}})){repairRequest.current={branch:desiredKey,kind:"beacon"};setNotice("Mochi lifts the lens into place. The beacon finds the bay again.");setSurface(null);}} - else if(restoration==="signal"&&home.lit&&home.banked.includes("vane")){if(persist({...saveRef.current,home:{...saveRef.current.home,signaled:true}})){repairRequest.current={branch:desiredKey,kind:"signal"};setNotice("The vane catches the breeze. Bram reads the wind from the quay.");setSurface(null);}} + if(restoration==="beacon"&&home.banked.includes("lens")){if(persist({...saveRef.current,home:{...saveRef.current.home,lit:true}})){repairRequest.current={branch:desiredKey,kind:"beacon"};setNotice(`Mochi lifts the lens into place. The beacon finds the bay again. The Tidekeeper stops mid-turn and stares at the light. Bram: “${CHAPTERS.lens.after[0]}”`);setSurface(null);}} + else if(restoration==="signal"&&home.lit&&home.banked.includes("vane")){if(persist({...saveRef.current,home:{...saveRef.current.home,signaled:true}})){repairRequest.current={branch:desiredKey,kind:"signal"};setNotice(`The vane catches the breeze. Bram: “${CHAPTERS.vane.after.join(" ")}”`);setSurface(null);}} } function storePassage(next:PassageHome){ if(!passageReadable.current||passageScope!==passageKey||keyRef.current!==desiredKey||leaseRef.current!=="held")return false; @@ -282,7 +369,34 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in const completed=passageDelivered(state); backFromPassage(next,next.heardBell&&!passage.heardBell?"Bram rigs a bell pull for both crossings. One pull per outing calls the next surge left from the far-center landing.":completed?(state.job==="bell"?"Bram’s supplies are stacked at Bell Steps.":"Mochi’s skiff is tied up at the quay."):state.court.outcome==="rescued"?"Bram brought Mochi home. The crossing can wait.":"Mochi is back at the dock."); } - const button=(input:Command,label=commandName(input))=>; + function storeTideBook(next:TideBook){ + if(!tideBookReadable.current||passageScope!==passageKey||keyRef.current!==desiredKey||leaseRef.current!=="held")return false; + try{writeBook(localStorage,tideRunKey,next);setTideBook(next);return true;}catch{return false;} + } + function departTide(start:TideStart){ + if(savedMode||run||passage.active||corruptRef.current)return; + if(!tideResume&&!storeTideBook({...tideBook,active:startTide(start)})){setNotice(tideBookReadable.current?"The tide could not be saved on this device. Nothing has changed.":"The saved tide could not be read. Its original record is still on this device.");return;} + setTideAway(false);setTideRound(n=>n+1);setResting(false);buffer.current=null;setSurface(null);setNotice(""); + audio.current?.playMusic("departure"); + } + function finishTideRun(state:TideState,again:boolean):boolean{ + if(savedMode||!tideBook.active||state.outcome==="active")return false; + const prize=state.story,won=!!prize&&state.banked.includes(prize); + 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;} + 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{ + const result=todayResult(closed,state.seed)!; + const message=first?`Banked ${state.score}. Bram guessed ${result.guess}.`:`A practice tide: banked ${state.score}. Today’s first tide is the one that counts.`; + setArrival({day:state.seed,result});setArrivalNotice(first?"":message);setNotice(message);open("home"); + } + return true; + } + const button=(input:Command,label=commandName(input))=>; const interactionLegal=busy?[]:legal; const pickups=interactionLegal.filter(c=>/^(take:|reel:|turn:)/.test(c)); const activeReturn=save.active?.state.outcome!=="active"&&!!save.active; @@ -296,19 +410,35 @@ export default function ExpeditionGame({session,accountPanel,audio:titleAudio,in }); const earlierReturns=stagedReturns.filter(record=>!recordReturns.includes(record)); const waitingCraft=["reserved","recovery-required"].includes(canonical?.craft?.state??""),waitingPolish=["reserved","recovery-required"].includes(canonical?.polish?.state??""); - const objective=visibleRun?.area==="wind"?visibleRun.cargo.includes("vane")?"Vane secured · reach the center dock.":visibleRun.banked.includes("vane")?"Practice the channels · your vane stays home.":!visibleRun.opened.includes(0)||!visibleRun.opened.includes(1)?`Charge the ${!visibleRun.opened.includes(0)&&!visibleRun.opened.includes(1)?"left and center exits":!visibleRun.opened.includes(0)?"left exit":"center exit"}.`:visibleRun.orientation!==0?"Turn the wheel at far center to align the cradle.":"The cradle is open. Lift the Signal Vane.":visibleRun?.cargo.includes("lens")?"Lens secured · reach the center dock.":visibleRun?.banked.includes("lens")?visibleRun.banked.includes("moth")?"Practice the tides · discoveries stay home.":"Rescue the wind-moth from the Right oyster.":"Open the Left oyster; bring its lens home."; + const objective=tideCard&&tideRun?tideObjective(tideCard,tideRun):visibleRun?.area==="wind"?visibleRun.cargo.includes("vane")?"Vane secured · reach the center dock.":visibleRun.banked.includes("vane")?"Practice the channels · your vane stays home.":!visibleRun.opened.includes(0)||!visibleRun.opened.includes(1)?`Charge the ${!visibleRun.opened.includes(0)&&!visibleRun.opened.includes(1)?"left and center exits":!visibleRun.opened.includes(0)?"left exit":"center exit"}.`:visibleRun.orientation!==0?"Turn the wheel at far center to align the cradle.":"The cradle is open. Lift the Signal Vane.":visibleRun?.cargo.includes("lens")?"Lens secured · reach the center dock.":visibleRun?.banked.includes("lens")?visibleRun.banked.includes("moth")?"Practice the tides · discoveries stay home.":"Rescue the wind-moth from the Right oyster.":"Open the Left oyster; bring its lens home."; const needLens=home.banked.includes("lens")&&!home.lit,needVane=home.lit&&home.banked.includes("vane")&&!home.signaled; - const canPreviewCrest=previewReturns.some(record=>record.outcome==="returned"&&record.cargo.includes("lens")); - const canPreviewMoth=previewReturns.some(record=>record.outcome==="returned"&&record.cargo.includes("moth")); + const storyNext=savedMode?null:chapterFor(home); + 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=recordReturns.length?"satchel":needLens||needVane?"beacon":chapterComplete?"chart":home.signaled?"crossings":needsLantern?"workbench":null; - const homeTitle=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=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 he 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=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 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 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; + const returnedToday=savedMode?!run&&readTide(tideScope).some(record=>{ + if(deviceDay(Date.parse(record.savedAt))!==today)return false; + 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 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):""; + if(showTideRun&&tideBook.active&&lease==="held"&&!problem)return storeTideBook({...tideBook,active:next})} onFinish={finishTideRun} onToggleSound={()=>void toggleSound()} + onLeave={()=>{setTideAway(true);setReadySceneKey(-1);setSceneKey(k=>k+1);}}/>; if(showPassage&&passage.active&&lease==="held"&&!problem&&!session?.state.review)return <> void toggleSound()} onLeave={()=>backFromPassage({...passage,active:null},"The line is coiled at home. You can choose another crossing.")}/> {passageError&&

{passageError}

} ; - return
+ return
{pressed.current=(event.target as Element).closest("button");}} data-testid="expedition-game" data-mode={run?"court":"harbor"} data-busy={busy} data-lease={lease} data-content={CONTENT_VERSION} data-beat={lastBeat}> {lease!=="waiting"&&{setFault(message);buffer.current=null;}} onReady={()=>setReadySceneKey(sceneKey)}/>} {!worldReady&&!fault&&

familiar.

Unpacking the harbor.

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

Reload Familiar
} {worldReady&&<> -
familiar.{authority}
{run?COURTS[run.area].title:"Pocket Harbor"}
{!run&&!surface&&!session?.state.review&&}
- {visibleRun&&
{title(phaseOf(visibleRun))} tide {visibleRun.turn+1>TURN_LIMIT?TURN_LIMIT:visibleRun.turn+1}/{TURN_LIMIT}Resolve {visibleRun.resolve}/3Pack {packSlots(visibleRun.cargo)}/3{title(visibleRun.tool)} {visibleRun.uses}
} +
familiar.{authority}
{run?COURTS[run.area].title:"Pocket Harbor"}
{!run&&}{!run&&!surface&&!session?.state.review&&}
+ {visibleRun&&
+ + +

{title(phaseOf(visibleRun))} tide, decision {Math.min(TURN_LIMIT,visibleRun.turn+1)} of {TURN_LIMIT}. Mochi can take {visibleRun.resolve} more {visibleRun.resolve===1?"splash":"splashes"}. Satchel {packSlots(visibleRun.cargo)} of 3. {title(visibleRun.tool)}: {visibleRun.uses} {visibleRun.uses===1?"use":"uses"} left.

+
} {visibleRun&&

Mochi is at {columns[visibleRun.position.x]}, {visibleRun.position.y>=3?"upper":"lower"} bank, row {visibleRun.position.y+1} of 5. The {columns[visibleRun.bridge]} bridge is open. Carried: {visibleRun.cargo.length?visibleRun.cargo.map(i=>names[i]).join(", "):"nothing"}.

} {visibleRun?.area==="wind"&&} - {!run&&!surface&&<> - -

{resting?"A moment together.":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."):homeIntent}

{resting&&}
+ {!run&&<> + + } - {run&&!surface&&!fault&&!session?.state.review&&

{objective}

{shownForecast}

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

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

}
} -
{notice}
+ {run&&!surface&&!fault&&!session?.state.review&&
{tideCard&&tideRun&&
{cardStatus(tideCard,tideRun).includes("slipped")&&}
}
{feedback}

{objective}

{shownForecast}

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

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

}
{interactionLegal.includes("return")&&
{button("return")}
}
} + {(!run||surface||fault||session?.state.review)&&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.

{sound&&
Sound mix
}:surface==="lantern"?<>

A light on the water.

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

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

Read the water.

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

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

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

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

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

}

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

:surface==="chart"?{setArea(choice);open("sail");}} onCrossing={departPassage} onRepair={()=>open("beacon")} + {(surface||session?.state.review)&&
+ {session?.state.review?<>

{session.state.review.title}

{session.state.review.description}

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

Keep your harbor

{accountPanel??

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

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

A moment at the water’s edge.

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

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

A light on the water.

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

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

Read the water.

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

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

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

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

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

}

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

:surface==="chart"?{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

{harbor.heardBell?"Bram’s bell pull is rigged at the far-center landing on both crossings. Once per outing, call a marked surge left.":chapterComplete?"Mochi pricks her ears toward Bell Steps. The old far-left arch falls quiet at low water.":"One line, two landings. Choose which way to rig the boat."}

@@ -346,7 +497,7 @@ 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.

}{SEASON2&&Bram is setting out his shelf…

}>begin({tool:choice})} tideScope={savedMode?session!.state.snapshot!.binding.nearAccountId:"preview"}/>
}: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==="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} {session?.state.message&&

{session.state.message}

}
} } diff --git a/web/src/expedition/game.css b/web/src/expedition/game.css index 23bc5b6..2f4642d 100644 --- a/web/src/expedition/game.css +++ b/web/src/expedition/game.css @@ -1,61 +1,77 @@ -:root:has(.exp-game){--exp-ink:#263e32;--exp-paper:#f5e3ba;--exp-wood:#5d4228;--exp-brass:#c8a365;--exp-sea:#386457} html:has(.exp-game),body:has(.exp-game){margin:0;width:100%;height:100%;overflow:hidden;background:#355a5d} -.exp-game,.exp-game *{box-sizing:border-box}.exp-game{position:fixed;inset:0;width:100%;height:100dvh;overflow:hidden;color:var(--exp-ink);font:500 16px/1.4 "Figtree Variable",sans-serif;isolation:isolate;background:#426b6b} -.exp-game::selection{color:#fff5d7;background:#486957}.exp-game h1,.exp-game h2{font-family:"Fraunces Variable",serif;text-wrap:balance;line-height:1.12;letter-spacing:-.025em}.exp-game h1{font-size:clamp(23px,2.3vw,32px);margin:0 0 9px}.exp-game h2{font-size:28px;margin:6px 42px 18px 0}.exp-game p{margin:0 0 14px}.exp-game button,.exp-game a,.exp-game input{font:inherit}.exp-game button,.exp-game a{touch-action:manipulation}.exp-game button{min-height:44px;min-width:44px;border:1px solid #ae9062;border-radius:9px;padding:9px 14px;background:#eddbad;color:#2d4637;box-shadow:inset 0 2px 0 #fff0cf,inset 0 -2px 0 #b9945a40,0 3px 8px #33271120;cursor:pointer;font-weight:750;transition:background .15s,transform .15s}.exp-game button:hover:not(:disabled){background:#fff1ca}.exp-game button:active:not(:disabled){transform:translateY(1px)}.exp-game button:disabled{cursor:default;opacity:.5;box-shadow:none}.exp-game :focus-visible{outline:3px solid #fff5ce;outline-offset:3px;box-shadow:0 0 0 5px #315b4a}.exp-game .exp-primary{background:#3c6555;color:#fff5dc;box-shadow:inset 0 2px 0 #61816c,inset 0 -3px 0 #234b3d,0 4px 10px #2d261b30;border-color:#2b5748}.exp-game .exp-primary:hover:not(:disabled){background:#496f59}.exp-game a{display:inline-flex;align-items:center;min-height:44px;color:inherit;text-underline-offset:3px}.exp-world{position:absolute;inset:0;z-index:-1;touch-action:none}.exp-world canvas{display:block;touch-action:none}.exp-mast{position:absolute;top:max(12px,env(safe-area-inset-top));left:max(16px,env(safe-area-inset-left));right:max(16px,env(safe-area-inset-right));display:flex;align-items:flex-start;justify-content:space-between;pointer-events:none;gap:12px}.exp-mast>*{pointer-events:auto}.exp-brand{flex-direction:column;justify-content:center;text-decoration:none;background:#60472b;color:#fff1d1!important;box-shadow:inset 0 0 0 2px #e4be78,0 4px 12px #31231130;border-radius:13px;padding:5px 15px 7px;font-family:"Fraunces Variable",serif!important;font-weight:850!important;font-size:28px!important;line-height:1.06;letter-spacing:-.04em}.exp-brand small{font-family:"Figtree Variable",sans-serif;font-size:10px;letter-spacing:0;font-weight:600;margin-top:3px}.exp-place{color:#fff4d7;background:#304e40df;border:1px solid #b9aa76;padding:5px 11px;border-radius:6px;font-size:13px;font-weight:750;margin-top:10px}.exp-menu-button{background:#61482d!important;color:#ffedca!important;border-color:#c8a365!important;width:48px;padding:10px!important}.exp-hud{position:absolute;top:max(92px,calc(env(safe-area-inset-top) + 82px));left:max(18px,env(safe-area-inset-left));display:flex;align-items:center;gap:15px;padding:8px 13px;color:#fff1d4;background:#304e40ed;border:1px solid #b7a878;border-radius:9px;font-size:14px;box-shadow:0 3px 10px #253b3020}.exp-hud strong{font-size:16px}.exp-hud strong span{font-size:12px;font-weight:550;margin-left:6px}.exp-command-tray{position:absolute;bottom:max(16px,env(safe-area-inset-bottom));right:max(22px,env(safe-area-inset-right));width:340px;color:#283f33;background:#f6e5becf;border:2px solid #fff0d0;outline:1px solid #ad8653;border-radius:16px;padding:12px;box-shadow:0 8px 24px #243b342b;backdrop-filter:blur(5px)}.exp-forecast{font-size:14px;line-height:1.3;margin-bottom:10px!important;min-height:36px}.exp-current-controls{display:flex;gap:12px;align-items:center}.exp-directions{display:grid;grid-template-columns:repeat(3,44px);grid-template-rows:repeat(3,44px);gap:3px;flex:0 0 auto}.exp-directions button{padding:8px;display:grid;place-items:center}.exp-directions .exp-north{grid-column:2;grid-row:1}.exp-directions .exp-west{grid-column:1;grid-row:2}.exp-directions .exp-east{grid-column:3;grid-row:2}.exp-directions .exp-south{grid-column:2;grid-row:3}.exp-directions .exp-wait{grid-column:2;grid-row:2;font-size:12px;padding:0}.exp-context-actions{flex:1;min-width:0;display:flex;flex-direction:column;gap:6px}.exp-context-actions>p{font-size:14px;margin:0}.exp-context-actions button{font-size:13px;padding:8px;line-height:1.15}.exp-lures{display:flex;flex-direction:column;gap:4px}.exp-feedback{position:absolute;bottom:max(18px,env(safe-area-inset-bottom));left:max(18px,env(safe-area-inset-left));max-width:calc(100% - 410px);padding:7px 11px;color:#fff3d8;background:#304e40e8;border-radius:7px;font-size:14px;pointer-events:none}.exp-feedback:empty{display:none}.exp-home-places button{position:absolute;color:#fff0ce;background:#5d432ce8;border-color:#d6b374;box-shadow:inset 0 1px 0 #b48d55,0 4px 14px #382b202c}.exp-home-places small{display:block;font-size:11px;font-weight:500}.exp-place-beacon{right:11%;top:23%}.exp-place-bram{left:20%;top:69%}.exp-place-workbench{left:8%;top:79%}.exp-place-satchel{left:43%;top:83%;display:flex;align-items:center;gap:5px}.exp-departure{position:absolute;right:max(24px,env(safe-area-inset-right));bottom:max(24px,env(safe-area-inset-bottom));width:320px;padding:19px;background:#f3e1b8;border:2px solid #fff0cf;outline:1px solid #a77d45;border-radius:15px;box-shadow:0 8px 24px #352c2428}.exp-departure p{font-size:15px}.exp-departure>.exp-primary{width:100%}.exp-game .exp-text-button{background:transparent;box-shadow:none;border:0;font-size:12px;width:100%;text-decoration:underline;text-underline-offset:3px;margin-top:4px}.exp-panel-shade{position:absolute;inset:0;background:#172f2a44;display:flex;align-items:center;justify-content:flex-end;padding:24px;z-index:30;backdrop-filter:blur(2px)}.exp-panel{position:relative;width:min(440px,100%);max-height:calc(100dvh - 48px);overflow-y:auto;overscroll-behavior:contain;background:#f6e6c3;color:#2c4335;padding:23px;border:2px solid #fff4d6;outline:1px solid #ae8953;border-radius:16px;box-shadow:0 12px 36px #20352f40;scrollbar-color:#8b734c #e3d0a7;scrollbar-width:thin}.exp-panel>button,.exp-panel>a{margin-bottom:8px;width:100%}.exp-panel>.exp-close{position:absolute;right:11px;top:11px;width:44px;min-width:44px;padding:9px}.exp-panel fieldset{margin:0 0 18px;padding:0;border:0}.exp-panel legend{font-weight:800;margin-bottom:6px}.exp-panel label{display:flex;gap:10px;align-items:center;min-height:48px;padding:8px 5px}.exp-panel input[type=radio]{width:20px;height:20px;accent-color:#3b6652}.exp-panel .exp-owned-item{padding:12px 0;border-top:1px solid #c4ad7e}.exp-owned-item button{margin:0 5px 7px 0}.exp-panel :focus-visible{outline-color:#37634b;box-shadow:none}.exp-save-problem,.exp-fault{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:min(440px,calc(100% - 30px));max-height:calc(100dvh - 40px);overflow:auto;background:#f9e8c3;color:#6a2e22;border:2px solid #f9d4a4;padding:22px;border-radius:16px;box-shadow:0 10px 30px #20362e55;z-index:50}.exp-save-problem button,.exp-fault button{width:100%}.exp-paused{position:absolute;left:50%;top:45%;transform:translate(-50%,-50%);padding:16px 20px;background:#f5e3bd;box-shadow:0 5px 20px #20362e40;border-radius:12px;text-align:center;max-width:calc(100% - 30px);z-index:25} -@media(max-width:900px) and (orientation:portrait) and (min-height:500px){.exp-mast{left:max(10px,env(safe-area-inset-left));right:max(10px,env(safe-area-inset-right));top:max(10px,env(safe-area-inset-top))}.exp-brand{font-size:23px!important;padding:6px 12px}.exp-place{font-size:11px;margin-top:7px;padding:5px 7px}.exp-hud{top:max(76px,calc(env(safe-area-inset-top) + 70px));left:max(10px,env(safe-area-inset-left));right:max(10px,env(safe-area-inset-right));gap:9px;padding:7px 10px;justify-content:space-between;font-size:11px}.exp-hud strong{font-size:13px}.exp-hud strong span{font-size:10px;margin-left:3px}.exp-command-tray{left:max(10px,env(safe-area-inset-left));right:max(10px,env(safe-area-inset-right));bottom:max(10px,env(safe-area-inset-bottom));width:auto;padding:9px 10px;background:#f6e5bee8}.exp-forecast{font-size:12px;min-height:28px;margin-bottom:5px!important}.exp-current-controls{gap:10px}.exp-directions{grid-template-columns:repeat(3,44px);grid-template-rows:repeat(3,44px);gap:2px}.exp-context-actions button{font-size:12px}.exp-context-actions p{font-size:12px}.exp-lures{gap:2px}.exp-feedback{bottom:205px;left:10px;right:10px;max-width:none;font-size:12px;line-height:1.25;padding:6px 9px}.exp-game[data-mode=harbor] .exp-feedback{bottom:10px;font-size:12px}.exp-departure{left:12px;right:12px;bottom:48px;width:auto;padding:15px}.exp-departure h1{font-size:24px}.exp-departure p{font-size:14px;margin-bottom:10px}.exp-home-places .exp-place-beacon{top:23%;right:7%}.exp-home-places .exp-place-bram{top:49%;left:10%}.exp-home-places .exp-place-workbench{top:58%;left:5%}.exp-home-places .exp-place-satchel{top:59%;left:auto;right:9%}.exp-panel-shade{padding:12px}.exp-panel{max-height:calc(100dvh - 24px);padding:20px}.exp-panel h2{font-size:26px}} -@media(max-height:600px) and (min-width:700px){.exp-hud{top:80px;font-size:12px;gap:10px}.exp-command-tray{width:310px;bottom:10px;right:12px;padding:9px}.exp-current-controls{gap:8px}.exp-forecast{font-size:12px}.exp-feedback{max-width:calc(100% - 355px);font-size:12px}.exp-departure{bottom:12px;width:290px;padding:14px}.exp-departure h1{font-size:23px}.exp-panel-shade{padding:10px}.exp-panel{max-height:calc(100dvh - 20px)}} -@media(prefers-reduced-motion:reduce){.exp-game *{scroll-behavior:auto!important;transition:none!important}} -@media(max-width:900px) and (orientation:portrait) and (min-height:500px){ - .exp-current-controls{flex-direction:column;gap:7px} - .exp-directions{display:flex;justify-content:space-between;width:100%;gap:5px} - .exp-directions button{width:44px;height:44px} - .exp-directions .exp-north{order:0}.exp-directions .exp-west{order:1}.exp-directions .exp-wait{order:2}.exp-directions .exp-east{order:3}.exp-directions .exp-south{order:4} - .exp-context-actions{width:100%;min-height:44px;justify-content:center;flex-direction:row;align-items:center} - .exp-context-actions>button{flex:1}.exp-context-actions>p{font-size:12px;line-height:1.2;margin:0} - .exp-lures{flex-direction:row;width:100%;gap:5px}.exp-lures button{flex:1;min-width:44px} - .exp-feedback{bottom:166px} -} -.exp-channel-map{position:absolute;top:146px;left:18px;background:#304e40ed;color:#fff1d4;border-radius:8px;padding:7px 11px;font-size:13px;max-width:380px;pointer-events:none}.exp-channel-map small{display:block;font-size:11px;margin-top:3px}.exp-panel .ex-account h2{font-size:23px}.exp-panel .ex-account button{display:block;width:100%;margin:8px 0}.exp-panel .ex-account input{display:block;max-width:100%;min-height:44px;border:1px solid #ad9165;border-radius:6px;padding:8px;accent-color:#386453;background:#fff6de;color:#283f33}.exp-panel .ex-account label{display:block}.exp-panel .ex-account p{overflow-wrap:anywhere} -@media(max-width:900px) and (orientation:portrait) and (min-height:500px){.exp-home-places .exp-place-bram{top:calc(100% - 365px);left:4%}.exp-home-places .exp-place-workbench{top:calc(100% - 430px);left:4%}.exp-home-places .exp-place-satchel{top:calc(100% - 350px);right:6%}.exp-channel-map{top:113px;left:10px;right:10px;max-width:none;font-size:12px;padding:5px 9px}.exp-channel-map small{font-size:10px}} +.exp-game,.exp-game *{box-sizing:border-box} +.exp-game [hidden]{display:none!important} +.exp-game{position:fixed;inset:0;width:100%;height:100dvh;overflow:hidden;color:var(--exp-ink);font:500 16px/1.4 "Figtree Variable",sans-serif;isolation:isolate;background:#426b6b} +.exp-game::selection{color:#fff5d7;background:#486957} +.exp-game h1,.exp-game h2{font-family:"Fraunces Variable",serif;text-wrap:balance;line-height:1.12;letter-spacing:-.025em} +.exp-game h1{font-size:clamp(23px,2.3vw,32px);margin:0 0 9px} +.exp-game h2{font-size:28px;margin:6px 42px 18px 0} +.exp-game p{margin:0 0 14px} +.exp-game :where(button,a,input){font:inherit} +.exp-game button,.exp-game a{touch-action:manipulation} +.exp-game button:disabled{cursor:default;opacity:.5;box-shadow:none} +.exp-game a{display:inline-flex;align-items:center;min-height:44px;color:inherit;text-underline-offset:3px} +.exp-world{position:absolute;inset:0;z-index:-1;touch-action:none} +.exp-world canvas{display:block;touch-action:none} +.exp-mast{position:absolute;top:max(12px,env(safe-area-inset-top));left:max(16px,env(safe-area-inset-left));right:max(16px,env(safe-area-inset-right));display:flex;align-items:flex-start;justify-content:space-between;pointer-events:none;gap:12px} +.exp-mast>*{pointer-events:auto} +.exp-brand{flex-direction:column;justify-content:center;text-decoration:none;background:#60472b;color:#fff1d1!important;box-shadow:inset 0 0 0 2px #e4be78,0 4px 12px #31231130;border-radius:13px;padding:5px 15px 7px;font-family:"Fraunces Variable",serif!important;font-weight:850!important;font-size:28px!important;line-height:1.06;letter-spacing:-.04em} +.exp-place{color:#fff4d7;background:#304e40df;border:1px solid #b9aa76;padding:5px 11px;border-radius:6px;font-size:13px;font-weight:750;margin-top:10px} +.exp-menu-button{background:#61482d!important;color:#ffedca!important;border-color:#c8a365!important;width:48px;padding:10px!important} +.exp-forecast{font-size:14px;line-height:1.3;margin-bottom:10px!important;min-height:36px} +.exp-current-controls{display:flex;gap:12px;align-items:center} +.exp-directions{display:grid;grid-template-columns:repeat(3,44px);grid-template-rows:repeat(3,44px);gap:3px;flex:0 0 auto} +.exp-directions button{padding:8px;display:grid;place-items:center} +.exp-directions .exp-north{grid-column:2;grid-row:1} +.exp-directions .exp-west{grid-column:1;grid-row:2} +.exp-directions .exp-east{grid-column:3;grid-row:2} +.exp-directions .exp-south{grid-column:2;grid-row:3} +.exp-directions .exp-wait{grid-column:2;grid-row:2;font-size:12px;padding:0} +.exp-context-actions{flex:1;min-width:0;display:flex;flex-direction:column;gap:6px} +.exp-context-actions>p{font-size:14px;margin:0} +.exp-context-actions button{font-size:13px;padding:8px;line-height:1.15} +.exp-lures{display:flex;flex-direction:column;gap:4px} +.exp-feedback:empty{display:none} +.exp-panel>button,.exp-panel>a{margin-bottom:8px;width:100%} +.exp-panel fieldset{margin:0 0 18px;padding:0;border:0} +.exp-panel legend{font-weight:800;margin-bottom:6px} +.exp-panel label{display:flex;gap:10px;align-items:center;min-height:48px;padding:8px 5px} +.exp-panel input[type=radio]{width:20px;height:20px;accent-color:#3b6652} +.exp-panel .exp-owned-item{padding:12px 0;border-top:1px solid #c4ad7e} +.exp-owned-item button{margin:0 5px 7px 0} +.exp-save-problem,.exp-fault{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);width:min(440px,calc(100% - 30px));max-height:calc(100dvh - 40px);overflow:auto;background:#f9e8c3;color:#6a2e22;border:2px solid #f9d4a4;padding:22px;border-radius:16px;box-shadow:0 10px 30px #20362e55;z-index:50} +.exp-save-problem button,.exp-fault button{width:100%} +.exp-paused{position:absolute;left:50%;top:45%;transform:translate(-50%,-50%);padding:16px 20px;background:#f5e3bd;box-shadow:0 5px 20px #20362e40;border-radius:12px;text-align:center;max-width:calc(100% - 30px);z-index:25} +.exp-channel-map{position:absolute;top:146px;left:18px;background:#304e40ed;color:#fff1d4;border-radius:8px;padding:7px 11px;font-size:13px;max-width:380px;pointer-events:none} +.exp-channel-map small{display:block;font-size:12px;margin-top:3px} +.exp-panel .ex-account h2{font-size:23px} +.exp-panel .ex-account button{display:block;width:100%;margin:8px 0} +.exp-panel .ex-account input{display:block;max-width:100%;min-height:44px;border:1px solid #ad9165;border-radius:6px;padding:8px;accent-color:#386453;background:#fff6de;color:#283f33} +.exp-panel .ex-account label{display:block} +.exp-panel .ex-account p{overflow-wrap:anywhere} .exp-objective{font-size:13px;font-weight:800;line-height:1.3;margin-bottom:6px!important} -@media(max-width:900px) and (orientation:portrait) and (min-height:500px){.exp-departure{bottom:max(10px,env(safe-area-inset-bottom))}.exp-home-places .exp-place-bram{top:calc(100% - 326px)}.exp-home-places .exp-place-workbench{top:calc(100% - 281px)}.exp-home-places .exp-place-satchel{top:calc(100% - 328px)}.exp-game[data-mode=harbor] .exp-feedback{top:90px;bottom:auto}.exp-hud{right:auto;display:grid;grid-template-columns:1fr 1fr;width:143px;gap:3px 9px}.exp-hud strong{grid-column:span 2}.exp-hud>span:last-child{grid-column:span 2}.exp-channel-map{left:auto;right:10px;top:116px;width:180px;font-size:10px}.exp-channel-map small{font-size:10px}.exp-objective{font-size:12px}.exp-feedback{bottom:192px}} -.exp-panel summary{min-height:44px;display:list-item;padding:10px 2px;cursor:pointer;font-weight:750}.exp-panel details{margin:10px 0}.exp-panel details button{display:block;width:100%;margin:7px 0}.exp-panel .exp-gift-details input{display:block;width:100%;min-height:44px;border:1px solid #a78c5d;border-radius:6px;padding:8px;background:#fff6dd;color:#2c4335}.exp-panel .exp-gift-details label{display:block} -@media(max-width:900px) and (orientation:portrait) and (min-height:500px){.exp-hud{grid-template-columns:auto auto auto;width:auto;gap:2px 8px;padding:5px 8px}.exp-hud strong{grid-column:span 3}.exp-hud>span:last-child{grid-column:auto}} -@media(max-height:499px){.exp-mast{top:10px;left:12px;right:12px}.exp-mast .exp-place{display:none}.exp-brand{font-size:23px!important;padding:6px 12px}.exp-hud{top:12px;left:auto;right:70px;width:174px;display:grid;grid-template-columns:auto auto;gap:2px 6px;padding:5px 8px;font-size:10px}.exp-hud strong{grid-column:span 2;font-size:12px}.exp-hud strong span{font-size:10px}.exp-hud>span:last-child{grid-column:span 2}.exp-command-tray{right:10px;bottom:10px;width:230px;padding:9px}.exp-command-tray .exp-current-controls{gap:7px}.exp-directions{grid-template-columns:repeat(3,44px);grid-template-rows:repeat(3,44px);gap:2px}.exp-context-actions button,.exp-context-actions p{font-size:11px;line-height:1.15;padding:5px}.exp-command-tray .exp-forecast,.exp-command-tray .exp-objective{font-size:11px;line-height:1.2;min-height:0;margin-bottom:6px!important}.exp-feedback{left:10px;bottom:8px;max-width:calc(100% - 265px);font-size:11px;padding:4px 6px;line-height:1.2}.exp-channel-map{top:89px;right:12px;left:auto;width:215px;font-size:10px;padding:5px 7px}.exp-channel-map small{font-size:10px}.exp-departure{width:250px;padding:12px;bottom:10px;right:10px}.exp-departure h1{font-size:20px}.exp-departure p{font-size:12px}.exp-home-places .exp-place-beacon{top:22%;right:8%}.exp-home-places .exp-place-bram{top:58%;left:10%}.exp-home-places .exp-place-workbench{top:77%;left:6%}.exp-home-places .exp-place-satchel{top:81%;left:29%}} -@media(max-height:650px){.exp-channel-map{display:none}} -.exp-lease{position:absolute;z-index:40;top:50%;left:50%;transform:translate(-50%,-50%);width:min(390px,calc(100% - 30px));max-height:calc(100dvh - 30px);overflow:auto;background:#f6e4be;padding:20px;border-radius:14px;box-shadow:0 8px 28px #20362e44}.exp-lease button{width:100%} +.exp-panel summary{min-height:44px;display:list-item;padding:10px 2px;cursor:pointer;font-weight:750} +.exp-panel details{margin:10px 0} +.exp-panel details button{display:block;width:100%;margin:7px 0} +.exp-panel .exp-gift-details input{display:block;width:100%;min-height:44px;border:1px solid #a78c5d;border-radius:6px;padding:8px;background:#fff6dd;color:#2c4335} +.exp-panel .exp-gift-details label{display:block} +.exp-lease{position:absolute;z-index:40;top:50%;left:50%;transform:translate(-50%,-50%);width:min(390px,calc(100% - 30px));max-height:calc(100dvh - 30px);overflow:auto;background:#f6e4be;padding:20px;border-radius:14px;box-shadow:0 8px 28px #20362e44} +.exp-lease button{width:100%} .exp-sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0} -.exp-panel .exp-origin .tb-origin-scene{width:min(100%,280px);margin:8px auto 14px}.exp-origin-metadata{font-size:12px;overflow-wrap:anywhere}.exp-game[data-busy=true] .exp-forecast{font-weight:650} -@media(max-width:900px) and (orientation:portrait) and (min-height:500px){.exp-home-places .exp-place-workbench{top:calc(100% - 382px)}} -.exp-lantern-preview{display:flex;align-items:center;justify-content:center;gap:18px;margin:8px 0 20px;font-family:"Fraunces Variable",serif;font-size:21px;font-weight:650}.exp-panel .exp-recipe-preview{display:flex;align-items:center;gap:18px;text-align:left}.exp-owned-item>.exp-lantern-preview{justify-content:flex-start} - -.exp-loading{position:absolute;inset:0;z-index:45;min-height:0;height:100%;font-family:"Figtree Variable",sans-serif}.exp-loading h1{font-family:"Fraunces Variable",serif} -@media(max-width:900px) and (orientation:portrait) and (max-height:499px){ - .exp-mast{top:max(10px,env(safe-area-inset-top));left:max(10px,env(safe-area-inset-left));right:max(10px,env(safe-area-inset-right))} - .exp-hud{top:max(77px,calc(env(safe-area-inset-top) + 70px));left:max(10px,env(safe-area-inset-left));right:auto;display:flex;width:auto;gap:6px;font-size:10px}.exp-hud strong{font-size:11px}.exp-hud>span:last-child{grid-column:auto} - .exp-command-tray{left:max(10px,env(safe-area-inset-left));right:max(10px,env(safe-area-inset-right));bottom:max(10px,env(safe-area-inset-bottom));width:auto;padding:8px 9px} - .exp-command-tray .exp-current-controls{flex-direction:row;gap:4px}.exp-directions{display:flex;flex:0 0 228px;gap:2px}.exp-directions button{width:44px;height:44px;flex:0 0 44px}.exp-directions .exp-north{order:0}.exp-directions .exp-west{order:1}.exp-directions .exp-wait{order:2}.exp-directions .exp-east{order:3}.exp-directions .exp-south{order:4} - .exp-context-actions{min-width:0;flex:1}.exp-context-actions button{font-size:10px;line-height:1.1;padding:4px}.exp-context-actions>p{font-size:10px;line-height:1.15;margin:0}.exp-feedback{left:10px;right:10px;bottom:137px;max-width:none;font-size:10px} - .exp-departure{left:10px;right:10px;bottom:10px;width:auto;padding:10px}.exp-departure p{font-size:12px;margin-bottom:7px}.exp-departure h1{font-size:20px;margin-bottom:6px}.exp-departure .exp-text-button{font-size:11px} - .exp-home-places .exp-place-beacon{top:87px;right:5%}.exp-home-places .exp-place-bram{top:160px;left:5%}.exp-home-places .exp-place-workbench{top:212px;left:5%}.exp-home-places .exp-place-satchel{top:212px;right:5%;left:auto}.exp-game[data-mode=harbor] .exp-feedback{top:77px;bottom:auto;max-width:52%} -} -@media(orientation:landscape) and (max-height:499px){.exp-home-places .exp-place-beacon{right:280px}} - +.exp-panel .exp-origin .tb-origin-scene{width:min(100%,280px);margin:8px auto 14px} +.exp-origin-metadata{font-size:12px;overflow-wrap:anywhere} +.exp-game[data-busy=true] .exp-forecast{font-weight:650} +.exp-lantern-preview{display:flex;align-items:center;justify-content:center;gap:18px;margin:8px 0 20px;font-family:"Fraunces Variable",serif;font-size:21px;font-weight:650} +.exp-panel .exp-recipe-preview{display:flex;align-items:center;gap:18px;text-align:left} +.exp-owned-item>.exp-lantern-preview{justify-content:flex-start} +.exp-loading{position:absolute;inset:0;z-index:45;min-height:0;height:100%;font-family:"Figtree Variable",sans-serif} +.exp-loading h1{font-family:"Fraunces Variable",serif} .exp-objective-row{display:flex;align-items:center;gap:8px;justify-content:space-between} .exp-objective-row .exp-objective{margin:0;flex:1} -.exp-game .exp-inspect-button{min-width:48px;min-height:44px;padding:0 5px;border:0;background:transparent;box-shadow:none;text-decoration:underline;text-underline-offset:3px;color:#2b5146;font-size:12px} .exp-panel .exp-mix{display:grid;gap:5px} .exp-panel .exp-mix label{display:grid;grid-template-columns:55px 1fr;align-items:center} .exp-panel .exp-mix input{width:100%;min-height:44px;accent-color:#416b5a} .exp-header-actions{display:flex;gap:6px;align-items:flex-start;pointer-events:auto} -.exp-hud .exp-tide-dial{display:inline-flex;align-items:end;gap:2px;height:12px;margin-right:5px;vertical-align:baseline} -.exp-tide-dial i{display:block;width:3px;background:#f8e9c5;opacity:.35;border-radius:2px 2px 0 0} -.exp-tide-dial i:first-child{height:4px;opacity:1} -.exp-tide-dial i:nth-child(2){height:8px} -.exp-tide-dial i:nth-child(3){height:12px} -.exp-tide-dial.phase-rising i:nth-child(2),.exp-tide-dial.phase-surge i{opacity:1} - -.exp-wind-brief{border-left:3px solid #996830;padding-left:10px} .exp-signal-study{position:relative;width:106px;height:58px;margin:4px 0 10px;color:#875321} .exp-signal-study i{position:absolute;left:49px;bottom:1px;width:5px;height:35px;background:linear-gradient(90deg,#76532d,#c89449,#705434);border-radius:3px} .exp-signal-study b{position:absolute;left:10px;top:1px;width:81px;height:21px;background:linear-gradient(#77502c,#e8bb65 42%,#a67334 62%,#744725);clip-path:polygon(0 0,20% 29%,24% 45%,73% 45%,68% 8%,100% 50%,68% 96%,73% 62%,24% 62%,0 100%,9% 52%);transform:rotate(-10deg)} @@ -72,8 +88,6 @@ html:has(.exp-game),body:has(.exp-game){margin:0;width:100%;height:100%;overflow .exp-job-list small{color:#355246} .exp-panel .exp-crossing-note{margin-top:12px;font-size:.85rem} .passage-storage-error{position:fixed;top:12%;left:8%;right:8%;margin:0;padding:10px;background:#fff0cb;color:#793927;z-index:20} -.exp-harbor-links{display:flex;gap:6px;justify-content:space-between;margin-top:5px} -.exp-game .exp-harbor-links button{min-height:44px;padding:4px 7px;background:transparent;border:0;box-shadow:none;font-size:12px;color:#2b5146;text-decoration:underline;text-underline-offset:3px} .harbor-routes{list-style:none;padding:0;margin:20px 0} .harbor-routes li{display:flex;gap:14px;padding:14px 0;border-bottom:1px solid #b59e76} .harbor-routes li:first-child{padding-top:0} @@ -82,16 +96,239 @@ html:has(.exp-game),body:has(.exp-game){margin:0;width:100%;height:100%;overflow .harbor-routes p{font-size:14px;line-height:1.4} .harbor-routes button{margin:0} .exp-panel .chart-save-note{font-size:12px;margin-top:16px;color:#485744} -@media(max-height:600px){.exp-game .exp-harbor-links{margin:0}.exp-game .exp-harbor-links button{font-size:11px}} +.exp-panel .exp-records{margin:16px 0 6px;padding-top:12px;border-top:1px solid #c4ad7e} +.exp-records-intro{font-size:14px} +.exp-records-status:empty{display:none} +.exp-panel .exp-record h3{font-family:"Fraunces Variable",serif;font-size:19px;line-height:1.2;letter-spacing:-.02em;margin:18px 0 8px} +.exp-record ul{list-style:none;margin:0;padding:0;display:grid;gap:9px} +.exp-record li{position:relative;padding-left:17px;font-size:15px;line-height:1.4;overflow-wrap:anywhere} +.exp-record li::before{content:"";position:absolute;left:1px;top:.5em;width:7px;height:7px;border-radius:50%;background:#3c6555} +.exp-record li[data-state=finding]::before{background:#9a5a1c} +.exp-record li[data-state=unchecked]{color:#6b4a26} +.exp-record li[data-state=unchecked]::before{background:none;box-shadow:inset 0 0 0 1.5px #6b4a26} +.exp-record li[data-state=source]::before{background:#8b734c;border-radius:1px} +.exp-record li small{display:block;margin-top:2px;font-size:12px;color:#485744;font-variant-numeric:tabular-nums} +:root:has(.exp-game){--exp-ink:#263e32;--exp-secondary-ink:#4f5d52;--exp-paper:#fbf3e2;--exp-card:#fbf3e2;--exp-hairline:#e6d6b4;--exp-wood:#5d4228;--exp-brass:#c8a365;--exp-sea:#2b5f4d;--exp-card-radius:22px;--exp-card-shadow:0 14px 34px rgba(64,40,18,.20),0 2px 6px rgba(64,40,18,.12)} +.exp-game{caret-color:var(--exp-sea);scrollbar-color:#8b734c var(--exp-card);scrollbar-width:thin} +.exp-game ::selection{color:#fff6e2;background:var(--exp-sea)} +.exp-game :where(button){display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:48px;min-width:44px;padding:8px 18px;border:1.5px solid #d6c29b;border-radius:999px;background:#fffaf0;color:var(--exp-ink);box-shadow:none;font:600 17px/1.2 "Fraunces Variable",serif;cursor:pointer;transition:background 150ms cubic-bezier(.16,1,.3,1),transform 150ms cubic-bezier(.16,1,.3,1)} +.exp-game :where(button:hover:not(:disabled)){background:#fff3dc} +.exp-game :where(button:active:not(:disabled)){transform:translateY(1px)} +.exp-directions button{min-height:44px;width:44px;border-radius:12px} +.exp-game :focus-visible{outline:3px solid #fff5ce;outline-offset:3px} +.exp-game :where(.exp-panel,.exp-departure,.exp-command-tray,.exp-phone-dock,.exp-harbor-tools,.exp-hud) :focus-visible{outline-color:#2b5f4d} +.exp-game .exp-primary{min-height:52px;padding:10px 26px;gap:10px;border:0;border-radius:999px;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} +.exp-game .exp-primary:hover:not(:disabled){background:#326d58} +.exp-game .exp-primary:active:not(:disabled){transform:translateY(1px);box-shadow:inset 0 1px 0 #5f9a83,inset 0 -1px 0 #1d4436,0 3px 9px rgba(31,68,54,.28)} +.exp-game .exp-primary>svg{flex:0 0 20px;width:20px;height:20px} +.exp-game .exp-secondary{min-height:48px;border:1.5px solid #d6c29b;border-radius:999px;background:#fffaf0;color:var(--exp-ink);box-shadow:none;font:600 17px/1.2 "Fraunces Variable",serif} +.exp-game .exp-secondary:hover:not(:disabled){background:#fff3dc} +.exp-game .exp-secondary>svg{flex:0 0 18px;width:18px;height:18px} +.exp-game .exp-text-button,.exp-game .exp-inspect-button{min-height:44px;min-width:44px;padding:8px 6px;border:0;background:transparent;color:var(--exp-ink);box-shadow:none;font:600 15px/1.3 "Figtree Variable",sans-serif;text-decoration:underline;text-underline-offset:3px} +.exp-game .exp-text-button:hover:not(:disabled),.exp-game .exp-inspect-button:hover:not(:disabled){background:transparent;color:#2b5f4d} +.exp-brand small{font-family:"Figtree Variable",sans-serif;font-size:12px;letter-spacing:0;font-weight:600;margin-top:3px} +/* The stake tip is the scene anchor; the lettering stays on the painted board. */ +.exp-home-places{position:absolute;inset:0;pointer-events:none} +.exp-game .exp-home-places button{position:absolute;left:var(--exp-sign-x);top:var(--exp-sign-y);right:auto;bottom:auto;width:176px;min-width:0;min-height:0;padding:0;border:0;border-radius:0;background:transparent;color:#4a3220;box-shadow:none;transform:translate(-50%,-100%);pointer-events:auto;transition:transform 150ms cubic-bezier(.16,1,.3,1),filter 150ms cubic-bezier(.16,1,.3,1)} +.exp-home-places button>img{display:block;width:100%;height:auto;pointer-events:none} +.exp-home-places button>span{position:absolute;left:28.125%;right:5.2%;top:9.4%;height:37.6%;display:flex;flex-direction:column;justify-content:center;align-items:center;font:600 17px/1.1 "Fraunces Variable",serif;white-space:nowrap;pointer-events:none} +.exp-home-places small{display:block;font:500 12px/1.05 "Figtree Variable",sans-serif} +.exp-game .exp-home-places button:hover:not(:disabled){background:transparent;transform:translate(-50%,-100%) translateY(-2px);filter:drop-shadow(0 0 2px #f2c879) drop-shadow(0 3px 6px #b27836)} +.exp-game .exp-home-places button:focus-visible{outline:0;filter:drop-shadow(0 0 1px #4a3220) drop-shadow(0 0 3px #fff5ce) drop-shadow(0 0 6px #fff5ce) drop-shadow(0 3px 8px #4a3220)} +.exp-place-beacon{--exp-sign-x:var(--exp-anchor-beacon-x);--exp-sign-y:var(--exp-anchor-beacon-y)} +.exp-place-bram{--exp-sign-x:var(--exp-anchor-bram-x);--exp-sign-y:var(--exp-anchor-bram-y)} +.exp-place-workbench{--exp-sign-x:var(--exp-anchor-workbench-x);--exp-sign-y:var(--exp-anchor-workbench-y)} +.exp-place-satchel{--exp-sign-x:var(--exp-anchor-satchel-x);--exp-sign-y:var(--exp-anchor-satchel-y)} +.exp-departure,.exp-panel,.exp-command-tray,.exp-hud,.exp-save-problem,.exp-fault,.exp-lease,.exp-paused{color:var(--exp-ink);background:var(--exp-card);border:0;outline:0;border-radius:var(--exp-card-radius);box-shadow:var(--exp-card-shadow)} +.exp-departure{position:absolute;left:50%;right:auto;bottom:max(20px,env(safe-area-inset-bottom));transform:translateX(-50%);width:calc(100% - 48px);max-width:1180px;display:flex;align-items:center;gap:20px;padding:16px 20px} +.exp-departure-heading{display:flex;align-items:center;gap:16px;flex:1;min-width:0} +.exp-departure-heading>div{min-width:0} +.exp-departure-heading .tide-departure-stamp{display:block;float:none;flex:0 0 88px;width:88px;margin:0;padding-right:16px;border-right:1px solid var(--exp-hairline);box-sizing:content-box} +.exp-departure h1{font-size:27px;margin:0 0 6px} +.exp-departure p{font-size:14px;line-height:1.4;margin:0;color:var(--exp-secondary-ink)} +.exp-departure-actions{display:flex;flex-direction:column;align-items:flex-end;gap:2px;flex:none} +.exp-departure-buttons{display:flex;align-items:center;gap:10px} +.exp-departure-actions button{white-space:nowrap;flex:none} +.exp-preparation{display:flex;align-items:center;gap:2px;width:max-content;max-width:100%;margin-top:4px;padding:0 2px 0 10px;border-radius:999px;background:#f0e6d0;color:var(--exp-ink);font-size:12px;white-space:nowrap} +.exp-game .exp-preparation button{width:44px;height:44px;min-height:44px;padding:12px;border:0;background:transparent;box-shadow:none} +.exp-preparation svg{width:18px;height:18px} +.exp-game .exp-preparation .exp-preparation-link{width:auto;padding:10px 12px;font:650 13px/1.2 "Figtree Variable",sans-serif;color:#2b5f4d;text-decoration:underline;text-underline-offset:3px;border-radius:999px;white-space:nowrap} +.exp-game .exp-preparation .exp-preparation-link:hover:not(:disabled){color:#263e32;background:#e6d9ba} +.exp-harbor-tools{display:flex;gap:6px} +.exp-harbor-tools button{min-height:48px;gap:7px;font:600 15px/1.2 "Figtree Variable",sans-serif} +.exp-harbor-tools svg{width:18px;height:18px} +.exp-harbor-tools button[aria-pressed=true]{background:#e8dcc0} +.exp-phone-dock{display:none} +.exp-panel-shade{position:absolute;inset:0;background:#172f2a44;display:flex;align-items:center;justify-content:flex-end;padding:24px;z-index:30} +.exp-panel-shade[data-inspect=true]{background:transparent;pointer-events:none} +.exp-panel-shade[data-inspect=true]>.exp-panel{pointer-events:auto} +.exp-panel{--exp-panel-pad:23px;position:relative;width:min(440px,100%);max-height:calc(100dvh - 48px);overflow-y:auto;overscroll-behavior:contain;padding:var(--exp-panel-pad);scrollbar-color:#8b734c var(--exp-card);scrollbar-width:thin;scroll-padding-top:78px} +.exp-panel>.exp-close{position:sticky;float:right;right:0;top:calc(-1 * var(--exp-panel-pad));width:44px;min-width:44px;min-height:44px;margin:0 0 4px 8px;padding:10px;z-index:5;background:var(--exp-card)} +.exp-panel>h2,.exp-panel>.tide>h3,.exp-panel>.tide-home>h2,.exp-panel .tide-log-header,.exp-panel>.harbor-chart>h2,.exp-panel>.exp-inspect>h2{position:sticky;top:calc(-1 * var(--exp-panel-pad));z-index:4;margin-top:0;padding:8px 0 14px;background:var(--exp-card)} +.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-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%)} +.exp-hud{position:absolute;top:max(92px,calc(env(safe-area-inset-top) + 82px));left:max(18px,env(safe-area-inset-left));display:flex;align-items:center;gap:12px;padding:12px 16px;border-radius:18px;font-size:13px;max-width:calc(100% - 36px)} +.exp-mochi-portrait{display:block;flex:0 0 48px;width:48px;height:48px;min-height:0;border-radius:50%;object-fit:cover} +.exp-mochi-status{min-width:0} +.exp-hud .exp-mochi-status h2{font-size:24px;margin:0 0 2px} +.exp-hud .exp-mochi-status>p{font-size:13px;margin:0 0 7px;color:var(--exp-secondary-ink);font-variant-numeric:tabular-nums} +.exp-status-pips{display:flex;align-items:center;gap:14px;flex-wrap:wrap} +.exp-status-pips>span{display:flex;align-items:center;gap:5px;font-size:12px} +.exp-pips{display:inline-flex;align-items:center;gap:3px} +.exp-pips i{display:block;width:8px;height:8px;border:1px solid #7c806b;border-radius:50%;background:transparent} +.exp-pips i[data-filled=true]{background:#2b5f4d;border-color:#2b5f4d} +.exp-command-tray{position:absolute;bottom:max(16px,env(safe-area-inset-bottom));right:max(22px,env(safe-area-inset-right));width:340px;padding:16px} +.exp-command-tray .exp-feedback{position:static;max-width:none;margin:0 0 12px;padding:0 0 10px;color:var(--exp-ink);background:transparent;border-radius:0;border-bottom:1px solid var(--exp-hairline);font-size:13px;line-height:1.35} +.exp-feedback{position:absolute;bottom:max(18px,env(safe-area-inset-bottom));left:max(18px,env(safe-area-inset-left));max-width:calc(100% - 410px);padding:8px 12px;color:#fff6e2;background:#304e40;border-radius:12px;font-size:14px;pointer-events:none} +.exp-game[data-mode=harbor]>.exp-feedback:not(.exp-sr-only){left:max(24px,calc((100% - 1180px)/2));right:auto;bottom:var(--exp-harbor-feedback-bottom,180px);transform:none;width:max-content;max-width:min(560px,calc(100% - 408px));margin:0} +.exp-feedback:empty{display:contents} +.exp-tray-reading{display:flex;flex-direction:column;min-height:0} +.exp-tray-scroll{min-height:0;overflow-y:auto;overscroll-behavior:contain;scrollbar-color:#8b734c var(--exp-card);scrollbar-width:thin} +.exp-command-tray .exp-tray-reading>.tide-outing{position:static;inset:auto;max-width:none;flex:none;margin:0 0 8px;pointer-events:auto} + +.exp-command-tray .exp-return-button{width:100%;margin-top:12px;padding-top:12px;border-top:1px solid var(--exp-hairline)} +.exp-command-tray .exp-return-button>button{width:100%} +.exp-wind-brief{border-left:1px solid #996830;padding-left:10px} +@media(hover:none){ + .exp-game .exp-primary{min-height:56px} +} +@media(max-width:899px){ + .exp-mast{left:max(10px,env(safe-area-inset-left));right:max(10px,env(safe-area-inset-right));top:max(10px,env(safe-area-inset-top))} + .exp-brand{font-size:23px!important;padding:6px 12px} + .exp-place{font-size:12px;margin-top:7px;padding:5px 7px} + .exp-harbor-tools{display:none} + .exp-game[data-mode=harbor] .exp-mast button[aria-label="Game menu"]{display:none} + .exp-phone-dock{position:fixed;left:0;right:0;bottom:0;z-index:10;display:grid;grid-template-columns:repeat(4,1fr);align-items:start;height:calc(64px + env(safe-area-inset-bottom));padding:4px max(8px,env(safe-area-inset-right)) env(safe-area-inset-bottom) max(8px,env(safe-area-inset-left));background:var(--exp-card);box-shadow:0 -2px 10px rgba(64,40,18,.10)} + .exp-game .exp-phone-dock button{display:flex;flex-direction:column;gap:3px;justify-self:center;width:min(100%,80px);height:56px;min-height:56px;padding:5px 8px;border:0;background:transparent;box-shadow:none;color:var(--exp-ink);font:600 12px/1.2 "Figtree Variable",sans-serif} + .exp-phone-dock button[aria-current],.exp-phone-dock button[aria-pressed=true]{background:#e8dcc0} + .exp-phone-dock svg{width:22px;height:22px} + .exp-game .exp-home-places button{width:132px} + .exp-home-places button>span{font-size:14px} + .exp-game .exp-home-places .exp-place-satchel{display:none} + .exp-departure{left:12px;right:12px;bottom:calc(76px + env(safe-area-inset-bottom));transform:none;width:auto;max-width:none;display:block;padding:16px} + .exp-departure-heading{gap:12px;margin-bottom:12px} + .exp-departure-heading .tide-departure-stamp{padding:0;border:0;box-sizing:border-box;flex-basis:72px;width:72px} + .exp-departure-heading .tide-stamp{zoom:.8181818} + .exp-departure h1{font-size:24px} + .exp-departure p{font-size:13px} + .exp-departure-actions{align-items:stretch;gap:6px} + .exp-departure-buttons{flex-direction:column;align-items:stretch;gap:8px} + .exp-departure-buttons>button,.exp-departure-actions>.exp-text-button{width:100%} + .exp-preparation{margin-top:4px;padding-left:8px} + .exp-panel-shade{padding:12px} + .exp-panel{--exp-panel-pad:20px;max-height:calc(100dvh - 24px)} + .exp-panel h2{font-size:26px} + .exp-hud{top:max(80px,calc(env(safe-area-inset-top) + 74px));left:max(10px,env(safe-area-inset-left));right:auto;max-width:calc(100% - 20px);gap:8px;padding:10px 12px} + .exp-mochi-portrait{flex-basis:44px;width:44px;height:44px} + .exp-hud .exp-mochi-status h2{font-size:22px} + .exp-status-pips{gap:10px} + .exp-command-tray{left:max(10px,env(safe-area-inset-left));right:max(10px,env(safe-area-inset-right));bottom:max(10px,env(safe-area-inset-bottom));width:auto;padding:12px} + .exp-command-tray .exp-tray-reading>.tide-outing{flex-direction:row;align-items:center;gap:4px;margin-bottom:4px} + .exp-command-tray .tide-outing>.tide-asks{flex:1;min-width:0} + .exp-command-tray .tide-outing>.tide-restart{flex:none;width:44px;min-width:44px;padding:10px} + .exp-restart-label{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0} + .exp-command-tray .exp-return-button{margin-top:6px;padding-top:6px} + .exp-forecast{font-size:13px;min-height:0;margin-bottom:10px!important} + .exp-objective{font-size:13px} + .exp-current-controls{flex-direction:column;gap:10px} + .exp-directions{display:flex;justify-content:space-between;width:100%;gap:5px} + .exp-directions button{width:44px;height:44px;min-height:44px} + .exp-directions .exp-north{order:0} + .exp-directions .exp-west{order:1} + .exp-directions .exp-wait{order:2} + .exp-directions .exp-east{order:3} + .exp-directions .exp-south{order:4} + .exp-context-actions{width:100%;min-height:44px;justify-content:center;flex-direction:row;align-items:center} + .exp-context-actions>button{flex:1} + .exp-context-actions>p{font-size:12px;line-height:1.3;margin:0} + .exp-lures{flex-direction:row;width:100%;gap:5px} + .exp-lures button{flex:1} + .exp-game[data-mode=harbor]>.exp-feedback:not(.exp-sr-only){top:82px;bottom:auto;left:12px;right:12px;width:auto;max-width:none;transform:none;font-size:12px} + .exp-channel-map{display:none} +} +@media(max-width:899px) and (orientation:portrait){ + .exp-harbor-home{height:100%;display:grid;grid-template-rows:minmax(0,1fr) auto;padding-bottom:calc(76px + env(safe-area-inset-bottom))} + .exp-departure p{display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden} + .exp-game[data-mode=harbor] .exp-departure{position:relative;grid-row:2;left:auto;right:auto;bottom:auto;margin:0 12px} +} +@media(max-width:479px){ + :root:has(.exp-game){--exp-card-radius:20px} +} +@media(max-width:400px){ + .exp-game .exp-home-places button{width:128px} +} +@media(orientation:landscape) and (max-height:500px){ + .exp-mast{top:10px;left:12px;right:12px} + .exp-mast .exp-place{display:none} + .exp-brand{font-size:23px!important;padding:6px 12px} + .exp-harbor-tools{display:flex} + .exp-game[data-mode=harbor] .exp-mast button[aria-label="Game menu"]{display:inline-flex} + .exp-phone-dock{display:none} + .exp-game .exp-home-places button{width:132px} + .exp-game .exp-home-places .exp-place-satchel{display:none} + .exp-hud{top:70px;left:auto;right:10px;max-width:260px;padding:8px 10px;gap:8px} + .exp-hud .exp-mochi-status h2{font-size:20px} + .exp-mochi-portrait{flex-basis:44px;width:44px;height:44px} + .exp-status-pips{gap:8px} + .exp-hud .exp-mochi-status>p{margin-bottom:4px;font-size:12px} + .exp-command-tray{left:auto;right:10px;bottom:10px;width:260px;max-height:calc(100dvh - 170px);padding:10px;display:flex;flex-direction:column;gap:6px} + .exp-tray-reading{flex:1} + .exp-tray-actions{flex:none} + .exp-command-tray .exp-current-controls{gap:6px} + .exp-command-tray .tide-outing>.tide-asks{flex-wrap:wrap} + .exp-directions{display:flex;justify-content:space-between;gap:3px} + .exp-context-actions{flex-direction:row;min-height:0} + .exp-context-actions>p,.exp-context-actions>button{font-size:12px} + .exp-command-tray .exp-forecast,.exp-command-tray .exp-objective{font-size:12px;line-height:1.3;margin-bottom:6px!important;min-height:0} + .exp-command-tray .exp-feedback{font-size:12px;margin-bottom:6px;padding-bottom:6px} + .exp-command-tray .exp-return-button{margin-top:6px;padding-top:6px} + .exp-departure{left:12px;right:12px;bottom:max(10px,env(safe-area-inset-bottom));transform:none;width:auto;display:flex;gap:12px;align-items:center;padding:10px 12px} + .exp-departure-heading{margin:0;gap:10px} + .exp-departure-heading .tide-departure-stamp{flex-basis:56px;width:56px;padding:0;border:0} + .exp-departure-heading .tide-stamp{zoom:.6363636} + .exp-departure h1{font-size:20px;white-space:nowrap;text-wrap:nowrap} + .exp-departure p{font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} + .exp-departure-actions{gap:0;align-items:flex-end} + .exp-departure-buttons{flex-direction:row;gap:6px} + .exp-game .exp-departure-buttons>button{width:auto;min-height:44px;font-size:14px;padding:8px 12px;gap:6px} + .exp-departure-actions>.exp-text-button{width:auto;font-size:13px;padding:6px;min-height:44px} + .exp-preparation{font-size:12px;margin:0} + .exp-game[data-mode=harbor]>.exp-feedback:not(.exp-sr-only){top:76px;left:50%;right:auto;width:max-content;max-width:min(480px,calc(100% - 24px));transform:translateX(-50%)} + .exp-panel-shade{padding:10px} + .exp-panel{max-height:calc(100dvh - 20px)} + .exp-channel-map{display:none} +} +@media(prefers-reduced-motion:reduce){ + .exp-game *,.exp-game *::before,.exp-game *::after{scroll-behavior:auto!important;transition:none!important;animation:none!important} +} + +.chart-place-mark{font-size:0;border:0;border-radius:0;color:var(--exp-ink)} +.chart-place-mark::before{content:"";width:24px;height:24px;background:currentColor;mask:var(--chart-icon) center/24px 24px no-repeat} +.harbor-routes>li:nth-child(1) .chart-place-mark{--chart-icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.8%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Ccircle%20cx%3D%2212%22%20cy%3D%2212%22%20r%3D%224%22/%3E%3Cpath%20d%3D%22M12%202v2m0%2016v2M2%2012h2m16%200h2M5%205l1.5%201.5m11%2011L19%2019M5%2019l1.5-1.5m11-11L19%205%22/%3E%3C/svg%3E")} +.harbor-routes>li:nth-child(2) .chart-place-mark{--chart-icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.8%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22M3%208h12a3%203%200%201%200-3-3M3%2012h17M3%2016h9a3%203%200%201%201-3%203%22/%3E%3C/svg%3E")} +.harbor-routes>li:nth-child(3) .chart-place-mark{--chart-icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.8%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22m5%2015%207-7%207%207M12%208v13%22/%3E%3C/svg%3E")} +.harbor-routes>li:nth-child(4) .chart-place-mark{--chart-icon:url("data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22black%22%20stroke-width%3D%221.8%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22m5%209%207%207%207-7M12%203v13%22/%3E%3C/svg%3E")} + +@media(min-width:900px){ + .exp-departure-heading p{white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +} +@media(min-width:900px) and (max-width:1100px) and (min-height:501px){ + .exp-departure{gap:12px;padding:14px 16px} + .exp-departure-heading{gap:12px} + .exp-departure-heading .tide-departure-stamp{padding-right:12px} + .exp-game .exp-departure-buttons>button{font-size:16px;padding-inline:18px} +} + +.exp-channel-map small svg{display:inline-block;width:12px;height:12px;margin-right:4px;vertical-align:-1px} +.exp-panel[data-surface=menu]>button:not(.exp-primary):not(.exp-close){border:0;background:transparent;box-shadow:none;font:600 15px/1.3 "Figtree Variable",sans-serif;text-decoration:underline;text-underline-offset:3px} +.exp-context-actions:empty{display:none} -@media (max-width:900px) and (orientation:portrait) and (min-height:500px) { - .exp-game[data-mode=harbor] { display:grid; grid-template-rows:minmax(0,1fr) auto; } - .exp-home-places { grid-row:1; position:relative; pointer-events:none; } - .exp-home-places button { pointer-events:auto; } - .exp-home-places .exp-place-beacon { top:23dvh; } - .exp-home-places .exp-place-bram, - .exp-home-places .exp-place-satchel { top:auto; bottom:8px; } - .exp-home-places .exp-place-workbench { top:auto; bottom:60px; } - .exp-game[data-mode=harbor] .exp-departure { grid-row:2; position:static; margin:0 12px max(10px,env(safe-area-inset-bottom)); } +@media(max-width:899px) and (orientation:portrait) and (min-height:500px){ + .exp-game:not(.passage-game) .exp-command-tray{display:flex;flex-direction:column;gap:4px;max-height:212px} + .exp-tray-reading{min-height:0;flex:1} + .exp-tray-actions{flex:none} } -.exp-panel .exp-records{margin:16px 0 6px;padding-top:12px;border-top:1px solid #c4ad7e}.exp-records-intro{font-size:14px}.exp-records-status:empty{display:none}.exp-panel .exp-record h3{font-family:"Fraunces Variable",serif;font-size:19px;line-height:1.2;letter-spacing:-.02em;margin:18px 0 8px}.exp-record ul{list-style:none;margin:0;padding:0;display:grid;gap:9px}.exp-record li{position:relative;padding-left:17px;font-size:15px;line-height:1.4;overflow-wrap:anywhere}.exp-record li::before{content:"";position:absolute;left:1px;top:.5em;width:7px;height:7px;border-radius:50%;background:#3c6555}.exp-record li[data-state=finding]::before{background:#9a5a1c}.exp-record li[data-state=unchecked]{color:#6b4a26}.exp-record li[data-state=unchecked]::before{background:none;box-shadow:inset 0 0 0 1.5px #6b4a26}.exp-record li[data-state=source]::before{background:#8b734c;border-radius:1px}.exp-record li small{display:block;margin-top:2px;font-size:12px;color:#485744;font-variant-numeric:tabular-nums} diff --git a/web/src/expedition/harbor-session.tsx b/web/src/expedition/harbor-session.tsx index 6d5a5ad..4941d00 100644 --- a/web/src/expedition/harbor-session.tsx +++ b/web/src/expedition/harbor-session.tsx @@ -57,7 +57,7 @@ export function HarborAccountPanel() { {state.mode==="saved"&&state.snapshot&&!state.snapshot.pets.length&&} :<> -

Use the same recoverable identity on each device. Login never creates another wallet or merges your memories.

+

Use the same recoverable identity on each device. Logging in never makes a second account or merges your memories.

{!controller.configured&&

Saving across devices is not connected at this address. Keep playing in the device preview.

} {unbound&&
{event.preventDefault();if(checked)void act(async()=>{await controller.provisionPlayer(username);if(alive.current)setUnbound(false);});}}> diff --git a/web/src/expedition/records.ts b/web/src/expedition/records.ts index 93ce531..544ffb4 100644 --- a/web/src/expedition/records.ts +++ b/web/src/expedition/records.ts @@ -19,7 +19,7 @@ export const SIGNER_ACTIONS:readonly {receiver:"root"|"items"|"season"|"self";me {receiver:"items",method:"mt_transfer",label:"gift a lantern"}, {receiver:"items",method:"storage_deposit",label:"cover a lantern’s storage"}, {receiver:"season",method:"storage_deposit",label:"open your page in Bram’s ledger"}, - {receiver:"season",method:"claim_daily",label:"dock today’s haul"}, + {receiver:"season",method:"claim_daily",label:"shelve today’s haul"}, {receiver:"season",method:"buy",label:"buy from Bram’s shelf"}, {receiver:"season",method:"sell",label:"sell to Bram’s till"}, {receiver:"season",method:"set_wish",label:"set Mochi’s wish"}, diff --git a/web/src/expedition/scene.ts b/web/src/expedition/scene.ts index 582ff6c..360f8f4 100644 --- a/web/src/expedition/scene.ts +++ b/web/src/expedition/scene.ts @@ -116,7 +116,7 @@ export class ExpeditionScene extends Phaser.Scene { this.actorShadow=this.add.ellipse(0,0,50,13,0x342719,.25).setDepth(7); this.actor=this.add.sprite(0,0,"exp-mochi",12).setOrigin(.5,MOCHI_GROUND).setDepth(10); this.actor.setInteractive({useHandCursor:true}).on("pointerdown",(pointer:Phaser.Input.Pointer)=>{ - if(!this.visual&&!this.gated)this.presses.set(pointer.id,{target:"mochi",x:pointer.x,y:pointer.y,dragged:false}); + if(!this.visual&&!this.gated&&this.onCanvas(pointer))this.presses.set(pointer.id,{target:"mochi",x:pointer.x,y:pointer.y,dragged:false}); }).on("pointerup",(pointer:Phaser.Input.Pointer)=>{ const press=this.presses.get(pointer.id);this.presses.delete(pointer.id); if(!this.visual&&!this.gated&&!pointer.wasCanceled&&press?.target==="mochi"&&!press.dragged&& @@ -139,9 +139,9 @@ export class ExpeditionScene extends Phaser.Scene { private field(){ const portrait=this.w<=900&&this.h>this.w; if(portrait&&this.h<500){const top=144,bottom=this.h-166,width=this.w*.82;return{cx:this.w/2,width,top,bottom,dy:(bottom-top)/4,dx:width/3};} - if(this.h<500){const available=this.w-260,width=Math.max(240,Math.min(available*.91,760)),top=98,bottom=this.h-34;return{cx:available/2,width,top,bottom,dy:(bottom-top)/4,dx:width/3};} + if(this.h<=500){const available=this.w-280,width=Math.max(240,Math.min(available*.91,760)),top=98,bottom=this.h-34;return{cx:available/2,width,top,bottom,dy:(bottom-top)/4,dx:width/3};} const top=portrait?(this.h<650?151:Math.max(200,this.h*.29)):this.h<500?122:Math.max(190,this.h*.31); - const bottom=portrait?this.h-240:this.h-72; + const bottom=portrait?this.h-264:this.h-72; const width=Math.min(portrait?this.w*.84:this.h<500?this.w*.45:this.w*.50,760); return {cx:portrait?this.w*.5:this.h<500?this.w*.40:this.w*.45,width,top,bottom,dy:(bottom-top)/4,dx:width/3}; } @@ -241,7 +241,7 @@ export class ExpeditionScene extends Phaser.Scene { const hitHeight=Math.max(44,Math.min(tile.height+15,f.dy-2)); const zone=this.add.zone(p.x,p.y,Math.max(44,tile.width),hitHeight).setInteractive({useHandCursor:true}).setDepth(16); const target=`${x},${y}`; - zone.on("pointerdown",(pointer:Phaser.Input.Pointer)=>{if(!this.gated)this.presses.set(pointer.id,{target,x:pointer.x,y:pointer.y,dragged:false});}); + zone.on("pointerdown",(pointer:Phaser.Input.Pointer)=>{if(!this.gated&&this.onCanvas(pointer))this.presses.set(pointer.id,{target,x:pointer.x,y:pointer.y,dragged:false});}); zone.on("pointerup",(pointer:Phaser.Input.Pointer)=>{ const press=this.presses.get(pointer.id);this.presses.delete(pointer.id); if(this.gated||pointer.wasCanceled||!press||press.target!==target||press.dragged||Math.hypot(pointer.x-press.x,pointer.y-press.y)>12)return; @@ -253,7 +253,7 @@ export class ExpeditionScene extends Phaser.Scene { } this.hooks.geometry(targets); const portrait=this.w<=900&&this.h>this.w; - const dock=this.point({x:1,y:0});if(!(portrait&&this.h<500&&court.position.x===1&&court.position.y===0))this.text(dock.x,dock.y+(this.h<500?-tile.height*.45:tile.height*.72),"DOCK",Math.min(14,this.w/28)); + const dock=this.point({x:1,y:0});if(!(portrait&&this.h<500&&court.position.x===1&&court.position.y===0))this.text(dock.x,dock.y+(this.h<500?-tile.height*.45:portrait?tile.height*.42:tile.height*.72),"DOCK",Math.min(14,this.w/28)); const keeperHeight=Math.min(this.h<500?f.top-(portrait?78:15):230,this.h*.26,portrait?this.w*(this.h<650?.38:.45):this.w*.52,portrait?f.top-(this.h<650?15:80):Infinity);this.keeper.setPosition(this.h<500&&!portrait?f.cx+Math.min(60,f.width*.18):portrait&&this.h<650?this.w*.72:f.cx,f.top-8).setDisplaySize(keeperHeight*1.32,keeperHeight); for(const item of ["lens","moth","vane"] as const){ const position=COURTS[court.area].finds[item];if(!position)continue; @@ -440,10 +440,12 @@ export class ExpeditionScene extends Phaser.Scene { this.forecast.lineStyle(2,0xffdd91).lineBetween(mark.x,sourceY,tip,sourceY); this.forecast.fillStyle(0xffdd91).fillTriangle(tip,sourceY,tail,sourceY-4,tail,sourceY+4); } - const lanes=["L","C","R"]; - const label=source===exit?`IN + OUT · ${["LEFT","CENTER","RIGHT"][exit]}`:`IN ${lanes[source]} → OUT ${lanes[exit]}`; - this.forecastLabel.setPosition(p.x,this.h<500?f.top+35:f.top-46).setFontSize(Math.min(14,this.w/27)).setText(bellPreview?`IF BELL · ${["LEFT","CENTER","RIGHT"][exit]}`:label).setVisible(true); + const lanes=["left","center","right"]; + const label=source===exit?`Next wave: ${lanes[exit]} lane`:`Next wave: ${lanes[source]} to ${lanes[exit]} lane`; + this.forecastLabel.setPosition(p.x,this.h<500?f.top+35:f.top-46).setFontSize(Math.min(14,this.w/27)).setText(bellPreview?`With bell: ${lanes[exit]} lane`:label).setVisible(true); } + /** Phaser hit-tests game objects even when a DOM card above the canvas took the press. */ + private onCanvas(pointer:Phaser.Input.Pointer){return pointer.downElement===this.game.canvas;} private paintHints(court:CourtState){ this.neighbors.clear();const tile=this.tileSize(); for(let y=0;y<5;y++)for(const x of [0,1,2] as const){const target={x,y},command=commandAt(court,target);if(!command)continue;const accepted=applyCommand(court,command);if(!accepted)continue;const risk=accepted.events.some(e=>e.kind==="hit"),p=this.point(target);this.neighbors.lineStyle(3,risk?0x8e3527:0xffe1a1,.95); @@ -462,17 +464,24 @@ export class ExpeditionScene extends Phaser.Scene { } private harbor(){ const portrait=this.w<=900&&this.h>this.w; - const groundY=portrait?this.h-(this.h<500?235:316):this.h*.81; + const landscape=!portrait&&this.h<=500; + const groundY=portrait?Math.max(230,this.h-522):landscape?this.h*.60:this.h*.81; + const source=this.textures.get("exp-island").getSourceImage() as HTMLImageElement; + const landing=(x:number,y:number,width:number)=>{ + const pier=this.add.image(x,y,"exp-island").setOrigin(.5,.41).setDisplaySize(width,width*source.height/source.width).setDepth(1);this.surfaces.push(pier); + }; if(portrait){ + this.fit(this.backdrop,this.w,this.h*1.16);this.backdrop.y=this.h-this.backdrop.displayHeight/2; const harborWidth=this.backdrop.displayWidth; const requestedX=this.w*.77-(.824-.5)*harborWidth; this.backdrop.x=Phaser.Math.Clamp(requestedX,this.w-harborWidth/2,harborWidth/2); - const source=this.textures.get("exp-island").getSourceImage() as HTMLImageElement; - const pier=this.add.image(this.w*.40,groundY,"exp-island").setOrigin(.5,.41).setDisplaySize(this.w*.92,this.w*.92*source.height/source.width).setDepth(1);this.surfaces.push(pier); + landing(this.w*.40,groundY,this.w*.92); + landing(this.w*.50,this.h-444,this.w*1.18); } + if(landscape){landing(this.w*.40,groundY,this.w*.55);landing(this.w-224,this.h-146,440);} const actorSize=Math.min(180,this.w*.28,this.h*.25); - this.actor.setPosition(this.w*.49,groundY).setDisplaySize(actorSize,actorSize);this.pose(this.snapshot.home.lit?"relieved":"curious");this.actorShadow.setPosition(this.actor.x,this.actor.y).setSize(actorSize*.5,14); - const b=Math.min(255,this.w*.36,this.h*.38);this.bram.setFlipX(false).setPosition(this.w*.28,portrait?groundY-4:this.h*.82).setDisplaySize(b*.75,b); + this.actor.setPosition(this.w*(landscape?.43:.49),groundY).setDisplaySize(actorSize,actorSize);this.pose(this.snapshot.home.lit?"relieved":"curious");this.actorShadow.setPosition(this.actor.x,this.actor.y).setSize(actorSize*.5,14); + const b=Math.min(255,this.w*.36,this.h*.38);this.bram.setFlipX(false).setPosition(this.w*(landscape?.23:.28),portrait?groundY-4:landscape?this.h*.59:this.h*.82).setDisplaySize(b*.75,b); const services=this.snapshot.home.services; if(services?.includes("bell")){ const landing=this.homeProps,w=Math.min(27,actorSize*.18); @@ -545,6 +554,19 @@ export class ExpeditionScene extends Phaser.Scene { g.fillStyle(0xe3bc79).fillTriangle(x+15,y-28,x+9,y-17,x+22,y-17).fillCircle(x+15,y-15,2); g.lineStyle(1.5,0xe0bf86).lineBetween(x+15,y-13,x+15,y+2).strokeCircle(x+15,y+5,3); } + const painted=(x:number,y:number)=>({x:this.backdrop.x+this.backdrop.displayWidth*(x-.5),y:this.backdrop.y+this.backdrop.displayHeight*(y-.5)}); + const signs=portrait?{ + workbench:{x:this.w/6,y:this.h-440},bram:{x:this.w/2,y:this.h-440},beacon:{x:this.w*5/6,y:this.h-440},satchel:{x:this.w*5/6,y:this.h-440}, + }:landscape?{ + workbench:{x:this.w-368,y:this.h-142},bram:{x:this.w-224,y:this.h-142},beacon:{x:this.w-80,y:this.h-142},satchel:{x:this.w-80,y:this.h-142}, + }:{ + bram:{x:this.w-272,y:this.h*.60},beacon:{x:this.w-88,y:this.h*.60},workbench:{x:this.w-272,y:this.h-198},satchel:{x:this.w-88,y:this.h-198}, + }; + const landmarks={bramFeet:{x:this.bram.x,y:this.bram.y},mochi:{x:this.actor.x,y:this.actor.y},beacon:painted(.824,.55),workbench:painted(.18,.70),lantern:{x:portrait?this.w*.72:this.w*.19,y:portrait?groundY-25:this.h*.69}}; + const root=this.game.canvas.closest(".exp-game"); + for(const [place,point] of Object.entries(signs))for(const axis of ["x","y"] as const)root?.style.setProperty(`--exp-anchor-${place}-${axis}`,`${point[axis]}px`); + for(const axis of ["x","y"] as const)root?.style.setProperty(`--exp-anchor-mochi-${axis}`,`${landmarks.mochi[axis]}px`); + if(this.game.canvas.parentElement)this.game.canvas.parentElement.dataset.harborAnchors=JSON.stringify({landmarks,signs}); } private addHomeFind(item:Find,x:number,y:number,size:number){const image=this.add.image(x,y,`exp-${item}`).setDisplaySize(size,size).setDepth(item==="vane"?11:7);this.cargo.push(image);} private async tween(targets:object,config:Omit,duration:number){ diff --git a/web/src/main.tsx b/web/src/main.tsx index 17e45ce..bfdcaab 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -12,6 +12,7 @@ async function entry() { if (path === "" || path === "/plan" || path.startsWith("/plan/")) return (await import("./landing/Landing")).Landing; if (import.meta.env.DEV && new URLSearchParams(window.location.search).has("storyboard")) return (await import("./opening/Storyboard")).default; if (import.meta.env.DEV && new URLSearchParams(window.location.search).has("season-harness")) return (await import("./season/Harness")).default; + if (import.meta.env.DEV && new URLSearchParams(window.location.search).has("tide-harness")) return (await import("./tide/Harness")).default; const game=Promise.all([import("./expedition/Game"),import("./expedition/harbor-session")]); // `?play` skips the title screen (browser tests and direct links into play). if(new URLSearchParams(window.location.search).has("play")){ @@ -30,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]}/>}; + screen={session=>} audio={audio} initialSound={play.start.sound} initialMix={[play.start.music,play.start.effects]} initialSurface={play.start.surface}/>}; } return <> {screen} diff --git a/web/src/opening/Opening.test.tsx b/web/src/opening/Opening.test.tsx new file mode 100644 index 0000000..047b1b5 --- /dev/null +++ b/web/src/opening/Opening.test.tsx @@ -0,0 +1,76 @@ +import { expect, test } from "bun:test"; +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", () => { + 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 }; + const soundtag = { style: {} as Record, isConnected: true }; + const world = { style: {} as Record, isConnected: true }; + const post = { style: {} as Record, isConnected: true }; + const boards = Object.fromEntries(opening.items().map(id => [id, { style: { background: "painted board" } as Record, isConnected: true }])); + opening.root = { + clientWidth: width, clientHeight: height, dataset: {}, + querySelector: (selector: string) => selector === '[data-el="bell"]' ? bell : selector === '[data-el="soundtag"]' ? soundtag : selector === '[data-el="world"]' ? world : selector === '[data-el="post"]' ? post : boards[selector.match(/data-plank="([^"]+)"/)?.[1] ?? ""] ?? null, + querySelectorAll: () => [], + } as unknown as HTMLDivElement; + opening.s = { camT: 0, zoomAdd: 0, courtA: 0, titleA: 1, promptA: 0, capA: 0 }; + opening.mode = "menu"; opening.sel = "new"; + for (const id of opening.items()) opening.mp[id] = 1; + opening.draw(); + const scale = Number(world.style.transform.match(/scale\(([^)]+)\)/)![1]); + const k = Number(post.style.transform.match(/scale\(([^)]+)\)/)![1]); + expect(parseFloat(bell.style.width) * scale * k).toBeGreaterThanOrEqual(44 - 1e-9); + expect(parseFloat(bell.style.height) * scale * k).toBeGreaterThanOrEqual(44 - 1e-9); + expect(parseFloat(bell.style.left) + parseFloat(bell.style.width) / 2).toBe(826); + expect(parseFloat(soundtag.style.fontSize) * scale * k).toBeGreaterThanOrEqual(12 - 1e-9); + 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)"); + } +}); + +test("options keep volume targets at 44px and the scroll inside the viewport", () => { + 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 world = { style: {} as Record, isConnected: true }; + const post = { style: {} as Record, isConnected: true }; + const pegs = Array.from({ length: 10 }, () => ({ dataset: { bus: "music" }, style: {} as Record })); + const buttons = [...pegs, ...Array.from({ length: 2 }, () => ({ dataset: {}, style: {} as Record }))]; + const scroll = { style: {} as Record, offsetHeight: 330, get offsetWidth() { return parseFloat(this.style.width); }, isConnected: true, querySelectorAll: () => buttons }; + opening.root = { + clientWidth: width, clientHeight: height, dataset: {}, + querySelector: (selector: string) => ({ '[data-el="world"]': world, '[data-el="post"]': post, '[data-el="scroll"]': scroll } as Record)[selector] ?? null, + querySelectorAll: () => [], + } as unknown as HTMLDivElement; + opening.s = { camT: 0, zoomAdd: 0, courtA: 0, titleA: 1, promptA: 0, capA: 0, scrollP: 1 }; + opening.mode = "menu"; + opening.draw(); + const [, tx, , scale] = world.style.transform.match(/translate\(([^,]+)px,([^)]+)px\) scale\(([^)]+)\)/)!; + const [, dx, k] = post.style.transform.match(/translateX\(([^)]+)px\) scale\(([^)]+)\)/)!; + const factor = Number(scale) * Number(k); + for (const peg of pegs) { + expect(parseFloat(peg.style.width) * factor).toBeGreaterThanOrEqual(44 - 1e-9); + expect(parseFloat(peg.style.height) * factor).toBeGreaterThanOrEqual(44 - 1e-9); + } + const x = parseFloat(scroll.style.transform.match(/translate\(([^,]+)px/)![1]); + const left = Number(tx) + (890 + Number(dx) - 8 * Number(k) + x * Number(k)) * Number(scale); + expect(left).toBeGreaterThanOrEqual(10 - 1e-9); + expect(left + parseFloat(scroll.style.width) * factor).toBeLessThanOrEqual(width - 10 + 1e-9); + } +}); + +test("options show current volume without changing the control names", () => { + const opening = new Opening({ audio: new HarborAudio(), hasSave: false, onStart: async () => {}, onDone() {} }); + opening.state = { ...opening.state, scroll: "options" }; + const html = renderToStaticMarkup(opening.render()); + expect(html).toContain("Music 4 of 5"); + expect(html).toContain("Effects 5 of 5"); + for (const bus of ["Music", "Effects"]) for (let n = 1; n <= 5; n++) expect(html).toContain(`aria-label="${bus} level ${n}"`); + expect(html).toContain('role="dialog" aria-label="Options"'); + expect(html).toContain('aria-pressed="false"'); + expect(html).toContain(">Sound off"); + expect(html).toContain(">Back"); +}); diff --git a/web/src/opening/Opening.tsx b/web/src/opening/Opening.tsx index 0d05a7a..0d6b896 100644 --- a/web/src/opening/Opening.tsx +++ b/web/src/opening/Opening.tsx @@ -1,4 +1,4 @@ -// Title screen for /outing/, ported from the Claude Design file FamiliarOpening.dc.html. +// Title screen for /outing/. // The render loop writes styles directly; React only renders text and structure. import { Component, type CSSProperties, type SyntheticEvent } from "react"; import "@fontsource-variable/fraunces"; @@ -8,6 +8,8 @@ import { MOCHI_POSES, type MochiPoseName } from "../motion/mochi"; import "./opening.css"; const ART = "/assets/expedition/runtime/"; +const TITLE = "/assets/title/"; +const TITLE_ART = ["title-plank-1", "title-plank-2", "title-plank-3", "title-plank-4", "title-post", "title-bell", "title-tag", "title-paper"]; const cache = new Map(); /** Inline style string -> React style object, so the markup stays close to the design file. */ export function sx(text: string): CSSProperties { @@ -23,7 +25,8 @@ 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 } +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; } } interface Props { audio: HarborAudio; hasSave: boolean; @@ -52,9 +55,7 @@ const E: Record number> = { in: p => p * p * p, back: p => 1 + 2.70158 * Math.pow(p - 1, 3) + 1.70158 * Math.pow(p - 1, 2), }; const COLS = ["Left", "Center", "Right"]; -const PLANK = "position:relative;height:56px;width:236px;box-sizing:border-box;padding:0 12px 0 30px;border:1px solid #d6b374;border-radius:9px;background:#5d432c;color:#fff0ce;box-shadow:inset 0 1px 0 #b48d55,0 4px 14px #382b2040;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 NAIL = "position:absolute;left:11px;top:50%;width:7px;height:7px;margin-top:-4px;border-radius:50%;background:#e4be78;box-shadow:inset -1px -1px 0 #9a733a"; -const TAG = "padding:4px 7px;background:#fff6dd;border:1px solid #a77d45;border-radius:4px;font:700 11px/1 'Figtree Variable',sans-serif"; +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 col = (x: number) => 126.67 + x * 253.33, row = (y: number) => 800 - y * 140; @@ -69,6 +70,7 @@ const GEO = { export default class Opening extends Component { state: State = { prompt: "Press any key", 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 = {}; @@ -172,6 +174,7 @@ 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"); }; 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) => { @@ -192,8 +195,8 @@ export default class Opening extends Component { // ---- beats async boot() { const k = ++this.seq, s = this.s; this.mode = "boot"; Object.assign(s, { veil: 1, tide: 0, tideA: 1, boot: 1, chapA: 0, promptA: 0, zoomAdd: .07 }); this.bootShown = 0; this.bootReal = 0; this.bootT0 = this.t; - const urls = ["harbor", "mochi-poses", "bram", "moth", "tide-court", "tidekeeper", "stone-island", "wooden-bridge", "shell", "lens", "wave"]; let n = 0; const total = urls.length + 1, bump = () => { n++; this.bootReal = n / total; }; - urls.forEach(u => { const i = new Image(); i.onload = i.onerror = bump; i.src = ART + u + ".webp"; }); + const urls = [...["harbor", "mochi-poses", "bram", "moth", "tide-court", "tidekeeper", "stone-island", "wooden-bridge", "shell", "lens", "wave"].map(name => ART + name + ".webp"), ...TITLE_ART.map(name => TITLE + name + ".webp")]; let n = 0; const total = urls.length + 1, bump = () => { n++; this.bootReal = n / total; }; + urls.forEach(url => { const i = new Image(); i.onload = i.onerror = bump; i.src = url; }); (document.fonts ? Promise.all([document.fonts.load("620 80px 'Fraunces Variable'"), document.fonts.load("700 16px 'Figtree Variable'")]) : Promise.resolve()).then(bump, bump); await new Promise(res => { this.bootDone = res; }); if (k !== this.seq) return; void this.tw(s, "veil", 0, 700, "lin", 420); await this.tw(s, "tide", 1.06, 900, "in"); if (k !== this.seq) return; s.boot = 0; @@ -219,7 +222,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) { + async travel(id: Plank, surface?: "tide") { 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; @@ -229,7 +232,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 }); + await this.props.onStart({ sound: this.soundOn, music: this.state.music / 5, effects: this.state.effects / 5, ...(surface ? { surface } : {}) }); await this.wait(140); await this.tw(s, "tideA", 0, 520, "out"); if (k === this.seq && !this.dead) this.props.onDone(); } @@ -347,7 +350,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! * (live ? .62 + .38 * (.5 + .5 * Math.sin(t / 1100)) : 1)); } + 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 = $("cap"); if (e) { e.style.opacity = String(s.capA); @@ -376,7 +379,12 @@ export default class Opening extends Component { e = $("post"); if (e) { e.style.transformOrigin = "890px 858px"; e.style.transform = "translateX(" + dx + "px) scale(" + k + ")"; } const bt = t - this.bellAt; let ang = this.bellFix ?? 0; if (live) { if (bt < 5000) ang = this.bellAmp * 16 * Math.exp(-bt / 900) * Math.sin(bt / 130); if (this.mode === "title" && !this.soundOn && bt > 5000) { const n = t % 7000; if (n < 1400) ang += 3 * Math.exp(-n / 420) * Math.sin(n / 110); } } - e = $("bell"); if (e) e.style.transform = "rotate(" + ang + "deg)"; + e = $("bell"); if (e) { + const hit = fz ? 60 : Math.max(60, 44 / (S * k)); + e.style.width = hit + "px"; e.style.left = (826 - hit / 2) + "px"; e.style.height = Math.max(144, hit) + "px"; + e.style.transform = "rotate(" + ang + "deg)"; + } + e = $("soundtag"); if (e) e.style.fontSize = (fz ? 14 : Math.max(14, 12 / (S * k))) + "px"; [0, 180].forEach((dl, i) => { const el = $("ring" + (i + 1)); if (!el) return; const p = this.bellFix != null ? .35 + i * .25 : (bt - dl) / 1100; if (p > 0 && p < 1 && (this.bellFix != null || this.bellAmp >= 1)) { el.style.opacity = String((1 - p) * .9); el.style.transform = "scale(" + (1 + p * 2.2) + ")"; } else el.style.opacity = "0"; }); const ids = this.items(), inMenu = this.mode === "menu"; ids.forEach((id, i) => { @@ -384,20 +392,24 @@ export default class Opening extends Component { 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) + ")"; 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.background = seld ? "#6a4d31" : "#5d432c"; el.style.borderColor = seld ? "#ffe1a1" : "#d6b374"; el.style.color = seld ? "#fff5d8" : "#fff0ce"; el.style.zIndex = seld ? "2" : "1"; + 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"; }); e = $("scroll"); if (e) { - e.style.width = port ? Math.max(220, PW + 16) + "px" : BW + "px"; - // Keep the scroll's buttons at least 44px on screen, and lift it above the bottom edge. - if (s.scrollP! > 0 && !fz) { const hh = Math.max(44, 44 / (S * k)), ww = Math.min(hh, (e.offsetWidth - 38) / 5); for (const bn of e.querySelectorAll("button")) { if (bn.dataset.bus) { bn.style.width = ww + "px"; bn.style.height = hh + "px"; } else bn.style.minHeight = hh + "px"; } } + const factor = S * k, hit = fz ? 44 : Math.max(44, 44 / factor); + e.style.width = Math.ceil(Math.max(port ? Math.max(220, PW + 16) : BW, hit * 5 + 60)) + "px"; + e.style.fontSize = (fz ? 14 : Math.max(14, 14 / factor)) + "px"; + e.style.maxHeight = (H - 20) / factor + "px"; + // Size controls in screen pixels, then keep the wider paper inside the painting. + if (s.scrollP! > 0 && !fz) for (const bn of e.querySelectorAll("button")) { if (bn.dataset.bus) { bn.style.width = hit + "px"; bn.style.height = hit + "px"; } else { const primary = bn.className === "fo-primary", size = primary ? 18 : 17, height = primary ? 56 : 48; bn.style.minHeight = Math.max(height, height / factor) + "px"; bn.style.fontSize = Math.max(size, size / factor) + "px"; } } + const left = tx + gx(882) * S, width = e.offsetWidth * factor, x = (Math.max(10, Math.min(left + (port ? -16 : 0) * factor, W - 10 - width)) - left) / factor; const ob = Math.max(0, gy(520) + e.offsetHeight * k - ((H - ty) / S - 10)) / k; - e.style.transform = "translate(" + (port ? -16 : 0) + "px," + (-ob) + "px) scaleY(" + Math.max(.001, s.scrollP!) + ")"; e.style.opacity = String(Math.min(1, s.scrollP! * 2)); e.style.pointerEvents = s.scrollP! > .9 ? "auto" : "none"; } + e.style.transform = "translate(" + x + "px," + (-ob) + "px) scaleY(" + Math.max(.001, s.scrollP!) + ")"; e.style.opacity = String(Math.min(1, s.scrollP! * 2)); e.style.pointerEvents = s.scrollP! > .9 ? "auto" : "none"; } // wind-moth let tg = { x: gx(852), y: gy(444) }; - if (inMenu && this.sel && !this.state.scroll) tg = { x: gx(900 + PW - (tight ? 32 : 0)), y: gy(520 + ids.indexOf(this.sel) * 63 + 40) }; - else if (this.mothTo === "board" && this.mode !== "menu") tg = { x: gx(900 + BW - (BW < 250 ? 34 : 24)), y: gy(602) }; + if (inMenu && this.sel && !this.state.scroll) tg = { x: gx(882 + PW - (tight ? 32 : 0)), y: gy(520 + ids.indexOf(this.sel) * 63 + 40) }; + else if (this.mothTo === "board" && this.mode !== "menu") tg = { x: gx(882 + BW - (BW < 250 ? 34 : 24)), y: gy(602) }; tg.x = Math.max(-tx / S + 38, Math.min((W - tx) / S - 38, tg.x)); tg.y = Math.max(-ty / S + 48, tg.y); const mo = this.moth, ddx = tg.x - mo.x, ddy = tg.y - mo.y; if (live) { const kk = 1 - Math.exp(-this.dt * .0055); mo.x += ddx * kk; mo.y += ddy * kk; } else { mo.x = tg.x; mo.y = tg.y; } @@ -431,7 +443,7 @@ export default class Opening extends Component { render() { const st = this.state, ids = this.items(); const pegs = (bus: "music" | "effects") => [1, 2, 3, 4, 5].map(n => ( - )); const scrollTitle = st.scroll ? LABEL[st.scroll] : ""; @@ -451,46 +463,42 @@ export default class Opening extends Component {
-
-
-
-
-
- -
- {ids.map(id => ( - ))}
-
-
{scrollTitle}
+
+
{scrollTitle}
-
+
{st.scroll === "tide" && <> -

One shared court a day, scored in Shells.

- Coming soon +

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

+ {this.hasLitHarbor ? :

The asks begin once the beacon is lit.

} } {st.scroll === "options" && <> - -
Music
{pegs("music")}
-
Effects
{pegs("effects")}
+ +
{`Music ${st.music} of 5`}
{pegs("music")}
+
{`Effects ${st.effects} of 5`}
{pegs("effects")}
} {st.scroll === "credits" && <>
Type
Fraunces · Figtree
Made with
Phaser · React · Hono · near-api-js
} - +
@@ -530,7 +538,7 @@ export default class Opening extends Component {

familiar.

-
First Light
+
@@ -538,7 +546,7 @@ export default class Opening extends Component {
{st.cap1}
{st.cap2}
-
{st.prompt}
+
{st.prompt}
); diff --git a/web/src/opening/opening.css b/web/src/opening/opening.css index 72c10fc..35e8fa0 100644 --- a/web/src/opening/opening.css +++ b/web/src/opening/opening.css @@ -1,7 +1,23 @@ html:has(.familiar-opening:not(.framed)),body:has(.familiar-opening:not(.framed)){margin:0;width:100%;height:100%;overflow:hidden;background:#304e40} -.familiar-opening{position:fixed;inset:0;height:100dvh;z-index:60} +.familiar-opening{--fo-card:#fbf3e2;--fo-ink:#263e32;--fo-secondary-ink:#4f5d52;--fo-hairline:#e6d6b4;position:fixed;inset:0;height:100dvh;z-index:60} .familiar-opening.framed{position:absolute;height:auto;z-index:auto} .familiar-opening button{font-family:inherit} .familiar-opening button:focus-visible{outline:3px solid #fff5ce;outline-offset:3px} +.familiar-opening [data-plank]:focus-visible{outline:none;filter:drop-shadow(0 0 2px #263e32) drop-shadow(0 0 3px #fff5ce) drop-shadow(0 0 7px #fff5ce)!important} .familiar-opening .fo-bell:focus-visible{border-radius:8px} -.familiar-opening .fo-row:hover{background:#fff1ca} +.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 .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} +.familiar-opening .fo-secondary:hover{background:#fff3dc} +.familiar-opening .fo-primary svg{width:1.12em;height:1.12em;flex-shrink:0} +.familiar-opening .fo-secondary svg{width:1.06em;height:1.06em;flex-shrink:0} +.familiar-opening .fo-peg{border-radius:999px} +.familiar-opening .fo-peg:hover{box-shadow:inset 0 0 0 1.5px #d6c29b} +.familiar-opening [data-el="scroll"]{scrollbar-width:thin;scrollbar-color:#4f5d52 #fbf3e2} +.familiar-opening .fo-chapter-name,.familiar-opening .fo-prompt{background:#263e32;border-radius:999px;box-shadow:0 3px 12px rgba(38,62,50,.22)} +.familiar-opening .fo-chapter-name{padding:.35em .7em} +.familiar-opening .fo-prompt{padding:12px 20px} +.familiar-opening ::selection{background:#e6d6b4;color:#263e32} +@media(pointer:coarse){.familiar-opening .fo-primary{min-height:56px}} diff --git a/web/src/run/TideRunGame.test.tsx b/web/src/run/TideRunGame.test.tsx new file mode 100644 index 0000000..7f1a2b5 --- /dev/null +++ b/web/src/run/TideRunGame.test.tsx @@ -0,0 +1,57 @@ +import { expect, mock, test } from "bun:test"; +import { renderToStaticMarkup } from "react-dom/server"; +import TideRunGame from "./TideRunGame"; +import { applyMove, startTide, type TideState } from "./engine"; +import { CHAPTERS, itemName, storyStart } from "./story"; + +function render(initial: TideState, blocked = false) { + const document = Object.getOwnPropertyDescriptor(globalThis, "document"), onFinish = mock(() => true); + Object.defineProperty(globalThis, "document", { configurable: true, value: { hidden: false } }); + try { + const html = renderToStaticMarkup( true} onFinish={onFinish} onLeave={() => {}} onToggleSound={() => {}}/>); + return { html, onFinish }; + } finally { + if (document) Object.defineProperty(globalThis, "document", document); + else Reflect.deleteProperty(globalThis, "document"); + } +} + +test("a finished daily tide never renders an end card before filing", () => { + const finished = applyMove(startTide({ seed: 20771 }), "home")!.after; + for (const outcome of ["home", "turned", "rescued"] as const) for (const blocked of [false, true]) { + const { html, onFinish } = render({ ...finished, outcome }, blocked); + expect(html).toContain(`data-outcome="${outcome}"`); + expect(html).not.toContain('aria-label="The tide is over"'); + expect(html).not.toContain('aria-label="Guide Mochi"'); + expect(html).not.toContain('data-testid="tide-again"'); + expect(html).not.toContain('class="tide-stamps"'); + expect(onFinish).not.toHaveBeenCalled(); + } +}); + +test("all three story chapters keep their end card and retry button", () => { + for (const prize of ["lens", "vane", "moth"] as const) { + const finished = applyMove(startTide(storyStart(prize)), "home")!.after; + const { html, onFinish } = render(finished); + 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('data-testid="tide-finish"'); + expect(html).toContain("Back to the harbor"); + expect(html).toContain('data-testid="tide-again"'); + expect(html).toContain("Try this tide again"); + expect(onFinish).not.toHaveBeenCalled(); + } +}); + +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('data-testid="tide-finish"'); + expect(html).not.toContain('data-testid="tide-again"'); + } +}); diff --git a/web/src/run/TideRunGame.tsx b/web/src/run/TideRunGame.tsx new file mode 100644 index 0000000..ab5bdff --- /dev/null +++ b/web/src/run/TideRunGame.tsx @@ -0,0 +1,229 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import TideWorld from "./TideWorld"; +import { HEARTS, PACK_SLOTS, SLOTS, applyMove, countdown, legalMoves, stepDestination, tideShape, type Move, type Position, 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"; +import type { HarborAudio } from "../expedition/audio"; +import type { CourtEvent } from "../expedition/types"; +import "../expedition/passage-game.css"; +import "../tide/tide.css"; +import "./tide-run.css"; + +interface Props { + initial: TideState; reduced: boolean; sound: boolean; audio: HarborAudio | null; blocked: boolean; + /** Persists every accepted move. False means the browser could not save it. */ + onSave: (next: TideState) => boolean; + /** False means filing failed. `again` asks for the same tide once more. */ + onFinish: (state: TideState, again: boolean) => boolean; + /** Back to the harbor with the tide still in progress and saved. */ + onLeave: () => void; + onToggleSound: () => void; +} + +const STEPS = ["north", "west", "east", "south"] as const; +const ARROWS = { north: "m5 15 7-7 7 7", west: "m15 5-7 7 7 7", east: "m9 5 7 7-7 7", south: "m5 9 7 7 7-7" }; +const WAVE = "M3 8c3-4 5 4 9 0s6 4 9 0M3 15c3-4 5 4 9 0s6 4 9 0"; +const HEART = "M12 20 4 12C-2 6 7 0 12 6c5-6 14 0 8 6l-8 8Z"; +const BAG = "M6 8h12l2 12H4L6 8Zm3 0V5a3 3 0 0 1 6 0v3"; +const HOME = "m3 11 9-8 9 8M6 9v12h12V9m-9 12v-7h6v7"; +const icon = (path: string) => ; +const LANES = ["left", "center", "right"]; +const ROWS = ["quay", "near landing", "channel", "far landing", "far shore"]; +const KEYS: Partial> = { arrowup: "north", w: "north", arrowdown: "south", s: "south", arrowleft: "west", a: "west", arrowright: "east", d: "east", " ": "wait", r: "home" }; +const same = (a: Position, b: Position) => a.x === b.x && a.y === b.y; +const where = (position: Position) => position.y === 4 && position.x !== 1 ? `the ${LANES[position.x]} shell` : `the ${LANES[position.x]} ${ROWS[position.y]}`; +const landing = (position: Position) => `${position.y === 4 && position.x !== 1 ? "in" : "on"} ${where(position)}`; + +/** A tap on a platform one step away walks there. The channel is never stood on: a tap on the bridge crosses it. */ +function moveToward(state: TideState, target: Position): Move | null { + const step = STEPS.find(move => { const to = stepDestination(state, move); return !!to && same(to, target); }); + if (step) return step; + if (target.y !== 2 || target.x !== state.bridge || state.position.x !== target.x) return null; + return state.position.y === 1 ? "north" : state.position.y === 3 ? "south" : null; +} + +function forecast(state: TideState): string { + const left = countdown(state), { lanes, drops } = state.next; + const leaves = drops.length ? ` It leaves ${drops.map(drop => `${aPrize(drop.kind)} ${landing(drop)}`).join(" and ")}.` : " It leaves nothing."; + return `${laneNames(lanes)} wave in ${left} ${left === 1 ? "move" : "moves"}.${leaves}`; +} + +/** The harbor's sound recipes are keyed by court events; a tide event borrows the closest one. */ +function sound(event: TideEvent): CourtEvent | null { + switch (event.kind) { + case "move": case "bridge": return event; + case "wave": return { kind: "wave", source: event.lanes[0]!, exit: event.lanes[0]! }; + case "open": return { kind: "open", column: event.lane }; + case "splash": return { kind: "hit", from: event.from, to: event.to, resolve: event.hearts }; + case "pickup": return { kind: "pickup", item: event.item === "vane" || event.item === "moth" ? event.item : "lens", from: event.at, rope: false }; + case "bank": return { kind: "return", cargo: [] }; + case "end": return event.reason === "rescued" ? { kind: "rescue", reason: "resolve" } : null; + default: return null; + } +} + +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 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 dialog = useRef(null), guideButton = useRef(null); + const guess = useMemo(() => initial.story ? null : bramsGuess(initial.seed), [initial.seed, initial.story]); + const busy = !!result, paused = away || blocked || guide || !!fault; + // The board catches up before the numbers do: the status shows the tide as drawn. + const seen = result ? result.before : state, over = state.outcome !== "active" && !busy; + const { waves, roughFrom } = tideShape(initial), legal = legalMoves(state); + const used = seen.pack.reduce((sum, item) => sum + SLOTS[item], 0); + const snapshot = useMemo(() => ({ tide: state, reducedMotion: reduced }), [state, reduced]); + + useEffect(() => { + const hide = () => setAway(true), show = () => setAway(document.hidden); + document.addEventListener("visibilitychange", show); window.addEventListener("blur", hide); window.addEventListener("focus", show); + return () => { document.removeEventListener("visibilitychange", show); window.removeEventListener("blur", hide); window.removeEventListener("focus", show); }; + }, []); + useEffect(() => { + if (!guide) { guideButton.current?.focus({ preventScroll: true }); return; } + const element = dialog.current; + element?.showModal(); + return () => element?.close(); + }, [guide]); + + function take(move: Move) { + if (!ready || paused || pending.current || current.current.outcome !== "active" || document.hidden) return; + const next = applyMove(current.current, move); + if (!next) return; + if (!onSave(next.after)) { setNotice("This move could not be saved. Try it again when this browser can save."); return; } + current.current = next.after; pending.current = next; serial.current++; + setResult(next); setState(next.after); + } + function beat(event: TideEvent) { + const cue = sound(event); + if (cue && pending.current && soundOn && !away && !document.hidden) audio?.play(cue); + } + function settle(id: number) { + const accepted = pending.current; + if (id !== serial.current || !accepted) return; + // The last thing that happened stays up until something else does. + const line = consequence(accepted); + if (line) setNotice(line); + 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; + } + const saved = onFinish(current.current, again); + if (!current.current.story && saved) filed.current = true; + setFinishError(!saved); + } + function leave() { + if (blocked) return; + if (current.current.outcome !== "active") finish(false); else onLeave(); + } + useEffect(() => { + if (!state.story && 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 || event.shiftKey || guide || + (event.target instanceof Element && event.target.closest("input,textarea,select,[contenteditable=true],dialog"))) return; + const key = event.key.toLowerCase(); + if (key === " " && event.target instanceof Element && event.target.closest("button,a")) return; + const move = KEYS[key]; + if (!move && key !== "i") return; + event.preventDefault(); + if (move) take(move); else setGuide(true); + } + window.addEventListener("keydown", keys); return () => window.removeEventListener("keydown", keys); + }); + + const prizeHome = !!state.story && state.banked.includes(state.story); + 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}
; + + return
+ setReady(true)} onFault={message => { setFault(message); setReady(false); pending.current = null; setResult(null); }} + onBeat={beat} onSettled={settle} onTarget={target} /> +
familiar.Played and saved on this device
+

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

+
+ + +
+
+ +
Wave {Math.min(seen.wave + 1, waves)}/{waves} + {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"}`}. +
+ {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}.

} + {feedback} + {finishError &&

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

} +
+
+ + {state.story && !prizeHome && } +
+
} + {!over &&
+ {guess !== null &&
    {STAMPS.map(stamp => { + const status = stamp.key === "home" ? (seen.score > 0 ? "kept" : undefined) + : stamp.key === "guess" ? (seen.score >= guess ? "kept" : undefined) + : seen.splashes > 0 ? "slipped" : seen.outcome !== "active" ? "kept" : undefined; + const label = stamp.key === "home" ? "Bring one home" : stamp.key === "dry" ? "Dry paws" : `${seen.score === guess ? "Matched" : "Beat"} ${guess}`; + return
  1. + + + {stamp.ask(guess)} {status === "kept" ? "Kept." : status === "slipped" ? "Slipped." : "Still open."} +
  2. ; + })}
} +
+ {chapter &&

{objective}

} +

{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} +
+
+ {STEPS.map(move => )} + +
+ + {legal.includes("home") && state.moves.length > 0 && } +
+
} + {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.
  • +
+

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

+
} +
; +} diff --git a/web/src/run/TideWorld.tsx b/web/src/run/TideWorld.tsx new file mode 100644 index 0000000..d4274cd --- /dev/null +++ b/web/src/run/TideWorld.tsx @@ -0,0 +1,46 @@ +import { useEffect, useRef, useState } from "react"; +import { countdown, type Position, type TideEvent, type TideTransition } from "./engine"; +import { itemName, laneNames } from "./story"; +import type { TideScene, TideSnapshot } from "./scene"; + +export interface TideWorldProps { + snapshot: TideSnapshot; + transition: TideTransition | null; + presentationId: number; + paused: boolean; + onTarget: (position: Position) => void; + onSettled: (id: number) => void; + onBeat: (event: TideEvent) => void; + onFault: (message: string) => void; + onReady: () => void; +} + +export default function TideWorld(props: TideWorldProps) { + const mount = useRef(null), scene = useRef(null), current = useRef(props); + const [ready, setReady] = useState(false); + current.current = props; + useEffect(() => { + let alive = true, game: import("phaser").Game | undefined; + const lost = (event: Event) => { event.preventDefault(); if (alive) current.current.onFault("The drawing surface stopped. Your accepted moves are saved. Reload the scene to continue."); }; + void Promise.all([import("phaser"), import("./scene")]).then(([{ default: Phaser }, { TideScene }]) => { + if (!alive || !mount.current) return; + const next = new TideScene(current.current.snapshot, { + target: position => current.current.onTarget(position), + ready: () => { if (!alive) return; setReady(true); current.current.onReady(); next.setGated(current.current.paused); }, + fault: message => { if (alive) current.current.onFault(message); }, + beat: event => { if (alive) current.current.onBeat(event); }, + settled: id => { if (alive) current.current.onSettled(id); }, + }); + scene.current = next; + game = new Phaser.Game({ type: Phaser.AUTO, parent: mount.current, width: mount.current.clientWidth, height: mount.current.clientHeight, transparent: true, antialias: true, banner: false, audio: { noAudio: true }, loader: { imageLoadType: "HTMLImageElement" }, scene: next, scale: { mode: Phaser.Scale.RESIZE, autoCenter: Phaser.Scale.CENTER_BOTH }, input: { keyboard: false } }); + game.canvas.setAttribute("aria-hidden", "true"); game.canvas.addEventListener("webglcontextlost", lost); + }).catch(() => { if (alive) current.current.onFault("The playfield could not open. Your saved harbor is safe. Retry the scene."); }); + return () => { alive = false; scene.current = null; if (game) { game.canvas.removeEventListener("webglcontextlost", lost); game.destroy(true); } }; + }, []); + useEffect(() => { if (ready) scene.current?.setSnapshot(props.snapshot, props.transition, props.presentationId); }, [ready, props.snapshot, props.transition, props.presentationId]); + useEffect(() => { scene.current?.setGated(props.paused); }, [props.paused]); + const { tide } = props.snapshot; + const coming = tide.outcome === "active" ? ` The next wave takes ${laneNames(tide.next.lanes)} in ${countdown(tide)}${tide.next.drops.length ? ` and leaves ${tide.next.drops.map(drop => itemName(drop.kind)).join(" and ")}` : ""}.` : ""; + return
; +} diff --git a/web/src/run/bot.ts b/web/src/run/bot.ts new file mode 100644 index 0000000..8ae3cff --- /dev/null +++ b/web/src/run/bot.ts @@ -0,0 +1,46 @@ +/** Bram's guess: what a cautious player banks on a tide. It never ends a wave beat in the water and takes no risks. */ +import { DOCK, PACK_SLOTS, SLOTS, VALUE, applyMove, countdown, legalMoves, startTide, stepDestination, tideShape, type Item, type Move, type Position, type TideState } from "./engine"; + +/** Sideways steps to the nearest lane the next wave spares; the quay is always safe. */ +const toSafety = (state: TideState, position: Position) => position.y === 0 ? 0 : + Math.min(...[0, 1, 2].filter(lane => !state.next.lanes.includes(lane as 0 | 1 | 2)).map(lane => Math.abs(lane - position.x))); + +function steps(state: TideState, from: Position, to: Position): number { + const seen = new Set([`${from.x},${from.y}`]); + let frontier = [from]; + for (let distance = 0; frontier.length; distance++) { + const next: Position[] = []; + for (const position of frontier) { + if (position.x === to.x && position.y === to.y) return distance; + for (const move of ["north", "south", "west", "east"] as const) { + const step = stepDestination({ position, bridge: state.bridge }, move); + if (step && !seen.has(`${step.x},${step.y}`)) { seen.add(`${step.x},${step.y}`); next.push(step); } + } + } + frontier = next; + } + return 99; +} + +/** `worth` lets a caller chase something else (the fixture's pearl diver); Bram's guess uses the real values. */ +export function cautiousMove(state: TideState, worth: Readonly> = VALUE): Move { + const left = countdown(state) - 1; + const all = legalMoves(state).filter(move => move !== "home").map(move => ({ move, position: stepDestination(state, move) ?? state.position })); + const safe = all.filter(option => toSafety(state, option.position) <= left), options = safe.length ? safe : all; + const used = state.pack.reduce((sum, item) => sum + SLOTS[item], 0), wavesLeft = tideShape(state).waves - state.wave; + const goals = used >= PACK_SLOTS || (used > 0 && wavesLeft <= 2) ? [{ ...DOCK, worth: 99 }] : + [...state.items.map(item => ({ x: item.x, y: item.y, worth: worth[item.kind] })), ...(used > 0 ? [{ ...DOCK, worth: 1 }] : [])]; + let best = options[0]!, score = -1; + for (const option of options) for (const goal of goals) { + const value = goal.worth / (1 + steps(state, option.position, goal)); + if (value > score) { score = value; best = option; } + } + return best.move; +} + +export function cautiousTide(seed: number): TideState { + let state = startTide({ seed }); + while (state.outcome === "active") state = applyMove(state, cautiousMove(state))!.after; + return state; +} +export const bramsGuess = (seed: number) => cautiousTide(seed).score; diff --git a/web/src/run/engine.test.ts b/web/src/run/engine.test.ts new file mode 100644 index 0000000..af95309 --- /dev/null +++ b/web/src/run/engine.test.ts @@ -0,0 +1,211 @@ +import { describe, expect, test } from "bun:test"; +import { DOCK, HEARTS, VALUE, applyMove, countdown, draw, haul, legalMoves, replayTide, seedState, startTide, tideShape, type Move, type TideEvent, type TideState } from "./engine"; +import { bramsGuess, cautiousTide } from "./bot"; + +const play = (state: TideState, ...moves: Move[]) => moves.reduce((s, move) => { + const turn = applyMove(s, move); + if (!turn) throw new Error(`illegal ${move}`); + return turn.after; +}, state); +const events = (state: TideState, move: Move): readonly TideEvent[] => applyMove(state, move)!.events; +/** A hand-set position inside a real tide, one beat before the wave in `lanes` lands. */ +const poised = (start: Parameters[0], patch: Partial): TideState => ({ ...startTide(start), beat: 2, ...patch }); + +describe("the tide run", () => { + test("starts on the dock with the first wave already forecast", () => { + const state = startTide({ seed: 20771 }); + expect(state.position).toEqual(DOCK); + expect(countdown(state)).toBe(3); + expect(state.next.lanes.length).toBe(1); + expect(legalMoves(state)).toEqual(["north", "west", "east", "wait", "home"]); + }); + + test("the generator is pinned for the contract copy", () => { + expect(seedState(20771)).toBe(2868735576); + let rng = seedState(20771); + const draws: number[] = []; + for (let i = 0; i < 4; i++) { const [value, next] = draw(rng); draws.push(value); rng = next; } + expect(draws).toEqual(PINNED_DRAWS); + }); + + test("a wave lands after every third move, moves the bridge and leaves its prize", () => { + const start = startTide({ seed: 20771 }), { lanes, drops } = start.next; + const after = play(start, "wait", "wait", "wait"); + expect(after.wave).toBe(1); + expect(after.bridge).toBe(lanes[0]!); + expect(after.items).toEqual([...drops]); + expect(after.hearts).toBe(HEARTS); + expect(countdown(after)).toBe(3); + }); + + test("standing in the wave's lane costs a heart, the last prize and a platform", () => { + const state = poised({ seed: 3 }, { position: { x: 0, y: 4 }, pack: ["reed", "glass"], next: { lanes: [0], drops: [] } }); + const turn = applyMove(state, "wait")!; + expect(turn.after.hearts).toBe(2); + expect(turn.after.pack).toEqual(["reed"]); + expect(turn.after.position).toEqual({ x: 0, y: 3 }); + expect(turn.events.find(e => e.kind === "splash")).toMatchObject({ lost: "glass", hearts: 2 }); + const across = applyMove({ ...state, position: { x: 0, y: 3 } }, "wait")!.after; + expect(across.position).toEqual({ x: 0, y: 1 }); + }); + + test("the quay is never hit, and a wave washing Mochi onto the dock banks her pack", () => { + const quay = applyMove(poised({ seed: 3 }, { position: { x: 1, y: 0 }, next: { lanes: [1], drops: [] } }), "wait")!.after; + expect(quay.hearts).toBe(HEARTS); + const washed = applyMove(poised({ seed: 3 }, { position: { x: 1, y: 1 }, pack: ["glass", "reed"], next: { lanes: [1], drops: [] } }), "wait")!.after; + expect(washed.position).toEqual(DOCK); + expect(washed.banked).toEqual(["glass"]); + expect(washed.score).toBe(VALUE.glass); + }); + + test("a wave sweeps loose prizes in its lane and spares the others", () => { + const state = poised({ seed: 3 }, { items: [{ x: 0, y: 1, kind: "reed" }, { x: 2, y: 3, kind: "glass" }], next: { lanes: [0], drops: [] } }); + expect(applyMove(state, "wait")!.after.items).toEqual([{ x: 2, y: 3, kind: "glass" }]); + }); + + test("walking onto a prize takes it, a full pack leaves it, and the dock banks", () => { + const state: TideState = { ...startTide({ seed: 3 }), position: { x: 0, y: 0 }, items: [{ x: 1, y: 1, kind: "pearl" }] }; + const carrying = play(state, "east"); + expect(carrying.position).toEqual(DOCK); + const got = play({ ...state, position: { x: 0, y: 1 } }, "east"); + expect(got.pack).toEqual(["pearl"]); + expect(got.items).toEqual([]); + const banked = play(got, "south"); + expect(banked.pack).toEqual([]); + expect(banked.score).toBe(VALUE.pearl); + const full: TideState = { ...state, position: { x: 0, y: 1 }, pack: ["reed", "reed", "reed"] }; + expect(events(full, "east").map(e => e.kind)).toContain("full"); + expect(play(full, "east").items.length).toBe(1); + }); + + test("the channel is crossed in one move and only in the bridge's lane", () => { + const state: TideState = { ...startTide({ seed: 3 }), position: { x: 1, y: 1 }, bridge: 1 }; + expect(play(state, "north").position).toEqual({ x: 1, y: 3 }); + expect(legalMoves({ ...state, bridge: 0 })).not.toContain("north"); + expect(play({ ...state, position: { x: 1, y: 3 } }, "south").position).toEqual({ x: 1, y: 1 }); + }); + + test("calling it a day is only for the dock and spends no beat", () => { + const start = startTide({ seed: 3 }); + const home = applyMove(start, "home")!.after; + expect(home.outcome).toBe("home"); + expect(home.beat).toBe(0); + expect(legalMoves(play(start, "north"))).not.toContain("home"); + expect(legalMoves(home)).toEqual([]); + }); + + test("a tide ends after its last wave and loses whatever is still in the pack", () => { + let state = startTide({ seed: 3 }); + while (state.outcome === "active") state = play(state, "wait"); + expect(state.outcome).toBe("turned"); + expect(state.wave).toBe(12); + expect(state.beat).toBe(36); + const last: TideState = { ...startTide({ seed: 3 }), beat: 35, wave: 11, position: { x: 2, y: 1 }, pack: ["pearl"], next: { lanes: [0], drops: [] } }; + const end = applyMove(last, "wait")!; + expect(end.after.outcome).toBe("turned"); + expect(end.after.score).toBe(0); + expect(end.events.at(-1)).toEqual({ kind: "end", reason: "turned", lost: ["pearl"] }); + }); + + test("the third splash ends the tide and Bram fetches Mochi", () => { + const state = poised({ seed: 3 }, { hearts: 1, position: { x: 0, y: 3 }, pack: ["glass", "reed"], banked: ["pearl"], score: 6, next: { lanes: [0], drops: [] } }); + const end = applyMove(state, "wait")!.after; + expect(end.outcome).toBe("rescued"); + expect(end.pack).toEqual([]); + expect(end.score).toBe(6); + }); + + test("rough waves take two lanes and leave two prizes; the far-shore center never holds a pearl", () => { + for (let seed = 1; seed <= 300; seed++) { + let state = startTide({ seed }); + while (state.outcome === "active") { + const { lanes, drops } = state.next, rough = state.wave >= 6, last = state.wave === 11; + expect(lanes.length).toBe(rough ? 2 : 1); + expect(new Set(lanes).size).toBe(lanes.length); + expect(drops.length).toBe(last ? 0 : lanes.length); + for (const drop of drops) { + expect([1, 3, 4]).toContain(drop.y); + expect(drop.kind).toBe(drop.y === 1 ? "reed" : drop.y === 3 || drop.x === 1 ? "glass" : "pearl"); + } + state = play(state, "wait", "wait", "wait"); + } + } + }); + + test("the same start and moves always give the same tide", () => { + const tide = cautiousTide(20771); + expect(replayTide({ seed: 20771 }, tide.moves)).toEqual(tide); + expect(replayTide({ seed: 20771 }, [...tide.moves, "wait"])).toBeNull(); + expect(replayTide({ seed: 20771 }, ["fly"])).toBeNull(); + expect(replayTide({ seed: -1 }, [])).toBeNull(); + expect(replayTide({ seed: 1, story: "crown" }, [])).toBeNull(); + }); + + test("the cautious bot stays dry, banks what it scores, and gives Bram a guess", () => { + let total = 0; + for (let seed = 1; seed <= 200; seed++) { + const tide = cautiousTide(seed); + expect(tide.splashes).toBe(0); + expect(tide.outcome).toBe("turned"); + expect(tide.score).toBe(tide.banked.reduce((sum, item) => sum + VALUE[item], 0)); + const h = haul(tide); + expect(h.reed + h.glass + h.pearl).toBe(tide.banked.length); + total += tide.score; + } + expect(total / 200).toBeGreaterThan(10); + expect(bramsGuess(20771)).toBe(cautiousTide(20771).score); + }); +}); + +describe("story tides", () => { + test("the first tide is eight calm waves", () => { + expect(tideShape({ story: "lens" })).toEqual({ waves: 8, roughFrom: 8 }); + let state = startTide({ seed: 5, story: "lens" }); + while (state.outcome === "active") { expect(state.next.lanes.length).toBe(1); state = play(state, "wait"); } + expect(state.wave).toBe(8); + }); + + test("the second wave opens the story shell, and the prize is never swept", () => { + for (const [story, lane] of [["lens", 0], ["vane", 2], ["moth", 2]] as const) { + let state = play(startTide({ seed: 9, story }), "wait", "wait", "wait"); + expect(state.next).toEqual({ lanes: [lane], drops: [] }); + const turn = applyMove(play(state, "wait", "wait"), "wait")!; + expect(turn.events).toContainEqual({ kind: "open", lane, item: story }); + state = turn.after; + while (state.outcome === "active") state = play(state, "wait"); + expect(state.items).toContainEqual({ x: lane, y: 4, kind: story }); + } + }); + + test("a story tide walks the generator exactly as the daily tide on the same seed does", () => { + const daily = play(startTide({ seed: 9 }), ...Array(9).fill("wait")), story = play(startTide({ seed: 9, story: "vane" }), ...Array(9).fill("wait")); + expect(story.rng).toBe(daily.rng); + expect(story.next).toEqual(daily.next); + }); + + test("a splashed story prize goes back to its shell, and a banked one scores nothing", () => { + const state = poised({ seed: 5, story: "lens" }, { wave: 3, position: { x: 0, y: 4 }, pack: ["glass", "lens"], next: { lanes: [0], drops: [] } }); + const after = applyMove(state, "wait")!.after; + expect(after.pack).toEqual(["glass"]); + expect(after.items).toContainEqual({ x: 0, y: 4, kind: "lens" }); + const home = play({ ...startTide({ seed: 5, story: "lens" }), position: { x: 0, y: 0 }, pack: ["lens"] }, "east"); + expect(home.banked).toEqual(["lens"]); + expect(home.score).toBe(0); + }); + + test("the moth takes two slots, and the Tidekeeper turns one wave aside while Mochi carries it", () => { + const beside: TideState = { ...startTide({ seed: 5, story: "moth" }), position: { x: 1, y: 4 }, pack: ["reed", "reed"], items: [{ x: 2, y: 4, kind: "moth" }] }; + expect(events(beside, "east").map(e => e.kind)).toContain("full"); + expect(play({ ...beside, pack: ["reed"] }, "east").pack).toEqual(["reed", "moth"]); + const carrying = poised({ seed: 5, story: "moth" }, { wave: 3, position: { x: 2, y: 3 }, pack: ["moth"], next: { lanes: [2], drops: [] } }); + const first = applyMove(carrying, "wait")!; + expect(first.events).toContainEqual({ kind: "shield", lane: 2 }); + expect(first.after.hearts).toBe(HEARTS); + expect(first.after.pack).toEqual(["moth"]); + const second = applyMove({ ...first.after, beat: 2, next: { lanes: [2], drops: [] } }, "wait")!.after; + expect(second.hearts).toBe(HEARTS - 1); + expect(second.items).toContainEqual({ x: 2, y: 4, kind: "moth" }); + }); +}); + +const PINNED_DRAWS = [691653857, 2339662837, 1525025796, 254531113]; diff --git a/web/src/run/engine.ts b/web/src/run/engine.ts new file mode 100644 index 0000000..597bf7b --- /dev/null +++ b/web/src/run/engine.ts @@ -0,0 +1,223 @@ +/** + * The tide run: the Tidekeeper aims the waves, each wave leaves a prize, Mochi brings what she can home. + * Pure rules. State comes only from `startTide` and `applyMove`; a tide is rebuilt from its start and moves. + * All randomness is 32-bit integer arithmetic so the season contract can replay a tide exactly. + */ +export const RULES_VERSION = "tide_run_v1" as const; + +export type Lane = 0 | 1 | 2; +export type Prize = "reed" | "glass" | "pearl"; +export type StoryPrize = "lens" | "vane" | "moth"; +export type Item = Prize | StoryPrize; +export type Move = "north" | "south" | "west" | "east" | "wait" | "home"; +export interface Position { readonly x: Lane; readonly y: number } +export interface Placed extends Position { readonly kind: Item } +export interface Wave { readonly lanes: readonly Lane[]; readonly drops: readonly Placed[] } +/** A daily tide has only a seed. A story tide also names the prize waiting in its shell. */ +export interface TideStart { readonly seed: number; readonly story?: StoryPrize } + +export interface TideState extends TideStart { + readonly rulesVersion: typeof RULES_VERSION; + /** Generator state after the forecast in `next` was rolled. */ + readonly rng: number; + readonly position: Position; + readonly hearts: number; + readonly pack: readonly Item[]; + readonly banked: readonly Item[]; + readonly score: number; + readonly beat: number; + readonly wave: number; + readonly bridge: Lane; + readonly items: readonly Placed[]; + /** The wave that lands next. Shown to the player from the moment the previous one lands. */ + readonly next: Wave; + readonly splashes: number; + /** The Tidekeeper turns one wave aside while Mochi carries the moth. */ + readonly shielded: boolean; + readonly moves: readonly Move[]; + readonly outcome: "active" | "turned" | "rescued" | "home"; +} + +export type TideEvent = + | { readonly kind: "move"; readonly from: Position; readonly to: Position } + | { readonly kind: "pickup"; readonly item: Item; readonly at: Position } + | { readonly kind: "full"; readonly item: Item } + | { readonly kind: "bank"; readonly items: readonly Item[]; readonly gained: number } + | { readonly kind: "wave"; readonly lanes: readonly Lane[] } + | { readonly kind: "sweep"; readonly items: readonly Placed[] } + | { readonly kind: "shield"; readonly lane: Lane } + | { readonly kind: "splash"; readonly from: Position; readonly to: Position; readonly lost: Item | null; readonly hearts: number } + | { readonly kind: "bridge"; readonly from: Lane; readonly to: Lane } + | { readonly kind: "open"; readonly lane: Lane; readonly item: StoryPrize } + | { readonly kind: "leave"; readonly items: readonly Placed[] } + | { readonly kind: "forecast"; readonly wave: Wave } + | { readonly kind: "end"; readonly reason: "turned" | "rescued" | "home"; readonly lost: readonly Item[] }; + +export interface TideTransition { readonly before: TideState; readonly after: TideState; readonly events: readonly TideEvent[] } + +export const HEARTS = 3; +export const PACK_SLOTS = 3; +export const BEATS_PER_WAVE = 3; +export const MOVE_LIMIT = 36; +export const VALUE: Readonly> = { reed: 1, glass: 3, pearl: 6, lens: 0, vane: 0, moth: 0 }; +export const SLOTS: Readonly> = { reed: 1, glass: 1, pearl: 1, lens: 1, vane: 1, moth: 2 }; +export const DOCK: Position = { x: 1, y: 0 }; +/** Where each story prize waits. The second wave of its tide always takes this lane. */ +export const STORY_SHELL: Readonly> = { lens: { x: 0, y: 4 }, vane: { x: 2, y: 4 }, moth: { x: 2, y: 4 } }; +const STORY_WAVE = 1; +/** [row, weight out of 100]. Reeds wash up on the near landing, glass on the far landing, pearls in the far-shore shells. */ +const ROWS_CALM: readonly (readonly [number, number])[] = [[1, 50], [3, 35], [4, 15]]; +const ROWS_ROUGH: readonly (readonly [number, number])[] = [[1, 25], [3, 40], [4, 35]]; +const DIRECTIONS: Readonly, readonly [number, number]>> = { north: [0, 1], south: [0, -1], west: [-1, 0], east: [1, 0] }; +const MOVES = ["north", "south", "west", "east", "wait", "home"] as const; + +/** The first tide is eight calm waves; every other tide is twelve, two lanes at a time from the seventh. */ +export function tideShape(start: Pick): { readonly waves: number; readonly roughFrom: number } { + return start.story === "lens" ? { waves: 8, roughFrom: 8 } : { waves: 12, roughFrom: 6 }; +} +const isStory = (item: Item): item is StoryPrize => item === "lens" || item === "vane" || item === "moth"; +const at = (a: Position, b: Position) => a.x === b.x && a.y === b.y; +const slotsUsed = (pack: readonly Item[]) => pack.reduce((sum, item) => sum + SLOTS[item], 0); + +/** mulberry32 on unsigned 32-bit integers: returns the draw and the next generator state. */ +export function draw(rng: number): readonly [number, number] { + const state = (rng + 0x6D2B79F5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), state | 1) >>> 0; + t = ((t + Math.imul(t ^ (t >>> 7), t | 61)) ^ t) >>> 0; + return [(t ^ (t >>> 14)) >>> 0, state]; +} +export const seedState = (seed: number) => ((Math.imul(seed >>> 0, 0x9E3779B1) ^ 0x85EBCA6B) >>> 0); + +function rollWave(start: TideStart, rngIn: number, wave: number): readonly [Wave, number] { + const { waves, roughFrom } = tideShape(start), rough = wave >= roughFrom; + let rng = rngIn, value: number; + [value, rng] = draw(rng); + const lanes: Lane[] = [value % 3 as Lane]; + if (rough) { [value, rng] = draw(rng); lanes.push((lanes[0]! + 1 + value % 2) % 3 as Lane); } + const drops: Placed[] = []; + if (wave < waves - 1) for (const x of lanes) { + [value, rng] = draw(rng); + let n = value % 100, y = 4; + for (const [row, weight] of rough ? ROWS_ROUGH : ROWS_CALM) { if (n < weight) { y = row; break; } n -= weight; } + drops.push({ x, y, kind: y === 1 ? "reed" : y === 3 || x === 1 ? "glass" : "pearl" }); + } + // The draws above are always spent, so a story tide and a daily tide walk the generator alike. + if (start.story && wave === STORY_WAVE) return [{ lanes: [STORY_SHELL[start.story].x], drops: [] }, rng]; + return [{ lanes, drops }, rng]; +} + +export function startTide(input: TideStart): TideState { + if (!input || !Number.isSafeInteger(input.seed) || input.seed < 0 || input.seed > 0xFFFFFFFF || + !(input.story === undefined || isStory(input.story as Item))) throw new RangeError("Unsupported tide."); + const start: TideStart = input.story ? { seed: input.seed, story: input.story } : { seed: input.seed }; + const [next, rng] = rollWave(start, seedState(start.seed), 0); + return { + ...start, rulesVersion: RULES_VERSION, rng, position: DOCK, hearts: HEARTS, pack: [], banked: [], score: 0, beat: 0, wave: 0, + bridge: 1, items: [], next, splashes: 0, shielded: false, moves: [], outcome: "active", + }; +} + +/** Moves left before the next wave lands: 3, 2 or 1. */ +export const countdown = (state: Pick) => BEATS_PER_WAVE - state.beat % BEATS_PER_WAVE; + +/** Row 2 is the channel: crossing is one move, and only in the bridge's lane. */ +export function stepDestination(state: Pick, move: Move): Position | null { + if (move === "wait" || move === "home") return null; + const [dx, dy] = DIRECTIONS[move], { x, y } = state.position; + if (dx) { const nx = x + dx; return nx < 0 || nx > 2 ? null : { x: nx as Lane, y }; } + if ((dy === 1 && y === 1) || (dy === -1 && y === 3)) return x === state.bridge ? { x, y: y + 2 * dy } : null; + const ny = y + dy; + return ny < 0 || ny > 4 ? null : { x, y: ny }; +} + +export function legalMoves(state: TideState): Move[] { + if (state.outcome !== "active") return []; + return MOVES.filter(move => move === "wait" || (move === "home" ? at(state.position, DOCK) : !!stepDestination(state, move))); +} + +function arrive(state: TideState, events: TideEvent[]): TideState { + let next = state; + const here = next.items.find(item => at(item, next.position)); + if (here && slotsUsed(next.pack) + SLOTS[here.kind] <= PACK_SLOTS) { + next = { ...next, items: next.items.filter(item => item !== here), pack: [...next.pack, here.kind] }; + events.push({ kind: "pickup", item: here.kind, at: next.position }); + } else if (here) events.push({ kind: "full", item: here.kind }); + if (at(next.position, DOCK) && next.pack.length) { + const gained = next.pack.reduce((sum, item) => sum + VALUE[item], 0); + events.push({ kind: "bank", items: next.pack, gained }); + next = { ...next, banked: [...next.banked, ...next.pack], score: next.score + gained, pack: [] }; + } + return next; +} + +function land(state: TideState, events: TideEvent[]): TideState { + const { lanes, drops } = state.next; + let next = state; + events.push({ kind: "wave", lanes }); + const swept = next.items.filter(item => lanes.includes(item.x) && !isStory(item.kind)); + if (swept.length) { events.push({ kind: "sweep", items: swept }); next = { ...next, items: next.items.filter(item => !swept.includes(item)) }; } + // The quay is out of the water's reach. + if (lanes.includes(next.position.x) && next.position.y > 0) { + if (next.pack.includes("moth") && !next.shielded) { + next = { ...next, shielded: true }; + events.push({ kind: "shield", lane: next.position.x }); + } else { + const from = next.position, to: Position = { x: from.x, y: from.y === 4 ? 3 : from.y === 3 ? 1 : 0 }; + const lost = next.pack.at(-1) ?? null; + next = { ...next, position: to, hearts: next.hearts - 1, splashes: next.splashes + 1, pack: next.pack.slice(0, -1) }; + // A story prize is never lost for good: it goes back to its shell. + if (lost && isStory(lost)) next = { ...next, items: [...next.items, { ...STORY_SHELL[lost], kind: lost }] }; + events.push({ kind: "splash", from, to, lost, hearts: next.hearts }); + } + } + if (lanes[0]! !== next.bridge) { events.push({ kind: "bridge", from: next.bridge, to: lanes[0]! }); next = { ...next, bridge: lanes[0]! }; } + if (next.story && next.wave === STORY_WAVE) { + events.push({ kind: "open", lane: STORY_SHELL[next.story].x, item: next.story }); + next = { ...next, items: [...next.items, { ...STORY_SHELL[next.story], kind: next.story }] }; + } + // A shell holds one thing: nothing is left on a platform that already has a prize. + const left = drops.filter(drop => !next.items.some(item => at(item, drop))); + if (left.length) { events.push({ kind: "leave", items: left }); next = { ...next, items: [...next.items, ...left] }; } + next = { ...next, wave: next.wave + 1 }; + if (next.hearts <= 0) { events.push({ kind: "end", reason: "rescued", lost: next.pack }); return { ...next, pack: [], outcome: "rescued" }; } + next = arrive(next, events); + if (next.wave >= tideShape(next).waves) { events.push({ kind: "end", reason: "turned", lost: next.pack }); return { ...next, pack: [], outcome: "turned" }; } + const [wave, rng] = rollWave(next, next.rng, next.wave); + events.push({ kind: "forecast", wave }); + return { ...next, next: wave, rng }; +} + +export function applyMove(before: TideState, candidate: unknown): TideTransition | null { + const move = legalMoves(before).find(legal => legal === candidate); + if (!move) return null; + const events: TideEvent[] = []; + if (move === "home") { + events.push({ kind: "end", reason: "home", lost: [] }); + return { before, after: { ...before, moves: [...before.moves, move], outcome: "home" }, events }; + } + let after: TideState = { ...before, beat: before.beat + 1, moves: [...before.moves, move] }; + const to = stepDestination(before, move); + if (to) { events.push({ kind: "move", from: before.position, to }); after = { ...after, position: to }; } + after = arrive(after, events); + if (after.beat % BEATS_PER_WAVE === 0) after = land(after, events); + return { before, after, events }; +} + +/** Persist the start and the moves, then derive everything else on reload. Null when the moves are not a legal tide. */ +export function replayTide(start: unknown, moves: unknown): TideState | null { + if (!Array.isArray(moves) || moves.length > MOVE_LIMIT) return null; + let state: TideState; + try { state = startTide(start as TideStart); } catch { return null; } + for (const move of moves) { + const turn = applyMove(state, move); + if (!turn) return null; + state = turn.after; + } + return state; +} + +/** What a finished tide brought home, for Bram's shelf and the season contract. */ +export function haul(state: Pick): Readonly> { + const count = (kind: Prize) => state.banked.filter(item => item === kind).length; + return { reed: count("reed"), glass: count("glass"), pearl: count("pearl") }; +} diff --git a/web/src/run/save.ts b/web/src/run/save.ts new file mode 100644 index 0000000..0a8865a --- /dev/null +++ b/web/src/run/save.ts @@ -0,0 +1,81 @@ +/** A harbor's tide runs: the one in progress and each day's finished tide. Only starts and moves are stored; the rest is replayed. */ +import { haul, replayTide, type Move, type Prize, type StoryPrize, type TideState } from "./engine"; +import { bramsGuess } from "./bot"; + +export type { Prize } from "./engine"; + +export interface TideBook { + /** The tide in progress, rebuilt from its start and moves. */ + readonly active: TideState | null; + /** The first finished daily tide of each day, newest last. */ + readonly days: readonly TideState[]; +} +export const emptyBook = (): TideBook => ({ active: null, days: [] }); +export const DAYS_KEPT = 30; +/** The UTC day number, the same boundary the season contract uses. */ +export const tideDay = (now = Date.now()) => Math.floor(now / 86_400_000); + +type Trace = { seed: number; story?: StoryPrize; moves: readonly Move[] }; +const trace = (state: TideState): Trace => ({ seed: state.seed, ...(state.story ? { story: state.story } : {}), moves: state.moves }); +const bad = () => new Error("The saved tide could not be read. Its original record is still on this device."); + +export function readBook(storage: Pick, key: string): TideBook { + const raw = storage.getItem(key); + if (raw === null) return emptyBook(); + if (raw.length > 65_536) throw bad(); + let value; + try { value = JSON.parse(raw); } catch { throw bad(); } + if (value?.version !== 1 || !Array.isArray(value.days) || value.days.length > DAYS_KEPT) throw bad(); + const restore = (entry: Trace | null): TideState => { + const state = entry && replayTide({ seed: entry.seed, ...(entry.story ? { story: entry.story } : {}) }, entry.moves); + if (!state) throw bad(); + return state; + }; + const active = value.active === null ? null : restore(value.active); + const days = (value.days as Trace[]).map(restore); + if (days.some((day, i) => day.story || day.outcome === "active" || (i > 0 && day.seed <= days[i - 1]!.seed))) throw bad(); + return { active, days }; +} + +export function writeBook(storage: Pick, key: string, book: TideBook) { + const raw = JSON.stringify({ version: 1, active: book.active ? trace(book.active) : null, days: book.days.map(trace) }); + storage.setItem(key, raw); + if (storage.getItem(key) !== raw) throw new Error("The tide could not be saved."); +} + +/** Ends the tide in progress. A daily tide is kept only if it is that day's first: the first tide docked each day counts. */ +export function closeTide(book: TideBook, finished: TideState): TideBook { + if (finished.outcome === "active") throw new Error("This tide has not ended."); + if (finished.story || book.days.some(day => day.seed === finished.seed)) return { ...book, active: null }; + return { active: null, days: [...book.days, finished].sort((a, b) => a.seed - b.seed).slice(-DAYS_KEPT) }; +} + +export interface DayResult { + day: number; + score: number; + guess: number; + banked: readonly Prize[]; + /** Came home with something; matched Bram's guess; dry paws. */ + stamps: { home: boolean; guess: boolean; dry: boolean }; + splashes: number; +} +export function dayResult(tide: TideState): DayResult { + const guess = bramsGuess(tide.seed); + return { day: tide.seed, score: tide.score, guess, + banked: tide.banked.filter((item): item is Prize => item === "reed" || item === "glass" || item === "pearl"), + stamps: { home: tide.score > 0, guess: tide.score >= guess, dry: tide.splashes === 0 }, splashes: tide.splashes }; +} +export function todayResult(book: TideBook, day: number): DayResult | null { + const tide = book.days.find(entry => entry.seed === day); + return tide ? dayResult(tide) : null; +} +export function dayResults(book: TideBook): readonly DayResult[] { + return [...book.days].reverse().map(dayResult); +} + +/** What reaches Bram's shelf from one tide: room for three reeds and three pieces of glass a day. */ +export const SHELF_CAP = 3; +export function shelfHaul(result: DayResult): { reed: number; glass: number; pearl: number } { + const h = haul(result); + return { reed: Math.min(h.reed, SHELF_CAP), glass: Math.min(h.glass, SHELF_CAP), pearl: h.pearl }; +} diff --git a/web/src/run/scene.ts b/web/src/run/scene.ts new file mode 100644 index 0000000..43acc0c --- /dev/null +++ b/web/src/run/scene.ts @@ -0,0 +1,438 @@ +/** Draws a tide run. The board is redrawn from `shown`; each accepted move plays its events, then shows the state after. */ +import Phaser from "phaser"; +import { MOCHI_GROUND, MOCHI_POSES, walkingPose, type MochiPoseName } from "../motion/mochi"; +import { companionIdle } from "../expedition/companion"; +import { DOCK, STORY_SHELL, applyMove, countdown, legalMoves, stepDestination, type Item, type Lane, type Position, type TideEvent, type TideState, type TideTransition } from "./engine"; + +const ART = "/assets/expedition/runtime/"; +const IMAGES: Readonly> = { + court: `${ART}tide-court.webp`, island: `${ART}stone-island.webp`, bridge: `${ART}wooden-bridge.webp`, mochi: `${ART}mochi-poses.webp`, + keeper: `${ART}tidekeeper.webp`, shell: `${ART}shell.webp`, wave: `${ART}wave.webp`, lens: `${ART}lens.webp`, moth: `${ART}moth.webp`, + reed: "/assets/season/reed.webp", glass: "/assets/season/glass.webp", + pearl: "/assets/run/pearl.webp", vane: "/assets/run/vane.webp", +}; +const FONT = "Figtree Variable, sans-serif"; +const LANES = [0, 1, 2] as const; +const same = (a: Position, b: Position) => a.x === b.x && a.y === b.y; + +export interface TideSnapshot { readonly tide: TideState; readonly reducedMotion: boolean } +export interface TideHooks { + target: (position: Position) => void; + ready: () => void; + fault: (message: string) => void; + beat: (event: TideEvent) => void; + settled: (id: number) => void; +} + +export class TideScene extends Phaser.Scene { + private hooks: TideHooks; + private snapshot: TideSnapshot; + private shown: TideState; + /** The story shell stays shut until its wave lands. */ + private shut = false; + private backdrop!: Phaser.GameObjects.Image; + private ground!: Phaser.GameObjects.Graphics; + private lanes!: Phaser.GameObjects.Graphics; + private hints!: Phaser.GameObjects.Graphics; + private bridgeArt!: Phaser.GameObjects.Image; + private keeper!: Phaser.GameObjects.Image; + private actor!: Phaser.GameObjects.Sprite; + private actorShadow!: Phaser.GameObjects.Ellipse; + private actorPose: MochiPoseName = "curious"; + private parts: Phaser.GameObjects.GameObject[] = []; + private prizes = new Map(); + private ghosts: Phaser.GameObjects.Image[] = []; + /** Everything `forecast` draws, so it can be redrawn without a full layout. */ + private marks: Phaser.GameObjects.GameObject[] = []; + private shell: Phaser.GameObjects.Image | null = null; + private pack: Phaser.GameObjects.Image[] = []; + private presses = new Map(); + private epoch = 0; + private lastPresentation = 0; + private playing = false; + private gated = false; + private stopped = false; + private idleElapsed = 0; + private idleScale = { x: 1, y: 1 }; + private presentationSize: { w: number; h: number } | null = null; + private get w() { return this.presentationSize?.w ?? this.scale.width; } + private get h() { return this.presentationSize?.h ?? this.scale.height; } + + constructor(snapshot: TideSnapshot, hooks: TideHooks) { + super("tide-run"); + this.snapshot = snapshot; this.hooks = hooks; this.shown = snapshot.tide; this.shut = this.shellShut(snapshot.tide); + } + private shellShut(tide: TideState) { return !!tide.story && tide.wave < 2; } + + preload() { + for (const [key, path] of Object.entries(IMAGES)) this.load.image(`tide-${key}`, path); + this.load.on("loaderror", (file: Phaser.Loader.File) => { + this.stopped = true; + this.hooks.fault(`The ${file.key.replace("tide-", "")} artwork did not load. Your saved moves are safe. Retry the scene.`); + }); + } + + create() { + if (this.stopped) return; + const missing = Object.keys(IMAGES).find(key => !this.textures.exists(`tide-${key}`)); + if (missing) { this.stopped = true; this.hooks.fault(`The ${missing} artwork could not be decoded. Your saved moves are safe. Retry the scene.`); return; } + const atlas = this.textures.get("tide-mochi"), source = atlas.getSourceImage() as HTMLImageElement; + for (let i = 0; i < 16; i++) atlas.add(i, 0, (i % 4) * source.width / 4, Math.floor(i / 4) * source.height / 4, source.width / 4, source.height / 4); + this.backdrop = this.add.image(0, 0, "tide-court").setOrigin(.5).setDepth(-20); + this.ground = this.add.graphics().setDepth(0); + this.bridgeArt = this.add.image(0, 0, "tide-bridge").setDepth(.5); + this.lanes = this.add.graphics().setDepth(2); + this.hints = this.add.graphics().setDepth(2.1); + this.keeper = this.add.image(0, 0, "tide-keeper").setOrigin(.5, 1).setDepth(3); + this.actorShadow = this.add.ellipse(0, 0, 50, 13, 0x342719, .25).setDepth(7); + this.actor = this.add.sprite(0, 0, "tide-mochi", 12).setOrigin(.5, MOCHI_GROUND).setDepth(10); + this.scale.on("resize", () => { + if (this.playing && this.presentationSize) { + const zoom = Math.min(this.scale.width / this.presentationSize.w, this.scale.height / this.presentationSize.h); + this.cameras.main.setZoom(zoom).centerOn(this.presentationSize.w / 2, this.presentationSize.h / 2); + } else { this.cameras.main.setZoom(1).setScroll(0, 0); this.layout(); } + }); + this.events.once("shutdown", () => { this.stopped = true; this.epoch++; }); + this.input.mouse?.disableContextMenu(); + const release = (pointer: Phaser.Input.Pointer) => this.presses.delete(pointer.id); + this.input.on("pointerup", release); this.input.on("pointerupoutside", release); + this.layout(); this.hooks.ready(); + } + + /** Presentation coordinates are responsive. Logical cells and accepted state never resize. */ + private field() { + const portrait = this.w <= 900 && this.h > this.w; + if (portrait && this.h < 500) { const top = 144, bottom = this.h - 166, width = this.w * .82; return { cx: this.w / 2, width, top, bottom, dy: (bottom - top) / 4, dx: width / 3 }; } + if (this.h <= 500) { + // The painted island and its rings extend below the dock anchor. + const available = this.w - 280, width = Math.max(240, Math.min(available * .91, 760)), top = 98, bottom = this.h - (portrait ? 34 : 56); + return { cx: available / 2, width, top, bottom, dy: (bottom - top) / 4, dx: width / 3 }; + } + const top = portrait ? (this.h < 650 ? 151 : Math.max(200, this.h * .29)) : Math.max(190, this.h * .31); + const bottom = portrait ? this.h - 276 : this.h - 72; + const width = Math.min(portrait ? this.w * .84 : this.w * .50, 760); + return { cx: portrait ? this.w * .5 : this.w * .45, width, top, bottom, dy: (bottom - top) / 4, dx: width / 3 }; + } + private point(position: Position) { const f = this.field(); return { x: f.cx + (position.x - 1) * f.dx, y: f.bottom - position.y * f.dy }; } + private tileSize() { const f = this.field(); return { width: Math.min(f.dx * .99, 220), height: Math.max(33, Math.min(f.dy * .65, 72)) }; } + private actorSize() { return Math.min(this.field().dx * .66, this.field().dy * 1.1, 112); } + private prizeSize(kind: Item) { return Math.min(kind === "reed" ? 62 : kind === "moth" ? 58 : 50, this.tileSize().width * .55); } + private pose(name: MochiPoseName) { this.actorPose = name; this.actor.setFrame(MOCHI_POSES[name].frame); } + private keep(part: T) { this.parts.push(part); return part; } + private label(x: number, y: number, text: string, size: number, background = "#314d42") { + return this.add.text(x, y, text, { fontFamily: FONT, fontSize: `${size}px`, fontStyle: "bold", color: "#fff5d8", backgroundColor: background, padding: { x: 7, y: 4 }, align: "center" }).setOrigin(.5).setDepth(12); + } + /** Phaser hit-tests game objects even when a DOM card above the canvas took the press. */ + private onCanvas(pointer: Phaser.Input.Pointer) { return pointer.downElement === this.game.canvas; } + + update(time: number, delta: number) { + if (!this.actor || this.stopped || document.hidden) return; + if (!this.snapshot.reducedMotion) for (const ghost of this.ghosts) ghost.setAlpha(.34 + .14 * Math.sin(time / 240)); + if (this.playing || this.gated || this.snapshot.reducedMotion) return; + this.idleElapsed += Math.min(delta, 100); + const idle = companionIdle(this.idleElapsed, this.attention(), false); + if (this.idleElapsed > 1200) this.pose(idle.pose); + this.actor.setScale(this.idleScale.x, this.idleScale.y * idle.breath); + } + private attention() { + const tide = this.shown; + if (tide.outcome !== "active") return "rest" as const; + return countdown(tide) === 1 && tide.next.lanes.includes(tide.position.x) && tide.position.y > 0 ? "water" as const : "player" as const; + } + private resetIdle() { + this.idleElapsed = 0; this.idleScale = { x: this.actor.scaleX, y: this.actor.scaleY }; this.actor.setAngle(0); + if (this.snapshot.reducedMotion) this.pose(companionIdle(0, this.attention(), true).pose); + } + + setSnapshot(snapshot: TideSnapshot, transition: TideTransition | null, id: number) { + this.snapshot = snapshot; + if (!this.actor || this.stopped) return; + if (transition && id !== this.lastPresentation) { this.lastPresentation = id; void this.present(transition, id); } + else if (!this.playing) { this.shown = snapshot.tide; this.shut = this.shellShut(snapshot.tide); this.layout(); } + } + setGated(gated: boolean) { + this.gated = gated; if (gated) this.presses.clear(); if (!this.actor) return; + this.input.enabled = !gated; this.time.paused = gated; + if (gated) this.tweens.pauseAll(); else this.tweens.resumeAll(); + } + + private layout() { + if (!this.actor || this.stopped) return; + this.presses.clear(); + for (const part of this.parts) part.destroy(); + this.parts = []; this.prizes.clear(); this.pack = []; this.shell = null; + this.ground.clear(); + const tide = this.shown, f = this.field(), tile = this.tileSize(), portrait = this.w <= 900 && this.h > this.w; + const cover = this.backdrop.texture.getSourceImage() as HTMLImageElement; + this.backdrop.setPosition(this.w / 2, this.h / 2).setScale(Math.max(this.w / cover.width, this.h / cover.height)); + // Fixed short walks join each bank. Only the long middle crossing moves with a wave. + for (const y of [0, 3]) for (const x of LANES) { + const from = this.point({ x, y }), to = this.point({ x, y: y + 1 }), length = f.dy * 1.35; + this.keep(this.add.image(from.x, (from.y + to.y) / 2, "tide-bridge").setDisplaySize(length / 3, length).setDepth(.4)); + } + const island = this.textures.get("tide-island").getSourceImage() as HTMLImageElement; + for (let y = 0; y < 5; y++) for (const x of LANES) { + const position = { x, y }, p = this.point(position); + if (y !== 2) { + this.ground.fillStyle(0x183c3d, .22).fillEllipse(p.x, p.y + tile.width * .1, tile.width * 1.05, tile.width * .18); + this.ground.lineStyle(1, 0xe5edce, .35).strokeEllipse(p.x, p.y + tile.width * .1, tile.width * 1.09, tile.width * .24); + this.keep(this.add.image(p.x, p.y, "tide-island").setOrigin(.5, .41).setDisplaySize(tile.width, tile.width * island.height / island.width).setDepth(1)); + } else if (x !== tide.bridge) this.ground.lineStyle(2, 0xa8c8bd, .4).strokeEllipse(p.x, p.y + 6, tile.width * .6, tile.height * .45); + const zone = this.keep(this.add.zone(p.x, p.y, Math.max(44, tile.width), Math.max(44, Math.min(tile.height + 15, f.dy - 2))).setInteractive({ useHandCursor: true }).setDepth(16)); + const target = `${x},${y}`; + zone.on("pointerdown", (pointer: Phaser.Input.Pointer) => { if (!this.gated && this.onCanvas(pointer)) this.presses.set(pointer.id, { target, x: pointer.x, y: pointer.y }); }); + zone.on("pointerup", (pointer: Phaser.Input.Pointer) => { + const press = this.presses.get(pointer.id); this.presses.delete(pointer.id); + if (this.gated || this.playing || pointer.wasCanceled || press?.target !== target || Math.hypot(pointer.x - press.x, pointer.y - press.y) > 12) return; + if (pointer.wasTouch || pointer.leftButtonReleased()) this.hooks.target(position); + }); + } + const crossing = this.point({ x: tide.bridge, y: 2 }), span = f.dy * 1.65 * 1.36; + this.bridgeArt.setPosition(crossing.x, crossing.y).setDisplaySize(span / 3, span).setAngle(0).setAlpha(1); + const dock = this.point(DOCK); + if (!(portrait && this.h < 500 && same(tide.position, DOCK))) this.keep(this.label(dock.x, dock.y + (portrait && this.h < 500 ? -tile.height * .45 : tile.height * .72), "DOCK", Math.max(13, Math.min(14, this.w / 28)))); + const keeperHeight = Math.min(this.h < 500 ? f.top - (portrait ? 78 : 15) : 230, this.h * .26, portrait ? this.w * (this.h < 650 ? .38 : .45) : this.w * .52, portrait ? f.top - (this.h < 650 ? 15 : 80) : Infinity); + this.keeper.setPosition(this.h < 500 && !portrait ? f.cx + Math.min(60, f.width * .18) : portrait && this.h < 650 ? this.w * .72 : f.cx, f.top - 8).setDisplaySize(keeperHeight * 1.32, keeperHeight); + + // The far-shore corners are shells: pearls arrive in them, and a story prize waits in one. + for (const x of [0, 2] as const) { + const p = this.point({ x, y: 4 }), waiting = this.shut && tide.story && STORY_SHELL[tide.story].x === x; + const size = tile.width * (waiting ? .64 : .4); + const shell = this.keep(this.add.image(p.x, p.y - (waiting ? 15 : 6), "tide-shell").setDisplaySize(size, size).setDepth(waiting ? 5 : 1.5)); + if (waiting) this.shell = shell; else shell.setAlpha(.9); + } + for (const item of tide.items) { + const p = this.point(item), size = this.prizeSize(item.kind), beside = same(item, tide.position) ? -tile.width * .3 : 0; + this.prizes.set(`${item.x},${item.y}`, this.keep(this.add.image(p.x + beside, p.y - size * .36, `tide-${item.kind}`).setDisplaySize(size, size).setDepth(6))); + } + const p = this.point(tide.position), size = this.actorSize(); + this.actor.setPosition(p.x, p.y).setDisplaySize(size, size).setFlipX(false); + this.actorShadow.setPosition(p.x, p.y + 2).setSize(size * .55, Math.max(4, size * .1)); + this.pose(tide.outcome === "rescued" ? "startled" : tide.outcome !== "active" ? "relieved" : "curious"); + this.drawPack(tide.pack); + this.forecast(); + this.resetIdle(); + } + + /** The lanes the next wave takes, its countdown, the prize it will leave, and which steps are safe. */ + private forecast() { + for (const mark of this.marks) mark.destroy(); + this.marks = []; this.ghosts = []; + this.lanes.clear(); this.hints.clear(); + const tide = this.shown, f = this.field(), tile = this.tileSize(), lanes = tide.outcome === "active" ? tide.next.lanes : []; + const aim = lanes.length ? lanes.reduce((sum, lane) => sum + lane, 0) / lanes.length - 1 : 0; + this.keeper.setAngle(aim * 4); + if (tide.outcome !== "active") return; + const left = countdown(tide), width = tile.width * .78, top = f.top - 30, bottom = f.bottom - f.dy * .5; + for (const lane of lanes) { + const x = this.point({ x: lane, y: 2 }).x; + const imminent = left === 1, rim = imminent ? 0x9a4733 : 0x52766a; + this.lanes.fillStyle(imminent ? 0xc66b49 : 0xd9b974, imminent ? .22 : .12).fillRoundedRect(x - width / 2, top, width, bottom - top, width / 2); + this.lanes.lineStyle(2, 0xffe6b6, .85).strokeRoundedRect(x - width / 2, top, width, bottom - top, width / 2); + this.lanes.lineStyle(2, rim, .8); + for (let y = f.top + 25; y < bottom - 8; y += 50) { + for (const edge of [-1, 1]) { + const rail = x + edge * (width / 2 - 8); + this.lanes.lineBetween(rail - 3, y - 4, rail, y).lineBetween(rail, y, rail + 3, y - 4); + } + } + // The channel holds the count so neither prizes nor Mochi sit beneath it. + const y = this.point({ x: lane, y: 2 }).y, radius = Math.max(22, Math.min(30, f.dy * .3)); + const badge = this.add.graphics().setDepth(12); + badge.fillStyle(0x342719, .2).fillCircle(x, y + 3, radius + 2); + badge.fillStyle(0xe6c48c).fillCircle(x, y, radius + 2); + badge.fillStyle(imminent ? 0x96432f : 0xfbf3e2).fillCircle(x, y, radius); + badge.lineStyle(1, imminent ? 0xe5b88a : 0xc3a675, .9).strokeCircle(x, y, radius - 3); + for (let pip = 0; pip < 3; pip++) badge.fillStyle(imminent ? 0xffe6bd : 0x2b5f4d, pip < left ? 1 : .22).fillCircle(x + (pip - 1) * 8, y + radius * .59, 2); + this.marks.push(badge, this.add.text(x, y - 4, String(left), { fontFamily: "Fraunces Variable, serif", fontSize: `${radius * 1.1}px`, fontStyle: "bold", color: imminent ? "#fff5de" : "#263e32" }).setOrigin(.5).setDepth(12.1)); + } + for (const drop of tide.next.drops) { + // A story prize is never swept, and a shell holds one thing: nothing will be left beside it. + if (tide.items.some(item => same(item, drop) && item.kind === tide.story)) continue; + const p = this.point(drop), size = this.prizeSize(drop.kind), x = p.x + (same(drop, tide.position) ? -tile.width * .3 : 0); + const ghost = this.add.image(x, p.y - size * .36, `tide-${drop.kind}`).setDisplaySize(size, size).setAlpha(.4).setDepth(5.5); + this.ghosts.push(ghost); this.marks.push(ghost); + this.marks.push(this.add.ellipse(x, p.y - size * .36, size * 1.2, size * 1.2).setStrokeStyle(2.5, 0xfff3c9, .85).setDepth(5.6)); + } + if (this.playing) return; + for (const move of legalMoves(tide)) { + if (move === "home") continue; + const to = stepDestination(tide, move) ?? tide.position, wet = applyMove(tide, move)!.events.some(event => event.kind === "splash"); + if (move === "wait" && !wet) continue; + const at = this.point(to); + const y = at.y + tile.width * .025, width = tile.width * 1.03, height = tile.width * .36; + this.hints.lineStyle(6, 0x304e40, .65).strokeEllipse(at.x, y, width, height); + this.hints.lineStyle(3, wet ? 0xf3ad82 : 0xffefc7, 1).strokeEllipse(at.x, y, width, height); + if (wet) { + const x = at.x + tile.width * .36; + this.hints.fillStyle(0x96432f).fillCircle(x, y + height * .3, 10); + this.hints.lineStyle(2, 0xfff1d4).lineBetween(x - 3, y + height * .3 - 3, x + 3, y + height * .3 + 3).lineBetween(x + 3, y + height * .3 - 3, x - 3, y + height * .3 + 3); + } + } + } + + private packSpot(index: number) { + const size = this.actor.displayHeight, [dx, dy] = ([[-.48, -.34], [.48, -.34], [0, -.98]] as const)[index] ?? [0, -.94]; + return { x: this.actor.x + dx * size, y: this.actor.y + dy * size }; + } + private drawPack(pack: readonly Item[]) { + for (const icon of this.pack) { icon.destroy(); this.parts = this.parts.filter(part => part !== icon); } + this.pack = pack.map((item, index) => { + const spot = this.packSpot(index), size = Math.min(item === "moth" ? 40 : 34, this.actor.displayHeight * .38); + return this.keep(this.add.image(spot.x, spot.y, `tide-${item}`).setDisplaySize(size, size).setDepth(11)); + }); + } + private followActor() { + this.actorShadow.setPosition(this.actor.x, this.actor.y + 2); + for (const [index, icon] of this.pack.entries()) { const spot = this.packSpot(index); icon.setPosition(spot.x, spot.y); } + } + + private async tween(targets: object, config: Omit, duration: number) { + if (this.stopped) return; + await new Promise(resolve => this.tweens.add({ ease: "Sine.easeInOut", ...config, targets, duration: this.snapshot.reducedMotion ? Math.min(duration, 70) : duration, onComplete: () => resolve() })); + } + private async hold(duration: number) { + if (this.stopped) return; + await new Promise(resolve => this.time.delayedCall(this.snapshot.reducedMotion ? 30 : duration, () => resolve())); + } + + private async present(transition: TideTransition, id: number) { + const epoch = ++this.epoch; + let reduced = this.snapshot.reducedMotion; + this.presentationSize = { w: this.scale.width, h: this.scale.height }; + this.playing = true; + this.shown = reduced ? transition.after : transition.before; + this.shut = this.shellShut(this.shown); + this.layout(); + for (const event of transition.events) { + if (this.stopped || this.epoch !== epoch) return; + if (!reduced && this.snapshot.reducedMotion) { + reduced = true; this.shown = transition.after; this.shut = this.shellShut(this.shown); this.layout(); + } + this.hooks.beat(event); + if (reduced) await this.hold(30); else await this.presentEvent(event); + } + if (this.stopped || this.epoch !== epoch) return; + this.shown = transition.after; this.shut = this.shellShut(this.shown); + this.playing = false; this.presentationSize = null; + this.cameras.main.setZoom(1).setScroll(0, 0); + this.layout(); this.hooks.settled(id); + } + + private async presentEvent(event: TideEvent) { + const tide = this.shown, f = this.field(); + switch (event.kind) { + case "move": { + const from = this.point(event.from), to = this.point(event.to), dx = to.x - from.x, dy = to.y - from.y, distance = Math.hypot(dx, dy); + const crossing = Math.abs(event.to.y - event.from.y) === 2; + this.hints.clear(); + this.pose(dx < 0 ? "turn-left" : dx > 0 ? "turn-right" : dy < 0 ? "curious" : "brace"); + this.actor.setFlipX(dx < 0); + await this.tween(this.actor, { x: to.x, y: to.y, onUpdate: () => { + const progress = distance === 0 ? 1 : Math.min(1, Math.hypot(this.actor.x - from.x, this.actor.y - from.y) / distance); + this.pose(walkingPose(progress * (crossing ? 2 : 1))); this.followActor(); + } }, crossing ? 280 : 170); + this.shown = { ...tide, position: event.to }; + this.actor.setFlipX(false); this.pose("neutral"); + break; + } + case "pickup": { + const prize = this.prizes.get(`${event.at.x},${event.at.y}`); + this.pose("reach-ready"); + if (prize) { const spot = this.packSpot(tide.pack.length); await this.tween(prize, { ...spot, scaleX: prize.scaleX * .6, scaleY: prize.scaleY * .6 }, 170); } + this.shown = { ...tide, items: tide.items.filter(item => !same(item, event.at)), pack: [...tide.pack, event.item] }; + this.layout(); this.pose("relieved"); await this.hold(60); + break; + } + case "full": { + const prize = this.prizes.get(`${tide.position.x},${tide.position.y}`); + this.pose("curious"); + if (prize) await this.tween(prize, { angle: 9, yoyo: true, repeat: 1 }, 70); + break; + } + case "bank": { + const dock = this.point(DOCK); + this.pose("relieved"); + await Promise.all(this.pack.map((icon, index) => this.tween(icon, { x: dock.x + (index - 1) * 14, y: dock.y + 10, alpha: 0, delay: index * 45 }, 210))); + if (event.gained) { + const gain = this.add.text(dock.x, dock.y - this.actor.displayHeight * .9, `+${event.gained}`, { fontFamily: FONT, fontSize: "26px", fontStyle: "bold", color: "#fff3c4", stroke: "#2b5f4d", strokeThickness: 6 }).setOrigin(.5).setDepth(20); + void this.tween(gain, { y: gain.y - 34, alpha: 0, ease: "Sine.easeIn" }, 720).then(() => gain.destroy()); + } + this.shown = { ...tide, pack: [] }; this.drawPack([]); + break; + } + case "wave": { + const stop = f.bottom - f.dy * .5, width = this.tileSize().width * 1.15; + if (event.lanes.includes(tide.position.x) && tide.position.y > 0) this.pose("brace"); + const waves = event.lanes.map(lane => this.add.image(this.point({ x: lane, y: 4 }).x, f.top - 70, "tide-wave").setDisplaySize(width, 90).setAlpha(.2).setDepth(14)); + await Promise.all(waves.map(wave => this.tween(wave, { y: stop, alpha: .92 }, 340))); + for (const wave of waves) void this.tween(wave, { y: stop + 14, alpha: 0 }, 130).then(() => wave.destroy()); + this.shown = { ...tide, next: { lanes: [], drops: [] } }; this.forecast(); + break; + } + case "sweep": { + const swept = event.items.flatMap(item => this.prizes.get(`${item.x},${item.y}`) ?? []); + await Promise.all(swept.map(prize => this.tween(prize, { y: prize.y + 26, alpha: 0, angle: 24 }, 170))); + this.shown = { ...tide, items: tide.items.filter(item => !event.items.some(gone => same(gone, item))) }; this.layout(); + break; + } + case "shield": { + const ring = this.add.ellipse(this.actor.x, this.actor.y - this.actor.displayHeight * .3, 30, 22).setStrokeStyle(4, 0xffe7a8, .95).setDepth(15); + this.pose("curious"); + await this.tween(this.keeper, { angle: this.keeper.angle - 7, yoyo: true }, 130); + await this.tween(ring, { scaleX: 4.4, scaleY: 4.4, alpha: 0 }, 330); + ring.destroy(); this.shown = { ...tide, shielded: true }; + break; + } + case "splash": { + const to = this.point(event.to), lost = event.lost ? this.pack.at(-1) : undefined; + this.pose("startled"); + if (lost) void this.tween(lost, { x: lost.x + 46, y: lost.y + 30, alpha: 0, angle: 40 }, 260); + await this.tween(this.actor, { x: to.x, y: to.y, onUpdate: () => this.followActor() }, 230); + const back = event.lost && event.lost !== "reed" && event.lost !== "glass" && event.lost !== "pearl" ? [{ ...STORY_SHELL[event.lost], kind: event.lost }] : []; + this.shown = { ...tide, position: event.to, hearts: event.hearts, pack: tide.pack.slice(0, -1), items: [...tide.items, ...back] }; + this.layout(); this.pose("startled"); await this.hold(140); this.pose("relieved"); + break; + } + case "bridge": { + const berth = this.point({ x: event.to, y: 2 }), direction = event.to > event.from ? 1 : -1; + await this.tween(this.bridgeArt, { angle: direction * 1.8, y: berth.y + 3, alpha: .88 }, 55); + await this.tween(this.bridgeArt, { x: berth.x, y: berth.y + 2, angle: -direction * .7 }, 180); + this.shown = { ...tide, bridge: event.to }; this.layout(); + break; + } + case "open": { + if (this.shell) await this.tween(this.shell, { y: this.shell.y + 15, scaleX: this.shell.scaleX * 1.25, scaleY: this.shell.scaleY * .55, alpha: .35 }, 240); + this.shut = false; + this.shown = { ...tide, items: [...tide.items, { ...STORY_SHELL[event.item], kind: event.item }] }; this.layout(); + await this.arrive([STORY_SHELL[event.item]]); await this.hold(160); + break; + } + case "leave": + this.shown = { ...tide, items: [...tide.items, ...event.items] }; this.layout(); + await this.arrive(event.items); + break; + case "forecast": + // A forecast only follows a wave, which lands on the beat this move spent. + this.shown = { ...tide, next: event.wave, beat: tide.beat + 1 }; this.forecast(); + await this.tween(this.keeper, { angle: this.keeper.angle + 2.5, yoyo: true }, 80); + break; + case "end": + this.hints.clear(); + this.pose(event.reason === "rescued" ? "startled" : "relieved"); + await this.hold(event.reason === "rescued" ? 360 : 200); + break; + } + } + + /** A prize the wave leaves pops onto its platform. */ + private async arrive(at: readonly Position[]) { + await Promise.all(at.map(position => { + const prize = this.prizes.get(`${position.x},${position.y}`); + if (!prize) return Promise.resolve(); + const { scaleX, scaleY, y } = prize; + prize.setScale(scaleX * .3, scaleY * .3).setY(y + 10); + return this.tween(prize, { scaleX, scaleY, y, ease: "Back.easeOut" }, 190); + })); + } +} diff --git a/web/src/run/story.test.ts b/web/src/run/story.test.ts new file mode 100644 index 0000000..f4290f2 --- /dev/null +++ b/web/src/run/story.test.ts @@ -0,0 +1,131 @@ +import { expect, test } from "bun:test"; +import { 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"; + +const careful = (prize: StoryPrize) => { + let state = startTide(storyStart(prize)), homeWave = -1; + const turns: TideTransition[] = []; + while (state.outcome === "active") { + const turn = applyMove(state, cautiousMove(state, { ...VALUE, [prize]: 60 }))!; + turns.push(turn); state = turn.after; + if (homeWave < 0 && state.banked.includes(prize)) homeWave = state.wave; + } + return { state, homeWave, turns }; +}; + +test("every story tide brings its prize home dry with three waves to spare", () => { + for (const prize of ["lens", "vane", "moth"] as const) { + const { state, homeWave } = careful(prize); + expect(state.banked).toContain(prize); + expect(state.splashes).toBe(0); + expect(tideShape({ story: prize }).waves - homeWave).toBeGreaterThanOrEqual(3); + } +}); + +test("the chapter follows what the harbor already saves", () => { + expect(chapterFor({ banked: [], lit: false, signaled: false })).toBe("lens"); + expect(chapterFor({ banked: ["lens"], lit: false, signaled: false })).toBeNull(); + expect(chapterFor({ banked: ["lens"], lit: true, signaled: false })).toBe("vane"); + expect(chapterFor({ banked: ["lens", "vane"], lit: true, signaled: false })).toBeNull(); + expect(chapterFor({ banked: ["lens", "vane"], lit: true, signaled: true })).toBe("moth"); + expect(chapterFor({ banked: ["lens", "vane", "moth"], lit: true, signaled: true })).toBeNull(); + expect(Object.values(CHAPTERS).map(chapter => chapter.number)).toEqual([1, 2, 3]); +}); + +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).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(""); +}); + +function memory() { + const data = new Map(); + return { data, getItem: (key: string) => data.get(key) ?? null, setItem: (key: string, value: string) => { data.set(key, value); } }; +} + +test("a finished tide stays active until it is filed", () => { + const storage = memory(), key = "tide"; + for (const finished of [careful("lens").state, cautiousTide(20771)]) { + expect(finished.outcome).not.toBe("active"); + const book = { active: finished, days: [] }; + writeBook(storage, key, book); + expect(readBook(storage, key)).toEqual(book); + } +}); + +test("a tide book survives a reload and keeps each day's first tide", () => { + const storage = memory(), key = "tide"; + expect(readBook(storage, key)).toEqual(emptyBook()); + const underway = applyMove(startTide(storyStart("lens")), "north")!.after; + writeBook(storage, key, { active: underway, days: [] }); + expect(readBook(storage, key).active).toEqual(underway); + + const first = cautiousTide(20771), again = replayTide({ seed: 20771 }, ["home"])!; + let book = closeTide({ active: first, days: [] }, first); + book = closeTide(book, again); + book = closeTide(book, careful("lens").state); + expect(book).toEqual({ active: null, days: [first] }); + writeBook(storage, key, book); + expect(readBook(storage, key)).toEqual(book); + + const today = todayResult(book, 20771)!; + expect(today).toEqual(dayResult(first)); + expect(today).toEqual({ day: 20771, score: 6, guess: 6, banked: ["reed", "glass", "reed", "reed"], + stamps: { home: true, guess: true, dry: true }, splashes: 0 }); + expect(today.guess).toBe(bramsGuess(20771)); + expect(today.stamps).toEqual({ home: true, guess: true, dry: true }); + expect(dayResult(again).stamps).toEqual({ home: false, guess: false, dry: true }); + expect(todayResult(book, 20772)).toBeNull(); + +}); + +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] }; + expect(dayResults(book)).toEqual([dayResult(second), dayResult(first)]); + expect(book.days).toEqual([first, second]); + expect(dayResults(emptyBook())).toEqual([]); +}); + +test("a daily result keeps every prize in banked order and records splashes", () => { + const daily = { ...cautiousTide(20771), banked: ["glass", "pearl", "reed", "glass", "reed"] as const, splashes: 2 }; + const result = dayResult(daily); + expect(result.banked).toEqual(["glass", "pearl", "reed", "glass", "reed"]); + expect(result.splashes).toBe(2); + expect(result.stamps).toEqual({ home: true, guess: true, dry: false }); +}); + +test("day results exclude story prizes while keeping the other prizes in order", () => { + const tide = { ...careful("lens").state, banked: ["glass", "lens", "pearl", "vane", "reed", "moth", "glass"] as const }; + expect(dayResult(tide).banked).toEqual(["glass", "pearl", "reed", "glass"]); +}); + +test("the shelf caps reed and glass at three and leaves pearls uncapped", () => { + const result: DayResult = { day: 20771, score: 40, guess: 6, + banked: ["reed", "glass", "pearl", "reed", "glass", "pearl", "reed", "glass", "pearl", "reed", "glass", "pearl"], + stamps: { home: true, guess: true, dry: true }, splashes: 0 }; + expect(shelfHaul(result)).toEqual({ reed: 3, glass: 3, pearl: 4 }); + expect(shelfHaul({ ...result, banked: ["reed", "pearl"] })).toEqual({ reed: 1, glass: 0, pearl: 1 }); + expect(shelfHaul({ ...result, banked: [] })).toEqual({ reed: 0, glass: 0, pearl: 0 }); +}); + +test("a damaged book is refused", () => { + for (const raw of [ + "{", JSON.stringify({ version: 2, active: null, days: [] }), + JSON.stringify({ version: 1, active: { seed: 5, moves: ["north", "north", "north", "north", "north"] }, days: [] }), + JSON.stringify({ version: 1, active: null, days: [{ seed: 5, moves: ["north"] }] }), + JSON.stringify({ version: 1, active: null, days: [{ seed: 5, story: "lens", moves: ["home"] }] }), + JSON.stringify({ version: 1, active: null, days: [{ seed: 6, moves: ["home"] }, { seed: 5, moves: ["home"] }] }), + ]) { + const storage = memory(); storage.data.set("tide", raw); + expect(() => readBook(storage, "tide")).toThrow(); + } +}); diff --git a/web/src/run/story.ts b/web/src/run/story.ts new file mode 100644 index 0000000..ad74261 --- /dev/null +++ b/web/src/run/story.ts @@ -0,0 +1,111 @@ +/** The story is three tides. Which one a harbor is on is read from what the harbor already saves. */ +import type { Item, Lane, StoryPrize, TideStart, TideTransition } from "./engine"; + +export interface HarborStory { readonly banked: readonly string[]; readonly lit: boolean; readonly signaled: boolean } + +export interface Chapter { + readonly number: 1 | 2 | 3; + readonly title: string; + /** A fixed tide every new player gets: a careful player brings the prize home dry with waves to spare. */ + readonly seed: number; + readonly before: string; + readonly goal: string; + /** Bram, once the prize is home and fitted. */ + readonly after: readonly string[]; +} + +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.", + 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.", + after: [ + "Wren kept this light. The night it failed she rowed out to guide the boats in by hand. The boats came home.", + "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.", + after: ["It knows she isn’t coming. It gave you the moth anyway.", "Two familiars and one light. That’ll do for a harbor."], + }, +}; + +/** The story tide a harbor should sail next, or null between chapters and once the moth is home. */ +export function chapterFor(home: HarborStory): StoryPrize | null { + if (!home.banked.includes("lens")) return "lens"; + if (home.lit && !home.banked.includes("vane")) return "vane"; + if (home.signaled && !home.banked.includes("moth")) return "moth"; + return null; +} +export const storyStart = (prize: StoryPrize): TideStart => ({ seed: CHAPTERS[prize].seed, story: prize }); + +const LANES = ["Left", "Center", "Right"] as const; +const NAMES: Readonly> = { reed: "reed", glass: "sea glass", pearl: "pearl", lens: "Beacon Lens", vane: "Signal Vane", moth: "wind-moth" }; +export const itemName = (item: Item) => NAMES[item]; +export const laneNames = (lanes: readonly Lane[]) => lanes.map(lane => LANES[lane]).join(" and "); +const A: Readonly> = { reed: "a reed", glass: "sea glass", pearl: "a pearl", lens: "the Beacon Lens", vane: "the Signal Vane", moth: "the wind-moth" }; +/** "a reed", "sea glass", "a pearl": the name as it reads in a sentence. */ +export const aPrize = (item: Item) => A[item]; +const MANY: Readonly> = { reed: "reeds", glass: "pieces of sea glass", pearl: "pearls", lens: "lenses", vane: "vanes", moth: "moths" }; +const COUNT = ["no", "one", "two", "three", "four", "five", "six"]; +/** "a reed and two pieces of sea glass", or with `the`: "the reed and the two pieces of sea glass". */ +function list(items: readonly Item[], the = false): string { + const parts = [...new Set(items)].map(kind => { + const count = items.filter(item => item === kind).length; + return count === 1 ? (the ? `the ${itemName(kind)}` : A[kind]) : `${the ? "the " : ""}${COUNT[count] ?? count} ${MANY[kind]}`; + }); + return parts.length > 1 ? `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}` : parts[0] ?? "nothing"; +} + +const OPENED: Readonly> = { + lens: "The left shell opens. The lens is inside.", + vane: "The right shell opens. Brass, and still turning.", + 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.", +}; +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.", +}; +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 { + 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 "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}.`); + 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 "open": facts.push(OPENED[event.item]); break; + case "leave": facts.push(`The tide leaves ${list(event.items.map(item => item.kind))}.`); break; + case "end": + if (event.reason === "rescued") facts.push("Bram wades out and carries Mochi home."); + else if (event.reason === "turned") facts.push(event.lost.length ? "The tide turns and takes what was still in the pack." : "The tide turns."); + else facts.push("Mochi calls it a day."); + break; + default: break; + } + return facts.join(" "); +} diff --git a/web/src/run/tide-run.css b/web/src/run/tide-run.css new file mode 100644 index 0000000..3b24702 --- /dev/null +++ b/web/src/run/tide-run.css @@ -0,0 +1,143 @@ +.tide-run .exp-brand small { font-size: 13px; line-height: 1.3; } +.tide-run h1.exp-place { max-width: none; font-size: 15px; padding: 9px 14px; border: 0; border-radius: 999px; background: #304e40; } +.tide-run .passage-header-actions button { min-width: 44px; min-height: 44px; padding: 10px 14px; border: 1.5px solid var(--exp-hairline); border-radius: 999px; color: var(--exp-ink); background: #fffaf0; font: 600 17px/1.2 "Fraunces Variable", serif; white-space: nowrap; } +.tide-run .passage-header-actions button:hover:not(:disabled) { color: var(--exp-ink); background: #fff3dc; } +.tide-run .passage-header-actions .tide-sound { width: 44px; height: 44px; padding: 10px; } +.tide-run button:focus-visible { outline: 3px solid #2b5f4d; outline-offset: 3px; } +.tide-run .tide-hud, .tide-run .passage-tray { color: var(--exp-ink); background: var(--exp-card); border: 0; border-radius: var(--exp-card-radius); box-shadow: var(--exp-card-shadow); } +.tide-run .tide-hud { gap: 14px; padding: 12px 16px; font-variant-numeric: tabular-nums; } +.tide-run .tide-sr { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; border: 0; } +.tide-run .tide-portrait { flex: none; width: 48px; height: 48px; object-fit: contain; } +.tide-run .tide-vitals { display: grid; gap: 5px; } +.tide-run .tide-vitals strong { font: 650 18px/1.15 "Fraunces Variable", serif; white-space: nowrap; } +.tide-run .tide-hearts { display: flex; gap: 4px; color: #a04432; line-height: 1; } +.tide-run .tide-hearts span { display: flex; } +.tide-run .tide-hearts svg { width: 17px; height: 17px; } +.tide-run .tide-heart-full svg { fill: currentColor; } +.tide-run .tide-heart-empty { color: #8a7d68; } +.tide-run .tide-tally { display: flex; align-items: center; gap: 7px; padding-left: 14px; border-left: 1px solid var(--exp-hairline); font-size: 13px; color: var(--exp-secondary-ink); } +.tide-run .tide-tally > svg { flex: none; color: var(--exp-sea); } +.tide-run .tide-tally b { display: block; font: 650 22px/1.1 "Fraunces Variable", serif; color: var(--exp-ink); } +.tide-run .passage-tray { display: flex; flex-direction: column; gap: 12px; width: 340px; padding: 16px; } +.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; } +.tide-run .exp-context-actions .exp-inspect-button, .tide-run .exp-context-actions .exp-text-button, .tide-run .tide-finish-actions .exp-text-button { min-width: 44px; min-height: 44px; padding: 8px 6px; border: 0; background: transparent; color: var(--exp-ink); box-shadow: none; font: 600 15px/1.3 "Figtree Variable", sans-serif; text-decoration: underline; text-underline-offset: 3px; white-space: nowrap; } +.tide-run .exp-forecast { display: flex; align-items: flex-start; gap: 9px; padding: 12px 0; border-top: 1px solid var(--exp-hairline); border-bottom: 1px solid var(--exp-hairline); margin: 0 0 14px!important; min-height: 0; font: 500 14px/1.45 "Figtree Variable", sans-serif; } +.tide-run .exp-forecast > svg { flex: none; margin-top: 1px; color: var(--exp-sea); } +.tide-run .tide-forecast-soon, .tide-run .tide-forecast-soon > svg { color: #8e3527; } +.tide-run .exp-directions { gap: 5px; } +.tide-run .exp-directions button { width: 44px; height: 44px; border: 1.5px solid var(--exp-hairline); border-radius: 999px; background: #fffaf0; } +.tide-run .exp-directions button:hover:not(:disabled) { background: #ede3ca; } +.tide-run .exp-directions button:disabled { opacity: 1; color: #8a8272; background: #eee6d4; border-color: #ded1b7; } +.tide-run .exp-directions .exp-wait { font: 600 17px/1 "Fraunces Variable", serif; } +.tide-run .exp-context-actions button { min-height: 44px; font-size: 15px; white-space: nowrap; } +.tide-run .exp-feedback { position: static; inset: auto; width: auto; max-width: none; margin: 0; padding: 0; border: 0; border-radius: 0; background: transparent; color: var(--exp-secondary-ink); font-size: 13px; line-height: 1.4; } +.tide-run .tide-finish .exp-feedback { margin-top: 16px; } +.tide-run .tide-finish { top: 50%; bottom: auto; left: 50%; right: auto; transform: translate(-50%, -50%); width: min(520px, calc(100% - 24px)); max-height: calc(100dvh - 32px); overflow-y: auto; overscroll-behavior: contain; display: block; padding: 26px; text-align: center; } +.tide-run .tide-finish-portrait { display: block; margin: 0 auto 8px; } +.tide-run .tide-finish h2 { margin: 0 0 12px; font-size: 30px; } +.tide-run .tide-finish p { display: block; overflow: visible; white-space: normal; font-size: 15px; line-height: 1.45; } +.tide-run .tide-finish-actions { display: flex; flex-direction: column; gap: 10px; margin-top: 22px; } +.tide-run .tide-finish-actions button { width: 100%; white-space: nowrap; } +.tide-run .tide-stamps { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; margin: 22px 0 0; padding: 18px 0 0; border-top: 1px solid var(--exp-hairline); list-style: none; font-size: 13px; line-height: 1.35; } +.tide-run .tide-stamps li { display: flex; flex-direction: column; align-items: center; gap: 9px; color: var(--exp-secondary-ink); } +.tide-run .tide-stamp-mark { position: relative; display: grid; place-items: center; width: 68px; height: 68px; border: 1px dashed #aa9774; border-radius: 50%; } +.tide-run .tide-stamp-mark img { opacity: .4; filter: grayscale(1); } +.tide-run .tide-stamp-mark > svg { position: absolute; bottom: -4px; right: -2px; width: 22px; height: 22px; padding: 3px; border-radius: 50%; color: var(--exp-secondary-ink); background: var(--exp-card); } +.tide-run .tide-stamps li[data-earned=true] { color: var(--exp-sea); font-weight: 700; } +.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 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); } +@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; } + .tide-run .exp-brand small { max-width: 162px; text-align: center; } + .tide-run .passage-header-actions { grid-column: 2; grid-row: 1; } + .tide-run .passage-header-actions button { padding-inline: 10px; } + .tide-run h1.exp-place { grid-column: 1 / -1; justify-self: start; margin: 0; padding: 5px 10px; font-size: 13px; } + .tide-run .tide-hud { top: max(124px, calc(env(safe-area-inset-top) + 114px)); left: 10px; right: 10px; width: auto; max-width: none; gap: 10px; padding: 10px 12px; } + .tide-run .tide-portrait { width: 42px; height: 42px; } + .tide-run .tide-vitals strong { font-size: 16px; } + .tide-run .tide-hearts { gap: 3px; } + .tide-run .tide-hearts svg { width: 15px; height: 15px; } + .tide-run .tide-tally { gap: 5px; padding-left: 10px; } + .tide-run .tide-tally > svg { width: 18px; height: 18px; } + .tide-run .tide-tally b { font-size: 19px; } + .tide-run .passage-tray { left: 10px; right: 10px; width: auto; padding: 10px 12px; max-height: 212px; gap: 4px; } + .tide-run .exp-objective-row { gap: 8px; margin-bottom: 4px; } + .tide-run .exp-objective { font-size: 15px; } + .tide-run .exp-forecast { padding: 7px 0; margin-bottom: 8px!important; font-size: 13px; line-height: 1.35; } + .tide-run .exp-current-controls { flex-direction: column; gap: 0; align-items: stretch; } + .tide-run .exp-directions { flex: 1; min-width: 0; gap: 4px; } + .tide-run .exp-directions button { width: 56px; height: 56px; flex: none; } + .tide-run .exp-context-actions { flex: none; width: auto; min-height: 44px; } + .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; } +} +@media (orientation: landscape) and (max-height: 500px) { + .tide-run .exp-brand { padding: 6px 12px; } + .tide-run .exp-brand small { font-size: 13px; } + .tide-run .tide-hud { top: 70px; left: auto; right: 10px; width: 260px; max-width: none; gap: 6px; padding: 10px; } + .tide-run .tide-portrait { width: 32px; height: 32px; } + .tide-run .tide-vitals strong { font-size: 16px; } + .tide-run .tide-hearts svg { width: 15px; height: 15px; } + .tide-run .tide-tally { gap: 5px; padding-left: 6px; } + .tide-run .tide-tally > svg { display: none; } + .tide-run .tide-tally b { font-size: 18px; } + .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; } + .tide-run .exp-forecast > svg { float: left; width: 18px; height: 18px; margin: 0 6px 2px 0; } + .tide-run .exp-current-controls { flex-direction: column; } + .tide-run .exp-directions { width: 100%; gap: 4px; } + .tide-run .exp-directions button { flex: none; } + .tide-run .exp-context-actions .exp-inspect-button, .tide-run .exp-context-actions .exp-text-button { padding-inline: 0; } + .tide-run .tide-finish { top: 140px; bottom: auto; transform: translateX(-50%); width: min(690px, calc(100% - 32px)); max-height: calc(100dvh - 150px); overflow-y: auto; display: flex; align-items: center; gap: 24px; padding: 20px 24px; } + .tide-run .tide-finish > div:first-child { flex: 1; min-width: 0; } + .tide-run .tide-finish-portrait { width: 52px; height: 52px; margin-bottom: 6px; } + .tide-run .tide-finish h2 { font-size: 24px; margin-bottom: 8px; } + .tide-run .tide-finish p { font-size: 13px; } + .tide-run .tide-finish-actions { flex: none; width: 230px; margin: 0; } + .tide-run .tide-finish-actions button { padding-inline: 12px; font-size: 16px; } + .tide-run .tide-finish:has(.tide-stamps) > div:first-child { display: grid; grid-template-columns: 52px minmax(0, 1fr); grid-template-rows: minmax(28px, auto) minmax(24px, auto); column-gap: 12px; text-align: left; } + .tide-run .tide-finish:has(.tide-stamps) .tide-finish-portrait { grid-row: 1 / 3; margin: 0; } + .tide-run .tide-finish:has(.tide-stamps) h2 { margin: 0; line-height: 28px; } + .tide-run .tide-finish:has(.tide-stamps) h2 + p { margin: 0; line-height: 18px; } + .tide-run .tide-finish:has(.tide-stamps) .exp-feedback { grid-column: 1 / -1; margin-top: 8px; line-height: 18px; } + .tide-run .tide-finish:has(.tide-stamps) [role=alert] { grid-column: 1 / -1; margin-top: 8px; } + .tide-run .tide-stamps { grid-column: 1 / -1; gap: 8px; margin-top: 8px; padding-top: 8px; line-height: 16px; } + .tide-run .tide-stamps li { flex-direction: row; gap: 6px; } + .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; } +} +@media (pointer: coarse) { + .tide-run .exp-directions { grid-template-columns: repeat(3, 56px); grid-template-rows: repeat(3, 56px); } + .tide-run .exp-directions button { width: 56px; height: 56px; min-height: 56px; } +} +@media (pointer: coarse) and (orientation: landscape) and (max-height: 500px) { + .tide-run .exp-current-controls { display: grid; grid-template-columns: repeat(4, 56px); grid-template-rows: 56px 56px; gap: 4px; } + .tide-run .exp-directions { display: contents; } + .tide-run .exp-directions button { grid-column: auto; grid-row: 1; order: 0; } + .tide-run .exp-directions .exp-wait { grid-column: 1; grid-row: 2; } + .tide-run .exp-context-actions { grid-column: 2 / -1; grid-row: 2; gap: 4px; } +} diff --git a/web/src/season/Harness.tsx b/web/src/season/Harness.tsx index cd4afcb..7d74757 100644 --- a/web/src/season/Harness.tsx +++ b/web/src/season/Harness.tsx @@ -34,13 +34,13 @@ async function seasonAct(intent:SeasonIntent) { const session={state:{mode:"saved",busy:false,snapshot:{binding:{nearAccountId:account},pets:[{token_id:pet}]}},seasonAct} as unknown as HarborSession; export default function SeasonHarness() { - const [sailed,setSailed]=useState(""); + const [opened,setOpened]=useState(false); return

Development harness. Shelf and today’s tide are read live; this account’s ledger, wish and signing are mocked. Nothing is signed or sent.

“You’re back.”

- setSailed(`Would sail with the ${t}.`)} tideScope="harness"/> - {sailed&&

{sailed}

} + setOpened(true)} tideScope="harness"/> + {opened&&

Would open today’s ask.

}
; } diff --git a/web/src/season/SeasonBoundary.tsx b/web/src/season/SeasonBoundary.tsx new file mode 100644 index 0000000..735d780 --- /dev/null +++ b/web/src/season/SeasonBoundary.tsx @@ -0,0 +1,8 @@ +import { Component, type ReactNode } from "react"; +import "./season.css"; + +export default class SeasonBoundary extends Component<{children:ReactNode},{failed:boolean}> { + state={failed:false}; + static getDerivedStateFromError(){return {failed:true};} + render(){return this.state.failed?

Bram’s shelf won’t open just now. Reload the page to try again.

:this.props.children;} +} diff --git a/web/src/season/SeasonBram.test.tsx b/web/src/season/SeasonBram.test.tsx new file mode 100644 index 0000000..54bb8cb --- /dev/null +++ b/web/src/season/SeasonBram.test.tsx @@ -0,0 +1,192 @@ +import { expect, test } from "bun:test"; +import { renderToStaticMarkup } from "react-dom/server"; +import SeasonBram, { Shelf, Status, TodayHaul, WishTab } from "./SeasonBram"; +import SeasonBoundary from "./SeasonBoundary"; +import { deviceDay, keepTide, seedPreview, type TideReturn } from "./data"; +import type { ShelfView, TodayView } from "./model"; +import type { DayResult } from "../tide/run-day"; + +const today:TodayView={day:20771,next_day_ns:0,rules_version:"tidebound_h1_v1",content_version:"first_light_v2",area:"beacon",command_limit:24, + mapping:[["lens","glass"],["moth","reed"]],best_haul:[{tool:"rope",hauls:[[1,1]]},{tool:"lantern",hauls:[[1,1]]}],best_fp:12_000_000,minted_today:null,traded_today:null}; +const shelf:ShelfView={day:20771,till:300,till_cap:300,till_refill:60,commission:0,shells_minted:0,goods_minted:[0,0],trade_seq:0, + goods:(["glass","reed"] as const).map(good=>({good,stock:40,target:40,base:good==="glass"?8:4,heat_fp:0,price_fp:good==="glass"?8_000_000:4_000_000,buyback_fp:0,buy_price:good==="glass"?8:4,sell_price:good==="glass"?7:3,waiting_wishes:0}))}; +const props={live:{shelf,today,account:null,wish:null,postcard:null,error:""},saved:false,registered:false,busy:false,preview:seedPreview(null),scope:"preview", + onOpenTide:()=>{},onPreview:()=>{},onPreviewBlock:()=>{},act:async()=>{}}; +const full=["step:north","step:north","step:west","wait","wait","step:east","reel:lens","step:east","step:west","step:east","take:moth","step:west","step:east","step:south","step:west","step:south","return"]; +const lens=["wait","step:west","wait","step:north","step:north","take:lens","step:south","step:east","return"]; +const entry=(id:string,commands:string[]):TideReturn=>({id,commands,contentVersion:"first_light_v2",tool:"rope",cargo:[],outcome:"returned",savedAt:"2026-11-14T23:59:59Z"}); + +test("the preview status explains blocked storage once in idle and confirmed states",()=>{ + const note="This shelf lasts only until the page closes. This browser isn’t keeping site data."; + for(const state of [{kind:"idle"} as const,{kind:"confirmed",value:null} as const]){ + const html=renderToStaticMarkup(); + expect(html).toContain(note); + expect(html.split(note)).toHaveLength(2); + expect(html).not.toContain("Shelved on this device"); + } + expect(renderToStaticMarkup()).toContain("Shelved on this device"); + expect(renderToStaticMarkup()).not.toContain(note); +}); + +test("a shelving press supplies distinct saved and in-memory confirmations",()=>withReturns([entry("full",full)],()=>{ + let texts:string[]=[]; + const haul=TodayHaul({...props,onPreview:(_market,saved,unsaved)=>{texts=[saved,unsaved??""];}}); + haul.props.children[0].props.children.find((child:{props:{onPress?:()=>void}})=>child.props.onPress).props.onPress(); + expect(texts).toEqual(["Shelved on this device: 1 glass and 1 reed bundle. Not recorded.","Shelved for this visit: 1 glass and 1 reed bundle. Not recorded."]); +})); + +test("the shelf boundary preserves healthy content and gives a local reload message on failure",()=>{ + const boundary=new SeasonBoundary({children:

Bram’s shelf

}); + expect(renderToStaticMarkup(<>{boundary.render()})).toContain("Bram’s shelf

"); + boundary.state=SeasonBoundary.getDerivedStateFromError(); + const html=renderToStaticMarkup(

“You’re back.”

)+renderToStaticMarkup(<>{boundary.render()}); + expect(html).toContain("“You’re back.”");expect(html).toContain('class="ss-problem" role="alert"'); + expect(html).toContain("Bram’s shelf won’t open just now. Reload the page to try again."); +}); + +function withReturns(entries:TideReturn[],check:()=>void) { + const previous=Object.getOwnPropertyDescriptor(globalThis,"localStorage"),items=new Map(); + const store={getItem:(key:string)=>items.get(key)??null,setItem:(key:string,value:string)=>{items.set(key,value);}}; + Object.defineProperty(globalThis,"localStorage",{configurable:true,value:store}); + try{for(const value of entries)keepTide("preview",value,store);check();} + finally{if(previous)Object.defineProperty(globalThis,"localStorage",previous);else Reflect.deleteProperty(globalThis,"localStorage");} +} + +test("Bram has one haul block before two tabs and keeps the action status region",()=>withReturns([],()=>{ + const html=renderToStaticMarkup({}}/>); + expect(html).toContain('aria-label="Bram’s shelf"');expect(html).toContain('role="status"'); + expect(html.match(/role="tab"/g)).toHaveLength(2); + expect(html).toContain("Shelf & till");expect(html).toContain("Mochi’s wish"); + expect(html.indexOf("Today’s haul")).toBeLessThan(html.indexOf('role="tablist"')); + expect(html).not.toContain("Sail today’s tide");expect(html).not.toContain("Bram’s season"); + expect(html).toContain("Device preview · not recorded"); + expect(html).not.toContain("Prices follow Bram’s formula on this device"); +})); + +test("the haul states read the ledger first, then a saved docking before the other route",()=>{ + expect(renderToStaticMarkup()).toContain("Reading Bram’s ledger…"); + const minted={day:20771,content_version:"first_light_v1",tool:"rope",goods:[1,1] as [number,number],value_fp:12_000_000,best_fp:12_000_000,score_bp:10_000}; + const html=renderToStaticMarkup(); + expect(html).toContain("Bram shelved 1 glass and 1 reed bundle today");expect(html).not.toContain("every other day"); + expect(renderToStaticMarkup()).toContain("Keep today’s find; he can shelve it tomorrow."); +}); + +test("empty and invalid returns lead to the Tidekeeper's ask",()=>withReturns([entry("empty",["return"])],()=>{ + const html=renderToStaticMarkup(); + expect(html).toContain("Bring a find home from today’s tide and Bram will shelve it.");expect(html).toContain("See today’s ask");expect(html).not.toContain("Shelve "); +})); + +test("shelving offers replayed hauls best first, names the outing day and works signed out",()=>withReturns([entry("full",full),entry("lens",lens)],()=>{ + const html=renderToStaticMarkup(); + expect(html.indexOf("Shelve 1 glass and 1 reed bundle")).toBeLessThan(html.indexOf("Shelve 1 glass")); + expect(html).toContain("Rope · Saturday 14 November");expect(html).not.toContain('aria-disabled="true"'); + expect(html.match(/class="ss-primary"/g)).toHaveLength(1); + expect(html).toContain('class="ss-haul-art" aria-hidden="true"'); + expect(html).toContain('/assets/season/glass.webp');expect(html).toContain('/assets/season/reed.webp'); + expect(renderToStaticMarkup()).not.toContain('class="ss-primary"'); + expect(renderToStaticMarkup()).toContain('aria-disabled="true"'); + expect(renderToStaticMarkup()).not.toContain('aria-disabled="true"'); +})); + +test("market cards keep both quotes and trade actions, with formulas in closed details",()=>{ + const html=renderToStaticMarkup({}}/>); + const cards=[...html.matchAll(/
(.*?)<\/article>/g)].map(match=>match[1]!); + expect(cards).toHaveLength(4); + for(const card of cards){ + expect(card.match(/'); + expect(html).not.toContain("Reading Bram’s ledger");expect(html).not.toContain("every other day"); + expect(html).not.toContain("Shelve "); + } + expect(renderToStaticMarkup({}} run={null}/>)).toContain("See today’s tide"); +}); + +test("a run harbor's docking takes priority even before a run or ledger is available",()=>{ + for(const result of [null,run]){ + const html=renderToStaticMarkup(); + expect(html).toContain('class="ss-docked" data-docked="true"'); + expect(html).toContain("Today’s haul is on Bram’s shelf. He takes one a day; bring another find tomorrow."); + expect(html).not.toContain("Shelve ");expect(html).not.toContain("See today’s tide"); + } + expect(renderToStaticMarkup()).toContain("Shelve 1 glass and 3 reed bundles"); +}); + +test("an empty run haul has nothing to press and pearls stay with Mochi",()=>{ + for(const [banked,keep] of [ + [[],""],[["pearl"]," Mochi keeps the pearl."],[["pearl","pearl"]," Mochi keeps the 2 pearls."], + ] as const){ + const html=renderToStaticMarkup(); + expect(html).toBe(`

Today’s tide brought no reed or glass.${keep}

`); + expect(html).not.toContain("{ + const html=renderToStaticMarkup(); + expect(html).toContain('class="ss-act ss-haul-offer ss-run-haul"'); + expect(html).toContain('/assets/season/glass.webp');expect(html).toContain('/assets/season/reed.webp'); + expect(html).toContain('width="56" height="56"/>×1'); + expect(html).toContain('width="56" height="56"/>×3'); + expect(html).not.toContain('/assets/run/pearl.webp'); + expect(html).toContain("From today’s tide run: Banked 6 · Bram guessed 6."); + expect(html).toContain("Shelve 1 glass and 3 reed bundles"); + expect(html).toContain('class="ss-info">Mochi keeps the pearl.'); + expect(html).toContain('class="ss-primary" aria-disabled="false"'); + expect(renderToStaticMarkup()).not.toContain('class="ss-primary"'); + expect(renderToStaticMarkup()).toContain('aria-disabled="true"'); + expect(renderToStaticMarkup()).toContain("Mochi keeps the 2 pearls."); + expect(renderToStaticMarkup()).not.toContain("Mochi keeps"); +}); + +test("a run press caps each shelf good and seeds a device preview when the RPC is unreadable",()=>{ + let next:ReturnType|undefined; + let texts:string[]=[]; + const result:DayResult={...run,banked:["glass","glass","glass","glass","reed","reed","reed","reed","pearl"]}; + const component=TodayHaul({...props,live:unread,preview:null,run:result,onPreview:(market,saved,unsaved)=>{next=market;texts=[saved,unsaved??""];},onPreviewBlock:()=>{throw Error("unexpected block");}}); + const offer=(component.type as (props:typeof component.props)=>typeof component)(component.props); + offer.props.children.find((child:{props?:{onPress?:()=>void}})=>child?.props?.onPress).props.onPress(); + expect(next?.goods).toEqual([4,5]); + expect(next?.docked).toBe(deviceDay()); + expect(next?.shelf).toEqual([{stock:40,heat_fp:0},{stock:40,heat_fp:0}]); + expect(texts).toEqual(["Shelved on this device: 3 glass and 3 reed bundles. Not recorded.","Shelved for this visit: 3 glass and 3 reed bundles. Not recorded."]); +}); + +test("signed-in hauls and omitted run props keep the legacy ledger flow",()=>withReturns([entry("full",full)],()=>{ + for(const result of [null,run]){ + expect(renderToStaticMarkup()).toBe(renderToStaticMarkup()); + expect(renderToStaticMarkup()).toBe("

Reading Bram’s ledger…

"); + } + expect(renderToStaticMarkup()).toBe(renderToStaticMarkup()); +})); diff --git a/web/src/season/SeasonBram.tsx b/web/src/season/SeasonBram.tsx index d5e105e..81d8f80 100644 --- a/web/src/season/SeasonBram.tsx +++ b/web/src/season/SeasonBram.tsx @@ -1,18 +1,20 @@ import { useCallback, useEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react"; import type { HarborSession, SeasonIntent } from "../expedition/harbor-port"; +import { dayLabel } from "../tide/cards"; +import { haulCount, resultLine, shelfGoods, type DayResult } from "../tide/run-day"; import { GOODS, type Good } from "./pricing"; import { - GOOD_INDEX, PURSE_MAX, WISH_QTY_MAX, bestHaulLine, claimable, goodName, haulLine, postcardLines, quoteBuy, quoteLine, quoteSell, reasonLine, scoreLine, + GOOD_INDEX, PURSE_MAX, WISH_QTY_MAX, claimable, goodName, haulLine, postcardLines, quoteBuy, quoteLine, quoteSell, reasonLine, scoreLine, OPEN_REQUEST, settle, settleError, tradeArgs, tradeBlock, wishBlock, wishStatus, type ActionState, type Mint, type Postcard, type SeasonAccount, type ShelfView, type TodayView, type Trade, type Wish, type WishResult, } from "./model"; -import { PREVIEW_SAMPLE, previewTrade, rollPreview, previewView, readPreview, readTide, seasonView, seedPreview, writePreview, type PreviewMarket, type TideReturn } from "./data"; +import { PREVIEW_SAMPLE, deviceDay, previewDock, previewTrade, rollPreview, previewView, readPreview, readTide, seasonView, seedPreview, writePreview, type PreviewMarket } from "./data"; import "./season.css"; const ART = "/assets/season/"; const STORAGE_NEAR = "0.0125"; -type Tab = "shelf" | "tide" | "wish"; -const TABS: [Tab, string][] = [["shelf","Shelf & till"],["tide","Today’s tide"],["wish","Mochi’s wish"]]; +type Tab = "shelf" | "wish"; +const TABS: [Tab, string][] = [["shelf","Shelf & till"],["wish","Mochi’s wish"]]; interface Live { shelf:ShelfView|null;today:TodayView|null;account:SeasonAccount|null|undefined;wish:Wish|null;postcard:Postcard|null;error:string } const empty:Live = { shelf:null,today:null,account:undefined,wish:null,postcard:null,error:"" }; @@ -37,9 +39,9 @@ function useSeason(accountId:string|null, pet:string|null) { return {live,loading,refresh}; } -const Status=({state,confirmed,ref}:{state:ActionState;confirmed:string;ref:React.Ref})=>{ +export const Status=({state,confirmed,previewSaved=true,ref}:{state:ActionState;confirmed:string;previewSaved?:boolean;ref?:React.Ref})=>{ const text=state.kind==="pending"?state.label:state.kind==="confirmed"?confirmed:state.kind==="refused"||state.kind==="uncertain"?state.words:""; - return

{text}

; + return

{text}{!previewSaved&&`${text?" ":""}This shelf lasts only until the page closes. This browser isn’t keeping site data.`}

; }; /** * A button that stays focusable while unavailable (aria-disabled), so a press that makes it @@ -49,9 +51,15 @@ function Press({off,onPress,children,className,describedBy,label}:{off:boolean;o return ; } -export interface SeasonBramProps { session?:HarborSession;tool:"rope"|"lantern";canSail:boolean;onSailTide:(tool:"rope"|"lantern")=>void;tideScope:string } +const iconPaths={shelf:"M4 4v16M20 4v16M4 12h16M4 20h16M8 7v5M12 5v7M16 8v4",buy:"M12 4v16m-6-6 6 6 6-6",sell:"M12 20V4m-6 6 6-6 6 6",minus:"M5 12h14",plus:"M12 5v14M5 12h14",wish:"M5 4h14v16l-7-4-7 4Z",back:"m9 5-6 6 6 6M3 11h11a6 6 0 0 1 6 6"}; +function SeasonIcon({kind}:{kind:keyof typeof iconPaths}) { + return ; +} + +/** `run` is today's tide-run result on a device harbor (null before today's tide). Leave it undefined where the three-ask court is the daily. */ +export interface SeasonBramProps { session?:HarborSession;onOpenTide:()=>void;tideScope:string;run?:DayResult|null } -export default function SeasonBram({session,tool,canSail,onSailTide,tideScope}:SeasonBramProps) { +export default function SeasonBram({session,onOpenTide,tideScope,run}:SeasonBramProps) { const saved=session?.state.mode==="saved"&&!!session.state.snapshot&&!!session.seasonAct; const accountId=saved?session!.state.snapshot!.binding.nearAccountId:null,pet=saved?session!.state.snapshot!.pets[0]?.token_id??null:null; const {live,loading,refresh}=useSeason(accountId,pet); @@ -59,11 +67,17 @@ export default function SeasonBram({session,tool,canSail,onSailTide,tideScope}:S const tabRefs=useRef<(HTMLButtonElement|null)[]>([]); const [action,setAction]=useState>({kind:"idle"}),[confirmedText,setConfirmedText]=useState(""); const [storedPreview,setPreview]=useState(()=>readPreview()); + const [previewSaved,setPreviewSaved]=useState(true); const preview=storedPreview&&rollPreview(storedPreview); - useEffect(()=>{if(!saved&&!preview&&live.shelf){const seeded=seedPreview(live.shelf);setPreview(seeded);writePreview(seeded);}},[saved,preview,live.shelf]); + useEffect(()=>{if(!saved&&!preview&&live.shelf){const seeded=seedPreview(live.shelf);setPreview(seeded);setPreviewSaved(writePreview(seeded));}},[saved,preview,live.shelf]); const openRequest=saved&&!!session?.state.pending; const busy=action.kind==="pending"||!!session?.state.busy||openRequest; const rootRef=useRef(null),statusRef=useRef(null); + function onPreview(next:PreviewMarket,text:string,unsavedText=text) { + setPreview(next);const kept=writePreview(next);setPreviewSaved(kept);setAction({kind:"confirmed",value:null});setConfirmedText(kept?text:unsavedText); + requestAnimationFrame(()=>{if(!rootRef.current?.contains(document.activeElement))statusRef.current?.focus();}); + } + const onPreviewBlock=(words:string)=>setAction({kind:"refused",code:"PREVIEW",words}); async function act(intent:SeasonIntent,label:string,done:(value:T)=>string) { if(!session?.seasonAct||busy)return; @@ -84,32 +98,34 @@ export default function SeasonBram({session,tool,canSail,onSailTide,tideScope}:S const needsLedger=saved&&live.account===null; const holdings=saved?live.account:preview?{shells:preview.shells,goods:preview.goods,traded:preview.traded}:null; - return
+ return

Bram’s shelf

-

{saved?`Season ledger for ${accountId}`:"Device preview. Prices follow Bram’s formula on this device; nothing here is recorded."}

+

{saved?`Bram’s ledger for ${accountId}`:"Device preview · not recorded"}

- {holdings&&

{holdings.shells} Shells{holdings.goods[0]} glass{holdings.goods[1]} reed{!saved&&Sample haul of {haulLine(PREVIEW_SAMPLE)} for the preview}

} {live.error&&

{live.error}

} {needsLedger&&

Bram keeps a ledger page for each harbor. Open yours before your first trade, tide or wish.

-
void act({kind:"register"},"Bram is writing your page…",()=>"Your ledger page is open. Recorded.")}>Open my ledger pageHolds {STORAGE_NEAR} test NEAR as its storage deposit
+
void act({kind:"register"},"Bram is writing your page…",()=>"Your ledger page is open. Recorded.")}>Open my ledger pageHolds {STORAGE_NEAR} test NEAR as its storage deposit
} -
+
+

Today’s haul

+ +
+ {holdings&&

{holdings.shells} Shells{holdings.goods[0]} glass{holdings.goods[1]} reed{!saved&&Sample haul of {haulLine(PREVIEW_SAMPLE)} for the preview}

} +
{TABS.map(([id,label],i)=>)}
{openRequest&&action.kind!=="pending"&&

{OPEN_REQUEST}

} - +
{tab==="shelf"&&{setPreview(next);writePreview(next);setAction({kind:"confirmed",value:null});setConfirmedText(text);}} - onPreviewBlock={words=>setAction({kind:"refused",code:"PREVIEW",words})} - onResetPreview={()=>{const seeded=seedPreview(live.shelf);setPreview(seeded);writePreview(seeded);setAction({kind:"idle"});}} + onPreview={onPreview} onPreviewBlock={onPreviewBlock} + onResetPreview={()=>{const seeded={...seedPreview(live.shelf),docked:preview?.docked};setPreview(seeded);setPreviewSaved(writePreview(seeded));setAction({kind:"idle"});}} act={act}/>} - {tab==="tide"&&} {tab==="wish"&&}
; @@ -120,14 +136,14 @@ const tradeText=(t:Trade)=>`${t.side==="buy"?"Bought":"Sold"} ${t.qty} ${goodNam function Stepper({value,min,max,onChange,label}:{value:number;min:number;max:number;onChange:(n:number)=>void;label:string}) { return
- onChange(value-1)}>− + onChange(value-1)}> {value} - =max} onPress={()=>onChange(value+1)}>+ + =max} onPress={()=>onChange(value+1)}>
; } -function Shelf({live,saved,registered,busy,preview,onPreview,onPreviewBlock,onResetPreview,act}:{live:Live;saved:boolean;registered:boolean;busy:boolean;preview:PreviewMarket|null; - onPreview:(m:PreviewMarket,text:string)=>void;onPreviewBlock:(words:string)=>void;onResetPreview:()=>void;act:Act}) { +export function Shelf({live,saved,registered,busy,preview,onPreview,onPreviewBlock,onResetPreview,act}:{live:Live;saved:boolean;registered:boolean;busy:boolean;preview:PreviewMarket|null; + onPreview:(m:PreviewMarket,text:string,unsavedText?:string)=>void;onPreviewBlock:(words:string)=>void;onResetPreview:()=>void;act:Act}) { const [qty,setQty]=useState>({glass:1,reed:1}); const till=saved?live.shelf?.till:preview?.till; if(!live.shelf&&!preview)return

Reading Bram’s shelf…

; @@ -150,56 +166,75 @@ function Shelf({live,saved,registered,busy,preview,onPreview,onPreviewBlock,onRe side==="buy"?"Bram is wrapping your goods…":"Bram is counting out Shells…",tradeText); } return
- -

{good==="glass"?"Sea glass":"Reed bundles"} {view.stock} on the shelf

-
Bram sells at
{view.buy_price}
Bram pays
{view.sell_price}
-

{reasonLine({...view,buy_price:view.buy_price},till??0)}

-
- setQty(q=>({...q,[good]:v}))}/> -
trade("buy")}>Buy {n}{buyBlock??`costs ${buy?quoteLine(buy):"…"}`}
-
trade("sell")}>Sell {n}{sellBlock??`pays ${quoteLine(sell)}`}
+ setQty(q=>({...q,[good]:v}))}/> +
+
+ +
Bram sells at
{view.buy_price}
+ trade("buy")}>Buy {n} + {buyBlock??`costs ${buy?quoteLine(buy):"…"}`} +
+
+ +
Bram pays
{view.sell_price}
+ trade("sell")}>Sell {n} + {sellBlock??`pays ${quoteLine(sell)}`} +
-
+
How Bram prices this

{reasonLine({...view,buy_price:view.buy_price},till??0)}

; })} -

{saved?"Each trade is priced unit by unit and refused if any unit moves past the quote shown.":"Prices here use the same formula as Bram’s ledger, starting from the shelf as last read."}

+ {saved&&

Each trade is priced unit by unit and refused if any unit moves past the quote shown.

} {!saved&&} ; } -function Tide({live,saved,registered,busy,tool,canSail,onSail,scope,act}:{live:Live;saved:boolean;registered:boolean;busy:boolean;tool:"rope"|"lantern";canSail:boolean;onSail:(tool:"rope"|"lantern")=>void;scope:string;act:Act}) { - const today=live.today,[choice,setChoice]=useState(tool); - const [returns]=useState(()=>scope==="preview"?readTide(scope):[...readTide(scope),...readTide("preview")]); - if(!today)return

Reading today’s tide…

; - const sailable=today.content_version==="first_light_v2"; +export function TodayHaul({live,saved,registered,busy,preview,scope,run,primary=true,onOpenTide,onPreview,onPreviewBlock,act}:{live:Live;saved:boolean;registered:boolean;busy:boolean;preview:PreviewMarket|null;scope:string;run?:DayResult|null;primary?:boolean;onOpenTide:()=>void; + onPreview:(m:PreviewMarket,text:string,unsavedText?:string)=>void;onPreviewBlock:(words:string)=>void;act:Act}) { + if(run!==undefined&&!saved)return ; + const today=live.today; + if(!today)return

Reading Bram’s ledger…

; const minted=saved?today.minted_today:null; + if(minted)return

Bram shelved {haulLine(minted.goods)} today: {scoreLine(minted)}.

; + if(today.content_version!=="first_light_v2")return

Bram shelves Beacon Court hauls every other day, and today isn’t one. Keep today’s find; he can shelve it tomorrow.

; + if(!saved&&preview?.docked===deviceDay())return

Today’s haul is on Bram’s shelf. He takes one a day; bring another find tomorrow.

; + const returns=scope==="preview"?readTide(scope):[...readTide(scope),...readTide("preview")]; const candidates=returns.map(r=>({r,c:claimable(today,{tool:r.tool,commands:r.commands,contentVersion:r.contentVersion})})).filter(x=>x.c); - const mapping=today.mapping.map(([item,good])=>`${item} → ${good??"nothing"}`).join(" · "); + const value=(goods:[number,number])=>GOODS.reduce((n,g,i)=>n+goods[i]!*(live.shelf?.goods.find(s=>s.good===g)?.price_fp??0),0); + candidates.sort((a,b)=>value(b.c!.goods)-value(a.c!.goods)); + if(!candidates.length)return <>

Bring a find home from today’s tide and Bram will shelve it.

; return <> -

{sailable?"Beacon Court":"The old First Light route"}

-

Every day’s tide is a fresh outing from the beacon with nothing banked. The first haul you dock each day becomes goods.

-
Cargo to goods
{mapping}
Best haul
{bestHaulLine(today)}
- {saved&&

{minted?<>Docked today with {haulLine(minted.goods)}: {scoreLine(minted)}.:"Not docked yet today."}

} - {!sailable&&

This route belongs to the first edition, and the harbor only sails Beacon Court now, so today’s tide cannot be sailed or docked from here. Beacon Court comes back with the next day’s tide.

} - {sailable&&!minted&&
Bring one tool - {(["rope","lantern"] as const).map(t=>)} - onSail(choice)}>Sail today’s tide -

Your harbor’s own finds stay as they are. This outing’s haul is kept here for docking.

-
} - {candidates.length>0&&!minted&&
-

Ready to dock

- {candidates.map(({r,c})=>
- void act({kind:"claim",contentVersion:r.contentVersion,tool:r.tool,commands:r.commands},"The harbor is replaying Mochi’s steps…",m=>`Docked ${haulLine(m.goods)}: ${scoreLine(m)}. Recorded.`)}>Dock this haul - {r.tool==="rope"?"Rope":"Lantern"} outing · {haulLine(c!.goods)} -
)} - {!saved&&

Docking a haul needs your saved harbor. Sign in from the menu.

} -
} - {!candidates.length&&returns.length>0&&!minted&&

The tide returns kept here would not dock today: they are from the other route, came home empty, or did not reach the dock.

} + {candidates.map(({r,c},i)=>
+ + { + if(!saved){const result=previewDock(preview!,c!.goods);if("block"in result)onPreviewBlock(result.block);else onPreview(result.market,`Shelved on this device: ${haulLine(c!.goods)}. Not recorded.`,`Shelved for this visit: ${haulLine(c!.goods)}. Not recorded.`);return;} + void act({kind:"claim",contentVersion:r.contentVersion,tool:r.tool,commands:r.commands},"The harbor is replaying Mochi’s steps…",m=>`Shelved ${haulLine(m.goods)}: ${scoreLine(m)}. Recorded.`); + }}>Shelve {haulLine(c!.goods)} + {r.tool==="rope"?"Rope":"Lantern"} · {dayLabel(deviceDay(Date.parse(r.savedAt)))} +
)} ; } -function WishTab({live,saved,registered,hasPet,busy,act}:{live:Live;saved:boolean;registered:boolean;hasPet:boolean;busy:boolean;act:Act}) { +/** A device harbor's daily haul is the tide run's: reed and glass up to three each, shelved on this device. Pearls stay with Mochi. */ +function RunHaul({run,busy,preview,shelf,primary,onOpenTide,onPreview,onPreviewBlock}:{run:DayResult|null;busy:boolean;preview:PreviewMarket|null;shelf:ShelfView|null;primary:boolean;onOpenTide:()=>void; + onPreview:(m:PreviewMarket,text:string,unsavedText?:string)=>void;onPreviewBlock:(words:string)=>void}) { + if(preview?.docked===deviceDay())return

Today’s haul is on Bram’s shelf. He takes one a day; bring another find tomorrow.

; + if(!run)return <>

Sail today’s tide and bring something home. Bram shelves reed and glass, up to three of each a day.

; + const goods=shelfGoods(run),pearls=haulCount(run).pearl,keep=pearls?`Mochi keeps the ${pearls===1?"pearl":`${pearls} pearls`}.`:""; + if(!goods[0]&&!goods[1])return

Today’s tide brought no reed or glass.{keep&&` ${keep}`}

; + return
+ +

From today’s tide run: {resultLine(run)}.

+ { + const result=previewDock(preview??seedPreview(shelf),goods); + if("block"in result)onPreviewBlock(result.block);else onPreview(result.market,`Shelved on this device: ${haulLine(goods)}. Not recorded.`,`Shelved for this visit: ${haulLine(goods)}. Not recorded.`); + }}>Shelve {haulLine(goods)} + {keep&&{keep}} +
; +} + +export function WishTab({live,saved,registered,hasPet,busy,act}:{live:Live;saved:boolean;registered:boolean;hasPet:boolean;busy:boolean;act:Act}) { const [good,setGood]=useState("glass"),[qty,setQty]=useState(1),[limit,setLimit]=useState(8); const status=wishStatus(live.wish,live.postcard); const shells=live.account?.shells??0,maxLimit=Math.floor(PURSE_MAX/qty),block=wishBlock(limit,qty,shells); @@ -209,15 +244,15 @@ function WishTab({live,saved,registered,hasPet,busy,act}:{live:Live;saved:boolea

{status.kind==="waiting"?<>Mochi is waiting for {status.wish.qty} {goodName(status.wish.good,status.wish.qty)} at up to {status.wish.limit} Shells each. Her purse holds {status.wish.purse} Shells. :status.kind==="filled"?"Mochi’s last wish was filled. Her postcard is below.":status.kind==="cancelled"?"Mochi’s last wish was taken back. Her postcard is below.":"Mochi has no wish waiting. She can hold up to 24 Shells in her purse for one."}

- {!saved?

Mochi’s wish lives in your saved harbor. Sign in from the menu to set one.

:!hasPet?

Bring Mochi home in your saved harbor before setting a wish.

:<> - {status.kind==="waiting"&&
void act({kind:"cancel-wish"},"Taking the wish back…",c=>`Wish taken back; ${c.refunded} Shells returned. Recorded.`)}>Take the wish backReturns {status.wish.purse} Shells
} + {!saved?

Mochi’s wishes need a saved harbor.

:!hasPet?

Bring Mochi home in your saved harbor before setting a wish.

:<> + {status.kind==="waiting"&&
void act({kind:"cancel-wish"},"Taking the wish back…",c=>`Wish taken back; ${c.refunded} Shells returned. Recorded.`)}>Take the wish backReturns {status.wish.purse} Shells
}
{status.kind==="waiting"?"Replace the wish":"Set a wish"} Good
{GOODS.map(g=>)}
How many
{Array.from({length:WISH_QTY_MAX},(_,i)=>i+1).map(q=>)}
Highest price per unit
-
void act({kind:"set-wish",good,limit,qty},"Bram is checking Mochi’s papers…", - r=>r.status==="filled"?`Filled at once: ${r.postcard?postcardLines(r.postcard)[1]:""} Recorded.`:r.status==="waiting"?`Mochi’s wish is waiting. Her purse holds ${r.wish?.purse??limit*qty} Shells. Recorded.`:"Recorded.")}>Set Mochi’s wish +
void act({kind:"set-wish",good,limit,qty},"Bram is checking Mochi’s papers…", + r=>r.status==="filled"?`Filled at once: ${r.postcard?postcardLines(r.postcard)[1]:""} Recorded.`:r.status==="waiting"?`Mochi’s wish is waiting. Her purse holds ${r.wish?.purse??limit*qty} Shells. Recorded.`:"Recorded.")}>Set Mochi’s wish {block??`Purse ${limit*qty} of ${PURSE_MAX} Shells${status.kind==="waiting"?"; the old purse comes back once the new wish is placed":""}`}
{live.shelf&&

Bram sells {goodName(good,2)} at {live.shelf.goods.find(g=>g.good===good)?.buy_price} now. A wish whose limit covers every unit fills at once; otherwise a later trade that brings the price within it does.

}
diff --git a/web/src/season/data.test.ts b/web/src/season/data.test.ts index 03578fc..1f3b14b 100644 --- a/web/src/season/data.test.ts +++ b/web/src/season/data.test.ts @@ -1,8 +1,67 @@ -import { expect, test } from "bun:test"; -import { keepTide, previewTrade, readPreview, readTide, rollPreview, seasonView, seedPreview, writePreview, type TideReturn } from "./data"; +import { expect, spyOn, test } from "bun:test"; +import { SEASON_ROOT, keepTide, previewDock, previewTrade, readPreview, readTide, rollPreview, seasonView, seedPreview, shelfNote, shelvesBeaconCourt, writePreview, type TideReturn } from "./data"; +import { readTideLog, readTidePending, recordTide, writeTidePending } from "../tide/log"; const memory=()=>{const m=new Map();return {getItem:(k:string)=>m.get(k)??null,setItem:(k:string,v:string)=>{m.set(k,v);}};}; +test("preview writes report whether the browser kept the shelf",()=>{ + const market=seedPreview(null,20771),store=memory(); + const blocked={setItem(){throw new DOMException("Site data blocked","SecurityError");}}; + expect(writePreview(market,blocked)).toBe(false); + expect(writePreview(market,store)).toBe(true); + expect(readPreview(store,20771)).toEqual(market); +}); + +test("blocked site data leaves tide and shelf readers empty and preserves writer failure contracts",()=>{ + const previous=Object.getOwnPropertyDescriptor(globalThis,"localStorage"),blocked=new DOMException("Site data blocked","SecurityError"); + Object.defineProperty(globalThis,"localStorage",{configurable:true,get(){throw blocked;}}); + try{ + expect(readTideLog("preview")).toEqual([]);expect(readTidePending("preview")).toBeNull(); + expect(readPreview()).toBeNull();expect(readTide("preview")).toEqual([]); + expect(writePreview(seedPreview(null))).toBe(false); + for(const pending of [null,{day:20771,late:false}])expect(()=>writeTidePending("preview",pending)).not.toThrow(); + expect(()=>recordTide("preview",{day:20771,tool:"rope",commands:["return"],late:false})).toThrow(blocked); + expect(()=>keepTide("preview",{id:"blocked",contentVersion:"first_light_v2",tool:"rope",commands:["return"],cargo:[],outcome:"returned",savedAt:"t"})).toThrow(blocked); + }finally{if(previous)Object.defineProperty(globalThis,"localStorage",previous);else Reflect.deleteProperty(globalThis,"localStorage");} +}); + +test("a stalled shelf read aborts after its eight-second budget",async()=>{ + const timeout=AbortSignal.timeout.bind(AbortSignal),timer=spyOn(AbortSignal,"timeout").mockImplementation(ms=>{expect(ms).toBe(8000);return timeout(1);}); + const stalled=(async(_url:unknown,init?:RequestInit)=>new Promise((_resolve,reject)=>{ + const signal=init?.signal;if(!signal){reject(Error("Missing abort signal"));return;} + signal.addEventListener("abort",()=>reject(signal.reason),{once:true}); + })) as typeof fetch; + try{await expect(seasonView("get_shelf",{},stalled)).rejects.toMatchObject({name:"TimeoutError"});} + finally{timer.mockRestore();} +}); + +test("a haul joins the preview satchel once a day, with another allowed after the day rolls", () => { + const current={...seedPreview(null,20771),traded:[20,0] as [number,number],till:200}; + const docked=previewDock(current,[1,1],20771);if("block"in docked)throw Error(docked.block); + expect(docked.market).toMatchObject({goods:[2,3],docked:20771}); + expect(current.goods).toEqual([1,2]);expect(current).not.toHaveProperty("docked"); + expect(previewDock(docked.market,[1,0],20771)).toEqual({block:"Bram has already shelved a haul today."}); + const next=previewDock(docked.market,[0,1],20772);if("block"in next)throw Error(next.block); + expect(next.market).toMatchObject({day:20772,goods:[2,4],docked:20772,traded:[0,0],till:260}); +}); + +test("preview saves accept a valid docking day, discard invalid ones and retain older saves", () => { + const store=memory(),market=seedPreview(null,20771); + writePreview(market,store);expect(readPreview(store,20771)).toEqual(market); + for(const docked of [0,20771]){writePreview({...market,docked},store);expect(readPreview(store,20771)?.docked).toBe(docked);} + for(const docked of [-1,1.5,Number.MAX_SAFE_INTEGER+1,"20771",null]){ + store.setItem("familiar.season.preview.v1",JSON.stringify({...market,docked})); + expect(readPreview(store,20771)).toEqual(market); + } +}); + +test("the shelf note follows the contract's alternating Beacon Court days and stays quiet for empty cargo", () => { + expect(shelvesBeaconCourt(20771)).toBe(true);expect(shelvesBeaconCourt(20772)).toBe(false); + expect(shelfNote({cargo:[],day:20771})).toBe("");expect(shelfNote({cargo:[],day:20772})).toBe(""); + expect(shelfNote({cargo:["lens"],day:20771})).toBe(" Bram can shelve it today."); + expect(shelfNote({cargo:["moth"],day:20772})).toBe(" Bram can shelve it tomorrow."); +}); + test("the device preview prices like the contract and refuses what the contract refuses", () => { const m=seedPreview(null); expect(m).toMatchObject({till:300,shells:0,goods:[1,2]}); @@ -45,7 +104,7 @@ test("views read final state from season. and decode the result bytes", as let body:Record={}; const fetcher=(async(_url:string,init:RequestInit)=>{body=JSON.parse(String(init.body));return new Response(JSON.stringify({result:{result:[...new TextEncoder().encode('{"day":1}')]}}));}) as unknown as typeof fetch; expect(await seasonView<{day:number}>("get_today",{account_id:null},fetcher)).toEqual({day:1}); - expect(body).toMatchObject({method:"query",params:{request_type:"call_function",finality:"final",account_id:"season.familiar-game.testnet",method_name:"get_today"}}); + expect(body).toMatchObject({method:"query",params:{request_type:"call_function",finality:"final",account_id:"season."+SEASON_ROOT,method_name:"get_today"}}); const failing=(async()=>new Response(JSON.stringify({error:{}}))) as unknown as typeof fetch; await expect(seasonView("get_shelf",{},failing)).rejects.toThrow("could not be read"); }); diff --git a/web/src/season/data.ts b/web/src/season/data.ts index e18001b..1fb5934 100644 --- a/web/src/season/data.ts +++ b/web/src/season/data.ts @@ -7,7 +7,7 @@ export const SEASON_CONTRACT = `season.${SEASON_ROOT}`; const RPC = import.meta.env.VITE_NEAR_RPC_URL || "https://test.rpc.fastnear.com"; export async function seasonView(method:string, args:Record={}, fetcher:typeof fetch=fetch):Promise { - const response=await fetcher(RPC,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:"season",method:"query", + const response=await fetcher(RPC,{method:"POST",signal:AbortSignal.timeout(8000),headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:"season",method:"query", params:{request_type:"call_function",finality:"final",account_id:SEASON_CONTRACT,method_name:method,args_base64:btoa(JSON.stringify(args))}})}); const body=await response.json() as {result?:{result?:number[]};error?:unknown}; if(!response.ok||!body.result?.result)throw Error("Bram’s shelf could not be read just now."); @@ -16,9 +16,12 @@ export async function seasonView(method:string, args:Record={ // ---------- device preview ---------- -export interface PreviewMarket { version:1;day:number;shelf:{stock:number;heat_fp:number}[];till:number;shells:number;goods:[number,number];traded:[number,number] } +export interface PreviewMarket { version:1;day:number;docked?:number;shelf:{stock:number;heat_fp:number}[];till:number;shells:number;goods:[number,number];traded:[number,number] } /** The device's day, on the contract's boundary (floor of UTC time / 24 h). */ export const deviceDay=(now=Date.now())=>Math.floor(now/86_400_000); +// contracts/season/src/lib.rs:88, court_of: odd days replay first_light_v2 (Beacon Court). +export const shelvesBeaconCourt=(day:number):boolean=>day%2===1; +export const shelfNote=({cargo,day}:{cargo:readonly string[];day:number}):string=>cargo.length?` Bram can shelve it ${shelvesBeaconCourt(day)?"today":"tomorrow"}.`:""; const TILL_CAP=300,TILL_REFILL=60,HEAT_HALVINGS_CAP=64; /** The contract's lazy day effects: heat halves per day, the till refills toward its cap, daily limits reset. */ export function rollPreview(m:PreviewMarket,day=deviceDay()):PreviewMarket { @@ -33,13 +36,19 @@ export const PREVIEW_SAMPLE:[number,number]=[1,2]; export function seedPreview(shelf:ShelfView|null,day=deviceDay()):PreviewMarket { return {version:1,day:shelf?.day??day,shelf:GOODS.map(g=>{const v=shelf?.goods.find(x=>x.good===g);return {stock:v?.stock??40,heat_fp:v?.heat_fp??0};}),till:shelf?.till??300,shells:0,goods:[...PREVIEW_SAMPLE],traded:[0,0]}; } -export function readPreview(store:Pick=localStorage,day=deviceDay()):PreviewMarket|null { - try{const v=JSON.parse(store.getItem(PREVIEW_KEY)??"null") as PreviewMarket; +export function readPreview(store?:Pick,day=deviceDay()):PreviewMarket|null { + try{const v=JSON.parse((store??localStorage).getItem(PREVIEW_KEY)??"null") as PreviewMarket; const n=(x:unknown)=>Number.isSafeInteger(x)&&(x as number)>=0; if(v?.version!==1||v.shelf?.length!==2||!v.shelf.every(s=>n(s.stock)&&n(s.heat_fp))||![v.till,v.shells,...v.goods,...v.traded].every(n))return null; - return rollPreview({...v,day:n(v.day)?v.day:day},day);}catch{return null;} + const {docked,...market}=v; + return rollPreview({...market,day:n(v.day)?v.day:day,...(n(docked)?{docked}:{})},day);}catch{return null;} +} +export function writePreview(value:PreviewMarket,store?:Pick):boolean {try{(store??localStorage).setItem(PREVIEW_KEY,JSON.stringify(value));return true;}catch{return false;}} +export function previewDock(current:PreviewMarket,goods:[number,number],day=deviceDay()):{market:PreviewMarket}|{block:string} { + const m=rollPreview(current,day); + if(m.docked===day)return {block:"Bram has already shelved a haul today."}; + return {market:{...m,goods:[m.goods[0]+goods[0],m.goods[1]+goods[1]],docked:day}}; } -export function writePreview(value:PreviewMarket,store:Pick=localStorage){try{store.setItem(PREVIEW_KEY,JSON.stringify(value));}catch{/* The preview keeps running in memory. */}} export const previewView=(m:PreviewMarket,good:Good):Pick=>{ const i=GOODS.indexOf(good),s=m.shelf[i]!; return {good,stock:s.stock,heat_fp:s.heat_fp,target:40,base:good==="glass"?8:4,buy_price:quoteBuy(good,s,1)?.units[0]??0,sell_price:quoteSell(good,s,1).units[0]!}; @@ -62,11 +71,12 @@ export const previewAccount=(m:PreviewMarket):Pick`familiar.season.tide.v1:${scope}`; -export function readTide(scope:string,store:Pick=localStorage):TideReturn[] { - try{const v=JSON.parse(store.getItem(tideKey(scope))??"[]");return Array.isArray(v)?v.filter(r=>r&&typeof r.id==="string"&&Array.isArray(r.commands)&&r.commands.every((c:unknown)=>typeof c==="string")&&(r.tool==="rope"||r.tool==="lantern")):[];}catch{return [];} +export function readTide(scope:string,store?:Pick):TideReturn[] { + try{const v=JSON.parse((store??localStorage).getItem(tideKey(scope))??"[]");return Array.isArray(v)?v.filter(r=>r&&typeof r.id==="string"&&Array.isArray(r.commands)&&r.commands.every((c:unknown)=>typeof c==="string")&&(r.tool==="rope"||r.tool==="lantern")):[];}catch{return [];} } /** Keeps the latest ten tide returns for this harbor; the oldest drop off first. */ -export function keepTide(scope:string,entry:TideReturn,store:Pick=localStorage) { +export function keepTide(scope:string,entry:TideReturn,store?:Pick) { + store=store??localStorage; const next=[entry,...readTide(scope,store).filter(r=>r.id!==entry.id)].slice(0,10),text=JSON.stringify(next); store.setItem(tideKey(scope),text);if(store.getItem(tideKey(scope))!==text)throw Error("Today’s tide return could not be saved on this device."); } diff --git a/web/src/season/model.ts b/web/src/season/model.ts index 21e3922..3924564 100644 --- a/web/src/season/model.ts +++ b/web/src/season/model.ts @@ -108,7 +108,7 @@ export const REFUSALS:Record = { ERR_NOT_REGISTERED:"Open your page in Bram’s ledger first.", ERR_STORAGE_DEPOSIT:"The ledger page needs its full storage deposit.", ERR_STORAGE:"Your ledger page has no room for another of Mochi’s records.", - ERR_ALREADY_MINTED:"You have already docked today’s tide. Come back tomorrow.", + ERR_ALREADY_MINTED:"Bram has already shelved a haul today. Come back tomorrow.", ERR_WRONG_COURT:"That return is from a different day’s tide.", ERR_RULES_VERSION:"That return follows different rules.", ERR_COMMAND_BOUND:"That return has too many moves for today’s tide.", diff --git a/web/src/season/season.css b/web/src/season/season.css index 0519a55..b4aaa0a 100644 --- a/web/src/season/season.css +++ b/web/src/season/season.css @@ -1,68 +1,116 @@ -.exp-panel.exp-panel-season{width:min(560px,100%)} -.ss{--ss-ink:#2c4335;--ss-soft:#53442b;--ss-line:#c9ad7c;--ss-card:#fbf0d6;--ss-sea:#2f5c4c;margin-top:18px;padding-top:16px;border-top:1px solid var(--ss-line);color:var(--ss-ink)} -.ss h3,.ss h4{font-family:"Fraunces Variable",serif;letter-spacing:-.02em;margin:0} -.ss h3{font-size:22px;line-height:1.15} -.ss h4{font-size:17px;line-height:1.2} -.ss p{font-size:15px;line-height:1.45} -.ss-head{display:flex;gap:12px;align-items:center;margin-bottom:10px} +.exp-panel.exp-panel-season,.ss{ + --ss-card:#fbf3e2; + --ss-ink:#263e32; + --ss-soft:#4f5d52; + --ss-line:#e6d6b4; + --ss-sea:#2b5f4d; + --ss-radius:22px; + --ss-elevation:0 14px 34px rgba(64,40,18,.20),0 2px 6px rgba(64,40,18,.12); + color:var(--ss-ink); + font-family:"Figtree Variable",sans-serif; + accent-color:var(--ss-sea); + scrollbar-color:#8b7957 var(--ss-card); +} +.exp-panel.exp-panel-season{width:min(560px,100%);background:var(--ss-card);border:0;outline:0;border-radius:var(--ss-radius);box-shadow:var(--ss-elevation)} +.ss{margin-top:24px;padding-top:20px;border-top:1px solid var(--ss-line)} +.ss ::selection{background:#d6e4cf;color:var(--ss-ink)} +.ss h3,.ss h4{font-family:"Fraunces Variable",serif;letter-spacing:-.02em;margin:0;text-wrap:balance} +.ss h3{font-size:26px;line-height:1.15} +.ss h4{font-size:19px;line-height:1.25} +.ss p{font-size:15px;line-height:1.5} +.ss-head{display:flex;gap:12px;align-items:center;margin-bottom:18px} .ss-head img{flex:0 0 auto;filter:drop-shadow(0 3px 4px #4a35202e)} -.ss-head p{margin:3px 0 0} +.ss-head p{margin:6px 0 0} .ss-mode{font-size:13px!important;color:var(--ss-soft);overflow-wrap:anywhere} -.ss-mode[data-mode=preview]{display:inline-block;padding:4px 9px;border-radius:7px;background:#ecd6a6;color:#4a3519;font-weight:650} -.ss-holdings{display:flex;flex-wrap:wrap;align-items:center;gap:6px 14px;margin:0 0 12px;padding:8px 12px;background:var(--ss-card);border-radius:10px;font-variant-numeric:tabular-nums} +.ss-mode[data-mode=preview]{display:inline-block;padding:5px 10px;border-radius:999px;background:#e8dcc0;color:var(--ss-ink);font-weight:650} +.ss-holdings{display:flex;flex-wrap:wrap;align-items:center;gap:6px 14px;margin:0 0 20px;padding:12px 0;border-block:1px solid var(--ss-line);font-variant-numeric:tabular-nums} .ss-holdings small{flex-basis:100%;font-size:12px;color:var(--ss-soft)} -.ss-holdings b{font-size:17px} -.ss-ledger{margin:0 0 14px;padding:12px;border-radius:12px;background:#e9dcb4} -.ss-tabs{display:flex;gap:4px;margin:4px 0 6px;padding:4px;background:#e5cf9f;border-radius:12px} -.exp-game .ss-tabs button{flex:1;min-height:44px;padding:8px 6px;font-size:14px;background:transparent;border-color:transparent;box-shadow:none;color:#3f3420} -.exp-game .ss-tabs button[aria-selected=true]{background:#fbf0d6;border-color:#b99561;color:var(--ss-ink);box-shadow:0 2px 5px #4a35201f} -.ss-status{min-height:22px;margin:6px 0 8px!important;font-size:14px!important;font-weight:650} -.ss-status[data-state=pending]{color:var(--ss-sea)} -.ss-status[data-state=confirmed]{color:#24533f} -.ss-status[data-state=refused],.ss-status[data-state=uncertain]{color:#7a3020} -.ss-problem{color:#7a3020} -.ss-panel{display:grid;gap:12px} +.ss-holdings b{font-size:18px} +.ss-ledger{margin:0 0 20px} +.ss-ledger p{margin:0 0 12px} +.ss button{display:inline-flex;align-items:center;justify-content:center;gap:10px;min-height:48px;min-width:44px;max-width:100%;padding:10px 20px;border:1.5px solid #d6c29b;border-radius:999px;background:#fffaf0;color:var(--ss-ink);box-shadow:none;font:600 17px/1.25 "Fraunces Variable",serif;text-align:center;cursor:pointer;overflow-wrap:anywhere} +.ss button:hover:not(:disabled){background:#fff3dc;color:var(--ss-ink)} +.ss button:active:not(:disabled):not([aria-disabled=true]){transform:translateY(1px)} +.ss button svg{width:18px;height:18px;flex:0 0 auto} +.ss button.ss-primary{min-height:52px;padding:12px 26px;border:0;background:var(--ss-sea);color:#fff6e2;box-shadow:inset 0 1px 0 #5f9a83,inset 0 -3px 0 #1d4436,0 6px 14px rgba(31,68,54,.28);font-size:18px;font-weight:650} +.ss button.ss-primary svg{width:20px;height:20px} +.ss button.ss-primary:hover:not(:disabled){background:var(--ss-sea);color:#fff6e2} +.ss button.ss-primary:active:not(:disabled):not([aria-disabled=true]){box-shadow:inset 0 1px 0 #5f9a83,inset 0 -1px 0 #1d4436,0 6px 14px rgba(31,68,54,.28)} +.ss :focus-visible{outline:3px solid var(--ss-sea);outline-offset:3px} +.ss-tabs{display:flex;gap:4px;margin:4px 0 6px;padding:4px;background:#e8dcc0;border-radius:999px} +.ss-tabs button{flex:1;padding:8px 10px;font:600 15px/1.3 "Figtree Variable",sans-serif;background:transparent;border-color:transparent} +.ss-tabs button[aria-selected=true],.ss-tabs button[aria-selected=true]:hover{background:#fffaf0;color:var(--ss-ink)} +.ss-status{min-height:22px;margin:8px 0 14px!important;font-size:14px!important;font-weight:650} +.ss-status[data-state=pending],.ss-status[data-state=confirmed]{color:var(--ss-sea)} +.ss-status[data-state=refused],.ss-status[data-state=uncertain],.ss-problem{color:#7a3020} +.ss-panel{display:grid;gap:20px} .ss-panel>p{margin:0} .ss-till{margin:0!important;font-variant-numeric:tabular-nums} -.ss-good{display:grid;grid-template-columns:56px 1fr;gap:12px;padding:12px;background:var(--ss-card);border-radius:14px;box-shadow:0 2px 8px #4a352014} -.ss-good img{filter:drop-shadow(0 2px 3px #4a352030)} -.ss-good h4 span{font-family:"Figtree Variable",sans-serif;font-size:13px;font-weight:600;color:var(--ss-soft);margin-left:6px;font-variant-numeric:tabular-nums} -.ss-good-body{min-width:0} -.ss-prices{display:flex;flex-wrap:wrap;gap:2px 18px;margin:6px 0} -.ss-prices div{display:flex;gap:6px;align-items:baseline;white-space:nowrap} -.ss-prices dt{font-size:13px;color:var(--ss-soft)} -.ss-prices dd{margin:0;font-weight:800;font-size:18px;font-variant-numeric:tabular-nums} +.ss-good{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:12px;align-items:center;min-width:0} +.ss-good h4 span{display:block;font-family:"Figtree Variable",sans-serif;font-size:13px;line-height:1.5;font-weight:600;color:var(--ss-soft);margin-top:4px;font-variant-numeric:tabular-nums} +.ss-trade-cards{grid-column:1/-1;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px} +.ss-trade-card{display:grid;grid-template-columns:56px minmax(0,1fr);align-items:center;gap:10px 8px;min-width:0;padding:16px;background:var(--ss-card);border:0;border-radius:var(--ss-radius);box-shadow:var(--ss-elevation)} +.ss-trade-card>img,.ss-haul-art img{filter:drop-shadow(0 2px 3px #4a352030)} +.ss-trade-card>button,.ss-trade-card>.ss-info{grid-column:1/-1;width:100%} +.ss-trade-card>.ss-info{align-self:start;min-height:40px} +.ss-prices{margin:0;font-variant-numeric:tabular-nums} +.ss-prices dt{font-size:13px;line-height:1.35;color:var(--ss-soft)} +.ss-prices dd{margin:2px 0 0;font-weight:750;font-size:19px} .ss-prices dd::after{content:" Shells";font-size:12px;font-weight:600} -.ss .ss-reason{font-size:13px;line-height:1.4;color:var(--ss-soft);margin:0 0 10px} -.ss-trade{display:grid;gap:6px} +.ss .ss-pricing{grid-column:1/-1;margin:0} +.ss-pricing summary{min-height:44px;min-width:44px;padding:12px 0;cursor:pointer;font-size:15px;font-weight:600;text-decoration:underline;text-underline-offset:3px;color:var(--ss-soft)} +.ss .ss-reason{font-size:13px;line-height:1.5;color:var(--ss-soft);margin:0 0 8px} .ss-act{display:flex;align-items:center;gap:10px;flex-wrap:wrap} -.ss-act>button{flex:0 0 auto;min-width:96px} -.ss-info{font-size:13px;color:var(--ss-soft);font-variant-numeric:tabular-nums;flex:1 1 140px} -.ss-stepper{display:inline-flex;align-items:center;gap:4px;margin-bottom:2px} -.exp-game .ss-stepper button{width:44px;padding:0;font-size:20px;line-height:1} -.ss-stepper output{min-width:36px;text-align:center;font-weight:800;font-size:18px;font-variant-numeric:tabular-nums} +.ss-act>button{flex:0 1 auto;min-width:96px} +.ss-info{font-size:13px;line-height:1.5;color:var(--ss-soft);font-variant-numeric:tabular-nums;flex:1 1 140px} +.ss-stepper{display:inline-flex;align-items:center;gap:2px} +.ss-stepper button{width:44px;min-height:44px;padding:0} +.ss-stepper output{min-width:28px;text-align:center;font-weight:750;font-size:18px;font-variant-numeric:tabular-nums} .ss .ss-note{font-size:13px;color:var(--ss-soft)} -.exp-game .ss-link{background:transparent;border:0;box-shadow:none;padding:8px 4px;text-decoration:underline;text-underline-offset:3px;font-weight:650} -.ss-court{font-size:20px!important} -.ss-facts{display:grid;gap:6px;margin:0;padding:10px 12px;background:var(--ss-card);border-radius:12px} -.ss-facts div{display:grid;grid-template-columns:112px 1fr;gap:8px} -.ss-facts dt{font-size:13px;color:var(--ss-soft)} -.ss-facts dd{margin:0;font-size:14px} +.ss button.ss-link{min-height:44px;background:transparent;border:0;box-shadow:none;padding:10px 4px;text-decoration:underline;text-underline-offset:3px;font:600 15px/1.4 "Figtree Variable",sans-serif} +.ss button.ss-link:hover:not(:disabled){background:transparent;color:var(--ss-sea)} +.ss-returns{display:grid;gap:12px} +.ss-haul{margin:0 0 20px} +.ss-haul>p{margin:0} +.ss-haul-art{display:flex;align-items:center;gap:0;flex:0 0 auto} +.ss-haul-art img+img{margin-left:-18px} +.ss-haul-offer>.ss-info{flex-basis:100%} +.ss-run-haul{gap:8px 16px;min-width:0} +.ss-run-haul>.ss-haul-art{gap:16px;font-size:15px;font-weight:650;font-variant-numeric:tabular-nums} +.ss-run-haul>.ss-haul-art>span{display:inline-flex;align-items:center;gap:4px;white-space:nowrap} +.ss-run-haul>.ss-haul-art img{width:32px;height:32px;object-fit:contain} +.ss-run-haul>p{flex-basis:100%;margin:0;color:var(--ss-soft);font-size:13px} +.ss-run-haul>button{white-space:nowrap;overflow-wrap:normal} .ss-docked{font-weight:650;margin:0} -.ss-docked[data-docked=true]{color:#24533f} -.exp-panel .ss-tool,.exp-panel .ss-wish-form{margin:0;padding:12px;border:1px solid var(--ss-line);border-radius:12px;display:grid;gap:6px} -.exp-panel .ss-tool label,.exp-panel .ss-choice label{min-height:44px;padding:4px 6px} -.ss-tool>button{width:100%} -.ss-returns{display:grid;gap:8px} +.ss-docked[data-docked=true]{color:var(--ss-sea)} .ss-wish-head{display:flex;gap:12px;align-items:center} .ss-wish-head p{margin:0} +.exp-panel .ss-wish-form,.ss .ss-wish-form{margin:0;padding:0;border:0;display:grid;gap:10px;min-width:0} .ss-choice{display:flex;gap:4px 14px;flex-wrap:wrap} +.ss .ss-choice label{display:flex;align-items:center;gap:10px;min-height:44px;min-width:44px;padding:4px 6px} +.ss-choice input{width:20px;height:20px;flex:0 0 auto} .ss-choice img{margin-left:-2px} .ss-limit{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap} -.ss-postcard{display:grid;grid-template-columns:40px 1fr;gap:10px;padding:12px 14px;background:#fff7e3;border-radius:6px;box-shadow:0 3px 10px #4a35201c;transform:rotate(-.4deg)} -.ss-postcard p{font-size:14px;margin:0 0 4px} -.ss-postcard p:last-child{font-size:12px;color:var(--ss-soft);margin:0} -@media (prefers-reduced-motion:reduce){.ss-postcard{transform:none}} -@media(max-width:480px){.ss-prices{gap:12px}.ss-facts div{grid-template-columns:1fr;gap:2px}.ss-good{grid-template-columns:44px 1fr;gap:10px;padding:10px}.ss-good>img{width:44px;height:44px}.exp-game .ss-tabs button{font-size:13px;padding:6px 4px}} .ss-field{font-size:13px;font-weight:700;color:var(--ss-soft);margin-top:4px} -.exp-game .ss button[aria-disabled=true]{cursor:default;opacity:.5;box-shadow:none}.exp-game .ss button[aria-disabled=true]:hover{background:#eddbad}.exp-game .ss .exp-primary[aria-disabled=true]:hover{background:#3c6555}.ss-status:focus{outline:none}.ss-status:focus-visible{outline:3px solid #37634b;outline-offset:2px} +.ss-postcard{display:grid;grid-template-columns:40px minmax(0,1fr);gap:10px;padding:16px;background:var(--ss-card);border:0;border-radius:var(--ss-radius);box-shadow:var(--ss-elevation)} +.ss-postcard p{font-size:14px;margin:0 0 4px} +.ss-postcard p:last-child{font-size:12px;color:var(--ss-soft);margin:0;overflow-wrap:anywhere} +.ss button[aria-disabled=true]{cursor:default;background:#efe7d5;color:var(--ss-soft);box-shadow:none} +.ss button[aria-disabled=true]:hover{background:#efe7d5;color:var(--ss-soft)} +.ss button.ss-primary[aria-disabled=true],.ss button.ss-primary[aria-disabled=true]:hover{background:#d9e1d4;color:var(--ss-ink)} +.ss-status:focus{outline:none} +.ss-status:focus-visible{outline:3px solid var(--ss-sea);outline-offset:3px} +@media(pointer:coarse){.ss button.ss-primary{min-height:56px}} +@media(max-width:480px){ + .exp-panel.exp-panel-season,.ss{--ss-radius:20px} + .ss-head>img{width:56px;height:56px} + .ss h3{font-size:24px} + .ss-trade-cards{gap:10px} + .ss-trade-card{grid-template-columns:minmax(0,1fr);gap:8px;padding:14px} + .ss-trade-card>img{width:48px;height:48px} + .ss-prices dd{font-size:18px} + .ss-haul-offer>.ss-primary{flex-basis:100%;order:1} + .ss-haul-offer>.ss-info{order:2} + .ss .ss-run-haul>button{flex-basis:100%;padding-inline:12px;gap:8px;font-size:17px} +} +@media(prefers-reduced-motion:reduce){.ss button:active:not(:disabled):not([aria-disabled=true]){transform:none}} diff --git a/web/src/tide/AskIcon.test.tsx b/web/src/tide/AskIcon.test.tsx new file mode 100644 index 0000000..b2c2560 --- /dev/null +++ b/web/src/tide/AskIcon.test.tsx @@ -0,0 +1,34 @@ +import { expect, test } from "bun:test"; +import { renderToStaticMarkup } from "react-dom/server"; +import type { Ask, Style } from "./asks"; +import AskIcon, { askIcons } from "./AskIcon"; + +test("haul asks pair the matching finds and decision asks use the hourglass", () => { + expect(askIcons({ kind: "haul", haul: "lens" }, "rope")).toEqual(["/assets/ui/ask-lens.webp"]); + expect(askIcons({ kind: "haul", haul: "moth" }, "lantern")).toEqual(["/assets/ui/ask-moth.webp"]); + expect(askIcons({ kind: "haul", haul: "both" }, "rope")).toEqual(["/assets/ui/ask-lens.webp", "/assets/ui/ask-moth.webp"]); + expect(askIcons({ kind: "within", decisions: 10 }, "rope")).toEqual(["/assets/ui/ask-within.webp"]); +}); + +test("every style maps to its painted object, with no rope art for an unlit lantern", () => { + const styles: Record = { + dry: "dry", splash: "splash", coiled: "coiled", "no-wait": "no-wait", "all-marks": "all-marks", + "one-crossing": "one-crossing", "both-shells": "both-shells", "shut-left": "shut-shell", "shut-right": "shut-shell", + "bridge-left": "bridge", "bridge-center": "bridge", "bridge-right": "bridge", + }; + for (const [style, icon] of Object.entries(styles)) { + expect(askIcons({ kind: "style", style: style as Style }, "rope")).toEqual([`/assets/ui/ask-${icon}.webp`]); + } + expect(askIcons({ kind: "style", style: "coiled" }, "lantern")).toEqual([]); +}); + +test("ask art is decorative, sized, asynchronously decoded and paired when needed", () => { + for (const size of [24, 28, 32]) { + const html = renderToStaticMarkup(); + expect(html).toContain('class="tide-ask-icon tide-ask-icon-pair"'); + expect(html.match(new RegExp(`width="${size}" height="${size}" alt="" decoding="async"`, "g"))).toHaveLength(2); + expect(html).toContain('aria-hidden="true"'); + } + const unlit: Ask = { kind: "style", style: "coiled" }; + expect(renderToStaticMarkup()).toBe(""); +}); diff --git a/web/src/tide/AskIcon.tsx b/web/src/tide/AskIcon.tsx new file mode 100644 index 0000000..030c2a7 --- /dev/null +++ b/web/src/tide/AskIcon.tsx @@ -0,0 +1,24 @@ +import type { JSX } from "react"; +import type { Tool } from "../expedition/types"; +import type { Ask, Style } from "./asks"; + +const styleIcons: Record = { + dry: "dry", splash: "splash", coiled: "coiled", "no-wait": "no-wait", "all-marks": "all-marks", + "one-crossing": "one-crossing", "both-shells": "both-shells", "shut-left": "shut-shell", "shut-right": "shut-shell", + "bridge-left": "bridge", "bridge-center": "bridge", "bridge-right": "bridge", +}; + +export function askIcons(ask: Ask, tool: Tool): readonly string[] { + if (ask.kind === "style" && ask.style === "coiled" && tool === "lantern") return []; + const names = ask.kind === "haul" ? ask.haul === "both" ? ["lens", "moth"] : [ask.haul] + : [ask.kind === "within" ? "within" : styleIcons[ask.style]]; + return names.map(name => `/assets/ui/ask-${name}.webp`); +} + +export default function AskIcon({ ask, tool, size }: { ask: Ask; tool: Tool; size: number }): JSX.Element | null { + const icons = askIcons(ask, tool); + if (!icons.length) return null; + return 1 ? " tide-ask-icon-pair" : ""}`} aria-hidden="true"> + {icons.map(src => )} + ; +} diff --git a/web/src/tide/Harness.tsx b/web/src/tide/Harness.tsx new file mode 100644 index 0000000..32f5afa --- /dev/null +++ b/web/src/tide/Harness.tsx @@ -0,0 +1,72 @@ +import { useMemo, useState, type JSX } from "react"; +import { cardStatus, replayRun, solve } from "./asks"; +import { cardForDay } from "./cards"; +import { tideSummary, type TideEntry } from "./log"; +import { earlierDays, pageForDay, tidePages } from "./pages"; +import TideAsk from "./TideAsk"; +import TideHud from "./TideHud"; +import TideLog, { type LogPage } from "./TideLog"; +import TideStamp from "./TideStamp"; +import "../expedition/game.css"; +import "./tide.css"; + +export default function TideHarness(): JSX.Element { + const [sailed, setSailed] = useState(false); + const [message, setMessage] = useState(""); + const [initialPage, setInitialPage] = useState(0); + const [press, setPress] = useState(0); + const [askOpen, setAskOpen] = useState(true); + const [logOpen, setLogOpen] = useState(true); + const sample = useMemo(() => { + const card = cardForDay(20771); + const entries: TideEntry[] = [20765, 20767, 20768, 20770, 20771].map((day, i) => { + const past = cardForDay(day); + const route = i % 2 === 0 ? solve(past.tool, past.asks)! : ["return" as const]; + const returned = replayRun(past.tool, route)!; + if (returned.state.outcome !== "returned") throw new Error("The sample tide must come home."); + return { day, cardId: past.id, tool: past.tool, commands: route, + kept: cardStatus(past, returned).map(status => status === "kept") as [boolean, boolean, boolean], + decisions: returned.state.turn, outcome: "returned", late: day !== 20771, attempts: 2, + savedAt: new Date(day * 86_400_000).toISOString() }; + }); + const entry = entries.at(-1)!; + const commands = entry.commands; + const run = replayRun(card.tool, commands.slice(0, 5))!; + const pages: LogPage[] = [ + { kind: "story", id: "lens", title: "The lens comes home", subtitle: "Your first return", area: "beacon", tool: "rope", banked: [], commands: solve("rope", [{ kind: "haul", haul: "lens" }]) ?? [] }, + ...tidePages(entries), + ]; + return { card, entry, run, returned: replayRun(card.tool, commands)!, entries, pages }; + }, []); + const onSail = (day: number) => setMessage(`Sample sail selected: day ${day}.`); + return
+

Development harness. Sample data only.

+
+
+

Stamps

+
{[52, 56, 72, 84, 112, 160].map(size =>
+ {size} px + 0} /> + 0} /> +
)}
+ +
+
+
Beacon CourtLow tide · Sample outing
+ +
+ {!askOpen && } + {askOpen &&
+ + { setInitialPage(pageForDay(sample.pages, day)); setLogOpen(true); setMessage("Sample log page selected."); }} /> + +

{message}

+
} + {!logOpen && } + {logOpen &&
+ + +
} +
+
; +} diff --git a/web/src/tide/RunStamps.tsx b/web/src/tide/RunStamps.tsx new file mode 100644 index 0000000..dcf8824 --- /dev/null +++ b/web/src/tide/RunStamps.tsx @@ -0,0 +1,25 @@ +import type { CSSProperties, JSX } from "react"; +import { sealArt } from "./art"; +import { STAMPS, haulCount, haulWords, type DayResult } from "./run-day"; +import "./tide.css"; + +const HAUL_ART = { reed: "/assets/season/reed.webp", glass: "/assets/season/glass.webp", pearl: "/assets/run/pearl.webp" } as const; + +/** The day's haul as painted prizes with counts, read as one sentence. Renders nothing for an empty haul. */ +export function HaulRow({ result }: { result: Pick }): JSX.Element | null { + const count = haulCount(result); + const shown = (["reed", "glass", "pearl"] as const).filter(prize => count[prize] > 0); + if (!shown.length) return null; + return

Haul: {haulWords(result)}. + {shown.map(prize => )} +

; +} + +/** The three stamps of a finished tide run, with their kept or slipped marks. */ +export function StampList({ result, arrival = false }: { result: DayResult; arrival?: boolean }): JSX.Element { + return
    {STAMPS.map((stamp, i) =>
  1. + + + {stamp.label(result)} ({result.stamps[stamp.key] ? "kept" : "slipped"}) +
  2. )}
; +} diff --git a/web/src/tide/TideAsk.tsx b/web/src/tide/TideAsk.tsx new file mode 100644 index 0000000..8b1c884 --- /dev/null +++ b/web/src/tide/TideAsk.tsx @@ -0,0 +1,105 @@ +import { useId, type JSX } from "react"; +import type { TideCard } from "./asks"; +import { askLine, dayLabel, TOOL_NOTE } from "./cards"; +import type { TideEntry } from "./log"; +import { CARD_PICTURE, keeperArt, sealArt } from "./art"; +import TideStamp from "./TideStamp"; +import AskIcon from "./AskIcon"; +import { STAMPS, allKept, resultLine, type DayResult } from "./run-day"; +import "./tide.css"; + +export interface TideDayView { day: number; card: TideCard; entry: TideEntry | null } +type ClassicProps = { + today: TideDayView; earlier: readonly TideDayView[]; sailBlockedReason: string | null; + onSail: (day: number) => void; onOpenLog: (day?: number) => void; +}; +/** Today's tide on a device harbor: the day's card, Bram's guess and the tide run's three stamps. */ +export type RunAskProps = { + day: number; card: TideCard; guess: number; result: DayResult | null; sailBlockedReason: string | null; + onSail: (day: number) => void; onOpenLog: (day?: number) => void; +}; + +const SAIL_ICON = ; + +export default function TideAsk(props: ClassicProps | RunAskProps): JSX.Element { + return "guess" in props ? : ; +} + +function RunAsk({ day, card, guess, result, sailBlockedReason, onSail, onOpenLog }: RunAskProps): JSX.Element { + const id = useId(); + const canSail = sailBlockedReason === null; + return
+ +

Today’s tide

+

{dayLabel(day)}

+
+
+ +

{card.name}

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

+
+

The Tidekeeper asks

+
    + {STAMPS.map(stamp =>
  1. + + {result && } + {stamp.ask(guess)}{result && ({result.stamps[stamp.key] ? "kept" : "slipped"})} +
  2. )} +
+

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.

} + + {!canSail &&

{sailBlockedReason}

} +
+ +
; +} + +function ClassicAsk({ today, earlier, sailBlockedReason, onSail, onOpenLog }: ClassicProps): JSX.Element { + const id = useId(); + const canSail = sailBlockedReason === null; + const { card, entry } = today; + const kept = entry?.kept.filter(Boolean).length ?? 0; + return
+ +

Today’s tide

+

{dayLabel(today.day)}

+
+
+ +

{card.name}

{TOOL_NOTE[card.tool]}

+
+

The Tidekeeper asks

+
    + {card.asks.map((ask, i) =>
  1. + + {entry && } + {askLine(ask, card.tool)}{entry && ({entry.kept[i] ? "kept" : "slipped"})} +
  2. )} +
+ {entry && <> +

{entry.outcome === "returned" + ? `Best so far: ${kept} of 3 asks kept in ${entry.decisions} ${entry.decisions === 1 ? "decision" : "decisions"}. The Tidekeeper knows a way in ${card.best} ${card.best === 1 ? "decision" : "decisions"}.` + : "Bram fetched Mochi back this time. Nothing kept yet — the tide is still yours to sail."}

+ {entry.attempts > 1 &&

{entry.attempts} sails today.

} + } + + {!canSail &&

{sailBlockedReason}

} +
+ {earlier.length > 0 &&
+ Earlier tides +
    {earlier.map(({ day, card: past, entry: saved }) =>
  • + +
    +

    {dayLabel(day)}

    +

    {past.name}

    +

    {saved ? `${saved.kept.filter(Boolean).length} of 3 kept` : "Not sailed"}

    +
    + + {saved && } +
    +
    +
  • )}
+
} + +
; +} diff --git a/web/src/tide/TideChart.tsx b/web/src/tide/TideChart.tsx new file mode 100644 index 0000000..f5135ca --- /dev/null +++ b/web/src/tide/TideChart.tsx @@ -0,0 +1,112 @@ +import { useEffect, useState, type JSX } from "react"; +import type { Area, Find, Position } from "../expedition/types"; +import { chartLines, type ChartFrame } from "./chart"; +import "./tide.css"; + +const colX = (x: number) => 70 + x * 80; +const rowY = (y: number) => 300 - y * 62; +const finds: Record = { lens: { x: 0, y: 4 }, moth: { x: 2, y: 4 }, vane: { x: 1, y: 4 } }; +const jitter = (index: number, seed: number) => ((index * seed + 7) % 13) / 4 - 1.5; + +/** Points of the inked route; a foothold visited again sits a little to one side, so a retraced leg stays readable. */ +function routePoints(frames: readonly ChartFrame[]) { + const visits = new Map(); + return frames.map((frame, i) => { + const place = `${frame.position.x}:${frame.position.y}`, seen = visits.get(place) ?? 0; + visits.set(place, seen + 1); + const lean = seen ? (seen % 2 ? 1 : -1) * Math.ceil(seen / 2) * 4.5 : 0; + return [colX(frame.position.x) + jitter(i, 5) + lean, rowY(frame.position.y) + jitter(i, 9) - lean] as const; + }); +} +/** A pen line through the points: straight runs, softly rounded at each turn. */ +function inkPath(points: readonly (readonly [number, number])[]) { + if (!points.length) return ""; + let d = `M${points[0]![0].toFixed(1)} ${points[0]![1].toFixed(1)}`; + for (let i = 1; i < points.length; i++) { + const [x, y] = points[i]!, next = points[i + 1]; + if (!next) { d += `L${x.toFixed(1)} ${y.toFixed(1)}`; break; } + const [px, py] = points[i - 1]!, ease = (a: number, b: number) => a + (b - a) * 0.22; + d += `L${ease(x, px).toFixed(1)} ${ease(y, py).toFixed(1)}Q${x.toFixed(1)} ${y.toFixed(1)} ${ease(x, next[0]).toFixed(1)} ${ease(y, next[1]).toFixed(1)}`; + } + return d; +} + +export default function TideChart({ frames, area, reduced, label }: { + frames: readonly ChartFrame[]; area: Area; reduced: boolean; label: string; +}): JSX.Element { + const [shown, setShown] = useState(reduced ? Math.max(0, frames.length - 1) : 0); + const [replay, setReplay] = useState(0); + const last = Math.max(0, frames.length - 1); + useEffect(() => { + setShown(reduced ? last : 0); + if (reduced || !last) return; + let cursor = 0; + const timer = setInterval(() => { + cursor += 1; + setShown(cursor); + if (cursor === last) clearInterval(timer); + }, 320); + return () => clearInterval(timer); + }, [frames, reduced, replay, last]); + + const end = reduced ? last : Math.min(shown, last); + const current = frames[end]; + const visible = frames.slice(0, end + 1); + const points = routePoints(frames); + const waits = new Map(); + const restart = () => { setShown(reduced ? last : 0); setReplay(value => value + 1); }; + + return
+ + + + + {[0, 1, 3, 4].flatMap(y => [0, 1, 2].map(x => ))} + + + {current && + + {[131, 154, 177, 200].map((y, i) => )} + } + {area === "beacon" ? [0, 2].map(x => + {current?.opened.includes(x as 0 | 2) ? <> + + + : <> + + + } + ) : + + + } + {visible.slice(1).filter(frame => frame.wave && (reduced || frame === current)).map(frame => )} + + {visible.slice(1).map(frame => { + const x = colX(frame.position.x), y = rowY(frame.position.y); + const place = `${frame.position.x}:${frame.position.y}`; + const wait = waits.get(place) ?? 0; + if (frame.command === "wait") waits.set(place, wait + 1); + const item: Find | null = frame.pickup; + const pickup = item && finds[item]; + return + {frame.command === "wait" && } + {pickup && {`${frame.pickup} collected`}} + {frame.splash && + {[-1, 0, 1].map(n => )} + } + ; + })} + {current && } + {end === last && current?.outcome === "returned" && home} + {end === last && current?.outcome === "rescued" && Bram fetched her} + +
+ +
Read the route
    {chartLines(frames, area).map((line: string, i: number) =>
  1. {line}
  2. )}
+
+
; +} diff --git a/web/src/tide/TideHome.tsx b/web/src/tide/TideHome.tsx new file mode 100644 index 0000000..eb46b9b --- /dev/null +++ b/web/src/tide/TideHome.tsx @@ -0,0 +1,81 @@ +import { useId, type CSSProperties, type JSX } from "react"; +import { cardStatus, type Run, type TideCard } from "./asks"; +import { askLine } from "./cards"; +import { CARD_PICTURE, sealArt } from "./art"; +import { homeResult } from "./pages"; +import TideStamp from "./TideStamp"; +import { allKept, resultLine, resultTitle, type DayResult } from "./run-day"; +import { HaulRow, StampList } from "./RunStamps"; +import "./tide.css"; + +type Shared = { card: TideCard; canShelve: boolean; reduced: boolean; notice: string; sailBlockedReason: string | null; + onBram: () => void; onSail: () => void; onOpenLog: () => void }; +type ClassicProps = Shared & { run: Run }; +/** The Home sheet after a daily tide run. */ +export type RunHomeProps = Shared & { result: DayResult }; + +const BAG = "M6 8h12l2 12H4L6 8Zm3 0V5a3 3 0 0 1 6 0v3", SAIL = "M4 14h16l-3 6H7l-3-6Zm8-11v11M12 4l7 7h-7"; +export default function TideHome(props: ClassicProps | RunHomeProps): JSX.Element { + return "result" in props ? : ; +} + +function RunHome({ card, result, canShelve, reduced, notice, sailBlockedReason, onBram, onSail, onOpenLog }: RunHomeProps): JSX.Element { + const id = useId(), kept = allKept(result); + const blocked = !canShelve && sailBlockedReason !== null; + return
+
+
+ +
+
+
+ {kept && } +

{resultTitle(result)}

+
+

{resultLine(result)}

+ + {notice &&

{notice}

} + + {blocked &&

{sailBlockedReason}

} + +
+
; +} + +function ClassicHome({ card, run, canShelve, reduced, notice, sailBlockedReason, onBram, onSail, onOpenLog }: ClassicProps): JSX.Element { + const id = useId(), result = homeResult(run, card), statuses = cardStatus(card, run); + const allKept = statuses.every(status => status === "kept"); + const blocked = !canShelve && sailBlockedReason !== null; + return
+
+
+
    {card.asks.map((ask, i) =>
  1. + + {askLine(ask, card.tool)} ({statuses[i] === "kept" ? "kept" : "slipped"}) +
  2. )}
+
+
+
+ {allKept && } +

{result.title}

+
+

{result.body}

+ {notice &&

{notice}

} + + {blocked &&

{sailBlockedReason}

} + +
+
; +} diff --git a/web/src/tide/TideHud.tsx b/web/src/tide/TideHud.tsx new file mode 100644 index 0000000..32d27ec --- /dev/null +++ b/web/src/tide/TideHud.tsx @@ -0,0 +1,26 @@ +import type { JSX } from "react"; +import { askHolds, cardStatus, type Run, type TideCard } from "./asks"; +import { sealArt } from "./art"; +import { askChip } from "./cards"; +import AskIcon from "./AskIcon"; +import "./tide.css"; + +export default function TideHud({ card, run }: { card: TideCard; run: Run; reduced: boolean }): JSX.Element { + const statuses = cardStatus(card, run); + const holding = card.asks.map(ask => askHolds(ask, run)); + return
    + {card.asks.map((ask, i) => { + const status = statuses[i]!; + const label = askChip(ask, card.tool, run), divider = label.indexOf(" · "); + const nounEnd = divider >= 0 ? divider + 3 : ask.kind === "style" && (ask.style === "coiled" || ask.style === "shut-left" || ask.style === "shut-right") ? label.lastIndexOf(" ") + 1 : 0; + const statusEnd = ask.kind === "style" && ask.style === "dry" ? label.indexOf(" ") : label.length; + return
  • + + + {nounEnd > 0 && {label.slice(0, nounEnd)}}{label.slice(nounEnd, statusEnd)}{statusEnd < label.length && {label.slice(statusEnd)}} ({status === "open" ? holding[i] ? "holding" : "not yet" : status}) +
  • ; + })} +
; +} diff --git a/web/src/tide/TideLog.tsx b/web/src/tide/TideLog.tsx new file mode 100644 index 0000000..4d7b768 --- /dev/null +++ b/web/src/tide/TideLog.tsx @@ -0,0 +1,121 @@ +import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type JSX } from "react"; +import type { Area, BankedItem, Tool } from "../expedition/types"; +import type { TideCard } from "./asks"; +import { CARD_PICTURE, logCoverArt, logPageArt, sealArt } from "./art"; +import { askLine, dayLabel } from "./cards"; +import { chartFrames } from "./chart"; +import type { TideEntry } from "./log"; +import { pageForCard, stampSheet } from "./pages"; +import TideChart from "./TideChart"; +import TideStamp from "./TideStamp"; +import AskIcon from "./AskIcon"; +import { allKept, keptCount, type DayResult } from "./run-day"; +import { HaulRow, StampList } from "./RunStamps"; +import "./tide.css"; + +export type LogPage = + | { kind: "story"; id: string; title: string; subtitle: string; area: Area; tool: Tool; banked: readonly BankedItem[]; commands: readonly string[] } + | { kind: "tide"; day: number; card: TideCard; entry: TideEntry } + | { kind: "run"; day: number; card: TideCard; result: DayResult }; + +export default function TideLog({ pages, initialPage, reduced, sailBlockedReason, summary, onSail }: { + pages: readonly LogPage[]; initialPage?: number; reduced: boolean; sailBlockedReason: string | null; + summary: { sailed: number; kept: number; allThree: number }; onSail: (day: number) => void; +}): JSX.Element { + const id = useId(); + const canSail = sailBlockedReason === null; + const last = Math.max(0, pages.length - 1); + const [selected, setSelected] = useState(() => Math.max(0, Math.min(last, Math.trunc(initialPage ?? 0)))); + useEffect(() => { setSelected(Math.max(0, Math.min(last, Math.trunc(initialPage ?? 0)))); }, [initialPage, last]); + const index = Math.max(0, Math.min(last, selected)); + const page = pages[index]; + const selectedDay = page?.kind === "tide" ? page.day : undefined; + const logRef = useRef(null); + useLayoutEffect(() => { + const panel = logRef.current?.closest(".exp-panel"); + if (panel) panel.scrollTop = 0; + }, [index]); + const stamps = useMemo(() => stampSheet( + pages.flatMap(item => item.kind === "tide" ? [item.entry] : []), + pages.flatMap(item => item.kind === "run" ? [item.result] : []), + ), [pages]); + const collected = stamps.filter(slot => slot.entry || slot.result).length; + const sealed = stamps.filter(slot => slot.allThree).length; + const frames = useMemo(() => page ? page.kind === "story" + ? chartFrames({ area: page.area, tool: page.tool, banked: page.banked }, page.commands) + : page.kind === "tide" ? chartFrames({ area: "beacon", tool: page.entry.tool, banked: [] }, page.entry.commands) : null + : 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 pageKey = page?.kind === "story" ? `story:${page.id}` : page?.kind === "run" ? `run:${page.day}` : `tide:${selectedDay}`; + return
+
+ +
+

Bram’s tide log

+ {summary.sailed > 0 &&

{summary.sailed} tide{summary.sailed === 1 ? "" : "s"} sailed · {summary.kept} ask{summary.kept === 1 ? "" : "s"} kept · {summary.allThree} with all three

} +
+
+
+

The Tidekeeper’s stamps

+

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

+
+ {stamps.map(({ card, entry, result, allThree }) => entry || result + ? + : Not collected yet)} +
+
+ {!page ?

The log is empty. Bring the lens home and Bram starts the first page.

: <> +
{ + if (event.key === "ArrowLeft" || event.key === "ArrowRight") { event.preventDefault(); move(event.key === "ArrowLeft" ? -1 : 1); } + }}> + +

Page {index + 1} of {pages.length}

+ +
+

{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" ? :
+ {frames ? + :

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

} + {page.kind === "tide" && + + } +
} + {page.kind === "tide" && <> +
    {page.card.asks.map((ask, i) =>
  1. + + + {askLine(ask, page.card.tool)} ({page.entry.kept[i] ? "kept" : "slipped"}) +
  2. )}
+
+
Decisions
{page.entry.decisions}
+
Sails
{page.entry.attempts}
+
The Tidekeeper’s way
{page.card.best} {page.card.best === 1 ? "decision" : "decisions"}
+
+ {page.entry.kept.every(Boolean) && page.entry.decisions <= page.card.best &&

Mochi matched the Tidekeeper’s way.

} + + {!canSail &&

{sailBlockedReason}

} + } + } +
; +} + +function RunPage({ page }: { page: Extract }): JSX.Element { + const { card, result } = page; + return <> +
+ +

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

+
+
+
Banked
{result.score}
+
Bram’s guess
{result.guess}
+
Splashes
{result.splashes}
+
+ + ; +} diff --git a/web/src/tide/TideStamp.tsx b/web/src/tide/TideStamp.tsx new file mode 100644 index 0000000..d3438fb --- /dev/null +++ b/web/src/tide/TideStamp.tsx @@ -0,0 +1,22 @@ +import type { CSSProperties, JSX } from "react"; +import { cardArt, sealArt } from "./art"; +import "./tide.css"; + +export default function TideStamp({ id, size, seal = false, tilt = 0, label = "", press = false }: { + id: string; size: number; seal?: boolean; tilt?: number; label?: string; press?: boolean; +}): JSX.Element { + const padding = Math.round(size * .065); + const picture = size - padding * 2; + const sealSize = Math.round(size * .38); + // A whole number of notches keeps the four corners identical at every size. + const pitch = size / Math.round(5 + size / 20); + return + + {label} + + {seal && } + ; +} diff --git a/web/src/tide/art.test.ts b/web/src/tide/art.test.ts new file mode 100644 index 0000000..8072acb --- /dev/null +++ b/web/src/tide/art.test.ts @@ -0,0 +1,33 @@ +import { expect, test } from "bun:test"; +import { CARD_PICTURE, cardArt, keeperArt, logCoverArt, logPageArt, sealArt } from "./art"; +import { TIDE_POOL } from "./cards"; + +const publicRoot = new URL("../../public/", import.meta.url); +const manifest: { files: { output: string; bytes: number; resizedTo: { width: number; height: number } }[] } = + await Bun.file(new URL("assets/tide/manifest.json", publicRoot)).json(); +const sizeOf = (url: string) => manifest.files.find(file => `/${file.output}` === url)?.resizedTo; + +test("every tide card has a picture description and a 480px picture", () => { + expect(Object.keys(CARD_PICTURE).sort()).toEqual(TIDE_POOL.map(card => card.id).sort()); + for (const { id } of TIDE_POOL) { + expect(CARD_PICTURE[id]?.trim().length).toBeGreaterThan(0); + expect(sizeOf(cardArt(id))).toEqual({ width: 480, height: 480 }); + } +}); + +test("the seals, keeper and log artwork have their runtime sizes", () => { + for (const kind of ["kept", "slipped", "all-three"] as const) + expect(sizeOf(sealArt(kind))).toEqual({ width: 168, height: 168 }); + expect(sizeOf(keeperArt)?.width).toBe(960); + expect(sizeOf(logCoverArt)).toEqual({ width: 384, height: 384 }); + expect(sizeOf(logPageArt)?.width).toBe(900); +}); + +test("every manifest output exists with its recorded byte count", async () => { + expect(manifest.files).toHaveLength(20); + for (const { output, bytes } of manifest.files) { + const file = Bun.file(new URL(output, publicRoot)); + expect(await file.exists()).toBe(true); + expect(file.size).toBe(bytes); + } +}); diff --git a/web/src/tide/art.ts b/web/src/tide/art.ts new file mode 100644 index 0000000..87b3d3e --- /dev/null +++ b/web/src/tide/art.ts @@ -0,0 +1,24 @@ +export const TIDE_ART = "/assets/tide/"; +export const cardArt = (id: string) => `${TIDE_ART}card-${id}.webp`; +export const sealArt = (kind: "kept" | "slipped" | "all-three") => `${TIDE_ART}seal-${kind}.webp`; +export const keeperArt = TIDE_ART + "keeper-ask.webp"; +export const logCoverArt = TIDE_ART + "log-cover.webp"; +export const logPageArt = TIDE_ART + "log-page.webp"; + +/** One short sentence describing each card picture, for screen readers. Keyed by card id. */ +export const CARD_PICTURE: Record = { + "wake-both-shells": "Two open coral shells glow on a spiral stone.", + "every-source": "Three teal waves with white foam stand in a row on a spiral stone.", + "no-waiting": "Three orange pawprints pass a sideways hourglass on a spiral stone.", + "full-satchel": "A brass lens and a golden moth peek from an open brown satchel.", + "dry-paws": "Two rust-red boots stay clear of a small teal wave on a spiral stone.", + "once-across": "One orange pawprint marks the middle of a little wooden rope bridge.", + "tidy-tide": "A straw broom stands beside a neat mound of white foam on a spiral stone.", + "coiled-rope": "A flat coil of rope rests on a spiral stone, tied with a red bow.", + "quiet-shell": "A golden moth sleeps on a closed coral shell on a spiral stone.", + "surf-home": "Mochi rides a teal wave with a brass lens tucked in her satchel.", + "brams-bridge": "A steaming brown mug and round brass spectacles rest at the left end of a wooden bridge.", + "dry-and-tidy": "Two folded cream towels with teal stripes sit beneath a wooden clothes peg.", + "lantern-haul": "A brass lens leans against a glowing lantern beside a golden moth.", + "left-for-bram": "A cream parcel tied with twine bears a round tag stitched with a coral shell.", +}; diff --git a/web/src/tide/ask-ui.test.tsx b/web/src/tide/ask-ui.test.tsx new file mode 100644 index 0000000..1c6a513 --- /dev/null +++ b/web/src/tide/ask-ui.test.tsx @@ -0,0 +1,114 @@ +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 type { TideEntry } from "./log"; +import TideAsk from "./TideAsk"; +import TideHud from "./TideHud"; +import TideLog from "./TideLog"; +import type { DayResult } from "./run-day"; + +const day = 20771, card = cardForDay(day); +const entry: TideEntry = { day, cardId: card.id, tool: card.tool, commands: ["return"], kept: [true, false, true], decisions: 1, outcome: "returned", late: false, attempts: 1, savedAt: "" }; + +test("today’s asks replace numerals with 32px objects and preserve every sentence", () => { + const html = renderToStaticMarkup( {}} onOpenLog={() => {}}/>); + expect(html.match(/src="\/assets\/ui\/ask-[^"]+" width="32" height="32" alt="" decoding="async"/g)).toHaveLength(3); + expect(html).not.toContain('class="tide-ask-mark"'); + for (const ask of card.asks) expect(html).toContain(askLine(ask, card.tool)); +}); + +test("saved asks and the log retain kept/slipped marks beside their painted objects", () => { + for (const [size, html] of [ + [32, renderToStaticMarkup( {}} onOpenLog={() => {}}/>)], + [28, renderToStaticMarkup( {}}/>)], + ] as const) { + expect(html.match(new RegExp(`src="/assets/ui/ask-[^"]+" width="${size}" height="${size}" alt="" decoding="async"`, "g"))).toHaveLength(3); + expect(html.match(/class="tide-ask-mark"/g)).toHaveLength(3); + expect(html.match(/\(kept\)/g)).toHaveLength(2); + expect(html.match(/\(slipped\)/g)).toHaveLength(1); + } +}); + +test("live chips retain noun and status separately without losing holding announcements", () => { + const html = renderToStaticMarkup(); + expect(html).toContain('aria-label="The Tidekeeper’s asks" aria-live="polite"'); + expect(html).toContain('Lens · still out'); + expect(html).toContain('One splash · 0 of 1'); + expect(html).toContain('Within 10 · 10 left'); + expect(html).toContain('(holding)'); + expect(html).toContain('(not yet)'); + expect(html.match(/class="tide-mark" aria-hidden="true"/g)).toHaveLength(3); + const home = replayRun(card.tool, ["return"])!; + expect(renderToStaticMarkup().match(/\(slipped\)/g)).toHaveLength(3); +}); + +test("phone style chips expose only the status while preserving the original full label", () => { + for (const [style, tool, prefix, status, suffix] of [ + ["dry", "rope", "", "Dry", " paws"], + ["coiled", "rope", "Rope ", "coiled", ""], + ["coiled", "lantern", "Lantern ", "unlit", ""], + ["shut-left", "rope", "Left shell ", "shut", ""], + ["shut-right", "lantern", "Right shell ", "shut", ""], + ["no-wait", "rope", "", "No waiting", ""], + ] as const) { + const ask: Ask = { kind: "style", style }; + const html = renderToStaticMarkup(); + const expected = `${prefix ? `${prefix}` : ""}${status}${suffix ? `${suffix}` : ""}`; + expect(html).toContain(`${expected}`); + expect(expected.replace(/<[^>]+>/g, "")).toBe(askChip(ask, tool, startRun(tool))); + } + const home = replayRun(card.tool, solve(card.tool, card.asks)!)!; + const html = renderToStaticMarkup(); + expect(html).toContain('Home in 9'); +}); + +const runResult: DayResult = { day, score: 7, guess: 6, banked: ["reed", "glass"], stamps: { home: true, guess: true, dry: false }, splashes: 1 }; +const runAsk = { day, card, guess: 6, result: null, sailBlockedReason: null, onSail: (_day: number) => {}, onOpenLog: (_day?: number) => {} }; + +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("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("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"]) { + expect(html).toContain(`src="${icon}" width="32" height="32" alt="" decoding="async"`); + } + expect(html.match(/]/g)).toHaveLength(3); + expect(html).toContain("Bram plays it safe: he never ends a wave in the water. His guess is what that careful tide banks."); + expect(html).toContain("Sail today’s tide"); + expect(html).toContain("Open the tide log"); + expect(html).not.toContain("Earlier tides"); + expect(html).not.toContain("tide-ask-mark"); + expect(html).not.toContain("data-kept"); + expect(html).not.toContain("tide-stamp-seal"); +}); + +test("a recorded tide run marks the three asks and offers practice", () => { + const html = renderToStaticMarkup(); + expect(html.match(/data-kept="true"/g)).toHaveLength(2); + expect(html.match(/data-kept="false"/g)).toHaveLength(1); + 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("Sail again for practice"); + expect(html).not.toContain("tide-stamp-seal"); + const allThree = renderToStaticMarkup(); + expect(allThree).toContain('class="tide-stamp-seal"'); +}); + +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."; + const html = renderToStaticMarkup(); + const described = html.match(/class="exp-primary" aria-disabled="true" aria-describedby="([^"]+)"/); + expect(described).not.toBeNull(); + expect(html).toContain(`

${reason}

`); + expect(html).not.toMatch(/]*\sdisabled(?:[=>\s])/); + expect(html).toContain(result ? "Sail again for practice" : "Sail today’s tide"); + } +}); diff --git a/web/src/tide/asks.ts b/web/src/tide/asks.ts new file mode 100644 index 0000000..624b047 --- /dev/null +++ b/web/src/tide/asks.ts @@ -0,0 +1,137 @@ +/** + * The Tidekeeper's ask: one card a day for a fresh Beacon Court outing. + * Pure functions over the canonical court engine. Nothing here changes a rule; an ask only reads what a run did. + * An outing that comes home with an empty satchel keeps no asks. + */ +import { applyCommand, legalCommands, phaseOf, startCourt } from "../expedition/engine"; +import { TURN_LIMIT, type Column, type Command, type CourtState, type Tool } from "../expedition/types"; + +export type Haul = "lens" | "moth" | "both"; +export type Style = + | "dry" | "splash" | "coiled" | "no-wait" | "all-marks" | "one-crossing" | "both-shells" + | "bridge-left" | "bridge-center" | "bridge-right" | "shut-left" | "shut-right"; +export type Ask = + | { readonly kind: "haul"; readonly haul: Haul } + | { readonly kind: "style"; readonly style: Style } + | { readonly kind: "within"; readonly decisions: number }; +export interface TideCard { + readonly id: string; + readonly name: string; + readonly tool: Tool; + readonly asks: readonly [Ask, Ask, Ask]; + /** Fewest decisions that keep all three asks, found by search and re-proved in the tests. */ + readonly best: number; +} + +/** What a run has done so far that the engine state alone does not remember. */ +export interface RunFacts { + readonly waits: number; + readonly marks: readonly Column[]; + readonly crossings: number; +} +export const NO_FACTS: RunFacts = { waits: 0, marks: [], crossings: 0 }; + +export function nextFacts(facts: RunFacts, before: CourtState, command: Command, after: CourtState): RunFacts { + const marked = phaseOf(before) === "rising" && after.locked !== null && !facts.marks.includes(after.locked); + // A legal step from either landing crosses before the surge can splash Mochi back. + const crossed = command === "step:north" && before.position.y === 1 || command === "step:south" && before.position.y === 3; + return { + waits: facts.waits + (command === "wait" ? 1 : 0), + marks: marked ? [...facts.marks, after.locked!] : facts.marks, + crossings: facts.crossings + (crossed ? 1 : 0), + }; +} + +export interface Run { readonly state: CourtState; readonly facts: RunFacts } +export const startRun = (tool: Tool): Run => ({ state: startCourt({ area: "beacon", tool, banked: [] }), facts: NO_FACTS }); +export function stepRun(run: Run, command: Command): Run | null { + const turn = applyCommand(run.state, command); + return turn ? { state: turn.after, facts: nextFacts(run.facts, run.state, command, turn.after) } : null; +} +/** Rebuilds a run from its saved commands. Null when the commands are not a legal fresh Beacon Court outing. */ +export function replayRun(tool: unknown, commands: unknown): Run | null { + if ((tool !== "rope" && tool !== "lantern") || !Array.isArray(commands) || commands.length > TURN_LIMIT) return null; + let run = startRun(tool); + for (const command of commands) { + const next = stepRun(run, command as Command); + if (!next) return null; + run = next; + } + return run; +} + +export type AskStatus = "open" | "kept" | "slipped"; +const home = (state: CourtState) => state.outcome === "returned"; +const over = (state: CourtState) => state.outcome !== "active"; + +/** Is this ask's condition met as things stand? An open ask that holds would be kept if nothing changed before home. */ +export function askHolds(ask: Ask, { state, facts }: Run): boolean { + if (state.outcome === "rescued") return false; + if (ask.kind === "within") return over(state) ? state.turn <= ask.decisions : state.turn < ask.decisions; + if (ask.kind === "haul") { + const lens = state.cargo.includes("lens"), moth = state.cargo.includes("moth"); + return ask.haul === "moth" ? moth && !lens : ask.haul === "both" ? lens && moth : lens; + } + switch (ask.style) { + case "dry": return state.resolve === 3; + case "splash": return state.resolve === 2; + case "coiled": return state.uses === 2; + case "no-wait": return facts.waits === 0; + case "all-marks": return facts.marks.length === 3; + case "one-crossing": return facts.crossings === 2; + case "both-shells": return state.opened.includes(0) && state.opened.includes(2); + case "bridge-left": return state.bridge === 0; + case "bridge-center": return state.bridge === 1; + case "bridge-right": return state.bridge === 2; + case "shut-left": return !state.opened.includes(0); + case "shut-right": return !state.opened.includes(2); + } +} + +/** `open` can still go either way; `kept` and `slipped` are final for this outing. */ +export function askStatus(ask: Ask, run: Run): AskStatus { + const { state, facts } = run; + if (state.outcome === "rescued" || home(state) && state.cargo.length === 0) return "slipped"; + const holds = askHolds(ask, run); + const settle = (broken = !holds): AskStatus => broken ? "slipped" : over(state) ? (home(state) && holds ? "kept" : "slipped") : "open"; + if (ask.kind === "within") return settle(); + if (ask.kind === "haul") return settle(ask.haul === "moth" && state.cargo.includes("lens")); + switch (ask.style) { + case "splash": return settle(state.resolve < 2); + case "one-crossing": return settle(facts.crossings > 2); + case "all-marks": case "both-shells": case "bridge-left": case "bridge-center": case "bridge-right": return settle(false); + default: return settle(); + } +} +export const cardStatus = (card: TideCard, run: Run) => card.asks.map(ask => askStatus(ask, run)) as [AskStatus, AskStatus, AskStatus]; +export const keptCount = (card: TideCard, run: Run) => cardStatus(card, run).filter(status => status === "kept").length; + +const key = ({ state: s, facts: f }: Run) => + `${s.position.x}${s.position.y}${s.turn % 3}${s.bridge}${s.locked ?? "n"}${s.opened.join("")}|${[...s.cargo].sort().join("")}|${s.uses}${s.resolve}|${Math.min(f.waits, 1)}${[...f.marks].sort().join("")}|${Math.min(f.crossings, 3)}`; + +/** Breadth-first over the real engine: the shortest command list that comes home with every ask kept. */ +export function solve(tool: Tool, asks: readonly Ask[], limit = TURN_LIMIT): Command[] | null { + let frontier: { run: Run; path: Command[] }[] = [{ run: startRun(tool), path: [] }]; + const seen = new Set([key(frontier[0]!.run)]); + for (let depth = 0; depth < limit && frontier.length; depth++) { + const next: typeof frontier = []; + for (const { run, path } of frontier) { + for (const command of legalCommands(run.state)) { + const after = stepRun(run, command); + if (!after || after.state.outcome === "rescued") continue; + if (asks.some(ask => askStatus(ask, after) === "slipped")) continue; + const route = [...path, command]; + if (after.state.outcome === "returned") { + if (asks.every(ask => askStatus(ask, after) === "kept")) return route; + continue; + } + const id = key(after); + if (seen.has(id)) continue; + seen.add(id); + next.push({ run: after, path: route }); + } + } + frontier = next; + } + return null; +} diff --git a/web/src/tide/cards.test.ts b/web/src/tide/cards.test.ts new file mode 100644 index 0000000..0f61c95 --- /dev/null +++ b/web/src/tide/cards.test.ts @@ -0,0 +1,117 @@ +import { expect, test } from "bun:test"; +import { legalCommands } from "../expedition/engine"; +import { TURN_LIMIT } from "../expedition/types"; +import { askHolds, askStatus, cardStatus, replayRun, solve, startRun, stepRun } from "./asks"; +import { askChip, askLine, cardForDay, TIDE_POOL } from "./cards"; + +for(const card of TIDE_POOL)test(`${card.id} keeps every ask in exactly ${card.best} decisions`,()=>{ + const route=solve(card.tool,card.asks);expect(route).not.toBeNull();expect(route!.length).toBe(card.best); + const run=replayRun(card.tool,route)!; + expect(run.state.outcome).toBe("returned");expect(cardStatus(card,run)).toEqual(["kept","kept","kept"]); + expect(solve(card.tool,card.asks,card.best-1)).toBeNull(); + for(const ask of card.asks){ + expect(askHolds(ask,run)).toBe(askStatus(ask,run)==="kept"); + if(ask.kind==="within")expect(ask.decisions).toBeGreaterThanOrEqual(card.best); + expect(askLine(ask,card.tool).trim().length).toBeGreaterThan(0); + for(const current of [startRun(card.tool),run])expect(askChip(ask,card.tool,current).trim().length).toBeGreaterThan(0); + } +},60_000); + +test("daily cards have unique ids, alternate tools and wrap fractional or negative days",()=>{ + expect(new Set(TIDE_POOL.map(card=>card.id)).size).toBe(TIDE_POOL.length); + for(let day=20771;day<=20798;day++)expect(cardForDay(day).tool).not.toBe(cardForDay(day+1).tool); + expect(cardForDay(20771).id).toBe("surf-home");expect(cardForDay(20772).id).toBe("brams-bridge"); + for(const day of [-1,-15.5,3.7]){expect(()=>cardForDay(day)).not.toThrow();expect(TIDE_POOL).toContain(cardForDay(day));} +}); + +test("a rescued outing slips every ask",()=>{ + let run=startRun("rope"); + for(let i=0;i{ + const ask={kind:"within",decisions:2} as const; + let run=startRun("rope");expect(askStatus(ask,run)).toBe("open");expect(askHolds(ask,run)).toBe(true); + run=stepRun(run,"step:north")!;expect(askStatus(ask,run)).toBe("open");expect(askHolds(ask,run)).toBe(true); + run=stepRun(run,"step:west")!;expect(run.state.outcome).toBe("active");expect(askStatus(ask,run)).toBe("slipped");expect(askHolds(ask,run)).toBe(false); +}); + +test("the surf route slips moth-only at the lens and dry paws at the first splash",()=>{ + const card=cardForDay(20771),route=solve(card.tool,card.asks)!; + expect(route).toEqual(["step:north","step:west","step:east","step:west","step:north","take:lens","step:south","step:east","return"]); + const dry={kind:"style",style:"dry"} as const,moth={kind:"haul",haul:"moth"} as const; + let run=startRun(card.tool),splashes=0,picked=false; + for(const command of route){ + const next=stepRun(run,command)!; + if(!splashes)expect(askStatus(dry,run)).toBe("open"); + if(next.state.resolve{ + for(const card of TIDE_POOL){ + const run=startRun(card.tool);expect(cardStatus(card,run)).toEqual(["open","open","open"]); + expect(cardStatus(card,stepRun(run,"return")!)).toEqual(["slipped","slipped","slipped"]); + } +}); + +test("a walked crossing still counts when the same surge washes Mochi back",()=>{ + const card=TIDE_POOL.find(card=>card.id==="once-across")!; + const repeated=replayRun(card.tool,["wait","step:north","step:north","step:north","step:east","step:north","take:moth","step:south","step:west","step:south","return"])!; + expect(repeated.state.outcome).toBe("returned");expect(repeated.facts.crossings).toBe(3); + expect(cardStatus(card,repeated)).toEqual(["kept","slipped","kept"]); + const onceEachWay=replayRun(card.tool,["step:north","step:north","step:west","step:east","step:east","step:west","step:east","take:moth","step:west","step:east","step:south","step:west","step:south","return"])!; + expect(onceEachWay.state.outcome).toBe("returned");expect(onceEachWay.facts.crossings).toBe(2); + expect(askStatus(card.asks[1],onceEachWay)).toBe("kept"); +}); + +test("a budget holds through the final return decision but not an extra active decision",()=>{ + const card=cardForDay(20771),route=solve(card.tool,card.asks)!,ask={kind:"within",decisions:route.length} as const; + const before=replayRun(card.tool,route.slice(0,-1))!,home=stepRun(before,"return")!; + expect(askHolds(ask,before)).toBe(true);expect(askStatus(ask,before)).toBe("open"); + expect(askHolds(ask,home)).toBe(true);expect(askStatus(ask,home)).toBe("kept"); + const spent={...ask,decisions:before.state.turn}; + expect(askHolds(spent,before)).toBe(false);expect(askStatus(spent,before)).toBe("slipped"); + expect(askHolds(spent,home)).toBe(false);expect(askStatus(spent,home)).toBe("slipped"); +}); + +test("a bridge ask can stop holding and hold again while remaining open",()=>{ + const ask={kind:"style",style:"bridge-center"} as const,start=startRun("lantern"); + const away=replayRun("lantern",["wait","wait","lure:left"])!,back=replayRun("lantern",[...away.state.commands,"wait","wait","lure:center"])!; + expect([start.state.bridge,away.state.bridge,back.state.bridge]).toEqual([1,0,1]); + expect([start,away,back].map(run=>askHolds(ask,run))).toEqual([true,false,true]); + expect([start,away,back].map(run=>askStatus(ask,run))).toEqual(["open","open","open"]); +}); + +test("bridge chips name the requested lane and the bridge's current lane",()=>{ + for(const [style,name,command] of [["bridge-left","Left","lure:left"],["bridge-center","Center","lure:center"],["bridge-right","Right","lure:right"]] as const){ + const ask={kind:"style",style} as const,there=replayRun("lantern",["wait","wait",command])!; + expect(askChip(ask,"lantern",there)).toBe(`Bridge at ${name} · there now`); + const elsewhere=style==="bridge-center"?replayRun("lantern",["wait","wait","lure:left"])!:startRun("lantern"); + expect(askChip(ask,"lantern",elsewhere)).toBe(`Bridge at ${name} · now ${style==="bridge-center"?"Left":"Center"}`); + } +}); + +test("the splash chip counts splashes past one",()=>{ + const ask={kind:"style",style:"splash"} as const,start=startRun("rope"); + const soaked=(resolve:number)=>({...start,state:{...start.state,resolve}}); + expect(askChip(ask,"rope",soaked(2))).toBe("One splash · 1 of 1"); + expect(askChip(ask,"rope",soaked(1))).toBe("One splash · 2 splashes"); +}); + +test("the moth-only chip says when the lens was taken",()=>{ + const ask={kind:"haul",haul:"moth"} as const,start=startRun("lantern"); + expect(askChip(ask,"lantern",start)).toBe("Moth only · still out"); + expect(askChip(ask,"lantern",{...start,state:{...start.state,cargo:["lens"]}})).toBe("Moth only · lens taken"); +}); diff --git a/web/src/tide/cards.ts b/web/src/tide/cards.ts new file mode 100644 index 0000000..05c02a2 --- /dev/null +++ b/web/src/tide/cards.ts @@ -0,0 +1,93 @@ +/** + * Two weeks of the Tidekeeper's asks. The day picks the card, so every harbor reads the same ask on the same day. + * `best` is the fewest decisions that keep all three asks; `cards.test.ts` re-proves each one with the solver. + */ +import type { Tool } from "../expedition/types"; +import { askStatus, type Ask, type Haul, type Run, type Style, type TideCard } from "./asks"; + +const card = (id: string, name: string, tool: Tool, haul: Haul, style: Style, third: Style | number, best: number): TideCard => ({ + id, name, tool, best, + asks: [ + { kind: "haul", haul }, + { kind: "style", style }, + typeof third === "number" ? { kind: "within", decisions: third } : { kind: "style", style: third }, + ], +}); + +/** Order matters: `cardForDay` walks it one card a day and the tools alternate. */ +export const TIDE_POOL: readonly TideCard[] = [ + card("wake-both-shells", "Wake both shells", "lantern", "lens", "both-shells", 12, 10), + card("every-source", "Every source speaks", "rope", "lens", "all-marks", 14, 12), + card("no-waiting", "No waiting", "lantern", "both", "no-wait", 13, 11), + card("full-satchel", "A full satchel", "rope", "both", "dry", 19, 17), + card("dry-paws", "Dry paws", "lantern", "lens", "dry", 13, 11), + card("once-across", "Once across", "rope", "moth", "one-crossing", 13, 11), + card("tidy-tide", "A tidy tide", "lantern", "lens", "all-marks", "bridge-center", 11), + card("coiled-rope", "The rope stays coiled", "rope", "both", "coiled", 16, 14), + card("quiet-shell", "The quiet shell", "lantern", "moth", "shut-left", 10, 8), + card("surf-home", "Surf home", "rope", "lens", "splash", 10, 9), + card("brams-bridge", "Bram’s bridge", "lantern", "moth", "bridge-left", 12, 10), + card("dry-and-tidy", "Dry and tidy", "rope", "moth", "dry", "bridge-center", 15), + card("lantern-haul", "The lantern haul", "lantern", "both", "dry", 17, 15), + card("left-for-bram", "Left for Bram", "rope", "both", "no-wait", "bridge-left", 15), +]; + +/** The same day boundary as the season contract: whole days of UTC time. */ +export const tideDay = (now: number = Date.now()) => Math.floor(now / 86_400_000); +export const msUntilNextTideDay = (now: number = Date.now()) => (tideDay(now) + 1) * 86_400_000 - now; +export function cardForDay(day: number): TideCard { + const size = TIDE_POOL.length; + return TIDE_POOL[((Math.trunc(day) % size) + size) % size]!; +} +export const dayLabel = (day: number) => + new Date(day * 86_400_000).toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long", timeZone: "UTC" }); + +export const TOOL_NOTE: Record = { + rope: "Mochi carries the rope: it reels the lens in from two steps away.", + lantern: "Mochi carries the lantern: on a surge turn it lures the marked wave to another lane, twice.", +}; + +const column = { left: "Left", center: "Center", right: "Right" } as const; +/** The full sentence, as the Tidekeeper asks it on the card. */ +export function askLine(ask: Ask, tool: Tool): string { + if (ask.kind === "within") return `Be home within ${ask.decisions} ${ask.decisions === 1 ? "decision" : "decisions"}.`; + if (ask.kind === "haul") return ask.haul === "both" ? "Bring both finds home." : ask.haul === "lens" ? "Bring the lens home." : "Bring the moth home, and leave the lens in its shell."; + switch (ask.style) { + case "dry": return "Keep Mochi dry the whole way."; + case "splash": return "Let one surge soak Mochi. Only one."; + case "coiled": return tool === "rope" ? "Leave the rope coiled." : "Leave the lantern unlit."; + case "no-wait": return "Never wait for the tide."; + case "all-marks": return "Mark all three sources: left, center and right."; + case "one-crossing": return "Cross the bridge once out and once home."; + case "both-shells": return "Open both shells."; + case "shut-left": return "Leave the left shell shut."; + case "shut-right": return "Leave the right shell shut."; + default: return `Leave the bridge at ${column[ask.style.slice(7) as keyof typeof column]} when Mochi comes home.`; + } +} + +/** A short live label for the outing: what the ask is and how far along it stands. */ +export function askChip(ask: Ask, tool: Tool, run: Run): string { + const { state, facts } = run, status = askStatus(ask, run); + if (ask.kind === "within") return status === "slipped" ? `Within ${ask.decisions} · passed` : status === "kept" ? `Home in ${state.turn}` : `Within ${ask.decisions} · ${ask.decisions - state.turn} left`; + if (ask.kind === "haul") { + const lens = state.cargo.includes("lens"), moth = state.cargo.includes("moth"); + if (ask.haul === "both") return `Both finds · ${Number(lens) + Number(moth)} of 2`; + return ask.haul === "lens" ? `Lens · ${lens ? "in the pack" : "still out"}` : `Moth only · ${lens ? "lens taken" : moth ? "in the pack" : "still out"}`; + } + switch (ask.style) { + case "dry": return "Dry paws"; + case "splash": return `One splash · ${3 - state.resolve > 1 ? `${3 - state.resolve} splashes` : `${3 - state.resolve} of 1`}`; + case "coiled": return tool === "rope" ? "Rope coiled" : "Lantern unlit"; + case "no-wait": return "No waiting"; + case "all-marks": return `Three sources · ${facts.marks.length} of 3`; + case "one-crossing": return `Once out, once home · ${Math.min(facts.crossings, 2)} of 2`; + case "both-shells": return `Both shells · ${Number(state.opened.includes(0)) + Number(state.opened.includes(2))} of 2`; + case "shut-left": return "Left shell shut"; + case "shut-right": return "Right shell shut"; + default: { + const target = column[ask.style.slice(7) as keyof typeof column], current = Object.values(column)[state.bridge]; + return `Bridge at ${target} · ${target === current ? "there now" : `now ${current}`}`; + } + } +} diff --git a/web/src/tide/chart.test.ts b/web/src/tide/chart.test.ts new file mode 100644 index 0000000..3efded5 --- /dev/null +++ b/web/src/tide/chart.test.ts @@ -0,0 +1,68 @@ +import { expect, test } from "bun:test"; +import { applyCommand, phaseOf, startCourt } from "../expedition/engine"; +import { TURN_LIMIT, type BankedItem } from "../expedition/types"; +import { solve, startRun, stepRun } from "./asks"; +import { cardForDay } from "./cards"; +import { chartFrames, chartLines } from "./chart"; + +const card=cardForDay(20771),surf=solve(card.tool,card.asks)!; +const beacon={area:"beacon",tool:"rope",banked:[]} as const; +const wind={area:"wind",tool:"rope",banked:["lens","moth"] as readonly BankedItem[]} as const; +const gate=["step:east","step:north","step:west","step:west","step:north","wait","step:east","turn:vane","wait","turn:vane","take:vane","step:west","step:east","step:south","step:west","step:south","step:east","return"]; + +test("the surf chart records one splash, one lens and the returned ending",()=>{ + const frames=chartFrames(beacon,surf)!;expect(frames.length).toBe(surf.length+1); + expect(frames[0]).toMatchObject({index:0,command:null,wave:null,splash:false,pickup:null,phase:"low",outcome:"active"}); + expect(frames.filter(frame=>frame.splash).length).toBe(1);expect(frames.filter(frame=>frame.pickup==="lens").length).toBe(1);expect(frames.at(-1)!.outcome).toBe("returned"); + let state=startCourt(beacon); + for(let i=0;ievent.kind==="wave"); + expect(frame).toMatchObject({index:i+1,command:surf[i],position:turn.after.position,bridge:turn.after.bridge,opened:turn.after.opened,cargo:turn.after.cargo,phase:phaseOf(turn.before),marked:turn.after.locked, + wave:wave?{source:wave.source,exit:wave.exit}:null,splash:turn.events.some(event=>event.kind==="hit"),pickup:turn.events.find(event=>event.kind==="pickup")?.item??null,outcome:turn.after.outcome}); + expect(frame.opened).not.toBe(turn.after.opened);expect(frame.cargo).not.toBe(turn.after.cargo);state=turn.after; + } + frames.at(-1)!.cargo.push("moth");expect(frames.at(-2)!.cargo).toEqual(["lens"]); +}); + +test("invalid starts, illegal commands and overlong routes cannot be charted",()=>{ + expect(chartFrames(beacon,["step:south"])).toBeNull();expect(chartFrames({...beacon,banked:["vane","vane"]},[])).toBeNull(); + expect(chartFrames(beacon,Array(TURN_LIMIT+1).fill("wait"))).toBeNull();expect(chartFrames(beacon,null as unknown as string[])).toBeNull(); + expect(chartFrames(beacon,["return","wait"])).toBeNull();expect(chartFrames(beacon,[])!.length).toBe(1); +}); + +test("the Wind Gate chart carries the vane home",()=>{ + const frames=chartFrames(wind,gate)!;expect(frames.length).toBe(19);expect(frames.at(-1)!.outcome).toBe("returned");expect(frames.some(frame=>frame.pickup==="vane")).toBe(true); +}); + +test("both courts tell one numbered plain sentence per decision",()=>{ + for(const [start,commands] of [[beacon,surf],[wind,gate]] as const){ + const frames=chartFrames(start,commands)!,lines=chartLines(frames,start.area); + expect(lines.length).toBe(frames.length-1); + lines.forEach((line,i)=>{expect(line.startsWith(`${i+1}. Mochi `)).toBe(true);expect(line.trim().length).toBeGreaterThan(10);expect(line.endsWith(".")).toBe(true);}); + expect(lines.at(-1)).toContain("comes home with"); + } + const lines=chartLines(chartFrames(beacon,surf)!,"beacon"); + expect(lines[0]).toContain("steps north");expect(lines.some(line=>line.includes("It soaks her."))).toBe(true);expect(lines.some(line=>line.includes("A wave runs down the"))).toBe(true); + expect(lines.find(line=>line.includes("takes the lens"))).toBeTruthy(); + const windLines=chartLines(chartFrames(wind,gate)!,"wind");expect(windLines.some(line=>line.includes("turns the wheel"))).toBe(true);expect(windLines.some(line=>line.includes("takes the vane"))).toBe(true); + expect(chartLines(chartFrames(beacon,["return"])!,"beacon")).toEqual(["1. Mochi comes home empty-pawed."]);expect(chartLines([],"beacon")).toEqual([]); +}); + +test("route descriptions include reels, lures and rescue",()=>{ + const lens=["wait","step:west","wait","step:north","step:north","step:east","reel:lens","step:west","step:south","step:east","return"]; + const rope=chartFrames(beacon,lens)!;expect(rope.at(-1)!.outcome).toBe("returned");expect(chartLines(rope,"beacon").some(line=>line.includes("reels in the lens"))).toBe(true); + const lantern=chartFrames({...beacon,tool:"lantern"},["wait","wait","lure:left"])!; + expect(chartLines(lantern,"beacon")[2]).toContain("lures the wave to the left column"); + let run=startRun("rope");for(let i=0;i{ + const lantern=chartLines(chartFrames({...beacon,tool:"lantern"},["wait","wait","lure:left"])!,"beacon"); + expect(lantern[2]).toBe("3. Mochi lures the wave to the left column. A wave runs down the left lane."); + const lines=chartLines(chartFrames(wind,gate)!,"wind"); + expect(lines[2]).toContain("A wave rises on the right and runs out on the left."); + expect(lines[5]).toContain("A wave rises on the left and runs out on the center."); + expect(lines[8]).toContain("A wave rises on the center and runs out on the left."); + expect(lines[11]).toContain("A wave runs down the center lane."); +}); diff --git a/web/src/tide/chart.ts b/web/src/tide/chart.ts new file mode 100644 index 0000000..5a9350e --- /dev/null +++ b/web/src/tide/chart.ts @@ -0,0 +1,39 @@ +import { applyCommand, phaseOf, startCourt } from "../expedition/engine"; +import { TURN_LIMIT, type Area, type BankedItem, type Column, type CourtState, type Find, type Phase, type Position, type Tool } from "../expedition/types"; + +export interface ChartFrame { index:number;command:string|null;position:Position;bridge:Column;opened:Column[];cargo:Find[];phase:Phase;marked:Column|null;wave:{source:Column;exit:Column}|null;splash:boolean;pickup:Find|null;outcome:CourtState["outcome"] } + +export function chartFrames(start:{area:Area;tool:Tool;banked:readonly BankedItem[]},commands:readonly string[]):ChartFrame[]|null { + let state:CourtState;try{state=startCourt(start);}catch{return null;} + if(!Array.isArray(commands)||commands.length>TURN_LIMIT)return null; + const frames:ChartFrame[]=[{index:0,command:null,position:{...state.position},bridge:state.bridge,opened:[...state.opened],cargo:[...state.cargo], + phase:phaseOf(state),marked:state.locked,wave:null,splash:false,pickup:null,outcome:state.outcome}]; + for(const command of commands){ + const turn=applyCommand(state,command);if(!turn)return null; + const wave=turn.events.find(event=>event.kind==="wave"),pickup=turn.events.find(event=>event.kind==="pickup"); + state=turn.after; + frames.push({index:frames.length,command,position:{...state.position},bridge:state.bridge,opened:[...state.opened],cargo:[...state.cargo], + phase:phaseOf(turn.before),marked:state.locked,wave:wave?{source:wave.source,exit:wave.exit}:null,splash:turn.events.some(event=>event.kind==="hit"),pickup:pickup?.item??null,outcome:state.outcome}); + } + return frames; +} + +export function chartLines(frames:readonly ChartFrame[],area:Area):string[] { + const columns=["left","center","right"]; + return frames.slice(1).map((frame,i)=>{ + const command=frame.command??""; + let action="waits for the tide"; + if(command.startsWith("step:"))action=`steps ${command.slice(5)} onto row ${frame.position.y}, ${columns[frame.position.x]} column`; + else if(command.startsWith("reel:"))action=`reels in the ${command.slice(5)}`; + else if(command.startsWith("take:"))action=`takes the ${command.slice(5)}`; + else if(command.startsWith("lure:"))action=`lures the wave to the ${command.slice(5)} column`; + else if(command==="turn:vane")action=`turns the ${area==="wind"?"wheel":"vane"}`; + else if(command==="return")action=frame.cargo.length?`comes home with ${frame.cargo.map(item=>`the ${item}`).join(" and ")}`:"comes home empty-pawed"; + let line=`${frame.index}. Mochi ${action}.`; + if(frame.wave)line+=frame.wave.source===frame.wave.exit?` A wave runs down the ${columns[frame.wave.source]} lane.`: + ` A wave rises on the ${columns[frame.wave.source]} and runs out on the ${columns[frame.wave.exit]}.`; + if(frame.splash)line+=" It soaks her."; + if(frame.outcome==="rescued"&&frames[i]!.outcome!=="rescued")line+=" She is rescued and carried home."; + return line; + }); +} diff --git a/web/src/tide/day.test.ts b/web/src/tide/day.test.ts new file mode 100644 index 0000000..381dbc3 --- /dev/null +++ b/web/src/tide/day.test.ts @@ -0,0 +1,26 @@ +import { expect, test } from "bun:test"; +import { msUntilNextTideDay, tideDay } from "./cards"; + +const delay = msUntilNextTideDay; +const midnight = Date.parse("2026-11-15T00:00:00.000Z"); + +test("the tide timer waits only until the next UTC midnight", () => { + expect(delay(midnight - 10_000)).toBe(10_000); + expect(delay(midnight - 1)).toBe(1); + expect(delay(midnight + 1)).toBe(86_399_999); +}); + +test("exactly at midnight the next tide boundary is a whole day away", () => { + expect(delay(midnight)).toBe(86_400_000); + expect(delay(0)).toBe(86_400_000); +}); + +test("the timer reaches the next day for UTC and offset timestamps", () => { + for (const now of [midnight - 1, midnight, Date.parse("2026-11-14T19:00:00-05:00"), -1]) { + const wait = delay(now); + expect(wait).toBeGreaterThan(0); + expect(wait).toBeLessThanOrEqual(86_400_000); + expect(tideDay(now + wait - 1)).toBe(tideDay(now)); + expect(tideDay(now + wait)).toBe(tideDay(now) + 1); + } +}); diff --git a/web/src/tide/home-ui.test.tsx b/web/src/tide/home-ui.test.tsx new file mode 100644 index 0000000..0582ff5 --- /dev/null +++ b/web/src/tide/home-ui.test.tsx @@ -0,0 +1,136 @@ +import { expect, test } from "bun:test"; +import { renderToStaticMarkup } from "react-dom/server"; +import { cardForDay } from "./cards"; +import { replayRun, solve } from "./asks"; +import TideHome from "./TideHome"; +import type { DayResult } from "./run-day"; + +const card = cardForDay(20771), run = replayRun(card.tool, solve(card.tool, card.asks)!)!; +const base = {card, run, canShelve:true, reduced:false, notice:"Home with Beacon Lens.", sailBlockedReason:null, onBram:()=>{}, onSail:()=>{}, onOpenLog:()=>{}}; + +test("the Home sheet shows the actual three asks and one next action", () => { + const html = renderToStaticMarkup(); + expect(html).toContain("All three asks kept."); + expect(html).toContain("9 decisions · the Tidekeeper’s way"); + expect(html).toContain("Home with Beacon Lens."); + expect(html).toContain("Take it to Bram"); + expect(html).toContain("See the tide log"); + expect(html).toContain('src="/assets/ui/mochi-portrait-proud.webp"'); + expect(html).toMatch(/]*class="tide-home-portrait"[^>]*width="72"[^>]*height="72"[^>]*alt=""[^>]*decoding="async"/); + expect(html.match(/data-kept="true"/g)).toHaveLength(3); + expect(html.match(/class="exp-primary"/g)).toHaveLength(1); + expect(html).toContain('data-press="true"'); + for (const delay of [360,480,600]) expect(html).toContain(`--ask-delay:${delay}ms`); +}); + +test("reduced motion renders a final result and sailing explains its block", () => { + const reason = "Finish the outing in progress first."; + const html = renderToStaticMarkup(); + expect(html).toContain("All three asks kept."); + expect(html).toContain("Sail again"); + expect(html).not.toContain("data-press"); + expect(html).toContain('aria-disabled="true"'); + expect(html).toContain("aria-describedby="); + expect(html).toContain(reason); +}); + +test("an empty replay cannot borrow the successful day's headline", () => { + const empty = replayRun(card.tool, ["return"])!; + const html = renderToStaticMarkup(); + expect(html).toContain("An empty satchel keeps no asks."); + expect(html).not.toContain("All three asks kept."); + expect(html.match(/data-kept="false"/g)).toHaveLength(3); + expect(html).not.toContain("Take it to Bram"); + expect(html).not.toContain("mochi-portrait-proud"); +}); + +test("a returned haul with a slipped ask has no proud portrait", () => { + const partial = { ...run, state: { ...run.state, resolve: 3 } }; + const html = renderToStaticMarkup(); + expect(html).toContain('data-kept="false"'); + expect(html).not.toContain("mochi-portrait-proud"); +}); + +test("the Home sheet renders the supplied notice without rewriting it", () => { + const notice = "Home with Beacon Lens. All three asks kept."; + const html = renderToStaticMarkup(); + expect(html).toContain(`

${notice}

`); + expect(renderToStaticMarkup()).not.toContain('class="tide-home-note"'); +}); + +const runResult: DayResult = { day: 20771, score: 6, guess: 6, banked: ["reed", "reed", "reed", "glass", "pearl"], stamps: { home: true, guess: true, dry: true }, splashes: 0 }; +const runHome = { card, result: runResult, canShelve: true, reduced: false, notice: "Kept on this device.", sailBlockedReason: null, onBram: () => {}, onSail: () => {}, onOpenLog: () => {} }; + +test("the run Home sheet celebrates all three with one primary and a compact, readable haul", () => { + const html = renderToStaticMarkup(); + expect(html).toContain("All three kept."); + expect(html).toContain("Banked 6 · Bram guessed 6"); + expect(html).toContain('src="/assets/ui/mochi-portrait-proud.webp"'); + expect(html).toMatch(/]*class="tide-home-portrait"[^>]*width="72"[^>]*height="72"[^>]*alt=""[^>]*decoding="async"/); + expect(html).toContain('class="tide-stamp-seal"'); + expect(html).toContain('data-press="true"'); + expect(html.match(/data-kept="true"/g)).toHaveLength(3); + expect(html.match(/\(kept\)/g)).toHaveLength(3); + expect(html.match(/class="tide-ask-mark"/g)).toHaveLength(3); + for (const label of ["Came home with something", "Matched Bram’s guess", "Dry paws"]) expect(html).toContain(label); + for (const delay of [360, 480, 600]) expect(html).toContain(`--ask-delay:${delay}ms`); + for (const icon of ["/assets/season/purse.webp", "/assets/ui/ask-all-marks.webp", "/assets/ui/ask-dry.webp"]) expect(html).toContain(`src="${icon}" width="28" height="28" alt="" decoding="async"`); + const haul = html.match(/

[\s\S]*?<\/p>/)![0]; + expect(haul).toContain('Haul: 3 reed, 1 glass and 1 pearl.'); + for (const [path, count] of [["/assets/season/reed.webp", 3], ["/assets/season/glass.webp", 1], ["/assets/run/pearl.webp", 1]] as const) { + expect(haul).toContain(``); + } + expect(html).toContain('

Kept on this device.

'); + expect(html.match(/class="exp-primary"/g)).toHaveLength(1); + expect(html).toContain("Take it to Bram"); + expect(html).toContain("See the tide log"); + expect(html).not.toContain("Sail again for practice"); +}); + +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(); + expect(html).toContain("1 of 3 kept."); + expect(html).toContain("Came home with something"); + expect(html).toContain("Short of Bram’s guess"); + expect(html).toContain("One splash"); + expect(html.match(/\(kept\)/g)).toHaveLength(1); + expect(html.match(/\(slipped\)/g)).toHaveLength(2); + expect(html).not.toContain("mochi-portrait-proud"); + expect(html).not.toContain("tide-stamp-seal"); + expect(html).toContain("Sail again for practice"); + expect(html).not.toContain("Take it to Bram"); +}); + +test("an empty run haul renders no haul row and only banked prizes appear", () => { + const empty = { ...runResult, banked: [], score: 0, stamps: { home: false, guess: false, dry: false }, splashes: 2 }; + const html = renderToStaticMarkup(); + expect(html).toContain("Nothing kept this time."); + expect(html).toContain("Came home empty-pawed"); + expect(html).toContain("2 splashes"); + expect(html).not.toContain('class="tide-haul"'); + expect(html).not.toContain("mochi-portrait-proud"); + expect(html).not.toContain('class="tide-home-note"'); + const reedOnly = renderToStaticMarkup().match(/

[\s\S]*?<\/p>/)![0]; + expect(reedOnly).toContain("Haul: 2 reed."); + expect(reedOnly).not.toContain("glass.webp"); + expect(reedOnly).not.toContain("pearl.webp"); +}); + +test("the reduced run Home sheet shows the final result and explains a sailing block", () => { + const reason = "Finish the outing in progress first."; + const html = renderToStaticMarkup(); + expect(html).toContain('data-reduced="true"'); + expect(html).not.toContain("data-press"); + expect(html).toContain("All three kept."); + expect(html).toContain("Matched Bram’s guess"); + expect(html).toContain("Sail again for practice"); + const described = html.match(/class="exp-primary" aria-disabled="true" aria-describedby="([^"]+)"/); + expect(described).not.toBeNull(); + expect(html).toContain(`

${reason}

`); + expect(html).not.toMatch(/]*\sdisabled(?:[=>\s])/); + const shelve = renderToStaticMarkup(); + expect(shelve).toContain('aria-disabled="false"'); + expect(shelve).toContain("Take it to Bram"); + expect(shelve).not.toContain(reason); +}); diff --git a/web/src/tide/log-ui.test.tsx b/web/src/tide/log-ui.test.tsx new file mode 100644 index 0000000..0fdb6a7 --- /dev/null +++ b/web/src/tide/log-ui.test.tsx @@ -0,0 +1,80 @@ +import { expect, test } from "bun:test"; +import { renderToStaticMarkup } from "react-dom/server"; +import { CARD_PICTURE } from "./art"; +import { cardForDay, dayLabel } from "./cards"; +import { tideSummary, type TideEntry } from "./log"; +import { logPages } from "./pages"; +import type { DayResult } from "./run-day"; +import TideLog from "./TideLog"; + +const day = 20771, card = cardForDay(day); +const result: DayResult = { + day, score: 6, guess: 6, banked: ["reed", "reed", "reed", "glass", "pearl"], + stamps: { home: true, guess: true, dry: true }, splashes: 0, +}; +const legacy: TideEntry = { + day, cardId: card.id, tool: card.tool, commands: ["return"], kept: [true, false, true], + decisions: 1, outcome: "returned", late: false, attempts: 1, savedAt: "", +}; + +function render(run = result, entries: readonly TideEntry[] = []) { + const pages = logPages([], entries, [run]); + return renderToStaticMarkup( {}}/>); +} + +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('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'); + expect(html).toContain(`alt="${CARD_PICTURE[card.id]}"`); + expect(html).toContain('class="tide-haul"'); + expect(html).toContain('class="tide-sr">Haul: 3 reed, 1 glass and 1 pearl.'); + for (const prize of ["/assets/season/reed.webp", "/assets/season/glass.webp", "/assets/run/pearl.webp"]) { + 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('
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); + expect(html.match(/class="tide-ask-mark"/g)).toHaveLength(3); + expect(html.match(/data-kept="true"/g)).toHaveLength(3); + expect(html.match(/\(kept\)/g)).toHaveLength(3); + expect(html).not.toContain("--ask-delay"); + expect(html).not.toContain("data-arrival"); + expect(html).not.toContain("data-press"); + expect(html).not.toContain("Chart of Mochi’s route"); + expect(html).not.toContain('class="exp-primary"'); + expect(html).not.toContain("Sail this tide again"); + expect(html).not.toContain("Finish the outing in progress first."); +}); + +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("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("1 of 14 collected"); + expect(html).not.toContain("brass seal"); + expect(html).not.toContain('class="tide-stamp-seal"'); + expect(html).not.toContain('class="tide-haul"'); + for (const line of ["Came home empty-pawed", "Short of Bram’s guess", "2 splashes"]) expect(html).toContain(line); + expect(html.match(/data-kept="false"/g)).toHaveLength(3); + expect(html.match(/\(slipped\)/g)).toHaveLength(3); +}); + +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."'); + expect(html).toContain("1 of 14 collected, 1 with the brass seal"); + expect(html).toContain("Page 2 of 2"); +}); diff --git a/web/src/tide/log.test.ts b/web/src/tide/log.test.ts new file mode 100644 index 0000000..5dceabc --- /dev/null +++ b/web/src/tide/log.test.ts @@ -0,0 +1,131 @@ +import { expect, test } from "bun:test"; +import { TURN_LIMIT } from "../expedition/types"; +import { replayRun, solve, startRun, stepRun } from "./asks"; +import { cardForDay, tideDay, TIDE_POOL } from "./cards"; +import { betterTide, readTideLog, readTidePending, recordTide, tideLogKey, tideSummary, writeTidePending } from "./log"; +import type { DayResult } from "./run-day"; + +const memory=()=>{const m=new Map();return {getItem:(k:string)=>m.get(k)??null,setItem:(k:string,v:string)=>{m.set(k,v);},removeItem:(k:string)=>{m.delete(k);}};}; +const day=20771,card=cardForDay(day),route=solve(card.tool,card.asks)!; +const input=(commands:readonly string[]=route)=>({day,tool:card.tool,commands,late:false,now:new Date("2026-11-14T12:00:00Z")}); +const rescue=()=>{let run=startRun("rope");for(let i=0;i{ + const store=memory(),slow=recordTide("p",input(["wait","return"]),store); + expect(slow.improved).toBe(true);expect(slow.previous).toBeNull(); + const quick=recordTide("p",input(["return"]),store); + expect(quick.improved).toBe(true);expect(quick.entry.kept).toEqual(slow.entry.kept);expect(quick.entry.decisions).toBeLessThan(slow.entry.decisions); + const best=recordTide("p",input(),store); + expect(best.improved).toBe(true);expect(best.entry.kept).toEqual([true,true,true]);expect(best.entry.attempts).toBe(3); + const longer=["wait","wait","wait",...route];expect(replayRun(card.tool,longer)?.state.outcome).toBe("returned"); + const worse=recordTide("p",{...input(longer),late:true},store); + expect(worse.improved).toBe(false);expect(worse.previous).toEqual(best.entry);expect(worse.entry).toEqual({...best.entry,attempts:4}); + expect(recordTide("p",input(),store).improved).toBe(false);expect(readTideLog("p",store)[0]!.attempts).toBe(5); + expect(readTideLog("other",store)).toEqual([]); +}); + +test("rescues can be logged but never replace a returned outing",()=>{ + const store=memory(),commands=rescue(); + const first=recordTide("p",input(commands),store);expect(first.entry.outcome).toBe("rescued");expect(first.entry.kept).toEqual([false,false,false]); + const home=recordTide("p",input(["return"]),store);expect(home.improved).toBe(true); + const again=recordTide("p",input(commands),store);expect(again.improved).toBe(false);expect(again.entry).toEqual({...home.entry,attempts:3}); +}); + +test("an empty return logs no asks kept on every card",()=>{ + const store=memory(); + for(let day=0;dayentry.kept.every(kept=>!kept))).toBe(true); +}); + +for(const late of [false,true])test(`${late?"a late":"an on-time"} day keeps its timing after a better late run`,()=>{ + const store=memory();recordTide("p",{...input(["return"]),late},store); + const better=recordTide("p",{...input(),late:true},store); + expect(better.improved).toBe(true);expect(better.entry.kept).toEqual([true,true,true]);expect(better.entry.late).toBe(late); + expect(readTideLog("p",store)[0]!.late).toBe(late); +}); + +test("an on-time attempt updates the day even when its route is not better",()=>{ + const store=memory(),best=recordTide("p",{...input(),late:true},store).entry; + const worse=recordTide("p",input(["return"]),store); + expect(worse.improved).toBe(false);expect(worse.entry).toEqual({...best,late:false,attempts:2}); + expect(readTideLog("p",store)[0]!.late).toBe(false); +}); + +test("reading ignores broken data and derives scores from commands",()=>{ + const store=memory(),key=tideLogKey("p"); + for(const raw of ["{","null","{}"]){store.setItem(key,raw);expect(readTideLog("p",store)).toEqual([]);} + expect(readTideLog("p",{getItem:()=>{throw Error("blocked");}})).toEqual([]); + const good=recordTide("p",input(),store).entry; + store.setItem(key,JSON.stringify([null,{...good,commands:["step:south"]},{...good,day:1.5},{...good,late:0},{...good,tool:"net"},{...good,commands:[7]}, + {...good,cardId:"wrong",kept:[false,false,false],decisions:999,outcome:"rescued",attempts:0,savedAt:7}])); + expect(readTideLog("p",store)).toEqual([{...good,attempts:1,savedAt:""}]); +}); + +test("duplicate days keep the better return and the largest attempt count",()=>{ + const store=memory(),good=recordTide("p",input(),store).entry; + const poor={...good,commands:["return"],attempts:7},rescued={...good,commands:rescue(),attempts:9}; + for(const entries of [[good,poor,rescued],[rescued,poor,good]]){ + store.setItem(tideLogKey("p"),JSON.stringify(entries));expect(readTideLog("p",store)).toEqual([{...good,attempts:9}]); + } + const slow={...good,commands:["wait","return"],attempts:4}; + for(const entries of [[slow,poor],[poor,slow]]){ + store.setItem(tideLogKey("p"),JSON.stringify(entries));expect(readTideLog("p",store)[0]).toMatchObject({commands:["return"],decisions:1,attempts:7}); + } + let run=replayRun(card.tool,route.slice(0,3))!; + while(run.state.outcome==="active")run=stepRun(run,"wait")!; + expect(run.state.commands.length).toBeGreaterThan(rescued.commands.length); + const laterRescue={...rescued,commands:run.state.commands,attempts:12}; + for(const entries of [[laterRescue,rescued],[rescued,laterRescue]]){ + store.setItem(tideLogKey("p"),JSON.stringify(entries));expect(readTideLog("p",store)[0]).toMatchObject({commands:rescued.commands,attempts:12}); + } +}); + +test("only the highest ninety days remain",()=>{ + const store=memory();for(let i=0;i<95;i++)recordTide("p",{...input(["return"]),day:day+i},store); + const entries=readTideLog("p",store);expect(entries.length).toBe(90);expect(entries[0]!.day).toBe(day+5);expect(entries[89]!.day).toBe(day+94); +}); + +test("unfinished, invalid and silently unsaved outings are refused",()=>{ + const store=memory(); + for(const value of [{...input(),day:1.5},input([]),input(["step:south"])])expect(()=>recordTide("p",value,store)).toThrow(new RangeError("This outing cannot be logged.")); + expect(()=>recordTide("p",input(),{getItem:()=>null,setItem:()=>{}})).toThrow("The tide log could not be saved on this device."); +}); + +test("pending outings round-trip, clear and tolerate unavailable storage",()=>{ + const store=memory(),key="familiar.tide.pending.v1:p"; + expect(readTidePending("p",store)).toBeNull();writeTidePending("p",{day,late:true},store);expect(readTidePending("p",store)).toEqual({day,late:true}); + writeTidePending("p",null,store);expect(store.getItem(key)).toBeNull();expect(readTidePending("p",store)).toBeNull(); + for(const raw of ["{","null",'{"day":1.5,"late":false}','{"day":1,"late":0}']){store.setItem(key,raw);expect(readTidePending("p",store)).toBeNull();} + const blocked=()=>{throw Error("blocked");},broken={getItem:blocked,setItem:blocked,removeItem:blocked}; + expect(readTidePending("p",broken)).toBeNull();expect(()=>writeTidePending("p",{day,late:false},broken)).not.toThrow();expect(()=>writeTidePending("p",null,broken)).not.toThrow(); +}); + +test("an outing docked after midnight is scored for its pending day",()=>{ + const store=memory(),midnight=(day+1)*86_400_000; + writeTidePending("p",{day:tideDay(midnight-10_000),late:false},store); + const pending=readTidePending("p",store)!; + const recorded=recordTide("p",{...input(),...pending,now:new Date(midnight+10_000)},store).entry; + expect(recorded).toMatchObject({day,cardId:card.id,tool:card.tool,kept:[true,true,true],late:false}); + expect(readTidePending("p",store)).toEqual({day,late:false}); + expect(readTideLog("p",store).some(entry=>entry.day===tideDay(midnight))).toBe(false); +}); + +test("score comparison and summary count asks and complete cards",()=>{ + const all={kept:[true,true,true] as [boolean,boolean,boolean],decisions:9},one={kept:[true,false,false] as [boolean,boolean,boolean],decisions:1}; + expect(betterTide(all,one)).toBe(true);expect(betterTide(one,all)).toBe(false);expect(betterTide(all,all)).toBe(false); + expect(betterTide({...all,decisions:8},all)).toBe(true);expect(betterTide({...all,decisions:10},all)).toBe(false); + const store=memory(),entry=recordTide("p",input(),store).entry; + expect(tideSummary([entry,{...entry,...one}])).toEqual({sailed:2,kept:4,allThree:1});expect(tideSummary([])).toEqual({sailed:0,kept:0,allThree:0}); +}); + +test("summary adds run-day stamps to legacy asks without changing legacy totals", () => { + const entry = recordTide("p", input(), memory()).entry; + const result: DayResult = { day, score: 6, guess: 6, banked: ["reed"], stamps: { home: true, guess: true, dry: true }, splashes: 0 }; + const partial = { ...result, day: day + 1, stamps: { home: true, guess: false, dry: false } }; + expect(tideSummary([], [result, partial])).toEqual({ sailed: 2, kept: 4, allThree: 1 }); + expect(tideSummary([entry], [result, partial])).toEqual({ sailed: 3, kept: 7, allThree: 2 }); + expect(tideSummary([entry], [])).toEqual(tideSummary([entry])); +}); diff --git a/web/src/tide/log.ts b/web/src/tide/log.ts new file mode 100644 index 0000000..406de7a --- /dev/null +++ b/web/src/tide/log.ts @@ -0,0 +1,63 @@ +import type { Command, Tool } from "../expedition/types"; +import { cardStatus, replayRun } from "./asks"; +import { cardForDay } from "./cards"; +import { runSummary, type DayResult } from "./run-day"; + +export interface TideEntry { day:number;cardId:string;tool:Tool;commands:Command[];kept:[boolean,boolean,boolean];decisions:number;outcome:"returned"|"rescued";late:boolean;attempts:number;savedAt:string } +export const tideLogKey=(scope:string)=>`familiar.tide.log.v1:${scope}`; +const pendingKey=(scope:string)=>`familiar.tide.pending.v1:${scope}`; + +function score(day:number,tool:Tool,commands:readonly string[]) { + const run=replayRun(tool,commands);if(!run||run.state.outcome==="active")return null; + const card=cardForDay(day); + return {cardId:card.id,kept:cardStatus(card,run).map(status=>status==="kept") as [boolean,boolean,boolean],decisions:run.state.turn,outcome:run.state.outcome}; +} + +export function readTideLog(scope:string,store?:Pick):TideEntry[] { + try{ + const values=JSON.parse((store??localStorage).getItem(tideLogKey(scope))??"[]");if(!Array.isArray(values))return []; + const days=new Map(); + for(const value of values){ + if(!value||!Number.isSafeInteger(value.day)||(value.tool!=="rope"&&value.tool!=="lantern")||!Array.isArray(value.commands)|| + !value.commands.every((command:unknown)=>typeof command==="string")||typeof value.late!=="boolean")continue; + const scored=score(value.day,value.tool,value.commands);if(!scored)continue; + const entry:TideEntry={day:value.day,tool:value.tool,commands:[...value.commands],...scored,late:value.late, + attempts:Number.isInteger(value.attempts)&&value.attempts>0?value.attempts:1,savedAt:typeof value.savedAt==="string"?value.savedAt:""}; + const previous=days.get(entry.day); + const best=!previous||(entry.outcome===previous.outcome?betterTide(entry,previous):entry.outcome==="returned")?entry:previous; + days.set(entry.day,{...best,attempts:Math.max(entry.attempts,previous?.attempts??1)}); + } + return [...days.values()].sort((a,b)=>a.day-b.day); + }catch{return [];} +} + +export function betterTide(a:Pick,b:Pick):boolean { + const kept=a.kept.filter(Boolean).length-b.kept.filter(Boolean).length; + return kept>0||kept===0&&a.decisions):{entry:TideEntry;improved:boolean;previous:TideEntry|null} { + const scored=Number.isSafeInteger(input.day)?score(input.day,input.tool,input.commands):null; + if(!scored)throw new RangeError("This outing cannot be logged."); + store=store??localStorage; + const log=readTideLog(scope,store),previous=log.find(entry=>entry.day===input.day)??null; + const candidate:TideEntry={day:input.day,tool:input.tool,commands:[...input.commands] as Command[],...scored,late:input.late&&(previous?.late??true), + attempts:(previous?.attempts??0)+1,savedAt:(input.now??new Date()).toISOString()}; + const improved=previous===null||candidate.outcome==="returned"&&(previous.outcome==="rescued"||betterTide(candidate,previous)); + const entry=improved?candidate:{...previous!,late:candidate.late,attempts:candidate.attempts}; + const next=[...log.filter(value=>value.day!==input.day),entry].sort((a,b)=>a.day-b.day).slice(-90),text=JSON.stringify(next),key=tideLogKey(scope); + store.setItem(key,text);if(store.getItem(key)!==text)throw Error("The tide log could not be saved on this device."); + return {entry,improved,previous}; +} + +export interface TidePending { day:number;late:boolean } +export function readTidePending(scope:string,store?:Pick):TidePending|null { + try{const value=JSON.parse((store??localStorage).getItem(pendingKey(scope))??"null");return value&&Number.isSafeInteger(value.day)&&typeof value.late==="boolean"?{day:value.day,late:value.late}:null;}catch{return null;} +} +export function writeTidePending(scope:string,pending:TidePending|null,store?:Pick):void { + try{store=store??localStorage;if(pending===null)store.removeItem(pendingKey(scope));else store.setItem(pendingKey(scope),JSON.stringify({day:pending.day,late:pending.late}));}catch{} +} +export function tideSummary(entries:readonly TideEntry[],results:readonly DayResult[]=[]):{sailed:number;kept:number;allThree:number} { + const runs=runSummary(results); + return {sailed:entries.length+runs.sailed,kept:entries.reduce((sum,entry)=>sum+entry.kept.filter(Boolean).length,0)+runs.kept,allThree:entries.filter(entry=>entry.kept.every(Boolean)).length+runs.allThree}; +} diff --git a/web/src/tide/pages.test.ts b/web/src/tide/pages.test.ts new file mode 100644 index 0000000..05b7d87 --- /dev/null +++ b/web/src/tide/pages.test.ts @@ -0,0 +1,498 @@ +import { describe, expect, test } from "bun:test"; +import { CONTENT_VERSION } from "../expedition/types"; +import { replayRun, solve, startRun, stepRun, type Run } from "./asks"; +import { cardForDay, TIDE_POOL } from "./cards"; +import type { TideEntry } from "./log"; +import type { DayResult } from "./run-day"; +import { + askFlips, devTideDay, earlierDays, harborTide, homeResult, logPages, outingNotice, pageForCard, pageForDay, restartTide, + runPages, stampSheet, storyPages, storyTitle, tideObjective, tidePages, tideResult, todayView, type StoryRecord, type TideLink, +} from "./pages"; + +const today = 20771; +const card = cardForDay(today); +const next = cardForDay(today + 1); +const commands = solve(card.tool, card.asks)!; +const returned = replayRun(card.tool, commands)!; + +function result(day = today, overrides: Partial = {}): DayResult { + return { day, score: 6, guess: 6, banked: ["reed", "glass"], stamps: { home: true, guess: true, dry: true }, splashes: 0, ...overrides }; +} + +function entry(day = today, overrides: Partial = {}): TideEntry { + const daily = cardForDay(day); + const route = day === today ? commands : solve(daily.tool, daily.asks)!; + return { + day, cardId: daily.id, tool: daily.tool, commands: [...route], + kept: [true, true, true], decisions: route.length, outcome: "returned", + late: false, attempts: 1, savedAt: "2026-11-14T00:00:00.000Z", ...overrides, + }; +} + +function story(id: string, overrides: Partial = {}): StoryRecord { + return { + id, contentVersion: CONTENT_VERSION, outcome: "returned", cargo: ["lens"], + area: "beacon", tool: "rope", banked: ["chart"], commands: ["wait", "return"], + ...overrides, + }; +} + +function waits(count: number): Run { + return replayRun(card.tool, Array.from({ length: count }, () => "wait"))!; +} + +describe("story pages", () => { + test("titles follow the cargo priority", () => { + expect(storyTitle(["moth", "vane", "lens"])).toBe("The lens and the moth come home"); + expect(storyTitle(["lens", "vane"])).toBe("The lens comes home"); + expect(storyTitle(["moth", "vane"])).toBe("The moth comes home"); + expect(storyTitle(["vane"])).toBe("The vane comes home"); + expect(storyTitle(["chart", "salvage"])).toBe("Mochi comes home"); + expect(storyTitle([])).toBe("Mochi comes home"); + }); + + test("filters incompatible and empty returns, keeps stored order and the first id", () => { + const first = story("z"); + const second = story("a", { area: "wind", tool: "lantern", cargo: ["vane"] }); + const records = [ + story("rescued", { outcome: "rescued" }), story("empty", { cargo: [] }), + story("old", { contentVersion: "first_light_v1" }), first, second, + story("z", { cargo: ["moth"] }), + ]; + const pages = storyPages(records); + expect(pages).toEqual([ + { + kind: "story", id: "z", title: "The lens comes home", + subtitle: "Beacon Court · the rope · 2 decisions", + area: first.area, tool: first.tool, banked: first.banked, commands: first.commands, + }, + { + kind: "story", id: "a", title: "The vane comes home", + subtitle: "Wind Gate · the lantern · 2 decisions", + area: second.area, tool: second.tool, banked: second.banked, commands: second.commands, + }, + ]); + expect(pages[0]!.banked).toBe(first.banked); + expect(pages[0]!.commands).toBe(first.commands); + expect(records[3]).toBe(first); + expect(storyPages([])).toEqual([]); + }); +}); + +describe("tide history", () => { + test("sorts a copy by day and derives cards from the day", () => { + const later = entry(today + 1, { cardId: "stale-card" }); + const earlier = entry(); + const entries = Object.freeze([later, earlier]); + expect(tidePages(entries)).toEqual([ + { kind: "tide", day: today, card, entry: earlier }, + { kind: "tide", day: today + 1, card: cardForDay(today + 1), entry: later }, + ]); + expect(entries).toEqual([later, earlier]); + expect(tidePages([])).toEqual([]); + }); + + test("places stories before tides and finds requested or final pages", () => { + const records = [story("z"), story("a")]; + const entries = [entry(today + 1), entry()]; + const pages = logPages(records, entries); + expect(pages).toEqual([...storyPages(records), ...tidePages(entries)]); + expect(pageForDay(pages, today)).toBe(2); + expect(pageForDay(pages, today + 1)).toBe(3); + expect(pageForDay(pages, -1)).toBe(3); + expect(pageForDay(pages)).toBe(3); + expect(pageForDay([], today)).toBe(0); + expect(pageForDay([])).toBe(0); + expect(logPages([], [])).toEqual([]); + }); + + test("matches today and earlier logged days, including gaps, most recent first", () => { + const current = entry(); + const previous = entry(today - 2); + const entries = [previous, current, entry(today + 1)]; + expect(todayView(today, entries)).toEqual({ day: today, card, entry: current }); + expect(todayView(today, entries).entry).toBe(current); + expect(todayView(today, entries).card.id).toBe("surf-home"); + expect(todayView(today + 1, []).card.id).toBe("brams-bridge"); + expect(todayView(today + 1, []).entry).toBeNull(); + const earlier = earlierDays(today, entries); + expect(earlier.map(view => view.day)).toEqual([20770, 20769]); + expect(earlier.map(view => view.entry)).toEqual([null, previous]); + expect(earlier.map(view => view.card)).toEqual(earlier.map(view => cardForDay(view.day))); + expect(earlierDays(today, entries, 2)).toEqual(earlier.slice(0, 2)); + expect(earlierDays(today, entries, 0)).toEqual([]); + expect(earlierDays(today, [])).toEqual([]); + const yesterday = entry(today - 1); + expect(earlierDays(today, [yesterday])).toEqual([{ day: today - 1, card: cardForDay(today - 1), entry: yesterday }]); + expect(earlierDays(today, [current])).toEqual([]); + expect(earlierDays(today, [entry(today - 10)], 20).map(view => view.day)).toEqual([20770, 20769, 20768, 20767, 20766, 20765]); + }); +}); + +describe("stamp sheet", () => { + test("keeps all fourteen slots in pool order, hiding cards without returned outings", () => { + const collected = entry(today, { kept: [false, false, false] }); + const rescued = entry(today + 1, { outcome: "rescued" }); + const entries = Object.freeze([rescued, collected]); + const sheet = stampSheet(entries); + expect(sheet.map(slot => slot.card)).toEqual([...TIDE_POOL]); + expect(sheet).toHaveLength(14); + expect(sheet.find(slot => slot.card.id === collected.cardId)).toEqual({ card, entry: collected, result: null, allThree: false }); + expect(sheet.filter(slot => slot.entry !== null)).toHaveLength(1); + expect(sheet.find(slot => slot.card.id === rescued.cardId)?.entry).toBeNull(); + expect(stampSheet([]).every(slot => slot.entry === null && !slot.allThree)).toBe(true); + expect(entries).toEqual([rescued, collected]); + }); + + test("collects the best returned run across repeated fourteen-day cycles", () => { + const partial = entry(today, { kept: [true, false, true], decisions: 3 }); + const complete = entry(today + 14, { decisions: 12 }); + const quicker = entry(today + 28, { decisions: 10 }); + const rescued = entry(today + 42, { outcome: "rescued", decisions: 1 }); + expect(cardForDay(partial.day)).toBe(cardForDay(quicker.day)); + const slot = stampSheet([rescued, quicker, partial, complete]).find(slot => slot.card.id === card.id)!; + expect(slot.entry).toBe(quicker); + expect(slot.allThree).toBe(true); + }); + + test("breaks exact score ties by earlier day regardless of input order", () => { + const earlier = entry(today, { decisions: 11, kept: [true, false, true] }); + const later = entry(today + 14, { decisions: 11, kept: [false, true, true] }); + for (const entries of [[later, earlier], [earlier, later]]) { + const slot = stampSheet(entries).find(slot => slot.card.id === card.id)!; + expect(slot.entry).toBe(earlier); + expect(slot.allThree).toBe(false); + } + }); + + test("finds a card’s best returned page among story pages and repeated days", () => { + const partial = entry(today, { kept: [true, false, true], decisions: 3 }); + const best = entry(today + 14, { decisions: 10 }); + const tiedLater = entry(today + 28, { decisions: 10 }); + const rescued = entry(today + 42, { outcome: "rescued", decisions: 1 }); + const pages = [...storyPages([story("first")]), ...tidePages([partial, best, tiedLater, rescued])]; + expect(pageForCard(pages, card.id)).toBe(2); + const reversed = [...pages].reverse(); + expect(pageForCard(reversed, card.id)).toBe(2); + expect(pageForCard(pages, cardForDay(today + 1).id)).toBe(-1); + expect(pageForCard(tidePages([rescued]), card.id)).toBe(-1); + expect(pageForCard([], card.id)).toBe(-1); + }); +}); + +describe("outing copy", () => { + test("reports saved returns and rescues", () => { + expect(tideResult(entry(today, { kept: [true, false, true], decisions: 12 }))) + .toBe("2 of 3 asks kept in 12 decisions."); + expect(tideResult(entry())).toBe(`All three asks kept in ${commands.length} decisions. The Tidekeeper’s way.`); + expect(tideResult(entry(today, { decisions: card.best + 1 }))).toBe(`All three asks kept in ${card.best + 1} decisions.`); + expect(tideResult(entry(today, { kept: [true, false, false], decisions: 1 }))).toBe("1 of 3 asks kept in 1 decision."); + expect(tideResult(entry(today, { commands: ["return"], kept: [false, false, false], decisions: 1 }))).toBe("An empty satchel keeps no asks."); + expect(tideResult(entry(today, { outcome: "rescued" }))) + .toBe("Bram brought Mochi home. The asks can wait for another try."); + }); + + test("describes this return, then compares it with the saved best", () => { + const best = entry(); + const partial = stepRun(startRun(card.tool), "return")!; + expect(returned.state.outcome).toBe("returned"); + expect(outingNotice(returned, card, { entry: best, improved: true, previous: null })) + .toBe(`All three asks kept in ${commands.length} decisions. The Tidekeeper’s way.`); + expect(outingNotice(returned, card, { entry: best, improved: true, previous: entry(today, { decisions: 10 }) })) + .toBe(`All three asks kept in ${commands.length} decisions. The Tidekeeper’s way. A new best for the day.`); + expect(outingNotice(partial, card, { entry: best, improved: false, previous: best })) + .toBe(`An empty satchel keeps no asks. The day’s best stays at 3 of 3 in ${commands.length} decisions.`); + }); + + test("describes this rescue even when the stored best returned", () => { + const rescued = waits(9); + expect(rescued.state.outcome).toBe("rescued"); + const best = entry(); + expect(outingNotice(rescued, card, { entry: best, improved: false, previous: best })) + .toBe("Bram brought Mochi home. The asks slipped this time; the tide log keeps the try."); + }); + + test("chooses the first open ask, using the outing’s actual tool", () => { + expect(tideObjective(card, startRun(card.tool))).toBe("Bring the lens home."); + const coiled = cardForDay(7); + const withoutHaul = { ...coiled, asks: [coiled.asks[1], coiled.asks[0], coiled.asks[2]] as const }; + expect(tideObjective(withoutHaul, startRun("lantern"))).toBe("Leave the lantern unlit."); + const slippedFirst = { ...card, asks: [{ kind: "style", style: "dry" }, card.asks[0], card.asks[2]] as const }; + expect(tideObjective(slippedFirst, waits(3))).toBe("Bring the lens home."); + expect(tideObjective(card, returned)).toBe("Bring Mochi home at the center dock."); + }); + + test("announces a second soaking as a slip and ignores unsettled steps", () => { + const before = waits(5); + const after = stepRun(before, "wait")!; + expect(before.state.resolve).toBe(2); + expect(after.state.resolve).toBe(1); + expect(askFlips(card, before, after)).toBe("One ask slipped: Let one surge soak Mochi. Only one."); + const start = startRun(card.tool); + expect(askFlips(card, start, stepRun(start, "wait")!)).toBe(""); + expect(askFlips(card, after, after)).toBe(""); + }); + + test("joins kept transitions in ask order and uses the actual tool", () => { + const before = replayRun(card.tool, commands.slice(0, -1))!; + expect(askFlips(card, before, returned)).toBe( + "Ask kept: Bring the lens home. Ask kept: Let one surge soak Mochi. Only one. Ask kept: Be home within 10 decisions.", + ); + const coiled = cardForDay(7); + const route = ["wait", "step:west", "wait", "step:north", "step:north", "take:lens", "step:south", "step:east", "return"]; + const home = replayRun("lantern", route)!; + expect(home.state.cargo).toEqual(["lens"]); + expect(askFlips(coiled, replayRun("lantern", route.slice(0, -1))!, home)).toBe( + "One ask slipped: Bring both finds home. Ask kept: Leave the lantern unlit. Ask kept: Be home within 16 decisions.", + ); + const start = startRun("lantern"); + expect(askFlips(coiled, start, stepRun(start, "return")!)).toBe( + "All three asks slipped: Bring both finds home. Leave the lantern unlit. Be home within 16 decisions.", + ); + }); + + test("groups two asks that slip in the same decision", () => { + const double = { ...card, asks: [{ kind: "style", style: "no-wait" }, { kind: "within", decisions: 1 }, card.asks[0]] as const }; + const start = startRun(card.tool); + expect(askFlips(double, start, stepRun(start, "wait")!)).toBe("Two asks slipped: Never wait for the tide. Be home within 1 decision."); + }); +}); + +describe("home result", () => { + test("describes the actual return independently of the saved best", () => { + expect(homeResult(returned, card)).toEqual({title:"All three asks kept.",body:"9 decisions · the Tidekeeper’s way"}); + expect(homeResult(replayRun(card.tool, ["return"])!, card)).toEqual({title:"An empty satchel keeps no asks.",body:"1 decision"}); + let rescued = startRun(card.tool); + while (rescued.state.outcome === "active") rescued = stepRun(rescued, "wait")!; + expect(homeResult(rescued, card)).toEqual({title:"Bram brought Mochi home.",body:"The asks can wait for another try."}); + }); + + test("keeps slipped wording and only names a matched way", () => { + expect(homeResult(returned, {...card, best:1})).toEqual({title:"All three asks kept.",body:"9 decisions"}); + const dry = {...card,asks:[card.asks[0],{kind:"style",style:"dry"},card.asks[2]] as const}; + expect(homeResult(returned,dry)).toEqual({title:"One ask slipped.",body:"9 decisions"}); + }); +}); + +describe("harbor tide", () => { + const base = {lit:true,card,next,returnedToday:false,shelved:false}; + const links: TideLink[] = [{label:"Sail today’s tide again",action:"sail"},{label:"Open the tide log",action:"log"}]; + + test("keeps the harbor quiet before the light", () => { + expect(harborTide({...base,lit:false,entry:null})).toBeNull(); + expect(harborTide({...base,lit:false,entry:entry()})).toBeNull(); + }); + + test("introduces an unrecorded ask", () => { + expect(harborTide({...base,entry:null})).toEqual({ + kind:"panel",title:"The Tidekeeper has an ask.",body:"Surf home. Three asks for one tide, with the rope.", + primary:{label:"See today’s ask",target:"tide"},links:[], + }); + }); + + test("keeps the next step honest even when the separate tide log is missing", () => { + expect(harborTide({...base,returnedToday:true,entry:null})).toMatchObject({ + primary:{label:"Take it to Bram",target:"bram"},links:[], + }); + expect(harborTide({...base,shelved:true,entry:null})).toMatchObject({ + title:"Tomorrow: Bram’s bridge.",body:"Today’s haul is on Bram’s shelf.",primary:null,links, + }); + }); + + test("makes today's unshelved find the next step", () => { + expect(harborTide({...base,returnedToday:true,entry:entry()})).toEqual({ + kind:"panel",title:"All three asks kept.",body:"9 decisions · the Tidekeeper’s way", + primary:{label:"Take it to Bram",target:"bram"},links, + }); + }); + + test("a sailed tide offers replay and log as secondaries", () => { + expect(harborTide({...base,entry:entry()})).toEqual({ + kind:"panel",title:"All three asks kept.",body:"9 decisions · the Tidekeeper’s way",primary:null,links, + }); + expect(harborTide({...base,entry:entry(today,{decisions:11})})).toMatchObject({body:"11 decisions; the Tidekeeper’s way takes 9."}); + expect(harborTide({...base,card:{...card,best:1},entry:entry(today,{decisions:1})})).toMatchObject({body:"1 decision · the Tidekeeper’s way"}); + }); + + test("names tomorrow only after Bram has shelved today's haul", () => { + expect(harborTide({...base,returnedToday:true,shelved:true,entry:entry()})).toEqual({ + kind:"panel",title:"Tomorrow: Bram’s bridge.",body:"All three asks kept. 9 decisions · the Tidekeeper’s way",primary:null,links, + }); + }); + + test("names one, two or all three slipped asks honestly", () => { + for (const [kept,title,lines] of [ + [[true,false,true],"One ask slipped.","Let one surge soak Mochi. Only one."], + [[true,false,false],"Two asks slipped.","Let one surge soak Mochi. Only one. Be home within 10 decisions."], + [[false,false,false],"All three asks slipped.","Bring the lens home. Let one surge soak Mochi. Only one. Be home within 10 decisions."], + ] as const) { + expect(harborTide({...base,entry:entry(today,{kept:[...kept],decisions:11})})).toEqual({ + kind:"panel",title,body:`Slipped: ${lines}`,primary:null,links, + }); + } + }); + + test("a rescue and an empty return never invent a find", () => { + expect(harborTide({...base,entry:entry(today,{outcome:"rescued"})})).toEqual({ + kind:"panel",title:"Bram brought Mochi home.",body:"The asks can wait for another try.",primary:null,links, + }); + expect(harborTide({...base,entry:entry(today,{commands:["return"],kept:[false,false,false]})})).toMatchObject({ + title:"All three asks slipped.",primary:null,links, + }); + }); +}); + +describe("restart tide", () => { + test("keeps the pending day and the outing’s tool across rollover", () => { + for (const late of [false, true]) { + const pending = Object.freeze({ day: today, late }); + expect(restartTide(pending, today + 1, "rope")).toEqual({ tool: "rope", day: today }); + expect(pending).toEqual({ day: today, late }); + } + expect(restartTide({ day: today + 1, late: true }, today + 2, "rope")).toEqual({ tool: "rope", day: today + 1 }); + expect(restartTide({ day: today, late: false }, today, "lantern")).toEqual({ tool: "lantern", day: today }); + }); + + test("uses today and keeps the outing’s tool when no marker remains", () => { + expect(restartTide(null, today, "lantern")).toEqual({ tool: "lantern", day: today }); + expect(restartTide(null, today + 1, "rope")).toEqual({ tool: "rope", day: today + 1 }); + }); +}); + +describe("development tide day", () => { + test("accepts only signed safe integer query values", () => { + expect(devTideDay("?tide-day=20771")).toBe(20771); + expect(devTideDay("?other=1&tide-day=-12")).toBe(-12); + expect(devTideDay("?tide-day=0")).toBe(0); + expect(devTideDay("?tide-day=9007199254740991")).toBe(Number.MAX_SAFE_INTEGER); + expect(devTideDay("?tide-day=-9007199254740991")).toBe(Number.MIN_SAFE_INTEGER); + for (const value of ["", "1.5", "1e3", "NaN", "Infinity", "%2B1", "%201", "1%20", "1%0A", "12x", "--1", "9007199254740992", "-9007199254740992"]) { + expect(devTideDay(`?tide-day=${value}`)).toBeNull(); + } + expect(devTideDay("")).toBeNull(); + expect(devTideDay("?other=20771")).toBeNull(); + }); +}); + +describe("tide-run pages and stamps", () => { + test("sorts run pages without changing the input and derives the day's card", () => { + const earlier = result(today - 1), later = result(); + const results = Object.freeze([later, earlier]); + expect(runPages(results)).toEqual([ + { kind: "run", day: today - 1, card: cardForDay(today - 1), result: earlier }, + { kind: "run", day: today, card, result: later }, + ]); + expect(results).toEqual([later, earlier]); + expect(runPages([])).toEqual([]); + }); + + test("merges daily pages after stories with legacy pages first on the same day", () => { + const records = [story("first")]; + const pages = logPages(records, [entry(today + 1), entry()], [result(today + 2), result(), result(today - 1)]); + expect(pages.map(page => page.kind === "story" ? page.id : `${page.kind}:${page.day}`)).toEqual([ + "first", `run:${today - 1}`, `tide:${today}`, `run:${today}`, `tide:${today + 1}`, `run:${today + 2}`, + ]); + expect(pageForDay(pages, today)).toBe(3); + expect(pageForDay(pages, today + 1)).toBe(4); + expect(pageForDay(pages, today - 1)).toBe(1); + expect(pageForDay(pages, -1)).toBe(5); + expect(pageForDay(pages)).toBe(5); + }); + + test("a run alone collects a stamp, even when no stamp was kept", () => { + const empty = result(today, { banked: [], stamps: { home: false, guess: false, dry: false } }); + const slot = stampSheet([], [empty]).find(slot => slot.card.id === card.id)!; + expect(slot).toEqual({ card, entry: null, result: empty, allThree: false }); + expect(stampSheet([]).every(slot => slot.result === null)).toBe(true); + }); + + test("legacy slots carry a null run result", () => { + expect(stampSheet([entry()]).find(slot => slot.card.id === card.id)!.result).toBeNull(); + }); + + test("chooses a card's run by kept count, then score, then earlier day", () => { + const partial = result(today, { score: 100, stamps: { home: true, guess: false, dry: true } }); + const complete = result(today + 14, { score: 5 }); + const high = result(today + 28, { score: 8 }); + const tiedLater = result(today + 42, { score: 8 }); + for (const results of [[partial, complete, tiedLater, high], [high, tiedLater, complete, partial]]) { + const slot = stampSheet([], results).find(slot => slot.card.id === card.id)!; + expect(slot.result).toBe(high); + expect(slot.allThree).toBe(true); + } + const exactEarly = result(today, { score: 8 }); + expect(stampSheet([], [tiedLater, exactEarly]).find(slot => slot.card.id === card.id)?.result).toBe(exactEarly); + }); + + test("legacy and run results each contribute their best record and brass seals", () => { + const legacy = entry(); + const partial = result(today + 14, { stamps: { home: true, guess: false, dry: false } }); + const mixed = stampSheet([legacy], [partial]).find(slot => slot.card.id === card.id)!; + expect(mixed.entry).toBe(legacy); + expect(mixed.result).toBe(partial); + expect(mixed.allThree).toBe(true); + const legacyPartial = entry(today, { kept: [true, false, false] }); + expect(stampSheet([legacyPartial], [result()]).find(slot => slot.card.id === card.id)?.allThree).toBe(true); + }); + + test("page selection prefers more kept, then run pages, then each flow's best", () => { + const legacy = entry(); + const partial = result(today + 14, { score: 100, stamps: { home: true, guess: true, dry: false } }); + expect(pageForCard(logPages([], [legacy], [partial]), card.id)).toBe(0); + const complete = result(today + 28, { score: 8 }); + const tiedLater = result(today + 42, { score: 8 }); + const pages = logPages([story("first")], [legacy], [partial, tiedLater, complete]); + for (const ordered of [pages, [...pages].reverse()]) { + const best = ordered[pageForCard(ordered, card.id)]; + expect(best?.kind).toBe("run"); + if (best?.kind === "run") expect(best.result).toBe(complete); + } + expect(pageForCard(runPages([partial, complete]), next.id)).toBe(-1); + const rescued = entry(today, { outcome: "rescued" }); + expect(pageForCard(logPages([], [rescued], [partial]), card.id)).toBe(1); + }); +}); + +describe("tide-run harbor card", () => { + const base = { lit: true, card, next, guess: 6, returnedToday: false, shelved: false }; + const practice: TideLink[] = [{ label: "Sail again for practice", action: "sail" }, { label: "Open the tide log", action: "log" }]; + + test("stays quiet before the light, before and after a result", () => { + expect(harborTide({ ...base, lit: false, result: null })).toBeNull(); + expect(harborTide({ ...base, lit: false, result: result() })).toBeNull(); + }); + + 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.", + 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, + links: [{ label: "Sail today’s tide", action: "sail" }, { label: "Open the tide log", action: "log" }], + }); + }); + + test("an unshelved return offers Bram, then the practice and log links", () => { + expect(harborTide({ ...base, returnedToday: true, result: result() })).toEqual({ + kind: "panel", title: "All three kept.", body: "Banked 6 · Bram guessed 6.", + primary: { label: "Take it to Bram", target: "bram" }, links: practice, + }); + }); + + 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.", + body: "All three kept. Banked 6 · Bram guessed 6. Today’s haul is on Bram’s shelf.", primary: null, links: practice, + }); + }); + + test("a result without a fresh return offers only practice and the log", () => { + expect(harborTide({ ...base, result: result(today, { stamps: { home: true, guess: false, dry: false } }) })).toEqual({ + kind: "panel", title: "1 of 3 kept.", body: "Banked 6 · Bram guessed 6.", primary: null, links: practice, + }); + }); +}); diff --git a/web/src/tide/pages.ts b/web/src/tide/pages.ts new file mode 100644 index 0000000..c07fe16 --- /dev/null +++ b/web/src/tide/pages.ts @@ -0,0 +1,210 @@ +import { CONTENT_VERSION, type BankedItem, type Tool } from "../expedition/types"; +import type { ReturnRecord } from "../expedition/return-record"; +import { askStatus, keptCount, replayRun, type Run, type TideCard } from "./asks"; +import { askLine, cardForDay, TIDE_POOL } from "./cards"; +import { betterTide, type TideEntry, type TidePending } from "./log"; +import type { TideDayView } from "./TideAsk"; +import type { LogPage } from "./TideLog"; +import { keptCount as runKeptCount, resultLine, resultTitle, type DayResult } from "./run-day"; + +export type StoryRecord = Pick; + +export function storyTitle(cargo: readonly BankedItem[]): string { + if (cargo.includes("lens") && cargo.includes("moth")) return "The lens and the moth come home"; + if (cargo.includes("lens")) return "The lens comes home"; + if (cargo.includes("moth")) return "The moth comes home"; + if (cargo.includes("vane")) return "The vane comes home"; + return "Mochi comes home"; +} + +export function storyPages(records: readonly StoryRecord[]): Extract[] { + const seen = new Set(); + return records.filter(record => { + if (record.outcome !== "returned" || !record.cargo.length || record.contentVersion !== CONTENT_VERSION || seen.has(record.id)) return false; + seen.add(record.id); + return true; + }).map(record => ({ + kind: "story", id: record.id, title: storyTitle(record.cargo), + subtitle: `${record.area === "wind" ? "Wind Gate" : "Beacon Court"} · the ${record.tool} · ${record.commands.length} decisions`, + area: record.area, tool: record.tool, banked: record.banked, commands: record.commands, + })); +} + +export function tidePages(entries: readonly TideEntry[]): Extract[] { + return [...entries].sort((a, b) => a.day - b.day).map(entry => ({ + kind: "tide", day: entry.day, card: cardForDay(entry.day), entry, + })); +} + +export function runPages(results: readonly DayResult[]): Extract[] { + return [...results].sort((a, b) => a.day - b.day).map(result => ({ kind: "run", day: result.day, card: cardForDay(result.day), result })); +} + +/** Story pages first, then one page per day: a three-ask page before a tide-run page on the same day. */ +export function logPages(records: readonly StoryRecord[], entries: readonly TideEntry[], results: readonly DayResult[] = []): LogPage[] { + const days = [...tidePages(entries), ...runPages(results)].sort((a, b) => a.day - b.day || (a.kind === b.kind ? 0 : a.kind === "tide" ? -1 : 1)); + return [...storyPages(records), ...days]; +} + +export function pageForDay(pages: readonly LogPage[], day?: number): number { + const run = day === undefined ? -1 : pages.findIndex(page => page.kind === "run" && page.day === day); + if (run >= 0) return run; + const index = day === undefined ? -1 : pages.findIndex(page => page.kind === "tide" && page.day === day); + return index < 0 ? Math.max(0, pages.length - 1) : index; +} + +function bestReturn(entries: readonly TideEntry[], cardId: string): TideEntry | null { + let best: TideEntry | null = null; + for (const entry of entries) { + if (entry.cardId !== cardId || entry.outcome !== "returned") continue; + if (!best || betterTide(entry, best) || !betterTide(best, entry) && entry.day < best.day) best = entry; + } + return best; +} + +function bestRun(results: readonly DayResult[], cardId: string): DayResult | null { + let best: DayResult | null = null; + for (const result of results) { + if (cardForDay(result.day).id !== cardId) continue; + if (!best || runKeptCount(result) > runKeptCount(best) + || runKeptCount(result) === runKeptCount(best) && (result.score > best.score || result.score === best.score && result.day < best.day)) best = result; + } + return best; +} + +export interface StampSlot { card: TideCard; entry: TideEntry | null; result: DayResult | null; allThree: boolean } + +export function stampSheet(entries: readonly TideEntry[], results: readonly DayResult[] = []): StampSlot[] { + return TIDE_POOL.map(card => { + const entry = bestReturn(entries, card.id), result = bestRun(results, card.id); + return { card, entry, result, allThree: !!entry?.kept.every(Boolean) || !!result && runKeptCount(result) === 3 }; + }); +} + +export function pageForCard(pages: readonly LogPage[], cardId: string): number { + const entry = bestReturn(pages.flatMap(page => page.kind === "tide" ? [page.entry] : []), cardId); + const result = bestRun(pages.flatMap(page => page.kind === "run" ? [page.result] : []), cardId); + if (result && (!entry || runKeptCount(result) >= entry.kept.filter(Boolean).length)) return pages.findIndex(page => page.kind === "run" && page.result === result); + return entry ? pages.findIndex(page => page.kind === "tide" && page.entry === entry) : -1; +} + +export function todayView(today: number, entries: readonly TideEntry[]): TideDayView { + return { day: today, card: cardForDay(today), entry: entries.find(entry => entry.day === today) ?? null }; +} + +export function earlierDays(today: number, entries: readonly TideEntry[], count = 6): TideDayView[] { + const first = Math.min(today, ...entries.map(entry => entry.day)); + return Array.from({ length: Math.max(0, Math.min(6, count, today - first)) }, (_, index) => todayView(today - index - 1, entries)); +} + +const decisions = (count: number) => `${count} ${count === 1 ? "decision" : "decisions"}`; +const slippedTitle = (count: number) => count === 1 ? "One ask slipped" : count === 2 ? "Two asks slipped" : "All three asks slipped"; + +function returnResult(kept: number, turns: number, best: number, empty: boolean): string { + if (empty) return "An empty satchel keeps no asks."; + return `${kept === 3 ? "All three asks" : `${kept} of 3 asks`} kept in ${decisions(turns)}.` + + (kept === 3 && turns <= best ? " The Tidekeeper’s way." : ""); +} + +export function tideResult(entry: TideEntry): string { + return entry.outcome === "rescued" + ? "Bram brought Mochi home. The asks can wait for another try." + : returnResult(entry.kept.filter(Boolean).length, entry.decisions, cardForDay(entry.day).best, + replayRun(entry.tool, entry.commands)?.state.cargo.length === 0); +} + +export function outingNotice(run: Run, card: TideCard, recorded: { entry: TideEntry; improved: boolean; previous: TideEntry | null }): string { + if (run.state.outcome === "rescued") return "Bram brought Mochi home. The asks slipped this time; the tide log keeps the try."; + const result = returnResult(keptCount(card, run), run.state.turn, card.best, run.state.cargo.length === 0); + if (!recorded.previous) return result; + return result + (recorded.improved + ? " A new best for the day." + : ` The day’s best stays at ${recorded.entry.kept.filter(Boolean).length} of 3 in ${decisions(recorded.entry.decisions)}.`); +} + +export function homeResult(run: Run, card: TideCard): { title: string; body: string } { + if (run.state.outcome === "rescued") return { + title: "Bram brought Mochi home.", body: "The asks can wait for another try.", + }; + const kept = keptCount(card, run); + return { + title: run.state.cargo.length === 0 ? "An empty satchel keeps no asks." + : kept === 3 ? "All three asks kept." : `${slippedTitle(3 - kept)}.`, + body: `${decisions(run.state.turn)}${kept === 3 && run.state.turn <= card.best ? " · the Tidekeeper’s way" : ""}`, + }; +} + +export type TideLink = { label: string; action: "tide" | "log" | "sail" | "bram" }; +export type HarborTide = + { kind: "panel"; title: string; body: string; primary: { label: string; target: "tide" | "log" | "sail" | "bram" } | null; links: TideLink[] }; + +type ClassicHarbor = { lit: boolean; card: TideCard; next: TideCard; entry: TideEntry | null; returnedToday: boolean; shelved: boolean }; +/** 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 { + 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 }; + return { kind: "panel", title: resultTitle(result), body: `${resultLine(result)}.`, primary: returnedToday ? { label: "Take it to Bram", target: "bram" } : null, links }; +} + +export function harborTide(input: ClassicHarbor | RunHarbor): HarborTide | null { + if ("result" in input) return harborRun(input); + const { lit, card, next, entry, returnedToday, shelved } = input; + if (!lit) return null; + if (!entry) return { + kind: "panel", title: shelved ? `Tomorrow: ${next.name}.` : returnedToday ? "Mochi comes home." : "The Tidekeeper has an ask.", + body: shelved ? "Today’s haul is on Bram’s shelf." : `${card.name}. Three asks for one tide, with the ${card.tool}.`, + primary: shelved ? null : returnedToday ? { label: "Take it to Bram", target: "bram" } : { label: "See today’s ask", target: "tide" }, + links: shelved ? [{ label: "Sail today’s tide again", action: "sail" }, { label: "Open the tide log", action: "log" }] : [], + }; + const allThree = entry.outcome === "returned" && entry.kept.every(Boolean); + const slipped = card.asks.filter((_, index) => !entry.kept[index]); + const result = entry.outcome === "rescued" ? { + title: "Bram brought Mochi home.", body: "The asks can wait for another try.", + } : allThree ? { + title: "All three asks kept.", + body: `${decisions(entry.decisions)}${entry.decisions <= card.best ? " · the Tidekeeper’s way" : `; the Tidekeeper’s way takes ${card.best}.`}`, + } : { + title: `${slippedTitle(slipped.length)}.`, + body: `Slipped: ${slipped.map(ask => askLine(ask, card.tool)).join(" ")}`, + }; + return { + kind: "panel", title: shelved ? `Tomorrow: ${next.name}.` : result.title, + body: shelved ? `${result.title} ${result.body}` : result.body, + primary: returnedToday && !shelved ? { label: "Take it to Bram", target: "bram" } : null, + links: [{ label: "Sail today’s tide again", action: "sail" }, { label: "Open the tide log", action: "log" }], + }; +} + +export function tideObjective(card: TideCard, run: Run): string { + const ask = card.asks.find(ask => askStatus(ask, run) === "open"); + return ask ? askLine(ask, run.state.tool) : "Bring Mochi home at the center dock."; +} + +export function askFlips(card: TideCard, before: Run, after: Run): string { + const changes = card.asks.flatMap(ask => { + if (askStatus(ask, before) !== "open") return []; + const status = askStatus(ask, after); + return status === "open" ? [] : [{ status, line: askLine(ask, after.state.tool) }]; + }); + const slipped = changes.filter(change => change.status === "slipped"); + const firstSlip = changes.findIndex(change => change.status === "slipped"); + return changes.flatMap((change, index) => change.status === "kept" ? [`Ask kept: ${change.line}`] + : index === firstSlip ? [`${slippedTitle(slipped.length)}: ${slipped.map(item => item.line).join(" ")}`] : []).join(" "); +} + +export function restartTide(pending: TidePending | null, today: number, tool: Tool): { tool: Tool; day: number } { + return { tool, day: pending?.day ?? today }; +} + +export function devTideDay(search: string): number | null { + const value = new URLSearchParams(search).get("tide-day"); + if (value === null || !/^-?\d+$/.test(value)) return null; + const day = Number(value); + return Number.isSafeInteger(day) ? day : null; +} diff --git a/web/src/tide/run-day.test.ts b/web/src/tide/run-day.test.ts new file mode 100644 index 0000000..bd110a9 --- /dev/null +++ b/web/src/tide/run-day.test.ts @@ -0,0 +1,75 @@ +import { expect, test } from "bun:test"; +import { SHELF_CAP } from "../run/save"; +import { allKept, haulCount, haulWords, keptCount, resultLine, resultTitle, runSummary, shelfGoods, STAMPS, type DayResult } from "./run-day"; + +const result: DayResult = { + day: 20771, score: 6, guess: 6, banked: ["reed", "reed", "reed", "glass", "pearl"], + stamps: { home: true, guess: true, dry: true }, splashes: 0, +}; + +test("haul counts preserve every prize while shelf goods are glass first and capped separately", () => { + expect(haulCount(result)).toEqual({ reed: 3, glass: 1, pearl: 1 }); + expect(haulCount({ banked: [] })).toEqual({ reed: 0, glass: 0, pearl: 0 }); + expect(shelfGoods(result)).toEqual([1, 3]); + expect(shelfGoods({ banked: ["pearl", "pearl"] })).toEqual([0, 0]); + expect(shelfGoods({ banked: [] })).toEqual([0, 0]); + expect(shelfGoods({ banked: [...Array<"glass">(SHELF_CAP + 2).fill("glass"), ...Array<"reed">(SHELF_CAP + 1).fill("reed"), "pearl"] })).toEqual([SHELF_CAP, SHELF_CAP]); + expect(result.banked).toEqual(["reed", "reed", "reed", "glass", "pearl"]); +}); + +test("the three stamps retain their order, painted icons and exact asks", () => { + expect(STAMPS.map(stamp => stamp.key)).toEqual(["home", "guess", "dry"]); + expect(STAMPS.map(stamp => stamp.icon)).toEqual(["/assets/season/purse.webp", "/assets/ui/ask-all-marks.webp", "/assets/ui/ask-dry.webp"]); + expect(STAMPS.map(stamp => stamp.ask(6))).toEqual([ + "Come home with something.", "Match or beat Bram’s guess of 6.", "Keep Mochi dry the whole tide.", + ]); + expect(STAMPS[1]!.ask(0)).toBe("Match or beat Bram’s guess of 0."); + expect(STAMPS[1]!.ask(12)).toBe("Match or beat Bram’s guess of 12."); +}); + +test("kept stamp labels distinguish matching from beating Bram", () => { + expect(STAMPS.map(stamp => stamp.label(result))).toEqual(["Came home with something", "Matched Bram’s guess", "Dry paws"]); + expect(STAMPS[1]!.label({ ...result, score: 7 })).toBe("Beat Bram’s guess"); +}); + +test("slipped stamp labels explain empty paws, a short score and splash counts", () => { + const slipped = { ...result, score: 0, banked: [], stamps: { home: false, guess: false, dry: false }, splashes: 1 }; + expect(STAMPS.map(stamp => stamp.label(slipped))).toEqual(["Came home empty-pawed", "Short of Bram’s guess", "One splash"]); + expect(STAMPS[2]!.label({ ...slipped, splashes: 2 })).toBe("2 splashes"); + expect(STAMPS[2]!.label({ ...slipped, splashes: 0 })).toBe("0 splashes"); +}); + +test("kept counts and headlines cover every combination of three stamps", () => { + for (let mask = 0; mask < 8; mask++) { + const stamps = { home: !!(mask & 1), guess: !!(mask & 2), dry: !!(mask & 4) }; + const count = Number(stamps.home) + Number(stamps.guess) + Number(stamps.dry); + const finished = { ...result, stamps }; + expect(keptCount(finished)).toBe(count); + expect(allKept(finished)).toBe(count === 3); + expect(resultTitle(finished)).toBe(["Nothing kept this time.", "1 of 3 kept.", "2 of 3 kept.", "All three kept."][count]!); + } +}); + +test("the result line preserves score and Bram’s guess", () => { + expect(resultLine(result)).toBe("Banked 6 · Bram guessed 6"); + expect(resultLine({ ...result, score: 0, guess: 12 })).toBe("Banked 0 · Bram guessed 12"); +}); + +test("haul words join goods naturally, never pluralise reed and pluralise pearls", () => { + expect(haulWords(result)).toBe("3 reed, 1 glass and 1 pearl"); + expect(haulWords({ banked: [] })).toBe("nothing"); + expect(haulWords({ banked: ["reed"] })).toBe("1 reed"); + expect(haulWords({ banked: ["reed", "reed"] })).toBe("2 reed"); + expect(haulWords({ banked: ["glass", "glass"] })).toBe("2 glass"); + expect(haulWords({ banked: ["pearl"] })).toBe("1 pearl"); + expect(haulWords({ banked: ["pearl", "pearl"] })).toBe("2 pearls"); + expect(haulWords({ banked: ["glass", "reed"] })).toBe("1 reed and 1 glass"); + expect(haulWords({ banked: ["pearl", "reed", "pearl"] })).toBe("1 reed and 2 pearls"); +}); + +test("run summaries total sailed days, kept stamps and all-three days", () => { + expect(runSummary([])).toEqual({ sailed: 0, kept: 0, allThree: 0 }); + const partial = { ...result, day: result.day + 1, stamps: { home: true, guess: false, dry: true } }; + const empty = { ...result, day: result.day + 2, stamps: { home: false, guess: false, dry: false } }; + expect(runSummary([result, partial, empty])).toEqual({ sailed: 3, kept: 5, allThree: 1 }); +}); diff --git a/web/src/tide/run-day.ts b/web/src/tide/run-day.ts new file mode 100644 index 0000000..cc99f82 --- /dev/null +++ b/web/src/tide/run-day.ts @@ -0,0 +1,55 @@ +/** A finished daily tide run as the harbor's screens show it: its score, Bram's guess, the haul and the three stamps. */ +import type { Prize } from "../run/engine"; +import { SHELF_CAP } from "../run/save"; + +/** The same shape run/save.ts exports; declared here so these screens depend only on the record, not the run's storage. */ +export interface DayResult { + readonly day: number; + readonly score: number; + readonly guess: number; + readonly banked: readonly Prize[]; + /** Came home with something; matched or beat Bram's guess; no splash. */ + readonly stamps: { readonly home: boolean; readonly guess: boolean; readonly dry: boolean }; + readonly splashes: number; +} + +export type StampKey = keyof DayResult["stamps"]; +export interface Stamp { key: StampKey; icon: string; ask: (guess: number) => string; label: (result: DayResult) => string } + +export const STAMPS: readonly Stamp[] = [ + { key: "home", icon: "/assets/season/purse.webp", ask: () => "Come home with something.", + label: r => r.stamps.home ? "Came home with something" : "Came home empty-pawed" }, + { key: "guess", icon: "/assets/ui/ask-all-marks.webp", ask: guess => `Match or beat Bram’s guess of ${guess}.`, + label: r => !r.stamps.guess ? "Short of Bram’s guess" : r.score > r.guess ? "Beat Bram’s guess" : "Matched Bram’s guess" }, + { key: "dry", icon: "/assets/ui/ask-dry.webp", ask: () => "Keep Mochi dry the whole tide.", + label: r => r.stamps.dry ? "Dry paws" : r.splashes === 1 ? "One splash" : `${r.splashes} splashes` }, +]; + +export function haulCount(result: Pick): Record { + const count = { reed: 0, glass: 0, pearl: 0 }; + for (const prize of result.banked) count[prize]++; + return count; +} +/** What Bram can shelve, as the season model's [glass, reed]. Pearls never reach the shelf. */ +export function shelfGoods(result: Pick): [number, number] { + const count = haulCount(result); + return [Math.min(count.glass, SHELF_CAP), Math.min(count.reed, SHELF_CAP)]; +} +export const keptCount = (result: Pick) => Object.values(result.stamps).filter(Boolean).length; +export const allKept = (result: Pick) => keptCount(result) === 3; + +export function resultTitle(result: DayResult): string { + const kept = keptCount(result); + return kept === 3 ? "All three kept." : kept === 0 ? "Nothing kept this time." : `${kept} of 3 kept.`; +} +export const resultLine = (result: DayResult) => `Banked ${result.score} · Bram guessed ${result.guess}`; + +export function haulWords(result: Pick): string { + const { reed, glass, pearl } = haulCount(result); + const parts = [reed ? `${reed} reed` : "", glass ? `${glass} glass` : "", pearl ? `${pearl} pearl${pearl === 1 ? "" : "s"}` : ""].filter(Boolean); + return parts.length ? parts.length === 1 ? parts[0]! : `${parts.slice(0, -1).join(", ")} and ${parts.at(-1)}` : "nothing"; +} + +export function runSummary(results: readonly DayResult[]): { sailed: number; kept: number; allThree: number } { + return { sailed: results.length, kept: results.reduce((sum, result) => sum + keptCount(result), 0), allThree: results.filter(allKept).length }; +} diff --git a/web/src/tide/sailing-ui.test.tsx b/web/src/tide/sailing-ui.test.tsx new file mode 100644 index 0000000..48ca8ac --- /dev/null +++ b/web/src/tide/sailing-ui.test.tsx @@ -0,0 +1,43 @@ +import { expect, test } from "bun:test"; +import { renderToStaticMarkup } from "react-dom/server"; +import { cardForDay } from "./cards"; +import type { TideEntry } from "./log"; +import TideAsk from "./TideAsk"; +import TideLog from "./TideLog"; + +const day=20771,card=cardForDay(day); +const reason="This expedition is open in another tab. Finish there, or close that tab before continuing here."; +const entry:TideEntry={day,cardId:card.id,tool:card.tool,commands:["return"],kept:[false,false,false],decisions:1,outcome:"returned",late:false,attempts:1,savedAt:"2026-11-14T00:00:00.000Z"}; + +function explainsBlock(html:string,count:number){ + expect(html).toContain(reason); + expect(html).not.toContain("Finish the outing in progress first."); + const described=html.match(/aria-describedby="([^"]+)"/g)??[]; + expect(described).toHaveLength(count); + for(const attribute of described){ + const id=attribute.slice('aria-describedby="'.length,-1); + expect(html).toContain(`id="${id}">${reason}

`); + } + expect(html.match(/aria-disabled="true"/g)?.length).toBeGreaterThanOrEqual(count); +} + +test("today’s and earlier tides describe the actual sailing block",()=>{ + const props={today:{day,card,entry:null},earlier:[{day:day-1,card:cardForDay(day-1),entry:null}],sailBlockedReason:reason,onSail:()=>{},onOpenLog:()=>{}}; + explainsBlock(renderToStaticMarkup(),2); +}); + +test("a tide log replay describes the actual sailing block",()=>{ + const props={pages:[{kind:"tide" as const,day,card,entry}],reduced:true,sailBlockedReason:reason,summary:{sailed:1,kept:0,allThree:0},onSail:()=>{}}; + explainsBlock(renderToStaticMarkup(),1); +}); + +test("a ready tide and log leave sailing enabled without a blocked note",()=>{ + for(const html of [ + renderToStaticMarkup({}} onOpenLog={()=>{}}/>), + renderToStaticMarkup({}}/>), + ]){ + expect(html).toMatch(/class="exp-primary" aria-disabled="false"/); + expect(html).not.toContain("aria-describedby"); + expect(html).not.toContain("Finish the outing in progress first."); + } +}); diff --git a/web/src/tide/sailing.test.ts b/web/src/tide/sailing.test.ts new file mode 100644 index 0000000..23c0976 --- /dev/null +++ b/web/src/tide/sailing.test.ts @@ -0,0 +1,27 @@ +import { expect, test } from "bun:test"; +import { tideSailReason } from "./sailing"; + +const ready={lit:true,lease:"held" as const,problem:"",run:false,worldReady:true,showPassage:false,busy:false,pending:false}; + +test("a ready harbor can sail",()=>expect(tideSailReason(ready)).toBeNull()); + +for(const [state,reason] of [ + [{lit:false},"Restore the beacon before sailing today’s tide."], + [{lease:"waiting"},"Checking whether this tab can sail."], + [{lease:"blocked"},"This expedition is open in another tab. Finish there, or close that tab before continuing here."], + [{lease:"unavailable"},"This browser cannot safely coordinate saved expeditions. Web Locks support is required; no move has been taken."], + [{problem:"The saved expedition could not be read. Its original data has been preserved."},"The saved expedition could not be read. Its original data has been preserved."], + [{run:true},"Finish the outing in progress first."], + [{worldReady:false},"Opening the artwork. Mochi’s saved moves are safe."], + [{showPassage:true},"Finish the harbor crossing first."], + [{busy:true},"The original harbor action is still being checked."], + [{pending:true},"Resolve the original request before setting out from this harbor."], +] satisfies [Partial[0]>,string][])test(`sailing explains ${Object.keys(state)[0]}`,()=>{ + expect(tideSailReason({...ready,...state})).toBe(reason); +}); + +test("a lease or saved-data problem takes priority over an outing",()=>{ + expect(tideSailReason({...ready,run:true,lease:"blocked"})).toContain("another tab"); + expect(tideSailReason({...ready,run:true,problem:"The move could not be saved."})).toBe("The move could not be saved."); + expect(tideSailReason({...ready,run:true,lit:false})).toBe("Finish the outing in progress first."); +}); diff --git a/web/src/tide/sailing.ts b/web/src/tide/sailing.ts new file mode 100644 index 0000000..b219f53 --- /dev/null +++ b/web/src/tide/sailing.ts @@ -0,0 +1,16 @@ +export function tideSailReason(state:{ + lit:boolean;lease:"waiting"|"held"|"blocked"|"unavailable";problem:string;run:boolean; + worldReady:boolean;showPassage:boolean;busy?:boolean;pending?:boolean; +}):string|null { + if(state.lease==="blocked")return "This expedition is open in another tab. Finish there, or close that tab before continuing here."; + if(state.lease==="unavailable")return "This browser cannot safely coordinate saved expeditions. Web Locks support is required; no move has been taken."; + if(state.lease==="waiting")return "Checking whether this tab can sail."; + if(state.problem)return state.problem; + if(state.run)return "Finish the outing in progress first."; + if(!state.worldReady)return "Opening the artwork. Mochi’s saved moves are safe."; + if(state.showPassage)return "Finish the harbor crossing first."; + if(state.busy)return "The original harbor action is still being checked."; + if(state.pending)return "Resolve the original request before setting out from this harbor."; + if(!state.lit)return "Restore the beacon before sailing today’s tide."; + return null; +} diff --git a/web/src/tide/tide.css b/web/src/tide/tide.css new file mode 100644 index 0000000..883ff77 --- /dev/null +++ b/web/src/tide/tide.css @@ -0,0 +1,166 @@ +.tide,.tide-chart,.tide-asks{font-family:"Figtree Variable",sans-serif} +.tide{--ss-ink:var(--exp-ink,#263e32);--ss-soft:var(--exp-secondary-ink,#4f5d52);--ss-line:var(--exp-hairline,#e6d6b4);--ss-card:var(--exp-card,#fbf3e2);color:var(--ss-ink);font-size:15px;line-height:1.45} +.tide h3,.tide h4{font-family:"Fraunces Variable",serif;letter-spacing:-.02em;margin:0 0 8px;line-height:1.2;text-wrap:balance} +.tide h3{font-size:28px} +.tide h4{font-size:18px} +.tide p{margin:0 0 12px} +.tide{container-type:inline-size;min-width:0} +.exp-game .exp-panel:has(>.tide)>.exp-close{margin-left:-44px} +.tide img{height:auto} +.tide-ask-icon{display:inline-flex;align-items:center;flex:none} +.tide-ask-icon img{display:block;flex:none;object-fit:contain} +.tide-ask-icon-pair img+img{margin-left:-10px} +.tide .tide-keeper{display:block;width:min(300px,calc(100% - 112px));margin:0 auto 10px} +.tide .tide-card{padding:0;background:transparent;border:0;border-radius:0} +.tide .tide-card-heading{display:flex;align-items:center;gap:20px;margin:2px 0 24px} +.tide .tide-card-heading>div{min-width:0} +.tide .tide-card-heading .tide-note{margin:0} +.tide-stamp{position:relative;display:inline-block;flex:0 0 var(--stamp);width:var(--stamp);height:var(--stamp);vertical-align:middle;transform:rotate(var(--tilt));filter:drop-shadow(0 2px 3px #4a352033)} +.tide-stamp-paper{display:block;box-sizing:border-box;width:100%;height:100%;padding:var(--stamp-padding);background:#fffaf0;-webkit-mask:radial-gradient(var(--r) at 50% 0,#0000 97%,#000) 0 0/var(--p) 100% repeat-x,radial-gradient(var(--r) at 50% 100%,#0000 97%,#000) 0 0/var(--p) 100% repeat-x,radial-gradient(var(--r) at 0 50%,#0000 97%,#000) 0 0/100% var(--p) repeat-y,radial-gradient(var(--r) at 100% 50%,#0000 97%,#000) 0 0/100% var(--p) repeat-y;mask:radial-gradient(var(--r) at 50% 0,#0000 97%,#000) 0 0/var(--p) 100% repeat-x,radial-gradient(var(--r) at 50% 100%,#0000 97%,#000) 0 0/var(--p) 100% repeat-x,radial-gradient(var(--r) at 0 50%,#0000 97%,#000) 0 0/100% var(--p) repeat-y,radial-gradient(var(--r) at 100% 50%,#0000 97%,#000) 0 0/100% var(--p) repeat-y;-webkit-mask-composite:source-in;mask-composite:intersect} +.tide-stamp-paper>img{display:block;object-fit:cover} +.tide-stamp>.tide-stamp-seal{position:absolute;right:-5%;bottom:-5%;width:var(--seal);height:var(--seal)} +.tide .tide-day,.tide .tide-sub,.tide .tide-note{color:var(--ss-soft);font-size:13px;line-height:1.45} +.tide .tide-day{margin-bottom:18px} +.tide .tide-ask-intro{font-weight:700;font-size:14px;margin:18px 0 8px} +.tide .tide-card>.exp-primary,.tide-log>.exp-primary{display:flex;align-items:center;justify-content:center;gap:10px;width:100%} +.tide .tide-card>.exp-primary+.tide-note,.tide-log>.exp-primary+.tide-note{margin-top:8px} +.tide .tide-result{font-size:14px;margin:16px 0 8px} +.tide .tide-list{list-style:none;padding:0;margin:10px 0 18px;display:grid;gap:9px} +.tide .tide-list li{display:flex;align-items:flex-start;gap:9px;overflow-wrap:anywhere} +.tide .tide-list .tide-ask-icon{margin-top:-2px} +.tide .tide-ask-mark{display:inline-flex;align-items:center;justify-content:center;flex:0 0 24px;height:24px;margin-top:-1px;font-size:12px;font-weight:700;color:var(--ss-ink)} +.tide .tide-ask-mark img{display:block;width:24px;height:24px} +.tide .tide-list [data-kept=false]{color:var(--ss-soft)} +.tide .tide-earlier{border-top:1px solid var(--ss-line);margin-top:22px;padding-top:6px} +.tide summary,.tide-chart summary{min-height:44px;padding:11px 0;cursor:pointer;font-weight:650;color:#2c4335} +.tide button,.tide-chart button{min-width:44px;min-height:44px;white-space:nowrap} +.tide .tide-earlier>ul{list-style:none;margin:0;padding:0} +.tide .tide-earlier>ul>li{display:flex;align-items:flex-start;gap:16px;padding:18px 4px;border-top:1px solid var(--ss-line)} +.tide .tide-earlier>ul>li>div{min-width:0;flex:1} +.tide .tide-earlier .tide-day{margin-bottom:5px} +.tide .tide-earlier h4{margin-bottom:4px} +.tide .tide-earlier .tide-note{margin-bottom:8px} +.tide .tide-actions{display:flex;flex-wrap:wrap;align-items:center;gap:6px 12px} +.exp-game .tide .tide-actions .exp-text-button{width:auto;margin:0;padding-inline:6px;font-size:15px} +.exp-game .tide .tide-open-log{margin-top:12px;font-size:15px} +.tide .tide-pages{display:grid;grid-template-columns:1fr auto 1fr;align-items:center;gap:8px;margin:16px 0 22px} +.exp-game .tide .tide-pages button{font-size:15px;line-height:1.2;padding:8px} +.exp-game .tide .tide-pages button[aria-disabled=true]{opacity:1;color:#667164;background:#f0e6d0;border-color:#d8ccb5;box-shadow:none;cursor:default} +.tide .tide-pages p{margin:0;font-size:12px;text-align:center;color:var(--ss-soft);font-variant-numeric:tabular-nums} +.tide .tide-log-header{position:sticky;top:0;z-index:3;display:flex;align-items:center;gap:14px;margin:0 0 24px;padding:0 52px 12px 0;background:var(--ss-card)} +.tide .tide-log-header>img{display:block;flex:0 0 64px;width:64px;height:64px} +.tide .tide-log-header>div{min-width:0} +.tide .tide-log-header .tide-sub{margin:0;text-wrap:balance} +.tide .tide-collection{margin:0 0 28px} +.tide .tide-collection>p{font-size:13px;color:var(--ss-soft)} +.tide .tide-stamp-sheet{display:grid;grid-template-columns:repeat(auto-fill,minmax(56px,1fr));gap:14px 8px;padding:6px 2px 8px} +.exp-game .tide .tide-stamp-sheet>button{display:grid;place-items:center;justify-self:center;width:56px;height:56px;padding:0;margin:0;border:0;border-radius:0;background:transparent;box-shadow:none} +.exp-game .tide .tide-stamp-sheet>button:hover{background:transparent} +.exp-game .tide .tide-stamp-sheet>button:hover .tide-stamp{filter:drop-shadow(0 3px 4px #4a352055)} +.tide .tide-stamp-empty{display:block;box-sizing:border-box;justify-self:center;width:56px;height:56px;border:1.5px dashed var(--ss-line)} +.tide-log-chart{position:relative;margin:20px 10px 6px} +.tide .tide-log-chart+.tide-list{margin-top:4px} +.tide-log-chart .tide-chart{display:grid;grid-template-columns:minmax(0,1fr);margin:0} +.tide-log-chart .tide-chart::before{content:"";grid-area:1/1;background-image:var(--tide-paper);background-size:100% 100%;background-repeat:no-repeat;filter:drop-shadow(0 3px 8px #4a352030);pointer-events:none} +.tide-log-chart .tide-chart>svg{position:relative;grid-area:1/1;box-sizing:border-box;max-width:none;padding:22px 22px 24px 36px} +.tide-log-chart-stamped .tide-chart>svg{padding-top:78px} +.tide-log-chart .tide-chart-controls{grid-area:2/1;margin-top:12px} +.tide-page-stamp{position:absolute;top:-8px;right:3px;z-index:1} +.tide .tide-haul{display:flex;align-items:center;gap:12px;margin:0 0 12px;font-size:14px;line-height:24px;font-variant-numeric:tabular-nums;white-space:nowrap} +.tide-haul>span[aria-hidden]{display:inline-flex;align-items:center;gap:4px;flex:none} +.tide .tide-haul img{display:block;width:24px;height:24px;object-fit:contain;flex:none} +.tide .tide-log-run{display:flex;align-items:center;gap:18px;margin:16px 0;padding:20px 18px} +.tide-log-run::before{content:"";position:absolute;inset:0;background:var(--tide-paper) center/100% 100% no-repeat;filter:drop-shadow(0 3px 8px #4a352030);pointer-events:none} +.tide-log-run>*{position:relative} +.tide-log-run>div{min-width:0} +.tide .tide-log-run .tide-haul{gap:10px;margin-bottom:8px} +.tide .tide-log-run .tide-note{margin:0} +.tide .tide-log-run+.tide-facts{grid-template-columns:repeat(3,minmax(0,1fr))} +.tide .tide-log-run+.tide-facts div{display:block} +.tide .tide-log-run+.tide-facts dd{margin-top:4px} +.tide-home-stamp .tide-stamp[data-press]{animation:tide-stamp-arrive 360ms cubic-bezier(.16,1,.3,1)} +@keyframes tide-stamp-arrive{from{transform:rotate(calc(var(--tilt) - 9deg)) scale(1.35)}to{transform:rotate(var(--tilt)) scale(1)}} +.tide-home .tide-list[data-arrival] .tide-ask-mark{animation:tide-ask-press 260ms cubic-bezier(.16,1,.3,1) var(--ask-delay) backwards} +@keyframes tide-ask-press{from{transform:rotate(-9deg) scale(1.35)}to{transform:none}} +.tide .tide-facts{display:grid;gap:8px;margin:16px 0;padding:12px 0;border-top:1px solid var(--ss-line);font-variant-numeric:tabular-nums} +.tide .tide-facts div{display:flex;justify-content:space-between;align-items:baseline;gap:12px} +.tide .tide-facts dt{font-size:13px;color:var(--ss-soft)} +.tide .tide-facts dd{margin:0;font-weight:700} +.tide :focus-visible{outline:3px solid #2b5f4d;outline-offset:3px} +.exp-game .tide button[aria-disabled=true],.tide button[aria-disabled=true],.tide-chart button[aria-disabled=true]{opacity:.5;cursor:default;box-shadow:none} +.exp-game .tide button[aria-disabled=true]:active{transform:none} +.tide-chart{margin:12px 0;color:#2c4335} +.tide-chart>svg{width:100%;max-width:360px;display:block;margin-inline:auto;height:auto} +.tide-chart .tide-home{font:italic 13px "Fraunces Variable",serif;fill:#2c4335} +.tide-chart .tide-chart-controls{display:flex;align-items:flex-start;flex-wrap:wrap;gap:0 16px;margin-top:6px} +.exp-game .tide-chart .tide-watch{min-height:44px;padding:8px 4px;background:transparent;border:0;box-shadow:none;text-decoration:underline;text-underline-offset:3px;color:#2c4335;font-size:15px;font-weight:600} +.tide-chart .tide-route{flex:1 1 100%;font-size:13px}.tide-chart .tide-route summary{padding-top:4px} +.tide-chart .tide-route ol{padding-left:22px;margin:0 0 12px;color:#53442b;line-height:1.45} +.tide-chart .tide-route li+li{margin-top:6px} +.tide-chart .tide-chart-wave{animation:tide-chart-wave 900ms ease-out forwards} +@keyframes tide-chart-wave{from{opacity:.5}to{opacity:0}} +.exp-game .tide-asks{margin:0;padding:0;list-style:none;display:flex;flex-direction:column;gap:6px;pointer-events:none;align-items:flex-start} +.exp-command-tray .tide-outing{position:static;display:flex;flex:none;flex-direction:column;align-items:flex-start;gap:6px;min-width:0;max-width:100%;pointer-events:none} +.exp-command-tray .tide-ask-icon img{width:28px;height:28px} +.exp-game .tide-restart{pointer-events:auto;width:auto;min-height:44px;margin:0;padding:6px 12px;border:0;border-radius:999px;box-shadow:none;color:var(--exp-ink,#263e32);background:var(--exp-card,#fbf3e2);font-size:15px} +.exp-game .tide-restart:hover:not(:disabled){background:#fff3dc} +.tide-asks>li{display:flex;align-items:center;gap:6px;max-width:100%;min-height:28px;padding:4px 8px;border:1px solid var(--exp-hairline,#e6d6b4);border-radius:999px;background:var(--exp-card,#fbf3e2);color:var(--exp-ink,#263e32);font-size:13px;line-height:1.25} +.tide-asks .tide-mark{flex:0 0 16px;width:16px;height:16px;display:inline-flex;align-items:center;justify-content:center} +.tide-asks .tide-mark:has(img){flex-basis:18px;width:18px;height:18px} +.tide-asks .tide-mark img{display:block;width:16px;height:16px} +.tide-asks>li[data-status=kept]{border-color:#2b5f4d} +.tide-asks>li[data-status=slipped]{border-style:dashed;color:var(--exp-secondary-ink,#4f5d52)} +.tide .tide-sr,.tide-chart .tide-sr,.tide-asks .tide-sr{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0} +.tide.tide-harness-note{margin:16px 16px 0;padding:8px 10px;background:#7a3020;color:#fff5dc;border-radius:8px;font-size:13px} +.tide.tide-harness-panels{display:flex;flex-wrap:wrap;align-items:flex-start;gap:16px;padding:16px} +.tide .tide-harness-court{position:relative;width:412px;max-width:100%;min-height:340px;background:#6b8876;border-radius:8px} +.tide .tide-harness-panel{width:412px;max-width:100%;flex:0 1 412px} +.tide .tide-harness-status{margin:16px 0 0;min-height:22px;color:#53442b;font-size:13px} +.tide .tide-harness-stamps{flex:0 1 100%;min-width:0;padding:20px;background:#f6e6c3;border-radius:12px} +.tide .tide-harness-stamp-row{display:flex;flex-wrap:wrap;align-items:flex-end;gap:28px;padding:16px 4px 24px} +.tide .tide-harness-stamp-pair{display:flex;flex-wrap:wrap;align-items:center;gap:16px;max-width:100%} +.tide .tide-harness-stamp-pair>span:not(.tide-stamp){flex:0 0 100%} +@container(max-width:315px){.tide .tide-card-heading{flex-direction:column;align-items:center;gap:18px;text-align:center}} +@media(max-width:899px){ + .exp-command-tray .tide-outing{align-items:stretch;width:100%} + .exp-game .exp-command-tray .tide-outing>.tide-asks{flex-direction:row;flex-wrap:nowrap;gap:3px;justify-content:space-between} + .exp-command-tray .tide-asks>li{flex:none;min-height:32px;max-height:36px;gap:3px;padding:3px;white-space:nowrap} + .exp-command-tray .tide-ask-icon img{width:24px;height:24px} + .exp-command-tray .tide-ask-icon-pair img+img{margin-left:-8px} + .exp-command-tray .tide-asks .tide-mark:has(img){flex-basis:16px;width:16px;height:16px} + .exp-command-tray .tide-chip-noun{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0} + .exp-command-tray .tide-restart{align-self:flex-start} + .exp-command-tray .tide-outing:has(>.tide-restart) .tide-asks>li{gap:2px;padding:3px 4px} + .exp-command-tray .tide-outing:has(>.tide-restart) .tide-ask-icon img{width:20px;height:20px} + .exp-command-tray .tide-outing:has(>.tide-restart) .tide-asks .tide-mark:has(img){flex-basis:14px;width:14px;height:14px} +} +@media(max-width:480px){.tide .tide-pages{gap:6px}.exp-game .tide .tide-pages button{padding:8px 5px}.tide .tide-facts{padding:10px}.tide.tide-harness-panels{padding:12px;gap:16px}.tide.tide-harness-note{margin-inline:12px}} +@media(prefers-reduced-motion:reduce){.tide-chart .tide-chart-wave,.tide-home-stamp .tide-stamp[data-press],.tide-home .tide-list[data-arrival] .tide-ask-mark{animation:none}} +.tide-home{text-align:center} +.tide-home .tide-home-stamp{margin:4px 0 22px} +.tide-home .tide-list{text-align:left;margin:0 auto 26px;max-width:38ch;gap:12px} +.tide-home .tide-home-heading{position:sticky;top:0;z-index:4;display:flex;align-items:center;justify-content:center;gap:14px;margin:0 0 12px;padding:8px 44px 14px 0;background:var(--ss-card)} +.tide-home .tide-home-heading:has(img){text-align:left} +.tide-home .tide-home-portrait{display:block;flex:0 0 72px;width:72px;height:72px;object-fit:contain;border-radius:50%} +.exp-game .tide-home h2{font-size:clamp(34px,4vw,40px);line-height:1.1;text-wrap:balance;margin:0} +.tide-home .tide-home-sub{font-size:16px;color:var(--ss-soft);font-variant-numeric:tabular-nums} +.tide-home .tide-haul{justify-content:center} +.tide-home .tide-home-note{font-size:14px;color:var(--ss-soft);max-width:45ch;margin:0 auto 22px} +.exp-game .tide-home .tide-home-result>.exp-primary,.exp-game .tide-home .tide-home-result>.exp-secondary{display:flex;align-items:center;justify-content:center;width:100%;gap:10px;margin-top:12px} +.tide-home[data-reduced] .tide-list[data-arrival] .tide-ask-mark{animation:none} +@media(max-height:500px) and (orientation:landscape){ + .exp-game .exp-command-tray .tide-outing>.tide-asks{flex-wrap:wrap;justify-content:flex-start} + .exp-game .exp-panel:has(.tide-home){width:min(780px,100%);padding:18px} + .exp-game .exp-panel:has(.tide-home)>.exp-close{position:absolute;top:10px;right:10px;margin:0} + .tide-home{display:grid;grid-template-columns:minmax(0,.9fr) minmax(0,1.1fr);gap:24px;align-items:center} + .tide-home .tide-home-keeps,.tide-home .tide-home-result{min-width:0} + .tide-home .tide-home-stamp{margin:0 0 12px} + .tide-home .tide-list{font-size:13px;line-height:1.35;gap:8px;margin-bottom:0} + .tide-home .tide-home-result{display:grid;gap:8px} + .tide-home .tide-home-result:has(>.tide-haul){gap:6px} + .tide-home .tide-haul{margin:0} + .tide-home .tide-home-heading{position:static;gap:10px;margin:0;padding:0 36px 0 0} + .exp-game .tide-home h2{font-size:clamp(24px,3.2vw,28px);line-height:1.08} + .tide-home .tide-home-sub,.tide-home .tide-home-note,.tide-home .tide-note{font-size:13px;line-height:1.35;margin:0} + .exp-game .tide-home .tide-home-result>.exp-primary,.exp-game .tide-home .tide-home-result>.exp-secondary{min-height:44px;font-size:16px;margin:0;padding:8px 16px} +}