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.
---
server/bin/main.dart | 3 +
server/lib/net/app.dart | 50 +-
server/test/net/app_test.dart | 9 +
server/test/net/ws_test_helpers.dart | 1 +
web/src/App.svelte | 179 +++++-
web/src/app.css | 746 +++++++++++++++++++++++-
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 ++
web/static/fonts/GermaniaOne-Regular.ttf | Bin 0 -> 30428 bytes
web/static/fonts/PirataOne-Gloomhaven.ttf | Bin 0 -> 91728 bytes
web/test/connection.test.ts | 196 +++++++
web/test/fake-socket.ts | 70 +++
web/test/gameDataClient.test.ts | 209 +++++++
web/test/gameLogic.test.ts | 149 +++++
web/test/levelValues.test.ts | 62 ++
web/test/playerStore.test.ts | 103 ++++
web/test/protocol.test.ts | 37 +-
web/test/state.test.ts | 183 ++++++
web/vite.config.ts | 8 +
54 files changed, 5210 insertions(+), 62 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
create mode 100644 web/static/fonts/GermaniaOne-Regular.ttf
create mode 100644 web/static/fonts/PirataOne-Gloomhaven.ttf
create mode 100644 web/test/connection.test.ts
create mode 100644 web/test/fake-socket.ts
create mode 100644 web/test/gameDataClient.test.ts
create mode 100644 web/test/gameLogic.test.ts
create mode 100644 web/test/levelValues.test.ts
create mode 100644 web/test/playerStore.test.ts
create mode 100644 web/test/state.test.ts
diff --git a/server/bin/main.dart b/server/bin/main.dart
index 7571960..f864828 100644
--- a/server/bin/main.dart
+++ b/server/bin/main.dart
@@ -40,6 +40,9 @@ Future main(List args) async {
port: port,
staticDir: staticDir,
gameServer: gameServer,
+ // The client's menus and artwork read the same assets the engine loads.
+ dataDir: 'assets/data/',
+ imageDir: 'assets/images/',
);
stdout
..writeln('X-Haven server listening on http://localhost:${server.port}')
diff --git a/server/lib/net/app.dart b/server/lib/net/app.dart
index 21a1b81..a38d5c0 100644
--- a/server/lib/net/app.dart
+++ b/server/lib/net/app.dart
@@ -19,13 +19,30 @@ import 'ws_upgrade.dart';
final _log = Logger('server');
/// Builds the HTTP handler for the game server.
-Handler createHandler({required String staticDir, required GameServer gameServer}) {
+///
+/// [dataDir] (e.g. `assets/data/`) is served read-only at `/data/` when
+/// non-null: the client's menus read the campaign/scenario/character/section
+/// JSON from it (the same files the engine loads). [imageDir] (e.g.
+/// `assets/images/`) is served at `/images/` when non-null — character and
+/// monster artwork for the main list.
+Handler createHandler({
+ required String staticDir,
+ required GameServer gameServer,
+ String? dataDir,
+ String? imageDir,
+}) {
final router = Router();
router.get('/ws', createWebSocketUpgradeHandler(gameServer));
router.get('/healthz', (Request request) => Response.ok(
jsonEncode({'status': 'ok'}),
headers: {'content-type': 'application/json; charset=utf-8'},
));
+ if (dataDir != null) {
+ router.mount('/data/', _createStaticHandler(dataDir, plain: true));
+ }
+ if (imageDir != null) {
+ router.mount('/images/', _createStaticHandler(imageDir, plain: true));
+ }
// Session endpoint (PLAN.md section 3.3): returns the caller's persistent
// session id, setting the `x-haven-session` cookie when the caller has
// none yet. Browsers then carry the cookie on every same-origin request,
@@ -53,8 +70,19 @@ Future startServer({
required int port,
required String staticDir,
required GameServer gameServer,
+ String? dataDir,
+ String? imageDir,
}) {
- return shelf_io.serve(createHandler(staticDir: staticDir, gameServer: gameServer), '0.0.0.0', port);
+ return shelf_io.serve(
+ createHandler(
+ staticDir: staticDir,
+ gameServer: gameServer,
+ dataDir: dataDir,
+ imageDir: imageDir,
+ ),
+ '0.0.0.0',
+ port,
+ );
}
/// The session id from [request]'s cookie, when well-formed.
@@ -71,9 +99,17 @@ String? _validSessionIdFrom(Request request) {
return null;
}
-Handler _createStaticHandler(String staticDir) {
+/// Serves [staticDir] as static files. When [plain] is true (data/image
+/// directories) it is plain static serving with a cache header and a plain
+/// 404; otherwise (the SPA build) a 404 on an extensionless path falls back
+/// to `index.html` so client-side routes resolve.
+Handler _createStaticHandler(String staticDir, {bool plain = false}) {
final directory = Directory(staticDir);
if (!directory.existsSync()) {
+ if (plain) {
+ _log.info('data dir $staticDir not found; serving 404');
+ return (Request request) => Response.notFound('not found');
+ }
_log.info('static dir $staticDir not found; serving stub page');
return (Request request) => Response.ok(
''
@@ -85,6 +121,14 @@ Handler _createStaticHandler(String staticDir) {
'with --static-dir ../web/dist.
',
);
}
+ if (plain) {
+ // Plain static serving (no SPA fallback) with long-lived caching —
+ // the JSON and images are immutable build inputs.
+ return createStaticHandler(
+ directory.path,
+ maxAge: const Duration(days: 1),
+ );
+ }
final staticHandler = createStaticHandler(
directory.path,
defaultDocument: 'index.html',
diff --git a/server/test/net/app_test.dart b/server/test/net/app_test.dart
index 4a02c15..a37a8e5 100644
--- a/server/test/net/app_test.dart
+++ b/server/test/net/app_test.dart
@@ -42,6 +42,15 @@ void main() {
expect(jsonDecode(body), {'status': 'ok'});
});
+ test('serves the game data JSON at /data/', () async {
+ final body = await httpGet(
+ server.httpUrl.replace(path: '/data/editions/editions.json'),
+ );
+ final decoded = jsonDecode(body) as Map;
+ expect(decoded['editions'], isA());
+ expect(decoded['editions'], contains('Jaws of the Lion'));
+ });
+
test('session endpoint mints a session and sets the cookie', () async {
final client = HttpClient();
addTearDown(client.close);
diff --git a/server/test/net/ws_test_helpers.dart b/server/test/net/ws_test_helpers.dart
index cb8af67..1903567 100644
--- a/server/test/net/ws_test_helpers.dart
+++ b/server/test/net/ws_test_helpers.dart
@@ -63,6 +63,7 @@ class TestGameServer {
port: 0,
staticDir: 'nonexistent-static-dir',
gameServer: instance.gameServer,
+ dataDir: dataDir,
);
return instance;
}
diff --git a/web/src/App.svelte b/web/src/App.svelte
index a1a370d..d694ee4 100644
--- a/web/src/App.svelte
+++ b/web/src/App.svelte
@@ -1,25 +1,166 @@
+
-
- X-Haven
- Connection: {status}
- {#if welcome}
- Session: {welcome.session}
- Role: {welcome.role}
- State index: {welcome.index}
- {:else}
- Waiting for server…
- {/if}
-
+ {
+ if (e.key === 'Escape') {
+ drawerOpen = false;
+ menuOpen = false;
+ figureOpen = false;
+ }
+}} />
+
+
+
(drawerOpen = true)} />
+
+
+
+
+
+ openMenu('setLevel')} />
+
+
+
+
+
+
+
+{#if menu === 'scenario'}
+
+{/if}
+{#if menu === 'section'}
+
+{/if}
+{#if menu === 'addChar'}
+
+{/if}
+{#if menu === 'removeChar'}
+
+{/if}
+{#if menu === 'setLevel'}
+
+{/if}
+{#if menu === 'addMon'}
+
+{/if}
+{#if menu === 'removeMon'}
+
+{/if}
+{#if menu === 'noteRow'}
+
+{/if}
+{#if menu === 'actionLog'}
+
+{/if}
+{#if menu === 'settings'}
+
+{/if}
+
+{#if figure}
+
+{/if}
diff --git a/web/src/app.css b/web/src/app.css
index 34530c9..90cc0c9 100644
--- a/web/src/app.css
+++ b/web/src/app.css
@@ -1,16 +1,754 @@
+/* X-Haven design tokens (Phase 3).
+ *
+ * Mirrors the reference app's look: a textured dark (or light) background,
+ * a 40px top bar with the six element buttons, character rows at 60px and
+ * monster rows at 96px, and a 40px bottom bar. Three style themes —
+ * frosthaven / gloomhaven / original — swap the background artwork and the
+ * display font (PLAN.md Phase 3: "the three style themes").
+ */
+
+@font-face {
+ font-family: 'GermaniaOne';
+ src: url('/fonts/GermaniaOne-Regular.ttf') format('truetype');
+ font-weight: 400;
+}
+
+@font-face {
+ font-family: 'PirataOne';
+ src: url('/fonts/PirataOne-Gloomhaven.ttf') format('truetype');
+ font-weight: 400;
+}
+
:root {
+ --font-display: 'PirataOne', 'Georgia', serif;
+ --font-body: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
+
+ /* Layout scale (the reference app multiplies every bar dimension by the
+ user's bar scaling; the web default is 1). */
+ --bar-h: 40px;
+ --row-character-h: 60px;
+ --row-monster-h: 96px;
+ --list-w: 400px;
+
+ /* Element colours (top_bar.dart). */
+ --el-fire: #e2421e;
+ --el-ice: #55c8ef;
+ --el-air: #98b0b5;
+ --el-earth: #7ca82a;
+ --el-light: #eca60f;
+ --el-dark: #1f3283;
+
+ /* Turn highlight (Colors.tealAccent). */
+ --turn-current: #64ffda;
+
color-scheme: dark;
- --bg: #15181d;
- --fg: #e6e8ee;
+}
+
+/* --- Style themes ------------------------------------------------------ */
+
+/* Gloomhaven / Frosthaven: dark textured background. */
+:root[data-style='gloomhaven'],
+:root[data-style='frosthaven'] {
+ --bg: #000;
+ --bg-image: url('/images/bg/bg.png');
+ --bar-image: url('/images/psd/gloomhaven-bar.png');
+ --bar-bg: #000;
+ --bar-opacity: 0.4;
+ --fg: #fff;
+ --shadow: #000;
+ --menu-bg: #101418;
+ --dialog-bg: #1a1f26;
+ --row-border: #000;
+}
+
+:root[data-style='frosthaven'] {
+ --font-display: 'GermaniaOne', 'Georgia', serif;
+}
+
+/* Original: light background (the reference default when style=original). */
+:root[data-style='original'] {
+ --bg: #808080;
+ --bg-image: url('/images/bg/frosthaven-bg.png');
+ --bar-image: url('/images/psd/frosthaven-bar.png');
+ --bar-bg: transparent;
+ --bar-opacity: 1;
+ --fg: #000;
+ --shadow: #00000099;
+ --menu-bg: #f4f1ea;
+ --dialog-bg: #fffdf7;
+ --row-border: #00000044;
+ color-scheme: light;
}
* {
box-sizing: border-box;
}
+html,
+body,
+#app {
+ height: 100%;
+}
+
body {
margin: 0;
- background: var(--bg);
color: var(--fg);
- font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
+ font-family: var(--font-body);
+ background-color: var(--bg);
+ background-image: var(--bg-image);
+ background-size: cover;
+ background-position: center;
+}
+
+button {
+ font-family: inherit;
+ color: inherit;
+ background: none;
+ border: none;
+ cursor: pointer;
+}
+
+/* --- App frame ---------------------------------------------------------- */
+
+.app {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+}
+
+.app__list {
+ flex: 1;
+ overflow-y: auto;
+ display: flex;
+ justify-content: center;
+}
+
+/* --- Top bar ------------------------------------------------------------ */
+
+.topbar {
+ height: var(--bar-h);
+ display: flex;
+ align-items: stretch;
+ gap: 2px;
+ background-color: var(--bar-bg);
+ background-image: var(--bar-image);
+ background-size: auto 100%;
+ background-repeat: repeat-x;
+ color: #fff;
+ position: relative;
+ z-index: 2;
+}
+
+.topbar__menu {
+ width: var(--bar-h);
+ display: grid;
+ place-items: center;
+ font-size: 20px;
+}
+
+.topbar__title {
+ font-family: var(--font-display);
+ font-size: 22px;
+ line-height: 0.9;
+ text-shadow: 1px 1px 2px var(--shadow);
+ align-self: center;
+ margin-left: 4px;
+ user-select: none;
+}
+
+.topbar__elements {
+ margin-left: auto;
+ display: flex;
+}
+
+/* --- Element buttons ---------------------------------------------------- */
+
+.elbtn {
+ position: relative;
+ width: 36px;
+ align-self: center;
+ margin-right: 4px;
+}
+
+.elbtn__fill {
+ position: absolute;
+ bottom: 4px;
+ left: 2px;
+ width: 32px;
+ height: 0;
+ background: var(--el-color);
+ border-radius: 16px;
+ transition: height 0.35s cubic-bezier(0, 0, 0.2, 1);
+}
+
+.elbtn__fill.half {
+ height: 14px;
+ border-radius: 0 0 16px 16px;
+}
+
+.elbtn__fill.full {
+ height: 30px;
+ border-radius: 16px;
+}
+
+.elbtn__icon {
+ position: relative;
+ width: 24px;
+ height: 24px;
+ margin: 4px auto 0;
+ display: block;
+ object-fit: contain;
+ pointer-events: none;
+}
+
+/* --- Main list / rows --------------------------------------------------- */
+
+.list {
+ width: var(--list-w);
+ padding-bottom: 50vh;
+}
+
+.row {
+ position: relative;
+ width: 100%;
+ overflow: hidden;
+ box-shadow: 0 2px 8px #00000059;
+ margin-bottom: 2px;
+ user-select: none;
+}
+
+.row--character {
+ height: var(--row-character-h);
+ display: flex;
+ align-items: center;
+}
+
+.row--monster {
+ height: var(--row-monster-h);
+}
+
+.row--note {
+ min-height: 34px;
+}
+
+.row__bg {
+ position: absolute;
+ inset: 0;
+ z-index: 0;
+}
+
+.row__inner {
+ position: relative;
+ z-index: 1;
+ display: flex;
+ align-items: center;
+ width: 100%;
+}
+
+.row__art {
+ flex: 0 0 auto;
+ width: 56px;
+ height: 100%;
+ display: grid;
+ place-items: center;
+}
+
+.row__art img {
+ max-width: 48px;
+ max-height: 52px;
+ object-fit: contain;
+ filter: drop-shadow(1px 1px 1px #000c);
+}
+
+.row__name {
+ font-family: var(--font-display);
+ font-size: 17px;
+ text-shadow: 1px 1px 1px var(--shadow);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.row__hp {
+ font-size: 14px;
+ margin-left: 6px;
+ text-shadow: 1px 1px 1px var(--shadow);
+}
+
+.row__xp,
+.row__level {
+ position: absolute;
+ top: 6px;
+ right: 60px;
+ font-size: 13px;
+ text-shadow: 1px 1px 1px var(--shadow);
+}
+
+.row__level {
+ top: auto;
+ bottom: 6px;
+}
+
+.row__summon {
+ position: absolute;
+ top: 4px;
+ right: 4px;
+ font-size: 12px;
+ background: #0006;
+ border-radius: 4px;
+ padding: 1px 4px;
+}
+
+/* Initiative */
+.init {
+ flex: 0 0 auto;
+ width: 34px;
+ text-align: center;
+ font-family: var(--font-display);
+ font-size: 26px;
+ line-height: 1;
+ text-shadow: 1px 1px 1px var(--shadow);
+ margin-left: 4px;
+}
+
+.init__input {
+ width: 30px;
+ background: transparent;
+ border: none;
+ border-bottom: 2px solid #ffffff88;
+ color: #fff;
+ font-family: var(--font-display);
+ font-size: 24px;
+ text-align: center;
+ outline: none;
+ padding: 0;
+}
+
+.init__secret {
+ opacity: 0.85;
+}
+
+/* Turn state */
+.row--current .row__bg {
+ background: var(--turn-current);
+}
+
+.row--done,
+.row--dead {
+ filter: grayscale(1);
+ opacity: 0.75;
+}
+
+/* Claim / ownership chip */
+.chip {
+ position: absolute;
+ left: 4px;
+ bottom: 2px;
+ font-size: 11px;
+ padding: 1px 5px;
+ border-radius: 8px;
+ background: #000a;
+ color: #fff;
+ z-index: 2;
+}
+
+.chip--claim {
+ cursor: pointer;
+ background: #b58900;
+}
+
+/* Conditions */
+.conds {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 2px;
+ margin-left: 4px;
+ max-width: 200px;
+}
+
+.cond {
+ font-size: 11px;
+ padding: 0 4px;
+ border-radius: 3px;
+ background: #00000066;
+ color: #fff;
+ line-height: 16px;
+}
+
+.cond--chill {
+ background: #55c8efaa;
+}
+
+.cond--plague {
+ background: #7ca82a99;
+}
+
+/* Monster standee boxes */
+.monster__boxes {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 2px;
+ padding: 2px 4px 4px;
+}
+
+.monster__box {
+ width: 46px;
+ background: #00000055;
+ border-radius: 4px;
+ display: grid;
+ place-items: center;
+ position: relative;
+}
+
+.monster__box img {
+ width: 34px;
+ height: 34px;
+ object-fit: contain;
+}
+
+.monster__box--dead {
+ filter: grayscale(1);
+ opacity: 0.6;
+}
+
+.monster__box-hp {
+ position: absolute;
+ bottom: 1px;
+ right: 2px;
+ font-size: 10px;
+ color: #fff;
+ text-shadow: 1px 1px 1px #000;
+}
+
+/* Note row */
+.note__text {
+ padding: 4px 8px;
+ font-size: 13px;
+}
+
+.note__edit {
+ text-align: left;
+ padding: 0;
+ font: inherit;
+}
+
+/* --- Bottom bar --------------------------------------------------------- */
+
+.bottombar {
+ height: var(--bar-h);
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ background-color: var(--bar-bg);
+ background-image: var(--bar-image);
+ background-size: auto 100%;
+ background-repeat: repeat-x;
+ color: #fff;
+ position: relative;
+ z-index: 2;
+ box-shadow: 0 -4px 10px #00000040;
+}
+
+.drawbtn {
+ position: relative;
+ height: 100%;
+ min-width: 110px;
+ font-family: var(--font-display);
+ font-size: 18px;
+ text-shadow: 1px 1px 2px var(--shadow);
+}
+
+.drawbtn__round {
+ position: absolute;
+ bottom: 2px;
+ left: 44px;
+ font-size: 12px;
+ color: #ff0;
+ text-shadow: 1px 1px 1px var(--shadow);
+}
+
+.drawbtn--locked {
+ opacity: 0.5;
+}
+
+.levelwidget {
+ font-family: var(--font-display);
+ font-size: 15px;
+ text-align: center;
+ text-shadow: 1px 1px 2px var(--shadow);
+ padding: 0 8px;
+}
+
+.levelwidget__scenario {
+ max-width: 200px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.levelwidget__stats {
+ font-size: 13px;
+}
+
+/* --- Connection banner / toasts ---------------------------------------- */
+
+.banner {
+ position: fixed;
+ top: var(--bar-h);
+ left: 50%;
+ transform: translateX(-50%);
+ background: #7a1f1f;
+ color: #fff;
+ padding: 4px 14px;
+ border-radius: 0 0 6px 6px;
+ font-size: 13px;
+ z-index: 50;
+}
+
+.toast {
+ position: fixed;
+ bottom: calc(var(--bar-h) + 10px);
+ left: 50%;
+ transform: translateX(-50%);
+ background: #000c;
+ color: #fff;
+ padding: 8px 18px;
+ border-radius: 8px;
+ font-size: 16px;
+ max-width: 80vw;
+ z-index: 60;
+ text-align: center;
+ white-space: pre-line;
+}
+
+/* --- Drawer menu -------------------------------------------------------- */
+
+.drawer {
+ position: fixed;
+ top: 0;
+ left: 0;
+ bottom: 0;
+ width: 280px;
+ background: var(--menu-bg);
+ color: var(--fg);
+ z-index: 40;
+ overflow-y: auto;
+ box-shadow: 2px 0 12px #00000080;
+ transform: translateX(-100%);
+ transition: transform 0.2s ease;
+}
+
+.drawer--open {
+ transform: translateX(0);
+}
+
+.drawer__header {
+ height: 90px;
+ background: #1565c0;
+ background-image: url('/images/icon.png');
+ background-size: cover;
+ position: relative;
+}
+
+.drawer__item {
+ display: block;
+ width: 100%;
+ text-align: left;
+ padding: 10px 16px;
+ font-size: 15px;
+}
+
+.drawer__item:hover:not(:disabled) {
+ background: #ffffff1a;
+}
+
+.drawer__item:disabled {
+ opacity: 0.4;
+ cursor: default;
+}
+
+.drawer__divider {
+ border: none;
+ border-top: 1px solid #ffffff22;
+ margin: 6px 0;
+}
+
+/* --- Dialogs (menus) ---------------------------------------------------- */
+
+.dialog__overlay {
+ position: fixed;
+ inset: 0;
+ background: #00000088;
+ display: grid;
+ place-items: center;
+ z-index: 45;
+}
+
+.dialog__card {
+ background: var(--dialog-bg);
+ color: var(--fg);
+ border-radius: 8px;
+ max-width: 420px;
+ width: 92vw;
+ max-height: 80vh;
+ display: flex;
+ flex-direction: column;
+ box-shadow: 0 8px 30px #000c;
+}
+
+.dialog__title {
+ font-family: var(--font-display);
+ font-size: 20px;
+ padding: 12px 16px 8px;
+ text-align: center;
+}
+
+.dialog__body {
+ padding: 0 12px;
+ overflow-y: auto;
+ flex: 1;
+}
+
+.dialog__footer {
+ display: flex;
+ justify-content: flex-end;
+ padding: 8px 12px;
+}
+
+.dialog__close {
+ font-family: var(--font-display);
+ font-size: 18px;
+ padding: 4px 14px;
+}
+
+/* --- Menu content bits -------------------------------------------------- */
+
+.menulist {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+}
+
+.menulist__item {
+ display: block;
+ width: 100%;
+ text-align: left;
+ padding: 9px 8px;
+ font-size: 15px;
+ border-radius: 4px;
+}
+
+.menulist__item:hover {
+ background: #ffffff1a;
+}
+
+.menulist__item--added {
+ opacity: 0.5;
+}
+
+.menulist__item img {
+ vertical-align: middle;
+ margin-right: 8px;
+ height: 32px;
+ width: 32px;
+ object-fit: contain;
+}
+
+.search {
+ width: 100%;
+ padding: 8px;
+ font-size: 15px;
+ background: #00000022;
+ border: 1px solid #ffffff33;
+ border-radius: 4px;
+ color: inherit;
+ margin: 8px 0;
+}
+
+.campaignbtns {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ padding: 8px 4px;
+}
+
+.campaignbtns button {
+ padding: 6px 10px;
+ border: 1px solid #ffffff44;
+ border-radius: 6px;
+ font-size: 14px;
+}
+
+.campaignbtns button--active {
+ background: #1565c0;
+ border-color: #1565c0;
+ color: #fff;
+}
+
+.statrow {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ padding: 6px 4px;
+}
+
+.statrow__label {
+ flex: 1;
+ font-size: 14px;
+}
+
+.statrow__value {
+ font-family: var(--font-display);
+ font-size: 18px;
+ min-width: 44px;
+ text-align: center;
+}
+
+.stepbtn {
+ width: 34px;
+ height: 34px;
+ border-radius: 50%;
+ border: 1px solid #ffffff55;
+ font-size: 18px;
+ line-height: 1;
+}
+
+.stepbtn:disabled {
+ opacity: 0.3;
+}
+
+.condgrid {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 4px;
+ padding: 8px 4px;
+}
+
+.condgrid button {
+ padding: 8px 4px;
+ font-size: 12px;
+ border: 1px solid #ffffff33;
+ border-radius: 4px;
+}
+
+.condgrid button.condgrid--on {
+ background: #1565c0;
+ color: #fff;
+}
+
+.settingsrow {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 10px 4px;
+ gap: 12px;
+}
+
+.settingsrow label {
+ font-size: 14px;
+}
+
+select.search {
+ padding: 8px;
}
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);
+ }}
+ >
+

+
+
+ {#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}
+ {text}
+{/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 @@
+
+
+
+
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}
+
+ (open = false)}
+ >
+
+{/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 title}
+
{title}
+ {/if}
+
+ {@render children?.()}
+
+
+
+
+{/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));
+ }}
+ >
+

+
+
+
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 @@
+
+
+
+
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 @@
+
+
+
+
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}
+
+ {#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}
+ {/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}
+ {/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 @@
+
+
+
+
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}
+
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}
+
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}
+
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}
+ {: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 @@
+
+
+
+
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 @@
+
+
+
+
diff --git a/web/static/fonts/GermaniaOne-Regular.ttf b/web/static/fonts/GermaniaOne-Regular.ttf
new file mode 100644
index 0000000..7d6fa34
Binary files /dev/null and b/web/static/fonts/GermaniaOne-Regular.ttf differ
diff --git a/web/static/fonts/PirataOne-Gloomhaven.ttf b/web/static/fonts/PirataOne-Gloomhaven.ttf
new file mode 100644
index 0000000..f174c83
Binary files /dev/null and b/web/static/fonts/PirataOne-Gloomhaven.ttf differ
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 = {}) {
+ 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 | 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) {
+ // 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 {
+ 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) {
+ sockets.current.serverSend({
+ t: 'welcome',
+ v: 1,
+ session: 'sess1',
+ role,
+ index: 1,
+ description: '',
+ event: null,
+ state: makeState(),
+ seats
+ });
+ }
+
+ function seats(seats: Record) {
+ 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 {
+ 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 = {},
+ 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 = {}
+ ) {
+ 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([]);
+ });
+});
diff --git a/web/vite.config.ts b/web/vite.config.ts
index d50c975..772ea4c 100644
--- a/web/vite.config.ts
+++ b/web/vite.config.ts
@@ -3,6 +3,9 @@ import { fileURLToPath } from 'node:url';
import { defineConfig } from 'vitest/config';
export default defineConfig({
+ // Game fonts live in `static/` (copied to the build root, served by the
+ // Dart server at /fonts/ in production).
+ publicDir: 'static',
plugins: [svelte()],
resolve: {
alias: {
@@ -17,6 +20,11 @@ export default defineConfig({
target: 'ws://localhost:4567',
ws: true,
},
+ // The Dart server owns the game data and artwork; the client
+ // fetches them from /data/ and /images/ exactly as it will in
+ // production (where the Dart server serves the built app too).
+ '/data': 'http://localhost:4567',
+ '/images': 'http://localhost:4567',
},
},
test: {
--
cgit v1.3.1