diff options
| author | Joel Klinghed <the_jk@spawned.biz> | 2026-11-15 13:45:21 +0100 |
|---|---|---|
| committer | Joel Klinghed <the_jk@spawned.biz> | 2026-11-15 13:45:21 +0100 |
| commit | 4f50f2008f4d7c2a635f7f26861fcfc7f7504423 (patch) | |
| tree | 94e6286e7e22e0467a61b99c18b9ab582fbbe656 /web/src/lib/protocol | |
| parent | 3ebbdf6ffa16f751c82e3bd2e74294f4fe843155 (diff) | |
Phase 3: web UI core loop (M3)
Browser game UI on top of the Phase 2 protocol: server-driven, input-only
clients with per-connection secret visibility.
Web (Svelte 5):
- Layout: TopBar (element buttons with use/imbue long-press, title, menu),
MainList (character/monster/note rows), BottomBar (draw/next-round +
level widget with T/H/X/C values).
- CharacterRow with the secret initiative input: own value editable,
server-masked values render as ??, revealed on draw.
- Per-figure StatusMenu: health/max/xp/bless/curse/empower/enfeeble
steppers, condition grid, turn-done — all server commands, player-gated.
- Menu dialogs: select scenario, add section, add/remove character,
set level/difficulty/solo/auto-level, add/remove monster, note row,
action log with rollback, settings (style theme + language).
- Player vs spectator UI gated on the live seat table; reconnecting
banner, error toasts, connection status plumbing.
- i18n: English ported, locale store with localStorage persistence.
- Design tokens + the three style themes (frosthaven/gloomhaven/original).
- Unit tests: level values, game logic (elements/conditions/art/stats),
i18n, the reactive player store, the data client (sections keyed by
scenario number), plus the existing connection/protocol/state tests.
Server:
- Serve the engine's data JSON at /data/ and artwork at /images/ so the
client menus and rows read the same assets the engine loads.
Diffstat (limited to 'web/src/lib/protocol')
| -rw-r--r-- | web/src/lib/protocol/connection.ts | 231 | ||||
| -rw-r--r-- | web/src/lib/protocol/types.ts | 214 |
2 files changed, 412 insertions, 33 deletions
diff --git a/web/src/lib/protocol/connection.ts b/web/src/lib/protocol/connection.ts index 0826a3c..51305a1 100644 --- a/web/src/lib/protocol/connection.ts +++ b/web/src/lib/protocol/connection.ts @@ -1,57 +1,222 @@ /** - * Client side of the X-Haven wire protocol (PLAN.md section 3.5). + * The X-Haven WebSocket client (PLAN.md section 3.5). * - * Phase 0 scope: connect to `/ws`, send the `hello` handshake, surface the - * `welcome` message and connection status. Reconnect/resync, commands, claims - * and state updates arrive in later phases. + * Responsibilities: + * - the `hello` handshake (the session id rides in the cookie, set by the + * `/session` endpoint / the upgrade request) + * - a keepalive `ping` so the server's dead-connection sweep never closes a + * live tab + * - automatic reconnect with exponential backoff; every (re)connect re-sends + * `hello`, which the server answers with a full `welcome` — that is the + * resync + * - typed dispatch of `welcome` / `update` / `seats` / `error` / `pong` + * - outbound command / claim / undo / redo helpers + * + * The [WebSocket]-compatible transport is injectable so the reconnect and + * resync behaviour can be exercised in unit tests with a fake socket. */ -export interface Welcome { - t: 'welcome'; - v: number; - session: string; - role: 'player' | 'spectator'; - index: number; - description: string | null; - event: unknown; - state: Record<string, unknown>; - seats: Record<string, unknown>; -} +import type { + ErrorMessage, + ServerMessage +} from './types'; +import { claimMessage, helloMessage, pingMessage } from './types'; + +export type ConnectionStatus = + | 'connecting' + | 'open' + | 'reconnecting' + | 'closed'; -export type ConnectionStatus = 'connecting' | 'open' | 'closed'; +/** A `WebSocket`-compatible surface (enough for the tests' fake). */ +export interface Transport { + onopen: ((ev?: unknown) => void) | null; + onclose: ((ev?: unknown) => void) | null; + onerror: ((ev?: unknown) => void) | null; + onmessage: ((ev: { data: unknown }) => void) | null; + send(data: string): void; + close(): void; + readyState: number; // 0 OPEN +} -/** The handshake message sent right after the WebSocket opens. */ -export function buildHello(): Record<string, unknown> { - return { t: 'hello', v: 1 }; +export interface ConnectionOptions { + /** Absolute `ws://` / `wss://` URL. Defaults to the page origin `/ws`. */ + url?: string; + /** Inject a transport factory (tests). Defaults to `new WebSocket(url)`. */ + transport?: (url: string) => Transport; + /** Reconnect base delay in ms (doubles each attempt, capped). */ + reconnectBaseMs?: number; + reconnectMaxMs?: number; + /** Keepalive ping interval in ms. */ + pingIntervalMs?: number; } +const OPEN = 0; + export class GameConnection { - private ws: WebSocket | null = null; + status: ConnectionStatus = 'connecting'; + /** The session id from the last `welcome` (null before the handshake). */ + session: string | null = null; - onWelcome: ((welcome: Welcome) => void) | null = null; onStatus: ((status: ConnectionStatus) => void) | null = null; + /** Every server message, in order (including `pong`). */ + onMessage: ((message: ServerMessage) => void) | null = null; + /** Convenience hook for `error` messages only. */ + onError: ((error: ErrorMessage) => void) | null = null; + + private ws: Transport | null = null; + private readonly options: Required< + Pick< + ConnectionOptions, + 'reconnectBaseMs' | 'reconnectMaxMs' | 'pingIntervalMs' + > + > & + ConnectionOptions; + private readonly url: string; + private intentionalClose = false; + private reconnectDelay = 0; + private reconnectTimer: ReturnType<typeof setTimeout> | null = null; + private pingTimer: ReturnType<typeof setInterval> | null = null; + private disposed = false; + + constructor(options: ConnectionOptions = {}) { + this.options = { + reconnectBaseMs: 500, + reconnectMaxMs: 15_000, + pingIntervalMs: 25_000, + ...options + }; + const explicit = options.url; + if (explicit) { + this.url = explicit; + } else { + const proto = window.location.protocol === 'https:' ? 'wss' : 'ws'; + this.url = `${proto}://${window.location.host}/ws`; + } + } + + private makeTransport(): Transport { + if (this.options.transport) return this.options.transport(this.url); + return new WebSocket(this.url) as unknown as Transport; + } connect(): void { - const proto = window.location.protocol === 'https:' ? 'wss' : 'ws'; - const ws = new WebSocket(`${proto}://${window.location.host}/ws`); + this.intentionalClose = false; + this.openSocket(); + } + + /** Stop connecting and never reconnect (page teardown). */ + disconnect(): void { + this.disposed = true; + this.intentionalClose = true; + this.clearTimers(); + this.ws?.close(); + this.ws = null; + } + + private setStatus(status: ConnectionStatus) { + this.status = status; + this.onStatus?.(status); + } + + private openSocket() { + if (this.disposed) return; + this.setStatus(this.ws === null && this.session === null ? 'connecting' : 'reconnecting'); + const ws = this.makeTransport(); this.ws = ws; ws.onopen = () => { - this.onStatus?.('open'); - ws.send(JSON.stringify(buildHello())); + this.setStatus('open'); + this.sendRaw(helloMessage()); + this.startPing(); }; - ws.onclose = () => this.onStatus?.('closed'); - ws.onerror = () => this.onStatus?.('closed'); - ws.onmessage = (event) => { - const message = JSON.parse(String(event.data)) as { t: string }; + ws.onmessage = (ev) => { + const text = typeof ev.data === 'string' ? ev.data : ''; + let message: ServerMessage; + try { + message = JSON.parse(text) as ServerMessage; + } catch { + return; // ignore non-JSON frames + } if (message.t === 'welcome') { - this.onWelcome?.(message as unknown as Welcome); + this.session = message.session; + // A real resync landed: the connection is healthy, so the + // backoff starts fresh from the base on the next drop. + this.reconnectDelay = 0; + } + this.onMessage?.(message); + if (message.t === 'error') this.onError?.(message); + }; + ws.onclose = () => { + this.stopPing(); + if (this.disposed || this.intentionalClose) { + this.setStatus('closed'); + return; } + this.scheduleReconnect(); }; + // onerror is always followed by onclose in the browser; nothing to do. + ws.onerror = () => {}; } - close(): void { - this.ws?.close(); - this.ws = null; + private scheduleReconnect() { + this.setStatus('reconnecting'); + const delay = this.reconnectDelay || this.options.reconnectBaseMs; + this.reconnectDelay = Math.min( + delay * 2, + this.options.reconnectMaxMs + ); + this.reconnectTimer = setTimeout(() => this.openSocket(), delay); + } + + private clearTimers() { + if (this.reconnectTimer) { + clearTimeout(this.reconnectTimer); + this.reconnectTimer = null; + } + this.stopPing(); + } + + private startPing() { + this.stopPing(); + this.pingTimer = setInterval(() => { + if (this.ws && this.ws.readyState === OPEN) this.sendRaw(pingMessage()); + }, this.options.pingIntervalMs); + } + + private stopPing() { + if (this.pingTimer) { + clearInterval(this.pingTimer); + this.pingTimer = null; + } + } + + private sendRaw(message: object) { + if (this.ws && this.ws.readyState === OPEN) { + this.ws.send(JSON.stringify(message)); + } + } + + /** Execute a registered command (players only on the server side). */ + sendCmd(name: string, args: Record<string, unknown> = {}): void { + this.sendRaw({ t: 'cmd', name, args }); + } + + /** Claim (or re-assert) a character seat. */ + claim(characterId: string): void { + this.sendRaw(claimMessage(characterId)); + } + + undo(): void { + this.sendRaw({ t: 'undo' }); + } + + redo(): void { + this.sendRaw({ t: 'redo' }); + } + + /** Re-request a full resync (the server re-answers with a `welcome`). */ + resync(): void { + this.sendRaw(helloMessage()); } } diff --git a/web/src/lib/protocol/types.ts b/web/src/lib/protocol/types.ts new file mode 100644 index 0000000..b8ced78 --- /dev/null +++ b/web/src/lib/protocol/types.ts @@ -0,0 +1,214 @@ +/** + * Client-side mirrors of the server's wire protocol and state JSON + * (PLAN.md section 3.5). Field names match the server's `toJson()` + * exactly — the server is the source of truth. + */ + +// --- Enums (the server serializes enums as their value index) ------------- + +/** 0 = chooseInitiative, 1 = playTurns. */ +export type RoundState = 0 | 1; +/** 0 = notDone, 1 = current, 2 = done. */ +export type TurnsState = 0 | 1 | 2; +/** MonsterType index: 0 normal, 1 elite, 2 boss, 3 summon. */ +export type MonsterType = 0 | 1 | 2 | 3; +export type Role = 'player' | 'spectator'; + +// --- State figures --------------------------------------------------------- + +/** The figure base shared by characters and monster standees. */ +export interface FigureState { + level: number; + health: number; + maxHealth: number; + chill: number; + /** Condition indices (see `Condition`). */ + conditions: number[]; + conditionsAddedThisTurn: number[]; + conditionsAddedPreviousTurn: number[]; +} + +export interface CharacterState extends FigureState { + /** + * Initiative value. `null` when the value is secret for this + * connection (the server masks every non-owned character during + * chooseInitiative — PLAN.md section 3.4). + */ + initiative: number | null; + xp: number; + display: string; + modifierDeck: unknown; + summonList: MonsterInstance[]; + useFHPerks: boolean; + perkList: boolean[]; +} + +export interface MonsterInstance extends FigureState { + standeeNr: number; + move: number; + attack: number; + range: number; + name: string; + /** Artwork file name (resolved under /images/). */ + gfx: string; + roundSummoned: number; + type: MonsterType; + plague: number; +} + +// --- Current-list items ---------------------------------------------------- + +export interface CharacterItem { + id: string; + turnState: TurnsState; + note: string; + characterState: CharacterState; + /** Character-class id (discriminator). */ + characterClass: string; + edition: string; +} + +export interface MonsterItem { + id: string; + turnState: TurnsState; + note: string; + isActive: boolean; + /** Monster model name (discriminator). */ + type: string; + monsterInstances: MonsterInstance[]; + isAlly: boolean; + v: number; + level: number; +} + +export interface NoteRowItem { + id: string; + /** Discriminator flag. */ + noteRow: true; + text: string; + color: number; + linkedId: string; + standeeNr: number; +} + +export type ListItem = CharacterItem | MonsterItem | NoteRowItem; + +export function isCharacter(item: ListItem): item is CharacterItem { + return 'characterState' in item && 'characterClass' in item; +} +export function isMonster(item: ListItem): item is MonsterItem { + return 'monsterInstances' in item && 'type' in item; +} +export function isNoteRow(item: ListItem): item is NoteRowItem { + return (item as NoteRowItem).noteRow === true; +} + +export interface SpecialRule { + type: string; + note: string; + name: string; + health: string; + condition: string; + init: number; + level: number; + startOfRound: boolean; + list: unknown[]; +} + +export interface GameState { + level: number; + solo: boolean; + autoScenarioLevel: boolean; + difficulty: number; + roundState: RoundState; + round: number; + totalRounds: number; + scenario: string; + toastMessage: string; + scenarioSpecialRules: SpecialRule[]; + scenarioSectionsAdded: string[]; + currentCampaign: string; + currentList: ListItem[]; + currentAbilityDecks: unknown[]; + sanctuaryDeck: unknown; + modifierDeck: unknown; + modifierDeckAllies: unknown; + lootDeck: unknown; + unlockedClasses: string[]; + showAllyDeck: boolean; + allyDeckInOGGloom: boolean; + /** element index → element-state index. */ + elementState: Record<string, number>; +} + +// --- Messages -------------------------------------------------------------- + +export interface GameEvent { + type: string; + [ key: string ]: unknown; +} + +export interface WelcomeMessage { + t: 'welcome'; + v: number; + session: string; + role: Role; + index: number; + description: string | null; + event: GameEvent | null; + state: GameState; + /** character id → owning session id (null when unclaimed). */ + seats: Record<string, string | null>; +} + +export interface UpdateMessage { + t: 'update'; + index: number; + description: string; + event: GameEvent; + state: GameState; +} + +export interface SeatsMessage { + t: 'seats'; + seats: Record<string, string | null>; +} + +export interface ErrorMessage { + t: 'error'; + code: string; + message: string; +} + +export interface PongMessage { + t: 'pong'; +} + +export type ServerMessage = + | WelcomeMessage + | UpdateMessage + | SeatsMessage + | ErrorMessage + | PongMessage; + +// --- Client → server ------------------------------------------------------- + +export interface CommandArgs { + [ key: string ]: unknown; +} + +/** Outbound command message body (without the `t` field, added by the client). */ +export function commandMessage(name: string, args: CommandArgs = {}) { + return { t: 'cmd', name, args } as const; +} +export function claimMessage(characterId: string) { + return { t: 'claim', characterId } as const; +} +export function helloMessage() { + return { t: 'hello', v: 1 } as const; +} +export function pingMessage() { + return { t: 'ping' } as const; +} +export const undoMessage = () => ({ t: 'undo' }) as const; +export const redoMessage = () => ({ t: 'redo' }) as const; |
