feat: client shell, sign-in and protocol client (#67)
New `client/` package (Vite + TypeScript + PixiJS v8, plain DOM overlay): the pure reducer seam (no Pixi import), an append-only slice registry build-time glob, the `proto` 2 WS client with envelope/ack/closing mapping, the sign-in door (`POST /join`, one "Key not recognised." for wrong and unknown), the DOM shell/HUD and a minimal Pixi stage created only after a live `hello`. `hello` resets every slice so a reconnect cannot show stale state; `proto-mismatch` shows reload; `revoked` returns to the sign-in page and stops. The browser e2e moves into the client package (`client/e2e/`, owning playwright-core) and runs the real Vite build through the TLS/HTTP2 test nginx: join -> canvas -> hello/roster for GM and player, no data before join, identical wrong/unknown key refusal, proto mismatch, revoked. `devbox run client-test` adds the Vitest seam; `devbox run e2e` builds the client first. The #66 stub dist stays local to `tools/vhost.test.mjs`, so `devbox run test` still needs no npm install. Refs #67
This commit is contained in:
@@ -0,0 +1,103 @@
|
||||
// Client bootstrap: one store, one WS client, one DOM shell, one Pixi stage created only once the
|
||||
// session is live. Every network/UI decision goes through the pure reducer; this file is wiring.
|
||||
|
||||
import './style.css'
|
||||
import { ProtocolClient } from './ws.ts'
|
||||
import { Store } from './store.ts'
|
||||
import { mountShell } from './shell.ts'
|
||||
import type { Stage } from './render/stage.ts'
|
||||
import { createStage } from './render/stage.ts'
|
||||
import type { RootState } from './reducer.ts'
|
||||
|
||||
const KEY_REFUSED = 'Key not recognised.'
|
||||
|
||||
const host = document.querySelector<HTMLElement>('#app')
|
||||
if (!host) throw new Error('#app is missing')
|
||||
|
||||
const store = new Store()
|
||||
let client: ProtocolClient | null = null
|
||||
let stage: Stage | null = null
|
||||
let startingStage: Promise<void> | null = null
|
||||
|
||||
const shell = mountShell(host, {
|
||||
onSubmitKey: key => {
|
||||
void signIn(key)
|
||||
},
|
||||
onReload: () => location.reload(),
|
||||
})
|
||||
|
||||
const stageHost = document.querySelector<HTMLElement>('#stage')
|
||||
if (!stageHost) throw new Error('#stage is missing')
|
||||
const stageRoot: HTMLElement = stageHost
|
||||
|
||||
async function signIn(key: string): Promise<void> {
|
||||
shell.setBusy(true)
|
||||
let accepted = false
|
||||
try {
|
||||
// DESIGN 3.2/6.6: POST /join, key in the body. `redirect: 'manual'` turns the 303 into an
|
||||
// opaque redirect the client cannot mistake for a body; a 401 (wrong or unknown key alike)
|
||||
// is a readable same-origin response.
|
||||
const response = await fetch('/join', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
redirect: 'manual',
|
||||
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams({ key }).toString(),
|
||||
})
|
||||
accepted = response.type === 'opaqueredirect' || response.status === 303
|
||||
} catch {
|
||||
accepted = false
|
||||
}
|
||||
if (!accepted) {
|
||||
// Story 3: one plain answer, whatever the reason. No key existence oracle.
|
||||
store.dispatch({ type: 'signin-failed', message: KEY_REFUSED })
|
||||
return
|
||||
}
|
||||
client?.close()
|
||||
store.dispatch({ type: 'connecting' })
|
||||
connect()
|
||||
}
|
||||
|
||||
function connect(): void {
|
||||
client = new ProtocolClient({
|
||||
onEvent: event => {
|
||||
store.dispatch(event)
|
||||
},
|
||||
})
|
||||
client.connect()
|
||||
}
|
||||
|
||||
function syncStage(state: RootState): void {
|
||||
const live = state.connection.phase === 'live'
|
||||
if (!live) {
|
||||
stage?.destroy()
|
||||
stage = null
|
||||
return
|
||||
}
|
||||
if (stage || startingStage) return
|
||||
startingStage = createStage(stageRoot, store)
|
||||
.then(created => {
|
||||
if (store.state.connection.phase !== 'live') {
|
||||
created.destroy()
|
||||
return
|
||||
}
|
||||
stage = created
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('stage init failed', error)
|
||||
})
|
||||
.finally(() => {
|
||||
startingStage = null
|
||||
})
|
||||
}
|
||||
|
||||
store.subscribe(state => {
|
||||
shell.render(state)
|
||||
syncStage(state)
|
||||
})
|
||||
|
||||
// Boot: show the neutral connecting screen and probe for a session. A visitor without a session
|
||||
// gets a refused `/ws` upgrade and lands on the sign-in page; no map data is ever created.
|
||||
store.dispatch({ type: 'connecting' })
|
||||
shell.render(store.state)
|
||||
connect()
|
||||
@@ -0,0 +1,181 @@
|
||||
// The wire contract (DESIGN 6). This module is pure: no Pixi, no DOM, no socket. The client speaks
|
||||
// `proto` 2 (ADR-0011) and ignores unknown server message types and unknown fields (6.2).
|
||||
|
||||
/** Compiled into the client exactly as into the server (DESIGN 6.2, ADR-0011). */
|
||||
export const PROTO = 2
|
||||
|
||||
export type Role = 'gm' | 'player'
|
||||
export type Vec2 = [number, number]
|
||||
|
||||
/** `hello.scene` (DESIGN 6.1; views.sceneBlock). No counts, no wall data, no owned ids. */
|
||||
export interface SceneInfo {
|
||||
id: number
|
||||
name: string
|
||||
w: number
|
||||
h: number
|
||||
tile_size: number
|
||||
cell: number
|
||||
grid_size: number
|
||||
vision_radius_default: number
|
||||
token_radius_default: number
|
||||
art_version: number
|
||||
}
|
||||
|
||||
export interface RosterEntry {
|
||||
id: number
|
||||
name: string | null
|
||||
role: Role
|
||||
colour: string
|
||||
connected: boolean
|
||||
}
|
||||
|
||||
export interface Me {
|
||||
id: number
|
||||
name: string | null
|
||||
}
|
||||
|
||||
/** Every server frame carries the per-connection counter `n` (DESIGN 6, 6.4). */
|
||||
export interface ServerFrame {
|
||||
t: string
|
||||
n: number
|
||||
[field: string]: unknown
|
||||
}
|
||||
|
||||
export interface HelloFrame extends ServerFrame {
|
||||
t: 'hello'
|
||||
proto: number
|
||||
role: Role
|
||||
me: Me
|
||||
scene?: SceneInfo
|
||||
extra?: unknown
|
||||
}
|
||||
|
||||
export interface AckFrame extends ServerFrame {
|
||||
t: 'ack'
|
||||
reqId: number
|
||||
ok: boolean
|
||||
code?: string
|
||||
id?: number
|
||||
key?: string
|
||||
pos?: Vec2
|
||||
ts?: number
|
||||
}
|
||||
|
||||
export const CLOSE_REASONS = [
|
||||
'revoked',
|
||||
'evicted',
|
||||
'proto-mismatch',
|
||||
'malformed-flood',
|
||||
'server-shutdown',
|
||||
] as const
|
||||
|
||||
export type CloseReason = (typeof CLOSE_REASONS)[number]
|
||||
|
||||
export interface ClosingFrame extends ServerFrame {
|
||||
t: 'closing'
|
||||
reason: CloseReason
|
||||
code: number
|
||||
}
|
||||
|
||||
/** What the shell does when a connection outcome arrives (DESIGN 6.5). */
|
||||
export type CloseOutcome = 'signin' | 'reload' | 'offline'
|
||||
|
||||
export function closeOutcome(reason: CloseReason | null): CloseOutcome {
|
||||
switch (reason) {
|
||||
case 'revoked':
|
||||
return 'signin'
|
||||
case 'proto-mismatch':
|
||||
return 'reload'
|
||||
case 'evicted':
|
||||
case 'malformed-flood':
|
||||
case 'server-shutdown':
|
||||
return 'offline'
|
||||
case null:
|
||||
return 'offline'
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse one text frame into a server envelope. Binary frames and anything that is not a JSON
|
||||
* object with a string `t` and an integer `n >= 1` are not frames (DESIGN 6: a binary frame counts
|
||||
* as malformed server input; the client ignores it, exactly as 6.2 says for unknown shapes).
|
||||
*/
|
||||
export function parseServerFrame(raw: unknown): ServerFrame | null {
|
||||
if (typeof raw !== 'string') return null
|
||||
let value: unknown
|
||||
try {
|
||||
value = JSON.parse(raw)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
if (!isRecord(value)) return null
|
||||
const t = value['t']
|
||||
const n = value['n']
|
||||
if (typeof t !== 'string' || t.length === 0) return null
|
||||
if (typeof n !== 'number' || !Number.isInteger(n) || n < 1) return null
|
||||
return value as ServerFrame
|
||||
}
|
||||
|
||||
function isRole(value: unknown): value is Role {
|
||||
return value === 'gm' || value === 'player'
|
||||
}
|
||||
|
||||
function isMe(value: unknown): value is Me {
|
||||
if (!isRecord(value)) return false
|
||||
const name = value['name']
|
||||
return (
|
||||
typeof value['id'] === 'number' &&
|
||||
Number.isInteger(value['id']) &&
|
||||
(name === null || typeof name === 'string')
|
||||
)
|
||||
}
|
||||
|
||||
export function isHello(frame: ServerFrame): frame is HelloFrame {
|
||||
if (frame.t !== 'hello') return false
|
||||
if (typeof frame['proto'] !== 'number' || !Number.isInteger(frame['proto'])) return false
|
||||
if (!isRole(frame['role'])) return false
|
||||
if (!isMe(frame['me'])) return false
|
||||
const scene = frame['scene']
|
||||
if (scene !== undefined && !isRecord(scene)) return false
|
||||
return true
|
||||
}
|
||||
|
||||
export function isAck(frame: ServerFrame): frame is AckFrame {
|
||||
return (
|
||||
frame.t === 'ack' &&
|
||||
typeof frame['reqId'] === 'number' &&
|
||||
Number.isInteger(frame['reqId']) &&
|
||||
typeof frame['ok'] === 'boolean'
|
||||
)
|
||||
}
|
||||
|
||||
function isCloseReason(value: unknown): value is CloseReason {
|
||||
return typeof value === 'string' && (CLOSE_REASONS as readonly string[]).includes(value)
|
||||
}
|
||||
|
||||
export function isClosing(frame: ServerFrame): frame is ClosingFrame {
|
||||
return (
|
||||
frame.t === 'closing' &&
|
||||
isCloseReason(frame['reason']) &&
|
||||
typeof frame['code'] === 'number' &&
|
||||
Number.isInteger(frame['code'])
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Serialise one intent: envelope `t` plus its `reqId` and fields (DESIGN 6 Conventions). The server
|
||||
* ignores unknown fields (6.2); the client never invents a `t` outside the catalogue.
|
||||
*/
|
||||
export function encodeIntent(t: string, reqId: number, fields: Record<string, unknown> = {}): string {
|
||||
return JSON.stringify({ ...fields, t, reqId })
|
||||
}
|
||||
|
||||
/** The only place the client spells the `proto` parameter (6.2: absent or non-integer is 400). */
|
||||
export function wsUrl(location: Pick<Location, 'protocol' | 'host'> = window.location): string {
|
||||
const scheme = location.protocol === 'https:' ? 'wss' : 'ws'
|
||||
return `${scheme}://${location.host}/ws?proto=${PROTO}`
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
// The client's one pure reducer (DESIGN 7.1, spec #63 decision 11): server frames and connection
|
||||
// events in, state out. No Pixi import here, ever: this module is the unit-test seam.
|
||||
//
|
||||
// Domain slices are *append-only*: every file in ./slices/ that exports `slice` is picked up by the
|
||||
// build-time glob below and registered automatically, so a later ticket (fog, tokens, walls, GM
|
||||
// panels) adds one file and touches no other slice. `hello` resets every slice (DESIGN 6.3: a
|
||||
// reconnect is a full resync), which is why the registry owns the reset rather than each slice.
|
||||
|
||||
import type {
|
||||
CloseReason,
|
||||
Me,
|
||||
Role,
|
||||
RosterEntry,
|
||||
SceneInfo,
|
||||
ServerFrame,
|
||||
} from './protocol.ts'
|
||||
import { closeOutcome, isClosing, isHello } from './protocol.ts'
|
||||
|
||||
export type Phase = 'boot' | 'connecting' | 'signin' | 'live' | 'reload' | 'offline'
|
||||
|
||||
export interface ConnectionState {
|
||||
phase: Phase
|
||||
/** Server frames seen on this connection (`n` is per connection, starts at 1). */
|
||||
frames: number
|
||||
lastN: number
|
||||
/** Human text for the shell; never game data. */
|
||||
notice: string | null
|
||||
/** Sign-in failure text ("Key not recognised.") or a transport message. */
|
||||
error: string | null
|
||||
}
|
||||
|
||||
export interface SessionState {
|
||||
role: Role | null
|
||||
me: Me | null
|
||||
proto: number | null
|
||||
scene: SceneInfo | null
|
||||
}
|
||||
|
||||
export interface RootState {
|
||||
connection: ConnectionState
|
||||
session: SessionState
|
||||
/**
|
||||
* Append-only domain state, keyed by slice name. Later tickets read `slices.tokens`, `slices.fog`
|
||||
* and so on; core connection/session/handshake state stays in this file.
|
||||
*/
|
||||
slices: Record<string, unknown>
|
||||
}
|
||||
|
||||
export type ReducerEvent =
|
||||
| { type: 'connecting' }
|
||||
| { type: 'open' }
|
||||
| { type: 'frame'; frame: ServerFrame }
|
||||
| { type: 'close'; reason: CloseReason | null; code: number | null }
|
||||
| { type: 'signin-failed'; message: string }
|
||||
| { type: 'signed-out' }
|
||||
|
||||
/**
|
||||
* A domain slice. `init()` returns the empty value; `reduce` mutates the draft it is handed (the
|
||||
* root reducer clones before dispatching, so the previous state is never touched).
|
||||
*/
|
||||
export interface Slice<S = unknown> {
|
||||
readonly name: string
|
||||
init(): S
|
||||
reduce(state: S, event: ReducerEvent, root: RootState): void
|
||||
}
|
||||
|
||||
interface SliceModule {
|
||||
slice: Slice
|
||||
}
|
||||
|
||||
// Build-time registry: no shared import list to merge, so parallel tickets never edit one file.
|
||||
const modules = import.meta.glob<SliceModule>('./slices/*.ts', { eager: true })
|
||||
|
||||
export const SLICES: readonly Slice[] = Object.keys(modules)
|
||||
.sort()
|
||||
.map(path => {
|
||||
const module = modules[path]
|
||||
if (!module || !module.slice) throw new Error(`slice ${path} has no \`slice\` export`)
|
||||
return module.slice
|
||||
})
|
||||
|
||||
const sliceNames = new Set(SLICES.map(slice => slice.name))
|
||||
if (sliceNames.size !== SLICES.length) throw new Error('duplicate slice name')
|
||||
|
||||
export function sliceOf<S>(state: RootState, name: string): S {
|
||||
return state.slices[name] as S
|
||||
}
|
||||
|
||||
function initialConnection(): ConnectionState {
|
||||
return { phase: 'boot', frames: 0, lastN: 0, notice: null, error: null }
|
||||
}
|
||||
|
||||
function initialSession(): SessionState {
|
||||
return { role: null, me: null, proto: null, scene: null }
|
||||
}
|
||||
|
||||
export function initialState(): RootState {
|
||||
const slices: Record<string, unknown> = {}
|
||||
for (const slice of SLICES) slices[slice.name] = slice.init()
|
||||
return { connection: initialConnection(), session: initialSession(), slices }
|
||||
}
|
||||
|
||||
/** Reset everything that came from the server; keep the connection envelope. */
|
||||
function resetDomain(state: RootState): void {
|
||||
state.session = initialSession()
|
||||
const slices: Record<string, unknown> = {}
|
||||
for (const slice of SLICES) slices[slice.name] = slice.init()
|
||||
state.slices = slices
|
||||
}
|
||||
|
||||
function onFrame(state: RootState, frame: ServerFrame): void {
|
||||
state.connection.frames += 1
|
||||
state.connection.lastN = frame.n
|
||||
|
||||
if (isHello(frame)) {
|
||||
// DESIGN 6.1/6.3: `hello` means "start clean". The resync that follows rebuilds the view; a
|
||||
// client that kept the previous connection's state would show stale tokens after a reconnect.
|
||||
resetDomain(state)
|
||||
state.session.role = frame.role
|
||||
state.session.me = frame.me
|
||||
state.session.proto = frame.proto
|
||||
state.session.scene = frame.scene ?? null
|
||||
state.connection.phase = 'live'
|
||||
state.connection.notice = null
|
||||
state.connection.error = null
|
||||
} else if (isClosing(frame)) {
|
||||
// DESIGN 6.5: the closing frame is the reason a browser cannot read from the close code.
|
||||
const outcome = closeOutcome(frame.reason)
|
||||
state.connection.notice =
|
||||
frame.reason === 'revoked'
|
||||
? 'Your session has ended. Sign in again.'
|
||||
: frame.reason === 'proto-mismatch'
|
||||
? 'This client is out of date.'
|
||||
: frame.reason === 'evicted'
|
||||
? 'This tab was replaced by a newer connection.'
|
||||
: 'The connection was closed by the server.'
|
||||
if (outcome === 'signin') {
|
||||
resetDomain(state)
|
||||
state.connection.phase = 'signin'
|
||||
} else if (outcome === 'reload') {
|
||||
state.connection.phase = 'reload'
|
||||
} else {
|
||||
state.connection.phase = 'offline'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function reduce(previous: RootState, event: ReducerEvent): RootState {
|
||||
const state: RootState = {
|
||||
connection: { ...previous.connection },
|
||||
session: { ...previous.session },
|
||||
slices: { ...previous.slices },
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case 'connecting':
|
||||
resetDomain(state)
|
||||
state.connection.phase = 'connecting'
|
||||
state.connection.frames = 0
|
||||
state.connection.lastN = 0
|
||||
state.connection.notice = null
|
||||
state.connection.error = null
|
||||
break
|
||||
case 'open':
|
||||
// An open socket is not a view: stay on the boot/connecting screen until `hello` (6.3).
|
||||
break
|
||||
case 'frame':
|
||||
onFrame(state, event.frame)
|
||||
break
|
||||
case 'close': {
|
||||
// A `closing` frame already decided the outcome (6.5); a close without one is a transport
|
||||
// failure. Before the first `hello` that means "no session" (the `/ws` upgrade was refused).
|
||||
if (state.connection.phase === 'live') {
|
||||
const outcome = closeOutcome(event.reason)
|
||||
if (outcome === 'signin') {
|
||||
resetDomain(state)
|
||||
state.connection.phase = 'signin'
|
||||
state.connection.notice = 'Your session has ended. Sign in again.'
|
||||
} else if (outcome === 'reload') {
|
||||
state.connection.phase = 'reload'
|
||||
state.connection.notice = 'This client is out of date.'
|
||||
} else {
|
||||
state.connection.phase = 'offline'
|
||||
state.connection.notice = 'Connection lost.'
|
||||
}
|
||||
} else if (state.connection.phase === 'connecting' || state.connection.phase === 'boot') {
|
||||
resetDomain(state)
|
||||
state.connection.phase = 'signin'
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'signin-failed':
|
||||
resetDomain(state)
|
||||
state.connection.phase = 'signin'
|
||||
state.connection.error = event.message
|
||||
break
|
||||
case 'signed-out':
|
||||
resetDomain(state)
|
||||
state.connection.phase = 'signin'
|
||||
state.connection.notice = null
|
||||
state.connection.error = null
|
||||
break
|
||||
}
|
||||
|
||||
for (const slice of SLICES) {
|
||||
slice.reduce(state.slices[slice.name], event, state)
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
/** `roster` lives in its own slice (append-only), read through here by the shell. */
|
||||
export interface RosterState {
|
||||
players: RosterEntry[]
|
||||
}
|
||||
|
||||
export function rosterOf(state: RootState): RosterEntry[] {
|
||||
return sliceOf<RosterState>(state, 'roster').players
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
# Render modules: append-only
|
||||
|
||||
Every `*.ts` file here that exports `renderModule` is registered by the build-time glob in
|
||||
`../stage.ts`. Add one file per feature; never edit the registry.
|
||||
|
||||
```ts
|
||||
import type { RenderModule } from '../stage.ts'
|
||||
|
||||
export const renderModule: RenderModule = {
|
||||
name: 'tiles', // unique
|
||||
mount({ app, world, layers, store }) {
|
||||
// create your objects in `layers.*`, subscribe to `store` for state changes,
|
||||
// return a teardown only for global resources you install.
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Layers bottom to top: `tiles`, `grid`, `tokens`, `fog`, `gm`, `dom` (DESIGN 7.1). Update only the
|
||||
entities that changed (DESIGN 7.2); no per-frame full redraw.
|
||||
@@ -0,0 +1,105 @@
|
||||
// The Pixi stage (DESIGN 7.1): one Application, one world container under pan/zoom, fixed layers
|
||||
// bottom to top. Render modules are append-only, exactly like reducer slices: every file in
|
||||
// ./modules/ that exports `renderModule` is picked up by the glob, so a later ticket (tiles/grid
|
||||
// T6, fog T7, tokens T8, walls T10, GM overlays) adds one file and touches no other module.
|
||||
//
|
||||
// Pixi is imported here (and in modules/) only. The reducer, the WS client and the DOM shell stay
|
||||
// Pixi-free so their unit tests run without a GPU or a DOM.
|
||||
|
||||
import { Application, Container } from 'pixi.js'
|
||||
import type { Store } from '../store.ts'
|
||||
import { PROTO } from '../protocol.ts'
|
||||
|
||||
export interface RenderLayers {
|
||||
tiles: Container
|
||||
grid: Container
|
||||
tokens: Container
|
||||
fog: Container
|
||||
gm: Container
|
||||
dom: Container
|
||||
}
|
||||
|
||||
export interface RenderContext {
|
||||
app: Application
|
||||
world: Container
|
||||
layers: RenderLayers
|
||||
store: Store
|
||||
}
|
||||
|
||||
export interface RenderModule {
|
||||
readonly name: string
|
||||
/** Start drawing. Return a teardown for anything global the module installed. */
|
||||
mount(context: RenderContext): void | (() => void)
|
||||
}
|
||||
|
||||
interface ModuleExport {
|
||||
renderModule: RenderModule
|
||||
}
|
||||
|
||||
const modules = import.meta.glob<ModuleExport>('./modules/*.ts', { eager: true })
|
||||
|
||||
const RENDER_MODULES: readonly RenderModule[] = Object.keys(modules)
|
||||
.sort()
|
||||
.map(path => {
|
||||
const module = modules[path]
|
||||
if (!module || !module.renderModule) {
|
||||
throw new Error(`render module ${path} has no \`renderModule\` export`)
|
||||
}
|
||||
return module.renderModule
|
||||
})
|
||||
|
||||
const moduleNames = new Set(RENDER_MODULES.map(module => module.name))
|
||||
if (moduleNames.size !== RENDER_MODULES.length) throw new Error('duplicate render module name')
|
||||
|
||||
export interface Stage {
|
||||
readonly app: Application
|
||||
readonly context: RenderContext
|
||||
destroy(): void
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the stage inside `host`. The caller creates it only when the session is live, so a
|
||||
* visitor without a session never gets a canvas (story 1). `PROTO` is touched here so the build
|
||||
* keeps the constant referenced even before an intent module exists.
|
||||
*/
|
||||
export async function createStage(host: HTMLElement, store: Store): Promise<Stage> {
|
||||
const app = new Application()
|
||||
await app.init({
|
||||
resizeTo: window,
|
||||
background: 0x000000,
|
||||
antialias: true,
|
||||
autoDensity: true,
|
||||
resolution: Math.min(window.devicePixelRatio || 1, 2),
|
||||
preference: 'webgl',
|
||||
})
|
||||
app.canvas.id = 'stage-canvas'
|
||||
app.canvas.dataset['proto'] = String(PROTO)
|
||||
host.replaceChildren(app.canvas)
|
||||
|
||||
const world = new Container()
|
||||
const layers: RenderLayers = {
|
||||
tiles: new Container(),
|
||||
grid: new Container(),
|
||||
tokens: new Container(),
|
||||
fog: new Container(),
|
||||
gm: new Container(),
|
||||
dom: new Container(),
|
||||
}
|
||||
world.addChild(layers.tiles, layers.grid, layers.tokens, layers.fog, layers.gm, layers.dom)
|
||||
app.stage.addChild(world)
|
||||
|
||||
// A v1 scene is large and the camera starts at the origin until T6 adds pan/zoom; scaling the
|
||||
// world down is not a map feature, so the world simply sits under the camera transform.
|
||||
const context: RenderContext = { app, world, layers, store }
|
||||
const teardowns = RENDER_MODULES.map(module => module.mount(context))
|
||||
|
||||
return {
|
||||
app,
|
||||
context,
|
||||
destroy() {
|
||||
for (const teardown of teardowns) teardown?.()
|
||||
app.destroy(true, { children: true })
|
||||
host.replaceChildren()
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
// The plain-DOM overlay (DESIGN 7.1 layer 6, spec #63 decision 15). No framework, no `innerHTML`:
|
||||
// every server-supplied string goes through `textContent`, so a name can never become markup.
|
||||
//
|
||||
// The shell is the only module that owns page structure; later panels (roster/keys/tokens T11,
|
||||
// characters/reveals T12) add their DOM under `#panels` or as their own file next to this one,
|
||||
// never by rewriting the sign-in flow.
|
||||
|
||||
import type { RootState } from './reducer.ts'
|
||||
import { rosterOf } from './reducer.ts'
|
||||
import type { RosterEntry } from './protocol.ts'
|
||||
|
||||
export interface ShellHandlers {
|
||||
onSubmitKey(key: string): void
|
||||
onReload(): void
|
||||
}
|
||||
|
||||
export interface Shell {
|
||||
render(state: RootState): void
|
||||
setBusy(busy: boolean): void
|
||||
}
|
||||
|
||||
function element<K extends keyof HTMLElementTagNameMap>(
|
||||
tag: K,
|
||||
id: string,
|
||||
text?: string,
|
||||
): HTMLElementTagNameMap[K] {
|
||||
const node = document.createElement(tag)
|
||||
node.id = id
|
||||
if (text !== undefined) node.textContent = text
|
||||
return node
|
||||
}
|
||||
|
||||
function rosterName(entry: RosterEntry): string {
|
||||
return entry.name ?? '(unnamed)'
|
||||
}
|
||||
|
||||
export function mountShell(root: HTMLElement, handlers: ShellHandlers): Shell {
|
||||
const stage = element('div', 'stage')
|
||||
stage.hidden = true
|
||||
|
||||
const boot = element('section', 'boot')
|
||||
const bootText = element('p', 'boot-text', 'Connecting…')
|
||||
boot.append(bootText)
|
||||
|
||||
const signin = element('section', 'signin')
|
||||
signin.hidden = true
|
||||
const title = element('h1', 'signin-title', 'FFF VTT')
|
||||
const notice = element('p', 'signin-notice')
|
||||
notice.hidden = true
|
||||
const form = element('form', 'signin-form')
|
||||
const label = element('label', 'signin-label', 'Player or GM key')
|
||||
label.htmlFor = 'key'
|
||||
const input = element('input', 'key')
|
||||
input.name = 'key'
|
||||
input.type = 'text'
|
||||
input.autocomplete = 'off'
|
||||
input.autocapitalize = 'characters'
|
||||
input.spellcheck = false
|
||||
input.required = true
|
||||
const submit = element('button', 'signin-submit', 'Sign in')
|
||||
submit.type = 'submit'
|
||||
form.append(label, input, submit)
|
||||
const error = element('p', 'signin-error')
|
||||
error.hidden = true
|
||||
error.setAttribute('role', 'alert')
|
||||
signin.append(title, notice, form, error)
|
||||
|
||||
const hud = element('header', 'hud')
|
||||
hud.hidden = true
|
||||
const role = element('span', 'role')
|
||||
const scene = element('span', 'scene')
|
||||
const me = element('span', 'me')
|
||||
const roster = element('ul', 'roster')
|
||||
hud.append(role, scene, me, roster)
|
||||
|
||||
const fatal = element('section', 'fatal')
|
||||
fatal.hidden = true
|
||||
const fatalText = element('p', 'fatal-text')
|
||||
const reload = element('button', 'reload', 'Reload')
|
||||
reload.type = 'button'
|
||||
reload.addEventListener('click', () => handlers.onReload())
|
||||
fatal.append(fatalText, reload)
|
||||
|
||||
const panels = element('div', 'panels')
|
||||
root.replaceChildren(stage, hud, signin, boot, fatal, panels)
|
||||
|
||||
form.addEventListener('submit', event => {
|
||||
event.preventDefault()
|
||||
const key = input.value.trim()
|
||||
if (key.length === 0) return
|
||||
handlers.onSubmitKey(key)
|
||||
})
|
||||
|
||||
let busy = false
|
||||
|
||||
function setBusy(next: boolean): void {
|
||||
busy = next
|
||||
submit.disabled = next
|
||||
input.disabled = next
|
||||
bootText.textContent = next ? 'Signing in…' : 'Connecting…'
|
||||
if (next) showOnly(boot)
|
||||
}
|
||||
|
||||
function showOnly(active: HTMLElement): void {
|
||||
for (const node of [boot, signin, hud, fatal]) node.hidden = node !== active
|
||||
}
|
||||
|
||||
function renderRoster(players: RosterEntry[]): void {
|
||||
roster.replaceChildren(
|
||||
...players.map(entry => {
|
||||
const item = document.createElement('li')
|
||||
item.dataset['player'] = String(entry.id)
|
||||
const name = element('span', 'roster-name', rosterName(entry))
|
||||
const state = element('span', 'roster-state', entry.connected ? 'connected' : 'offline')
|
||||
item.append(name, state)
|
||||
return item
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
function render(state: RootState): void {
|
||||
const phase = state.connection.phase
|
||||
|
||||
notice.textContent = state.connection.notice ?? ''
|
||||
notice.hidden = state.connection.notice === null
|
||||
error.textContent = state.connection.error ?? ''
|
||||
error.hidden = state.connection.error === null
|
||||
|
||||
stage.hidden = phase !== 'live'
|
||||
|
||||
// Leaving the live phase clears every server-derived DOM text, so a revoked session cannot
|
||||
// leave a roster (or names) behind the sign-in page.
|
||||
if (phase !== 'live') {
|
||||
role.textContent = ''
|
||||
scene.textContent = ''
|
||||
me.textContent = ''
|
||||
roster.replaceChildren()
|
||||
}
|
||||
|
||||
switch (phase) {
|
||||
case 'boot':
|
||||
case 'connecting':
|
||||
if (!busy) bootText.textContent = 'Connecting…'
|
||||
showOnly(boot)
|
||||
break
|
||||
case 'signin':
|
||||
busy = false
|
||||
submit.disabled = false
|
||||
input.disabled = false
|
||||
showOnly(signin)
|
||||
input.focus()
|
||||
break
|
||||
case 'live':
|
||||
busy = false
|
||||
showOnly(hud)
|
||||
role.textContent = state.session.role === 'gm' ? 'GM' : 'Player'
|
||||
scene.textContent = state.session.scene?.name ?? ''
|
||||
me.textContent = state.session.me?.name ?? ''
|
||||
renderRoster(rosterOf(state))
|
||||
break
|
||||
case 'reload':
|
||||
showOnly(fatal)
|
||||
fatalText.textContent = 'This client is out of date. Reload the page to get the matching version.'
|
||||
break
|
||||
case 'offline':
|
||||
showOnly(fatal)
|
||||
fatalText.textContent = state.connection.notice ?? 'Connection lost. Reload to reconnect.'
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return { render, setBusy }
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
// Roster slice (DESIGN 6.1 `roster`). Append-only registration: adding this file was enough; the
|
||||
// reducer's glob picked it up and `hello` reset it with every other slice.
|
||||
|
||||
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
|
||||
import type { RosterEntry } from '../protocol.ts'
|
||||
|
||||
export interface RosterState {
|
||||
/** Always the full list the server sent; the client never merges (6.1). */
|
||||
players: RosterEntry[]
|
||||
}
|
||||
|
||||
function rosterList(value: unknown): RosterEntry[] | null {
|
||||
if (!Array.isArray(value)) return null
|
||||
return value as RosterEntry[]
|
||||
}
|
||||
|
||||
export const slice: Slice<RosterState> = {
|
||||
name: 'roster',
|
||||
init: () => ({ players: [] }),
|
||||
reduce(state: RosterState, event: ReducerEvent, _root: RootState): void {
|
||||
if (event.type !== 'frame' || event.frame.t !== 'roster') return
|
||||
const players = rosterList(event.frame['players'])
|
||||
if (players) state.players = players
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// The store is the tiny bridge between the pure reducer and the renderer/DOM shell. It owns the
|
||||
// current state and notifies subscribers once per dispatch; render modules update only the
|
||||
// entities they saw change (DESIGN 7.2), so no module may assume a frame-by-frame redraw.
|
||||
|
||||
import type { ReducerEvent, RootState } from './reducer.ts'
|
||||
import { initialState, reduce } from './reducer.ts'
|
||||
|
||||
export type Listener = (state: RootState, event: ReducerEvent) => void
|
||||
|
||||
export class Store {
|
||||
#state: RootState
|
||||
#listeners = new Set<Listener>()
|
||||
|
||||
constructor(state: RootState = initialState()) {
|
||||
this.#state = state
|
||||
}
|
||||
|
||||
get state(): RootState {
|
||||
return this.#state
|
||||
}
|
||||
|
||||
dispatch(event: ReducerEvent): RootState {
|
||||
const next = reduce(this.#state, event)
|
||||
this.#state = next
|
||||
for (const listener of this.#listeners) listener(next, event)
|
||||
return next
|
||||
}
|
||||
|
||||
subscribe(listener: Listener): () => void {
|
||||
this.#listeners.add(listener)
|
||||
return () => {
|
||||
this.#listeners.delete(listener)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
background: #000;
|
||||
color: #eee;
|
||||
font: 14px/1.4 system-ui, sans-serif;
|
||||
}
|
||||
|
||||
#app {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
}
|
||||
|
||||
[hidden] {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
#stage {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
}
|
||||
|
||||
#stage canvas {
|
||||
display: block;
|
||||
}
|
||||
|
||||
#boot,
|
||||
#signin,
|
||||
#fatal {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
padding: 24px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
#signin form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
width: min(360px, 90vw);
|
||||
}
|
||||
|
||||
#key {
|
||||
font: inherit;
|
||||
padding: 10px 12px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid #555;
|
||||
background: #111;
|
||||
color: inherit;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
#signin button,
|
||||
#fatal button {
|
||||
font: inherit;
|
||||
padding: 10px 12px;
|
||||
border-radius: 6px;
|
||||
border: 1px solid #777;
|
||||
background: #222;
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
#signin-error {
|
||||
color: #ff8a8a;
|
||||
}
|
||||
|
||||
#hud {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
display: flex;
|
||||
gap: 16px;
|
||||
align-items: baseline;
|
||||
padding: 6px 12px;
|
||||
background: rgb(0 0 0 / 65%);
|
||||
pointer-events: none;
|
||||
font: 12px/1.4 ui-monospace, monospace;
|
||||
}
|
||||
|
||||
#roster {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
#roster li {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
#roster-state {
|
||||
opacity: 0.6;
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,143 @@
|
||||
// The protocol client (DESIGN 6.2, 6.3, 6.5; spec #63 decision 14). It owns the socket, the `reqId`
|
||||
// counter and the pending-request map; it emits reducer events and never touches the DOM. The
|
||||
// socket factory and clock-free design make it unit-testable without a browser.
|
||||
//
|
||||
// Close mapping (6.5, FIXED #18): a server-initiated close is `closing {reason, code}` and then a
|
||||
// close frame the browser reports as 1005, so the reason always comes from the last `closing` frame.
|
||||
// `revoked` and `proto-mismatch` are terminal: this client does not reconnect to them. Reconnect
|
||||
// with backoff is T5 (#68); T4 only proves the outcome mapping.
|
||||
|
||||
import type { AckFrame, CloseReason, ServerFrame } from './protocol.ts'
|
||||
import { encodeIntent, isAck, isClosing, parseServerFrame, wsUrl } from './protocol.ts'
|
||||
|
||||
export interface SocketLike {
|
||||
send(data: string): void
|
||||
close(code?: number, reason?: string): void
|
||||
onopen: (() => void) | null
|
||||
onmessage: ((event: { data: unknown }) => void) | null
|
||||
onclose: ((event: { code: number; reason: string }) => void) | null
|
||||
onerror: ((event: unknown) => void) | null
|
||||
}
|
||||
|
||||
export type ClientEvent =
|
||||
| { type: 'open' }
|
||||
| { type: 'frame'; frame: ServerFrame }
|
||||
| { type: 'close'; reason: CloseReason | null; code: number | null }
|
||||
|
||||
export interface ProtocolClientOptions {
|
||||
url?: string
|
||||
createSocket?: (url: string) => SocketLike
|
||||
onEvent: (event: ClientEvent) => void
|
||||
}
|
||||
|
||||
type Pending = {
|
||||
resolve: (ack: AckFrame) => void
|
||||
reject: (error: Error) => void
|
||||
}
|
||||
|
||||
function defaultSocket(url: string): SocketLike {
|
||||
return new WebSocket(url) as unknown as SocketLike
|
||||
}
|
||||
|
||||
export class ProtocolClient {
|
||||
#url: string
|
||||
#createSocket: (url: string) => SocketLike
|
||||
#onEvent: (event: ClientEvent) => void
|
||||
#socket: SocketLike | null = null
|
||||
#nextReqId = 1
|
||||
#pending = new Map<number, Pending>()
|
||||
#lastClosing: { reason: CloseReason; code: number } | null = null
|
||||
#state: 'idle' | 'connecting' | 'open' | 'closed' = 'idle'
|
||||
|
||||
constructor(options: ProtocolClientOptions) {
|
||||
this.#url = options.url ?? wsUrl()
|
||||
this.#createSocket = options.createSocket ?? defaultSocket
|
||||
this.#onEvent = options.onEvent
|
||||
}
|
||||
|
||||
get state(): 'idle' | 'connecting' | 'open' | 'closed' {
|
||||
return this.#state
|
||||
}
|
||||
|
||||
get pendingCount(): number {
|
||||
return this.#pending.size
|
||||
}
|
||||
|
||||
connect(): void {
|
||||
if (this.#state !== 'idle') return
|
||||
this.#state = 'connecting'
|
||||
const socket = this.#createSocket(this.#url)
|
||||
this.#socket = socket
|
||||
|
||||
socket.onopen = () => {
|
||||
if (this.#state !== 'connecting') return
|
||||
this.#state = 'open'
|
||||
this.#onEvent({ type: 'open' })
|
||||
}
|
||||
socket.onmessage = event => {
|
||||
if (this.#state === 'closed') return // a frame in flight after the client closed
|
||||
const frame = parseServerFrame(event.data)
|
||||
if (!frame) return // binary or unreadable: 6.2 says ignore what cannot be read
|
||||
if (isClosing(frame)) this.#lastClosing = { reason: frame.reason, code: frame.code }
|
||||
if (isAck(frame)) {
|
||||
const pending = this.#pending.get(frame.reqId)
|
||||
if (pending) {
|
||||
this.#pending.delete(frame.reqId)
|
||||
pending.resolve(frame)
|
||||
}
|
||||
}
|
||||
this.#onEvent({ type: 'frame', frame })
|
||||
}
|
||||
socket.onerror = () => {
|
||||
// The browser follows an error with a close; mapping the outcome there keeps it single.
|
||||
}
|
||||
socket.onclose = event => {
|
||||
if (this.#state === 'closed') return
|
||||
this.#state = 'closed'
|
||||
const reason = this.#lastClosing?.reason ?? null
|
||||
const code = this.#lastClosing?.code ?? event.code ?? null
|
||||
this.#failPending(new Error(`connection closed (${reason ?? code ?? 'no code'})`))
|
||||
this.#onEvent({ type: 'close', reason, code })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send one intent and resolve with its single `ack` (DESIGN 6 Conventions: exactly one ack per
|
||||
* readable intent, whatever the outcome). Pending reqIds die with the connection (6.3), and a
|
||||
* `hello` on a live connection does not drop them.
|
||||
*/
|
||||
send(t: string, fields: Record<string, unknown> = {}): Promise<AckFrame> {
|
||||
const socket = this.#socket
|
||||
if (this.#state !== 'open' || !socket) {
|
||||
return Promise.reject(new Error('not connected'))
|
||||
}
|
||||
const reqId = this.#nextReqId++
|
||||
const frame = encodeIntent(t, reqId, fields)
|
||||
return new Promise<AckFrame>((resolve, reject) => {
|
||||
this.#pending.set(reqId, { resolve, reject })
|
||||
try {
|
||||
socket.send(frame)
|
||||
} catch (error) {
|
||||
this.#pending.delete(reqId)
|
||||
reject(error instanceof Error ? error : new Error(String(error)))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.#state === 'closed') return
|
||||
this.#state = 'closed'
|
||||
try {
|
||||
this.#socket?.close()
|
||||
} catch {
|
||||
// A socket that is already gone is the outcome we wanted.
|
||||
}
|
||||
this.#failPending(new Error('connection closed by the client'))
|
||||
}
|
||||
|
||||
#failPending(error: Error): void {
|
||||
const pending = [...this.#pending.values()]
|
||||
this.#pending.clear()
|
||||
for (const entry of pending) entry.reject(error)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user