summaryrefslogtreecommitdiff
path: root/web/src/lib
diff options
context:
space:
mode:
authorJoel Klinghed <the_jk@spawned.biz>2026-11-15 13:45:21 +0100
committerJoel Klinghed <the_jk@spawned.biz>2026-11-15 13:45:21 +0100
commit4f50f2008f4d7c2a635f7f26861fcfc7f7504423 (patch)
tree94e6286e7e22e0467a61b99c18b9ab582fbbe656 /web/src/lib
parent3ebbdf6ffa16f751c82e3bd2e74294f4fe843155 (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')
-rw-r--r--web/src/lib/data/classInfo.ts29
-rw-r--r--web/src/lib/data/gameData.ts231
-rw-r--r--web/src/lib/game/art.ts27
-rw-r--r--web/src/lib/game/conditions.ts57
-rw-r--r--web/src/lib/game/elements.ts29
-rw-r--r--web/src/lib/game/levelValues.ts45
-rw-r--r--web/src/lib/game/stats.ts81
-rw-r--r--web/src/lib/i18n/en.ts138
-rw-r--r--web/src/lib/i18n/index.ts73
-rw-r--r--web/src/lib/protocol/connection.ts231
-rw-r--r--web/src/lib/protocol/types.ts214
-rw-r--r--web/src/lib/settings.ts33
-rw-r--r--web/src/lib/state/session.ts172
-rw-r--r--web/src/lib/ui/BottomBar.svelte22
-rw-r--r--web/src/lib/ui/CharacterRow.svelte195
-rw-r--r--web/src/lib/ui/ConnectionBanner.svelte20
-rw-r--r--web/src/lib/ui/DrawButton.svelte47
-rw-r--r--web/src/lib/ui/ElementButton.svelte88
-rw-r--r--web/src/lib/ui/LevelWidget.svelte52
-rw-r--r--web/src/lib/ui/MainList.svelte44
-rw-r--r--web/src/lib/ui/MainMenu.svelte89
-rw-r--r--web/src/lib/ui/Menu.svelte39
-rw-r--r--web/src/lib/ui/MonsterRow.svelte109
-rw-r--r--web/src/lib/ui/NoteRow.svelte57
-rw-r--r--web/src/lib/ui/StatusMenu.svelte211
-rw-r--r--web/src/lib/ui/Toast.svelte12
-rw-r--r--web/src/lib/ui/TopBar.svelte34
-rw-r--r--web/src/lib/ui/menus/ActionLogMenu.svelte83
-rw-r--r--web/src/lib/ui/menus/AddCharacterMenu.svelte96
-rw-r--r--web/src/lib/ui/menus/AddMonsterMenu.svelte125
-rw-r--r--web/src/lib/ui/menus/AddNoteRowMenu.svelte113
-rw-r--r--web/src/lib/ui/menus/AddSectionMenu.svelte79
-rw-r--r--web/src/lib/ui/menus/RemoveCharacterMenu.svelte86
-rw-r--r--web/src/lib/ui/menus/RemoveMonsterMenu.svelte81
-rw-r--r--web/src/lib/ui/menus/SelectScenarioMenu.svelte109
-rw-r--r--web/src/lib/ui/menus/SetLevelMenu.svelte66
-rw-r--r--web/src/lib/ui/menus/SettingsMenu.svelte50
37 files changed, 3234 insertions, 33 deletions
diff --git a/web/src/lib/data/classInfo.ts b/web/src/lib/data/classInfo.ts
new file mode 100644
index 0000000..6bbded0
--- /dev/null
+++ b/web/src/lib/data/classInfo.ts
@@ -0,0 +1,29 @@
+/**
+ * Class-metadata lookup for the rows: art, colour, per-level health. Loaded
+ * from the campaign edition JSON (via the shared `gameData` client) and
+ * cached per class.
+ */
+
+import { gameData, type ClassData } from './gameData';
+
+export type { ClassData };
+
+const cache = new Map<string, Promise<ClassData | null>>();
+
+export function classInfo(edition: string, className: string): Promise<ClassData | null> {
+ const key = `${edition}/${className}`;
+ let promise = cache.get(key);
+ if (!promise) {
+ promise = gameData
+ .loadCampaign(edition)
+ .then((c) => c.classes.find((x) => x.id === className) ?? null)
+ .catch(() => null);
+ cache.set(key, promise);
+ }
+ return promise;
+}
+
+/** True for the Escort / Objective classes (no initiative input). */
+export function isObjectiveOrEscort(className: string): boolean {
+ return className === 'Escort' || className === 'Objective';
+}
diff --git a/web/src/lib/data/gameData.ts b/web/src/lib/data/gameData.ts
new file mode 100644
index 0000000..2511022
--- /dev/null
+++ b/web/src/lib/data/gameData.ts
@@ -0,0 +1,231 @@
+/**
+ * Loads the campaign/character/monster/scenario data the menus read, from
+ * the same JSON files the engine uses (served at `/data/` by the Dart
+ * server). The reference app ships these as bundled assets; here the
+ * server is the single source and the client fetches on demand and caches.
+ */
+
+// --- Raw JSON shapes (the subset the UI needs) ----------------------------
+
+interface RawClass {
+ name: string;
+ edition: string;
+ health: number[];
+ hidden?: boolean;
+ color: string | string[];
+ colorSecondary?: string | string[];
+}
+
+interface RawMonsterStats {
+ health: number | string;
+ [ key: string ]: unknown;
+}
+interface RawMonsterLevel {
+ level: number;
+ normal?: RawMonsterStats;
+ elite?: RawMonsterStats;
+ boss?: RawMonsterStats;
+}
+interface RawMonster {
+ deck: string;
+ count: number;
+ levels: RawMonsterLevel[];
+ display?: string;
+ gfx?: string;
+ hidden?: boolean;
+ flying?: boolean;
+}
+interface RawScenario {
+ monsters?: string[];
+ lootDeck?: Record<string, number>;
+ special?: unknown[];
+ initialMessage?: string;
+}
+interface RawEdition {
+ edition: string;
+ classes: RawClass[];
+ monsters: Record<string, RawMonster>;
+ scenarios: Record<string, RawScenario>;
+}
+
+// --- UI-facing types -------------------------------------------------------
+
+export interface ClassData {
+ id: string;
+ name: string;
+ edition: string;
+ hidden: boolean;
+ health: number[];
+ color: string;
+ colorSecondary: string;
+ /** `/images/class-icons/<name>.png` */
+ icon: string;
+}
+
+export interface MonsterData {
+ name: string;
+ display: string;
+ gfx: string;
+ deck: string;
+ count: number;
+ hidden: boolean;
+ flying: boolean;
+ levels: RawMonsterLevel[];
+ maxLevel: number;
+ /** The first level has a boss block. */
+ isBoss: boolean;
+ edition: string;
+ /** `/images/monsters/<gfx>.png` */
+ portrait: string;
+}
+
+export interface ScenarioData {
+ name: string;
+ monsters: string[];
+}
+
+export interface CampaignData {
+ edition: string;
+ classes: ClassData[];
+ monsters: MonsterData[];
+ /** Scenario names in file order. */
+ scenarios: ScenarioData[];
+}
+
+export function firstColor(value: string | string[] | undefined, fallback = '000000') {
+ const v = Array.isArray(value) ? value[0] : value;
+ return v ?? fallback;
+}
+
+function escapePathSegment(value: string): string {
+ return encodeURIComponent(value);
+}
+
+// --- The loader ------------------------------------------------------------
+
+export class GameDataClient {
+ private campaignsPromise: Promise<string[]> | null = null;
+ private campaignsCache: string[] | null = null;
+ private readonly cache = new Map<string, Promise<CampaignData>>();
+ private readonly roomsCache = new Map<string, Promise<Record<string, Record<string, unknown>[]> | null>>();
+
+ constructor(private readonly base = '/data') {}
+
+ /** The list of campaign/edition names (order from `editions.json`). */
+ campaigns(): Promise<string[]> {
+ if (this.campaignsCache) return Promise.resolve(this.campaignsCache);
+ if (this.campaignsPromise) return this.campaignsPromise;
+ this.campaignsPromise = fetch(`${this.base}/editions/editions.json`)
+ .then((r) => r.json())
+ .then((d: { editions: string[] }) => {
+ this.campaignsCache = d.editions;
+ return d.editions;
+ });
+ return this.campaignsPromise;
+ }
+
+ /** Character classes, monsters, and scenario names for a campaign. */
+ loadCampaign(campaign: string): Promise<CampaignData> {
+ const cached = this.cache.get(campaign);
+ if (cached) return cached;
+ const promise = fetch(
+ `${this.base}/editions/${escapePathSegment(campaign)}.json`
+ )
+ .then((r) => {
+ if (!r.ok) throw new Error(`failed to load campaign ${campaign}`);
+ return r.json();
+ })
+ .then((raw: RawEdition) => ({
+ edition: raw.edition,
+ classes: raw.classes.map((c) => this.toClass(c)),
+ monsters: Object.entries(raw.monsters).map(([name, m]) =>
+ this.toMonster(name, m, raw.edition)
+ ),
+ scenarios: Object.entries(raw.scenarios).map(([name, s]) => ({
+ name,
+ monsters: s.monsters ?? []
+ }))
+ }));
+ this.cache.set(campaign, promise);
+ return promise;
+ }
+
+ /**
+ * The addable section names for a scenario, mirroring the server's
+ * `ScenarioModel`: the rooms file is keyed by the scenario number (the
+ * `#` and name stripped — `"#0 Howling in the Snow"` → `"0"`); the first
+ * room is the scenario start (skipped) and each remaining room's name is
+ * an addable section. Names containing "spawn" are excluded.
+ */
+ sections(campaign: string, scenario: string): Promise<string[]> {
+ const key = `${campaign}::${scenario}`;
+ const cached = this.roomsCache.get(campaign);
+ const roomsPromise = cached ??
+ fetch(`${this.base}/rooms/${escapePathSegment(campaign)}.json`)
+ .then((r) => (r.ok ? r.json() : null))
+ .then(
+ (rooms: Record<string, Record<string, unknown>[]> | null) => {
+ this.roomsCache.set(campaign, Promise.resolve(rooms));
+ return rooms;
+ }
+ );
+ const promise = roomsPromise.then((rooms) => {
+ if (!rooms) return [];
+ // The rooms key is the scenario number after `#` (first token):
+ // `"#1 A Town in Flames"` → `"1"`, `"#4A …"` → `"4A"`.
+ const nr = scenario.startsWith('#')
+ ? scenario.slice(1).split(/\s/)[0]
+ : scenario;
+ const entry = rooms[nr] ?? rooms[scenario] ?? null;
+ if (!Array.isArray(entry)) return [];
+ return entry
+ .slice(1) // skip the scenario start room
+ .map((room) => Object.keys(room)[0] ?? '')
+ .filter((name) => name && !name.toLowerCase().includes('spawn'));
+ });
+ this.roomsCache.set(campaign, roomsPromise);
+ void key; // (cache key kept for a possible per-scenario variant)
+ return promise;
+ }
+
+ private toClass(c: RawClass): ClassData {
+ const name = c.name;
+ return {
+ id: name,
+ name,
+ edition: c.edition,
+ hidden: c.hidden ?? false,
+ health: c.health,
+ color: firstColor(c.color),
+ colorSecondary: firstColor(c.colorSecondary, firstColor(c.color)),
+ icon: `/images/class-icons/${escapePathSegment(name)}.png`
+ };
+ }
+
+ private toMonster(name: string, m: RawMonster, edition: string): MonsterData {
+ const display = m.display ?? name;
+ const gfx = m.gfx ?? display;
+ const levels = m.levels ?? [];
+ const maxLevel = levels.reduce(
+ (max, l) => Math.max(max, l.level),
+ levels.length ? 0 : 1
+ );
+ return {
+ name,
+ display,
+ gfx,
+ deck: m.deck,
+ count: m.count,
+ hidden: m.hidden ?? false,
+ flying: m.flying ?? false,
+ levels,
+ maxLevel,
+ isBoss: levels.some((l) => l.boss != null),
+ edition,
+ portrait: `/images/monsters/${escapePathSegment(gfx)}.png`
+ };
+ }
+}
+
+/** The default shared client. */
+export const gameData = new GameDataClient();
diff --git a/web/src/lib/game/art.ts b/web/src/lib/game/art.ts
new file mode 100644
index 0000000..4be6637
--- /dev/null
+++ b/web/src/lib/game/art.ts
@@ -0,0 +1,27 @@
+/**
+ * Artwork helpers. The Dart server serves the engine's image assets under
+ * `/images/` (mirroring the reference app's `assets/images/`).
+ */
+
+/** Character-class icon (the reference row art). */
+export function classIcon(className: string): string {
+ return `/images/class-icons/${className}.png`;
+}
+
+/** Monster / summon artwork. */
+export function monsterImage(gfx: string): string {
+ return `/images/monsters/${gfx}.png`;
+}
+
+/**
+ * A character-class background colour. The data stores a Flutter ARGB hex
+ * string (e.g. `"ffa28b7c"`); CSS wants `#rrggbb` with the alpha dropped
+ * (the reference uses it at full opacity as the row backdrop).
+ */
+export function classColor(argb: string): string {
+ if (/^[0-9a-f]{8}$/i.test(argb)) {
+ return `#${argb.slice(2)}`;
+ }
+ if (/^#[0-9a-f]{6}$/i.test(argb)) return argb;
+ return '#3a3f47';
+}
diff --git a/web/src/lib/game/conditions.ts b/web/src/lib/game/conditions.ts
new file mode 100644
index 0000000..b7579ac
--- /dev/null
+++ b/web/src/lib/game/conditions.ts
@@ -0,0 +1,57 @@
+/**
+ * The `Condition` enum (server `lib/core/enums.dart`). The state serializes
+ * conditions as their index; the wire commands `addCondition` /
+ * `removeCondition` take the enum *name*.
+ */
+
+export const CONDITIONS = [
+ { name: 'stun', label: 'Stunned' },
+ { name: 'immobilize', label: 'Immobilized' },
+ { name: 'disarm', label: 'Disarmed' },
+ { name: 'wound', label: 'Wounded' },
+ { name: 'wound2', label: 'Wounded x2' },
+ { name: 'muddle', label: 'Muddled' },
+ { name: 'poison', label: 'Poisoned' },
+ { name: 'poison2', label: 'Poisoned x2' },
+ { name: 'poison3', label: 'Poisoned x3' },
+ { name: 'poison4', label: 'Poisoned x4' },
+ { name: 'bane', label: 'Bane' },
+ { name: 'brittle', label: 'Brittle' },
+ { name: 'chill', label: 'Chilled' },
+ { name: 'infect', label: 'Infected' },
+ { name: 'impair', label: 'Impaired' },
+ { name: 'rupture', label: 'Ruptured' },
+ { name: 'plague', label: 'Plagued' },
+ { name: 'strengthen', label: 'Strengthened' },
+ { name: 'invisible', label: 'Invisible' },
+ { name: 'regenerate', label: 'Regenerating' },
+ { name: 'ward', label: 'Warded' },
+ { name: 'dodge', label: 'Dodging' },
+ { name: 'safeguard', label: 'Safeguard' },
+ { name: 'shield', label: 'Shielded' },
+ { name: 'retaliate', label: 'Retaliating' },
+ // character1..4 are custom per-character slots; they are managed by the
+ // game data, not the condition menu, so they are excluded here.
+] as const;
+
+export type ConditionName = (typeof CONDITIONS)[number]['name'];
+
+/** Human label for a condition index (falling back to the index). */
+export function conditionLabel(index: number): string {
+ const c = CONDITIONS[index];
+ return c ? c.label : `condition ${index}`;
+}
+
+/** Wire name for a condition index (falling back to the index). */
+export function conditionName(index: number): string {
+ const c = CONDITIONS[index];
+ return c ? c.name : `condition${index}`;
+}
+
+/** True when [index] is chill or plague (rendered with a coloured chip). */
+export function conditionChipClass(index: number): string {
+ const name = CONDITIONS[index]?.name;
+ if (name === 'chill') return 'cond cond--chill';
+ if (name === 'plague') return 'cond cond--plague';
+ return 'cond';
+}
diff --git a/web/src/lib/game/elements.ts b/web/src/lib/game/elements.ts
new file mode 100644
index 0000000..61ecde3
--- /dev/null
+++ b/web/src/lib/game/elements.ts
@@ -0,0 +1,29 @@
+/**
+ * The six elemental abilities. The indices match the server's `Elements`
+ * enum (the state serializes `elementState` as element-index →
+ * state-index), and the wire commands `useElement` / `imbueElement` take
+ * the enum *name*.
+ */
+
+export const ELEMENTS = [
+ { name: 'fire', label: 'Fire', color: 'var(--el-fire)', icon: '/images/psd/element-fire.png' },
+ { name: 'ice', label: 'Ice', color: 'var(--el-ice)', icon: '/images/psd/element-ice.png' },
+ { name: 'air', label: 'Air', color: 'var(--el-air)', icon: '/images/psd/element-air.png' },
+ { name: 'earth', label: 'Earth', color: 'var(--el-earth)', icon: '/images/psd/element-earth.png' },
+ { name: 'light', label: 'Light', color: 'var(--el-light)', icon: '/images/psd/element-light.png' },
+ { name: 'dark', label: 'Dark', color: 'var(--el-dark)', icon: '/images/psd/element-dark.png' },
+] as const;
+
+/** ElementState index: 0 full, 1 half, 2 inert. */
+export type ElementState = 0 | 1 | 2;
+
+/**
+ * The element's fill state from the game state (absent → inert), matching
+ * the reference `ElementButton`: a tap uses the element when it is active,
+ * imbues it (full) when inert; a long press imbues the half (advanced)
+ * amount.
+ */
+export function elementState(state: Record<string, number>, index: number): ElementState {
+ const value = state[String(index)];
+ return value === 0 || value === 1 || value === 2 ? value : 2;
+}
diff --git a/web/src/lib/game/levelValues.ts b/web/src/lib/game/levelValues.ts
new file mode 100644
index 0000000..01b70a0
--- /dev/null
+++ b/web/src/lib/game/levelValues.ts
@@ -0,0 +1,45 @@
+/**
+ Scenario level values shown by the level widget (a port of the reference
+ `GameMethods.getTrapValue/getHazardValue/getXPValue/getCoinValue`).
+ */
+
+export function trapValue(level: number): number {
+ return 2 + level;
+}
+
+/**
+ The reference halves the trap value for OGGloom games unless the
+ "FH hazard/terrain calc in OG Gloomhaven" setting is on.
+ */
+export function hazardValue(
+ level: number,
+ isOgGloom: boolean,
+ fhHazTerrainCalcInOGGloom: boolean
+): number {
+ if (isOgGloom && !fhHazTerrainCalcInOGGloom) {
+ return Math.floor(trapValue(level) / 2);
+ }
+ return 1 + Math.ceil(level / 3);
+}
+
+export function xpValue(level: number): number {
+ return 4 + 2 * level;
+}
+
+export function coinValue(level: number): number {
+ if (level === 7) return 6;
+ return 2 + Math.floor(level / 2);
+}
+
+/** The reference `GameMethods.getRecommendedLevel`. */
+export function recommendedLevel(
+ characterLevels: number[],
+ solo: boolean
+): number {
+ if (characterLevels.length === 0) return 1;
+ const total = characterLevels.reduce((a, b) => a + b, 0);
+ if (solo) {
+ return Math.ceil((total / characterLevels.length + 1) / 2);
+ }
+ return Math.ceil(total / characterLevels.length / 2);
+}
diff --git a/web/src/lib/game/stats.ts b/web/src/lib/game/stats.ts
new file mode 100644
index 0000000..d842159
--- /dev/null
+++ b/web/src/lib/game/stats.ts
@@ -0,0 +1,81 @@
+/**
+ * Reads current stat values for the status menu from the live state.
+ *
+ * Health / max / xp / chill / conditions live on the figure; bless, curse,
+ * empower and enfeeble live as modifier-deck cards — the server keeps their
+ * counter in sync with the matching cards in the character's draw pile, so
+ * counting the cards here mirrors the server's own computation.
+ */
+
+import type {
+ CharacterItem,
+ MonsterInstance
+} from '$lib/protocol/types';
+
+export interface ModifierCard {
+ gfx: string;
+}
+
+export interface ModifierDeckJson {
+ drawPile: ModifierCard[];
+ discardPile: ModifierCard[];
+ removedPile?: ModifierCard[];
+ [ key: string ]: unknown;
+}
+
+/**
+ * The wire `figureId` for a standee (a monster instance or a summon): the
+ * reference app builds it as `name + gfx + standeeNr`.
+ */
+export function standeeFigureId(standee: MonsterInstance): string {
+ return standee.name + standee.gfx + standee.standeeNr.toString();
+}
+
+/** Count modifier cards matching [predicate] in the draw pile. */
+function countCards(
+ deck: ModifierDeckJson | undefined,
+ predicate: (gfx: string) => boolean
+): number {
+ if (!deck?.drawPile) return 0;
+ return deck.drawPile.filter((c) => c && predicate(c.gfx)).length;
+}
+
+/**
+ * The stat counters for a character, keyed by the modifier-deck removable
+ * name (which is also the `gfx` wire arg for empower/enfeeble).
+ */
+export function characterStatCounters(
+ character: CharacterItem
+): {
+ bless: number;
+ curse: number;
+ empower: number;
+ enfeeble: number;
+} {
+ const deck = character.characterState.modifierDeck as
+ | ModifierDeckJson
+ | undefined;
+ return {
+ bless: countCards(deck, (g) => g === 'bless'),
+ curse: countCards(deck, (g) => g === 'curse'),
+ empower: countCards(deck, (g) => g.includes('empower')),
+ enfeeble: countCards(deck, (g) => g.includes('enfeeble'))
+ };
+}
+
+/** The stat counters for a standee (its owner's modifier deck). */
+export function standeeStatCounters(
+ deck: ModifierDeckJson | undefined
+): {
+ bless: number;
+ curse: number;
+ empower: number;
+ enfeeble: number;
+} {
+ return {
+ bless: countCards(deck, (g) => g === 'bless'),
+ curse: countCards(deck, (g) => g === 'curse'),
+ empower: countCards(deck, (g) => g.includes('empower')),
+ enfeeble: countCards(deck, (g) => g.includes('enfeeble'))
+ };
+}
diff --git a/web/src/lib/i18n/en.ts b/web/src/lib/i18n/en.ts
new file mode 100644
index 0000000..b7037a7
--- /dev/null
+++ b/web/src/lib/i18n/en.ts
@@ -0,0 +1,138 @@
+/**
+ * English UI strings, ported from the reference app's `app_en.arb` (the subset
+ * the Phase 3 core-loop UI uses). Placeholder syntax: Flutter uses `{name}`,
+ * which `t()` substitutes from its `vars` map.
+ *
+ * Web-only strings (no `.arb` counterpart) — the spectator model, the claim
+ * flow, and reconnect UX — are added here and marked `web:`.
+ */
+export const en: Record<string, string> = {
+ // Menus / top bar
+ 'menuSetScenario': 'Set Scenario',
+ 'menuAddCharacter': 'Add Character',
+ 'menuRemoveCharacters': 'Remove Characters',
+ 'menuSetLevel': 'Set Level',
+ 'menuAddMonsters': 'Add Monsters',
+ 'menuRemoveMonsters': 'Remove Monsters',
+ 'menuSettings': 'Settings',
+ 'menuDocumentation': 'Documentation',
+ 'menuAddSection': 'Add Section',
+ 'menuAddNoteRow': 'Add Note Row',
+ 'menuActionLog': 'View Action Log',
+ 'currentCampaign': 'Current Campaign: {campaign}',
+
+ // Action log
+ 'actionLogTitle': 'Last 20 Actions',
+ 'actionLogEmpty': 'No actions yet',
+ 'actionLogRollbackHint': 'Tap an action to roll back to it',
+ 'actionLogRollbackTitle': 'Roll back?',
+ 'actionLogRollbackBody': 'Undo back to "{action}"? This reverses {count} later action(s). You can redo them until you make a change.',
+ 'actionLogRollbackConfirm': 'Roll back',
+
+ // Note rows
+ 'noteRowTitle': 'Note',
+ 'noteRowHint': 'Note text…',
+ 'noteRowAddFromMenu': 'Add note',
+ 'noteRowDelete': 'Delete note',
+ 'noteRowWholeGroup': 'Whole group',
+ 'noteRowAll': 'All',
+
+ // Common
+ 'undo': 'Undo',
+ 'redo': 'Redo',
+ 'undoWithDescription': 'Undo: {description}',
+ 'redoWithDescription': 'Redo: {description}',
+ 'close': 'Close',
+ 'retry': 'RETRY',
+ 'removeAll': 'Remove All',
+ 'noResultsFound': 'No results found',
+ 'levelLegendLabel': 'level',
+
+ // Scenario setup
+ 'setScenarioLevel': 'Set Scenario Level',
+ 'enhancedLevel': 'Enhanced: {level}',
+ 'soloLabel': 'Solo:',
+ 'automaticScenarioLevel': 'Automatic Scenario Level:',
+ 'difficultyLabel': 'Difficulty:',
+ 'allCampaigns': 'All Campaigns',
+ 'addMonsterLabel': 'Add Monster',
+ 'showMonstersFrom': 'Show monsters from:',
+
+ // Monsters
+ 'setMonsterLevel': "Set {name}'s level",
+ 'cmdAddMonster': 'Add {name}',
+ 'cmdRemoveMonster': 'Remove {name}',
+ 'cmdRemoveAllMonsters': 'Remove all monsters',
+ 'addStandeeNr': 'Add Standee Nr',
+
+ // Characters
+ 'addCharacterHint': 'Add Character (type name for hidden character classes)',
+ 'cmdAddCharacter': 'Add {id}',
+ 'cmdRemoveCharacter': 'Remove {id}',
+ 'cmdRemoveAllCharacters': 'Remove all characters',
+ 'cmdSetCharacterLevel': "Set {character}'s Level",
+ 'setLootOwner': 'Set Loot Owner:',
+
+ // Stat changes
+ 'cmdChangeStat': 'Change stat',
+ 'cmdIncreaseHealth': "Increase {figure}'s health by {amount}",
+ 'cmdDecreaseHealth': "Decrease {owner}'s health by {amount}",
+ 'cmdIncreaseMaxHealth': "Increase {owner}'s max health",
+ 'cmdDecreaseMaxHealth': "Decrease {owner}'s max health",
+ 'cmdIncreaseXp': "Increase {figure}'s xp by {amount}",
+ 'cmdDecreaseXp': "Decrease {figure}'s xp by {amount}",
+ 'cmdAddBless': 'Add a Bless',
+ 'cmdRemoveBless': 'Remove a Bless',
+ 'cmdAddCurse': 'Add a Curse',
+ 'cmdRemoveCurse': 'Remove a Curse',
+ 'cmdAddEmpower': 'Add Empower',
+ 'cmdRemoveEmpower': 'Remove Empower',
+ 'cmdAddEnfeeble': 'Add Enfeeble',
+ 'cmdRemoveEnfeeble': 'Remove Enfeeble',
+
+ // Conditions
+ 'cmdAddCondition': 'Add condition: {condition}',
+ 'cmdRemoveCondition': 'Remove condition: {condition}',
+
+ // Elements
+ 'cmdUseElement': 'Use Element {element}',
+ 'cmdImbueElement': 'Imbue element {element}',
+ 'removeImbue': 'Remove Imbue',
+ 'imbue': 'Imbue',
+ 'advancedImbue': 'Advanced Imbue',
+
+ // Turn / round
+ 'cmdTurnDone': "{id}'s turn done",
+ 'cmdDraw': 'Draw',
+ 'cmdNextRound': 'Next Round',
+ 'draw': 'Draw',
+ 'nextRound': 'Next Round',
+ 'shuffleAndDraw': 'Shuffle & Draw',
+ 'cmdSetInitiative': 'Set initiative of {character}',
+
+ // Sections
+ 'cmdAddSection': 'Add Section',
+
+ // Connection UX
+ 'connecting': 'Connecting...',
+ 'web:reconnecting': 'Reconnecting…',
+ 'web:connected': 'Connected',
+ 'lostConnectionToServer': 'Lost connection to server',
+ 'stateMismatch': 'Your state was not up to date, try again.',
+ 'serverOffline': 'Server Offline',
+ 'clientError': 'Client error: {error}',
+
+ // Player / spectator (web-only: the reference app has no spectator role)
+ 'web:spectator': 'Spectating',
+ 'web:player': 'Playing',
+ 'web:unclaimed': 'Unclaimed',
+ 'web:claimCharacter': 'Claim this character',
+ 'web:claimPrompt': 'You have not claimed a character yet. Tap a character row to claim it and take control.',
+ 'web:yourCharacter': 'You',
+ 'web:secret': '??',
+ 'web:initiative': 'Initiative',
+ 'web:noScenario': 'No scenario set',
+ 'web:round': 'Round',
+ 'web:level': 'Level',
+ 'web:difficulty': 'Difficulty'
+};
diff --git a/web/src/lib/i18n/index.ts b/web/src/lib/i18n/index.ts
new file mode 100644
index 0000000..9634712
--- /dev/null
+++ b/web/src/lib/i18n/index.ts
@@ -0,0 +1,73 @@
+/**
+ * UI string i18n (Phase 3: English first, locale plumbing in place).
+ *
+ * The reference app generates its UI strings from `.arb` files (gen-l10n);
+ * here we port the English set as a plain object and keep the same shape so
+ * the other 9 locales can be dropped in later (Phase 6). `t()` falls back to
+ * English for any key a locale is missing.
+ */
+
+import { get, writable, type Writable } from 'svelte/store';
+
+import { en } from './en';
+
+export type Locale =
+ | 'en'
+ | 'de'
+ | 'es'
+ | 'fr'
+ | 'ko'
+ | 'pl'
+ | 'ru'
+ | 'th'
+ | 'zh'
+ | 'zh_Hant';
+
+/** Locale → its string table. English is the only one ported in Phase 3. */
+const tables: Record<string, Record<string, string>> = { en };
+
+const LOCALE_KEY = 'x-haven-locale';
+
+function initialLocale(): Locale {
+ try {
+ const stored = window.localStorage.getItem(LOCALE_KEY);
+ if (stored && tables[stored]) return stored as Locale;
+ } catch {
+ // localStorage unavailable (SSR / privacy mode) — fall through.
+ }
+ return 'en';
+}
+
+export const locale: Writable<Locale> = writable<Locale>(initialLocale());
+
+locale.subscribe((value) => {
+ try {
+ window.localStorage.setItem(LOCALE_KEY, value);
+ } catch {
+ // ignore
+ }
+});
+
+/** The locales currently available in the client (for the settings picker). */
+export const availableLocales = Object.keys(tables);
+
+/**
+ * Translate a key with the active locale, falling back to English. Returns
+ * the key itself when it is unknown everywhere (so missing strings are
+ * visible rather than silently blank).
+ */
+export function t(key: string, vars?: Record<string, string | number>): string {
+ const active = tables[get(locale)] ?? {};
+ let template = active[key] ?? en[key] ?? key;
+ if (vars) {
+ for (const [name, value] of Object.entries(vars)) {
+ template = template.replaceAll(`{${name}}`, String(value));
+ }
+ }
+ return template;
+}
+
+/** True when [key] exists in the active locale (vs. falling back). */
+export function hasLocaleKey(key: string): boolean {
+ return key in (tables[get(locale)] ?? {});
+}
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;
diff --git a/web/src/lib/settings.ts b/web/src/lib/settings.ts
new file mode 100644
index 0000000..4238066
--- /dev/null
+++ b/web/src/lib/settings.ts
@@ -0,0 +1,33 @@
+/**
+ Client-side preferences (no server counterpart — these style the local
+ browser only). The reference app keeps them in `Settings` via
+ shared_preferences; here they live in localStorage.
+ */
+import { writable, type Writable } from 'svelte/store';
+
+export type StyleTheme = 'frosthaven' | 'gloomhaven' | 'original';
+
+const STYLE_KEY = 'x-haven-style';
+
+function initialStyle(): StyleTheme {
+ try {
+ const stored = window.localStorage.getItem(STYLE_KEY);
+ if (stored === 'frosthaven' || stored === 'gloomhaven' || stored === 'original') {
+ return stored;
+ }
+ } catch {
+ /* private browsing / disabled storage */
+ }
+ return 'frosthaven';
+}
+
+/** The visual style theme (PLAN.md Phase 3: the three style themes). */
+export const styleTheme: Writable<StyleTheme> = writable<StyleTheme>(initialStyle());
+
+styleTheme.subscribe((value) => {
+ try {
+ window.localStorage.setItem(STYLE_KEY, value);
+ } catch {
+ /* ignore */
+ }
+});
diff --git a/web/src/lib/state/session.ts b/web/src/lib/state/session.ts
new file mode 100644
index 0000000..c8820d4
--- /dev/null
+++ b/web/src/lib/state/session.ts
@@ -0,0 +1,172 @@
+/**
+ * The game session as seen by one browser: the live connection plus the
+ * derived Svelte stores the UI reads from.
+ *
+ * The server is the single source of truth (PLAN.md section 3.1): this
+ * client holds only the last full state snapshot, the seat table, its own
+ * session identity, and connection status. Every mutation is a command sent
+ * to the server; the resulting `update` replaces the local snapshot.
+ */
+
+import { derived, writable, get, type Readable, type Writable } from 'svelte/store';
+
+import {
+ GameConnection,
+ type ConnectionOptions,
+ type ConnectionStatus
+} from '../protocol/connection';
+import type {
+ GameState,
+ Role,
+ ServerMessage
+} from '../protocol/types';
+
+export interface SessionInfo {
+ id: string;
+ role: Role;
+}
+
+export interface ProtocolError {
+ code: string;
+ message: string;
+}
+
+export class GameSession {
+ readonly state: Writable<GameState | null> = writable<GameState | null>(null);
+ readonly seats: Writable<Record<string, string | null>> = writable({});
+ readonly session: Writable<SessionInfo | null> = writable<SessionInfo | null>(null);
+ readonly status: Writable<ConnectionStatus> = writable('connecting');
+ readonly index: Writable<number> = writable(-1);
+ readonly description: Writable<string | null> = writable<string | null>(null);
+ readonly lastError: Writable<ProtocolError | null> =
+ writable<ProtocolError | null>(null);
+
+ /**
+ * Reactive player/spectator flag derived from the live seat table (see
+ * `isSpectator()`). The UI reads this as a store — it flips the moment
+ * a claim is granted, without waiting for a new `welcome`.
+ */
+ readonly player: Readable<boolean> = derived(
+ [this.session, this.seats],
+ ([session, seats]) => {
+ if (!session) return false;
+ return Object.values(seats).some((owner) => owner === session.id);
+ }
+ );
+
+ private readonly connection: GameConnection;
+
+ constructor(options: ConnectionOptions = {}) {
+ this.connection = new GameConnection(options);
+ this.connection.onStatus = (s) => this.status.set(s);
+ this.connection.onMessage = (m) => this.handle(m);
+ this.connection.onError = (e) =>
+ this.lastError.set({ code: e.code, message: e.message });
+ }
+
+ /** The underlying connection (for advanced control / resync). */
+ get conn(): GameConnection {
+ return this.connection;
+ }
+
+ private handle(message: ServerMessage): void {
+ switch (message.t) {
+ case 'welcome':
+ this.session.set({ id: message.session, role: message.role });
+ this.state.set(message.state);
+ this.seats.set(message.seats);
+ this.index.set(message.index);
+ this.description.set(message.description);
+ break;
+ case 'update':
+ this.state.set(message.state);
+ this.index.set(message.index);
+ this.description.set(message.description);
+ break;
+ case 'seats':
+ this.seats.set(message.seats);
+ break;
+ case 'error':
+ this.lastError.set({ code: message.code, message: message.message });
+ break;
+ case 'pong':
+ // keepalive ack — nothing to surface
+ break;
+ }
+ }
+
+ connect(): void {
+ this.connection.connect();
+ }
+
+ disconnect(): void {
+ this.connection.disconnect();
+ }
+
+ // --- ownership ------------------------------------------------------------
+
+ /** True when [characterId] is owned by this session. */
+ owns(characterId: string): boolean {
+ const s = get(this.session);
+ const seats = get(this.seats);
+ return !!s && seats[characterId] === s.id;
+ }
+
+ /** This session's role (null before the first welcome). */
+ role(): Role | null {
+ return get(this.session)?.role ?? null;
+ }
+
+ /** The character ids this session owns. */
+ ownedCharacterIds(): string[] {
+ const s = get(this.session);
+ if (!s) return [];
+ const seats = get(this.seats);
+ return Object.keys(seats).filter((id) => seats[id] === s.id);
+ }
+
+ /**
+ * A spectator has claimed no character. Derived from the live seat table
+ * (not the `welcome` role, which is only computed at handshake) so that
+ * the moment a claim is granted the UI switches to player controls —
+ * the `seats` broadcast carries the truth.
+ */
+ isSpectator(): boolean {
+ return this.ownedCharacterIds().length === 0;
+ }
+
+ // --- commands -------------------------------------------------------------
+
+ command(name: string, args: Record<string, unknown> = {}): void {
+ this.connection.sendCmd(name, args);
+ }
+
+ claim(characterId: string): void {
+ this.connection.claim(characterId);
+ }
+
+ undo(): void {
+ this.connection.undo();
+ }
+
+ redo(): void {
+ this.connection.redo();
+ }
+
+ /** Clear a surfaced protocol error (call after toasting it). */
+ clearError(): void {
+ this.lastError.set(null);
+ }
+}
+
+/**
+ * Convenience: the set of character ids owned by a given session within a
+ * seat table. Exported for unit testing.
+ */
+export function ownedIds(
+ sessionId: string | null,
+ seats: Record<string, string | null>
+): string[] {
+ if (!sessionId) return [];
+ return Object.keys(seats).filter((id) => seats[id] === sessionId);
+}
diff --git a/web/src/lib/ui/BottomBar.svelte b/web/src/lib/ui/BottomBar.svelte
new file mode 100644
index 0000000..b4161ca
--- /dev/null
+++ b/web/src/lib/ui/BottomBar.svelte
@@ -0,0 +1,22 @@
+<!--
+ The bottom bar (the reference `BottomBar`): the draw/next-round button
+ and the scenario level widget.
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import DrawButton from './DrawButton.svelte';
+ import LevelWidget from './LevelWidget.svelte';
+
+ let {
+ session,
+ onOpenSetLevel
+ }: {
+ session: GameSession;
+ onOpenSetLevel: () => void;
+ } = $props();
+</script>
+
+<div class="bottombar">
+ <DrawButton {session} />
+ <LevelWidget {session} onOpenMenu={onOpenSetLevel} />
+</div>
diff --git a/web/src/lib/ui/CharacterRow.svelte b/web/src/lib/ui/CharacterRow.svelte
new file mode 100644
index 0000000..f4fdd76
--- /dev/null
+++ b/web/src/lib/ui/CharacterRow.svelte
@@ -0,0 +1,195 @@
+<!--
+ A character row (the reference `CharacterWidget`): class-coloured
+ backdrop, class art, the initiative slot, the name and health line with
+ condition chips, and the XP / level on the right.
+
+ Initiative (the server-gated secret, PLAN.md section 3.4):
+ - during chooseInitiative the owning player sees an editable field;
+ every other connection sees `??` (the server masks the value to
+ `null` for them)
+ - a value set by the owner is visible to the owner; after the draw the
+ number stays visible to everyone
+ The right-hand tap zone focuses the initiative field (chooseInitiative)
+ or ends the character's turn (playTurns), like the reference; tapping
+ the row opens the stat menu.
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import type { CharacterItem } from '$lib/protocol/types';
+ import { classInfo, isObjectiveOrEscort, type ClassData } from '$lib/data/classInfo';
+ import { classColor, classIcon } from '$lib/game/art';
+ import { conditionChipClass, conditionLabel } from '$lib/game/conditions';
+ import type { FigureRef } from './StatusMenu.svelte';
+
+ let {
+ session,
+ item,
+ onOpenMenu
+ }: {
+ session: GameSession;
+ item: CharacterItem;
+ onOpenMenu: (figure: FigureRef) => void;
+ } = $props();
+
+ const seats = session.seats;
+ const player = session.player;
+ const gameState = session.state;
+ const mySession = session.session; // my own {id, role} (store)
+
+ let cls = $state<ClassData | null>(null);
+ $effect(() => {
+ let alive = true;
+ classInfo(item.edition, item.characterClass)
+ .then((c) => {
+ if (alive) cls = c;
+ })
+ .catch(() => {});
+ return () => {
+ alive = false;
+ };
+ });
+
+ const cs = $derived(item.characterState);
+ const alive = $derived(cs.health > 0);
+ const roundState = $derived($gameState?.roundState ?? 0);
+ const turnState = $derived(item.turnState);
+ const isObjective = $derived(isObjectiveOrEscort(item.characterClass));
+
+ const owner = $derived($seats[item.id] ?? null);
+ const mine = $derived(!!$player && owner != null && owner === $mySession?.id);
+ const unclaimed = $derived(owner === null);
+
+ const currentTurn = $derived(roundState === 1 && turnState === 1);
+ const done = $derived(roundState === 1 && turnState === 2);
+
+ const canEnterInit = $derived(
+ roundState === 0 && alive && !isObjective && mine && $gameState != null
+ );
+
+ let initInput = $state<HTMLInputElement | null>(null);
+ let initDraft = $state('');
+
+ // `??` for a value masked by the server; the revealed number otherwise.
+ const initDisplay = $derived(
+ cs.initiative === null ? '??' : cs.initiative > 0 ? String(cs.initiative) : ''
+ );
+ const showInitNumber = $derived(
+ roundState === 0 ? alive && !canEnterInit : alive
+ );
+
+ function onInitInput() {
+ const value = initDraft.trim();
+ if (
+ /^\d{1,2}$/.test(value) &&
+ value !== '0' &&
+ cs.initiative !== Number(value)
+ ) {
+ session.command('setInit', { characterId: item.id, init: Number(value) });
+ }
+ }
+
+ function onTurnTap() {
+ if (roundState === 0) {
+ initInput?.focus();
+ return;
+ }
+ if (roundState === 1 && alive && $player) {
+ session.command('turnDone', { id: item.id });
+ }
+ }
+
+ const figure: FigureRef = $derived({
+ title: cs.display,
+ figureId: item.id,
+ ownerId: null,
+ kind: 'character',
+ rowId: item.id,
+ isObjective
+ });
+</script>
+
+<div
+ class="row row--character"
+ class:row--current={currentTurn}
+ class:row--done={done}
+ class:row--dead={!alive}
+>
+ <div
+ class="row__bg"
+ style:background-color={cls ? classColor(cls.color) : '#3a3f47'}
+ ></div>
+
+ <div class="row__inner">
+ <div
+ class="row__art"
+ role="button"
+ tabindex="0"
+ onclick={() => onOpenMenu(figure)}
+ onkeydown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') onOpenMenu(figure);
+ }}
+ >
+ <img src={cls ? classIcon(cls.name) : ''} alt={cs.display} loading="lazy" />
+ </div>
+
+ {#if canEnterInit}
+ <input
+ class="init__input"
+ bind:this={initInput}
+ bind:value={initDraft}
+ oninput={onInitInput}
+ onclick={() => (initDraft = '')}
+ maxlength={2}
+ inputmode="numeric"
+ autocomplete="off"
+ aria-label="Initiative"
+ />
+ {:else if showInitNumber}
+ <div class="init" class:init__secret={cs.initiative === null}>{initDisplay}</div>
+ {/if}
+
+ <div
+ style="overflow: hidden; min-width: 0; flex: 1"
+ role="button"
+ tabindex="0"
+ onclick={() => onOpenMenu(figure)}
+ onkeydown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') onOpenMenu(figure);
+ }}
+ >
+ <div class="row__name">{cs.display}</div>
+ <div class="row__hp">
+ {cs.health} / {cs.maxHealth}
+ <span class="conds">
+ {#each cs.conditions as condIndex}
+ <span class={conditionChipClass(condIndex)}>{conditionLabel(condIndex)}</span>
+ {/each}
+ </span>
+ </div>
+ </div>
+
+ {#if !isObjective}
+ <span class="row__xp">XP {cs.xp}</span>
+ {/if}
+ <span class="row__level">{cs.level}</span>
+ {#if cs.summonList.length > 0}
+ <span class="row__summon">⚔ {cs.summonList.length}</span>
+ {/if}
+
+ <!-- Right-hand tap zone: initiative focus / turn done (reference). -->
+ <div
+ style="width: 70px; height: 100%; flex: 0 0 auto"
+ role="button"
+ tabindex="0"
+ aria-label={roundState === 0 ? 'Initiative' : 'Turn done'}
+ onclick={onTurnTap}
+ onkeydown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') onTurnTap();
+ }}
+ ></div>
+ </div>
+</div>
+
+{#if unclaimed}
+ <button class="chip chip--claim" onclick={() => session.claim(item.id)}>Claim</button>
+{/if}
diff --git a/web/src/lib/ui/ConnectionBanner.svelte b/web/src/lib/ui/ConnectionBanner.svelte
new file mode 100644
index 0000000..94bfd43
--- /dev/null
+++ b/web/src/lib/ui/ConnectionBanner.svelte
@@ -0,0 +1,20 @@
+<!--
+ The connection-status banner (PLAN.md Phase 3 "Connection UX"): shown
+ while the client is connecting for the first time or reconnecting after
+ a drop (the connection layer retries with backoff and re-sends `hello`
+ to resync). It is informational — no action is required from the user,
+ and the server overwrites any drifted state on resync.
+-->
+<script lang="ts">
+ import type { ConnectionStatus } from '$lib/protocol/connection';
+ import { t } from '$lib/i18n';
+
+ let { status }: { status: ConnectionStatus } = $props();
+
+ const visible = $derived(status === 'reconnecting' || status === 'connecting');
+ const text = $derived(status === 'reconnecting' ? t('web:reconnecting') : t('connecting'));
+</script>
+
+{#if visible}
+ <div class="banner" role="status">{text}</div>
+{/if}
diff --git a/web/src/lib/ui/DrawButton.svelte b/web/src/lib/ui/DrawButton.svelte
new file mode 100644
index 0000000..40d9245
--- /dev/null
+++ b/web/src/lib/ui/DrawButton.svelte
@@ -0,0 +1,47 @@
+<!--
+ The bottom-bar draw button (the reference `DrawButtonWidget`): "Draw"
+ while choosing initiative, "Next Round" during turns, with the round
+ counter beneath.
+
+ Draw gating: only players act (the server rejects spectators). A player
+ may tap draw at any point during chooseInitiative — initiative values are
+ masked per connection (PLAN.md 3.4), so the client cannot know whether a
+ teammate has entered theirs; the server rejects an early draw with the
+ "all players must set initiative" error, which surfaces as a toast.
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import { t } from '$lib/i18n';
+
+ let { session }: { session: GameSession } = $props();
+
+ const gameState = session.state;
+ const player = session.player;
+ const status = session.status;
+
+ const roundState = $derived($gameState?.roundState ?? 0);
+ const label = $derived(roundState === 0 ? t('draw') : t('nextRound'));
+ const locked = $derived(
+ !$player || $gameState === null || ($status !== 'open' && $status !== 'reconnecting')
+ );
+
+ function onDraw() {
+ if (locked) return;
+ if (roundState === 0) session.command('draw', {});
+ else session.command('nextRound', {});
+ }
+</script>
+
+<button
+ class="drawbtn"
+ class:drawbtn--locked={locked}
+ disabled={locked}
+ onclick={onDraw}
+>
+ {label}
+ {#if $gameState}
+ <span class="drawbtn__round">
+ {t('web:round')} {$gameState.round}/{$gameState.totalRounds}
+ </span>
+ {/if}
+</button>
diff --git a/web/src/lib/ui/ElementButton.svelte b/web/src/lib/ui/ElementButton.svelte
new file mode 100644
index 0000000..46fd397
--- /dev/null
+++ b/web/src/lib/ui/ElementButton.svelte
@@ -0,0 +1,88 @@
+<!--
+ One of the six elemental ability buttons in the top bar. The coloured
+ fill rises with the element's state (inert → half → full), exactly like
+ the reference `ElementButton`:
+ - tap: uses the element when it is active, imbues (full) when inert
+ - long press: imbues the half ("advanced") amount
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import { elementState } from '$lib/game/elements';
+
+ let {
+ session,
+ index,
+ name,
+ color,
+ icon,
+ label
+ }: {
+ session: GameSession;
+ /** The `Elements` index (state map key). */
+ index: number;
+ /** The `Elements` wire name. */
+ name: string;
+ color: string;
+ icon: string;
+ label: string;
+ } = $props();
+
+ const gameState = session.state;
+ const status = session.status;
+ const player = session.player;
+
+ let pressTimer: ReturnType<typeof setTimeout> | null = null;
+ let longPressed = false;
+
+ const elState = $derived($gameState ? elementState($gameState.elementState, index) : 2);
+ const interactive = $derived(
+ $gameState !== null &&
+ ($status === 'open' || $status === 'reconnecting') &&
+ $player
+ );
+
+ function onPressDown() {
+ if (!interactive) return;
+ longPressed = false;
+ pressTimer = setTimeout(() => {
+ longPressed = true;
+ session.command('imbueElement', { element: name, half: true });
+ }, 500);
+ }
+
+ function onPressUp() {
+ if (pressTimer) {
+ clearTimeout(pressTimer);
+ pressTimer = null;
+ }
+ if (interactive && !longPressed) {
+ // Tap: use when active, imbue when inert.
+ if (elState === 0 || elState === 1) {
+ session.command('useElement', { element: name });
+ } else {
+ session.command('imbueElement', { element: name, half: false });
+ }
+ }
+ }
+
+ function onCancel() {
+ if (pressTimer) {
+ clearTimeout(pressTimer);
+ pressTimer = null;
+ }
+ }
+</script>
+
+<button
+ class="elbtn"
+ aria-label={label}
+ style="--el-color: {color}"
+ disabled={!interactive}
+ onpointerdown={onPressDown}
+ onpointerup={onPressUp}
+ onpointerleave={onCancel}
+ oncontextmenu={(e) => e.preventDefault()}
+>
+ <span class="elbtn__fill {elState === 0 ? 'full' : elState === 1 ? 'half' : ''}"></span>
+ <img class="elbtn__icon" src={icon} alt="" loading="lazy" />
+</button>
diff --git a/web/src/lib/ui/LevelWidget.svelte b/web/src/lib/ui/LevelWidget.svelte
new file mode 100644
index 0000000..4430de5
--- /dev/null
+++ b/web/src/lib/ui/LevelWidget.svelte
@@ -0,0 +1,52 @@
+<!--
+ The bottom-bar level widget (the reference `BottomBarLevelWidget`): the
+ scenario name, the scenario level, and the derived trap / hazard / XP /
+ coin values (GameMethods port). Tapping it opens the Set Level menu.
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import { coinValue, hazardValue, trapValue, xpValue } from '$lib/game/levelValues';
+ import { t } from '$lib/i18n';
+
+ let {
+ session,
+ onOpenMenu
+ }: {
+ session: GameSession;
+ onOpenMenu: () => void;
+ } = $props();
+
+ const gameState = session.state;
+ const player = session.player;
+
+ const scenario = $derived($gameState?.scenario ?? '');
+ const level = $derived($gameState?.level ?? 1);
+ const campaign = $derived($gameState?.currentCampaign ?? '');
+
+ const isOgGloom = $derived(campaign === 'Gloomhaven');
+
+ function onTap() {
+ // Spectators can view but not change the level.
+ if (!$player) return;
+ onOpenMenu();
+ }
+</script>
+
+<div class="levelwidget" onclick={onTap} role="button" tabindex="0"
+ onkeydown={(e) => {
+ if (e.key === 'Enter') onTap();
+ }}>
+ {#if scenario}
+ <div class="levelwidget__scenario">{scenario}</div>
+ {/if}
+ {#if $gameState}
+ <div class="levelwidget__stats">
+ {t('web:level')} {level} ·
+ {trapValue(level)} {t('levelLegendLabel')}
+ </div>
+ <div class="levelwidget__stats">
+ T {trapValue(level)} / H {hazardValue(level, isOgGloom, false)} /
+ X {xpValue(level)} / C {coinValue(level)}
+ </div>
+ {/if}
+</div>
diff --git a/web/src/lib/ui/MainList.svelte b/web/src/lib/ui/MainList.svelte
new file mode 100644
index 0000000..cb5ad49
--- /dev/null
+++ b/web/src/lib/ui/MainList.svelte
@@ -0,0 +1,44 @@
+<!--
+ The main list (the reference `MainList`/`GameList`): one row per entry of
+ the server's `currentList`. The reference lays wide screens out as two
+ reorderable columns; the web Phase 3 uses a single centred, scrollable
+ column (reordering arrives later, if at all).
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import { isCharacter, isMonster, isNoteRow } from '$lib/protocol/types';
+ import type { FigureRef } from './StatusMenu.svelte';
+ import CharacterRow from './CharacterRow.svelte';
+ import MonsterRow from './MonsterRow.svelte';
+ import NoteRow from './NoteRow.svelte';
+
+ let {
+ session,
+ onOpenMenu
+ }: {
+ session: GameSession;
+ onOpenMenu: (figure: FigureRef) => void;
+ } = $props();
+
+ const gameState = session.state;
+</script>
+
+<div class="list">
+ {#if $gameState}
+ {#each $gameState.currentList as item (item.id)}
+ {#if isCharacter(item)}
+ <CharacterRow {session} {item} {onOpenMenu} />
+ {:else if isMonster(item)}
+ <MonsterRow {session} {item} {onOpenMenu} />
+ {:else if isNoteRow(item)}
+ <NoteRow {session} {item} />
+ {/if}
+ {/each}
+ {#if $gameState.currentList.length === 0}
+ <p style="padding: 40px 12px; text-align: center; opacity: 0.7">
+ No characters or monsters yet — use the menu to set a scenario
+ and add characters.
+ </p>
+ {/if}
+ {/if}
+</div>
diff --git a/web/src/lib/ui/MainMenu.svelte b/web/src/lib/ui/MainMenu.svelte
new file mode 100644
index 0000000..f0aca7a
--- /dev/null
+++ b/web/src/lib/ui/MainMenu.svelte
@@ -0,0 +1,89 @@
+<!--
+ The slide-out main menu (the reference app's menu drawer): undo/redo,
+ action log, scenario setup, character/monster management, and settings.
+ Every entry either acts directly (undo/redo) or opens one of the menu
+ dialogs owned by the App.
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import { t } from '$lib/i18n';
+
+ export type MenuName =
+ | 'scenario'
+ | 'section'
+ | 'addChar'
+ | 'removeChar'
+ | 'setLevel'
+ | 'addMon'
+ | 'removeMon'
+ | 'noteRow'
+ | 'actionLog'
+ | 'settings';
+
+ let {
+ session,
+ open = $bindable(false),
+ onOpenMenu
+ }: {
+ session: GameSession;
+ open?: boolean;
+ onOpenMenu: (menu: MenuName) => void;
+ } = $props();
+
+ const gameState = session.state;
+ const index = session.index;
+
+ function pick(menu: MenuName) {
+ open = false;
+ onOpenMenu(menu);
+ }
+</script>
+
+{#if open}
+ <!-- Click-to-close scrim (Escape also closes; not a real control). -->
+ <div
+ class="scrim"
+ aria-hidden="true"
+ style="position: fixed; inset: 0; z-index: 39; background: #00000066"
+ onclick={() => (open = false)}
+ ></div>
+ <nav class="drawer drawer--open" aria-label="Main menu">
+ <div class="drawer__header"></div>
+ <div style="padding: 8px 0">
+ <div class="statrow" style="padding: 4px 16px">
+ <span class="statrow__label" style="opacity: 0.8; font-size: 13px">
+ {t('currentCampaign', { campaign: $gameState?.currentCampaign ?? '—' })}
+ </span>
+ </div>
+ </div>
+
+ <button class="drawer__item" disabled={$index <= 0} onclick={() => { open = false; session.undo(); }}>
+ {t('undo')}
+ </button>
+ <button class="drawer__item" onclick={() => { open = false; session.redo(); }}>
+ {t('redo')}
+ </button>
+ <button class="drawer__item" onclick={() => pick('actionLog')}>{t('menuActionLog')}</button>
+
+ <hr class="drawer__divider" />
+
+ <button class="drawer__item" onclick={() => pick('scenario')}>{t('menuSetScenario')}</button>
+ <button class="drawer__item" onclick={() => pick('section')}>{t('menuAddSection')}</button>
+
+ <hr class="drawer__divider" />
+
+ <button class="drawer__item" onclick={() => pick('addChar')}>{t('menuAddCharacter')}</button>
+ <button class="drawer__item" onclick={() => pick('removeChar')}>{t('menuRemoveCharacters')}</button>
+ <button class="drawer__item" onclick={() => pick('setLevel')}>{t('menuSetLevel')}</button>
+
+ <hr class="drawer__divider" />
+
+ <button class="drawer__item" onclick={() => pick('addMon')}>{t('menuAddMonsters')}</button>
+ <button class="drawer__item" onclick={() => pick('removeMon')}>{t('menuRemoveMonsters')}</button>
+ <button class="drawer__item" onclick={() => pick('noteRow')}>{t('menuAddNoteRow')}</button>
+
+ <hr class="drawer__divider" />
+
+ <button class="drawer__item" onclick={() => pick('settings')}>{t('menuSettings')}</button>
+ </nav>
+{/if}
diff --git a/web/src/lib/ui/Menu.svelte b/web/src/lib/ui/Menu.svelte
new file mode 100644
index 0000000..2ca117a
--- /dev/null
+++ b/web/src/lib/ui/Menu.svelte
@@ -0,0 +1,39 @@
+<!--
+ A dialog (the reference app's MenuCard): a centered card over a dimmed
+ backdrop with a Close button. The parent renders its content via the
+ `children` slot (Svelte 5 render-prop form).
+-->
+<script lang="ts">
+ import type { Snippet } from 'svelte';
+ import { t } from '$lib/i18n';
+
+ let {
+ open = $bindable(true),
+ title = '',
+ children
+ }: {
+ open?: boolean;
+ title?: string;
+ children?: Snippet;
+ } = $props();
+
+ function close() {
+ open = false;
+ }
+</script>
+
+{#if open}
+ <div class="dialog__overlay" role="dialog" aria-modal="true">
+ <div class="dialog__card">
+ {#if title}
+ <div class="dialog__title">{title}</div>
+ {/if}
+ <div class="dialog__body">
+ {@render children?.()}
+ </div>
+ <div class="dialog__footer">
+ <button class="dialog__close" onclick={close}>{t('close')}</button>
+ </div>
+ </div>
+ </div>
+{/if}
diff --git a/web/src/lib/ui/MonsterRow.svelte b/web/src/lib/ui/MonsterRow.svelte
new file mode 100644
index 0000000..3f3442b
--- /dev/null
+++ b/web/src/lib/ui/MonsterRow.svelte
@@ -0,0 +1,109 @@
+<!--
+ A monster row (the reference `MonsterWidget`): the monster art with its
+ name, the standee boxes (one per surviving instance, with health), the
+ level, and the turn-state styling. Tapping the art ends its turn
+ (playTurns); tapping the row or a standee box opens the stat menu.
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import type { MonsterItem } from '$lib/protocol/types';
+ import { monsterImage } from '$lib/game/art';
+ import { standeeFigureId } from '$lib/game/stats';
+ import type { FigureRef } from './StatusMenu.svelte';
+
+ let {
+ session,
+ item,
+ onOpenMenu
+ }: {
+ session: GameSession;
+ item: MonsterItem;
+ onOpenMenu: (figure: FigureRef) => void;
+ } = $props();
+
+ const player = session.player;
+ const gameState = session.state;
+
+ const roundState = $derived($gameState?.roundState ?? 0);
+ const turnState = $derived(item.turnState);
+ const currentTurn = $derived(roundState === 1 && turnState === 1);
+ const done = $derived(roundState === 1 && turnState === 2);
+ const gray = $derived(!item.isActive || done);
+
+ const instances = $derived(item.monsterInstances);
+ const aliveInstances = $derived(instances.filter((s) => s.health > 0));
+ const main = $derived(aliveInstances[0] ?? instances[0] ?? null);
+
+ function figureFor(standeeIndex = 0): FigureRef {
+ const s = instances[standeeIndex] ?? instances[0];
+ return {
+ title: item.id,
+ figureId: s ? standeeFigureId(s) : item.id,
+ ownerId: item.id,
+ kind: 'monster',
+ rowId: item.id,
+ isObjective: false
+ };
+ }
+
+ function onArtTap() {
+ if (roundState !== 1 || !item.isActive || !$player) return;
+ session.command('turnDone', { id: item.id });
+ }
+</script>
+
+<div class="row row--monster" class:row--current={currentTurn} class:row--done={gray}>
+ <div class="row__bg"></div>
+
+ <div class="row__inner" style="align-items: flex-start">
+ <div
+ class="row__art"
+ style="width: 96px; height: 96px"
+ role="button"
+ tabindex="0"
+ onclick={() => onOpenMenu(figureFor(0))}
+ onkeydown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') onOpenMenu(figureFor(0));
+ }}
+ >
+ <img
+ src={main ? monsterImage(main.gfx) : ''}
+ alt={item.id}
+ style="width: 88px; height: 88px"
+ loading="lazy"
+ />
+ </div>
+
+ <div
+ style="flex: 1; min-width: 0; padding: 4px 0"
+ role="button"
+ tabindex="0"
+ onclick={() => onArtTap()}
+ onkeydown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') onArtTap();
+ }}
+ >
+ <div class="row__name" style="font-size: 15px">
+ {item.id}
+ {#if item.isAlly}<span class="chip" style="position: static; margin-left: 6px">ally</span>{/if}
+ </div>
+ <div class="row__hp">Level {item.level}</div>
+ </div>
+ </div>
+
+ {#if instances.length > 0}
+ <div class="monster__boxes">
+ {#each instances as standee, i}
+ <button
+ class="monster__box"
+ class:monster__box--dead={standee.health <= 0}
+ onclick={() => onOpenMenu(figureFor(i))}
+ aria-label={item.id}
+ >
+ <img src={monsterImage(standee.gfx)} alt="" loading="lazy" />
+ <span class="monster__box-hp">{standee.health}</span>
+ </button>
+ {/each}
+ </div>
+ {/if}
+</div>
diff --git a/web/src/lib/ui/NoteRow.svelte b/web/src/lib/ui/NoteRow.svelte
new file mode 100644
index 0000000..34af63e
--- /dev/null
+++ b/web/src/lib/ui/NoteRow.svelte
@@ -0,0 +1,57 @@
+<!--
+ A note row (the reference `NoteRowWidget`, Phase 3 placeholder): a
+ free-form coloured row. Tapping it edits the text inline and commits
+ through `setNoteRowText`.
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import type { NoteRowItem } from '$lib/protocol/types';
+
+ let {
+ session,
+ item
+ }: {
+ session: GameSession;
+ item: NoteRowItem;
+ } = $props();
+
+ const player = session.player;
+
+ let editing = $state(false);
+ let draft = $state(item.text);
+
+ function colorCss(color: number): string {
+ return `#${color.toString(16).padStart(8, '0').slice(2)}`;
+ }
+
+ function startEdit() {
+ if (!$player) return;
+ draft = item.text;
+ editing = true;
+ }
+
+ function commit() {
+ editing = false;
+ if (draft !== item.text) {
+ session.command('setNoteRowText', { text: draft, noteId: item.id });
+ }
+ }
+</script>
+
+<div class="row row--note" style:background-color={colorCss(item.color)}>
+ <div class="note__text">
+ {#if editing}
+ <input
+ class="search"
+ style="margin: 0; width: 100%"
+ bind:value={draft}
+ onblur={commit}
+ onkeydown={(e) => {
+ if (e.key === 'Enter') commit();
+ }}
+ />
+ {:else}
+ <button class="note__edit" onclick={startEdit}>{item.text || '…'}</button>
+ {/if}
+ </div>
+</div>
diff --git a/web/src/lib/ui/StatusMenu.svelte b/web/src/lib/ui/StatusMenu.svelte
new file mode 100644
index 0000000..4563c07
--- /dev/null
+++ b/web/src/lib/ui/StatusMenu.svelte
@@ -0,0 +1,211 @@
+<!--
+ The per-figure stat menu (the reference `StatusMenu`): ± steppers for
+ health, max health, xp and the bless/curse/empower/enfeeble counters,
+ condition toggles, and turn-done. Values are read live from the state so
+ the dialog stays in sync while open. All actions are commands to the
+ server (players only — the server rejects spectators).
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import type { CharacterItem, MonsterInstance, MonsterItem } from '$lib/protocol/types';
+ import {
+ characterStatCounters,
+ standeeFigureId,
+ standeeStatCounters,
+ type ModifierDeckJson
+ } from '$lib/game/stats';
+ import { isObjectiveOrEscort } from '$lib/data/classInfo';
+ import { CONDITIONS } from '$lib/game/conditions';
+ import { t } from '$lib/i18n';
+ import Menu from './Menu.svelte';
+
+ export interface FigureRef {
+ title: string;
+ /** Wire `figureId`: the character id, or `name+gfx+standeeNr`. */
+ figureId: string;
+ ownerId: string | null;
+ kind: 'character' | 'monster' | 'summon';
+ /** The row's id (for turn-done / activate). */
+ rowId: string;
+ /** True for Escort / Objective characters (no xp, no initiative). */
+ isObjective: boolean;
+ }
+
+ let {
+ session,
+ figure,
+ open = $bindable(true)
+ }: {
+ session: GameSession;
+ figure: FigureRef;
+ open?: boolean;
+ } = $props();
+
+ const gameState = session.state;
+ const player = session.player;
+
+ function character(): CharacterItem | null {
+ if (figure.kind !== 'character' || !$gameState) return null;
+ return $gameState.currentList.find(
+ (item) => item.id === figure.figureId && 'characterState' in item
+ ) as CharacterItem | null;
+ }
+
+ function ownerItem(): MonsterItem | CharacterItem | null {
+ if (!figure.ownerId || !$gameState) return null;
+ return $gameState.currentList.find((item) => item.id === figure.ownerId) as
+ | MonsterItem
+ | CharacterItem
+ | null;
+ }
+
+ function standee() {
+ const owner = ownerItem();
+ if (!owner) return null;
+ if ('monsterInstances' in owner) {
+ return owner.monsterInstances.find(
+ (s: MonsterInstance) => standeeFigureId(s) === figure.figureId
+ );
+ }
+ if ('characterState' in owner) {
+ return owner.characterState.summonList.find(
+ (s: MonsterInstance) => standeeFigureId(s) === figure.figureId
+ );
+ }
+ return null;
+ }
+
+ const liveCharacter = $derived(figure.kind === 'character' ? character() : null);
+ const liveStandee = $derived(figure.kind !== 'character' ? standee() : null);
+ const liveOwner = $derived(figure.kind !== 'character' ? ownerItem() : null);
+
+ const health = $derived(
+ liveCharacter?.characterState.health ?? liveStandee?.health ?? null
+ );
+ const maxHealth = $derived(
+ liveCharacter?.characterState.maxHealth ?? liveStandee?.maxHealth ?? null
+ );
+ const xp = $derived(
+ figure.kind === 'character' && !figure.isObjective
+ ? liveCharacter?.characterState.xp ?? 0
+ : null
+ );
+
+ // Summons use the owning character's modifier deck; monsters use the
+ // scenario (global) deck — mirroring the reference's `deck` getter.
+ const counters = $derived.by(() => {
+ if (figure.kind === 'character') {
+ const c = liveCharacter;
+ return c ? characterStatCounters(c) : null;
+ }
+ const owner = liveOwner;
+ if (!owner) return null;
+ const deck = 'characterState' in owner
+ ? (owner.characterState.modifierDeck as ModifierDeckJson | undefined)
+ : ($gameState?.modifierDeck as ModifierDeckJson | undefined);
+ return deck ? standeeStatCounters(deck) : null;
+ });
+
+ const conditions = $derived(
+ liveCharacter?.characterState.conditions ?? liveStandee?.conditions ?? []
+ );
+
+ const roundState = $derived($gameState?.roundState ?? 0);
+ const canAct = $derived(!!$player && ($gameState != null));
+
+ function cmd(name: string, args: Record<string, unknown>) {
+ session.command(name, args);
+ }
+
+ function change(name: string, delta: number, extra: Record<string, unknown> = {}) {
+ cmd(name, { change: delta, figureId: figure.figureId, ...extra });
+ }
+
+ function toggleCondition(index: number, name: string) {
+ const args: Record<string, unknown> = { condition: name, figureId: figure.figureId };
+ if (figure.ownerId) args.ownerId = figure.ownerId;
+ if (conditions.includes(index)) cmd('removeCondition', args);
+ else cmd('addCondition', args);
+ }
+</script>
+
+<Menu open={open} title={figure.title}>
+ {#if health != null && maxHealth != null}
+ <div class="statrow">
+ <span class="statrow__label">Health</span>
+ <span class="statrow__value">{health} / {maxHealth}</span>
+ <button class="stepbtn" disabled={!canAct} onclick={() => change('changeHealth', 1)}>+</button>
+ <button class="stepbtn" disabled={!canAct || health <= 0} onclick={() => change('changeHealth', -1)}>−</button>
+ </div>
+ <div class="statrow">
+ <span class="statrow__label">Max Health</span>
+ <span class="statrow__value">{maxHealth}</span>
+ <button class="stepbtn" disabled={!canAct} onclick={() => change('changeMaxHealth', 1)}>+</button>
+ <button class="stepbtn" disabled={!canAct || health >= maxHealth} onclick={() => change('changeMaxHealth', -1)}>−</button>
+ </div>
+ {/if}
+
+ {#if xp != null}
+ <div class="statrow">
+ <span class="statrow__label">XP</span>
+ <span class="statrow__value">{xp}</span>
+ <button class="stepbtn" disabled={!canAct} onclick={() => change('changeXP', 10)}>+</button>
+ <button class="stepbtn" disabled={!canAct || xp <= 0} onclick={() => change('changeXP', -10)}>−</button>
+ </div>
+ {/if}
+
+ {#if counters}
+ <div class="statrow">
+ <span class="statrow__label">{t('cmdAddBless')}</span>
+ <span class="statrow__value">{counters.bless}</span>
+ <button class="stepbtn" disabled={!canAct} onclick={() => change('changeBless', 1)}>+</button>
+ <button class="stepbtn" disabled={!canAct || counters.bless <= 0} onclick={() => change('changeBless', -1)}>−</button>
+ </div>
+ <div class="statrow">
+ <span class="statrow__label">{t('cmdAddCurse')}</span>
+ <span class="statrow__value">{counters.curse}</span>
+ <button class="stepbtn" disabled={!canAct} onclick={() => change('changeCurse', 1)}>+</button>
+ <button class="stepbtn" disabled={!canAct || counters.curse <= 0} onclick={() => change('changeCurse', -1)}>−</button>
+ </div>
+ <div class="statrow">
+ <span class="statrow__label">{t('cmdAddEmpower')}</span>
+ <span class="statrow__value">{counters.empower}</span>
+ <button class="stepbtn" disabled={!canAct} onclick={() => change('changeEmpower', 1, { gfx: 'in-empower' })}>+</button>
+ <button class="stepbtn" disabled={!canAct || counters.empower <= 0} onclick={() => change('changeEmpower', -1, { gfx: 'in-empower' })}>−</button>
+ </div>
+ <div class="statrow">
+ <span class="statrow__label">{t('cmdAddEnfeeble')}</span>
+ <span class="statrow__value">{counters.enfeeble}</span>
+ <button class="stepbtn" disabled={!canAct} onclick={() => change('changeEnfeeble', 1, { gfx: 'in-enfeeble' })}>+</button>
+ <button class="stepbtn" disabled={!canAct || counters.enfeeble <= 0} onclick={() => change('changeEnfeeble', -1, { gfx: 'in-enfeeble' })}>−</button>
+ </div>
+ {/if}
+
+ <div class="condgrid">
+ {#each CONDITIONS as c, i}
+ <button
+ class:condgrid--on={conditions.includes(i)}
+ disabled={!canAct}
+ onclick={() => toggleCondition(i, c.name)}
+ >
+ {c.label}
+ </button>
+ {/each}
+ </div>
+
+ {#if roundState === 1}
+ <div class="dialog__body" style="padding-top: 8px">
+ <button
+ class="stepbtn"
+ style="width: 100%; height: 40px"
+ disabled={!canAct}
+ onclick={() => {
+ cmd('turnDone', { id: figure.rowId });
+ open = false;
+ }}
+ >
+ {t('cmdTurnDone', { id: figure.title })}
+ </button>
+ </div>
+ {/if}
+</Menu>
diff --git a/web/src/lib/ui/Toast.svelte b/web/src/lib/ui/Toast.svelte
new file mode 100644
index 0000000..8050e29
--- /dev/null
+++ b/web/src/lib/ui/Toast.svelte
@@ -0,0 +1,12 @@
+<!--
+ Transient toast (the reference app's snackbars): surfaces the server's
+ `toastMessage` (scenario events) and protocol errors. The parent decides
+ when to show and clear it.
+-->
+<script lang="ts">
+ let { message }: { message: string | null } = $props();
+</script>
+
+{#if message}
+ <div class="toast" role="status">{message}</div>
+{/if}
diff --git a/web/src/lib/ui/TopBar.svelte b/web/src/lib/ui/TopBar.svelte
new file mode 100644
index 0000000..ec09896
--- /dev/null
+++ b/web/src/lib/ui/TopBar.svelte
@@ -0,0 +1,34 @@
+<!--
+ The top bar: the menu button (opens the drawer), the app title, and the
+ six elemental ability buttons — the reference `TopBar` layout.
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import { ELEMENTS } from '$lib/game/elements';
+ import ElementButton from './ElementButton.svelte';
+
+ let {
+ session,
+ onMenu
+ }: {
+ session: GameSession;
+ onMenu: () => void;
+ } = $props();
+</script>
+
+<header class="topbar">
+ <button class="topbar__menu" onclick={onMenu} aria-label="Menu">☰</button>
+ <div class="topbar__title">X-haven<br />Assistant</div>
+ <div class="topbar__elements">
+ {#each ELEMENTS as el, i}
+ <ElementButton
+ {session}
+ index={i}
+ name={el.name}
+ color={el.color}
+ icon={el.icon}
+ label={el.label}
+ />
+ {/each}
+ </div>
+</header>
diff --git a/web/src/lib/ui/menus/ActionLogMenu.svelte b/web/src/lib/ui/menus/ActionLogMenu.svelte
new file mode 100644
index 0000000..61921dc
--- /dev/null
+++ b/web/src/lib/ui/menus/ActionLogMenu.svelte
@@ -0,0 +1,83 @@
+<!--
+ The action log (the reference `ActionLogMenu`): the last 20 command
+ descriptions, newest first. Tapping an entry rolls the game back to that
+ action by sending that many `undo` messages (each confirmed by the
+ server with its own update).
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import { t } from '$lib/i18n';
+ import Menu from '../Menu.svelte';
+
+ let {
+ session,
+ /** Newest last. */
+ log,
+ open = $bindable(true)
+ }: {
+ session: GameSession;
+ log: string[];
+ open?: boolean;
+ } = $props();
+
+ let confirming = $state<number | null>(null);
+
+ // The number of undos back to the entry being confirmed (newest entry
+ // is 0 away). Null when nothing is confirmed.
+ const undosPending = $derived(
+ confirming == null ? null : log.length - 1 - confirming
+ );
+ const confirmDesc = $derived(
+ confirming == null ? '' : log[log.length - 1 - confirming]
+ );
+
+ function rollBack() {
+ if (undosPending == null) return;
+ confirming = null;
+ open = false;
+ for (let i = 0; i < undosPending; i++) session.undo();
+ }
+</script>
+
+<Menu open={open} title={t('actionLogTitle')}>
+ {#if log.length === 0}
+ <p style="padding: 12px; text-align: center; opacity: 0.7">{t('actionLogEmpty')}</p>
+ {:else}
+ <p style="padding: 8px 4px 0; opacity: 0.7; font-size: 13px">{t('actionLogRollbackHint')}</p>
+ <ul class="menulist">
+ {#each log.slice().reverse() as desc, i (i + '::' + desc)}
+ <li>
+ <button
+ class="menulist__item"
+ disabled={i === 0}
+ onclick={() => (confirming = i)}
+ >
+ {desc}
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+
+ {#if confirming != null}
+ <div style="padding: 12px 4px">
+ <div style="font-size: 15px; margin-bottom: 8px">
+ {t('actionLogRollbackTitle')}
+ </div>
+ <div style="font-size: 13px; opacity: 0.85; margin-bottom: 12px">
+ {t('actionLogRollbackBody', {
+ action: confirmDesc,
+ count: undosPending ?? 0
+ })}
+ </div>
+ <div style="display: flex; gap: 8px; justify-content: flex-end">
+ <button class="stepbtn" style="border-radius: 6px" onclick={() => (confirming = null)}>
+ {t('close')}
+ </button>
+ <button class="stepbtn" style="border-radius: 6px; background: #7a1f1f" onclick={rollBack}>
+ {t('actionLogRollbackConfirm')}
+ </button>
+ </div>
+ </div>
+ {/if}
+</Menu>
diff --git a/web/src/lib/ui/menus/AddCharacterMenu.svelte b/web/src/lib/ui/menus/AddCharacterMenu.svelte
new file mode 100644
index 0000000..20a5ca7
--- /dev/null
+++ b/web/src/lib/ui/menus/AddCharacterMenu.svelte
@@ -0,0 +1,96 @@
+<!--
+ Add Character (the reference `AddCharacterMenu`): the current campaign's
+ class list (hidden classes surface when the search matches their name),
+ a level selector, and the class icon. Selecting sends `addCharacter` —
+ the server assigns the new character to the session that sent it.
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import { gameData, type ClassData } from '$lib/data/gameData';
+ import { classColor, classIcon } from '$lib/game/art';
+ import { t } from '$lib/i18n';
+ import Menu from '../Menu.svelte';
+
+ let {
+ session,
+ open = $bindable(true)
+ }: {
+ session: GameSession;
+ open?: boolean;
+ } = $props();
+
+ const gameState = session.state;
+ const player = session.player;
+
+ let campaignData = $state<ClassData[] | null>(null);
+ let search = $state('');
+ let level = $state(1);
+ let error = $state<string | null>(null);
+
+ $effect(() => {
+ if (!open) return;
+ const c = $gameState?.currentCampaign;
+ if (!c) {
+ campaignData = [];
+ return;
+ }
+ let alive = true;
+ campaignData = null;
+ error = null;
+ gameData
+ .loadCampaign(c)
+ .then((d) => {
+ if (alive) campaignData = d.classes;
+ })
+ .catch(() => {
+ if (alive) error = 'failed to load campaign';
+ });
+ return () => {
+ alive = false;
+ };
+ });
+
+ const q = $derived(search.trim().toLowerCase());
+ /** Hidden classes are listed only when the search matches them. */
+ const classes = $derived(
+ (campaignData ?? []).filter((c) => !c.hidden || q.includes(c.name.toLowerCase()))
+ );
+
+ function pick(cls: ClassData) {
+ if (!$player) return;
+ session.command('addCharacter', { id: cls.id, edition: cls.edition, level });
+ open = false;
+ }
+</script>
+
+<Menu open={open} title={t('menuAddCharacter')}>
+ {#if error}
+ <p style="padding: 12px; opacity: 0.8">{error}</p>
+ {:else}
+ <input class="search" placeholder={t('addCharacterHint')} bind:value={search} />
+
+ <div class="statrow">
+ <span class="statrow__label">{t('web:level')}</span>
+ <button class="stepbtn" disabled={!$player || level <= 1} onclick={() => (level -= 1)}>−</button>
+ <span class="statrow__value">{level}</span>
+ <button class="stepbtn" disabled={!$player || level >= 10} onclick={() => (level += 1)}>+</button>
+ </div>
+
+ {#if campaignData === null}
+ <p style="padding: 12px; opacity: 0.7">{t('connecting')}</p>
+ {:else if classes.length === 0}
+ <p style="padding: 12px; opacity: 0.7">{t('noResultsFound')}</p>
+ {:else}
+ <ul class="menulist">
+ {#each classes as cls (cls.id)}
+ <li>
+ <button class="menulist__item" disabled={!$player} onclick={() => pick(cls)}>
+ <img src={classIcon(cls.name)} alt="" loading="lazy" style="background: {classColor(cls.color)}" />
+ {cls.name}
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ {/if}
+</Menu>
diff --git a/web/src/lib/ui/menus/AddMonsterMenu.svelte b/web/src/lib/ui/menus/AddMonsterMenu.svelte
new file mode 100644
index 0000000..23de120
--- /dev/null
+++ b/web/src/lib/ui/menus/AddMonsterMenu.svelte
@@ -0,0 +1,125 @@
+<!--
+ Add Monster (the reference `AddMonsterMenu`): search, the monster list
+ (from a selectable campaign), a level stepper, and the monster portrait.
+ Selecting sends `addMonster`.
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import { gameData, type MonsterData } from '$lib/data/gameData';
+ import { monsterImage } from '$lib/game/art';
+ import { t } from '$lib/i18n';
+ import Menu from '../Menu.svelte';
+
+ let {
+ session,
+ open = $bindable(true)
+ }: {
+ session: GameSession;
+ open?: boolean;
+ } = $props();
+
+ const gameState = session.state;
+ const player = session.player;
+
+ let campaigns = $state<string[] | null>(null);
+ let campaign = $state('');
+ let monsters = $state<MonsterData[] | null>(null);
+ let search = $state('');
+ let level = $state(1);
+ let error = $state<string | null>(null);
+
+ $effect(() => {
+ if (!open) return;
+ let alive = true;
+ campaigns = null;
+ error = null;
+ gameData
+ .campaigns()
+ .then((list) => {
+ if (!alive) return;
+ campaigns = list;
+ campaign = $gameState?.currentCampaign && list.includes($gameState.currentCampaign)
+ ? $gameState.currentCampaign
+ : list[0] ?? '';
+ })
+ .catch(() => {
+ if (alive) error = 'failed to load campaigns';
+ });
+ return () => {
+ alive = false;
+ };
+ });
+
+ $effect(() => {
+ const c = campaign;
+ if (!open || !c) return;
+ let alive = true;
+ monsters = null;
+ gameData
+ .loadCampaign(c)
+ .then((d) => {
+ if (alive) monsters = d.monsters;
+ })
+ .catch(() => {
+ if (alive) error = 'failed to load campaign';
+ });
+ return () => {
+ alive = false;
+ };
+ });
+
+ const q = $derived(search.trim().toLowerCase());
+ const list = $derived(
+ (monsters ?? []).filter((m) => q === '' || m.display.toLowerCase().includes(q))
+ );
+
+ function pick(m: MonsterData) {
+ if (!$player) return;
+ const lvl = Math.min(level, Math.max(1, m.maxLevel));
+ session.command('addMonster', { name: m.name, level: lvl, isAlly: false });
+ open = false;
+ }
+</script>
+
+<Menu open={open} title={t('addMonsterLabel')}>
+ {#if error}
+ <p style="padding: 12px; opacity: 0.8">{error}</p>
+ {:else}
+ <input class="search" placeholder={t('addMonsterLabel')} bind:value={search} />
+
+ {#if campaigns}
+ <div class="statrow" style="align-items: center">
+ <span class="statrow__label" style="font-size: 13px">{t('showMonstersFrom')}</span>
+ <select class="search" style="margin: 0; width: auto" value={campaign} onchange={(e) => (campaign = e.currentTarget.value)}>
+ {#each campaigns as c (c)}
+ <option value={c}>{c}</option>
+ {/each}
+ </select>
+ </div>
+ {/if}
+
+ <div class="statrow">
+ <span class="statrow__label">{t('web:level')}</span>
+ <button class="stepbtn" disabled={!$player || level <= 1} onclick={() => (level -= 1)}>−</button>
+ <span class="statrow__value">{level}</span>
+ <button class="stepbtn" disabled={!$player || level >= 10} onclick={() => (level += 1)}>+</button>
+ </div>
+
+ {#if monsters === null}
+ <p style="padding: 12px; opacity: 0.7">{t('connecting')}</p>
+ {:else if list.length === 0}
+ <p style="padding: 12px; opacity: 0.7">{t('noResultsFound')}</p>
+ {:else}
+ <ul class="menulist">
+ {#each list as m (m.name)}
+ <li>
+ <button class="menulist__item" disabled={!$player} onclick={() => pick(m)}>
+ <img src={monsterImage(m.gfx)} alt="" loading="lazy" />
+ {m.display}
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ {/if}
+</Menu>
diff --git a/web/src/lib/ui/menus/AddNoteRowMenu.svelte b/web/src/lib/ui/menus/AddNoteRowMenu.svelte
new file mode 100644
index 0000000..5bb14a0
--- /dev/null
+++ b/web/src/lib/ui/menus/AddNoteRowMenu.svelte
@@ -0,0 +1,113 @@
+<!--
+ Add Note Row (the reference `NoteRowAddMenu`, Phase 3 form): a colour
+ picker, free text, and an optional link to a figure. Sending
+ `addNoteRow` appends the row (beneath its linked figure, if any).
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import { isCharacter, isMonster } from '$lib/protocol/types';
+ import { t } from '$lib/i18n';
+ import Menu from '../Menu.svelte';
+
+ let {
+ session,
+ open = $bindable(true)
+ }: {
+ session: GameSession;
+ open?: boolean;
+ } = $props();
+
+ const gameState = session.state;
+ const player = session.player;
+
+ const COLORS = [
+ 0xffb58900,
+ 0xff1565c0,
+ 0xff2e7d32,
+ 0xffc2185b,
+ 0xffffb300,
+ 0xff5e35b1
+ ];
+
+ let color = $state(COLORS[0]);
+ let text = $state('');
+ let linkedId = $state('');
+
+ $effect(() => {
+ if (!open) return;
+ color = COLORS[0];
+ text = '';
+ linkedId = '';
+ });
+
+ const figures = $derived.by(() =>
+ ($gameState?.currentList ?? [])
+ .filter((i) => isCharacter(i) || isMonster(i))
+ .map((i) => ({
+ id: i.id,
+ name: isCharacter(i) ? i.characterState.display : i.id
+ }))
+ );
+
+ function colorCss(c: number): string {
+ return `#${c.toString(16).padStart(8, '0').slice(2)}`;
+ }
+
+ function add() {
+ if (!$player) return;
+ const id =
+ typeof crypto !== 'undefined' && 'randomUUID' in crypto
+ ? crypto.randomUUID()
+ : `note-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
+ session.command('addNoteRow', {
+ noteRow: {
+ id,
+ text: text.trim(),
+ color,
+ linkedId,
+ standeeNr: 0
+ }
+ });
+ open = false;
+ }
+</script>
+
+<Menu open={open} title={t('menuAddNoteRow')}>
+ <div style="display: flex; gap: 6px; padding: 8px 4px">
+ {#each COLORS as c (c)}
+ <button
+ aria-label="note colour"
+ style="width: 32px; height: 32px; border-radius: 6px; background: {colorCss(c)}; outline: {c === color ? '3px solid #fff' : 'none'}"
+ onclick={() => (color = c)}
+ ></button>
+ {/each}
+ </div>
+
+ <input class="search" placeholder={t('noteRowHint')} bind:value={text} />
+
+ <div class="statrow" style="align-items: center">
+ <span class="statrow__label" style="font-size: 13px">{t('noteRowWholeGroup')}</span>
+ <select
+ class="search"
+ style="margin: 0; width: auto"
+ value={linkedId}
+ onchange={(e) => (linkedId = e.currentTarget.value)}
+ >
+ <option value="">{t('noteRowAll')}</option>
+ {#each figures as f (f.id)}
+ <option value={f.id}>{f.name}</option>
+ {/each}
+ </select>
+ </div>
+
+ <div style="display: flex; justify-content: flex-end; padding: 8px 4px">
+ <button
+ class="stepbtn"
+ style="border-radius: 6px"
+ disabled={!$player || text.trim() === ''}
+ onclick={add}
+ >
+ {t('noteRowAddFromMenu')}
+ </button>
+ </div>
+</Menu>
diff --git a/web/src/lib/ui/menus/AddSectionMenu.svelte b/web/src/lib/ui/menus/AddSectionMenu.svelte
new file mode 100644
index 0000000..991b6a5
--- /dev/null
+++ b/web/src/lib/ui/menus/AddSectionMenu.svelte
@@ -0,0 +1,79 @@
+<!--
+ Add Section (the reference `AddSectionMenu`): lists the addable sections
+ of the current scenario (its rooms after the start room, minus spawns)
+ and adds one via `setScenario { scenario, section: true }`.
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import { gameData } from '$lib/data/gameData';
+ import { t } from '$lib/i18n';
+ import Menu from '../Menu.svelte';
+
+ let {
+ session,
+ open = $bindable(true)
+ }: {
+ session: GameSession;
+ open?: boolean;
+ } = $props();
+
+ const gameState = session.state;
+ const player = session.player;
+
+ let sections = $state<string[] | null>(null);
+
+ $effect(() => {
+ if (!open) return;
+ const s = $gameState?.scenario ?? '';
+ const c = $gameState?.currentCampaign ?? '';
+ if (!s || !c) {
+ sections = [];
+ return;
+ }
+ let alive = true;
+ sections = null;
+ gameData
+ .sections(c, s)
+ .then((list) => {
+ if (alive) sections = list;
+ })
+ .catch(() => {
+ if (alive) sections = [];
+ });
+ return () => {
+ alive = false;
+ };
+ });
+
+ function pick(section: string) {
+ if (!$player) return;
+ // For sections the wire `scenario` field carries the *section name*;
+ // the server matches it against the current scenario's sections.
+ session.command('setScenario', { scenario: section, section: true });
+ open = false;
+ }
+</script>
+
+<Menu open={open} title={t('menuAddSection')}>
+ {#if !$gameState?.scenario}
+ <p style="padding: 12px; opacity: 0.7">{t('web:noScenario')}</p>
+ {:else if sections === null}
+ <p style="padding: 12px; opacity: 0.7">{t('connecting')}</p>
+ {:else if sections.length === 0}
+ <p style="padding: 12px; opacity: 0.7">{t('noResultsFound')}</p>
+ {:else}
+ <ul class="menulist">
+ {#each sections as section (section)}
+ <li>
+ <button
+ class="menulist__item"
+ disabled={!$player}
+ onclick={() => pick(section)}
+ >
+ {section}
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+</Menu>
diff --git a/web/src/lib/ui/menus/RemoveCharacterMenu.svelte b/web/src/lib/ui/menus/RemoveCharacterMenu.svelte
new file mode 100644
index 0000000..bb7e970
--- /dev/null
+++ b/web/src/lib/ui/menus/RemoveCharacterMenu.svelte
@@ -0,0 +1,86 @@
+<!--
+ Remove Characters (the reference `RemoveCharacterMenu`): checkbox list
+ of the current characters; "Remove All" clears everything.
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import { isCharacter } from '$lib/protocol/types';
+ import { t } from '$lib/i18n';
+ import Menu from '../Menu.svelte';
+
+ let {
+ session,
+ open = $bindable(true)
+ }: {
+ session: GameSession;
+ open?: boolean;
+ } = $props();
+
+ const gameState = session.state;
+ const player = session.player;
+
+ let selected = $state<Set<string>>(new Set());
+
+ // Default to selecting every current character.
+ $effect(() => {
+ if (!open) return;
+ const ids = ($gameState?.currentList ?? []).filter(isCharacter).map((c) => c.id);
+ selected = new Set(ids);
+ });
+
+ const characters = $derived(($gameState?.currentList ?? []).filter(isCharacter));
+
+ function toggle(id: string) {
+ const next = new Set(selected);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ selected = next;
+ }
+
+ function remove() {
+ if (!$player || selected.size === 0) return;
+ session.command('removeCharacter', { ids: [...selected] });
+ open = false;
+ }
+
+ function removeAll() {
+ if (!$player || characters.length === 0) return;
+ session.command('removeCharacter', { ids: characters.map((c) => c.id) });
+ open = false;
+ }
+</script>
+
+<Menu open={open} title={t('menuRemoveCharacters')}>
+ {#if characters.length === 0}
+ <p style="padding: 12px; opacity: 0.7">{t('noResultsFound')}</p>
+ {:else}
+ <ul class="menulist">
+ {#each characters as c (c.id)}
+ <li>
+ <label class="menulist__item" style="cursor: pointer">
+ <input
+ type="checkbox"
+ checked={selected.has(c.id)}
+ onchange={() => toggle(c.id)}
+ />
+ {c.characterState.display}
+ </label>
+ </li>
+ {/each}
+ </ul>
+
+ <div style="display: flex; gap: 8px; justify-content: flex-end; padding: 8px 4px">
+ <button class="stepbtn" style="border-radius: 6px" disabled={!$player} onclick={removeAll}>
+ {t('removeAll')}
+ </button>
+ <button
+ class="stepbtn"
+ style="border-radius: 6px; background: #7a1f1f"
+ disabled={!$player || selected.size === 0}
+ onclick={remove}
+ >
+ {t('menuRemoveCharacters')} ({selected.size})
+ </button>
+ </div>
+ {/if}
+</Menu>
diff --git a/web/src/lib/ui/menus/RemoveMonsterMenu.svelte b/web/src/lib/ui/menus/RemoveMonsterMenu.svelte
new file mode 100644
index 0000000..f995abd
--- /dev/null
+++ b/web/src/lib/ui/menus/RemoveMonsterMenu.svelte
@@ -0,0 +1,81 @@
+<!--
+ Remove Monsters (the reference `RemoveMonsterMenu`): checkbox list of the
+ current monsters; "Remove All" clears everything.
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import { isMonster } from '$lib/protocol/types';
+ import { t } from '$lib/i18n';
+ import Menu from '../Menu.svelte';
+
+ let {
+ session,
+ open = $bindable(true)
+ }: {
+ session: GameSession;
+ open?: boolean;
+ } = $props();
+
+ const gameState = session.state;
+ const player = session.player;
+
+ let selected = $state<Set<string>>(new Set());
+
+ $effect(() => {
+ if (!open) return;
+ const ids = ($gameState?.currentList ?? []).filter(isMonster).map((m) => m.id);
+ selected = new Set(ids);
+ });
+
+ const monsters = $derived(($gameState?.currentList ?? []).filter(isMonster));
+
+ function toggle(id: string) {
+ const next = new Set(selected);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ selected = next;
+ }
+
+ function remove() {
+ if (!$player || selected.size === 0) return;
+ session.command('removeMonster', { ids: [...selected] });
+ open = false;
+ }
+
+ function removeAll() {
+ if (!$player || monsters.length === 0) return;
+ session.command('removeMonster', { ids: monsters.map((m) => m.id) });
+ open = false;
+ }
+</script>
+
+<Menu open={open} title={t('menuRemoveMonsters')}>
+ {#if monsters.length === 0}
+ <p style="padding: 12px; opacity: 0.7">{t('noResultsFound')}</p>
+ {:else}
+ <ul class="menulist">
+ {#each monsters as m (m.id)}
+ <li>
+ <label class="menulist__item" style="cursor: pointer">
+ <input type="checkbox" checked={selected.has(m.id)} onchange={() => toggle(m.id)} />
+ {m.id} ({m.monsterInstances.length})
+ </label>
+ </li>
+ {/each}
+ </ul>
+
+ <div style="display: flex; gap: 8px; justify-content: flex-end; padding: 8px 4px">
+ <button class="stepbtn" style="border-radius: 6px" disabled={!$player} onclick={removeAll}>
+ {t('removeAll')}
+ </button>
+ <button
+ class="stepbtn"
+ style="border-radius: 6px; background: #7a1f1f"
+ disabled={!$player || selected.size === 0}
+ onclick={remove}
+ >
+ {t('menuRemoveMonsters')} ({selected.size})
+ </button>
+ </div>
+ {/if}
+</Menu>
diff --git a/web/src/lib/ui/menus/SelectScenarioMenu.svelte b/web/src/lib/ui/menus/SelectScenarioMenu.svelte
new file mode 100644
index 0000000..14add41
--- /dev/null
+++ b/web/src/lib/ui/menus/SelectScenarioMenu.svelte
@@ -0,0 +1,109 @@
+<!--
+ Set Scenario (the reference `SelectScenarioMenu`): pick a campaign, then
+ a scenario from it. Selecting sends `setCampaign` (when the campaign
+ changed) followed by `setScenario` — the server applies them in order.
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import { gameData, type CampaignData } from '$lib/data/gameData';
+ import { t } from '$lib/i18n';
+ import Menu from '../Menu.svelte';
+
+ let {
+ session,
+ open = $bindable(true)
+ }: {
+ session: GameSession;
+ open?: boolean;
+ } = $props();
+
+ const gameState = session.state;
+ const player = session.player;
+
+ let campaigns = $state<string[] | null>(null);
+ let campaign = $state('');
+ let data = $state<CampaignData | null>(null);
+ let error = $state<string | null>(null);
+
+ // Load the campaign list and default to the current campaign.
+ $effect(() => {
+ if (!open) return;
+ let alive = true;
+ campaigns = null;
+ error = null;
+ gameData
+ .campaigns()
+ .then((list) => {
+ if (!alive) return;
+ campaigns = list;
+ campaign = $gameState?.currentCampaign && list.includes($gameState.currentCampaign)
+ ? $gameState.currentCampaign
+ : list[0] ?? '';
+ })
+ .catch(() => {
+ if (alive) error = 'failed to load campaigns';
+ });
+ return () => {
+ alive = false;
+ };
+ });
+
+ // Load the selected campaign's scenarios.
+ $effect(() => {
+ const c = campaign;
+ if (!open || !c) return;
+ let alive = true;
+ data = null;
+ gameData
+ .loadCampaign(c)
+ .then((d) => {
+ if (alive) data = d;
+ })
+ .catch(() => {
+ if (alive) error = 'failed to load campaign';
+ });
+ return () => {
+ alive = false;
+ };
+ });
+
+ function pickScenario(scenario: string) {
+ if (!$player) return;
+ if ($gameState && $gameState.currentCampaign !== campaign) {
+ session.command('setCampaign', { campaign });
+ }
+ session.command('setScenario', { scenario, section: false });
+ open = false;
+ }
+</script>
+
+<Menu open={open} title={t('menuSetScenario')}>
+ {#if error}
+ <p style="padding: 12px; opacity: 0.8">{error}</p>
+ {:else if campaigns}
+ <div class="campaignbtns">
+ {#each campaigns as c (c)}
+ <button class:button--active={c === campaign} onclick={() => (campaign = c)}>
+ {c}
+ </button>
+ {/each}
+ </div>
+ {#if data}
+ {#if data.scenarios.length === 0}
+ <p style="padding: 12px; opacity: 0.7">{t('noResultsFound')}</p>
+ {:else}
+ <ul class="menulist">
+ {#each data.scenarios as s (s.name)}
+ <li>
+ <button class="menulist__item" disabled={!$player} onclick={() => pickScenario(s.name)}>
+ {s.name}
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ {:else}
+ <p style="padding: 12px; opacity: 0.7">{t('connecting')}</p>
+ {/if}
+ {/if}
+</Menu>
diff --git a/web/src/lib/ui/menus/SetLevelMenu.svelte b/web/src/lib/ui/menus/SetLevelMenu.svelte
new file mode 100644
index 0000000..158aec1
--- /dev/null
+++ b/web/src/lib/ui/menus/SetLevelMenu.svelte
@@ -0,0 +1,66 @@
+<!--
+ Set Level (the reference `SetLevelMenu`): the scenario level, difficulty,
+ solo, and automatic-level toggles. Each control sends its command
+ immediately (the reference behaviour); the derived trap/hazard/XP/coin
+ values update live.
+-->
+<script lang="ts">
+ import type { GameSession } from '$lib/state/session';
+ import { coinValue, hazardValue, trapValue, xpValue } from '$lib/game/levelValues';
+ import { t } from '$lib/i18n';
+ import Menu from '../Menu.svelte';
+
+ let {
+ session,
+ open = $bindable(true)
+ }: {
+ session: GameSession;
+ open?: boolean;
+ } = $props();
+
+ const gameState = session.state;
+ const player = session.player;
+
+ const level = $derived($gameState?.level ?? 1);
+ const difficulty = $derived($gameState?.difficulty ?? 0);
+ const solo = $derived($gameState?.solo ?? false);
+ const autoLevel = $derived($gameState?.autoScenarioLevel ?? false);
+ const isOgGloom = $derived(($gameState?.currentCampaign ?? '') === 'Gloomhaven');
+
+ function cmd(name: string, args: Record<string, unknown>) {
+ if ($player) session.command(name, args);
+ }
+</script>
+
+<Menu open={open} title={t('setScenarioLevel')}>
+ {#if $gameState}
+ <div class="statrow">
+ <span class="statrow__label">{t('web:level')}</span>
+ <button class="stepbtn" disabled={!$player || level <= 1} onclick={() => cmd('setLevel', { level: level - 1 })}>−</button>
+ <span class="statrow__value">{level}</span>
+ <button class="stepbtn" disabled={!$player || level >= 10} onclick={() => cmd('setLevel', { level: level + 1 })}>+</button>
+ </div>
+
+ <div class="statrow">
+ <span class="statrow__label">{t('difficultyLabel')}</span>
+ <button class="stepbtn" disabled={!$player || difficulty <= 0} onclick={() => cmd('setDifficulty', { difficulty: difficulty - 1 })}>−</button>
+ <span class="statrow__value">{difficulty}</span>
+ <button class="stepbtn" disabled={!$player || difficulty >= 10} onclick={() => cmd('setDifficulty', { difficulty: difficulty + 1 })}>+</button>
+ </div>
+
+ <div class="statrow">
+ <span class="statrow__label">{t('soloLabel')}</span>
+ <input type="checkbox" disabled={!$player} checked={solo} onchange={() => cmd('setSolo', { solo: !solo })} />
+ </div>
+
+ <div class="statrow">
+ <span class="statrow__label">{t('automaticScenarioLevel')}</span>
+ <input type="checkbox" disabled={!$player} checked={autoLevel} onchange={() => cmd('setAutoLevelAdjust', { on: !autoLevel })} />
+ </div>
+
+ <div style="padding: 8px 4px; font-size: 13px; opacity: 0.8">
+ T {trapValue(level)} / H {hazardValue(level, isOgGloom, false)} /
+ X {xpValue(level)} / C {coinValue(level)}
+ </div>
+ {/if}
+</Menu>
diff --git a/web/src/lib/ui/menus/SettingsMenu.svelte b/web/src/lib/ui/menus/SettingsMenu.svelte
new file mode 100644
index 0000000..ef5a91a
--- /dev/null
+++ b/web/src/lib/ui/menus/SettingsMenu.svelte
@@ -0,0 +1,50 @@
+<!--
+ Settings (Phase 3 subset of the reference `SettingsMenu`): the visual
+ style theme and the UI language. Both are client-only preferences.
+-->
+<script lang="ts">
+ import { availableLocales, locale, type Locale } from '$lib/i18n';
+ import { styleTheme, type StyleTheme } from '$lib/settings';
+ import { t } from '$lib/i18n';
+ import Menu from '../Menu.svelte';
+
+ let { open = $bindable(true) }: { open?: boolean } = $props();
+
+ const THEMES: { id: StyleTheme; label: string }[] = [
+ { id: 'frosthaven', label: 'Frosthaven' },
+ { id: 'gloomhaven', label: 'Gloomhaven' },
+ { id: 'original', label: 'Original' }
+ ];
+</script>
+
+<Menu open={open} title={t('menuSettings')}>
+ <div class="settingsrow">
+ <label for="theme">{t('menuSettings')}</label>
+ <select
+ id="theme"
+ class="search"
+ style="margin: 0; width: auto"
+ value={$styleTheme}
+ onchange={(e) => styleTheme.set(e.currentTarget.value as StyleTheme)}
+ >
+ {#each THEMES as th (th.id)}
+ <option value={th.id}>{th.label}</option>
+ {/each}
+ </select>
+ </div>
+
+ <div class="settingsrow">
+ <label for="locale">Language</label>
+ <select
+ id="locale"
+ class="search"
+ style="margin: 0; width: auto"
+ value={$locale}
+ onchange={(e) => locale.set(e.currentTarget.value as Locale)}
+ >
+ {#each availableLocales as l (l)}
+ <option value={l}>{l}</option>
+ {/each}
+ </select>
+ </div>
+</Menu>