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/test | |
| 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/test')
| -rw-r--r-- | web/test/connection.test.ts | 196 | ||||
| -rw-r--r-- | web/test/fake-socket.ts | 70 | ||||
| -rw-r--r-- | web/test/gameDataClient.test.ts | 209 | ||||
| -rw-r--r-- | web/test/gameLogic.test.ts | 149 | ||||
| -rw-r--r-- | web/test/levelValues.test.ts | 62 | ||||
| -rw-r--r-- | web/test/playerStore.test.ts | 103 | ||||
| -rw-r--r-- | web/test/protocol.test.ts | 37 | ||||
| -rw-r--r-- | web/test/state.test.ts | 183 |
8 files changed, 1006 insertions, 3 deletions
diff --git a/web/test/connection.test.ts b/web/test/connection.test.ts new file mode 100644 index 0000000..27958ba --- /dev/null +++ b/web/test/connection.test.ts @@ -0,0 +1,196 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { GameConnection } from '$lib/protocol/connection'; +import { FakeSocket, SocketSequence } from './fake-socket'; + +function welcome(overrides: Record<string, unknown> = {}) { + return { + t: 'welcome', + v: 1, + session: 's1', + role: 'spectator', + index: 0, + description: null, + event: null, + state: { currentList: [] }, + seats: {}, + ...overrides + }; +} + +describe('GameConnection', () => { + let sockets: SocketSequence; + let conn: GameConnection; + + beforeEach(() => { + vi.useFakeTimers(); + sockets = new SocketSequence(); + conn = new GameConnection({ + transport: sockets.factory, + url: 'ws://test/ws', + reconnectBaseMs: 100, + reconnectMaxMs: 400, + pingIntervalMs: 1_000 + }); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('handshakes with hello and records the session from welcome', () => { + const statuses: string[] = []; + conn.onStatus = (s) => statuses.push(s); + conn.connect(); + sockets.current.open(); + expect(sockets.current.lastJson()).toEqual({ t: 'hello', v: 1 }); + expect(conn.status).toBe('open'); + + let welcomed: unknown = null; + conn.onMessage = (m) => (welcomed = m); + sockets.current.serverSend(welcome({ session: 'abc' })); + expect(conn.session).toBe('abc'); + expect(welcomed).toMatchObject({ t: 'welcome' }); + expect(statuses).toContain('open'); + }); + + it('forwards update, seats, and error to their handlers', () => { + const messages: string[] = []; + let errorMessage: string | null = null; + conn.onMessage = (m) => messages.push(m.t); + conn.onError = (e) => (errorMessage = e.message); + + conn.connect(); + sockets.current.open(); + sockets.current.serverSend(welcome()); + + sockets.current.serverSend({ + t: 'update', + index: 1, + description: 'd', + event: { type: 'none' }, + state: {} + }); + sockets.current.serverSend({ t: 'seats', seats: { a: null } }); + sockets.current.serverSend({ t: 'error', code: 'rejected', message: 'nope' }); + sockets.current.serverSend({ t: 'pong' }); + + expect(messages).toEqual([ + 'welcome', + 'update', + 'seats', + 'error', + 'pong' + ]); + expect(errorMessage).toBe('nope'); + }); + + it('sends outbound commands, claims, undo and redo', () => { + conn.connect(); + sockets.current.open(); + sockets.current.serverSend(welcome()); + + conn.sendCmd('draw'); + expect(sockets.current.lastJson()).toEqual({ + t: 'cmd', + name: 'draw', + args: {} + }); + + conn.sendCmd('addCharacter', { id: 'Berserker', edition: 'x' }); + expect(sockets.current.lastJson()).toEqual({ + t: 'cmd', + name: 'addCharacter', + args: { id: 'Berserker', edition: 'x' } + }); + + conn.claim('Berserker'); + expect(sockets.current.lastJson()).toEqual({ + t: 'claim', + characterId: 'Berserker' + }); + + conn.undo(); + expect(sockets.current.lastJson()).toEqual({ t: 'undo' }); + conn.redo(); + expect(sockets.current.lastJson()).toEqual({ t: 'redo' }); + }); + + it('pings on the keepalive interval while open', () => { + conn.connect(); + sockets.current.open(); + sockets.current.serverSend(welcome()); + // clear the hello frame so we can see pings + const before = sockets.current.sent.length; + vi.advanceTimersByTime(1_000); + expect(sockets.current.sent.slice(before)).toEqual([ + JSON.stringify({ t: 'ping' }) + ]); + vi.advanceTimersByTime(2_000); + expect(sockets.current.sent.slice(before)).toHaveLength(3); + }); + + it('reconnects, resyncs via a fresh hello, and backs off across churn', () => { + conn.connect(); + const first = sockets.current; + first.open(); + first.serverSend(welcome({ session: 'abc' })); + expect(conn.session).toBe('abc'); + + // Server drops the connection → first retry after the base delay. + first.serverClose(); + expect(conn.status).toBe('reconnecting'); + vi.advanceTimersByTime(99); + expect(sockets.sockets.length).toBe(1); + vi.advanceTimersByTime(1); + expect(sockets.sockets.length).toBe(2); + + // The reconnect re-sends hello (the resync). + const second = sockets.current; + second.open(); + expect(second.lastJson()).toEqual({ t: 'hello', v: 1 }); + expect(conn.status).toBe('open'); + + // A failed second attempt (closes without a welcome) doubles the backoff. + second.serverClose(); + vi.advanceTimersByTime(199); + expect(sockets.sockets.length).toBe(2); + vi.advanceTimersByTime(1); + expect(sockets.sockets.length).toBe(3); + expect(conn.status).toBe('reconnecting'); + + // A real welcome resets the backoff to the base. + const third = sockets.current; + third.open(); + third.serverSend(welcome({ session: 'abc' })); + third.serverClose(); + vi.advanceTimersByTime(99); + expect(sockets.sockets.length).toBe(3); + vi.advanceTimersByTime(1); + expect(sockets.sockets.length).toBe(4); + }); + + it('resync() re-requests a full welcome', () => { + conn.connect(); + sockets.current.open(); + sockets.current.serverSend(welcome()); + conn.resync(); + expect(sockets.current.lastJson()).toEqual({ t: 'hello', v: 1 }); + }); + + it('does not reconnect after an intentional disconnect', () => { + conn.connect(); + sockets.current.open(); + sockets.current.serverSend(welcome()); + conn.disconnect(); + expect(conn.status).toBe('closed'); + vi.advanceTimersByTime(10_000); + expect(sockets.sockets.length).toBe(1); + }); + + it('ignores non-JSON frames', () => { + conn.connect(); + sockets.current.open(); + sockets.current.serverSend('not json'); + expect(conn.session).toBeNull(); + }); +}); diff --git a/web/test/fake-socket.ts b/web/test/fake-socket.ts new file mode 100644 index 0000000..290f9a8 --- /dev/null +++ b/web/test/fake-socket.ts @@ -0,0 +1,70 @@ +/** + * A scriptable fake WebSocket for the connection tests. It records outbound + * frames and lets tests drive `open` / `message` / `close` from either side. + */ +import type { Transport } from '$lib/protocol/connection'; + +export class FakeSocket implements Transport { + onopen: ((ev?: unknown) => void) | null = null; + onclose: ((ev?: unknown) => void) | null = null; + onerror: ((ev?: unknown) => void) | null = null; + onmessage: ((ev: { data: unknown }) => void) | null = null; + readyState = 1; // CONNECTING + + readonly sent: string[] = []; + closed = false; + + send(data: string): void { + if (this.readyState !== 0) throw new Error('not open'); + this.sent.push(data); + } + + close(): void { + if (this.closed) return; + this.closed = true; + this.readyState = 3; + this.onclose?.(); + } + + // test drivers -------------------------------------------------------- + + open(): void { + this.readyState = 0; + this.onopen?.(); + } + + /** Deliver a raw server frame. */ + serverSend(obj: object | string): void { + const data = typeof obj === 'string' ? obj : JSON.stringify(obj); + this.onmessage?.({ data }); + } + + /** The socket drops (server-side close). */ + serverClose(): void { + if (this.closed) return; + this.closed = true; + this.readyState = 3; + this.onclose?.(); + } + + lastJson(): Record<string, unknown> | null { + if (this.sent.length === 0) return null; + return JSON.parse(this.sent[this.sent.length - 1]); + } +} + +/** Creates and tracks a sequence of fake sockets handed to a connection. */ +export class SocketSequence { + readonly sockets: FakeSocket[] = []; + + // Arrow field so `this` survives being passed as a bare transport factory. + factory = (_url: string): Transport => { + const socket = new FakeSocket(); + this.sockets.push(socket); + return socket; + }; + + get current(): FakeSocket { + return this.sockets[this.sockets.length - 1]; + } +} diff --git a/web/test/gameDataClient.test.ts b/web/test/gameDataClient.test.ts new file mode 100644 index 0000000..4249283 --- /dev/null +++ b/web/test/gameDataClient.test.ts @@ -0,0 +1,209 @@ +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { GameDataClient } from '$lib/data/gameData'; + +afterEach(() => vi.unstubAllGlobals()); + +function json(value: unknown) { + return Promise.resolve({ + ok: true, + json: () => Promise.resolve(value) + } as Response); +} + +function withFetch(handler: (url: string) => Promise<Response>) { + // Clients are constructed per test, so the per-instance caches are clean. + vi.stubGlobal('fetch', (input: RequestInfo | URL) => { + const url = typeof input === 'string' ? input : input.toString(); + return handler(url); + }); +} + +const ROOMS = { + '1': [ + { 'A Town in Flames': {} }, + { 'The Cellar': {} }, + { 'Spawn Alley': {} }, + { 'The Chapel': {} } + ], + '4A': [ + { 'Frostbite Landing': {} }, + { 'Frozen Harbor': {} } + ] +}; + +describe('GameDataClient.campaigns', () => { + it('reads the campaign list from editions.json', async () => { + withFetch((url) => { + expect(url).toBe('/data/editions/editions.json'); + return json({ editions: ['Gloomhaven', 'Jaws of the Lion'] }); + }); + const data = new GameDataClient(); + await expect(data.campaigns()).resolves.toEqual([ + 'Gloomhaven', + 'Jaws of the Lion' + ]); + }); + + it('caches after the first load', async () => { + let calls = 0; + withFetch(() => { + calls++; + return json({ editions: ['Gloomhaven'] }); + }); + const data = new GameDataClient(); + await data.campaigns(); + await data.campaigns(); + expect(calls).toBe(1); + }); +}); + +describe('GameDataClient.loadCampaign', () => { + it('maps classes, monsters and scenarios', async () => { + withFetch((url) => { + expect(url).toBe('/data/editions/Jaws%20of%20the%20Lion.json'); + return json({ + edition: 'Jaws of the Lion', + classes: [ + { + name: 'Berserker', + edition: 'Jaws of the Lion', + health: [12, 14], + hidden: false, + color: 'FF35ACD5', + colorSecondary: 'ff313959' + }, + { + name: 'Secret', + edition: 'Jaws of the Lion', + health: [10], + hidden: true, + color: ['FF112233'] + } + ], + monsters: { + 'Zombie': { + deck: 'Zombie', + count: 4, + levels: [ + { level: 0, normal: { health: 3 } }, + { level: 2, normal: { health: 5 }, elite: { health: 8 } } + ] + }, + 'Dreadnaught': { + deck: 'Dreadnaught', + count: 2, + display: 'Dreadnaught (Boss)', + levels: [{ level: 0, boss: { health: 40 } }], + gfx: 'Dreadnaught' + } + }, + scenarios: { + '#1 A Town in Flames': { monsters: ['Zombie'] }, + '#2 A Dark Night': {} + } + }); + }); + const data = new GameDataClient(); + const campaign = await data.loadCampaign('Jaws of the Lion'); + expect(campaign.edition).toBe('Jaws of the Lion'); + expect(campaign.classes).toEqual([ + { + id: 'Berserker', + name: 'Berserker', + edition: 'Jaws of the Lion', + hidden: false, + health: [12, 14], + color: 'FF35ACD5', + colorSecondary: 'ff313959', + icon: '/images/class-icons/Berserker.png' + }, + expect.objectContaining({ + id: 'Secret', + hidden: true, + color: 'FF112233' // first of an array + }) + ]); + const zombie = campaign.monsters.find((m) => m.name === 'Zombie'); + expect(zombie).toMatchObject({ + display: 'Zombie', + gfx: 'Zombie', + count: 4, + maxLevel: 2, + isBoss: false, + portrait: '/images/monsters/Zombie.png' + }); + const boss = campaign.monsters.find((m) => m.name === 'Dreadnaught'); + expect(boss).toMatchObject({ + display: 'Dreadnaught (Boss)', + maxLevel: 0, + isBoss: true + }); + expect(campaign.scenarios.map((s) => s.name)).toEqual([ + '#1 A Town in Flames', + '#2 A Dark Night' + ]); + expect(campaign.scenarios[0].monsters).toEqual(['Zombie']); + }); + + it('caches per campaign (one fetch per campaign)', async () => { + let calls = 0; + withFetch(() => { + calls++; + return json({ edition: 'Gloomhaven', classes: [], monsters: {}, scenarios: {} }); + }); + const data = new GameDataClient(); + await data.loadCampaign('Gloomhaven'); + await data.loadCampaign('Gloomhaven'); + expect(calls).toBe(1); + }); + + it('rejects on a missing campaign', async () => { + withFetch(() => + Promise.resolve({ ok: false, json: () => Promise.reject(new Error('nope')) } as Response) + ); + const data = new GameDataClient(); + await expect(data.loadCampaign('Nope')).rejects.toThrow( + 'failed to load campaign Nope' + ); + }); +}); + +describe('GameDataClient.sections', () => { + it('lists the addable rooms for a scenario number', async () => { + withFetch((url) => { + expect(url).toBe('/data/rooms/Jaws%20of%20the%20Lion.json'); + return json(ROOMS); + }); + const data = new GameDataClient(); + await expect(data.sections('Jaws of the Lion', '#1 A Town in Flames')).resolves.toEqual([ + 'The Cellar', + 'The Chapel' + ]); // first room skipped, "Spawn Alley" filtered + }); + + it('handles lettered scenario numbers', async () => { + withFetch(() => json(ROOMS)); + const data = new GameDataClient(); + await expect(data.sections('Jaws of the Lion', '#4A Frostbite')).resolves.toEqual([ + 'Frozen Harbor' + ]); + }); + + it('returns empty for unknown scenarios', async () => { + withFetch(() => json(ROOMS)); + const data = new GameDataClient(); + await expect(data.sections('Jaws of the Lion', '#99 Nowhere')).resolves.toEqual( + [] + ); + }); + + it('returns empty when the rooms file is missing', async () => { + withFetch(() => + Promise.resolve({ ok: false, json: () => Promise.reject(new Error('nope')) } as Response) + ); + const data = new GameDataClient(); + await expect(data.sections('Jaws of the Lion', '#1 A Town in Flames')).resolves.toEqual( + [] + ); + }); +}); diff --git a/web/test/gameLogic.test.ts b/web/test/gameLogic.test.ts new file mode 100644 index 0000000..263ba14 --- /dev/null +++ b/web/test/gameLogic.test.ts @@ -0,0 +1,149 @@ +import { describe, it, expect } from 'vitest'; +import { ELEMENTS, elementState } from '$lib/game/elements'; +import { + CONDITIONS, + conditionChipClass, + conditionLabel, + conditionName +} from '$lib/game/conditions'; +import { classColor, classIcon, monsterImage } from '$lib/game/art'; +import { + characterStatCounters, + standeeFigureId, + standeeStatCounters, + type ModifierDeckJson +} from '$lib/game/stats'; +import { t, hasLocaleKey, availableLocales } from '$lib/i18n'; + +describe('elements', () => { + it('lists the six elements in server enum order', () => { + expect(ELEMENTS.map((e) => e.name)).toEqual([ + 'fire', + 'ice', + 'air', + 'earth', + 'light', + 'dark' + ]); + }); + + it('reads the element state by index string (absent → inert)', () => { + expect(elementState({}, 0)).toBe(2); + expect(elementState({ '0': 0, '1': 1 }, 0)).toBe(0); + expect(elementState({ '0': 0, '1': 1 }, 1)).toBe(1); + expect(elementState({ '0': 9 }, 0)).toBe(2); // out-of-range → inert + }); +}); + +describe('conditions', () => { + it('keeps the server Condition index mapping', () => { + // stun = 0, wound = 3, chill = 12, retaliate = 24 + expect(conditionName(0)).toBe('stun'); + expect(conditionName(3)).toBe('wound'); + expect(conditionName(12)).toBe('chill'); + expect(conditionName(24)).toBe('retaliate'); + }); + + it('labels fall back to the index for unknown entries', () => { + expect(conditionLabel(0)).toBe('Stunned'); + expect(conditionLabel(999)).toBe('condition 999'); + }); + + it('chill and plague get coloured chips, the rest are plain', () => { + expect(conditionChipClass(12)).toBe('cond cond--chill'); + expect(conditionChipClass(16)).toBe('cond cond--plague'); + expect(conditionChipClass(0)).toBe('cond'); + }); + + it('excludes the custom character slots (character1..4)', () => { + const names = CONDITIONS.map((c) => c.name); + expect(names).not.toContain('character1'); + expect(names).not.toContain('character4'); + }); +}); + +describe('art', () => { + it('resolves class icons and monster art under /images/', () => { + // gfx values in the data carry no extension; .png is appended (the + // reference app builds the same path). + expect(classIcon('Berserker')).toBe('/images/class-icons/Berserker.png'); + expect(monsterImage('Zombie')).toBe('/images/monsters/Zombie.png'); + }); + + it('classColor accepts 0xAARRGGBB and plain hex', () => { + expect(classColor('FF9C881A')).toBe('#9C881A'); + expect(classColor('#a1b2c3')).toBe('#a1b2c3'); + expect(classColor('garbage')).toBe('#3a3f47'); + }); +}); + +describe('stat counters', () => { + function deck(cards: { gfx: string }[]): ModifierDeckJson { + return { drawPile: cards, discardPile: [] }; + } + + it('standeeFigureId is name + gfx + standeeNr', () => { + const standee = { + name: 'Zombie', + gfx: 'BLA zombie', + standeeNr: 2 + } as never; + expect(standeeFigureId(standee)).toBe('ZombieBLA zombie2'); + }); + + it('counts bless/curse/empower/enfeeble cards in the draw pile', () => { + const d = deck([ + { gfx: 'bless' }, + { gfx: 'curse' }, + { gfx: 'in-empower' }, + { gfx: 'out-enfeeble' }, + { gfx: 'bless' }, + { gfx: 'hazard-1' } + ]); + expect(standeeStatCounters(d)).toEqual({ + bless: 2, + curse: 1, + empower: 1, + enfeeble: 1 + }); + expect(standeeStatCounters(undefined)).toEqual({ + bless: 0, + curse: 0, + empower: 0, + enfeeble: 0 + }); + }); + + it('characterStatCounters reads the character\'s own deck', () => { + const character = { + id: 'Berserker', + characterState: { + modifierDeck: deck([{ gfx: 'curse' }, { gfx: 'curse' }]) + } + } as never; + expect(characterStatCounters(character).curse).toBe(2); + }); +}); + +describe('i18n', () => { + it('translates English keys', () => { + expect(t('draw')).toBe('Draw'); + expect(t('menuAddCharacter')).toBe('Add Character'); + }); + + it('substitutes {vars}', () => { + expect(t('cmdAddMonster', { name: 'Zombie' })).toBe('Add Zombie'); + expect(t('cmdIncreaseXp', { figure: 'Berserker', amount: 10 })).toBe( + "Increase Berserker's xp by 10" + ); + }); + + it('returns the key for unknown keys', () => { + expect(t('noSuchKey')).toBe('noSuchKey'); + }); + + it('only English is ported in Phase 3', () => { + expect(availableLocales).toEqual(['en']); + expect(hasLocaleKey('draw')).toBe(true); + }); +}); diff --git a/web/test/levelValues.test.ts b/web/test/levelValues.test.ts new file mode 100644 index 0000000..bdcb08c --- /dev/null +++ b/web/test/levelValues.test.ts @@ -0,0 +1,62 @@ +import { describe, it, expect } from 'vitest'; +import { + coinValue, + hazardValue, + recommendedLevel, + trapValue, + xpValue +} from '$lib/game/levelValues'; + +describe('level values (GameMethods port)', () => { + it('trap = 2 + level', () => { + expect(trapValue(1)).toBe(3); + expect(trapValue(10)).toBe(12); + }); + + it('hazard = 1 + ceil(level / 3)', () => { + expect(hazardValue(1, false, false)).toBe(2); + expect(hazardValue(3, false, false)).toBe(2); + expect(hazardValue(4, false, false)).toBe(3); + }); + + it('OGGloom hazard halves the trap value by default', () => { + // floor((2 + level) / 2) + expect(hazardValue(1, true, false)).toBe(1); + expect(hazardValue(5, true, false)).toBe(3); + }); + + it('OGGloom with the FH setting uses the regular formula', () => { + expect(hazardValue(5, true, true)).toBe(3); // 1 + ceil(5/3) + expect(hazardValue(4, true, true)).toBe(3); // 1 + ceil(4/3) + }); + + it('xp = 4 + 2 * level', () => { + expect(xpValue(1)).toBe(6); + expect(xpValue(4)).toBe(12); + }); + + it('coin = 2 + floor(level / 2), capped at 6 on level 7', () => { + expect(coinValue(1)).toBe(2); + expect(coinValue(2)).toBe(3); + expect(coinValue(6)).toBe(5); + expect(coinValue(7)).toBe(6); + expect(coinValue(8)).toBe(6); // 2 + floor(8/2) = 6, same + }); +}); + +describe('recommendedLevel (GameMethods port)', () => { + it('defaults to 1 with no characters', () => { + expect(recommendedLevel([], false)).toBe(1); + }); + + it('party: average level divided by 2, rounded up', () => { + expect(recommendedLevel([2, 2, 2, 2], false)).toBe(1); + expect(recommendedLevel([4, 4, 4, 4], false)).toBe(2); + expect(recommendedLevel([3, 3, 3, 3], false)).toBe(2); + }); + + it('solo: (average + 1) / 2, rounded up', () => { + expect(recommendedLevel([1], true)).toBe(1); + expect(recommendedLevel([4], true)).toBe(3); + }); +}); diff --git a/web/test/playerStore.test.ts b/web/test/playerStore.test.ts new file mode 100644 index 0000000..c3aefe8 --- /dev/null +++ b/web/test/playerStore.test.ts @@ -0,0 +1,103 @@ +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { get } from 'svelte/store'; +import { GameSession } from '$lib/state/session'; +import type { GameState } from '$lib/protocol/types'; +import { SocketSequence } from './fake-socket'; + +function makeState(overrides: Partial<GameState> = {}): GameState { + return { + level: 1, + solo: false, + autoScenarioLevel: false, + difficulty: 1, + roundState: 0, + round: 1, + totalRounds: 1, + scenario: 'custom', + toastMessage: '', + scenarioSpecialRules: [], + scenarioSectionsAdded: [], + currentCampaign: 'Jaws of the Lion', + currentList: [], + currentAbilityDecks: [], + sanctuaryDeck: {}, + modifierDeck: {}, + modifierDeckAllies: {}, + lootDeck: {}, + unlockedClasses: [], + showAllyDeck: false, + allyDeckInOGGloom: true, + elementState: {}, + ...overrides + }; +} + +describe('GameSession.player (reactive player/spectator flag)', () => { + let session: GameSession; + let sockets: SocketSequence; + + beforeEach(() => { + vi.useFakeTimers(); + sockets = new SocketSequence(); + session = new GameSession({ + transport: sockets.factory, + url: 'ws://test/ws', + reconnectBaseMs: 100, + pingIntervalMs: 60_000 + }); + session.connect(); + sockets.current.open(); + }); + + afterEach(() => vi.useRealTimers()); + + function welcome(role: 'player' | 'spectator', seats: Record<string, string | null>) { + sockets.current.serverSend({ + t: 'welcome', + v: 1, + session: 'sess1', + role, + index: 1, + description: '', + event: null, + state: makeState(), + seats + }); + } + + function seats(seats: Record<string, string | null>) { + sockets.current.serverSend({ t: 'seats', seats }); + } + + it('is false before a welcome arrives', () => { + expect(get(session.player)).toBe(false); + }); + + it('is false for a spectator with no claimed seats', () => { + welcome('spectator', { A: 'sess2' }); + expect(get(session.player)).toBe(false); + expect(session.isSpectator()).toBe(true); + }); + + it('is true when a seat belongs to the session', () => { + welcome('player', { A: 'sess1', B: 'sess2' }); + expect(get(session.player)).toBe(true); + expect(session.isSpectator()).toBe(false); + }); + + it('flips to true the moment a claim is granted (seats broadcast)', () => { + welcome('spectator', { A: 'sess2', B: null }); + expect(get(session.player)).toBe(false); + seats({ A: 'sess2', B: 'sess1' }); + expect(get(session.player)).toBe(true); + expect(session.ownedCharacterIds()).toEqual(['B']); + }); + + it('flips back to false when the seat is released', () => { + welcome('player', { A: 'sess1' }); + expect(get(session.player)).toBe(true); + seats({ A: null }); + expect(get(session.player)).toBe(false); + expect(session.isSpectator()).toBe(true); + }); +}); diff --git a/web/test/protocol.test.ts b/web/test/protocol.test.ts index c804d8b..e12df4e 100644 --- a/web/test/protocol.test.ts +++ b/web/test/protocol.test.ts @@ -1,8 +1,39 @@ import { describe, expect, it } from 'vitest'; -import { buildHello } from '$lib/protocol/connection'; +import { + claimMessage, + commandMessage, + helloMessage, + pingMessage +} from '$lib/protocol/types'; -describe('wire protocol', () => { +describe('wire protocol builders', () => { it('builds the hello handshake message', () => { - expect(buildHello()).toEqual({ t: 'hello', v: 1 }); + expect(helloMessage()).toEqual({ t: 'hello', v: 1 }); + }); + + it('builds a command message with default empty args', () => { + expect(commandMessage('draw')).toEqual({ + t: 'cmd', + name: 'draw', + args: {} + }); + }); + + it('builds a command message with args', () => { + expect( + commandMessage('addCharacter', { id: 'Berserker', edition: 'x' }) + ).toEqual({ + t: 'cmd', + name: 'addCharacter', + args: { id: 'Berserker', edition: 'x' } + }); + }); + + it('builds claim, ping messages', () => { + expect(claimMessage('Berserker')).toEqual({ + t: 'claim', + characterId: 'Berserker' + }); + expect(pingMessage()).toEqual({ t: 'ping' }); }); }); diff --git a/web/test/state.test.ts b/web/test/state.test.ts new file mode 100644 index 0000000..3dada4f --- /dev/null +++ b/web/test/state.test.ts @@ -0,0 +1,183 @@ +import { + describe, + it, + expect, + beforeEach, + afterEach, + vi +} from 'vitest'; +import { get } from 'svelte/store'; +import { GameSession, ownedIds } from '$lib/state/session'; +import type { GameState } from '$lib/protocol/types'; +import { SocketSequence } from './fake-socket'; + +function makeState(overrides: Partial<GameState> = {}): GameState { + return { + level: 1, + solo: false, + autoScenarioLevel: false, + difficulty: 1, + roundState: 0, + round: 1, + totalRounds: 1, + scenario: 'custom', + toastMessage: '', + scenarioSpecialRules: [], + scenarioSectionsAdded: [], + currentCampaign: 'Jaws of the Lion', + currentList: [], + currentAbilityDecks: [], + sanctuaryDeck: {}, + modifierDeck: {}, + modifierDeckAllies: {}, + lootDeck: {}, + unlockedClasses: [], + showAllyDeck: false, + allyDeckInOGGloom: true, + elementState: {}, + ...overrides + }; +} + +function welcome( + state: GameState, + session = 'sess1', + role: 'player' | 'spectator' = 'spectator', + seats: Record<string, string | null> = {}, + index = 7 +) { + return { + t: 'welcome', + v: 1, + session, + role, + index, + description: 'last action', + event: null, + state, + seats + }; +} + +describe('GameSession', () => { + let session: GameSession; + let sockets: SocketSequence; + + beforeEach(() => { + vi.useFakeTimers(); + sockets = new SocketSequence(); + session = new GameSession({ + transport: sockets.factory, + url: 'ws://test/ws', + reconnectBaseMs: 100, + pingIntervalMs: 60_000 + }); + session.connect(); + sockets.current.open(); + }); + + afterEach(() => vi.useRealTimers()); + + function welcomeWith( + state: GameState, + sessionId = 'sess1', + role: 'player' | 'spectator' = 'player', + seats: Record<string, string | null> = {} + ) { + sockets.current.serverSend( + welcome(state, sessionId, role, seats) + ); + } + + it('starts empty and connecting', () => { + expect(get(session.state)).toBeNull(); + expect(get(session.session)).toBeNull(); + expect(get(session.index)).toBe(-1); + }); + + it('applies a welcome to every store', () => { + welcomeWith(makeState({ round: 3 }), 'sess1', 'player', { B: 'sess1' }); + expect(get(session.session)).toEqual({ id: 'sess1', role: 'player' }); + expect(get(session.state)?.round).toBe(3); + expect(get(session.seats)).toEqual({ B: 'sess1' }); + expect(get(session.index)).toBe(7); + expect(get(session.status)).toBe('open'); + }); + + it('replaces state and index on an update', () => { + welcomeWith(makeState({ round: 4 })); + sockets.current.serverSend({ + t: 'update', + index: 8, + description: 'x', + event: { type: 'none' }, + state: makeState({ round: 5 }) + }); + expect(get(session.state)?.round).toBe(5); + expect(get(session.index)).toBe(8); + }); + + it('owns() is true only for the session\'s characters', () => { + welcomeWith(makeState(), 'sess1', 'player', { + A: 'sess1', + B: 'sess2', + C: null + }); + expect(session.owns('A')).toBe(true); + expect(session.owns('B')).toBe(false); + expect(session.owns('C')).toBe(false); + }); + + it('reports spectator when no seat is claimed', () => { + welcomeWith(makeState(), 'sess1', 'spectator', { A: 'sess2' }); + expect(session.isSpectator()).toBe(true); + expect(session.ownedCharacterIds()).toEqual([]); + }); + + it('lists owned character ids', () => { + welcomeWith(makeState(), 'sess1', 'player', { + A: 'sess1', + B: 'sess1', + C: 'sess2' + }); + expect(session.ownedCharacterIds().sort()).toEqual(['A', 'B']); + }); + + it('surfaces protocol errors and clears them', () => { + sockets.current.serverSend({ + t: 'error', + code: 'forbidden', + message: 'claim a character first' + }); + expect(get(session.lastError)).toEqual({ + code: 'forbidden', + message: 'claim a character first' + }); + session.clearError(); + expect(get(session.lastError)).toBeNull(); + }); + + it('sends commands and claims through the socket', () => { + welcomeWith(makeState()); + session.command('draw'); + expect(sockets.current.lastJson()).toEqual({ + t: 'cmd', + name: 'draw', + args: {} + }); + session.claim('Berserker'); + expect(sockets.current.lastJson()).toEqual({ + t: 'claim', + characterId: 'Berserker' + }); + }); +}); + +describe('ownedIds', () => { + it('returns ids owned by the session', () => { + expect(ownedIds('s', { a: 's', b: 't', c: null })).toEqual(['a']); + }); + it('returns empty for a null session', () => { + expect(ownedIds(null, { a: 's' })).toEqual([]); + }); +}); |
