feat(client): GM roster, player keys and token panel (#74)

This commit is contained in:
2026-11-21 00:38:52 +01:00
parent e254a0e0f3
commit 12c2e88f99
7 changed files with 1352 additions and 0 deletions
+275
View File
@@ -0,0 +1,275 @@
// T11 (#74, TESTING 10.3): GM roster, player keys and the token panel against the real server
// through the TLS/HTTP2 test nginx. The GM drives the panel; a player page records its own WS
// frames so the test also proves that keys never reach player traffic and `gm_only` tokens never
// reach the player until the GM allows them.
import test from 'node:test'
import assert from 'node:assert/strict'
import { createPlayer, join, namePlayer } 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 {
// non-JSON frames are not state
}
})
}
}
window.WebSocket = RecordingSocket
})
}
const frames = page => page.evaluate(() => window.__wsLog.frames ?? [])
async function lastTokenFrame(page, id) {
return page.evaluate(
tokenId => (window.__wsLog?.frames ?? []).filter(frame => frame.t === 'token' && frame.id === tokenId).at(-1),
id,
)
}
async function keyFromStatus(page, pattern) {
const text = await waitForText(page, '#gm-key-status', pattern)
const match = /^(?:Key for player \d+|New key for player \d+): (.+)$/.exec(text.trim())
assert.ok(match, `no key in status ${JSON.stringify(text)}`)
return match[1]
}
async function waitTokenFrame(page, id, predicate, timeout = 20000) {
const deadline = Date.now() + timeout
let last = null
while (Date.now() < deadline) {
last = await lastTokenFrame(page, id)
if (last && predicate(last)) return last
await new Promise(resolve => setTimeout(resolve, 50))
}
throw new Error(`token ${id} never matched; last was ${JSON.stringify(last)}`)
}
async function waitForHiddenRow(page, tokenId) {
await page.locator(`#gm-token-list li[data-token="${tokenId}"]`).waitFor({ state: 'detached', timeout: 20000 })
}
test('GM roster, keys and token panel drive the real server', { timeout: 240000 }, async () => {
await withStack(async ({ origin, gmKey, server }) => {
const keys = []
const browser = await launchBrowser()
const raw = await openAs(origin, gmKey)
const rawHello = await raw.ws.waitText('hello')
const scene = rawHello.scene?.id ?? (await raw.ws.waitText('walls')).scene
try {
// ---- sign in as GM and see the roster with connected state ------------------------------
const gmView = await newPage(browser)
const gm = gmView.page
await gm.goto(`${origin}/`)
await waitForVisible(gm, '#signin')
await signIn(gm, gmKey)
await waitForVisible(gm, '#gm-panels')
await waitForText(gm, '#gm-roster-list', /GM/)
await waitForText(gm, '#gm-roster-list', /connected/)
assert.equal(await gm.locator('#gm-panels').isVisible(), true)
// ---- key.create through the panel, key visible only in the GM DOM ----------------------
await gm.click('#gm-key-create')
const firstStatus = await waitForText(gm, '#gm-key-status', /Key for player \d+: /)
const firstMatch = /^Key for player (\d+): (.+)$/.exec(firstStatus.trim())
assert.ok(firstMatch, `unexpected key status ${firstStatus}`)
const aliceId = Number(firstMatch[1])
const aliceKey = firstMatch[2]
keys.push(aliceKey)
assert.equal(await gm.textContent(`#gm-key-${aliceId}`), aliceKey)
// A player created outside the panel (an unused key) can be shown by the panel's Show.
const second = await createPlayer(raw.ws)
keys.push(second.key)
await waitForVisible(gm, `#gm-key-show-${second.id}`)
await gm.click(`#gm-key-show-${second.id}`)
await waitForText(gm, `#gm-key-${second.id}`, new RegExp(second.key.replace(/-/g, '\\-')))
// ---- key.replace through the panel ----------------------------------------------------
await gm.click(`#gm-key-replace-${second.id}`)
const replacement = await keyFromStatus(gm, /New key for player/)
keys.push(replacement)
assert.notEqual(replacement, second.key)
assert.equal((await join(origin, second.key)).status, 401, 'the replaced key is dead')
assert.equal((await join(origin, replacement)).status, 303, 'the new key works')
// ---- the cap, then remove frees the slot ----------------------------------------------
// alice + second are 2 of 6; fill the table to the cap with real key.create acks.
for (let i = 0; i < 4; i += 1) {
const extra = await createPlayer(raw.ws)
keys.push(extra.key)
}
await gm.click('#gm-key-create')
await waitForText(gm, '#gm-key-status', /full/i)
await waitForVisible(gm, `#gm-player-remove-${second.id}`)
await gm.click(`#gm-player-remove-${second.id}`)
await waitForText(gm, '#gm-key-status', /removed/i)
assert.equal(await gm.locator(`#gm-player-remove-${second.id}`).count(), 0)
await gm.click('#gm-key-create')
const freed = await keyFromStatus(gm, /Key for player \d+: /)
keys.push(freed)
// ---- a named player page records its own wire for the token and key assertions ---------
await namePlayer(origin, aliceKey, 'Alice')
const playerView = await newPage(browser)
const player = playerView.page
await recordSockets(player)
await player.goto(`${origin}/`)
await waitForVisible(player, '#signin')
await signIn(player, aliceKey)
await waitForVisible(player, '#hud')
await waitForText(player, '#me', /^Alice$/)
await waitForText(gm, '#gm-roster-list', /Alice/)
await waitForText(gm, '#gm-roster-list', /connected/)
// A scout gives the player a real line of sight, so a GM-controlled token can be shown and
// hidden by `gm_only` (a token the player controls is always visible, by 3.1).
const scout = await raw.ws.request({
t: 'token.create',
scene,
kind: 'pc',
pos: [400, 400],
descriptive_name: 'Scout',
actual_name: 'Scout',
controller: aliceId,
flags: { vision: true },
})
assert.equal(scout.ok, true)
await waitTokenFrame(player, scout.id, frame => frame.mine === true)
// ---- token.create through the panel ---------------------------------------------------
await gm.fill('#token-name', 'Rat')
await gm.fill('#token-actual', 'Giant Rat')
await gm.fill('#token-x', '460')
await gm.fill('#token-y', '450')
await gm.fill('#token-radius', '5')
await gm.click('#token-create-submit')
const tokenRow = gm.locator('#gm-token-list li', { hasText: 'Rat' }).first()
await tokenRow.waitFor({ state: 'visible', timeout: 20000 })
const tokenId = await tokenRow.getAttribute('data-token')
assert.ok(tokenId, 'new token has no id in the panel')
await waitTokenFrame(player, tokenId, frame => frame.mine === false)
// ---- controller: the player becomes the token's controller ----------------------------
await gm.click(`#gm-token-select-${tokenId}`)
await waitForVisible(gm, '#gm-token-editor')
await gm.selectOption('#token-edit-controller', String(aliceId))
await gm.click('#token-save')
await waitTokenFrame(player, tokenId, frame => frame.mine === true)
assert.equal((await lastTokenFrame(player, tokenId)).name, 'Rat')
// ---- edit: a rename reaches the player ------------------------------------------------
await gm.fill('#token-edit-name', 'Big Rat')
await gm.click('#token-save')
await waitTokenFrame(player, tokenId, frame => frame.name === 'Big Rat')
await waitForText(gm, '#gm-token-list', /Big Rat/)
// ---- gm_only hides the token from the player, clearing it reveals it again -------------
// A controlled token is always visible (3.1), so hand it back to the GM while it is hidden.
await gm.check('#token-edit-gm-only')
await gm.click('#token-save')
await waitForText(gm, '#gm-token-list', /gm_only/)
await gm.selectOption('#token-edit-controller', '')
await gm.click('#token-save')
await waitForText(gm, '#gm-token-list', /controller GM/)
await player.waitForFunction(
tokenId => {
const gone = (window.__wsLog?.frames ?? []).findLast(frame => frame.t === 'token_gone' && frame.id === tokenId)
if (!gone) return false
const last = (window.__wsLog?.frames ?? []).filter(frame => frame.t === 'token' && frame.id === tokenId).at(-1)
return !last || (window.__wsLog.frames.indexOf(last) < window.__wsLog.frames.indexOf(gone))
},
tokenId,
{ timeout: 20000 },
)
await gm.uncheck('#token-edit-gm-only')
await gm.click('#token-save')
await waitForText(gm, '#gm-token-list', /visible/)
await player.waitForFunction(
tokenId => {
const log = window.__wsLog?.frames ?? []
const last = log.filter(frame => frame.t === 'token' && frame.id === tokenId).at(-1)
const gone = log.findLast(frame => frame.t === 'token_gone' && frame.id === tokenId)
return Boolean(last) && (!gone || log.indexOf(last) > log.indexOf(gone))
},
tokenId,
{ timeout: 20000 },
)
// ---- status: GM-sourced stuck reaches the viewer, then clears --------------------------
await gm.click('#token-status-stuck')
await waitTokenFrame(player, tokenId, frame => (frame.statuses ?? []).some(entry => entry.status === 'stuck'))
await waitForText(gm, '#token-status', /stuck \(GM\)/i)
await gm.click('#token-status-clear-stuck')
await waitTokenFrame(
player,
tokenId,
frame => !(frame.statuses ?? []).some(entry => entry.status === 'stuck'),
)
// ---- resize: the server pushes the grown token away from a blocking wall ---------------
const wall = await raw.ws.request({
t: 'wall.add',
scene,
a: [500, 400],
b: [500, 500],
preset: 'wall',
})
assert.equal(wall.ok, true)
await gm.fill('#token-resize-radius', '60')
await gm.click('#token-resize')
await waitTokenFrame(player, tokenId, frame => Math.round(frame.radius) === 60)
const pushed = await lastTokenFrame(player, tokenId)
assert.ok(pushed.pos[0] < 460, `expected the grow push left of 460, got ${JSON.stringify(pushed.pos)}`)
await waitForText(gm, '#gm-token-list', /r60/)
// ---- remove: the panel drives token.remove and the player is told ----------------------
await gm.click('#token-remove')
await waitForHiddenRow(gm, tokenId)
await player.waitForFunction(
tokenId => (window.__wsLog?.frames ?? []).some(frame => frame.t === 'token_gone' && frame.id === tokenId),
tokenId,
{ timeout: 20000 },
)
// ---- keys never reach the player: no frame field, no DOM text, no server log ----------
const playerFrames = await frames(player)
assert.equal(
playerFrames.some(frame => frame && Object.prototype.hasOwnProperty.call(frame, 'key')),
false,
'a `key` field reached the player wire',
)
const wire = JSON.stringify(playerFrames)
const playerHtml = await player.content()
const log = server.log()
for (const key of keys) {
assert.equal(wire.includes(key), false, 'a player key reached the player wire')
assert.equal(playerHtml.includes(key), false, 'a player key reached the player DOM')
assert.equal(log.includes(key), false, 'a player key reached the server log')
}
assert.equal(await player.locator('#gm-panels').isVisible(), false)
} finally {
raw.ws.close()
await browser.close()
}
})
})
+12
View File
@@ -5,6 +5,7 @@ import './style.css'
import { ProtocolClient } from './ws.ts'
import { Store } from './store.ts'
import { mountShell } from './shell.ts'
import { mountAdminPanel } from './panels/admin.ts'
import type { Stage } from './render/stage.ts'
import { createStage } from './render/stage.ts'
import type { RootState } from './reducer.ts'
@@ -40,6 +41,16 @@ const stageHost = document.querySelector<HTMLElement>('#stage')
if (!stageHost) throw new Error('#stage is missing')
const stageRoot: HTMLElement = stageHost
// GM panels (T11, #74). A player never sees this section: the panel hides and clears itself unless
// the live session is the GM. Its send callback is the same protocol client as every other intent.
const panelsHost = document.querySelector<HTMLElement>('#panels')
if (!panelsHost) throw new Error('#panels is missing')
const adminPanel = mountAdminPanel(panelsHost, {
send: (t, fields) =>
client ? client.send(t, fields) : Promise.reject(new Error('not connected')),
select: token => store.dispatch({ type: 'admin-select', token }),
})
async function signIn(key: string): Promise<void> {
shell.setBusy(true)
let accepted = false
@@ -133,6 +144,7 @@ function syncStage(state: RootState): void {
store.subscribe(state => {
shell.render(state)
syncStage(state)
adminPanel.render(state)
})
// Story 7: the badge distinguishes "no network at all" from "socket is reconnecting". The socket
+628
View File
@@ -0,0 +1,628 @@
// GM panels (T11, #74): roster + connected state, player keys, and the token panel. Plain DOM and
// `textContent` only (DESIGN 7.1 layer 6, spec #63 decision 15). Mounted under the shell's existing
// `#panels` host; the sign-in flow and HUD are untouched.
//
// SECRETS: a player key lives only in this module's `keys` map and in a `#gm-key-*` <code> element
// inside the GM-only `#gm-panels`. It is never dispatched into the reducer, never sent over the
// socket, never written to the console, and the whole map is dropped the moment the GM session
// leaves the table. This is the "keys exist only in GM DOM" acceptance criterion for #74.
//
// TOKEN SELECTION: this panel dispatches `{type:'admin-select', token}`; the id lives in the
// `admin` slice (`src/slices/admin.ts`), so #71's token renderer and #72's drag module can read the
// same selection later without importing this file.
import type { RootState } from '../reducer.ts'
import type { AckFrame, RosterEntry } from '../protocol.ts'
import { rosterOf } from '../reducer.ts'
import type { AdminToken } from '../slices/admin.ts'
import { adminTokens, selectedTokenId } from '../slices/admin.ts'
export interface AdminPanelHandlers {
send(t: string, fields?: Record<string, unknown>): Promise<AckFrame>
select(token: string | null): void
}
export interface AdminPanel {
render(state: RootState): void
destroy(): void
}
const CODE_TEXT: Record<string, string> = {
'cap-reached': 'The table is full (6 players). Remove a player first.',
'not-found': 'That player or token no longer exists.',
'not-allowed': 'The server refused that action.',
invalid: 'That value is not valid.',
'in-use': 'That is still in use.',
}
function describeCode(code: string | undefined): string {
if (code === undefined) return 'The server refused that action.'
return CODE_TEXT[code] ?? `The server refused that action (${code}).`
}
function element<K extends keyof HTMLElementTagNameMap>(
tag: K,
id?: string,
text?: string,
): HTMLElementTagNameMap[K] {
const node = document.createElement(tag)
if (id !== undefined) node.id = id
if (text !== undefined) node.textContent = text
return node
}
function field<K extends keyof HTMLElementTagNameMap>(tag: K, id: string, text?: string) {
const node = element(tag, id, text)
const label = element('label', undefined, text ?? '')
label.htmlFor = id
return { node, label }
}
function playerLabel(entry: RosterEntry): string {
return entry.name ?? `(unnamed ${entry.id})`
}
export function mountAdminPanel(host: HTMLElement, handlers: AdminPanelHandlers): AdminPanel {
const root = element('section', 'gm-panels')
root.hidden = true
const heading = element('h2', undefined, 'GM table')
root.append(heading)
// ---- roster and keys -----------------------------------------------------------------------
const rosterSection = element('section', 'gm-roster')
const rosterTitle = element('h3', undefined, 'Roster')
const rosterList = element('ul', 'gm-roster-list')
const keyCreate = element('button', 'gm-key-create', 'Create player key')
keyCreate.type = 'button'
const keyStatus = element('p', 'gm-key-status')
keyStatus.hidden = true
keyStatus.setAttribute('role', 'status')
rosterSection.append(rosterTitle, rosterList, keyCreate, keyStatus)
// ---- token panel ---------------------------------------------------------------------------
const tokenSection = element('section', 'gm-tokens')
const tokenTitle = element('h3', undefined, 'Tokens')
const createForm = element('form', 'gm-token-create')
const kindInput = field('input', 'token-kind', 'Kind')
kindInput.node.value = 'npc'
kindInput.node.type = 'text'
const nameInput = field('input', 'token-name', 'Descriptive name')
nameInput.node.type = 'text'
const actualInput = field('input', 'token-actual', 'Actual name')
actualInput.node.type = 'text'
const xInput = field('input', 'token-x', 'X')
xInput.node.type = 'number'
xInput.node.value = '400'
const yInput = field('input', 'token-y', 'Y')
yInput.node.type = 'number'
yInput.node.value = '400'
const radiusInput = field('input', 'token-radius', 'Radius (blank = scene default)')
radiusInput.node.type = 'number'
radiusInput.node.min = '0.1'
radiusInput.node.step = 'any'
const createGmOnly = field('input', 'token-gm-only', 'GM only')
createGmOnly.node.type = 'checkbox'
const createController = field('select', 'token-controller', 'Controller')
const createControllerLabel = createController.label
const createSubmit = element('button', 'token-create-submit', 'Create token')
createSubmit.type = 'submit'
createForm.append(
kindInput.label,
kindInput.node,
nameInput.label,
nameInput.node,
actualInput.label,
actualInput.node,
xInput.label,
xInput.node,
yInput.label,
yInput.node,
radiusInput.label,
radiusInput.node,
createGmOnly.label,
createGmOnly.node,
createControllerLabel,
createController.node,
createSubmit,
)
const tokenList = element('ul', 'gm-token-list')
const editor = element('section', 'gm-token-editor')
editor.hidden = true
const editorTitle = element('h4', 'gm-token-editor-title', 'No token selected')
const editName = field('input', 'token-edit-name', 'Descriptive name')
editName.node.type = 'text'
const editActual = field('input', 'token-edit-actual', 'Actual name')
editActual.node.type = 'text'
const editKind = field('input', 'token-edit-kind', 'Kind')
editKind.node.type = 'text'
const editGmOnly = field('input', 'token-edit-gm-only', 'GM only')
editGmOnly.node.type = 'checkbox'
const editController = field('select', 'token-edit-controller', 'Controller')
const save = element('button', 'token-save', 'Save token')
save.type = 'button'
const remove = element('button', 'token-remove', 'Remove token')
remove.type = 'button'
const statusTitle = element('p', 'token-status', 'Statuses: none')
const setStuck = element('button', 'token-status-stuck', 'Add stuck')
setStuck.type = 'button'
const setSqueezed = element('button', 'token-status-squeezed', 'Add squeezed')
setSqueezed.type = 'button'
const clearStuck = element('button', 'token-status-clear-stuck', 'Clear stuck (GM)')
clearStuck.type = 'button'
const clearSqueezed = element('button', 'token-status-clear-squeezed', 'Clear squeezed (GM)')
clearSqueezed.type = 'button'
const clearWalls = element('button', 'token-status-clear-walls', 'Clear stuck (walls)')
clearWalls.type = 'button'
const resizeRadius = field('input', 'token-resize-radius', 'New radius')
resizeRadius.node.type = 'number'
resizeRadius.node.min = '0.1'
resizeRadius.node.step = 'any'
const resize = element('button', 'token-resize', 'Resize')
resize.type = 'button'
const tokenError = element('p', 'gm-token-error')
tokenError.hidden = true
tokenError.setAttribute('role', 'alert')
editor.append(
editorTitle,
editName.label,
editName.node,
editActual.label,
editActual.node,
editKind.label,
editKind.node,
editGmOnly.label,
editGmOnly.node,
editController.label,
editController.node,
save,
remove,
statusTitle,
setStuck,
setSqueezed,
clearStuck,
clearSqueezed,
clearWalls,
resizeRadius.label,
resizeRadius.node,
resize,
)
tokenSection.append(tokenTitle, createForm, tokenList, editor, tokenError)
root.append(rosterSection, tokenSection)
host.append(root)
// Secrets and local UI state. Never dispatched, never logged.
const keys = new Map<number, string>()
const revealed = new Set<number>()
let keyVersion = 0
let active = false
let rosterSig = ''
let tokenSig = ''
let populatedFor: string | null = null
let current: RootState | null = null
function showSecret(entry: RosterEntry): string {
if (!revealed.has(entry.id)) return ''
return keys.get(entry.id) ?? ''
}
function renderControllerOptions(select: HTMLSelectElement, players: RosterEntry[], value: string) {
const signature = players.map(p => `${p.id}:${p.role}`).join(',')
if (select.dataset['options'] === signature) {
select.value = value
return
}
const gm = element('option', undefined, 'GM (no controller)')
gm.value = ''
select.replaceChildren(gm)
for (const entry of players) {
if (entry.role === 'gm') continue
const option = element('option', undefined, playerLabel(entry))
option.value = String(entry.id)
select.append(option)
}
select.dataset['options'] = signature
select.value = value
}
function renderRoster(players: RosterEntry[]): void {
rosterList.replaceChildren(
...players.map(entry => {
const item = element('li')
item.dataset['player'] = String(entry.id)
const name = element('span', 'gm-roster-name', playerLabel(entry))
const state = element('span', 'gm-roster-state', entry.connected ? 'connected' : 'offline')
item.append(name, state)
if (entry.role !== 'gm') {
const keyCode = element('code', `gm-key-${entry.id}`)
keyCode.className = 'gm-key'
keyCode.textContent = showSecret(entry)
keyCode.hidden = keyCode.textContent === ''
const show = element('button', `gm-key-show-${entry.id}`, 'Show')
show.type = 'button'
show.addEventListener('click', () => {
revealed.add(entry.id)
void showKey(entry.id)
})
const hide = element('button', `gm-key-hide-${entry.id}`, 'Hide')
hide.type = 'button'
hide.addEventListener('click', () => {
revealed.delete(entry.id)
refresh()
})
const replace = element('button', `gm-key-replace-${entry.id}`, 'Replace')
replace.type = 'button'
replace.addEventListener('click', () => {
void replaceKey(entry.id)
})
const cut = element('button', `gm-player-remove-${entry.id}`, 'Remove')
cut.type = 'button'
cut.addEventListener('click', () => {
void removePlayer(entry.id)
})
item.append(keyCode, show, hide, replace, cut)
}
return item
}),
)
}
function tokenMeta(token: AdminToken, players: RosterEntry[]): string {
const controller =
token.controller === null
? 'GM'
: (players.find(p => p.id === token.controller)?.name ?? `#${token.controller}`)
const statuses = token.statuses
.map(entry => (entry.source ? `${entry.status}/${entry.source}` : entry.status))
.join(', ')
return [
token.kind ?? '?',
`controller ${controller}`,
token.gmOnly ? 'gm_only' : 'visible',
`r${Math.round(token.radius)}`,
statuses === '' ? 'no status' : statuses,
].join(' · ')
}
function renderTokenList(tokens: AdminToken[], players: RosterEntry[], selected: string | null) {
tokenList.replaceChildren(
...tokens.map(token => {
const item = element('li')
item.dataset['token'] = token.id
if (token.id === selected) item.dataset['selected'] = 'true'
const name = element('span', 'gm-token-name', token.name)
const meta = element('span', 'gm-token-meta', tokenMeta(token, players))
const pick = element('button', `gm-token-select-${token.id}`, 'Select')
pick.type = 'button'
pick.addEventListener('click', () => handlers.select(token.id))
item.append(name, meta, pick)
return item
}),
)
}
function populateEditor(token: AdminToken | null, players: RosterEntry[]): void {
if (token === null) {
editor.hidden = true
editorTitle.textContent = 'No token selected'
populatedFor = null
return
}
editor.hidden = false
if (populatedFor === token.id) {
renderControllerOptions(
editController.node,
players,
token.controller === null ? '' : String(token.controller),
)
return
}
populatedFor = token.id
editorTitle.textContent = `${token.name} (${token.id})`
editName.node.value = token.descriptiveName ?? token.name
editActual.node.value = token.actualName ?? token.name
editKind.node.value = token.kind ?? ''
editGmOnly.node.checked = token.gmOnly
renderControllerOptions(
editController.node,
players,
token.controller === null ? '' : String(token.controller),
)
}
function refresh(): void {
const state = current
if (!state || !active) return
const players = rosterOf(state)
const tokens = adminTokens(state)
const selected = selectedTokenId(state)
const nextRosterSig = JSON.stringify(players) + JSON.stringify([...revealed]) + keyVersion
if (nextRosterSig !== rosterSig) {
rosterSig = nextRosterSig
renderRoster(players)
}
const token = tokens.find(entry => entry.id === selected) ?? null
const nextTokenSig = JSON.stringify(tokens) + selected
if (nextTokenSig !== tokenSig) {
tokenSig = nextTokenSig
renderTokenList(tokens, players, selected)
populateEditor(token, players)
if (token) {
statusTitle.textContent =
token.statuses.length === 0
? 'Statuses: none'
: `Statuses: ${token.statuses
.map(entry => (entry.source ? `${entry.status} (${entry.source})` : entry.status))
.join(', ')}`
resizeRadius.node.placeholder = String(Math.round(token.radius))
}
}
renderControllerOptions(createController.node, players, createController.node.value || '')
}
function setError(text: string | null): void {
if (text === null) {
tokenError.textContent = ''
tokenError.hidden = true
} else {
tokenError.textContent = text
tokenError.hidden = false
}
}
function setKeyStatus(text: string): void {
keyStatus.textContent = text
keyStatus.hidden = text === ''
}
function currentSelection(): string | null {
return current ? selectedTokenId(current) : null
}
async function request(t: string, fields: Record<string, unknown> = {}): Promise<AckFrame | null> {
try {
const ack = await handlers.send(t, fields)
if (!ack.ok) setError(describeCode(ack.code))
return ack
} catch {
setError('Could not reach the server.')
return null
}
}
async function showKey(id: number): Promise<void> {
setError(null)
setKeyStatus('')
const ack = await request('key.show', { id })
if (ack?.ok && typeof ack.key === 'string') {
keys.set(id, ack.key)
revealed.add(id)
keyVersion += 1
refresh()
} else if (ack) {
setKeyStatus(describeCode(ack.code))
}
}
async function replaceKey(id: number): Promise<void> {
setError(null)
setKeyStatus('')
const ack = await request('key.replace', { id })
if (ack?.ok && typeof ack.key === 'string') {
keys.set(id, ack.key)
revealed.add(id)
keyVersion += 1
setKeyStatus(`New key for player ${id}: ${ack.key}`)
refresh()
} else if (ack) {
setKeyStatus(describeCode(ack.code))
}
}
async function removePlayer(id: number): Promise<void> {
setError(null)
setKeyStatus('')
const ack = await request('player.remove', { id })
if (ack?.ok) {
keys.delete(id)
revealed.delete(id)
keyVersion += 1
setKeyStatus(`Player ${id} removed; their key and session are gone.`)
refresh()
} else if (ack) {
setKeyStatus(describeCode(ack.code))
}
}
async function createKey(): Promise<void> {
setError(null)
setKeyStatus('')
const ack = await request('key.create')
if (ack?.ok) {
const created = ack as { id?: unknown; key?: unknown }
if (typeof created.id === 'number' && typeof created.key === 'string') {
keys.set(created.id, created.key)
revealed.add(created.id)
keyVersion += 1
setKeyStatus(`Key for player ${created.id}: ${created.key}`)
}
refresh()
} else if (ack) {
setKeyStatus(describeCode(ack.code))
}
}
async function createToken(): Promise<void> {
setError(null)
const kind = kindInput.node.value.trim()
const name = nameInput.node.value.trim()
const actual = actualInput.node.value.trim()
const x = Number(xInput.node.value)
const y = Number(yInput.node.value)
if (kind === '' || name === '' || actual === '' || !Number.isFinite(x) || !Number.isFinite(y)) {
setError('Kind, both names and a numeric position are required.')
return
}
const scene = current?.session.scene?.id
if (scene === undefined) {
setError('No scene yet.')
return
}
const rawRadius = radiusInput.node.value.trim()
const radius = rawRadius === '' ? null : Number(rawRadius)
if (radius !== null && (!Number.isFinite(radius) || radius <= 0)) {
setError('Radius must be a positive number or blank.')
return
}
const controllerValue = createController.node.value
const controller = controllerValue === '' ? null : Number(controllerValue)
const ack = await request('token.create', {
scene,
kind,
pos: [x, y],
descriptive_name: name,
actual_name: actual,
radius,
gm_only: createGmOnly.node.checked,
controller,
})
if (ack?.ok) {
const created = ack as { id?: unknown }
if (typeof created.id === 'string') handlers.select(created.id)
}
}
async function saveToken(): Promise<void> {
const selected = currentSelection()
if (selected === null) return
setError(null)
const name = editName.node.value.trim()
const actual = editActual.node.value.trim()
const kind = editKind.node.value.trim()
if (name === '' || actual === '' || kind === '') {
setError('Kind and both names are required.')
return
}
const controllerValue = editController.node.value
await request('token.update', {
id: selected,
kind,
descriptive_name: name,
actual_name: actual,
gm_only: editGmOnly.node.checked,
controller: controllerValue === '' ? null : Number(controllerValue),
})
}
async function removeToken(): Promise<void> {
const selected = currentSelection()
if (selected === null) return
setError(null)
const ack = await request('token.remove', { id: selected })
if (ack?.ok) handlers.select(null)
}
async function setStatus(status: 'stuck' | 'squeezed'): Promise<void> {
const selected = currentSelection()
if (selected === null) return
setError(null)
await request('status.set', { id: selected, status })
}
async function clearStatus(status: 'stuck' | 'squeezed', source: 'GM' | 'walls'): Promise<void> {
const selected = currentSelection()
if (selected === null) return
setError(null)
await request('status.clear', { id: selected, status, source })
}
async function resizeToken(): Promise<void> {
const selected = currentSelection()
if (selected === null) return
setError(null)
const raw = resizeRadius.node.value.trim()
const radius = raw === '' ? null : Number(raw)
if (radius !== null && (!Number.isFinite(radius) || radius <= 0)) {
setError('Radius must be a positive number or blank for the scene default.')
return
}
await request('token.resize', { id: selected, radius })
}
keyCreate.addEventListener('click', () => {
void createKey()
})
createForm.addEventListener('submit', event => {
event.preventDefault()
void createToken()
})
save.addEventListener('click', () => {
void saveToken()
})
remove.addEventListener('click', () => {
void removeToken()
})
setStuck.addEventListener('click', () => {
void setStatus('stuck')
})
setSqueezed.addEventListener('click', () => {
void setStatus('squeezed')
})
clearStuck.addEventListener('click', () => {
void clearStatus('stuck', 'GM')
})
clearSqueezed.addEventListener('click', () => {
void clearStatus('squeezed', 'GM')
})
clearWalls.addEventListener('click', () => {
void clearStatus('stuck', 'walls')
})
resize.addEventListener('click', () => {
void resizeToken()
})
function render(state: RootState): void {
current = state
const live = state.connection.phase === 'live' || state.connection.phase === 'reconnecting'
const gm = state.session.role === 'gm' && state.session.me?.name != null
const nextActive = live && gm
if (!nextActive) {
// Leaving the GM view erases every secret and every server-derived row from the DOM.
active = false
keys.clear()
revealed.clear()
rosterSig = ''
tokenSig = ''
populatedFor = null
root.hidden = true
rosterList.replaceChildren()
tokenList.replaceChildren()
editor.hidden = true
setKeyStatus('')
setError(null)
return
}
if (!active) {
active = true
rosterSig = ''
tokenSig = ''
}
root.hidden = false
refresh()
}
return {
render,
destroy() {
keys.clear()
revealed.clear()
root.remove()
},
}
}
+2
View File
@@ -66,6 +66,8 @@ export type ReducerEvent =
| { type: 'signin-failed'; message: string }
| { type: 'name-failed'; message: string }
| { type: 'signed-out' }
/** GM token panel selection (#74); slices own the state, the core just carries the event. */
| { type: 'admin-select'; token: string | null }
/**
* A domain slice. `init()` returns the empty value; `reduce` mutates the draft it is handed (the
+151
View File
@@ -0,0 +1,151 @@
// GM admin slice (T11, #74): the GM-only token records the token panel edits, plus the one piece of
// selection state the panel owns. Append-only registration: adding this file was enough; the
// reducer's glob picked it up and `hello` resets it with every other slice.
//
// TOKEN SELECTION FOR #71/#72: the selected token id lives here, not in the panel, so the token
// renderer (#71) and the drag module (#72) can read it without importing the panel. Read it with
// `selectedTokenId(state)` and change it only by dispatching
// `{ type: 'admin-select', token: <id> | null }`. This slice never writes selection from a `token`
// frame; a `token_gone` for the selected id clears it.
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
import type { ServerFrame } from '../protocol.ts'
export interface AdminStatus {
status: string
/** GM frames carry the source (`walls`|`GM`); a player frame cannot reach this panel. */
source?: string
}
/** The GM's view of one token frame (DESIGN 6.1 `token`, GM columns). */
export interface AdminToken {
id: string
scene: number
name: string
pos: [number, number]
radius: number
/** GM-only fields; optional so a malformed frame is ignored rather than guessed. */
kind: string | null
controller: number | null
gmOnly: boolean
statuses: AdminStatus[]
descriptiveName: string | null
actualName: string | null
visionRadius: number | null
radiusOwn: number | null
}
export interface AdminState {
tokens: AdminToken[]
/** Id of the token selected in the GM panel; `null` when nothing is selected. */
selectedToken: string | null
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function isVec2(value: unknown): value is [number, number] {
return (
Array.isArray(value) &&
value.length === 2 &&
typeof value[0] === 'number' &&
Number.isFinite(value[0]) &&
typeof value[1] === 'number' &&
Number.isFinite(value[1])
)
}
function finiteOrNull(value: unknown): number | null {
return typeof value === 'number' && Number.isFinite(value) ? value : null
}
function parseStatuses(value: unknown): AdminStatus[] {
if (!Array.isArray(value)) return []
const out: AdminStatus[] = []
for (const entry of value) {
if (!isRecord(entry) || typeof entry['status'] !== 'string') continue
const source = entry['source']
out.push(
typeof source === 'string'
? { status: entry['status'], source }
: { status: entry['status'] },
)
}
return out
}
/** Read one GM `token` frame; `null` for a shape the panel cannot edit. */
export function tokenFromFrame(frame: ServerFrame): AdminToken | null {
const id = frame['id']
const scene = frame['scene']
const name = frame['name']
const pos = frame['pos']
const radius = frame['radius']
if (
typeof id !== 'string' ||
id.length === 0 ||
typeof scene !== 'number' ||
!Number.isInteger(scene) ||
typeof name !== 'string' ||
!isVec2(pos) ||
typeof radius !== 'number' ||
!Number.isFinite(radius)
) {
return null
}
return {
id,
scene,
name,
pos: [pos[0], pos[1]],
radius,
kind: typeof frame['kind'] === 'string' ? frame['kind'] : null,
controller: finiteOrNull(frame['controller']),
gmOnly: frame['gm_only'] === true,
statuses: parseStatuses(frame['statuses']),
descriptiveName:
typeof frame['descriptive_name'] === 'string' ? frame['descriptive_name'] : null,
actualName: typeof frame['actual_name'] === 'string' ? frame['actual_name'] : null,
visionRadius: finiteOrNull(frame['vision_radius']),
radiusOwn: finiteOrNull(frame['radius_own']),
}
}
function upsert(state: AdminState, token: AdminToken): void {
const index = state.tokens.findIndex(entry => entry.id === token.id)
if (index >= 0) state.tokens[index] = token
else state.tokens.push(token)
}
export const slice: Slice<AdminState> = {
name: 'admin',
init: () => ({ tokens: [], selectedToken: null }),
reduce(state: AdminState, event: ReducerEvent, _root: RootState): void {
if (event.type === 'admin-select') {
state.selectedToken = event.token
return
}
if (event.type !== 'frame') return
const frame = event.frame
if (frame.t === 'token') {
const token = tokenFromFrame(frame)
if (token) upsert(state, token)
} else if (frame.t === 'token_gone') {
const id = frame['id']
if (typeof id !== 'string') return
state.tokens = state.tokens.filter(token => token.id !== id)
if (state.selectedToken === id) state.selectedToken = null
}
},
}
/** The selected token id, owned by this slice for #71/#72 to read. */
export function selectedTokenId(state: RootState): string | null {
return (state.slices['admin'] as AdminState | undefined)?.selectedToken ?? null
}
/** The GM token records, in the order the server sent them. */
export function adminTokens(state: RootState): AdminToken[] {
return (state.slices['admin'] as AdminState | undefined)?.tokens ?? []
}
+130
View File
@@ -141,3 +141,133 @@ body {
#badge[data-state='offline'] {
color: #ff7b72;
}
/* GM panels (T11, #74): a right-hand column over the canvas. The root is hidden for players and
for every phase outside the table; secrets live only inside it. */
#panels {
position: absolute;
top: 40px;
right: 8px;
bottom: 8px;
width: min(330px, 44vw);
overflow: auto;
pointer-events: none;
}
#gm-panels {
display: flex;
flex-direction: column;
gap: 10px;
padding: 10px;
border-radius: 8px;
background: rgb(10 10 12 / 88%);
border: 1px solid #333;
pointer-events: auto;
font: 12px/1.4 ui-monospace, monospace;
}
#gm-panels h2,
#gm-panels h3,
#gm-panels h4 {
margin: 0;
font-weight: 600;
}
#gm-panels h2 {
font-size: 14px;
}
#gm-panels h3 {
font-size: 12px;
opacity: 0.8;
}
#gm-roster-list,
#gm-token-list {
display: flex;
flex-direction: column;
gap: 4px;
margin: 6px 0;
padding: 0;
list-style: none;
}
#gm-roster-list li,
#gm-token-list li {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px;
padding: 4px;
border-radius: 4px;
background: rgb(255 255 255 / 4%);
}
#gm-token-list li[data-selected='true'] {
outline: 1px solid #7ee787;
}
#gm-roster-state {
opacity: 0.6;
}
.gm-key {
flex-basis: 100%;
color: #e3b341;
word-break: break-all;
}
#gm-panels button {
font: inherit;
padding: 2px 6px;
border-radius: 4px;
border: 1px solid #666;
background: #222;
color: inherit;
}
#gm-panels input,
#gm-panels select {
font: inherit;
padding: 3px 5px;
border-radius: 4px;
border: 1px solid #555;
background: #111;
color: inherit;
width: 100%;
box-sizing: border-box;
}
#gm-panels input[type='checkbox'] {
width: auto;
}
#gm-token-create,
#gm-token-editor {
display: flex;
flex-direction: column;
gap: 4px;
margin: 6px 0;
}
#gm-token-create label,
#gm-token-editor label {
opacity: 0.7;
}
#gm-key-status,
#gm-token-error {
margin: 4px 0 0;
word-break: break-word;
color: #e3b341;
}
#gm-token-error {
color: #ff8a8a;
}
#gm-token-meta {
flex-basis: 100%;
opacity: 0.7;
word-break: break-word;
}
+154
View File
@@ -0,0 +1,154 @@
// T11 (#74) reducer seam: the GM admin slice consumes `token`/`token_gone` frames and owns the
// token selection that #71/#72 will read. Pure, no DOM and no socket.
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 type { AdminToken } from '../src/slices/admin.ts'
import { adminTokens, selectedTokenId } from '../src/slices/admin.ts'
const frame = (body: Record<string, unknown>): 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: 'gm',
me: { id: 1, name: 'GM' },
scene: {
id: 1,
name: 'Cellar',
w: 4096,
h: 4096,
tile_size: 32,
cell: 32,
grid_size: 64,
vision_radius_default: 320,
token_radius_default: 20,
art_version: 1,
},
})
const gmToken = (id: string, patch: Record<string, unknown> = {}): ReducerEvent =>
frame({
t: 'token',
n: 3,
id,
scene: 1,
name: 'Rat',
pos: [400, 400],
radius: 20,
mine: false,
statuses: [{ status: 'stuck', source: 'walls' }],
props: {},
kind: 'npc',
controller: null,
gm_only: false,
flags: {},
vision_radius: null,
radius_own: null,
character_id: null,
descriptive_name: 'Rat',
actual_name: 'Giant Rat',
reveal_all: false,
revealed: [],
...patch,
})
const run = (...events: ReducerEvent[]): RootState =>
events.reduce((state, event) => reduce(state, event), initialState())
const tokenOf = (state: RootState, id: string): AdminToken | undefined =>
adminTokens(state).find(token => token.id === id)
describe('GM token records', () => {
it('upserts the GM fields of a `token` frame and replaces on a later frame', () => {
const first = run({ type: 'connecting' }, hello(1), gmToken('abc'))
expect(adminTokens(first)).toHaveLength(1)
expect(tokenOf(first, 'abc')).toMatchObject({
id: 'abc',
scene: 1,
name: 'Rat',
pos: [400, 400],
radius: 20,
kind: 'npc',
controller: null,
gmOnly: false,
statuses: [{ status: 'stuck', source: 'walls' }],
descriptiveName: 'Rat',
actualName: 'Giant Rat',
})
const changed = reduce(
first,
gmToken('abc', {
name: 'Big Rat',
pos: [420, 400],
radius: 30,
gm_only: true,
controller: 2,
statuses: [{ status: 'squeezed', source: 'GM' }],
}),
)
expect(adminTokens(changed)).toHaveLength(1)
expect(tokenOf(changed, 'abc')).toMatchObject({
name: 'Big Rat',
pos: [420, 400],
radius: 30,
gmOnly: true,
controller: 2,
statuses: [{ status: 'squeezed', source: 'GM' }],
})
})
it('ignores a malformed token frame instead of inventing a row', () => {
const state = run({ type: 'connecting' }, hello(1), frame({ t: 'token', n: 2, id: 7 }))
expect(adminTokens(state)).toEqual([])
})
it('removes the row on token_gone and clears a selection that pointed at it', () => {
const selected = run(
{ type: 'connecting' },
hello(1),
gmToken('abc'),
{ type: 'admin-select', token: 'abc' },
frame({ t: 'token_gone', n: 4, id: 'abc' }),
)
expect(adminTokens(selected)).toEqual([])
expect(selectedTokenId(selected)).toBeNull()
})
it('hello resets the token list and the selection with every other slice', () => {
const live = run(
{ type: 'connecting' },
hello(1),
gmToken('abc'),
{ type: 'admin-select', token: 'abc' },
)
expect(selectedTokenId(live)).toBe('abc')
const reset = reduce(live, hello(9))
expect(adminTokens(reset)).toEqual([])
expect(selectedTokenId(reset)).toBeNull()
})
})
describe('token selection (#71/#72 hook)', () => {
it('is slice state, changed only by the admin-select event', () => {
const state = run(
{ type: 'connecting' },
hello(1),
gmToken('abc'),
gmToken('def'),
{ type: 'admin-select', token: 'def' },
)
expect(selectedTokenId(state)).toBe('def')
expect(adminTokens(state).map(token => token.id)).toEqual(['abc', 'def'])
expect(selectedTokenId(reduce(state, { type: 'admin-select', token: null }))).toBeNull()
})
})