diff --git a/client/README.md b/client/README.md index 84e99f7..1d2794a 100644 --- a/client/README.md +++ b/client/README.md @@ -99,3 +99,39 @@ change them only if a slice needs a new *core* event, and say so in the PR. `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. + +## 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). diff --git a/client/e2e/tokens.test.mjs b/client/e2e/tokens.test.mjs new file mode 100644 index 0000000..99a08bf --- /dev/null +++ b/client/e2e/tokens.test.mjs @@ -0,0 +1,202 @@ +// T8 (#71, TESTING 10.3): tokens, BitmapText labels, statuses and the two lists, against the real +// server through the TLS/HTTP2 nginx. The browser's own WebSocket is only *recorded* (as in +// session.test.mjs), so the assertions read the real per-recipient frames; the canvas dataset is +// the token renderer's own instrumentation (published by render/modules/tokens.ts). +import test from 'node:test' +import assert from 'node:assert/strict' +import { createPlayer, namePlayer, sleep } from '../../tools/lib.mjs' +import { openAs } from '../../tools/withserver.mjs' +import { + launchBrowser, + newPage, + signIn, + waitForText, + waitForVisible, + withStack, +} from './stack.mjs' + +async function recordSockets(page) { + await page.addInitScript(() => { + window.__wsLog = { frames: [] } + const Native = window.WebSocket + class RecordingSocket extends Native { + constructor(url, protocols) { + super(url, protocols) + this.addEventListener('message', event => { + try { + window.__wsLog.frames.push(JSON.parse(event.data)) + } catch { + // not a frame; the app ignores it too + } + }) + } + } + window.WebSocket = RecordingSocket + }) +} + +const frames = page => page.evaluate(() => window.__wsLog.frames) + +async function waitForBadge(page, state, timeout = 30000) { + await page.locator(`#badge[data-state="${state}"]`).waitFor({ state: 'visible', timeout }) +} + +/** The token renderer's instrumentation, read from the canvas it draws on. */ +async function tokenRender(page) { + return page.evaluate(() => { + const canvas = document.querySelector('#stage canvas') + if (!canvas) return null + const data = canvas.dataset + return { + count: Number(data.tokens ?? '0'), + entered: Number(data.tokenEntered ?? '0'), + updated: Number(data.tokenUpdated ?? '0'), + left: Number(data.tokenLeft ?? '0'), + labels: Number(data.tokenLabels ?? '0'), + ids: (data.tokenIds ?? '').split(' ').filter(Boolean), + statuses: (data.tokenStatuses ?? '').split(' ').filter(Boolean), + } + }) +} + +async function waitForRender(page, predicate, timeout = 20000) { + const deadline = Date.now() + timeout + let last = null + while (Date.now() < deadline) { + last = await tokenRender(page) + if (last !== null && predicate(last)) return last + await sleep(50) + } + throw new Error(`token renderer never reached the expected state: ${JSON.stringify(last)}`) +} + +test('tokens: enter/leave/update, labels once, statuses, lists, GM sees gm_only', { timeout: 180000 }, async () => { + await withStack(async ({ origin, gmKey }) => { + const gm = await openAs(origin, gmKey) + await gm.ws.waitText('hello') + const scene = (await gm.ws.waitText('walls')).scene + const player = await createPlayer(gm.ws) + await namePlayer(origin, player.key, 'Ann') + + // Story 31: a character owned by the player, with a value only the owner's side carries. + const character = await gm.ws.request({ + t: 'character.create', + descriptive_name: 'Ann', + actual_name: 'Ann of the Vale', + owner: player.id, + props: { public: { kind: 'pc' }, owner: { hp: 12 } }, + }) + assert.equal(character.ok, true) + + // Story 28: the player's own token (linked to the character) and another figure in sight. + const own = await gm.ws.request({ + t: 'token.create', scene, kind: 'pc', character_id: character.id, controller: player.id, + pos: [400, 400], flags: { vision: true }, + }) + assert.equal(own.ok, true) + const rat = await gm.ws.request({ + t: 'token.create', scene, kind: 'npc', pos: [460, 400], + descriptive_name: 'Rat', actual_name: 'Giant Rat', + }) + assert.equal(rat.ok, true) + // Story 34: a gm_only token next to the others; if the player ever received it, it would show. + const ghost = await gm.ws.request({ + t: 'token.create', scene, kind: 'npc', pos: [520, 400], + descriptive_name: 'Ghost', actual_name: 'Ghost', gm_only: true, + }) + assert.equal(ghost.ok, true) + // Story 30: a status the server records and every viewer sees (cause GM-only). + const stuck = await gm.ws.request({ t: 'status.set', id: own.id, status: 'stuck' }) + assert.equal(stuck.ok, true) + + const browser = await launchBrowser() + try { + const gmView = await newPage(browser) + const playerView = await newPage(browser) + await recordSockets(gmView.page) + await recordSockets(playerView.page) + + for (const view of [gmView, playerView]) { + await view.page.goto(`${origin}/`) + await waitForVisible(view.page, '#signin') + } + await signIn(gmView.page, gmKey) + await waitForBadge(gmView.page, 'connected') + await signIn(playerView.page, player.key) + await waitForBadge(playerView.page, 'connected') + + // Story 34: the GM renders every token, the gm_only one included. + await waitForRender(gmView.page, view => view.ids.includes(ghost.id)) + const gmTokens = await tokenRender(gmView.page) + assert.deepEqual(gmTokens.ids.slice().sort(), [own.id, rat.id, ghost.id].sort()) + assert.equal(gmTokens.count, 3) + + // Story 28: the player renders their own token and the one in sight, labelled with the name + // the server gave them, and never the gm_only one. + await waitForRender(playerView.page, view => view.ids.includes(own.id) && view.ids.includes(rat.id)) + const playerTokens = await tokenRender(playerView.page) + assert.deepEqual(playerTokens.ids.slice().sort(), [own.id, rat.id].sort()) + assert.equal(playerTokens.ids.includes(ghost.id), false, 'a gm_only token never reaches a player') + // Story 30: the stuck badge is on the player's own token. + assert.ok(playerTokens.statuses.includes(`${own.id}:stuck`), playerTokens.statuses.join(' ')) + // Q17/DESIGN 7.2: one label per name, built once (two names, two builds). + assert.equal(playerTokens.labels, 2) + + // The player's own frames: the status carries no `source`, and the gm_only id never appears. + const playerFrames = await frames(playerView.page) + const ownFrame = playerFrames.filter(frame => frame.t === 'token' && frame.id === own.id).at(-1) + assert.ok(ownFrame, 'the player received their own token') + assert.deepEqual(ownFrame.statuses, [{ status: 'stuck' }]) + assert.equal(playerFrames.some(frame => frame.t === 'token' && frame.id === ghost.id), false) + + // Story 31: the owner's list, with the owner's own value. + await waitForVisible(playerView.page, '#lists') + const characterRow = playerView.page.locator(`#characters li[data-character="${character.id}"]`) + await characterRow.waitFor({ state: 'visible' }) + assert.match(await characterRow.textContent(), /Ann/) + assert.match(await characterRow.textContent(), /hp 12/) + + // Story 32: met figures, in sight first. + const ratRow = playerView.page.locator(`#encountered li[data-token="${rat.id}"]`) + await ratRow.waitFor({ state: 'visible' }) + assert.equal(await ratRow.getAttribute('data-grey'), 'false') + + // Story 29: the figure leaves sight -> token_gone, and the encountered entry greys out. + const movedRat = await gm.ws.request({ t: 'token.move', id: rat.id, pos: [2000, 2000] }) + assert.equal(movedRat.ok, true) + await waitForRender(playerView.page, view => !view.ids.includes(rat.id)) + const afterLeave = await tokenRender(playerView.page) + assert.deepEqual(afterLeave.ids, [own.id], 'the token that left sight is gone from the renderer') + assert.equal(afterLeave.left, 1, 'exactly one entity left') + assert.equal(afterLeave.updated, 0) + assert.equal(afterLeave.entered, 0) + await playerView.page.locator(`#encountered li[data-token="${rat.id}"][data-grey="true"]`).waitFor({ + state: 'visible', + timeout: 20000, + }) + assert.match(await playerView.page.textContent(`#encountered li[data-token="${rat.id}"]`), /Rat/) + + // DESIGN 7.2 / the instrumented count: moving one token updates one entity, nothing else. + const movedOwn = await gm.ws.request({ t: 'token.move', id: own.id, pos: [400, 430] }) + assert.equal(movedOwn.ok, true) + await waitForRender(playerView.page, view => view.updated === 1) + const afterMove = await tokenRender(playerView.page) + assert.equal(afterMove.updated, 1, 'one changed token, one updated entity') + assert.equal(afterMove.entered, 0) + assert.equal(afterMove.left, 0) + assert.equal(afterMove.count, 1) + // The label was built once per name: a move does not rebuild it. + assert.equal(afterMove.labels, 2) + + // The GM saw the same move (one entity updated) and still holds all three tokens. + await waitForRender(gmView.page, view => view.updated === 1) + const gmAfter = await tokenRender(gmView.page) + assert.equal(gmAfter.updated, 1) + assert.equal(gmAfter.count, 3) + assert.ok(await waitForText(gmView.page, '#lists', /No characters yet/)) + } finally { + gm.ws.close() + await browser.close() + } + }) +}) diff --git a/client/src/panels/lists.ts b/client/src/panels/lists.ts new file mode 100644 index 0000000..a7bba4c --- /dev/null +++ b/client/src/panels/lists.ts @@ -0,0 +1,135 @@ +// The lists panel (T8, #71; DESIGN 7.1 layer 6): story 31's own characters and story 32's +// encountered list. Plain DOM, every server string through `textContent` (decision 15): a token +// name can never become markup. +// +// Mounted by `render/modules/lists.ts` under the shell's existing `#panels` host, so the shell's +// sign-in flow is untouched and the panel exists only while a live stage does. The panel is +// pointer-transparent (see style.css): it must never eat a pan or a token drag. + +import type { RootState } from '../reducer.ts' +import type { Store } from '../store.ts' +import { ownCharactersOf } from '../slices/characters.ts' +import type { CharacterView } from '../slices/characters.ts' +import { encounteredOf } from '../slices/encountered.ts' +import type { EncounteredEntry } from '../slices/encountered.ts' + +const NAME_FALLBACK = '(unnamed)' + +function text(tag: keyof HTMLElementTagNameMap, className: string, value: string): HTMLElement { + const node = document.createElement(tag) + node.className = className + node.textContent = value + return node +} + +/** A prop value as text: scalars plainly, anything else as bounded JSON. */ +function valueText(value: unknown): string { + if (value === null) return 'null' + if (typeof value === 'string') return value + if (typeof value === 'number' || typeof value === 'boolean') return String(value) + try { + const json = JSON.stringify(value) + return json.length > 80 ? `${json.slice(0, 77)}…` : json + } catch { + return '?' + } +} + +/** Story 31: the values this player may read, public first then the owner bucket on top. */ +function valuesOf(character: CharacterView): Array<[string, string]> { + const merged: Record = { ...character.props['public'], ...character.props['owner'] } + return Object.entries(merged).map(([key, value]) => [key, valueText(value)]) +} + +function characterRow(character: CharacterView): HTMLLIElement { + const item = document.createElement('li') + item.dataset['character'] = character.id + const label = character.descriptiveName.trim() || NAME_FALLBACK + const name = text('span', 'entry-name', label) + if (character.actualName && character.actualName !== character.descriptiveName) { + name.title = character.actualName + } + item.append(name) + const values = valuesOf(character) + if (values.length > 0) { + item.append(text('span', 'entry-values', values.map(([key, value]) => `${key} ${value}`).join(' · '))) + } + return item +} + +function encounteredRow(entry: EncounteredEntry): HTMLLIElement { + const item = document.createElement('li') + item.dataset['token'] = entry.id + item.dataset['grey'] = entry.grey ? 'true' : 'false' + item.classList.toggle('grey', entry.grey) + item.append(text('span', 'entry-name', entry.name.trim() || NAME_FALLBACK)) + // Greyed means "met before, whereabouts unknown" (story 32); the text says it without colour. + item.append(text('span', 'entry-state', entry.grey ? 'out of sight' : 'in sight')) + return item +} + +function listSignature(characters: readonly CharacterView[], encountered: readonly EncounteredEntry[]): string { + return JSON.stringify([ + characters.map(character => [ + character.id, + character.descriptiveName, + character.actualName, + valuesOf(character), + ]), + encountered.map(entry => [entry.id, entry.name, entry.grey]), + ]) +} + +export function mountListsPanel(host: HTMLElement, store: Store): () => void { + const section = document.createElement('section') + section.id = 'lists' + section.hidden = true + + const charactersSection = document.createElement('section') + charactersSection.id = 'characters-panel' + const charactersTitle = text('h2', 'panel-title', 'My characters') + const charactersList = document.createElement('ul') + charactersList.id = 'characters' + const charactersEmpty = text('p', 'empty', 'No characters yet.') + charactersSection.append(charactersTitle, charactersEmpty, charactersList) + + const encounteredSection = document.createElement('section') + encounteredSection.id = 'encountered-panel' + const encounteredTitle = text('h2', 'panel-title', 'Encountered') + const encounteredList = document.createElement('ul') + encounteredList.id = 'encountered' + const encounteredEmpty = text('p', 'empty', 'Nobody met yet.') + encounteredSection.append(encounteredTitle, encounteredEmpty, encounteredList) + + section.append(charactersSection, encounteredSection) + host.append(section) + + let signature = '' + + function render(state: RootState): void { + const visible = state.session.role !== null && + (state.connection.phase === 'live' || state.connection.phase === 'reconnecting') + section.hidden = !visible + if (!visible) return + + const characters = ownCharactersOf(state) + const encountered = encounteredOf(state) + const next = listSignature(characters, encountered) + // The lists change on frames, not per frame: rebuild rows only when their content changed. + if (next !== signature) { + signature = next + charactersList.replaceChildren(...characters.map(characterRow)) + encounteredList.replaceChildren(...encountered.map(encounteredRow)) + charactersEmpty.hidden = characters.length > 0 + encounteredEmpty.hidden = encountered.length > 0 + } + } + + const unsubscribe = store.subscribe(render) + render(store.state) + + return () => { + unsubscribe() + section.remove() + } +} diff --git a/client/src/render/modules/lists.ts b/client/src/render/modules/lists.ts new file mode 100644 index 0000000..27f8d24 --- /dev/null +++ b/client/src/render/modules/lists.ts @@ -0,0 +1,16 @@ +// Mounts the lists panel under the shell's `#panels` host when the stage comes up (T8, #71). A +// render module rather than a `main.ts` edit: the stage's lifetime is the live session's, so a +// panel cannot outlive a sign-in screen, and parallel tickets add their own panels without touching +// a shared registry. + +import type { RenderModule } from '../stage.ts' +import { mountListsPanel } from '../../panels/lists.ts' + +export const renderModule: RenderModule = { + name: 'lists', + mount({ store }): (() => void) | void { + const host = document.querySelector('#panels') + if (!host) return + return mountListsPanel(host, store) + }, +} diff --git a/client/src/render/modules/tokens.ts b/client/src/render/modules/tokens.ts new file mode 100644 index 0000000..72a24df --- /dev/null +++ b/client/src/render/modules/tokens.ts @@ -0,0 +1,243 @@ +// The token layer (T8, #71; DESIGN 7.1 layer 3, 6.1 `token`/`token_gone`). +// +// Pooled containers in world coordinates on the `tokens` layer: the camera (#69) transforms the +// layer's parent, never the tokens, so pan/zoom composes without this module knowing about it. +// A name is a `BitmapText` from one pre-installed `BitmapFont` (DESIGN 7.2, Q17): atlased once, and +// the text is re-assigned only when the name actually changed, never per frame. Statuses are drawn +// as badges (story 30): a barred ring for `stuck`, inward brackets for `squeezed`. +// +// Everything here is driven by TokenBoard patches, so one changed token touches one container and +// the untouched ones are not visited (DESIGN 7.2). The counts are published on the canvas dataset +// so the browser e2e can prove that rule against the real server (`data-token-updated` etc). + +import { BitmapFont, BitmapText, Container, Graphics, GraphicsContext } from 'pixi.js' +import type { RenderContext, RenderModule } from '../stage.ts' +import { TokenBoard } from '../tokenBoard.ts' +import type { TokenPatch } from '../tokenBoard.ts' +import { tokensOf } from '../../slices/tokens.ts' +import type { TokenView } from '../../slices/tokens.ts' + +/** One font for every token label: Latin (incl. accented) and the ASCII the names use. */ +const TOKEN_FONT = 'fff-token-label' +const LABEL_SIZE = 16 +const GLYPHS: Array = [ + [' ', '~'], + ['\u00A0', '\u00FF'], + ['\u0100', '\u017F'], + '×·—–’‘“”…€£¥°', +] + +let fontInstalled = false +function installFont(): void { + if (fontInstalled) return + fontInstalled = true + BitmapFont.install({ + name: TOKEN_FONT, + style: { + fontFamily: 'Arial, Helvetica, sans-serif', + fontSize: LABEL_SIZE, + fill: 0xffffff, + stroke: { color: 0x000000, width: 3 }, + }, + chars: GLYPHS, + }) +} + +/** + * Shared unit-circle contexts, tessellated once and scaled to each token's radius (DESIGN 7.2: + * one GraphicsContext per colour, never one Graphics per token per frame). + */ +const BODY_STYLES = { + mine: new GraphicsContext() + .circle(0, 0, 1) + .fill(0xe8bf4f) + .stroke({ width: 0.09, color: 0xfff3c4 }), + other: new GraphicsContext() + .circle(0, 0, 1) + .fill(0x4f7fbf) + .stroke({ width: 0.09, color: 0xc7dcff }), + gmOnly: new GraphicsContext() + .circle(0, 0, 1) + .fill(0x6d4f86) + .stroke({ width: 0.09, color: 0xc9a5e0 }), +} as const + +interface TokenNode { + container: Container + body: Graphics + label: BitmapText + badges: Graphics + /** What this node currently shows, so a patch can skip work that would change nothing. */ + shape: 'mine' | 'other' | 'gmOnly' | null + statusKey: string +} + +function createNode(radius: number): TokenNode { + const container = new Container() + const body = new Graphics() + const label = new BitmapText({ + text: '', + style: { fontFamily: TOKEN_FONT, fontSize: LABEL_SIZE }, + roundPixels: true, + }) + label.anchor.set(0.5, 0) + label.y = radius + 2 + const badges = new Graphics() + badges.visible = false + container.addChild(body, label, badges) + return { container, body, label, badges, shape: null, statusKey: '' } +} + +function shapeOf(view: TokenView): 'mine' | 'other' | 'gmOnly' { + if (view.gmOnly) return 'gmOnly' + return view.mine ? 'mine' : 'other' +} + +/** The badge glyphs. Two statuses stack; a cause is never drawn (players do not know it, 5.5). */ +function drawBadges(graphics: Graphics, radius: number, statuses: readonly string[]): void { + graphics.clear() + if (statuses.length === 0) { + graphics.visible = false + return + } + graphics.visible = true + const size = Math.max(6, Math.min(12, radius * 0.42)) + const x = radius * 0.62 + let y = -radius * 0.62 + for (const status of statuses) { + if (status === 'stuck') { + // A barred ring: the token is held in place. + graphics.circle(x, y, size).fill(0x2a0505).stroke({ width: 2, color: 0xff4d4d }) + graphics + .moveTo(x - size * 0.62, y + size * 0.62) + .lineTo(x + size * 0.62, y - size * 0.62) + .stroke({ width: 2, color: 0xff4d4d }) + } else if (status === 'squeezed') { + // Two arrows pressing inward: the token has no room. + const half = size * 0.55 + graphics.circle(x, y, size).fill(0x2a1a02).stroke({ width: 2, color: 0xffb02e }) + graphics + .moveTo(x - half, y) + .lineTo(x - half * 0.2, y) + .moveTo(x + half, y) + .lineTo(x + half * 0.2, y) + .stroke({ width: 2, color: 0xffb02e }) + } else { + // A status this client has no badge for still shows that something is wrong. + graphics.circle(x, y, size).fill(0x222222).stroke({ width: 2, color: 0xcccccc }) + } + y += size * 2.3 + } +} + +/** + * Draw one token. `at` is the position to draw at; it is the server's `pos` today, and the drag + * module (#72) passes its optimistic position here while a drag is in flight, so prediction and + * rollback never touch the reducer's authoritative view. + */ +function applyView( + node: TokenNode, + view: TokenView, + stats: { labels: number }, + at: readonly [number, number] = view.pos, +): void { + const container = node.container + container.position.set(at[0], at[1]) + container.alpha = view.gmOnly ? 0.72 : 1 + + const shape = shapeOf(view) + if (shape !== node.shape) { + node.body.context = BODY_STYLES[shape] + node.shape = shape + } + // A unit circle scaled to the effective radius: one shared context for every token of a kind. + node.body.scale.set(view.radius) + node.body.visible = true + + // The label is built once per name: assigning `text` re-lays out quads, so only do it on a change. + if (node.label.text !== view.name) { + node.label.text = view.name + stats.labels += 1 + } + node.label.y = view.radius + 2 + + // Badge size and place follow the radius, so a resize redraws them too. + const statusKey = `${view.radius}:${view.statuses.join(' ')}` + if (statusKey !== node.statusKey) { + drawBadges(node.badges, view.radius, view.statuses) + node.statusKey = statusKey + } +} + +/** Publish the renderer's own counts, so the e2e can observe "only changed entities touched". */ +function publish(canvas: HTMLCanvasElement, board: TokenBoard, patch: TokenPatch, labels: number): void { + const datasets = canvas.dataset + datasets['tokens'] = String(board.size) + datasets['tokenEntered'] = String(patch.entered.length) + datasets['tokenUpdated'] = String(patch.updated.length) + datasets['tokenLeft'] = String(patch.left.length) + datasets['tokenLabels'] = String(labels) + datasets['tokenIds'] = [...board.views.keys()].join(' ') + datasets['tokenStatuses'] = [...board.views.values()] + .flatMap(view => view.statuses.map(status => `${view.id}:${status}`)) + .join(' ') +} + +export const renderModule: RenderModule = { + name: 'tokens', + mount(context: RenderContext): (() => void) | void { + installFont() + const { store, app, layers } = context + const canvas = app.canvas + const board = new TokenBoard() + const pool: TokenNode[] = [] + const nodes = new Map() + const stats = { labels: 0 } + + function removeNode(id: string): void { + const node = nodes.get(id) + if (!node) return + layers.tokens.removeChild(node.container) + node.container.visible = false + nodes.delete(id) + pool.push(node) + } + + function enterNode(view: TokenView): void { + const node = pool.pop() ?? createNode(view.radius) + node.container.visible = true + applyView(node, view, stats) + layers.tokens.addChild(node.container) + nodes.set(view.id, node) + } + + // The stage is created only once the session is live, but `app.init` is async and the resync + // can beat it: start from whatever the reducer already holds, then follow the event stream. + board.seed(tokensOf(store.state)) + let patch = board.drain() + for (const view of patch.entered) enterNode(view) + publish(canvas, board, patch, stats.labels) + + const unsubscribe = store.subscribe((_state, event) => { + board.apply(event) + patch = board.drain() + if (patch.reset) { + for (const id of [...nodes.keys()]) removeNode(id) + } + for (const id of patch.left) removeNode(id) + for (const view of patch.updated) { + const node = nodes.get(view.id) + if (node) applyView(node, view, stats) + else enterNode(view) + } + for (const view of patch.entered) enterNode(view) + if (patch.reset || patch.entered.length > 0 || patch.updated.length > 0 || patch.left.length > 0) { + publish(canvas, board, patch, stats.labels) + } + }) + + return () => { + unsubscribe() + } + }, +} diff --git a/client/src/render/tokenBoard.ts b/client/src/render/tokenBoard.ts new file mode 100644 index 0000000..3ebbf68 --- /dev/null +++ b/client/src/render/tokenBoard.ts @@ -0,0 +1,111 @@ +// The token renderer's pure half (T8, #71). No Pixi import: it turns the store's event stream into +// the exact nodes a renderer must create, update or remove, so the "only changed entities" rule of +// DESIGN 7.2 is observable and unit-tested instead of hidden inside a WebGL module. +// +// It mirrors the token slice's parsing (one wire shape, one parser) but keeps its own view of what +// is currently on screen, which is what a renderer actually needs: a `token_gone` is only a removal +// if a node exists, and a `token` frame for an existing node is an update, not an entry. + +import type { ReducerEvent } from '../reducer.ts' +import { isHello } from '../protocol.ts' +import type { TokenView } from '../slices/tokens.ts' +import { tokenViewFromFrame } from '../slices/tokens.ts' + +export interface TokenPatch { + /** Everything on screen must go (a `hello` is a full reset, 6.3). */ + reset: boolean + entered: TokenView[] + updated: TokenView[] + left: string[] +} + +export class TokenBoard { + #views = new Map() + #reset = false + #entered = new Map() + #updated = new Map() + #left = new Set() + + get size(): number { + return this.#views.size + } + + /** What is on screen now, in entry order. Read-only for the renderer's dataset/teardown. */ + get views(): ReadonlyMap { + return this.#views + } + + /** + * Start from the reducer's current view. The stage is created asynchronously, so the resync may + * have run before a render module mounts; without this a token that arrived during `app.init` + * would stay invisible until it changed. Every seeded token is an entry. + */ + seed(views: readonly TokenView[]): void { + this.#views.clear() + this.#entered.clear() + this.#updated.clear() + this.#left.clear() + this.#reset = false + for (const view of views) { + this.#views.set(view.id, view) + this.#entered.set(view.id, view) + } + } + + /** Fold one store event into the pending patch. Nothing is drawn here. */ + apply(event: ReducerEvent): void { if (event.type !== 'frame') return + const frame = event.frame + if (isHello(frame)) { + // A `hello` means "start clean" (6.3): the nodes all die, and anything still pending for the + // previous connection is dropped rather than replayed onto the new view. + this.#views.clear() + this.#entered.clear() + this.#updated.clear() + this.#left.clear() + this.#reset = true + return + } + if (frame.t === 'token') { + const view = tokenViewFromFrame(frame) + if (!view) return + const existing = this.#views.has(view.id) + this.#views.set(view.id, view) + if (existing) { + // A token that entered and changed between two drains is still one entry, drawn once. + if (this.#entered.has(view.id)) { + this.#entered.set(view.id, view) + return + } + this.#updated.set(view.id, view) + this.#left.delete(view.id) + } else { + this.#updated.delete(view.id) + this.#entered.set(view.id, view) + } + return + } + if (frame.t === 'token_gone') { + const id = frame['id'] + if (typeof id !== 'string' || !this.#views.has(id)) return + this.#views.delete(id) + this.#entered.delete(id) + this.#updated.delete(id) + this.#left.add(id) + } + } + + /** Take the pending patch: the renderer touches exactly these entities, then waits. */ + drain(): TokenPatch { + const patch: TokenPatch = { + reset: this.#reset, + entered: [...this.#entered.values()], + updated: [...this.#updated.values()], + left: [...this.#left], + } + this.#reset = false + this.#entered.clear() + this.#updated.clear() + this.#left.clear() + return patch + } +} diff --git a/client/src/slices/characters.ts b/client/src/slices/characters.ts new file mode 100644 index 0000000..f8b1ad3 --- /dev/null +++ b/client/src/slices/characters.ts @@ -0,0 +1,93 @@ +// Characters slice (DESIGN 6.1 `character`/`character_gone`, story 31). The server sends a character +// record only to the GM and to the player who owns it, so a player's slice *is* that player's list; +// the GM's slice is the whole cast and the list panel filters it to the GM's own. + +import type { ReducerEvent, RootState, Slice } from '../reducer.ts' +import type { ServerFrame } from '../protocol.ts' + +export interface CharacterView { + id: string + /** Absent on the owner's own view (6.1); the GM's copy carries it. */ + owner: number | null + descriptiveName: string + actualName: string + props: Record> +} + +function own(record: Record, key: string): unknown { + return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined +} + +export interface CharactersState { + byId: Record + order: string[] +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function propBuckets(value: unknown): Record> { + if (!isRecord(value)) return {} + const buckets: Record> = {} + for (const [bucket, contents] of Object.entries(value)) { + if (isRecord(contents)) buckets[bucket] = contents + } + return buckets +} + +export function characterViewFromFrame(frame: ServerFrame): CharacterView | null { + const id = frame['id'] + if (typeof id !== 'string' || id.length === 0) return null + if (typeof frame['descriptive_name'] !== 'string') return null + if (typeof frame['actual_name'] !== 'string') return null + const owner = frame['owner'] + return { + id, + owner: typeof owner === 'number' && Number.isFinite(owner) ? owner : null, + descriptiveName: frame['descriptive_name'], + actualName: frame['actual_name'], + props: propBuckets(frame['props']), + } +} + +export const slice: Slice = { + name: 'characters', + init: () => ({ byId: {}, order: [] }), + reduce(state: CharactersState, event: ReducerEvent, _root: RootState): void { + if (event.type !== 'frame') return + const frame = event.frame + if (frame.t === 'character') { + const character = characterViewFromFrame(frame) + if (!character) return + if (own(state.byId, character.id) === undefined) state.order.push(character.id) + state.byId = { ...state.byId, [character.id]: character } + } else if (frame.t === 'character_gone') { + const id = frame['id'] + if (typeof id !== 'string' || own(state.byId, id) === undefined) return + const byId = { ...state.byId } + delete byId[id] + state.byId = byId + state.order = state.order.filter(entry => entry !== id) + } + }, +} + +export function charactersOf(state: RootState): CharacterView[] { + const characters = state.slices['characters'] as CharactersState | undefined + if (!characters) return [] + return characters.order + .map(id => characters.byId[id]) + .filter((character): character is CharacterView => character !== undefined) +} + +/** Story 31: the characters this player may call their own. */ +export function ownCharactersOf(state: RootState): CharacterView[] { + const me = state.session.me + const characters = charactersOf(state) + // A player only ever receives their own records (6.1), so everything is theirs. + if (state.session.role !== 'gm') return characters + // The GM's copy of the whole cast carries `owner`; the list is the GM's own figures. + if (me === null) return [] + return characters.filter(character => character.owner === me.id) +} diff --git a/client/src/slices/encountered.ts b/client/src/slices/encountered.ts new file mode 100644 index 0000000..4c4f53f --- /dev/null +++ b/client/src/slices/encountered.ts @@ -0,0 +1,73 @@ +// Encountered slice (DESIGN 6.1 `encountered`, story 32). Per player: the figures that player has +// met, with `grey` marking one that is no longer in view ("met before, whereabouts unknown"). The GM +// receives one message per player; those are not the GM's own list and are ignored here. + +import type { ReducerEvent, RootState, Slice } from '../reducer.ts' +import type { ServerFrame } from '../protocol.ts' + +export interface EncounteredEntry { + id: string + name: string + grey: boolean +} + +export interface EncounteredState { + entries: EncounteredEntry[] +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function entry(value: unknown): EncounteredEntry | null { + if (!isRecord(value)) return null + const id = value['id'] + const name = value['name'] + if (typeof id !== 'string' || typeof name !== 'string') return null + return { id, name, grey: value['grey'] === true } +} + +function upsert(entries: EncounteredEntry[], next: EncounteredEntry): EncounteredEntry[] { + const index = entries.findIndex(existing => existing.id === next.id) + if (index < 0) return [...entries, next] + const copy = entries.slice() + copy[index] = next + return copy +} + +export const slice: Slice = { + name: 'encountered', + init: () => ({ entries: [] }), + reduce(state: EncounteredState, event: ReducerEvent, root: RootState): void { + if (event.type !== 'frame') return + const frame: ServerFrame = event.frame + if (frame.t !== 'encountered') return + // The GM's copies carry `player` (6.1): one list per player, never the GM's own. + if (root.session.role === 'gm' || typeof frame['player'] === 'number') return + const set = frame['set'] + if (!Array.isArray(set)) return + const incoming: EncounteredEntry[] = [] + for (const item of set) { + const parsed = entry(item) + if (!parsed) return + incoming.push(parsed) + } + if (frame['full'] === true) { + state.entries = incoming + return + } + let entries = state.entries + const del = frame['del'] + if (Array.isArray(del)) { + const removed = new Set(del.filter((id): id is string => typeof id === 'string')) + if (removed.size > 0) entries = entries.filter(existing => !removed.has(existing.id)) + } + for (const item of incoming) entries = upsert(entries, item) + state.entries = entries + }, +} + +export function encounteredOf(state: RootState): EncounteredEntry[] { + const encountered = state.slices['encountered'] as EncounteredState | undefined + return encountered?.entries ?? [] +} diff --git a/client/src/slices/tokens.ts b/client/src/slices/tokens.ts new file mode 100644 index 0000000..b4884e7 --- /dev/null +++ b/client/src/slices/tokens.ts @@ -0,0 +1,152 @@ +// Tokens slice (DESIGN 6.1 `token`/`token_gone`, stories 28-30 and 34). Append-only registration: +// adding this file was enough; the reducer's glob picked it up and `hello` resets it with every +// other slice. +// +// A token frame is *the whole view of one token* for this recipient (6.1), built by the server at +// egress: a player only ever receives tokens they control plus tokens inside their own line of +// sight and not `gm_only`, and the GM receives every token. The client therefore never filters for +// secrecy; it only keeps what arrived and forgets a token on `token_gone` (the server's "you may +// not see it any more", story 29). + +import type { ReducerEvent, RootState, Slice } from '../reducer.ts' +import type { ServerFrame, Vec2 } from '../protocol.ts' + +export interface TokenView { + id: string + scene: number | null + /** The one name this recipient may see (8); never a reveal state. */ + name: string + pos: Vec2 + /** Effective radius in px (5.6). */ + radius: number + /** True when this recipient controls the token (players only; GM frames say false). */ + mine: boolean + /** Status names only; the cause (`source`) is GM-only (5.5, 6.1 leak note 6). */ + statuses: string[] + /** The prop buckets this recipient may read: public, plus owner for the controller. */ + props: Record> + /** GM-only fields (6.1): present on a GM connection, absent for a player. */ + gmOnly: boolean + kind: string | null + controller: number | null + characterId: string | null +} + +function own(record: Record, key: string): unknown { + return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined +} + +export interface TokensState { + byId: Record + /** Render order: entry order, kept across updates so a token never jumps layers on a move. */ + order: string[] +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function isVec2(value: unknown): value is Vec2 { + return ( + Array.isArray(value) && + value.length === 2 && + typeof value[0] === 'number' && + typeof value[1] === 'number' && + Number.isFinite(value[0]) && + Number.isFinite(value[1]) + ) +} + +function statusNames(value: unknown): string[] | null { + if (!Array.isArray(value)) return null + const names: string[] = [] + for (const entry of value) { + if (!isRecord(entry) || typeof entry['status'] !== 'string') return null + // `source` is deliberately not stored: players never receive it, and a GM's own renderer has + // no use for it yet (6.1 leak note 6). + names.push(entry['status']) + } + return names +} + +function propBuckets(value: unknown): Record> { + if (!isRecord(value)) return {} + const buckets: Record> = {} + for (const [bucket, contents] of Object.entries(value)) { + if (isRecord(contents)) buckets[bucket] = contents + } + return buckets +} + +function optionalString(value: unknown): string | null { + return typeof value === 'string' ? value : null +} + +function optionalNumber(value: unknown): number | null { + return typeof value === 'number' && Number.isFinite(value) ? value : null +} + +/** + * One `token` frame as the slice stores it, or null when the frame cannot be that shape. An + * unreadable frame is ignored (6.2: unknown shapes never become state), not half-applied. + */ +export function tokenViewFromFrame(frame: ServerFrame): TokenView | null { + const id = frame['id'] + const pos = frame['pos'] + const radius = frame['radius'] + const statuses = statusNames(frame['statuses']) + if (typeof id !== 'string' || id.length === 0) return null + if (!isVec2(pos)) return null + if (typeof radius !== 'number' || !Number.isFinite(radius)) return null + if (statuses === null) return null + return { + id, + scene: optionalNumber(frame['scene']), + name: typeof frame['name'] === 'string' ? frame['name'] : '', + pos, + radius, + mine: frame['mine'] === true, + statuses, + props: propBuckets(frame['props']), + gmOnly: frame['gm_only'] === true, + kind: optionalString(frame['kind']), + controller: optionalNumber(frame['controller']), + characterId: optionalString(frame['character_id']), + } +} + +export const slice: Slice = { + name: 'tokens', + init: () => ({ byId: {}, order: [] }), + reduce(state: TokensState, event: ReducerEvent, _root: RootState): void { + if (event.type !== 'frame') return + const frame = event.frame + if (frame.t === 'token') { + const token = tokenViewFromFrame(frame) + if (!token) return + if (own(state.byId, token.id) === undefined) state.order.push(token.id) + state.byId = { ...state.byId, [token.id]: token } + } else if (frame.t === 'token_gone') { + const id = frame['id'] + if (typeof id !== 'string' || own(state.byId, id) === undefined) return + const byId = { ...state.byId } + delete byId[id] + state.byId = byId + state.order = state.order.filter(entry => entry !== id) + } + }, +} + +/** Every token this recipient may see, in entry order. */ +export function tokensOf(state: RootState): TokenView[] { + const tokens = state.slices['tokens'] as TokensState | undefined + if (!tokens) return [] + return tokens.order.map(id => tokens.byId[id]).filter((token): token is TokenView => token !== undefined) +} + +export function tokenOf(state: RootState, id: string): TokenView | null { + const tokens = state.slices['tokens'] as TokensState | undefined + if (!tokens) return null + const token = own(tokens.byId, id) + return (token as TokenView | undefined) ?? null +} diff --git a/client/src/style.css b/client/src/style.css index a86e56c..2b85142 100644 --- a/client/src/style.css +++ b/client/src/style.css @@ -271,3 +271,66 @@ body { opacity: 0.7; word-break: break-word; } + +/* Lists panel (T8, #71): story 31's own characters and story 32's encountered list. Overlaid on the + canvas inside the shared `#panels` column; the pointers stay with the canvas (DESIGN 7.2). */ +#lists { + display: flex; + flex-direction: column; + gap: 6px; + padding: 8px 10px; + border: 1px solid #333; + border-radius: 6px; + background: rgb(0 0 0 / 55%); + font: 12px/1.4 ui-monospace, monospace; + pointer-events: none; +} + +#lists .panel-title { + margin: 0 0 2px; + font: 600 11px/1.2 system-ui, sans-serif; + letter-spacing: 0.08em; + text-transform: uppercase; + opacity: 0.65; +} + +#lists ul { + display: flex; + flex-direction: column; + gap: 2px; + margin: 0 0 6px; + padding: 0; + list-style: none; +} + +#lists li { + display: flex; + gap: 6px; + align-items: baseline; + justify-content: space-between; +} + +#lists .entry-values { + font-size: 11px; + opacity: 0.6; +} + +#lists .entry-state { + font-size: 10px; + opacity: 0.45; +} + +#lists .empty { + margin: 0 0 6px; + opacity: 0.45; +} + +/* Story 32: met before, whereabouts unknown. */ +#lists li.grey, +#lists li[data-grey='true'] { + opacity: 0.55; +} + +#lists li.grey .entry-name { + color: #8f8f8f; +} diff --git a/client/test/lists.test.ts b/client/test/lists.test.ts new file mode 100644 index 0000000..387ddcf --- /dev/null +++ b/client/test/lists.test.ts @@ -0,0 +1,149 @@ +// T8 (#71): the lists' reducer seam. Story 31 (my characters with my own values) and story 32 (an +// encountered list with greyed entries). `character`/`character_gone` and `encountered` in, the +// two lists out; `hello` resets both with every other slice. +import { describe, expect, it } from 'vitest' +import { initialState, reduce } from '../src/reducer.ts' +import type { ReducerEvent, RootState } from '../src/reducer.ts' +import { parseServerFrame } from '../src/protocol.ts' +import { charactersOf, ownCharactersOf } from '../src/slices/characters.ts' +import { encounteredOf } from '../src/slices/encountered.ts' + +const frame = (body: Record): ReducerEvent => { + const parsed = parseServerFrame(JSON.stringify(body)) + if (!parsed) throw new Error(`bad test frame ${JSON.stringify(body)}`) + return { type: 'frame', frame: parsed } +} + +const hello = (n: number, role: 'gm' | 'player' = 'player', id = 2): ReducerEvent => + frame({ t: 'hello', n, proto: 2, role, me: { id, name: role === 'gm' ? 'GM' : 'Ann' } }) + +/** The owner's view has no `owner`/`reveal_all`/`revealed` field (6.1). */ +const ownerCharacter = (n: number, id: string, overrides: Record = {}): ReducerEvent => + frame({ + t: 'character', + n, + id, + descriptive_name: 'Ann', + actual_name: 'Ann of the Vale', + props: { public: {}, owner: { hp: 12 } }, + ...overrides, + }) + +const gmCharacter = (n: number, id: string, owner: number, overrides: Record = {}): ReducerEvent => + frame({ + t: 'character', + n, + id, + owner, + descriptive_name: 'Ann', + actual_name: 'Ann of the Vale', + reveal_all: false, + revealed: [], + props: { public: {}, owner: { hp: 12 }, gm: { secret: true } }, + ...overrides, + }) + +const encountered = (n: number, body: Record): ReducerEvent => + frame({ t: 'encountered', n, ...body }) + +const run = (...events: ReducerEvent[]): RootState => + events.reduce((state, event) => reduce(state, event), initialState()) + +describe('my characters (story 31)', () => { + it('lists the characters the server sent the owner, with their own values', () => { + const state = run({ type: 'connecting' }, hello(1), ownerCharacter(2, 'char1')) + expect(charactersOf(state)).toHaveLength(1) + expect(ownCharactersOf(state)).toEqual([ + expect.objectContaining({ + id: 'char1', + descriptiveName: 'Ann', + actualName: 'Ann of the Vale', + props: { public: {}, owner: { hp: 12 } }, + }), + ]) + }) + + it('replaces a character on a later frame and drops it on character_gone', () => { + const state = run( + { type: 'connecting' }, + hello(1), + ownerCharacter(2, 'char1'), + ownerCharacter(3, 'char1', { descriptive_name: 'Ann the Bold' }), + ) + expect(ownCharactersOf(state)).toEqual([expect.objectContaining({ descriptiveName: 'Ann the Bold' })]) + + const gone = reduce(state, frame({ t: 'character_gone', n: 4, id: 'char1' })) + expect(ownCharactersOf(gone)).toEqual([]) + expect(charactersOf(gone)).toEqual([]) + }) + + it('shows a GM only the characters that GM owns, never the whole cast', () => { + const state = run( + { type: 'connecting' }, + hello(1, 'gm', 1), + gmCharacter(2, 'char1', 2), + gmCharacter(3, 'char2', 1), + ) + expect(ownCharactersOf(state).map(character => character.id)).toEqual(['char2']) + }) + + it('clears the list on hello', () => { + const state = run({ type: 'connecting' }, hello(1), ownerCharacter(2, 'char1'), hello(3)) + expect(ownCharactersOf(state)).toEqual([]) + }) +}) + +describe('encountered list (story 32)', () => { + it('replaces the whole list on full:true and keeps the grey flag', () => { + const state = run( + { type: 'connecting' }, + hello(1), + encountered(2, { + full: true, + set: [ + { id: 'aaa', name: 'Rat', grey: false }, + { id: 'bbb', name: 'Bat', grey: true }, + ], + }), + ) + expect(encounteredOf(state)).toEqual([ + { id: 'aaa', name: 'Rat', grey: false }, + { id: 'bbb', name: 'Bat', grey: true }, + ]) + }) + + it('applies a diff: set upserts and del removes, without touching anything else', () => { + const state = run( + { type: 'connecting' }, + hello(1), + encountered(2, { + full: true, + set: [ + { id: 'aaa', name: 'Rat', grey: false }, + { id: 'bbb', name: 'Bat', grey: false }, + ], + }), + encountered(3, { full: false, set: [{ id: 'aaa', name: 'Rat', grey: true }], del: ['bbb'] }), + ) + expect(encounteredOf(state)).toEqual([{ id: 'aaa', name: 'Rat', grey: true }]) + }) + + it('ignores the GM copy, which is one message per player and not the GM own list', () => { + const state = run( + { type: 'connecting' }, + hello(1, 'gm', 1), + encountered(2, { full: true, set: [{ id: 'aaa', name: 'Rat', grey: false }], player: 2 }), + ) + expect(encounteredOf(state)).toEqual([]) + }) + + it('clears on hello', () => { + const state = run( + { type: 'connecting' }, + hello(1), + encountered(2, { full: true, set: [{ id: 'aaa', name: 'Rat', grey: false }] }), + hello(3), + ) + expect(encounteredOf(state)).toEqual([]) + }) +}) diff --git a/client/test/token-board.test.ts b/client/test/token-board.test.ts new file mode 100644 index 0000000..7b3f663 --- /dev/null +++ b/client/test/token-board.test.ts @@ -0,0 +1,177 @@ +// T8 (#71): the token renderer's pure seam. The board turns store events into the exact set of +// entities a renderer has to touch — entered, updated, left — so a frame that moves one token costs +// one node update, never a full redraw (DESIGN 7.2, spec #63 decision 11). +import { describe, expect, it } from 'vitest' +import { initialState, reduce } from '../src/reducer.ts' +import type { ReducerEvent } from '../src/reducer.ts' +import { parseServerFrame } from '../src/protocol.ts' +import { TokenBoard } from '../src/render/tokenBoard.ts' +import { tokenViewFromFrame } from '../src/slices/tokens.ts' + +const frame = (body: Record): ReducerEvent => { + const parsed = parseServerFrame(JSON.stringify(body)) + if (!parsed) throw new Error(`bad test frame ${JSON.stringify(body)}`) + return { type: 'frame', frame: parsed } +} + +const hello = (n = 1): ReducerEvent => + frame({ t: 'hello', n, proto: 2, role: 'player', me: { id: 2, name: 'Ann' } }) + +const token = (n: number, id: string, overrides: Record = {}): ReducerEvent => + frame({ + t: 'token', + n, + id, + scene: 1, + name: 'Rat', + pos: [400, 400], + radius: 20, + mine: false, + statuses: [], + props: {}, + ...overrides, + }) + +/** Apply every event, draining after each one the way the renderer does. */ +function feed(board: TokenBoard, events: ReducerEvent[]) { + const patches = [] + for (const event of events) { + board.apply(event) + patches.push(board.drain()) + } + return patches +} + +describe('the token board (stories 28, 29; DESIGN 7.2)', () => { + it('reports one entity entered per new token', () => { + const board = new TokenBoard() + const patches = feed(board, [hello(), token(2, 'aaa'), token(3, 'bbb')]) + expect(patches[0]).toMatchObject({ reset: true, entered: [], updated: [], left: [] }) + expect(patches[1]?.entered.map(view => view.id)).toEqual(['aaa']) + expect(patches[1]?.updated).toEqual([]) + // The second token arrives on its own frame; nothing earlier is re-entered. + expect(board.size).toBe(2) + }) + + it('moves only the changed token, never the whole set (the instrumented count)', () => { + const board = new TokenBoard() + const events: ReducerEvent[] = [hello()] + for (let i = 0; i < 50; i += 1) events.push(token(2 + i, `t${i}`)) + feed(board, events) + expect(board.size).toBe(50) + + board.apply(token(100, 't7', { pos: [420, 400] })) + const patch = board.drain() + // One token moved -> one entity updated. 49 untouched tokens are not touched again. + expect(patch.updated.map(view => view.id)).toEqual(['t7']) + expect(patch.entered).toEqual([]) + expect(patch.left).toEqual([]) + expect(board.size).toBe(50) + }) + + it('reports a token leaving once, with no stale entered entry', () => { + const board = new TokenBoard() + feed(board, [hello(), token(2, 'aaa'), token(3, 'bbb')]) + board.apply(frame({ t: 'token_gone', n: 4, id: 'aaa' })) + const patch = board.drain() + expect(patch.left).toEqual(['aaa']) + expect(patch.entered).toEqual([]) + expect(patch.updated).toEqual([]) + expect(board.size).toBe(1) + }) + + it('never both enters and leaves one token between drains', () => { + const board = new TokenBoard() + board.apply(hello()) + board.drain() + board.apply(token(2, 'aaa')) + board.apply(frame({ t: 'token_gone', n: 3, id: 'aaa' })) + const patch = board.drain() + expect(patch.entered).toEqual([]) + expect(patch.updated).toEqual([]) + expect(patch.left).toEqual(['aaa']) + expect(board.size).toBe(0) + }) + + it('asks for a reset on hello, and clears anything still pending', () => { + const board = new TokenBoard() + feed(board, [hello(), token(2, 'aaa')]) + board.apply(token(3, 'bbb')) + board.apply(hello(4)) + const patch = board.drain() + expect(patch.reset).toBe(true) + expect(patch.entered).toEqual([]) + expect(patch.updated).toEqual([]) + expect(patch.left).toEqual([]) + expect(board.size).toBe(0) + }) + + it('ignores a close: the map stays on screen, the resync arrives after the next hello', () => { + const board = new TokenBoard() + feed(board, [hello(), token(2, 'aaa')]) + board.apply({ type: 'close', reason: null, code: 1006 }) + const patch = board.drain() + expect(patch).toMatchObject({ reset: false, entered: [], updated: [], left: [] }) + expect(board.size).toBe(1) + }) + + it('keeps the view an entity was last given, for the renderer to compare against', () => { const board = new TokenBoard() + board.apply(hello()) + board.apply(token(2, 'aaa', { name: 'Rat' })) + expect(board.views.get('aaa')?.name).toBe('Rat') + board.apply(token(3, 'aaa', { name: 'Giant Rat' })) + expect(board.views.get('aaa')?.name).toBe('Giant Rat') + }) + + it('seeds the current state when a stage mounts after the resync', () => { + const board = new TokenBoard() + const view = parseServerFrame( + JSON.stringify({ + t: 'token', + n: 1, + id: 'aaa', + scene: 1, + name: 'Rat', + pos: [400, 400], + radius: 20, + mine: false, + statuses: [], + props: {}, + }), + ) + if (!view) throw new Error('bad test frame') + const parsed = tokenViewFromFrame(view) + if (!parsed) throw new Error('bad test token') + board.seed([parsed]) + const patch = board.drain() + expect(patch.entered.map(entry => entry.id)).toEqual(['aaa']) + expect(patch.reset).toBe(false) + expect(board.size).toBe(1) + }) + + it('is a pure reader of reducer state too: the slice agrees with the board', () => { + let state = reduce(initialState(), { type: 'connecting' }) + const board = new TokenBoard() + for (const event of [hello(), token(2, 'aaa'), token(3, 'bbb')]) { + state = reduce(state, event) + board.apply(event) + board.drain() + } + expect([...board.views.keys()]).toEqual(['aaa', 'bbb']) + expect(state.slices['tokens']).toBeDefined() + }) +}) + +describe('the token board keeps one pending entry per entity', () => { + it('draws a token once when it enters and changes before the drain', () => { + const board = new TokenBoard() + board.apply(hello()) + board.drain() + board.apply(token(2, 'aaa', { name: 'Rat' })) + board.apply(token(3, 'aaa', { name: 'Giant Rat' })) + const patch = board.drain() + expect(patch.entered.map(view => [view.id, view.name])).toEqual([['aaa', 'Giant Rat']]) + expect(patch.updated).toEqual([]) + expect(board.size).toBe(1) + }) +}) diff --git a/client/test/tokens.test.ts b/client/test/tokens.test.ts new file mode 100644 index 0000000..ea29282 --- /dev/null +++ b/client/test/tokens.test.ts @@ -0,0 +1,142 @@ +// T8 (#71): the token slice is the reducer seam for stories 28-30 and 34. Server frames in, the +// token view out; `token` upserts one token, `token_gone` removes it, `hello` resets the view. +import { describe, expect, it } from 'vitest' +import { initialState, reduce } from '../src/reducer.ts' +import type { ReducerEvent, RootState } from '../src/reducer.ts' +import { parseServerFrame } from '../src/protocol.ts' +import { tokenOf, tokensOf } from '../src/slices/tokens.ts' + +const frame = (body: Record): ReducerEvent => { + const parsed = parseServerFrame(JSON.stringify(body)) + if (!parsed) throw new Error(`bad test frame ${JSON.stringify(body)}`) + return { type: 'frame', frame: parsed } +} + +const hello = (n: number): ReducerEvent => + frame({ t: 'hello', n, proto: 2, role: 'player', me: { id: 2, name: 'Ann' } }) + +/** A player-shaped token frame: `statuses` are names only, no `source` (6.1 leak note 6). */ +const playerToken = (n: number, id: string, overrides: Record = {}): ReducerEvent => + frame({ + t: 'token', + n, + id, + scene: 1, + name: 'Rat', + pos: [400, 400], + radius: 20, + mine: false, + statuses: [], + props: { public: {}, cprops: { public: {} } }, + ...overrides, + }) + +const run = (...events: ReducerEvent[]): RootState => + events.reduce((state, event) => reduce(state, event), initialState()) + +describe('token enters, updates and leaves (stories 28, 29)', () => { + it('enters on a token frame and replaces the whole view on a later one', () => { + const state = run( + { type: 'connecting' }, + hello(1), + playerToken(2, 'aaa'), + playerToken(3, 'bbb'), + ) + expect(tokensOf(state).map(token => token.id)).toEqual(['aaa', 'bbb']) + + // 6.1: every `token` message is the whole view of one token; a later one replaces it in place. + const moved = reduce(state, playerToken(4, 'aaa', { pos: [420, 400], radius: 26, name: 'Giant Rat' })) + expect(tokensOf(moved)).toHaveLength(2) + expect(tokensOf(moved).map(token => token.id)).toEqual(['aaa', 'bbb']) + expect(tokenOf(moved, 'aaa')).toMatchObject({ name: 'Giant Rat', pos: [420, 400], radius: 26 }) + expect(tokenOf(moved, 'bbb')).toMatchObject({ name: 'Rat', pos: [400, 400] }) + }) + + it('removes a token on token_gone, and a later frame re-enters it', () => { + const state = run( + { type: 'connecting' }, + hello(1), + playerToken(2, 'aaa'), + playerToken(3, 'bbb'), + frame({ t: 'token_gone', n: 4, id: 'aaa' }), + ) + expect(tokensOf(state).map(token => token.id)).toEqual(['bbb']) + expect(tokenOf(state, 'aaa')).toBeNull() + + const back = reduce(state, playerToken(5, 'aaa')) + expect(tokensOf(back).map(token => token.id)).toEqual(['bbb', 'aaa']) + }) + + it('clears every token on hello: a token that left the view must not survive a reconnect', () => { + const state = run( + { type: 'connecting' }, + hello(1), + playerToken(2, 'aaa'), + playerToken(3, 'bbb'), + hello(4), + ) + expect(tokensOf(state)).toEqual([]) + }) + + it('keeps the status names and drops the GM-only source (6.1 leak note 6)', () => { + const state = run( + { type: 'connecting' }, + hello(1), + playerToken(2, 'aaa', { statuses: [{ status: 'stuck', source: 'walls' }] }), + ) + expect(tokenOf(state, 'aaa')?.statuses).toEqual(['stuck']) + }) + + it('keeps the GM-only fields when the server sends them (story 34)', () => { + const state = run( + { type: 'connecting' }, + hello(1), + playerToken(2, 'aaa', { + statuses: [{ status: 'stuck', source: 'walls' }, { status: 'squeezed', source: 'GM' }], + gm_only: true, + kind: 'npc', + controller: null, + character_id: 'char1', + flags: {}, + vision_radius: 320, + radius_own: null, + }), + ) + const token = tokenOf(state, 'aaa') + expect(token).toMatchObject({ + gmOnly: true, + kind: 'npc', + controller: null, + characterId: 'char1', + statuses: ['stuck', 'squeezed'], + }) + }) + + it('marks the tokens the recipient controls (mine)', () => { + const state = run( + { type: 'connecting' }, + hello(1), + playerToken(2, 'aaa', { mine: true }), + playerToken(3, 'bbb'), + ) + expect(tokensOf(state).filter(token => token.mine).map(token => token.id)).toEqual(['aaa']) + }) + + it('ignores a malformed token frame instead of inventing a token (6.2)', () => { + const state = run( + { type: 'connecting' }, + hello(1), + frame({ t: 'token', n: 2, id: 'aaa', name: 'Rat' }), + ) + expect(tokensOf(state)).toEqual([]) + }) + + it('does not let a token_gone for an unknown id create anything', () => { + const state = run( + { type: 'connecting' }, + hello(1), + frame({ t: 'token_gone', n: 2, id: 'nope' }), + ) + expect(tokensOf(state)).toEqual([]) + }) +})