Files
FFF_vtt_frozen/client/src/panels/walls.ts
T
SirStone ac5a6ac8dc test: deflake map fill gate and wall-locked under load
Map gate (a): measure the fastest of 4 fresh page loads after a warm-up (min-of-N,
TESTING 5.3) against 2x the 1 s DESIGN budget (the documented saturated-host
tolerance), and print every sample; a planted 50 ms/tile decode delay fails it.

Wall editor: an ack dispatch re-renders with the previous server record, and the
panel repopulated every control on every render, so a just-toggled checkbox was
reverted until the wall frame landed (Playwright saw 'did not change its state').
Repopulate only when the record changed (src/panels/wallSync.ts, unit-tested) and
restore the controls when the server refuses an edit.
2026-11-21 17:37:11 +01:00

661 lines
21 KiB
TypeScript

// GM wall editor panel (T10, #73; DESIGN 5.8, 6.1 wall payloads, 7.4). Plain DOM and `textContent`
// only. Mounted under the shell's `#panels` host by the wall render module, so a player never gets a
// wall panel and the panel cannot outlive the live stage.
//
// The panel owns the editor's local UI state (the armed preset, the first click, the snap toggle)
// and sends `wall.add` / `wall.update` / `wall.remove` / `door.set` through the session's intent
// bridge. Every payload is built by `src/wallEditor.ts`, which enforces preset XOR raw (an
// `open:false` never rides beside a preset) and never puts `open` in a `wall.update` patch: opening
// and closing a door is the `door.set` intent.
//
// Undo (story 52) is single-step: the panel records the inverse of the last successful edit as a
// wall-slice descriptor, and the Undo button sends that inverse. A new edit replaces it.
import type { ReducerEvent, RootState } from '../reducer.ts'
import type { AckFrame, Vec2 } from '../protocol.ts'
import { sendIntent } from '../intents.ts'
import type { WallView } from '../slices/walls.ts'
import { restoreOf, selectedWallOf, undoOf, wallsOf } from '../slices/walls.ts'
import type { SightDir, WallPreset, WallSwitches, WallUndo } from '../wallEditor.ts'
import type { PopulatedWall } from './wallSync.ts'
import { shouldPopulate, wallFieldsSignature } from './wallSync.ts'
import {
PRESETS,
buildAddFields,
buildDoorFields,
buildUpdateFields,
flipSightDir,
presetSwitches,
snapPoint,
undoIntent,
validateLabel,
validateSwitches,
} from '../wallEditor.ts'
export interface WallPanel {
render(state: RootState): void
/** The editor is waiting for the two draw points; the renderer must take the gesture. */
readonly armed: boolean
/** The first snapped point of the wall being drawn, or null. */
readonly first: Vec2 | null
/** Snap a world point with the current grid/endpoint settings. */
snap(point: Vec2): Vec2
/** Feed one click while armed; the second one sends `wall.add`. */
drawPoint(point: Vec2): void
cancelDraw(): void
destroy(): void
}
const CODE_TEXT: Record<string, string> = {
invalid: 'That combination is not valid.',
'not-found': 'That wall no longer exists.',
'not-allowed': 'The server refused that action.',
}
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 }
}
const PRESET_LABELS: Record<WallPreset, string> = {
wall: 'Wall',
door: 'Door',
window: 'Window',
one_way: 'One-way',
}
export function mountWallPanel(
host: HTMLElement,
dispatch: (event: ReducerEvent) => void,
): WallPanel {
const root = element('section', 'gm-walls')
root.hidden = true
root.append(element('h2', undefined, 'Walls'))
// ---- draw ----------------------------------------------------------------------------------
const drawSection = element('section', 'wall-draw')
drawSection.append(element('h3', undefined, 'Draw'))
const presetRow = element('div', 'wall-presets')
const presetButtons = new Map<WallPreset, HTMLButtonElement>()
for (const preset of PRESETS) {
const button = element('button', `wall-preset-${preset}`, PRESET_LABELS[preset])
button.type = 'button'
button.dataset['preset'] = preset
button.addEventListener('click', () => arm(preset))
presetButtons.set(preset, button)
presetRow.append(button)
}
const snapWrap = field('input', 'wall-snap', 'Snap to grid and endpoints')
snapWrap.node.type = 'checkbox'
snapWrap.node.checked = true
const drawHint = element('p', 'wall-hint', 'Choose a preset, then click two points.')
const drawState = element('p', 'wall-drawing', '')
drawSection.append(presetRow, snapWrap.label, snapWrap.node, drawHint, drawState)
// ---- selected wall -------------------------------------------------------------------------
const selected = element('section', 'wall-selected')
selected.hidden = true
const selectedTitle = element('h3', 'wall-kind', 'No wall selected')
const kindHint = element('p', 'wall-kind-hint', 'Derived kind (server)')
const labelInput = field('input', 'wall-label', 'Private label')
labelInput.node.type = 'text'
labelInput.node.maxLength = 64
const labelApply = element('button', 'wall-label-apply', 'Set label')
labelApply.type = 'button'
const markerWrap = field('input', 'wall-player-marker', 'Players see a marker')
markerWrap.node.type = 'checkbox'
const doorWrap = field('input', 'wall-door', 'Door')
doorWrap.node.type = 'checkbox'
const secretWrap = field('input', 'wall-secret', 'Secret')
secretWrap.node.type = 'checkbox'
const lockedWrap = field('input', 'wall-locked', 'Locked')
lockedWrap.node.type = 'checkbox'
const openButton = element('button', 'wall-open', 'Open door')
openButton.type = 'button'
const flipButton = element('button', 'wall-flip', 'Flip direction')
flipButton.type = 'button'
flipButton.hidden = true
const hintLocked = element('p', 'wall-hint-locked', 'locked: unlock first')
hintLocked.hidden = true
const unlockButton = element('button', 'wall-unlock', 'Unlock')
unlockButton.type = 'button'
unlockButton.hidden = true
const deleteButton = element('button', 'wall-delete', 'Delete wall')
deleteButton.type = 'button'
// ---- advanced raw switches -----------------------------------------------------------------
const advancedToggle = element('button', 'wall-advanced-toggle', 'Advanced switches')
advancedToggle.type = 'button'
const advanced = element('section', 'wall-advanced')
advanced.hidden = true
const advSight = field('input', 'wall-blocks-sight', 'blocks_sight')
advSight.node.type = 'checkbox'
const advMove = field('input', 'wall-blocks-movement', 'blocks_movement')
advMove.node.type = 'checkbox'
const advDir = field('select', 'wall-sight-dir', 'sight_dir')
for (const value of ['both', 'left', 'right'] as const) {
const option = element('option', undefined, value)
option.value = value
advDir.node.append(option)
}
const advMarker = field('input', 'wall-adv-marker', 'player_marker')
advMarker.node.type = 'checkbox'
const advDoor = field('input', 'wall-adv-door', 'door')
advDoor.node.type = 'checkbox'
const advSecret = field('input', 'wall-adv-secret', 'secret')
advSecret.node.type = 'checkbox'
const advLocked = field('input', 'wall-adv-locked', 'locked')
advLocked.node.type = 'checkbox'
const advApply = element('button', 'wall-adv-apply', 'Apply switches')
advApply.type = 'button'
advanced.append(
advSight.label,
advSight.node,
advMove.label,
advMove.node,
advDir.label,
advDir.node,
advMarker.label,
advMarker.node,
advDoor.label,
advDoor.node,
advSecret.label,
advSecret.node,
advLocked.label,
advLocked.node,
advApply,
)
const error = element('p', 'wall-error')
error.hidden = true
error.setAttribute('role', 'alert')
selected.append(
selectedTitle,
kindHint,
labelInput.label,
labelInput.node,
labelApply,
markerWrap.label,
markerWrap.node,
doorWrap.label,
doorWrap.node,
openButton,
secretWrap.label,
secretWrap.node,
lockedWrap.label,
lockedWrap.node,
hintLocked,
unlockButton,
flipButton,
advancedToggle,
advanced,
deleteButton,
error,
)
// ---- undo ----------------------------------------------------------------------------------
const undoButton = element('button', 'wall-undo', 'Undo')
undoButton.type = 'button'
root.append(drawSection, selected, undoButton)
host.append(root)
let active = false
let current: RootState | null = null
let preset: WallPreset = 'wall'
let armed = false
let first: Vec2 | null = null
let snapEnabled = true
/** The server record last copied into the controls (id + field signature), or null. */
let populated: PopulatedWall | null = null
let advancedOpen = false
/** The last rendered wall record, so a field edit uses exactly what the GM saw. */
let shown: WallView | null = null
function setError(text: string | null): void {
error.textContent = text ?? ''
error.hidden = text === null
}
function scene(): { id: number; w: number; h: number; grid: number } | null {
const info = current?.session.scene
if (!info) return null
return { id: info.id, w: info.w, h: info.h, grid: info.grid_size }
}
function endpoints(): Vec2[] {
const out: Vec2[] = []
if (!current) return out
for (const wall of wallsOf(current)) out.push(wall.a, wall.b)
return out
}
function clamp(world: Vec2): Vec2 {
const info = scene()
if (!info) return world
return [
Math.min(info.w, Math.max(0, world[0])),
Math.min(info.h, Math.max(0, world[1])),
]
}
function snap(point: Vec2): Vec2 {
const info = scene()
return clamp(
snapPoint(point, {
enabled: snapEnabled,
gridSize: info?.grid ?? 0,
endpoints: endpoints(),
// Endpoint snap is a small pull: 12 world px at the board's 32 px grid.
threshold: 12,
}),
)
}
function updateDrawState(): void {
for (const [value, button] of presetButtons) {
button.setAttribute('aria-pressed', value === preset ? 'true' : 'false')
}
drawState.textContent = armed
? first === null
? `Drawing ${PRESET_LABELS[preset]}: click the first point.`
: `Drawing ${PRESET_LABELS[preset]}: click the second point.`
: 'Not drawing.'
}
function arm(next: WallPreset): void {
preset = next
armed = true
first = null
setError(null)
updateDrawState()
}
function cancelDraw(): void {
armed = false
first = null
updateDrawState()
}
async function send(t: string, fields: Record<string, unknown>): Promise<AckFrame | null> {
try {
const ack = await sendIntent(t, fields)
if (!ack.ok) setError(describeCode(ack.code))
return ack
} catch {
setError('Could not reach the server.')
return null
}
}
function drawPoint(point: Vec2): void {
if (!armed) return
const info = scene()
if (!info) return
const snapped = snap(point)
if (first === null) {
first = snapped
updateDrawState()
return
}
const a = first
first = null
armed = false
updateDrawState()
if (a[0] === snapped[0] && a[1] === snapped[1]) {
setError('A wall needs two different points.')
return
}
const payload = { preset, switches: presetSwitches(preset), label: null }
const fields = buildAddFields(info.id, a, snapped, payload)
void send('wall.add', fields).then(ack => {
if (ack?.ok && typeof ack.id === 'number') {
// Select the new wall so the GM can label it or open it, and make the add undoable.
dispatch({ type: 'wall-select', id: ack.id })
dispatch({ type: 'wall-record-undo', undo: { kind: 'remove', id: ack.id } })
}
})
}
async function patch(fields: Record<string, unknown>, prior: WallView): Promise<boolean> {
const info = scene()
if (!info) return false
const ack = await send('wall.update', { scene: info.id, id: prior.id, ...fields })
if (ack?.ok) {
dispatch({
type: 'wall-record-undo',
undo: {
kind: 'update',
id: prior.id,
switches: { ...prior.switches },
label: prior.label,
flags: { ...prior.flags },
},
})
setError(null)
return true
}
return false
}
function mergedSwitches(next: Partial<WallSwitches>): WallSwitches | null {
if (!shown) return null
return { ...shown.switches, ...next }
}
/** Send one checkbox/select field, validating the resulting switch set first. */
async function applySwitch<K extends keyof WallSwitches>(
key: K,
value: WallSwitches[K],
): Promise<void> {
const prior = shown
if (!prior) return
setError(null)
// Clearing `door` is the one patch that also closes/de-secrets server-side (6.1), so it is sent
// alone rather than as a contradictory full switch set.
if (key === 'door' && value === false) {
if (!(await patch({ door: false }, prior))) populate(prior)
return
}
const merged = mergedSwitches({ [key]: value } as Partial<WallSwitches>)
if (!merged) return
const invalid = validateSwitches(merged)
if (invalid !== null) {
setError(invalid)
return
}
const payload = buildUpdateFields(prior.id, { preset: null, switches: merged })
const info = scene()
if (!info) return
const ack = await send('wall.update', { scene: info.id, ...payload })
if (ack?.ok) {
dispatch({
type: 'wall-record-undo',
undo: {
kind: 'update',
id: prior.id,
switches: { ...prior.switches },
label: prior.label,
flags: { ...prior.flags },
},
})
} else {
// The server refused: put the control back to the record the GM last saw.
populate(prior)
}
}
// ---- listeners -----------------------------------------------------------------------------
snapWrap.node.addEventListener('change', () => {
snapEnabled = snapWrap.node.checked
})
labelApply.addEventListener('click', () => {
const prior = shown
if (!prior) return
const message = validateLabel(labelInput.node.value)
if (message !== null) {
setError(message)
return
}
const trimmed = labelInput.node.value.trim()
void patch({ label: trimmed === '' ? null : trimmed }, prior)
})
markerWrap.node.addEventListener('change', () => {
void applySwitch('playerMarker', markerWrap.node.checked)
})
doorWrap.node.addEventListener('change', () => {
void applySwitch('door', doorWrap.node.checked)
})
secretWrap.node.addEventListener('change', () => {
void applySwitch('secret', secretWrap.node.checked)
})
lockedWrap.node.addEventListener('change', () => {
void applySwitch('locked', lockedWrap.node.checked)
})
openButton.addEventListener('click', () => {
void toggleDoor()
})
unlockButton.addEventListener('click', () => {
void unlock()
})
flipButton.addEventListener('click', () => {
const prior = shown
if (!prior) return
void applySwitch('sightDir', flipSightDir(prior.switches.sightDir))
})
deleteButton.addEventListener('click', () => {
void deleteWall()
})
advanceButtonSetup()
undoButton.addEventListener('click', () => {
void runUndo()
})
function advanceButtonSetup(): void {
advancedToggle.addEventListener('click', () => {
advancedOpen = !advancedOpen
advanced.hidden = !advancedOpen
advancedToggle.setAttribute('aria-expanded', advancedOpen ? 'true' : 'false')
})
advApply.addEventListener('click', () => {
void applyAdvanced()
})
}
function populate(wall: WallView): void {
const switches = wall.switches
labelInput.node.value = wall.label ?? ''
markerWrap.node.checked = switches.playerMarker
doorWrap.node.checked = switches.door
secretWrap.node.checked = switches.secret
lockedWrap.node.checked = switches.locked
advSight.node.checked = switches.blocksSight
advMove.node.checked = switches.blocksMovement
advDir.node.value = switches.sightDir
advMarker.node.checked = switches.playerMarker
advDoor.node.checked = switches.door
advSecret.node.checked = switches.secret
advLocked.node.checked = switches.locked
}
async function applyAdvanced(): Promise<void> {
const prior = shown
if (!prior) return
setError(null)
const switches: WallSwitches = {
...prior.switches,
blocksSight: advSight.node.checked,
blocksMovement: advMove.node.checked,
sightDir: advDir.node.value as SightDir,
playerMarker: advMarker.node.checked,
door: advDoor.node.checked,
secret: advSecret.node.checked,
locked: advLocked.node.checked,
}
const invalid = validateSwitches(switches)
if (invalid !== null) {
setError(invalid)
return
}
await patch({ ...buildUpdateFields(prior.id, { preset: null, switches }) }, prior)
}
async function toggleDoor(): Promise<void> {
const prior = shown
if (!prior || !prior.switches.door) return
setError(null)
hintLocked.hidden = true
unlockButton.hidden = true
if (!prior.switches.open && (prior.switches.locked || prior.switches.secret)) {
// 5.8/6.1: a secret or locked door cannot open; the editor offers the one click that clears
// the block first. No intent is sent, so the server never sees a refused open.
hintLocked.textContent = prior.switches.locked
? 'locked: unlock first'
: 'secret: clear secret first'
hintLocked.hidden = false
unlockButton.textContent = prior.switches.locked ? 'Unlock' : 'Clear secret'
unlockButton.dataset['action'] = prior.switches.locked ? 'locked' : 'secret'
unlockButton.hidden = false
return
}
const info = scene()
if (!info) return
const open = !prior.switches.open
const ack = await send('door.set', buildDoorFields(info.id, prior.id, open))
if (ack?.ok) {
dispatch({
type: 'wall-record-undo',
undo: { kind: 'door', id: prior.id, open: prior.switches.open },
})
}
}
async function unlock(): Promise<void> {
const prior = shown
if (!prior) return
setError(null)
hintLocked.hidden = true
unlockButton.hidden = true
const field = unlockButton.dataset['action'] === 'secret' ? 'secret' : 'locked'
await applySwitch(field, false)
}
async function deleteWall(): Promise<void> {
const prior = shown
const info = scene()
if (!prior || !info) return
setError(null)
const ack = await send('wall.remove', { scene: info.id, id: prior.id })
if (ack?.ok) {
dispatch({ type: 'wall-record-undo', undo: { kind: 'restore', wall: restoreOf(prior) } })
dispatch({ type: 'wall-select', id: null })
}
}
async function runUndo(): Promise<void> {
if (!current) return
const info = scene()
const undo = undoOf(current)
if (!info || undo === null) return
const intent = undoIntent(info.id, undo)
if (!intent) return
setError(null)
const ack = await send(intent.t, intent.fields)
if (ack?.ok) {
dispatch({ type: 'wall-record-undo', undo: null })
if (intent.t === 'wall.remove') dispatch({ type: 'wall-select', id: null })
}
}
function undoLabel(undo: WallUndo | null): string {
if (undo === null) return 'Undo'
switch (undo.kind) {
case 'remove':
return 'Undo draw'
case 'restore':
return 'Undo delete'
case 'update':
return 'Undo edit'
case 'door':
return 'Undo door'
}
}
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) {
active = false
armed = false
first = null
shown = null
populated = null
root.hidden = true
selected.hidden = true
setError(null)
hintLocked.hidden = true
unlockButton.hidden = true
updateDrawState()
return
}
if (!active) {
active = true
populated = null
}
root.hidden = false
const wall = selectedWallOf(state)
shown = wall
if (wall === null) {
selected.hidden = true
populated = null
undoButton.textContent = undoLabel(undoOf(state))
undoButton.disabled = undoOf(state) === null
return
}
selected.hidden = false
selectedTitle.textContent = `${wall.kind}`
if (populated?.id !== wall.id) {
populated = null
advancedOpen = false
advanced.hidden = true
advancedToggle.setAttribute('aria-expanded', 'false')
hintLocked.hidden = true
unlockButton.hidden = true
setError(null)
}
// Repopulate only when the server record changed: an ack dispatch carries the previous record
// and must not undo the switch the GM just made while the authoritative frame is in flight.
// Do not overwrite a field the GM is typing in either; the server's record still drives every
// other control and the derived kind.
if (shouldPopulate(populated, wall) && document.activeElement !== labelInput.node) {
populate(wall)
populated = { id: wall.id, signature: wallFieldsSignature(wall) }
}
kindHint.textContent = `Derived kind: ${wall.kind}`
openButton.textContent = wall.switches.open ? 'Close door' : 'Open door'
openButton.disabled = !wall.switches.door
flipButton.hidden = wall.switches.sightDir === 'both'
undoButton.textContent = undoLabel(undoOf(state))
undoButton.disabled = undoOf(state) === null
}
return {
render,
get armed() {
return armed
},
get first() {
return first
},
snap,
drawPoint,
cancelDraw,
destroy() {
root.remove()
},
}
}