feat(client): tokens, BitmapText labels, statuses and lists (#71)

- slices/tokens.ts: token upsert, token_gone, hello reset; status names only.
- slices/characters.ts + slices/encountered.ts: own characters, encountered
  list with grey entries; the GM's per-player copies are ignored.
- render/tokenBoard.ts (pure): event -> entered/updated/left patches, so one
  changed token costs one container; seeds from the reducer on mount.
- render/modules/tokens.ts: pooled world-coordinate nodes on the tokens layer,
  one shared unit-circle context per kind, BitmapText from one pre-installed
  BitmapFont assigned only on a name change, stuck/squeezed badges, canvas
  dataset instrumentation for the "only changed entities" criterion.
- panels/lists.ts + render/modules/lists.ts: #lists under #panels, textContent
  only, greyed encountered rows; mounted by a render module so no shared
  bootstrap file changed.
This commit is contained in:
2026-11-21 00:51:16 +01:00
parent 12c2e88f99
commit 429f023c62
13 changed files with 1592 additions and 0 deletions
+135
View File
@@ -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<string, unknown> = { ...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()
}
}
+16
View File
@@ -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<HTMLElement>('#panels')
if (!host) return
return mountListsPanel(host, store)
},
}
+243
View File
@@ -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<string | [string, string]> = [
[' ', '~'],
['\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<string, TokenNode>()
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()
}
},
}
+111
View File
@@ -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<string, TokenView>()
#reset = false
#entered = new Map<string, TokenView>()
#updated = new Map<string, TokenView>()
#left = new Set<string>()
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<string, TokenView> {
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
}
}
+93
View File
@@ -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<string, Record<string, unknown>>
}
function own(record: Record<string, unknown>, key: string): unknown {
return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined
}
export interface CharactersState {
byId: Record<string, CharacterView>
order: string[]
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function propBuckets(value: unknown): Record<string, Record<string, unknown>> {
if (!isRecord(value)) return {}
const buckets: Record<string, Record<string, unknown>> = {}
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<CharactersState> = {
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)
}
+73
View File
@@ -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<string, unknown> {
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<EncounteredState> = {
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 ?? []
}
+152
View File
@@ -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<string, Record<string, unknown>>
/** 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<string, unknown>, key: string): unknown {
return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined
}
export interface TokensState {
byId: Record<string, TokenView>
/** 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<string, unknown> {
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<string, Record<string, unknown>> {
if (!isRecord(value)) return {}
const buckets: Record<string, Record<string, unknown>> = {}
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<TokensState> = {
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
}
+63
View File
@@ -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;
}