From 4f50f2008f4d7c2a635f7f26861fcfc7f7504423 Mon Sep 17 00:00:00 2001 From: Joel Klinghed Date: Sun, 15 Nov 2026 13:45:21 +0100 Subject: Phase 3: web UI core loop (M3) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- web/src/lib/data/classInfo.ts | 29 +++ web/src/lib/data/gameData.ts | 231 ++++++++++++++++++++++++ web/src/lib/game/art.ts | 27 +++ web/src/lib/game/conditions.ts | 57 ++++++ web/src/lib/game/elements.ts | 29 +++ web/src/lib/game/levelValues.ts | 45 +++++ web/src/lib/game/stats.ts | 81 +++++++++ web/src/lib/i18n/en.ts | 138 ++++++++++++++ web/src/lib/i18n/index.ts | 73 ++++++++ web/src/lib/protocol/connection.ts | 231 ++++++++++++++++++++---- web/src/lib/protocol/types.ts | 214 ++++++++++++++++++++++ web/src/lib/settings.ts | 33 ++++ web/src/lib/state/session.ts | 172 ++++++++++++++++++ web/src/lib/ui/BottomBar.svelte | 22 +++ web/src/lib/ui/CharacterRow.svelte | 195 ++++++++++++++++++++ web/src/lib/ui/ConnectionBanner.svelte | 20 ++ web/src/lib/ui/DrawButton.svelte | 47 +++++ web/src/lib/ui/ElementButton.svelte | 88 +++++++++ web/src/lib/ui/LevelWidget.svelte | 52 ++++++ web/src/lib/ui/MainList.svelte | 44 +++++ web/src/lib/ui/MainMenu.svelte | 89 +++++++++ web/src/lib/ui/Menu.svelte | 39 ++++ web/src/lib/ui/MonsterRow.svelte | 109 +++++++++++ web/src/lib/ui/NoteRow.svelte | 57 ++++++ web/src/lib/ui/StatusMenu.svelte | 211 ++++++++++++++++++++++ web/src/lib/ui/Toast.svelte | 12 ++ web/src/lib/ui/TopBar.svelte | 34 ++++ web/src/lib/ui/menus/ActionLogMenu.svelte | 83 +++++++++ web/src/lib/ui/menus/AddCharacterMenu.svelte | 96 ++++++++++ web/src/lib/ui/menus/AddMonsterMenu.svelte | 125 +++++++++++++ web/src/lib/ui/menus/AddNoteRowMenu.svelte | 113 ++++++++++++ web/src/lib/ui/menus/AddSectionMenu.svelte | 79 ++++++++ web/src/lib/ui/menus/RemoveCharacterMenu.svelte | 86 +++++++++ web/src/lib/ui/menus/RemoveMonsterMenu.svelte | 81 +++++++++ web/src/lib/ui/menus/SelectScenarioMenu.svelte | 109 +++++++++++ web/src/lib/ui/menus/SetLevelMenu.svelte | 66 +++++++ web/src/lib/ui/menus/SettingsMenu.svelte | 50 +++++ 37 files changed, 3234 insertions(+), 33 deletions(-) create mode 100644 web/src/lib/data/classInfo.ts create mode 100644 web/src/lib/data/gameData.ts create mode 100644 web/src/lib/game/art.ts create mode 100644 web/src/lib/game/conditions.ts create mode 100644 web/src/lib/game/elements.ts create mode 100644 web/src/lib/game/levelValues.ts create mode 100644 web/src/lib/game/stats.ts create mode 100644 web/src/lib/i18n/en.ts create mode 100644 web/src/lib/i18n/index.ts create mode 100644 web/src/lib/protocol/types.ts create mode 100644 web/src/lib/settings.ts create mode 100644 web/src/lib/state/session.ts create mode 100644 web/src/lib/ui/BottomBar.svelte create mode 100644 web/src/lib/ui/CharacterRow.svelte create mode 100644 web/src/lib/ui/ConnectionBanner.svelte create mode 100644 web/src/lib/ui/DrawButton.svelte create mode 100644 web/src/lib/ui/ElementButton.svelte create mode 100644 web/src/lib/ui/LevelWidget.svelte create mode 100644 web/src/lib/ui/MainList.svelte create mode 100644 web/src/lib/ui/MainMenu.svelte create mode 100644 web/src/lib/ui/Menu.svelte create mode 100644 web/src/lib/ui/MonsterRow.svelte create mode 100644 web/src/lib/ui/NoteRow.svelte create mode 100644 web/src/lib/ui/StatusMenu.svelte create mode 100644 web/src/lib/ui/Toast.svelte create mode 100644 web/src/lib/ui/TopBar.svelte create mode 100644 web/src/lib/ui/menus/ActionLogMenu.svelte create mode 100644 web/src/lib/ui/menus/AddCharacterMenu.svelte create mode 100644 web/src/lib/ui/menus/AddMonsterMenu.svelte create mode 100644 web/src/lib/ui/menus/AddNoteRowMenu.svelte create mode 100644 web/src/lib/ui/menus/AddSectionMenu.svelte create mode 100644 web/src/lib/ui/menus/RemoveCharacterMenu.svelte create mode 100644 web/src/lib/ui/menus/RemoveMonsterMenu.svelte create mode 100644 web/src/lib/ui/menus/SelectScenarioMenu.svelte create mode 100644 web/src/lib/ui/menus/SetLevelMenu.svelte create mode 100644 web/src/lib/ui/menus/SettingsMenu.svelte (limited to 'web/src/lib') 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>(); + +export function classInfo(edition: string, className: string): Promise { + 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; + special?: unknown[]; + initialMessage?: string; +} +interface RawEdition { + edition: string; + classes: RawClass[]; + monsters: Record; + scenarios: Record; +} + +// --- UI-facing types ------------------------------------------------------- + +export interface ClassData { + id: string; + name: string; + edition: string; + hidden: boolean; + health: number[]; + color: string; + colorSecondary: string; + /** `/images/class-icons/.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/.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 | null = null; + private campaignsCache: string[] | null = null; + private readonly cache = new Map>(); + private readonly roomsCache = new Map[]> | null>>(); + + constructor(private readonly base = '/data') {} + + /** The list of campaign/edition names (order from `editions.json`). */ + campaigns(): Promise { + 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 { + 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 { + 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[]> | 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, 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 = { + // 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> = { 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 = writable(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 { + 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; - seats: Record; -} +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 { - 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 | null = null; + private pingTimer: ReturnType | 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 = {}): 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; +} + +// --- 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; +} + +export interface UpdateMessage { + t: 'update'; + index: number; + description: string; + event: GameEvent; + state: GameState; +} + +export interface SeatsMessage { + t: 'seats'; + seats: Record; +} + +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 = writable(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 = writable(null); + readonly seats: Writable> = writable({}); + readonly session: Writable = writable(null); + readonly status: Writable = writable('connecting'); + readonly index: Writable = writable(-1); + readonly description: Writable = writable(null); + readonly lastError: Writable = + writable(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 = 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 = {}): 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[] { + 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 @@ + + + +
+ + +
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 @@ + + + +
+
+ +
+
onOpenMenu(figure)} + onkeydown={(e) => { + if (e.key === 'Enter' || e.key === ' ') onOpenMenu(figure); + }} + > + {cs.display} +
+ + {#if canEnterInit} + (initDraft = '')} + maxlength={2} + inputmode="numeric" + autocomplete="off" + aria-label="Initiative" + /> + {:else if showInitNumber} +
{initDisplay}
+ {/if} + +
onOpenMenu(figure)} + onkeydown={(e) => { + if (e.key === 'Enter' || e.key === ' ') onOpenMenu(figure); + }} + > +
{cs.display}
+
+ {cs.health} / {cs.maxHealth} + + {#each cs.conditions as condIndex} + {conditionLabel(condIndex)} + {/each} + +
+
+ + {#if !isObjective} + XP {cs.xp} + {/if} + {cs.level} + {#if cs.summonList.length > 0} + ⚔ {cs.summonList.length} + {/if} + + +
{ + if (e.key === 'Enter' || e.key === ' ') onTurnTap(); + }} + >
+
+
+ +{#if unclaimed} + +{/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 @@ + + + +{#if visible} + +{/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 @@ + + + + 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 @@ + + + + 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 @@ + + + +
{ + if (e.key === 'Enter') onTap(); + }}> + {#if scenario} +
{scenario}
+ {/if} + {#if $gameState} +
+ {t('web:level')} {level} · + {trapValue(level)} {t('levelLegendLabel')} +
+
+ T {trapValue(level)} / H {hazardValue(level, isOgGloom, false)} / + X {xpValue(level)} / C {coinValue(level)} +
+ {/if} +
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 @@ + + + +
+ {#if $gameState} + {#each $gameState.currentList as item (item.id)} + {#if isCharacter(item)} + + {:else if isMonster(item)} + + {:else if isNoteRow(item)} + + {/if} + {/each} + {#if $gameState.currentList.length === 0} +

+ No characters or monsters yet — use the menu to set a scenario + and add characters. +

+ {/if} + {/if} +
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 @@ + + + +{#if open} + + + +{/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 @@ + + + +{#if open} + +{/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 @@ + + + +
+
+ +
+
onOpenMenu(figureFor(0))} + onkeydown={(e) => { + if (e.key === 'Enter' || e.key === ' ') onOpenMenu(figureFor(0)); + }} + > + {item.id} +
+ +
onArtTap()} + onkeydown={(e) => { + if (e.key === 'Enter' || e.key === ' ') onArtTap(); + }} + > +
+ {item.id} + {#if item.isAlly}ally{/if} +
+
Level {item.level}
+
+
+ + {#if instances.length > 0} +
+ {#each instances as standee, i} + + {/each} +
+ {/if} +
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 @@ + + + +
+
+ {#if editing} + { + if (e.key === 'Enter') commit(); + }} + /> + {:else} + + {/if} +
+
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 @@ + + + + + {#if health != null && maxHealth != null} +
+ Health + {health} / {maxHealth} + + +
+
+ Max Health + {maxHealth} + + +
+ {/if} + + {#if xp != null} +
+ XP + {xp} + + +
+ {/if} + + {#if counters} +
+ {t('cmdAddBless')} + {counters.bless} + + +
+
+ {t('cmdAddCurse')} + {counters.curse} + + +
+
+ {t('cmdAddEmpower')} + {counters.empower} + + +
+
+ {t('cmdAddEnfeeble')} + {counters.enfeeble} + + +
+ {/if} + +
+ {#each CONDITIONS as c, i} + + {/each} +
+ + {#if roundState === 1} +
+ +
+ {/if} +
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 @@ + + + +{#if message} +
{message}
+{/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 @@ + + + +
+ +
X-haven
Assistant
+
+ {#each ELEMENTS as el, i} + + {/each} +
+
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 @@ + + + + + {#if log.length === 0} +

{t('actionLogEmpty')}

+ {:else} +

{t('actionLogRollbackHint')}

+ + {/if} + + {#if confirming != null} +
+
+ {t('actionLogRollbackTitle')} +
+
+ {t('actionLogRollbackBody', { + action: confirmDesc, + count: undosPending ?? 0 + })} +
+
+ + +
+
+ {/if} +
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 @@ + + + + + {#if error} +

{error}

+ {:else} + + +
+ {t('web:level')} + + {level} + +
+ + {#if campaignData === null} +

{t('connecting')}

+ {:else if classes.length === 0} +

{t('noResultsFound')}

+ {:else} + + {/if} + {/if} +
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 @@ + + + + + {#if error} +

{error}

+ {:else} + + + {#if campaigns} +
+ {t('showMonstersFrom')} + +
+ {/if} + +
+ {t('web:level')} + + {level} + +
+ + {#if monsters === null} +

{t('connecting')}

+ {:else if list.length === 0} +

{t('noResultsFound')}

+ {:else} + + {/if} + {/if} +
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 @@ + + + + +
+ {#each COLORS as c (c)} + + {/each} +
+ + + +
+ {t('noteRowWholeGroup')} + +
+ +
+ +
+
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 @@ + + + + + {#if !$gameState?.scenario} +

{t('web:noScenario')}

+ {:else if sections === null} +

{t('connecting')}

+ {:else if sections.length === 0} +

{t('noResultsFound')}

+ {:else} + + {/if} +
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 @@ + + + + + {#if characters.length === 0} +

{t('noResultsFound')}

+ {:else} + + +
+ + +
+ {/if} +
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 @@ + + + + + {#if monsters.length === 0} +

{t('noResultsFound')}

+ {:else} + + +
+ + +
+ {/if} +
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 @@ + + + + + {#if error} +

{error}

+ {:else if campaigns} +
+ {#each campaigns as c (c)} + + {/each} +
+ {#if data} + {#if data.scenarios.length === 0} +

{t('noResultsFound')}

+ {:else} + + {/if} + {:else} +

{t('connecting')}

+ {/if} + {/if} +
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 @@ + + + + + {#if $gameState} +
+ {t('web:level')} + + {level} + +
+ +
+ {t('difficultyLabel')} + + {difficulty} + +
+ +
+ {t('soloLabel')} + cmd('setSolo', { solo: !solo })} /> +
+ +
+ {t('automaticScenarioLevel')} + cmd('setAutoLevelAdjust', { on: !autoLevel })} /> +
+ +
+ T {trapValue(level)} / H {hazardValue(level, isOgGloom, false)} / + X {xpValue(level)} / C {coinValue(level)} +
+ {/if} +
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 @@ + + + + +
+ + +
+ +
+ + +
+
-- cgit v1.3.1