Files
FFF_vtt_frozen/client/README.md
T
SirStone 4534ed6426 feat(client): map tiles, grid and pan/zoom (#69)
T6 of spec #63. Tiles are requested only for the viewport plus one tile of
margin, in viewport order, at most 8 at a time (TileScheduler); decoded
textures are cached by URL so a reconnect refetches nothing; a 403/404 is
remembered as denied and never retried. The browser image loader is the hot
path, with one status fetch only to classify an error.

Camera: drag to pan, wheel/pinch to zoom around the pointer/midpoint; players
clamp at 0.5 (ADR-0013) and the GM has no player floor; both stop at 4.0.
Grid is one TilingSprite toggled by #grid-toggle. Camera is local UI state,
not a reducer slice, so hello/reconnect does not move the view.

Tests: viewport/tile unit tests (clamps, margin window, 8-wide queue, denial,
cache) and client/e2e/map.test.mjs (mobile viewport fill gate (a), grid,
pinch, cache across reconnect, GM zoom, 403 no-retry) against the real
server through TLS/h2. Tile-size gate (a) documented in client/README.md.
2026-11-21 01:11:12 +01:00

176 lines
13 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# FFF VTT client
Vite + TypeScript + PixiJS v8, plain DOM overlay, `proto` 2 (DESIGN §7, ADR-0011). No framework.
## Run and gates
All through devbox, from the repo root:
```sh
devbox run client-test # Vitest: pure reducer + protocol client + envelope (no DOM, no GPU)
devbox run e2e # builds client/dist, then Chromium against the real server through the
# TLS/HTTP2 test nginx (client/e2e/*.test.mjs, playwright-core)
devbox run test # the server gate; unaffected by the client
devbox run -- bash -c 'cd client && npm run dev' # local dev (Vite, no server API on :5173)
```
`npm run build` = `tsc --noEmit && vite build` into `client/dist`, which the test/production nginx
serves at `/` (DESIGN §11.1). `client/dist` and `client/node_modules` are not committed.
## The one seam that matters
`src/reducer.ts` is pure: server frames and connection events in, state out. **It must never import
Pixi, the DOM, or the socket.** Its unit tests (`test/*.test.ts`) are the contract. Everything else
is wiring:
| File | Owns |
|---|---|
| `src/protocol.ts` | Wire types, envelope/ack/closing guards, intent encoding, `/ws?proto=2` URL. Pure. |
| `src/reducer.ts` | `RootState`, phase machine (`boot/connecting/signin/live/reload/offline`), `hello` reset, slice registry. Pure. |
| `src/slices/*.ts` | Append-only domain state (roster today; fog, tokens, walls, panels later). |
| `src/ws.ts` | Socket, `reqId` counter, pending map, close-code mapping, backoff and retry. No DOM. |
| `src/shell.ts` | Sign-in, HUD/roster, fatal screens. Plain DOM, `textContent` only. |
| `src/render/stage.ts` | One Pixi `Application`, one world container, fixed layers. Pixi lives here and in modules only. |
| `src/render/modules/*.ts` | Append-only render modules. |
| `src/main.ts` | Wiring: store -> shell/stage, `/join`, connect. |
## Convention for the M4 fan-out (T7, T8/T9, T10, T11/T12)
The registry is a **build-time glob**, so parallel tickets are file-disjoint: no shared import list
to merge and no registry file to edit.
- **State slice**: add `src/slices/<feature>.ts` exporting `export const slice: Slice<YourState>`
(`name`, `init()`, `reduce(state, event, root)`). It is registered automatically. Read it with
`sliceOf<YourState>(state, '<name>')`. `hello` resets every slice for you (DESIGN §6.3): never
keep server-derived state outside a slice or the core session.
- **Render module**: add `src/render/modules/<feature>.ts` exporting
`export const renderModule: RenderModule` (`name`, `mount(context)`, optional teardown). Draw into
your layer: `tiles`, `grid`, `tokens`, `fog` (players), `gm` (GM only), `dom`.
- **Panel/DOM**: add `src/panels/<feature>.ts` and mount under the existing `#panels` host; do not
rewrite the sign-in flow. Server strings go through `textContent` (never `innerHTML`); token
labels use `BitmapText` with the pre-installed `BitmapFont` (DESIGN §7.2).
- **No per-frame full redraw**: subscribe to the store and touch only entities that changed
(DESIGN §7.2). Keep the DOM overlay work per frame minimal.
- **Protocol**: only the catalogue in DESIGN §6.1. The client ignores unknown frame types/fields
(§6.2). `closing` reasons map through `closeOutcome`: `proto-mismatch` -> reload, `revoked` ->
sign-in, `evicted`/`malformed-flood` -> offline. Do not invent wire fields; server-side additions
are separate tickets (e.g. `seen_by`, T12).
Suggested ownership (no file overlap): T7 fog = `slices/fog.ts` + `render/modules/fog.ts`; T8/T9
tokens/drag = `slices/tokens.ts`, `slices/move.ts`, `render/modules/tokens.ts`; T10 walls =
`slices/walls.ts` + `render/modules/walls.ts`; T11/T12 GM panels = `slices/admin.ts` +
`src/panels/*.ts`. `src/reducer.ts`, `src/main.ts` and `src/render/stage.ts` are already generic;
change them only if a slice needs a new *core* event, and say so in the PR.
## Protocol notes already encoded
- `/ws?proto=2`; a mismatch is `closing{reason:"proto-mismatch",code:4003}` then close. The reason
is read from the last `closing` frame because browsers report 1005 at the mummy pin (ADR-0019).
- `hello` resets all state; the resync after it rebuilds the view. Pending `reqId`s survive a
`hello` on a live connection and die with the socket (DESIGN §6.3).
- Sign-in is `POST /join` (form body, key never in the URL). A `401` for a wrong key and for an
unknown key is shown as the same "Key not recognised." (DESIGN §3.2, story 3).
- No game data (and no Pixi `Application`) exists before a live `hello`; a visitor without a session
only sees the sign-in page.
## Name, badge and reconnect (T5, #68)
- **First sign-in name prompt.** A live player with `me.name === null` gets the `#name` section
instead of the HUD, and no Pixi stage (the server sends no scene, no state, until named). Submitting
sends `player.setname`; the server acks *before* the second `hello` (FIXED #33), so a refusal's
code becomes visible text on the prompt (`name-taken` → "That name is taken. Choose another.",
`invalid` and `not-allowed` have their own copy) and an acceptance is followed by the `hello` that
resets every slice plus the 6.3 resync. The prompt is keyed on state, so it cannot come back and
survives a reload with the same session.
- **Badge** (`#badge[data-state]`): `connected` while live; `reconnecting` while the socket backs
off, with the stale map staying on screen; `offline` when the browser reports no network
(`navigator.onLine`/`online`/`offline` events) or after a terminal outcome (`evicted`,
`malformed-flood`, `server-shutdown`). Hidden on boot, sign-in and reload.
- **Reconnect** (DESIGN 6.3): a transport close (no `closing` frame) after a connection has been
live retries with `backoffDelay`: base 1/2/4/8/10 s then the cap, ±20 % jitter
(`RECONNECT_BASE_DELAYS_MS`, `RECONNECT_JITTER`). Terminal reasons never retry: `revoked` →
sign-in, `proto-mismatch` → reload. Pending `reqId`s die with the socket; a browser `online` event
calls `retryNow()` to skip the rest of the wait. The view is **not** cleared on a drop: `hello` is
the reset point, and the resync that follows rebuilds tokens, fog, explored, markers and lists.
- **Two devices** of one player both stay live and receive the same frame stream (each connection
has its own `known` table, DESIGN 6.3).
- **Proof**: `test/ws.test.ts` (schedule, retry state machine, pending drop) and
`test/reducer.test.ts` (badge transitions, reconnect reset, name errors) are the unit seam;
`e2e/session.test.mjs` kills and restarts the real server under a live page, drops the browser
network with `context.setOffline`, asserts the badge transitions and the full resync frames, and
runs two pages on one key.
## Map tiles, grid and pan/zoom (T6, #69)
- **Camera** (`src/viewport.ts`, pure): the world container is `screen = world * zoom + (x, y)`.
Players clamp at `0.5` and the GM has no player floor (a `1/64` sanity floor only keeps the
transform non-singular); both clamp at `4.0` (ADR-0013, spec #63 decision 7). Wheel and pinch zoom
around the pointer/midpoint, one-finger drag pans. Input is hand-rolled DOM pointer/wheel events
on the canvas (`src/render/modules/camera.ts`, DESIGN 7.2: no Pixi federated events), and the
canvas gets `touch-action: none`.
- **Camera is not a reducer slice.** It is local UI state; a `hello` resets every slice by design,
and a reconnect must not move the player's view. `ViewportModel` is owned by the render layer and
reset only when a new stage is created. The canvas carries the e2e facts `data-zoom`, `data-grid`
and `data-view` (viewport px).
- **Tiles** (`src/tiles.ts` scheduler + `src/render/modules/tiles.ts` layer): the wanted set is
`visibleTiles()` — every tile intersecting the viewport plus exactly one tile of margin, clamped
to the scene, in viewport order (row-major). The scheduler keeps at most `TILE_CONCURRENCY` (8)
loads in flight, drops queued tiles that leave the window, never asks twice for a tile, and
remembers a `403`/`404` as `denied` forever: the gate has said "not yours", so it is never retried
in a loop. A transient failure is retried only on a new window or after a reconnect (`hello`).
The decoded-texture cache is module-level and keyed by URL, so a reconnect keeps every tile and
the page makes no new tile request. `data-tiles` is `ready` once every wanted tile has settled
(`ok` or `denied`); `data-tile-requests` counts image attempts (plus the single status fetch used
to classify an image error).
- **Why `<img>` and not `fetch` + `createImageBitmap`:** the browser's image loader does the
fetch/decode off the JS hot path; one `onload` per tile is the cheapest way to put the ~480 tiles
of a phone viewport on the GPU. A failed image is classified once with `fetch`, which is where the
`403` distinction comes from.
- **Grid** (`src/render/modules/grid.ts`): one `TilingSprite` over a `grid_size` cell texture, drawn
once, toggled by `#grid-toggle` (story 18). No per-frame redraw.
- **Tile-size gate (a)** (`client/e2e/map.test.mjs`): mobile emulation 412×869 CSS px, DPR 2.625,
touch; real server through the TLS/HTTP2 nginx; viewport **412×869 at zoom 1**. The measurement is
from the canvas becoming visible to `data-tiles=ready`, i.e. the first viewport filling; the budget
is **< 1 s** (DESIGN §13). Measured on this dev host: **~0.4–0.8 s** for the 480-tile window
(marginal under parallel test load). The same test then applies CDP's 4× CPU throttle for the grid,
pinch and reconnect checks. Note: under the 4× throttle the *fill itself* takes ~3.2 s, because CDP
multiplies each of the ~480 image-load callbacks; that measures the throttler rather than the app,
so the gate is measured at real CPU and gate (b), the real-phone run (#77), remains authoritative
for phone speed.
## Tokens, labels, statuses and the two lists (T8, #71)
- **State**: `src/slices/tokens.ts` (`token` upsert, `token_gone`, `hello` reset; `tokensOf`),
`src/slices/characters.ts` (`character`/`character_gone`, `ownCharactersOf`) and
`src/slices/encountered.ts` (`full` replace, `set`/`del` diff, grey flag; the GM's per-player
copies are ignored). All three are append-only slice files: the registry and `main.ts` are
untouched.
- **Renderer**: `src/render/tokenBoard.ts` is the pure half. It turns the store's *events* into the
exact nodes to touch — `entered`, `updated`, `left`, or a `hello` reset — and keeps the view it
last drew, so a frame that moves one token updates one container and nothing else (DESIGN 7.2).
It also seeds itself from the reducer on mount, because `app.init()` is async and the resync can
beat the stage. `src/render/modules/tokens.ts` is the Pixi half: pooled containers on the
`tokens` layer **in world coordinates** (the camera from #69 transforms the layer's parent, never
a token), one shared unit-circle `GraphicsContext` per kind scaled to the effective radius, and
`BitmapText` labels from one pre-installed `BitmapFont` (`fff-token-label`: Latin, accented Latin
and ASCII) assigned only when the name actually changed. `stuck` and `squeezed` are drawn badges
(barred ring, inward brackets); the cause is never drawn because a player never receives it.
- **Instrumentation** for the "only changed entities touched" acceptance criterion lives on the
canvas dataset: `data-tokens`, `data-token-entered`, `data-token-updated`, `data-token-left`,
`data-token-labels`, `data-token-ids`, `data-token-statuses`. It is updated only when a patch did
something, and `e2e/tokens.test.mjs` reads it against the real server.
- **Lists panel**: `src/panels/lists.ts` (`#lists` under the shell's `#panels`: `#characters`,
`#encountered`, rows with `data-character`/`data-token` and `data-grey`, `textContent` only) is
mounted by `src/render/modules/lists.ts`, a render module, so the panel's lifetime is the live
stage's and no shared bootstrap file had to change. Greyed rows carry both `data-grey="true"` and
the `grey` class, plus an "out of sight" label so the state is not colour-only.
- **Drag seam (#72)**: `applyView(node, view, stats, at?)` already takes the position to draw, so a
drag module can pass its optimistic position for the node under the pointer and let the
authoritative view resume on ack/rollback. The reducer's token view stays the server's word.
- **Proof**: `test/tokens.test.ts` (enter/update/leave, status names without `source`, GM fields,
malformed frames), `test/lists.test.ts` (own characters, encountered full/diff/grey, GM copies),
`test/token-board.test.ts` (one changed entity per frame, no phantom enter+leave, reset on
`hello`, seeding) and `e2e/tokens.test.mjs` (real server: player and GM token sets, a `gm_only`
token the player never receives, the stuck badge, both lists, `token_gone` plus the grey flip,
and one-entity updates with unchanged label builds).