feat(client): GM wall editor, round-1 fields (#73)
Draw, select, edit and delete walls through the GM panel: the four 5.8 presets, raw switches (preset XOR raw, open excluded from wall.update), a private label, the one-way arrow + flip (sight_dir names the blind side), the player-marker switch, door open/close through door.set, secret/locked with the locked hint and one-click unlock, delete and single-step undo. No thickness, height or position-flip control (ADR-0012). The pure rules and payload builders live in src/wallEditor.ts; the GM wall slice (src/slices/walls.ts) owns the server records, selection and undo; the render module draws on the gm layer and defines the input precedence: token drag (#72) > armed wall draw > camera pan (#69), with a click (no movement) selecting the nearest wall. Shared core edits: client/src/reducer.ts gains the wall-select and wall-record-undo events (the only new core events); style.css and the client README document the panel and rules. Unit tests cover the slice, presets, derived kind, arrow side, snapping, payload XOR, door intent and undo builders; the e2e draws every preset, edits the fields, flips the one-way wall, opens/closes a door, deletes and undoes, proves a token drag still wins over draw mode, and probes the player's fog pixels, with the player WS leaking no wall data. Ref #73
This commit is contained in:
@@ -138,6 +138,41 @@ change them only if a slice needs a new *core* event, and say so in the PR.
|
||||
so the gate is measured at real CPU and gate (b), the real-phone run (#77), remains authoritative
|
||||
for phone speed.
|
||||
|
||||
## GM wall editor, round-1 fields (T10, #73)
|
||||
|
||||
- **State**: `src/slices/walls.ts` is the GM wall slice: `walls` (full snapshot on connect/resync),
|
||||
`wall` (upsert, doors included) and `wall_gone`, plus the editor's selected id and its single-step
|
||||
undo descriptor. Wall frames are GM-only, and the slice also ignores them on a player-shaped
|
||||
session, so a server bug could not quietly turn the client into a wall-data renderer. `hello`
|
||||
resets it like every slice.
|
||||
- **Pure rules**: `src/wallEditor.ts` expands the four 5.8 presets (`wall`, `door`, `window`,
|
||||
`one_way`), derives `kind` in the fixed order (window, one_way, door, wall, else custom), computes
|
||||
the one-way arrow toward the blind side named by `sight_dir`, snaps to endpoints then the grid,
|
||||
and builds the exact DESIGN 6.1 payloads. A preset payload carries only `preset` (never a raw
|
||||
switch, `open:false` included); `wall.update` never carries `open` because opening and closing are
|
||||
`door.set`. The same module holds the local pre-flight validation so an impossible combination is
|
||||
shown before an intent leaves the browser.
|
||||
- **Renderer + input**: `src/render/modules/walls.ts` draws each wall on the `gm` layer (derived-kind
|
||||
colour, open doors dashed, secret doors dotted, selected endpoints, the one-way arrow and the
|
||||
marker switch). Input precedence is explicit: token drag (#72) wins first and consumes its
|
||||
gesture; wall drawing wins next while a preset is armed (the two clicks never pan); otherwise the
|
||||
camera (#69) pans and a click with no movement selects the nearest wall. A drag that moved is a
|
||||
pan, not a selection. The canvas publishes `data-walls`, `data-wall-kinds`, `data-wall-selected`,
|
||||
`data-wall-arrows`, `data-wall-markers`, `data-wall-draw`, `data-wall-preview` and `data-wall-undo`
|
||||
for the e2e.
|
||||
- **Panel**: `src/panels/walls.ts` adds `#gm-walls` under `#panels` via the render module (no shared
|
||||
bootstrap edit): preset buttons arm the draw, then the selected wall exposes its server-derived
|
||||
kind, label, `player_marker`, door/open/close, `secret`/`locked`, the advanced raw switches (with
|
||||
`Apply switches`), the one-way flip, delete and Undo. A locked or secret door's open action shows
|
||||
`locked: unlock first` / `secret: clear secret first` and the one click that clears the block
|
||||
instead of sending a refused intent. No thickness, height or position control (ADR-0012).
|
||||
- **Proof**: `test/walls.test.ts` (slice load/upsert/remove/reset, player frames ignored, preset
|
||||
expansion, derived kind, arrow side, snap, payload XOR rules, `open` excluded from updates, undo
|
||||
intents, local validation) and `e2e/walls.test.mjs` (real server: draw all four presets, label,
|
||||
marker, locked hint + one-click unlock, open/close, advanced invalid combination shown, delete +
|
||||
undo, a token drag still beats draw mode, and the player's fog pixels change for a wall, a one-way
|
||||
flip, a door open/close and the marker, with no wall data in the player's frames).
|
||||
|
||||
## Tokens, labels, statuses and the two lists (T8, #71)
|
||||
|
||||
- **State**: `src/slices/tokens.ts` (`token` upsert, `token_gone`, `hello` reset; `tokensOf`),
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
// T10 (#73, TESTING 10.3): the GM wall editor against the real server through the TLS/HTTP2 nginx.
|
||||
// The browser's real mouse draws walls; the assertions read the real GM `wall`/`wall_gone` frames,
|
||||
// the player's real fog pixels and a second real player WebSocket for the leak scan. No fixture, no
|
||||
// mocked protocol.
|
||||
//
|
||||
// Two tests:
|
||||
// 1. every round-1 field round-trips (four presets, label, marker switch, open/close, secret,
|
||||
// locked hint + one click, advanced raw switches with the invalid combination shown, delete +
|
||||
// undo, and token drag still beats draw mode);
|
||||
// 2. the player's fog changes: a drawn wall blocks, the one-way flip re-blocks the floor, opening
|
||||
// a door reveals it again, and a marked window sends its marker pixel.
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { createPlayer, namePlayer, sleep } from '../../tools/lib.mjs'
|
||||
import { openAs } from '../../tools/withserver.mjs'
|
||||
import { writeTileGrid } from '../../tools/tilefixture.mjs'
|
||||
import {
|
||||
launchBrowser,
|
||||
newPage,
|
||||
signIn,
|
||||
waitForText,
|
||||
waitForVisible,
|
||||
withStack,
|
||||
} from './stack.mjs'
|
||||
import { luminance, probe } from './pixels.mjs'
|
||||
|
||||
const CENTRE = [2048, 2048]
|
||||
const SCENE = { w: 4096, h: 4096, tile: 32, cell: 32 }
|
||||
|
||||
function tileColour(worldX, worldY) {
|
||||
const x = Math.floor(worldX / SCENE.tile)
|
||||
const y = Math.floor(worldY / SCENE.tile)
|
||||
return { r: (x * 37 + y * 11) & 0xff, g: (x * 17 + y * 53) & 0xff, b: (x * 97 + y * 5) & 0xff }
|
||||
}
|
||||
|
||||
const cellCentre = (cx, cy) => [cx * SCENE.cell + 16, cy * SCENE.cell + 16]
|
||||
// Cell centres chosen off the drawn wall lines (DESIGN 5.8: a wall blocks the ray crossing it).
|
||||
const PROBES = {
|
||||
right: cellCentre(67, 64), // [2160,2064]: blocked by the vertical wall at x=2112
|
||||
left: cellCentre(58, 64), // [1872,2064]: blocked by the closed door at x=1920
|
||||
below: cellCentre(64, 71), // [2064,2288]: blocked by the one-way wall once its blind side is above
|
||||
window: [2032, 1920], // the marked window's drawn midpoint
|
||||
}
|
||||
|
||||
function near(actual, expected, tolerance = 12) {
|
||||
return (
|
||||
Math.abs(actual.r - expected.r) <= tolerance &&
|
||||
Math.abs(actual.g - expected.g) <= tolerance &&
|
||||
Math.abs(actual.b - expected.b) <= tolerance
|
||||
)
|
||||
}
|
||||
|
||||
async function gmWorld(origin, gmKey) {
|
||||
const gm = await openAs(origin, gmKey)
|
||||
const hello = await gm.ws.waitText('hello')
|
||||
const walls = await gm.ws.waitText('walls')
|
||||
return { ...gm, hello, scene: hello.scene ?? walls.scene }
|
||||
}
|
||||
|
||||
/** A named player with one sighted token: the wall editor's effects have something to change. */
|
||||
async function worldWithPlayer(origin, gmKey, { tiles = false, stateDir } = {}) {
|
||||
const gm = await gmWorld(origin, gmKey)
|
||||
const scene = gm.scene
|
||||
if (tiles) {
|
||||
writeTileGrid(stateDir, {
|
||||
scene: scene.id,
|
||||
artVersion: scene.art_version,
|
||||
size: scene.tile_size,
|
||||
x0: 40,
|
||||
x1: 87,
|
||||
y0: 40,
|
||||
y1: 87,
|
||||
})
|
||||
}
|
||||
const player = await createPlayer(gm.ws)
|
||||
await namePlayer(origin, player.key, 'Ann')
|
||||
const token = await gm.ws.request({
|
||||
t: 'token.create',
|
||||
scene: scene.id,
|
||||
kind: 'pc',
|
||||
pos: CENTRE,
|
||||
descriptive_name: 'Ann',
|
||||
actual_name: 'Ann',
|
||||
controller: player.id,
|
||||
flags: { vision: true },
|
||||
vision_radius: 300,
|
||||
radius: 20,
|
||||
})
|
||||
assert.equal(token.ok, true, JSON.stringify(token))
|
||||
return { gm, player, scene, token: token.id }
|
||||
}
|
||||
|
||||
async function viewOf(page) {
|
||||
return page.evaluate(() => {
|
||||
const canvas = document.querySelector('#stage canvas')
|
||||
if (!canvas) throw new Error('no canvas')
|
||||
const rect = canvas.getBoundingClientRect()
|
||||
const [x, y] = (canvas.dataset.camera ?? '').split(',').map(Number)
|
||||
return { left: rect.left, top: rect.top, x, y, zoom: Number(canvas.dataset.zoom ?? '1') }
|
||||
})
|
||||
}
|
||||
|
||||
async function screenOf(page, world) {
|
||||
const view = await viewOf(page)
|
||||
return {
|
||||
x: view.left + world[0] * view.zoom + view.x,
|
||||
y: view.top + world[1] * view.zoom + view.y,
|
||||
}
|
||||
}
|
||||
|
||||
async function clickWorld(page, world) {
|
||||
const point = await screenOf(page, world)
|
||||
await page.mouse.click(point.x, point.y)
|
||||
}
|
||||
|
||||
async function drawPreset(page, preset, a, b) {
|
||||
await page.click(`#wall-preset-${preset}`)
|
||||
await clickWorld(page, a)
|
||||
await clickWorld(page, b)
|
||||
}
|
||||
|
||||
async function waitWalls(page, count, timeout = 20000) {
|
||||
await page.waitForFunction(
|
||||
expected => {
|
||||
const canvas = document.querySelector('#stage canvas')
|
||||
return canvas !== null && Number(canvas.dataset.walls ?? '-1') === expected
|
||||
},
|
||||
count,
|
||||
{ timeout },
|
||||
)
|
||||
}
|
||||
|
||||
async function gmPage(browser, origin, gmKey) {
|
||||
const { page } = await newPage(browser)
|
||||
const errors = []
|
||||
page.on('pageerror', error => errors.push(error.message))
|
||||
await page.goto(`${origin}/`)
|
||||
await waitForVisible(page, '#signin')
|
||||
await signIn(page, gmKey)
|
||||
await waitForVisible(page, '#stage canvas')
|
||||
await waitForVisible(page, '#gm-walls')
|
||||
await waitWalls(page, 0)
|
||||
return { page, errors }
|
||||
}
|
||||
|
||||
/** A GM-frame wait that returns the wall message, so a test can read the server's record. */
|
||||
function nextWall(gm, predicate, timeout = 10000) {
|
||||
return gm.ws.waitFor(message => message.t === 'wall' && predicate(message), timeout)
|
||||
}
|
||||
|
||||
test('GM wall editor: presets, label, door, secret/locked, advanced, undo, drag precedence', { timeout: 240000 }, async () => {
|
||||
await withStack(async ({ origin, gmKey }) => {
|
||||
const { gm, player } = await worldWithPlayer(origin, gmKey)
|
||||
// A second real player connection: the leak scan's independent witness.
|
||||
const witness = await openAs(origin, player.key)
|
||||
await witness.ws.waitText('hello')
|
||||
const browser = await launchBrowser()
|
||||
try {
|
||||
const { page, errors } = await gmPage(browser, origin, gmKey)
|
||||
|
||||
// --- wall preset + label -------------------------------------------------------------
|
||||
await drawPreset(page, 'wall', [2112, 1920], [2112, 2144])
|
||||
const wall = await nextWall(gm, message => message.a[0] === 2112 && message.b[1] === 2144)
|
||||
assert.equal(wall.kind, 'wall')
|
||||
await waitWalls(page, 1)
|
||||
await waitForVisible(page, '#wall-selected')
|
||||
await page.fill('#wall-label', 'railing')
|
||||
await page.click('#wall-label-apply')
|
||||
await nextWall(gm, message => message.id === wall.id && message.label === 'railing')
|
||||
assert.equal((await page.textContent('#wall-kind'))?.trim(), 'wall')
|
||||
|
||||
// --- door: open/close, locked hint and one-click unlock ------------------------------
|
||||
await drawPreset(page, 'door', [1920, 1920], [1920, 2144])
|
||||
const door = await nextWall(gm, message => message.a[0] === 1920 && message.door === true)
|
||||
assert.equal(door.kind, 'door')
|
||||
await waitWalls(page, 2)
|
||||
await page.check('#wall-locked')
|
||||
await nextWall(gm, message => message.id === door.id && message.locked === true)
|
||||
await page.click('#wall-open')
|
||||
await waitForVisible(page, '#wall-hint-locked')
|
||||
assert.match((await page.textContent('#wall-hint-locked')) ?? '', /locked: unlock first/)
|
||||
assert.equal(door.open, false)
|
||||
await page.click('#wall-unlock')
|
||||
await nextWall(gm, message => message.id === door.id && message.locked === false)
|
||||
await page.click('#wall-open')
|
||||
await nextWall(gm, message => message.id === door.id && message.open === true)
|
||||
await page.click('#wall-open')
|
||||
await nextWall(gm, message => message.id === door.id && message.open === false)
|
||||
|
||||
// Secret is a door checkbox that round-trips; it never reaches the player (leak scan below).
|
||||
await page.check('#wall-secret')
|
||||
await nextWall(gm, message => message.id === door.id && message.secret === true)
|
||||
await page.uncheck('#wall-secret')
|
||||
await nextWall(gm, message => message.id === door.id && message.secret === false)
|
||||
|
||||
// --- window and one-way presets ------------------------------------------------------
|
||||
await drawPreset(page, 'window', [1984, 1920], [2080, 1920])
|
||||
const win = await nextWall(gm, message => message.a[1] === 1920 && message.a[0] === 1984)
|
||||
assert.equal(win.kind, 'window')
|
||||
assert.equal(win.player_marker, true)
|
||||
await waitWalls(page, 3)
|
||||
// The marker switch is authorable on any wall; the window preset turns it on.
|
||||
assert.equal(await page.isChecked('#wall-player-marker'), true)
|
||||
await page.uncheck('#wall-player-marker')
|
||||
await nextWall(gm, message => message.id === win.id && message.player_marker === false)
|
||||
await page.check('#wall-player-marker')
|
||||
await nextWall(gm, message => message.id === win.id && message.player_marker === true)
|
||||
// Round 1 has no thickness, height or position-flip control (ADR-0012).
|
||||
assert.equal(await page.locator('#wall-thickness').count(), 0)
|
||||
assert.equal(await page.locator('#wall-height').count(), 0)
|
||||
await drawPreset(page, 'one_way', [1792, 2208], [2176, 2208])
|
||||
const oneWay = await nextWall(gm, message => message.a[1] === 2208)
|
||||
assert.equal(oneWay.kind, 'one_way')
|
||||
assert.equal(oneWay.sight_dir, 'left')
|
||||
await waitWalls(page, 4)
|
||||
|
||||
// --- advanced switches: an impossible raw combination shows the reason --------------
|
||||
await page.click('#wall-advanced-toggle')
|
||||
await page.uncheck('#wall-blocks-sight')
|
||||
await page.selectOption('#wall-sight-dir', 'left')
|
||||
await page.click('#wall-adv-apply')
|
||||
await waitForVisible(page, '#wall-error')
|
||||
assert.match((await page.textContent('#wall-error')) ?? '', /sight direction/)
|
||||
// The server still holds the valid one-way wall; the client did not send an invalid patch.
|
||||
assert.equal(oneWay.blocks_sight, true)
|
||||
|
||||
// --- delete then single-step undo ----------------------------------------------------
|
||||
await page.click('#wall-delete')
|
||||
await gm.ws.waitFor(message => message.t === 'wall_gone' && message.id === oneWay.id)
|
||||
await waitWalls(page, 3)
|
||||
await page.click('#wall-undo')
|
||||
const restored = await nextWall(gm, message => message.a[1] === 2208 && message.id !== oneWay.id)
|
||||
assert.equal(restored.kind, 'one_way')
|
||||
assert.deepEqual([restored.a, restored.b], [oneWay.a, oneWay.b])
|
||||
await waitWalls(page, 4)
|
||||
|
||||
// --- input precedence: a token drag wins over an armed draw --------------------------
|
||||
await page.click('#wall-preset-wall')
|
||||
const start = await screenOf(page, CENTRE)
|
||||
const end = await screenOf(page, [2000, 2112])
|
||||
await page.mouse.move(start.x, start.y)
|
||||
await page.mouse.down()
|
||||
for (let step = 1; step <= 6; step += 1) {
|
||||
await page.mouse.move(
|
||||
start.x + ((end.x - start.x) * step) / 6,
|
||||
start.y + ((end.y - start.y) * step) / 6,
|
||||
)
|
||||
await sleep(60)
|
||||
}
|
||||
await page.mouse.up()
|
||||
const moved = await gm.ws.waitFor(
|
||||
message =>
|
||||
message.t === 'token' &&
|
||||
Math.abs(message.pos[0] - 2000) <= 3 &&
|
||||
Math.abs(message.pos[1] - 2112) <= 3,
|
||||
10000,
|
||||
)
|
||||
assert.deepEqual(moved.pos, [2000, 2112])
|
||||
// Drawing mode never saw the gesture: no fifth wall and the draw is still armed.
|
||||
await sleep(300)
|
||||
assert.equal(await page.getAttribute('#stage canvas', 'data-walls'), '4')
|
||||
assert.equal(await page.getAttribute('#stage canvas', 'data-wall-draw'), 'first')
|
||||
await page.keyboard.press('Escape')
|
||||
|
||||
// --- player traffic: no wall data beyond the marker (3.1) ---------------------------
|
||||
const bad = witness.ws.messages.filter(message => {
|
||||
if (['wall', 'walls', 'wall_gone'].includes(message.t)) return true
|
||||
if (message.t === 'marker') return false
|
||||
const banned = [
|
||||
'blocks_sight',
|
||||
'blocks_movement',
|
||||
'sight_dir',
|
||||
'player_marker',
|
||||
'thickness',
|
||||
'position',
|
||||
'secret',
|
||||
'locked',
|
||||
'label',
|
||||
]
|
||||
return banned.some(key => Object.prototype.hasOwnProperty.call(message, key))
|
||||
})
|
||||
assert.deepEqual(bad, [], `player frames carried wall data: ${JSON.stringify(bad.slice(0, 2))}`)
|
||||
assert.deepEqual(errors, [])
|
||||
await page.context().close()
|
||||
} finally {
|
||||
await browser.close()
|
||||
witness.ws.close()
|
||||
gm.ws.close()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
async function fogState(page) {
|
||||
return page.evaluate(() => {
|
||||
const canvas = document.querySelector('#stage canvas')
|
||||
if (!canvas) return null
|
||||
const data = canvas.dataset
|
||||
return {
|
||||
tiles: data.tiles ?? '',
|
||||
markers: (data.fogMarkers ?? '').split(' ').filter(Boolean),
|
||||
cells: Number(data.fogCells ?? '-1'),
|
||||
visionBuilds: Number(data.fogVisionBuilds ?? '-1'),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async function waitFog(page, predicate, timeout = 30000) {
|
||||
const deadline = Date.now() + timeout
|
||||
let last = null
|
||||
while (Date.now() < deadline) {
|
||||
last = await fogState(page)
|
||||
if (last !== null && predicate(last)) return last
|
||||
await sleep(50)
|
||||
}
|
||||
throw new Error(`fog never reached the expected state: ${JSON.stringify(last)}`)
|
||||
}
|
||||
|
||||
async function probeWorld(page, world) {
|
||||
const point = await screenOf(page, world)
|
||||
return probe(page, point.x, point.y)
|
||||
}
|
||||
|
||||
async function waitProbe(page, world, predicate, timeout = 20000) {
|
||||
const deadline = Date.now() + timeout
|
||||
let last = null
|
||||
while (Date.now() < deadline) {
|
||||
last = await probeWorld(page, world)
|
||||
if (predicate(last)) return last
|
||||
await sleep(100)
|
||||
}
|
||||
throw new Error(`pixel at ${world.join(',')} never matched: ${JSON.stringify(last)}`)
|
||||
}
|
||||
|
||||
test('GM walls change the player fog: block, one-way flip, door open/close, marker pixel', { timeout: 240000 }, async () => {
|
||||
await withStack(async ({ origin, gmKey, stateDir }) => {
|
||||
const { gm, player } = await worldWithPlayer(origin, gmKey, { tiles: true, stateDir })
|
||||
const witness = await openAs(origin, player.key)
|
||||
await witness.ws.waitText('hello')
|
||||
const browser = await launchBrowser()
|
||||
try {
|
||||
const playerView = await browser.newContext({
|
||||
ignoreHTTPSErrors: true,
|
||||
viewport: { width: 900, height: 900 },
|
||||
})
|
||||
const page = await playerView.newPage()
|
||||
const errors = []
|
||||
page.on('pageerror', error => errors.push(error.message))
|
||||
await page.goto(`${origin}/`)
|
||||
await waitForVisible(page, '#signin')
|
||||
await signIn(page, player.key)
|
||||
await waitForVisible(page, '#stage canvas')
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector('#stage canvas')?.dataset.tiles === 'ready',
|
||||
null,
|
||||
{ timeout: 30000 },
|
||||
)
|
||||
await waitFog(page, state => state.cells > 100)
|
||||
|
||||
const rightMap = tileColour(...PROBES.right)
|
||||
const leftMap = tileColour(...PROBES.left)
|
||||
const belowMap = tileColour(...PROBES.below)
|
||||
assert.ok(near(await probeWorld(page, PROBES.right), rightMap), 'right floor starts visible')
|
||||
assert.ok(near(await probeWorld(page, PROBES.left), leftMap), 'left floor starts visible')
|
||||
assert.ok(near(await probeWorld(page, PROBES.below), belowMap), 'below floor starts visible')
|
||||
|
||||
const gmView = await gmPage(browser, origin, gmKey)
|
||||
|
||||
// A drawn solid wall blocks the right floor: visible -> explored-dim without a reload.
|
||||
await drawPreset(gmView.page, 'wall', [2112, 1920], [2112, 2144])
|
||||
await nextWall(gm, message => message.a[0] === 2112)
|
||||
const dimRight = await waitProbe(page, PROBES.right, colour => luminance(colour) < luminance(rightMap) * 0.6)
|
||||
assert.ok(luminance(dimRight) < luminance(rightMap) * 0.6, 'the wall dimmed the right floor')
|
||||
|
||||
// A closed door blocks the left floor.
|
||||
await drawPreset(gmView.page, 'door', [1920, 1920], [1920, 2144])
|
||||
const door = await nextWall(gm, message => message.a[0] === 1920 && message.door === true)
|
||||
const dimLeft = await waitProbe(page, PROBES.left, colour => luminance(colour) < luminance(leftMap) * 0.6)
|
||||
assert.ok(luminance(dimLeft) < luminance(leftMap) * 0.6, 'the door dimmed the left floor')
|
||||
|
||||
// One-way preset: sight_dir "left" names the blind side (below). The player is above, so the
|
||||
// wall is initially transparent to sight; flipping it to "right" makes the player's side
|
||||
// blind and dims the floor below.
|
||||
await drawPreset(gmView.page, 'one_way', [1792, 2208], [2176, 2208])
|
||||
const oneWay = await nextWall(gm, message => message.a[1] === 2208)
|
||||
assert.equal(oneWay.sight_dir, 'left')
|
||||
assert.ok(near(await probeWorld(page, PROBES.below), belowMap), 'the seeing side sees across')
|
||||
await waitForVisible(gmView.page, '#wall-selected')
|
||||
await waitForText(gmView.page, '#wall-kind', /^one_way$/)
|
||||
await gmView.page.click('#wall-flip')
|
||||
await nextWall(gm, message => message.id === oneWay.id && message.sight_dir === 'right')
|
||||
const dimBelow = await waitProbe(page, PROBES.below, colour => luminance(colour) < luminance(belowMap) * 0.6)
|
||||
assert.ok(luminance(dimBelow) < luminance(belowMap) * 0.6, 'the flip moved the blind side to the player')
|
||||
|
||||
// Opening the door reveals the left floor; closing it dims it again.
|
||||
await clickWorld(gmView.page, [1920, 2025])
|
||||
await waitForText(gmView.page, '#wall-kind', /^door$/)
|
||||
await gmView.page.click('#wall-open')
|
||||
await nextWall(gm, message => message.id === door.id && message.open === true)
|
||||
await waitProbe(page, PROBES.left, colour => near(colour, leftMap))
|
||||
await gmView.page.click('#wall-open')
|
||||
await nextWall(gm, message => message.id === door.id && message.open === false)
|
||||
await waitProbe(page, PROBES.left, colour => luminance(colour) < luminance(leftMap) * 0.6)
|
||||
|
||||
// A marked window sends its marker; the player draws it at the wall's drawn midpoint.
|
||||
await drawPreset(gmView.page, 'window', [1984, 1920], [2080, 1920])
|
||||
const win = await nextWall(gm, message => message.a[1] === 1920 && message.a[0] === 1984)
|
||||
assert.equal(win.player_marker, true)
|
||||
await waitFog(page, state => state.markers.length === 1)
|
||||
const marker = await probeWorld(page, PROBES.window)
|
||||
assert.ok(near(marker, { r: 255, g: 204, b: 51 }, 26), `the window marker pixel: ${JSON.stringify(marker)}`)
|
||||
|
||||
// The player never received the editor's wall records, even for the secret/locked states.
|
||||
assert.equal(witness.ws.messages.some(message => ['wall', 'walls', 'wall_gone'].includes(message.t)), false)
|
||||
assert.deepEqual(errors, [])
|
||||
await playerView.close()
|
||||
await gmView.page.context().close()
|
||||
} finally {
|
||||
await browser.close()
|
||||
witness.ws.close()
|
||||
gm.ws.close()
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,649 @@
|
||||
// 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 {
|
||||
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
|
||||
let populatedFor = -1
|
||||
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) {
|
||||
await patch({ door: false }, 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 },
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 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
|
||||
populatedFor = -1
|
||||
root.hidden = true
|
||||
selected.hidden = true
|
||||
setError(null)
|
||||
hintLocked.hidden = true
|
||||
unlockButton.hidden = true
|
||||
updateDrawState()
|
||||
return
|
||||
}
|
||||
if (!active) {
|
||||
active = true
|
||||
populatedFor = -1
|
||||
}
|
||||
root.hidden = false
|
||||
|
||||
const wall = selectedWallOf(state)
|
||||
shown = wall
|
||||
if (wall === null) {
|
||||
selected.hidden = true
|
||||
populatedFor = -1
|
||||
undoButton.textContent = undoLabel(undoOf(state))
|
||||
undoButton.disabled = undoOf(state) === null
|
||||
return
|
||||
}
|
||||
selected.hidden = false
|
||||
selectedTitle.textContent = `${wall.kind}`
|
||||
if (populatedFor !== wall.id) {
|
||||
populatedFor = wall.id
|
||||
advancedOpen = false
|
||||
advanced.hidden = true
|
||||
advancedToggle.setAttribute('aria-expanded', 'false')
|
||||
hintLocked.hidden = true
|
||||
unlockButton.hidden = true
|
||||
setError(null)
|
||||
}
|
||||
// Do not overwrite a field the GM is typing in; the server's record still drives every other
|
||||
// control and the derived kind.
|
||||
if (document.activeElement !== labelInput.node) populate(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()
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import type {
|
||||
Vec2,
|
||||
} from './protocol.ts'
|
||||
import { closeOutcome, isClosing, isHello } from './protocol.ts'
|
||||
import type { WallUndo } from './wallEditor.ts'
|
||||
|
||||
export type Phase = 'boot' | 'connecting' | 'signin' | 'live' | 'reconnecting' | 'reload' | 'offline'
|
||||
|
||||
@@ -82,6 +83,10 @@ export type ReducerEvent =
|
||||
| { type: 'move-sent'; reqId: number; id: string; pos: Vec2 }
|
||||
/** The renderer finished the cosmetic rollback tween for this token. */
|
||||
| { type: 'rollback-done'; id: string; seq: number }
|
||||
/** GM wall editor selection (#73): the id lives in the wall slice, the core just carries it. */
|
||||
| { type: 'wall-select'; id: number | null }
|
||||
/** The last successful wall edit's inverse, for the editor's single-step undo (#73). */
|
||||
| { type: 'wall-record-undo'; undo: WallUndo | null }
|
||||
|
||||
/**
|
||||
* A domain slice. `init()` returns the empty value; `reduce` mutates the draft it is handed (the
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
// GM wall layer and editor input (T10, #73; DESIGN 5.8, 7.4, 7.2). Walls are GM-only, so this module
|
||||
// draws into the `gm` layer and arms nothing for a player session. It is the Pixi half of the
|
||||
// editor: the panel (`src/panels/walls.ts`) owns the armed preset and sends the intents, the slice
|
||||
// (`src/slices/walls.ts`) owns the server's records, and `src/wallEditor.ts` owns the pure rules.
|
||||
//
|
||||
// Input precedence (the thing #73 must not break):
|
||||
// 1. token drag (#72) wins first: its window-capture `pointerdown` runs before this module's and
|
||||
// stops immediate propagation when the press lands on a token the session may move;
|
||||
// 2. wall drawing wins next, but only while a preset is armed: the two clicks are consumed and the
|
||||
// camera never starts a pan;
|
||||
// 3. otherwise the camera (#69) keeps pan/pinch, and a click (no movement) selects the wall under
|
||||
// the pointer. A drag that moved more than a few pixels is a pan, not a selection.
|
||||
// The e2e arms a preset and starts a drag on a token to prove rule 1 still wins.
|
||||
//
|
||||
// A one-way wall's arrow points from the seeing side toward the blind side (`sight_dir` names the
|
||||
// blind side, GLOSSARY "Blind side"): `arrowVector` is the one place that direction is computed.
|
||||
|
||||
import { Container, Graphics } from 'pixi.js'
|
||||
import type { RenderContext, RenderModule } from '../stage.ts'
|
||||
import { dragOf } from '../../slices/move.ts'
|
||||
import type { WallView } from '../../slices/walls.ts'
|
||||
import { selectedWallId, undoOf, wallsOf } from '../../slices/walls.ts'
|
||||
import { arrowVector, distanceToSegment, wallMidpoint } from '../../wallEditor.ts'
|
||||
import type { Vec2 } from '../../protocol.ts'
|
||||
import { mountWallPanel } from '../../panels/walls.ts'
|
||||
|
||||
const COLORS: Record<string, number> = {
|
||||
wall: 0xb8c4d0,
|
||||
door: 0xd19a51,
|
||||
window: 0x54c7c9,
|
||||
one_way: 0xb989e0,
|
||||
custom: 0xd8d8d8,
|
||||
}
|
||||
|
||||
interface WallNode {
|
||||
container: Container
|
||||
graphics: Graphics
|
||||
sig: string
|
||||
}
|
||||
|
||||
function wallSignature(wall: WallView, selected: boolean): string {
|
||||
const s = wall.switches
|
||||
return [
|
||||
wall.id,
|
||||
wall.a.join(','),
|
||||
wall.b.join(','),
|
||||
wall.kind,
|
||||
s.blocksSight ? 1 : 0,
|
||||
s.blocksMovement ? 1 : 0,
|
||||
s.sightDir,
|
||||
s.playerMarker ? 1 : 0,
|
||||
s.door ? 1 : 0,
|
||||
s.open ? 1 : 0,
|
||||
s.secret ? 1 : 0,
|
||||
s.locked ? 1 : 0,
|
||||
selected ? 1 : 0,
|
||||
].join('|')
|
||||
}
|
||||
|
||||
/** A dashed/dotted stroke, used for an open door (nothing is there) and a secret door (GM view). */
|
||||
function dashedLine(
|
||||
graphics: Graphics,
|
||||
a: Vec2,
|
||||
b: Vec2,
|
||||
width: number,
|
||||
color: number,
|
||||
dash: number,
|
||||
gap: number,
|
||||
alpha: number,
|
||||
): void {
|
||||
const dx = b[0] - a[0]
|
||||
const dy = b[1] - a[1]
|
||||
const length = Math.hypot(dx, dy)
|
||||
if (!(length > 0)) return
|
||||
const ux = dx / length
|
||||
const uy = dy / length
|
||||
for (let start = 0; start < length; start += dash + gap) {
|
||||
const end = Math.min(length, start + dash)
|
||||
graphics
|
||||
.moveTo(a[0] + ux * start, a[1] + uy * start)
|
||||
.lineTo(a[0] + ux * end, a[1] + uy * end)
|
||||
.stroke({ width, color, alpha })
|
||||
}
|
||||
}
|
||||
|
||||
function drawWall(graphics: Graphics, wall: WallView, selected: boolean): void {
|
||||
graphics.clear()
|
||||
const a = wall.a
|
||||
const b = wall.b
|
||||
const color = COLORS[wall.kind] ?? COLORS['custom']!
|
||||
const width = selected ? 6 : 4
|
||||
const alpha = selected ? 1 : 0.85
|
||||
const open = wall.switches.door && wall.switches.open
|
||||
|
||||
if (selected) {
|
||||
graphics.moveTo(a[0], a[1]).lineTo(b[0], b[1]).stroke({ width: width + 6, color: 0x7ee787, alpha: 0.25 })
|
||||
}
|
||||
if (open) {
|
||||
// An open door leaves a gap; the schema keeps the record, the GM sees where it was.
|
||||
dashedLine(graphics, a, b, width, color, 8, 8, 0.55)
|
||||
} else if (wall.switches.secret) {
|
||||
dashedLine(graphics, a, b, width, color, 3, 5, alpha)
|
||||
} else {
|
||||
graphics.moveTo(a[0], a[1]).lineTo(b[0], b[1]).stroke({ width, color, alpha })
|
||||
}
|
||||
|
||||
// Endpoint handles while selected: the two authoring points, never moved in round 1.
|
||||
if (selected) {
|
||||
for (const point of [a, b]) {
|
||||
graphics.circle(point[0], point[1], 5).fill(0x0b0b0d).stroke({ width: 2, color: 0x7ee787 })
|
||||
}
|
||||
}
|
||||
|
||||
// Story 50: the one-way arrow at the wall's middle, toward the blind side.
|
||||
const direction = arrowVector(a, b, wall.switches.sightDir)
|
||||
if (direction) {
|
||||
const [mx, my] = wallMidpoint(a, b)
|
||||
const tip: Vec2 = [mx + direction[0] * 22, my + direction[1] * 22]
|
||||
const back: Vec2 = [mx - direction[0] * 8, my - direction[1] * 8]
|
||||
const px = -direction[1]
|
||||
const py = direction[0]
|
||||
graphics
|
||||
.moveTo(back[0], back[1])
|
||||
.lineTo(tip[0], tip[1])
|
||||
.stroke({ width: 3, color: 0xfff3c4, alpha: 0.95 })
|
||||
graphics
|
||||
.moveTo(tip[0], tip[1])
|
||||
.lineTo(tip[0] - direction[0] * 9 + px * 6, tip[1] - direction[1] * 9 + py * 6)
|
||||
.lineTo(tip[0] - direction[0] * 9 - px * 6, tip[1] - direction[1] * 9 - py * 6)
|
||||
.closePath()
|
||||
.fill(0xfff3c4)
|
||||
}
|
||||
|
||||
// Story 48: the GM sees the marker switch. A marked window is the only wall a player learns about.
|
||||
if (wall.switches.playerMarker) {
|
||||
const [mx, my] = wallMidpoint(a, b)
|
||||
if (wall.kind === 'window') {
|
||||
graphics.circle(mx, my, 6).fill(0xffcc33).stroke({ width: 2, color: 0x2b1d00 })
|
||||
} else {
|
||||
graphics.circle(mx, my, 5).stroke({ width: 2, color: 0xffcc33, alpha: 0.7 })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const renderModule: RenderModule = {
|
||||
name: 'walls',
|
||||
mount({ app, layers, store }: RenderContext): () => void {
|
||||
const canvas = app.canvas
|
||||
const host = document.querySelector<HTMLElement>('#panels')
|
||||
const panel = host ? mountWallPanel(host, event => store.dispatch(event)) : null
|
||||
const container = new Container()
|
||||
layers.gm.addChild(container)
|
||||
const preview = new Graphics()
|
||||
container.addChild(preview)
|
||||
|
||||
const nodes = new Map<number, WallNode>()
|
||||
let hover: Vec2 | null = null
|
||||
let down: { x: number; y: number; pointerId: number } | null = null
|
||||
|
||||
function worldOf(event: PointerEvent): Vec2 {
|
||||
const rect = canvas.getBoundingClientRect()
|
||||
const local = layers.gm.toLocal({ x: event.clientX - rect.left, y: event.clientY - rect.top })
|
||||
return [local.x, local.y]
|
||||
}
|
||||
|
||||
function zoom(): number {
|
||||
const scale = Math.abs(layers.gm.worldTransform.a)
|
||||
return scale > 0 ? scale : 1
|
||||
}
|
||||
|
||||
function drawPreview(): void {
|
||||
preview.clear()
|
||||
if (!panel?.armed || panel.first === null) return
|
||||
const a = panel.first
|
||||
const b = hover ?? a
|
||||
preview
|
||||
.moveTo(a[0], a[1])
|
||||
.lineTo(b[0], b[1])
|
||||
.stroke({ width: 2, color: 0x7ee787, alpha: 0.8 })
|
||||
preview.circle(a[0], a[1], 4).fill(0x7ee787)
|
||||
preview.circle(b[0], b[1], 3).stroke({ width: 2, color: 0x7ee787 })
|
||||
}
|
||||
|
||||
function renderWalls(): void {
|
||||
const state = store.state
|
||||
const selected = selectedWallId(state)
|
||||
const walls = wallsOf(state)
|
||||
const seen = new Set<number>()
|
||||
for (const wall of walls) {
|
||||
seen.add(wall.id)
|
||||
const sig = wallSignature(wall, wall.id === selected)
|
||||
let node = nodes.get(wall.id)
|
||||
if (!node) {
|
||||
const graphics = new Graphics()
|
||||
const wallContainer = new Container()
|
||||
wallContainer.addChild(graphics)
|
||||
container.addChild(wallContainer)
|
||||
node = { container: wallContainer, graphics, sig: '' }
|
||||
nodes.set(wall.id, node)
|
||||
}
|
||||
if (node.sig !== sig) {
|
||||
drawWall(node.graphics, wall, wall.id === selected)
|
||||
node.sig = sig
|
||||
}
|
||||
}
|
||||
for (const [id, node] of nodes) {
|
||||
if (seen.has(id)) continue
|
||||
container.removeChild(node.container)
|
||||
node.container.destroy({ children: true })
|
||||
nodes.delete(id)
|
||||
}
|
||||
}
|
||||
|
||||
function publish(): void {
|
||||
const state = store.state
|
||||
const walls = wallsOf(state)
|
||||
const selected = selectedWallId(state)
|
||||
const dataset = canvas.dataset
|
||||
dataset['walls'] = String(walls.length)
|
||||
dataset['wallKinds'] = walls.map(wall => `${wall.id}:${wall.kind}`).join(' ')
|
||||
dataset['wallSelected'] = selected === null ? '' : String(selected)
|
||||
dataset['wallArrows'] = walls
|
||||
.filter(wall => wall.switches.sightDir !== 'both')
|
||||
.map(wall => `${wall.id}:${wall.switches.sightDir}`)
|
||||
.join(' ')
|
||||
dataset['wallMarkers'] = walls
|
||||
.filter(wall => wall.switches.playerMarker)
|
||||
.map(wall => String(wall.id))
|
||||
.join(' ')
|
||||
dataset['wallDraw'] = panel?.armed ? (panel.first === null ? 'first' : 'second') : 'off'
|
||||
dataset['wallPreview'] = panel?.first ? panel.first.join(',') : ''
|
||||
dataset['wallUndo'] = undoOf(state) === null ? 'no' : 'yes'
|
||||
}
|
||||
|
||||
function sync(): void {
|
||||
renderWalls()
|
||||
drawPreview()
|
||||
publish()
|
||||
}
|
||||
|
||||
function onPointerDown(event: PointerEvent): void {
|
||||
if (event.button !== 0 || !event.isPrimary || event.target !== canvas) return
|
||||
const state = store.state
|
||||
if (state.connection.phase !== 'live' || state.session.role !== 'gm' || !panel) return
|
||||
if (panel.armed) {
|
||||
// Drawing takes precedence over pan: consume the gesture and feed the point.
|
||||
event.preventDefault()
|
||||
event.stopImmediatePropagation()
|
||||
hover = worldOf(event)
|
||||
panel.drawPoint(hover)
|
||||
sync()
|
||||
return
|
||||
}
|
||||
down = { x: event.clientX, y: event.clientY, pointerId: event.pointerId }
|
||||
}
|
||||
|
||||
function onPointerMove(event: PointerEvent): void {
|
||||
if (!panel?.armed) return
|
||||
// A token drag owns its gesture (#72); do not paint a wall preview under it.
|
||||
if (dragOf(store.state) !== null) return
|
||||
if (!event.isPrimary) return
|
||||
hover = worldOf(event)
|
||||
drawPreview()
|
||||
}
|
||||
|
||||
function onPointerUp(event: PointerEvent): void {
|
||||
const start = down
|
||||
down = null
|
||||
if (!panel || panel.armed) return
|
||||
if (!start || start.pointerId !== event.pointerId) return
|
||||
if (event.target !== canvas) return
|
||||
// A moved pointer was a pan (#69), not a click on a wall.
|
||||
if (Math.hypot(event.clientX - start.x, event.clientY - start.y) > 5) return
|
||||
if (store.state.session.role !== 'gm') return
|
||||
const point = worldOf(event)
|
||||
const tolerance = 8 / zoom()
|
||||
let hit: WallView | null = null
|
||||
let best = tolerance
|
||||
for (const wall of wallsOf(store.state)) {
|
||||
const distance = distanceToSegment(point, wall.a, wall.b)
|
||||
if (distance <= best) {
|
||||
best = distance
|
||||
hit = wall
|
||||
}
|
||||
}
|
||||
store.dispatch({ type: 'wall-select', id: hit?.id ?? null })
|
||||
}
|
||||
|
||||
function onCancel(): void {
|
||||
down = null
|
||||
}
|
||||
|
||||
function onKey(event: KeyboardEvent): void {
|
||||
if (event.key !== 'Escape' || !panel?.armed) return
|
||||
panel.cancelDraw()
|
||||
hover = null
|
||||
sync()
|
||||
}
|
||||
|
||||
const unsubscribe = store.subscribe(() => {
|
||||
panel?.render(store.state)
|
||||
sync()
|
||||
})
|
||||
panel?.render(store.state)
|
||||
sync()
|
||||
|
||||
window.addEventListener('pointerdown', onPointerDown, true)
|
||||
window.addEventListener('pointermove', onPointerMove, true)
|
||||
window.addEventListener('pointerup', onPointerUp, true)
|
||||
window.addEventListener('pointercancel', onCancel, true)
|
||||
window.addEventListener('blur', onCancel)
|
||||
window.addEventListener('keydown', onKey)
|
||||
|
||||
return () => {
|
||||
unsubscribe()
|
||||
window.removeEventListener('pointerdown', onPointerDown, true)
|
||||
window.removeEventListener('pointermove', onPointerMove, true)
|
||||
window.removeEventListener('pointerup', onPointerUp, true)
|
||||
window.removeEventListener('pointercancel', onCancel, true)
|
||||
window.removeEventListener('blur', onCancel)
|
||||
window.removeEventListener('keydown', onKey)
|
||||
panel?.destroy()
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
// GM wall slice (T10, #73; DESIGN 6.1 `walls`/`wall`/`wall_gone`, 5.8, 7.4). Append-only
|
||||
// registration: adding this file was enough; the reducer's glob picked it up and `hello` resets it
|
||||
// with every other slice.
|
||||
//
|
||||
// Wall records are GM-only on the wire (3.1). A player connection never receives these frames and a
|
||||
// player-shaped frame is ignored here too, so a bug on the server side could not quietly turn this
|
||||
// client into a wall-data renderer. The slice keeps the server's typed record plus the editor's
|
||||
// selection and its single-step undo descriptor; it never derives or invents a wall field.
|
||||
|
||||
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
|
||||
import type { Vec2 } from '../protocol.ts'
|
||||
import type {
|
||||
SightDir,
|
||||
WallKind,
|
||||
WallPosition,
|
||||
WallRestore,
|
||||
WallSwitches,
|
||||
WallUndo,
|
||||
} from '../wallEditor.ts'
|
||||
import { deriveKind } from '../wallEditor.ts'
|
||||
|
||||
export interface WallView {
|
||||
id: number
|
||||
scene: number
|
||||
a: Vec2
|
||||
b: Vec2
|
||||
thickness: number
|
||||
position: WallPosition
|
||||
height: number | null
|
||||
kind: WallKind
|
||||
switches: WallSwitches
|
||||
label: string | null
|
||||
flags: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface WallsState {
|
||||
byId: Record<number, WallView>
|
||||
order: number[]
|
||||
/** The wall selected in the GM editor, or null. */
|
||||
selectedId: number | null
|
||||
/** The inverse of the last successful edit; single-step undo (story 52). */
|
||||
undo: WallUndo | null
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
function own(record: Record<string, unknown>, key: string): unknown {
|
||||
return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined
|
||||
}
|
||||
|
||||
function isVec2(value: unknown): value is Vec2 {
|
||||
return (
|
||||
Array.isArray(value) &&
|
||||
value.length === 2 &&
|
||||
typeof value[0] === 'number' &&
|
||||
Number.isFinite(value[0]) &&
|
||||
typeof value[1] === 'number' &&
|
||||
Number.isFinite(value[1])
|
||||
)
|
||||
}
|
||||
|
||||
function isPosition(value: unknown): value is WallPosition {
|
||||
return value === 'center' || value === 'left' || value === 'right'
|
||||
}
|
||||
|
||||
function isSightDir(value: unknown): value is SightDir {
|
||||
return value === 'both' || value === 'left' || value === 'right'
|
||||
}
|
||||
|
||||
function isKind(value: unknown): value is WallKind {
|
||||
return value === 'wall' || value === 'door' || value === 'window' || value === 'one_way' || value === 'custom'
|
||||
}
|
||||
|
||||
function bool(value: unknown): boolean {
|
||||
return value === true
|
||||
}
|
||||
|
||||
function optionalLabel(value: unknown): string | null {
|
||||
return typeof value === 'string' ? value : null
|
||||
}
|
||||
|
||||
function flagObject(value: unknown): Record<string, unknown> {
|
||||
return isRecord(value) ? value : {}
|
||||
}
|
||||
|
||||
/**
|
||||
* One GM `wall` frame (the same shape inside `walls`) as the editor stores it, or null when the
|
||||
* frame cannot be that shape. `kind` is the server's derived label; an absent one is derived from
|
||||
* the switches so an older-shaped frame still shows a label.
|
||||
*/
|
||||
export function wallViewFromFrame(frame: Record<string, unknown>): WallView | null {
|
||||
const id = frame['id']
|
||||
const scene = frame['scene']
|
||||
const a = frame['a']
|
||||
const b = frame['b']
|
||||
const thickness = frame['thickness']
|
||||
const position = frame['position']
|
||||
const sightDir = frame['sight_dir']
|
||||
if (typeof id !== 'number' || !Number.isInteger(id) || id <= 0) return null
|
||||
if (typeof scene !== 'number' || !Number.isInteger(scene)) return null
|
||||
if (!isVec2(a) || !isVec2(b)) return null
|
||||
if (typeof thickness !== 'number' || !Number.isFinite(thickness)) return null
|
||||
if (!isPosition(position) || !isSightDir(sightDir)) return null
|
||||
const switches: WallSwitches = {
|
||||
blocksSight: bool(frame['blocks_sight']),
|
||||
blocksMovement: bool(frame['blocks_movement']),
|
||||
sightDir,
|
||||
playerMarker: bool(frame['player_marker']),
|
||||
door: bool(frame['door']),
|
||||
open: bool(frame['open']),
|
||||
secret: bool(frame['secret']),
|
||||
locked: bool(frame['locked']),
|
||||
}
|
||||
const height = frame['height']
|
||||
const kind = own(frame, 'kind')
|
||||
const label = own(frame, 'label')
|
||||
return {
|
||||
id,
|
||||
scene,
|
||||
a: [a[0], a[1]],
|
||||
b: [b[0], b[1]],
|
||||
thickness,
|
||||
position,
|
||||
height: typeof height === 'number' && Number.isFinite(height) ? height : null,
|
||||
kind: isKind(kind) ? kind : deriveKind(switches),
|
||||
switches,
|
||||
label: optionalLabel(label),
|
||||
flags: flagObject(frame['flags']),
|
||||
}
|
||||
}
|
||||
|
||||
function upsert(state: WallsState, wall: WallView): void {
|
||||
if (state.byId[wall.id] === undefined) state.order = [...state.order, wall.id]
|
||||
state.byId = { ...state.byId, [wall.id]: wall }
|
||||
}
|
||||
|
||||
function remove(state: WallsState, id: number): void {
|
||||
if (state.byId[id] === undefined) return
|
||||
const byId = { ...state.byId }
|
||||
delete byId[id]
|
||||
state.byId = byId
|
||||
state.order = state.order.filter(entry => entry !== id)
|
||||
if (state.selectedId === id) state.selectedId = null
|
||||
}
|
||||
|
||||
/** The editor's restore payload for one wall: everything `wall.add` needs to bring it back. */
|
||||
export function restoreOf(wall: WallView): WallRestore {
|
||||
return {
|
||||
a: [wall.a[0], wall.a[1]],
|
||||
b: [wall.b[0], wall.b[1]],
|
||||
thickness: wall.thickness,
|
||||
position: wall.position,
|
||||
height: wall.height,
|
||||
switches: { ...wall.switches },
|
||||
label: wall.label,
|
||||
flags: { ...wall.flags },
|
||||
}
|
||||
}
|
||||
|
||||
export const slice: Slice<WallsState> = {
|
||||
name: 'walls',
|
||||
init: () => ({ byId: {}, order: [], selectedId: null, undo: null }),
|
||||
reduce(state: WallsState, event: ReducerEvent, root: RootState): void {
|
||||
if (event.type === 'wall-select') {
|
||||
state.selectedId = event.id
|
||||
return
|
||||
}
|
||||
if (event.type === 'wall-record-undo') {
|
||||
state.undo = event.undo
|
||||
return
|
||||
}
|
||||
if (event.type !== 'frame') return
|
||||
const frame = event.frame
|
||||
// Wall data is GM-only (DESIGN 3.1); never accept it on a player-shaped session.
|
||||
if (root.session.role !== 'gm') return
|
||||
if (frame.t === 'walls') {
|
||||
const list = frame['walls']
|
||||
if (!Array.isArray(list)) return
|
||||
const byId: Record<number, WallView> = {}
|
||||
const order: number[] = []
|
||||
for (const entry of list) {
|
||||
if (!isRecord(entry)) continue
|
||||
const wall = wallViewFromFrame(entry)
|
||||
if (!wall) continue
|
||||
byId[wall.id] = wall
|
||||
order.push(wall.id)
|
||||
}
|
||||
state.byId = byId
|
||||
state.order = order
|
||||
if (state.selectedId !== null && byId[state.selectedId] === undefined) {
|
||||
state.selectedId = null
|
||||
}
|
||||
return
|
||||
}
|
||||
if (frame.t === 'wall') {
|
||||
const wall = wallViewFromFrame(frame)
|
||||
if (wall) upsert(state, wall)
|
||||
return
|
||||
}
|
||||
if (frame.t === 'wall_gone') {
|
||||
const id = frame['id']
|
||||
if (typeof id === 'number' && Number.isInteger(id)) remove(state, id)
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
/** Every wall the GM's connection knows, in the server's id order. */
|
||||
export function wallsOf(state: RootState): WallView[] {
|
||||
const walls = state.slices['walls'] as WallsState | undefined
|
||||
if (!walls) return []
|
||||
return walls.order
|
||||
.map(id => walls.byId[id])
|
||||
.filter((wall): wall is WallView => wall !== undefined)
|
||||
}
|
||||
|
||||
export function wallOf(state: RootState, id: number): WallView | null {
|
||||
const walls = state.slices['walls'] as WallsState | undefined
|
||||
if (!walls) return null
|
||||
return walls.byId[id] ?? null
|
||||
}
|
||||
|
||||
export function selectedWallId(state: RootState): number | null {
|
||||
return (state.slices['walls'] as WallsState | undefined)?.selectedId ?? null
|
||||
}
|
||||
|
||||
export function selectedWallOf(state: RootState): WallView | null {
|
||||
const id = selectedWallId(state)
|
||||
return id === null ? null : wallOf(state, id)
|
||||
}
|
||||
|
||||
export function undoOf(state: RootState): WallUndo | null {
|
||||
return (state.slices['walls'] as WallsState | undefined)?.undo ?? null
|
||||
}
|
||||
@@ -424,3 +424,110 @@ body {
|
||||
#gm-seen-hint {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
/* GM wall editor (T10, #73): draw presets, the selected wall's round-1 fields and single-step undo,
|
||||
in the same right-hand column. Hidden and inert for players exactly like the other GM panels. */
|
||||
#gm-walls {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin-top: 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-walls h2,
|
||||
#gm-walls h3 {
|
||||
margin: 0;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
#gm-walls h2 {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
#gm-walls h3 {
|
||||
font-size: 12px;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
#wall-presets {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin: 4px 0;
|
||||
}
|
||||
|
||||
#gm-walls button {
|
||||
font: inherit;
|
||||
padding: 2px 6px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #666;
|
||||
background: #222;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
#gm-walls button[aria-pressed='true'] {
|
||||
outline: 1px solid #7ee787;
|
||||
background: #1d3322;
|
||||
}
|
||||
|
||||
#gm-walls button:disabled {
|
||||
opacity: 0.45;
|
||||
}
|
||||
|
||||
#gm-walls input,
|
||||
#gm-walls select {
|
||||
font: inherit;
|
||||
padding: 3px 5px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid #555;
|
||||
background: #111;
|
||||
color: inherit;
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
#gm-walls input[type='checkbox'] {
|
||||
width: auto;
|
||||
}
|
||||
|
||||
#wall-selected,
|
||||
#wall-advanced {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
margin: 6px 0;
|
||||
}
|
||||
|
||||
#wall-selected label,
|
||||
#wall-advanced label {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
#wall-kind {
|
||||
color: #7ee787;
|
||||
}
|
||||
|
||||
#wall-hint,
|
||||
#wall-drawing,
|
||||
#wall-kind-hint {
|
||||
margin: 2px 0;
|
||||
opacity: 0.7;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
#wall-hint-locked {
|
||||
margin: 4px 0 0;
|
||||
color: #e3b341;
|
||||
}
|
||||
|
||||
#wall-error {
|
||||
margin: 4px 0 0;
|
||||
color: #ff8a8a;
|
||||
word-break: break-word;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
// The wall editor's pure half (T10, #73; DESIGN 5.8, 6.1 wall payloads, 7.4 GM editor). No Pixi, no
|
||||
// DOM, no socket: presets and derived kinds, the preset-XOR-raw payload rules, local validation
|
||||
// before an intent leaves the client, grid/endpoint snapping, the one-way arrow side and the undo
|
||||
// intent. `slices/walls.ts` holds the server's wall records; this module turns editor state into
|
||||
// exactly the fields DESIGN 6.1 accepts.
|
||||
//
|
||||
// Round 1 deliberately has no thickness, height or position control (ADR-0012, spec #63 decision 3):
|
||||
// the geometry fields stay at the server defaults and `open` is never a `wall.update` patch field
|
||||
// (it belongs to `door.set`, 6.1 FIXED #49).
|
||||
|
||||
import type { Vec2 } from './protocol.ts'
|
||||
|
||||
export type WallPreset = 'wall' | 'door' | 'window' | 'one_way'
|
||||
export type WallKind = 'wall' | 'door' | 'window' | 'one_way' | 'custom'
|
||||
export type SightDir = 'both' | 'left' | 'right'
|
||||
export type WallPosition = 'center' | 'left' | 'right'
|
||||
|
||||
/** The v1 switches (DESIGN 5.8, 6.1). `open` is a stored door state, not a switch patch. */
|
||||
export interface WallSwitches {
|
||||
blocksSight: boolean
|
||||
blocksMovement: boolean
|
||||
sightDir: SightDir
|
||||
playerMarker: boolean
|
||||
door: boolean
|
||||
open: boolean
|
||||
secret: boolean
|
||||
locked: boolean
|
||||
}
|
||||
|
||||
export const PRESETS: readonly WallPreset[] = ['wall', 'door', 'window', 'one_way']
|
||||
|
||||
/**
|
||||
* The four preset expansions of DESIGN 5.8's table. `window` is the opening form: see-through while
|
||||
* closed, passable once opened, and it is the only preset that turns `player_marker` on. A preset
|
||||
* never implies thickness, position or height (6.1).
|
||||
*/
|
||||
export function presetSwitches(preset: WallPreset): WallSwitches {
|
||||
switch (preset) {
|
||||
case 'door':
|
||||
return {
|
||||
blocksSight: true,
|
||||
blocksMovement: true,
|
||||
sightDir: 'both',
|
||||
playerMarker: false,
|
||||
door: true,
|
||||
open: false,
|
||||
secret: false,
|
||||
locked: false,
|
||||
}
|
||||
case 'window':
|
||||
return {
|
||||
blocksSight: false,
|
||||
blocksMovement: true,
|
||||
sightDir: 'both',
|
||||
playerMarker: true,
|
||||
door: true,
|
||||
open: false,
|
||||
secret: false,
|
||||
locked: false,
|
||||
}
|
||||
case 'one_way':
|
||||
return {
|
||||
blocksSight: true,
|
||||
blocksMovement: true,
|
||||
sightDir: 'left',
|
||||
playerMarker: false,
|
||||
door: false,
|
||||
open: false,
|
||||
secret: false,
|
||||
locked: false,
|
||||
}
|
||||
case 'wall':
|
||||
return {
|
||||
blocksSight: true,
|
||||
blocksMovement: true,
|
||||
sightDir: 'both',
|
||||
playerMarker: false,
|
||||
door: false,
|
||||
open: false,
|
||||
secret: false,
|
||||
locked: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The 5.8 derived shape label: output only, never stored and never accepted as input. */
|
||||
export function deriveKind(switches: WallSwitches): WallKind {
|
||||
if (!switches.blocksSight && switches.blocksMovement) return 'window'
|
||||
if (switches.blocksSight && switches.sightDir !== 'both') return 'one_way'
|
||||
if (switches.blocksSight && switches.blocksMovement && switches.door) return 'door'
|
||||
if (
|
||||
switches.blocksSight &&
|
||||
switches.blocksMovement &&
|
||||
!switches.door &&
|
||||
switches.sightDir === 'both'
|
||||
) {
|
||||
return 'wall'
|
||||
}
|
||||
return 'custom'
|
||||
}
|
||||
|
||||
export function flipSightDir(sightDir: SightDir): SightDir {
|
||||
if (sightDir === 'left') return 'right'
|
||||
if (sightDir === 'right') return 'left'
|
||||
return 'both'
|
||||
}
|
||||
|
||||
/**
|
||||
* The direction the GM's one-way arrow points: from the seeing side toward the watched (blind)
|
||||
* side. `sight_dir` names the BLIND side (GLOSSARY "Blind side", DESIGN 5.8): `left` is the
|
||||
* `(-dy, dx)` normal of `a -> b`. Null for a two-way wall (no arrow).
|
||||
*/
|
||||
export function arrowVector(a: Vec2, b: Vec2, sightDir: SightDir): Vec2 | null {
|
||||
if (sightDir === 'both') return null
|
||||
const dx = b[0] - a[0]
|
||||
const dy = b[1] - a[1]
|
||||
const length = Math.hypot(dx, dy)
|
||||
if (!(length > 0)) return null
|
||||
if (sightDir === 'left') return normalize([-dy, dx])
|
||||
return normalize([dy, -dx])
|
||||
}
|
||||
|
||||
function normalize([x, y]: Vec2): Vec2 {
|
||||
const length = Math.hypot(x, y)
|
||||
if (!(length > 0)) return [0, 0]
|
||||
return [x / length === 0 ? 0 : x / length, y / length === 0 ? 0 : y / length]
|
||||
}
|
||||
|
||||
/** The arrow's midpoint: the wall's drawn midpoint, the same anchor a player marker uses (5.8). */
|
||||
export function wallMidpoint(a: Vec2, b: Vec2): Vec2 {
|
||||
return [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2]
|
||||
}
|
||||
|
||||
export interface SnapOptions {
|
||||
enabled: boolean
|
||||
gridSize: number
|
||||
endpoints: readonly Vec2[]
|
||||
/** Endpoint snap radius in world px; it wins over the grid when both are in reach. */
|
||||
threshold: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Story 45: optional grid and endpoint snap while drawing. Endpoint snap is tried first (the GM is
|
||||
* extending a wall), then the grid; disabled means the raw pointer position. Values stay in world
|
||||
* px and are clamped by the caller to the scene.
|
||||
*/
|
||||
export function snapPoint(point: Vec2, options: SnapOptions): Vec2 {
|
||||
if (!options.enabled) return [point[0], point[1]]
|
||||
let best: Vec2 | null = null
|
||||
let bestDistance = options.threshold
|
||||
for (const endpoint of options.endpoints) {
|
||||
const distance = Math.hypot(endpoint[0] - point[0], endpoint[1] - point[1])
|
||||
if (distance <= bestDistance) {
|
||||
bestDistance = distance
|
||||
best = endpoint
|
||||
}
|
||||
}
|
||||
if (best) return [best[0], best[1]]
|
||||
const size = options.gridSize
|
||||
if (!(size > 0)) return [point[0], point[1]]
|
||||
return [Math.round(point[0] / size) * size, Math.round(point[1] / size) * size]
|
||||
}
|
||||
|
||||
/** Distance from a point to a segment, for choosing the wall under a click. */
|
||||
export function distanceToSegment(point: Vec2, a: Vec2, b: Vec2): number {
|
||||
const dx = b[0] - a[0]
|
||||
const dy = b[1] - a[1]
|
||||
const lengthSq = dx * dx + dy * dy
|
||||
if (lengthSq <= 0) return Math.hypot(point[0] - a[0], point[1] - a[1])
|
||||
let t = ((point[0] - a[0]) * dx + (point[1] - a[1]) * dy) / lengthSq
|
||||
t = Math.min(1, Math.max(0, t))
|
||||
return Math.hypot(point[0] - (a[0] + t * dx), point[1] - (a[1] + t * dy))
|
||||
}
|
||||
|
||||
/** DESIGN 6.5's text rule for a wall label: 1..64 code points, trimmed, no control characters. */
|
||||
export function validateLabel(label: string): string | null {
|
||||
const trimmed = label.trim()
|
||||
if (trimmed.length === 0) return null
|
||||
if ([...trimmed].length > 64) return 'The label must be at most 64 characters.'
|
||||
if (/[\u0000-\u001f\u007f]/.test(trimmed)) return 'The label cannot contain control characters.'
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* The server's 5.8/6.1 switch rules, checked before an intent leaves the client so the editor can
|
||||
* show the reason. The server remains the validator; this is the same rule read locally.
|
||||
*/
|
||||
export function validateSwitches(switches: WallSwitches): string | null {
|
||||
if (!switches.blocksSight && switches.sightDir !== 'both') {
|
||||
return 'invalid: a sight direction needs blocks_sight.'
|
||||
}
|
||||
if ((switches.open || switches.secret || switches.locked) && !switches.door) {
|
||||
return 'invalid: open, secret and locked need a door.'
|
||||
}
|
||||
if (switches.secret) {
|
||||
if (switches.open) return 'invalid: a secret door is always closed.'
|
||||
if (switches.sightDir !== 'both') return 'invalid: a secret door is always two-way.'
|
||||
if (!switches.blocksSight || !switches.blocksMovement) {
|
||||
return 'invalid: a secret door is opaque and solid.'
|
||||
}
|
||||
}
|
||||
if (switches.open && switches.locked) return 'invalid: a locked door cannot open.'
|
||||
return null
|
||||
}
|
||||
|
||||
/** What a preset payload or a raw-switch payload carries; never both (6.1, preset XOR raw). */
|
||||
export interface WallPayload {
|
||||
/** A preset name, or null for the raw switches. */
|
||||
preset: WallPreset | null
|
||||
switches: WallSwitches
|
||||
/** `undefined` leaves it alone; `null` clears it; a string sets it. */
|
||||
label?: string | null
|
||||
}
|
||||
|
||||
function labelFields(label: string | null | undefined): Record<string, unknown> {
|
||||
return label === undefined ? {} : { label }
|
||||
}
|
||||
|
||||
/**
|
||||
* `wall.add` fields for the editor's one-drag default. A preset payload carries ONLY `preset` (plus
|
||||
* the label): no raw switch may sit beside it, `open:false` included (DESIGN 6.1 FIXED #49). A raw
|
||||
* payload names every switch; `wall.add` accepts `open` on a new door.
|
||||
*/
|
||||
export function buildAddFields(
|
||||
scene: number,
|
||||
a: Vec2,
|
||||
b: Vec2,
|
||||
payload: WallPayload,
|
||||
): Record<string, unknown> {
|
||||
const label = payload.label === null || payload.label === undefined ? {} : { label: payload.label }
|
||||
if (payload.preset !== null) {
|
||||
return { scene, a: [a[0], a[1]], b: [b[0], b[1]], preset: payload.preset, ...label }
|
||||
}
|
||||
const s = payload.switches
|
||||
return {
|
||||
scene,
|
||||
a: [a[0], a[1]],
|
||||
b: [b[0], b[1]],
|
||||
blocks_sight: s.blocksSight,
|
||||
blocks_movement: s.blocksMovement,
|
||||
sight_dir: s.sightDir,
|
||||
player_marker: s.playerMarker,
|
||||
door: s.door,
|
||||
open: s.open,
|
||||
secret: s.secret,
|
||||
locked: s.locked,
|
||||
...label,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `wall.update` fields. `open` is not a patch field (it belongs to `door.set`): even an editor that
|
||||
* holds a full switch set must drop it here. A preset replaces the whole switch set; a raw patch
|
||||
* names every switch it holds except `open`.
|
||||
*/
|
||||
export function buildUpdateFields(id: number, payload: WallPayload): Record<string, unknown> {
|
||||
const label = labelFields(payload.label)
|
||||
if (payload.preset !== null) return { id, preset: payload.preset, ...label }
|
||||
const s = payload.switches
|
||||
return {
|
||||
id,
|
||||
blocks_sight: s.blocksSight,
|
||||
blocks_movement: s.blocksMovement,
|
||||
sight_dir: s.sightDir,
|
||||
player_marker: s.playerMarker,
|
||||
door: s.door,
|
||||
secret: s.secret,
|
||||
locked: s.locked,
|
||||
...label,
|
||||
}
|
||||
}
|
||||
|
||||
/** `door.set` is the only way to open or close a door (6.1): `open` is a door intent, not a patch. */
|
||||
export function buildDoorFields(scene: number, id: number, open: boolean): Record<string, unknown> {
|
||||
return { scene, id, open }
|
||||
}
|
||||
|
||||
/** The restore payload for undoing a delete: the whole wall, switches and label included. */
|
||||
export interface WallRestore {
|
||||
a: Vec2
|
||||
b: Vec2
|
||||
thickness: number
|
||||
position: WallPosition
|
||||
height: number | null
|
||||
switches: WallSwitches
|
||||
label: string | null
|
||||
flags: Record<string, unknown>
|
||||
}
|
||||
|
||||
export type WallUndo =
|
||||
| { kind: 'remove'; id: number }
|
||||
| { kind: 'restore'; wall: WallRestore }
|
||||
| { kind: 'update'; id: number; switches: WallSwitches; label: string | null; flags: Record<string, unknown> }
|
||||
| { kind: 'door'; id: number; open: boolean }
|
||||
|
||||
/** The inverse intent of the last edit, or null when there is nothing to undo. */
|
||||
export function undoIntent(
|
||||
scene: number,
|
||||
undo: WallUndo | null,
|
||||
): { t: string; fields: Record<string, unknown> } | null {
|
||||
if (undo === null) return null
|
||||
switch (undo.kind) {
|
||||
case 'remove':
|
||||
return { t: 'wall.remove', fields: { scene, id: undo.id } }
|
||||
case 'restore': {
|
||||
const wall = undo.wall
|
||||
return {
|
||||
t: 'wall.add',
|
||||
fields: {
|
||||
scene,
|
||||
a: [wall.a[0], wall.a[1]],
|
||||
b: [wall.b[0], wall.b[1]],
|
||||
thickness: wall.thickness,
|
||||
position: wall.position,
|
||||
height: wall.height,
|
||||
blocks_sight: wall.switches.blocksSight,
|
||||
blocks_movement: wall.switches.blocksMovement,
|
||||
sight_dir: wall.switches.sightDir,
|
||||
player_marker: wall.switches.playerMarker,
|
||||
door: wall.switches.door,
|
||||
open: wall.switches.open,
|
||||
secret: wall.switches.secret,
|
||||
locked: wall.switches.locked,
|
||||
label: wall.label,
|
||||
flags: wall.flags,
|
||||
},
|
||||
}
|
||||
}
|
||||
case 'update':
|
||||
return {
|
||||
t: 'wall.update',
|
||||
fields: {
|
||||
...buildUpdateFields(undo.id, {
|
||||
preset: null,
|
||||
switches: undo.switches,
|
||||
label: undo.label,
|
||||
}),
|
||||
flags: undo.flags,
|
||||
},
|
||||
}
|
||||
case 'door':
|
||||
return { t: 'door.set', fields: buildDoorFields(scene, undo.id, undo.open) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
// T10 (#73): the wall slice and the wall editor's pure rules are the reducer seam. Server GM frames
|
||||
// in, the wall view out; presets expand to the 5.8 table; `kind` is derived in the fixed order; the
|
||||
// one-way arrow points at the blind side; a payload is preset XOR raw, and `open` never rides in a
|
||||
// `wall.update`. No DOM, no Pixi, 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 { Vec2 } from '../src/protocol.ts'
|
||||
import { selectedWallId, wallOf, wallsOf } from '../src/slices/walls.ts'
|
||||
import type { SightDir, WallPreset, WallSwitches } from '../src/wallEditor.ts'
|
||||
import {
|
||||
PRESETS,
|
||||
arrowVector,
|
||||
buildAddFields,
|
||||
buildDoorFields,
|
||||
buildUpdateFields,
|
||||
deriveKind,
|
||||
flipSightDir,
|
||||
presetSwitches,
|
||||
snapPoint,
|
||||
undoIntent,
|
||||
validateLabel,
|
||||
validateSwitches,
|
||||
} from '../src/wallEditor.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, role: 'gm' | 'player' = 'gm'): ReducerEvent =>
|
||||
frame({
|
||||
t: 'hello',
|
||||
n,
|
||||
proto: 2,
|
||||
role,
|
||||
me: { id: role === 'gm' ? 1 : 2, name: role === 'gm' ? 'GM' : 'Ann' },
|
||||
...(role === 'player' ? {} : { scene: { id: 1, name: 'S', w: 4096, h: 4096, tile_size: 32, cell: 32, grid_size: 32, vision_radius_default: 300, token_radius_default: 20, art_version: 1 } }),
|
||||
})
|
||||
|
||||
const wallBody = (id: number, overrides: Record<string, unknown> = {}): Record<string, unknown> => ({
|
||||
id,
|
||||
scene: 1,
|
||||
a: [100, 100],
|
||||
b: [300, 100],
|
||||
thickness: 0,
|
||||
position: 'center',
|
||||
height: null,
|
||||
kind: 'wall',
|
||||
blocks_sight: true,
|
||||
blocks_movement: true,
|
||||
sight_dir: 'both',
|
||||
player_marker: false,
|
||||
door: false,
|
||||
open: false,
|
||||
secret: false,
|
||||
locked: false,
|
||||
label: null,
|
||||
flags: {},
|
||||
...overrides,
|
||||
})
|
||||
|
||||
const run = (...events: ReducerEvent[]): RootState =>
|
||||
events.reduce((state, event) => reduce(state, event), initialState())
|
||||
|
||||
const switches = (overrides: Partial<WallSwitches> = {}): WallSwitches => ({
|
||||
...presetSwitches('wall'),
|
||||
...overrides,
|
||||
})
|
||||
|
||||
describe('wall slice (DESIGN 6.1, GM only)', () => {
|
||||
it('loads the walls snapshot, upserts a wall and removes one', () => {
|
||||
const state = run(
|
||||
{ type: 'connecting' },
|
||||
hello(1),
|
||||
frame({ t: 'walls', n: 2, scene: 1, walls: [wallBody(1), wallBody(2, { a: [100, 200], b: [100, 400] })] }),
|
||||
)
|
||||
expect(wallsOf(state).map(wall => wall.id)).toEqual([1, 2])
|
||||
expect(wallOf(state, 1)?.kind).toBe('wall')
|
||||
|
||||
const moved = reduce(state, frame({ t: 'wall', n: 3, ...wallBody(1, { kind: 'door', door: true, a: [120, 100] }) }))
|
||||
expect(wallsOf(moved)).toHaveLength(2)
|
||||
expect(wallOf(moved, 1)).toMatchObject({ kind: 'door', a: [120, 100] })
|
||||
|
||||
const gone = reduce(moved, frame({ t: 'wall_gone', n: 4, scene: 1, id: 2 }))
|
||||
expect(wallsOf(gone).map(wall => wall.id)).toEqual([1])
|
||||
})
|
||||
|
||||
it('keeps selection while the wall exists and clears it on wall_gone or a snapshot without it', () => {
|
||||
const state = run(
|
||||
{ type: 'connecting' },
|
||||
hello(1),
|
||||
frame({ t: 'wall', n: 2, ...wallBody(7) }),
|
||||
{ type: 'wall-select', id: 7 },
|
||||
)
|
||||
expect(selectedWallId(state)).toBe(7)
|
||||
expect(selectedWallId(reduce(state, frame({ t: 'wall_gone', n: 3, id: 7 })))).toBeNull()
|
||||
expect(
|
||||
selectedWallId(reduce(state, frame({ t: 'walls', n: 4, scene: 1, walls: [] }))),
|
||||
).toBeNull()
|
||||
})
|
||||
|
||||
it('resets on hello and ignores wall frames on a player-shaped session (3.1)', () => {
|
||||
const gm = run({ type: 'connecting' }, hello(1), frame({ t: 'wall', n: 2, ...wallBody(1) }))
|
||||
expect(wallsOf(reduce(gm, hello(3)))).toEqual([])
|
||||
|
||||
const player = run({ type: 'connecting' }, hello(1, 'player'), frame({ t: 'wall', n: 2, ...wallBody(1) }))
|
||||
expect(wallsOf(player)).toEqual([])
|
||||
})
|
||||
|
||||
it('derives `kind` when the server frame omits it', () => {
|
||||
const state = run(
|
||||
{ type: 'connecting' },
|
||||
hello(1),
|
||||
frame({
|
||||
t: 'wall',
|
||||
n: 2,
|
||||
...wallBody(1, { kind: undefined, blocks_sight: false, blocks_movement: true, door: true }),
|
||||
}),
|
||||
)
|
||||
expect(wallOf(state, 1)?.kind).toBe('window')
|
||||
})
|
||||
})
|
||||
|
||||
describe('presets, derived kind and the arrow (5.8)', () => {
|
||||
it('expands the four presets exactly as the 5.8 table says', () => {
|
||||
expect(PRESETS).toEqual(['wall', 'door', 'window', 'one_way'])
|
||||
expect(presetSwitches('wall')).toEqual({
|
||||
blocksSight: true,
|
||||
blocksMovement: true,
|
||||
sightDir: 'both',
|
||||
playerMarker: false,
|
||||
door: false,
|
||||
open: false,
|
||||
secret: false,
|
||||
locked: false,
|
||||
})
|
||||
expect(presetSwitches('door')).toMatchObject({ door: true, open: false, playerMarker: false })
|
||||
expect(presetSwitches('window')).toMatchObject({
|
||||
blocksSight: false,
|
||||
blocksMovement: true,
|
||||
door: true,
|
||||
playerMarker: true,
|
||||
})
|
||||
expect(presetSwitches('one_way')).toMatchObject({ sightDir: 'left', blocksSight: true, door: false })
|
||||
})
|
||||
|
||||
it('derives kind in the fixed order: window, one_way, door, wall, else custom', () => {
|
||||
expect(deriveKind(switches({ blocksSight: false }))).toBe('window')
|
||||
expect(deriveKind(switches({ sightDir: 'left' }))).toBe('one_way')
|
||||
expect(deriveKind(switches({ door: true }))).toBe('door')
|
||||
expect(deriveKind(switches())).toBe('wall')
|
||||
expect(deriveKind(switches({ blocksMovement: false }))).toBe('custom')
|
||||
// A one-way door is labelled one_way, and secret/locked never change the label.
|
||||
expect(deriveKind(switches({ door: true, sightDir: 'right' }))).toBe('one_way')
|
||||
expect(deriveKind(switches({ door: true, secret: true, locked: true }))).toBe('door')
|
||||
})
|
||||
|
||||
it('points the arrow at the blind side named by sight_dir, and flips left/right only', () => {
|
||||
const a: Vec2 = [0, 0]
|
||||
const b: Vec2 = [100, 0]
|
||||
// a -> b runs +x; left is (-dy, dx) = +y, so sight_dir:"left" means the +y side is blind.
|
||||
expect(arrowVector(a, b, 'left')).toEqual([0, 1])
|
||||
expect(arrowVector(a, b, 'right')).toEqual([0, -1])
|
||||
expect(arrowVector(a, b, 'both')).toBeNull()
|
||||
expect(flipSightDir('left')).toBe('right')
|
||||
expect(flipSightDir('right')).toBe('left')
|
||||
expect(flipSightDir('both')).toBe('both')
|
||||
})
|
||||
})
|
||||
|
||||
describe('snap while drawing (story 45)', () => {
|
||||
it('prefers an endpoint inside the threshold, else rounds to the grid, and does nothing when off', () => {
|
||||
const endpoints = [([100, 100] as Vec2), ([300, 200] as Vec2)]
|
||||
expect(snapPoint([105, 97], { enabled: true, gridSize: 32, endpoints, threshold: 12 })).toEqual([100, 100])
|
||||
expect(snapPoint([143, 154], { enabled: true, gridSize: 32, endpoints, threshold: 12 })).toEqual([128, 160])
|
||||
expect(snapPoint([143, 154], { enabled: false, gridSize: 32, endpoints, threshold: 12 })).toEqual([143, 154])
|
||||
// An endpoint outside the threshold loses to the grid.
|
||||
expect(snapPoint([130, 130], { enabled: true, gridSize: 32, endpoints, threshold: 12 })).toEqual([128, 128])
|
||||
})
|
||||
})
|
||||
|
||||
describe('payload rules (6.1): preset XOR raw, and open is a door intent', () => {
|
||||
it('sends only `preset` beside a preset, never a raw switch such as open:false', () => {
|
||||
const fields = buildAddFields(1, [0, 0], [100, 0], { preset: 'door', switches: presetSwitches('door'), label: null })
|
||||
expect(fields).toEqual({ scene: 1, a: [0, 0], b: [100, 0], preset: 'door' })
|
||||
for (const key of ['open', 'blocks_sight', 'blocks_movement', 'sight_dir', 'player_marker', 'door', 'secret', 'locked']) {
|
||||
expect(fields).not.toHaveProperty(key)
|
||||
}
|
||||
})
|
||||
|
||||
it('sends every raw switch on a raw add and a label only when given', () => {
|
||||
const fields = buildAddFields(1, [0, 0], [100, 0], {
|
||||
preset: null,
|
||||
switches: switches({ sightDir: 'left' }),
|
||||
label: 'railing',
|
||||
})
|
||||
expect(fields).toMatchObject({
|
||||
blocks_sight: true,
|
||||
blocks_movement: true,
|
||||
sight_dir: 'left',
|
||||
player_marker: false,
|
||||
door: false,
|
||||
open: false,
|
||||
secret: false,
|
||||
locked: false,
|
||||
label: 'railing',
|
||||
})
|
||||
})
|
||||
|
||||
it('never puts `open` in a wall.update patch, preset or raw', () => {
|
||||
const raw = buildUpdateFields(9, { preset: null, switches: switches({ open: true }), label: null })
|
||||
expect(raw).toEqual({
|
||||
id: 9,
|
||||
blocks_sight: true,
|
||||
blocks_movement: true,
|
||||
sight_dir: 'both',
|
||||
player_marker: false,
|
||||
door: false,
|
||||
secret: false,
|
||||
locked: false,
|
||||
label: null,
|
||||
})
|
||||
expect(raw).not.toHaveProperty('open')
|
||||
const preset = buildUpdateFields(9, { preset: 'window', switches: presetSwitches('window') })
|
||||
expect(preset).toEqual({ id: 9, preset: 'window' })
|
||||
expect(buildDoorFields(1, 9, true)).toEqual({ scene: 1, id: 9, open: true })
|
||||
})
|
||||
|
||||
it('builds the inverse of each edit for single-step undo', () => {
|
||||
expect(undoIntent(1, { kind: 'remove', id: 4 })).toEqual({
|
||||
t: 'wall.remove',
|
||||
fields: { scene: 1, id: 4 },
|
||||
})
|
||||
expect(undoIntent(1, { kind: 'door', id: 4, open: true })).toEqual({
|
||||
t: 'door.set',
|
||||
fields: { scene: 1, id: 4, open: true },
|
||||
})
|
||||
const update = undoIntent(1, {
|
||||
kind: 'update',
|
||||
id: 4,
|
||||
switches: switches({ sightDir: 'right' }),
|
||||
label: 'x',
|
||||
flags: { a: 1 },
|
||||
})
|
||||
expect(update?.t).toBe('wall.update')
|
||||
expect(update?.fields).toMatchObject({ id: 4, sight_dir: 'right', label: 'x', flags: { a: 1 } })
|
||||
expect(update?.fields).not.toHaveProperty('open')
|
||||
const restore = undoIntent(1, {
|
||||
kind: 'restore',
|
||||
wall: {
|
||||
a: [0, 0],
|
||||
b: [100, 0],
|
||||
thickness: 0,
|
||||
position: 'center',
|
||||
height: null,
|
||||
switches: switches({ open: true, door: true }),
|
||||
label: 'door',
|
||||
flags: {},
|
||||
},
|
||||
})
|
||||
expect(restore?.t).toBe('wall.add')
|
||||
expect(restore?.fields).toMatchObject({ door: true, open: true, label: 'door', height: null })
|
||||
})
|
||||
})
|
||||
|
||||
describe('local validation mirrors the server rules (5.8, 6.1)', () => {
|
||||
it('rejects a sight direction with nothing to block', () => {
|
||||
expect(validateSwitches(switches({ blocksSight: false, sightDir: 'left' }))).toContain('sight direction')
|
||||
expect(validateSwitches(switches({ blocksSight: false, sightDir: 'both' }))).toBeNull()
|
||||
})
|
||||
|
||||
it('rejects door settings without a door and impossible secret/locked doors', () => {
|
||||
expect(validateSwitches(switches({ locked: true }))).toContain('need a door')
|
||||
expect(validateSwitches(switches({ door: true, secret: true, open: true }))).toContain('always closed')
|
||||
expect(validateSwitches(switches({ door: true, secret: true, sightDir: 'left' }))).toContain('two-way')
|
||||
expect(validateSwitches(switches({ door: true, secret: true, blocksMovement: false }))).toContain('opaque')
|
||||
expect(validateSwitches(switches({ door: true, open: true, locked: true }))).toContain('locked')
|
||||
expect(validateSwitches(switches({ door: true, secret: true, locked: true }))).toBeNull()
|
||||
expect(validateSwitches(switches({ door: true, open: true }))).toBeNull()
|
||||
})
|
||||
|
||||
it('accepts 1..64 trimmed code points with no control characters', () => {
|
||||
expect(validateLabel(' railing ')).toBeNull()
|
||||
expect(validateLabel('')).toBeNull()
|
||||
expect(validateLabel('x'.repeat(65))).toContain('64')
|
||||
expect(validateLabel('a\nb')).toContain('control')
|
||||
expect(validateLabel('😀'.repeat(64))).toBeNull()
|
||||
})
|
||||
|
||||
it('treats a preset and raw switches as one draft mode', () => {
|
||||
// The editor's preset draft never carries a raw switch; the type is the guard.
|
||||
const preset: WallPreset = 'wall'
|
||||
const fields = buildAddFields(1, [0, 0], [1, 1], { preset, switches: switches(), label: null })
|
||||
expect(fields).toHaveProperty('preset', 'wall')
|
||||
expect(fields).not.toHaveProperty('open')
|
||||
const dir: SightDir = 'left'
|
||||
expect(validateSwitches(switches({ sightDir: dir }))).toBeNull()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user