diff options
| author | Joel Klinghed <the_jk@spawned.biz> | 2026-11-15 13:45:21 +0100 |
|---|---|---|
| committer | Joel Klinghed <the_jk@spawned.biz> | 2026-11-15 13:45:21 +0100 |
| commit | 4f50f2008f4d7c2a635f7f26861fcfc7f7504423 (patch) | |
| tree | 94e6286e7e22e0467a61b99c18b9ab582fbbe656 /web/src/lib/data | |
| parent | 3ebbdf6ffa16f751c82e3bd2e74294f4fe843155 (diff) | |
Phase 3: web UI core loop (M3)
Browser game UI on top of the Phase 2 protocol: server-driven, input-only
clients with per-connection secret visibility.
Web (Svelte 5):
- Layout: TopBar (element buttons with use/imbue long-press, title, menu),
MainList (character/monster/note rows), BottomBar (draw/next-round +
level widget with T/H/X/C values).
- CharacterRow with the secret initiative input: own value editable,
server-masked values render as ??, revealed on draw.
- Per-figure StatusMenu: health/max/xp/bless/curse/empower/enfeeble
steppers, condition grid, turn-done — all server commands, player-gated.
- Menu dialogs: select scenario, add section, add/remove character,
set level/difficulty/solo/auto-level, add/remove monster, note row,
action log with rollback, settings (style theme + language).
- Player vs spectator UI gated on the live seat table; reconnecting
banner, error toasts, connection status plumbing.
- i18n: English ported, locale store with localStorage persistence.
- Design tokens + the three style themes (frosthaven/gloomhaven/original).
- Unit tests: level values, game logic (elements/conditions/art/stats),
i18n, the reactive player store, the data client (sections keyed by
scenario number), plus the existing connection/protocol/state tests.
Server:
- Serve the engine's data JSON at /data/ and artwork at /images/ so the
client menus and rows read the same assets the engine loads.
Diffstat (limited to 'web/src/lib/data')
| -rw-r--r-- | web/src/lib/data/classInfo.ts | 29 | ||||
| -rw-r--r-- | web/src/lib/data/gameData.ts | 231 |
2 files changed, 260 insertions, 0 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(); |
