summaryrefslogtreecommitdiff
path: root/web/src/lib/state/session.ts
diff options
context:
space:
mode:
Diffstat (limited to 'web/src/lib/state/session.ts')
-rw-r--r--web/src/lib/state/session.ts172
1 files changed, 172 insertions, 0 deletions
diff --git a/web/src/lib/state/session.ts b/web/src/lib/state/session.ts
new file mode 100644
index 0000000..c8820d4
--- /dev/null
+++ b/web/src/lib/state/session.ts
@@ -0,0 +1,172 @@
+/**
+ * The game session as seen by one browser: the live connection plus the
+ * derived Svelte stores the UI reads from.
+ *
+ * The server is the single source of truth (PLAN.md section 3.1): this
+ * client holds only the last full state snapshot, the seat table, its own
+ * session identity, and connection status. Every mutation is a command sent
+ * to the server; the resulting `update` replaces the local snapshot.
+ */
+
+import { derived, writable, get, type Readable, type Writable } from 'svelte/store';
+
+import {
+ GameConnection,
+ type ConnectionOptions,
+ type ConnectionStatus
+} from '../protocol/connection';
+import type {
+ GameState,
+ Role,
+ ServerMessage
+} from '../protocol/types';
+
+export interface SessionInfo {
+ id: string;
+ role: Role;
+}
+
+export interface ProtocolError {
+ code: string;
+ message: string;
+}
+
+export class GameSession {
+ readonly state: Writable<GameState | null> = writable<GameState | null>(null);
+ readonly seats: Writable<Record<string, string | null>> = writable({});
+ readonly session: Writable<SessionInfo | null> = writable<SessionInfo | null>(null);
+ readonly status: Writable<ConnectionStatus> = writable('connecting');
+ readonly index: Writable<number> = writable(-1);
+ readonly description: Writable<string | null> = writable<string | null>(null);
+ readonly lastError: Writable<ProtocolError | null> =
+ writable<ProtocolError | null>(null);
+
+ /**
+ * Reactive player/spectator flag derived from the live seat table (see
+ * `isSpectator()`). The UI reads this as a store — it flips the moment
+ * a claim is granted, without waiting for a new `welcome`.
+ */
+ readonly player: Readable<boolean> = derived(
+ [this.session, this.seats],
+ ([session, seats]) => {
+ if (!session) return false;
+ return Object.values(seats).some((owner) => owner === session.id);
+ }
+ );
+
+ private readonly connection: GameConnection;
+
+ constructor(options: ConnectionOptions = {}) {
+ this.connection = new GameConnection(options);
+ this.connection.onStatus = (s) => this.status.set(s);
+ this.connection.onMessage = (m) => this.handle(m);
+ this.connection.onError = (e) =>
+ this.lastError.set({ code: e.code, message: e.message });
+ }
+
+ /** The underlying connection (for advanced control / resync). */
+ get conn(): GameConnection {
+ return this.connection;
+ }
+
+ private handle(message: ServerMessage): void {
+ switch (message.t) {
+ case 'welcome':
+ this.session.set({ id: message.session, role: message.role });
+ this.state.set(message.state);
+ this.seats.set(message.seats);
+ this.index.set(message.index);
+ this.description.set(message.description);
+ break;
+ case 'update':
+ this.state.set(message.state);
+ this.index.set(message.index);
+ this.description.set(message.description);
+ break;
+ case 'seats':
+ this.seats.set(message.seats);
+ break;
+ case 'error':
+ this.lastError.set({ code: message.code, message: message.message });
+ break;
+ case 'pong':
+ // keepalive ack — nothing to surface
+ break;
+ }
+ }
+
+ connect(): void {
+ this.connection.connect();
+ }
+
+ disconnect(): void {
+ this.connection.disconnect();
+ }
+
+ // --- ownership ------------------------------------------------------------
+
+ /** True when [characterId] is owned by this session. */
+ owns(characterId: string): boolean {
+ const s = get(this.session);
+ const seats = get(this.seats);
+ return !!s && seats[characterId] === s.id;
+ }
+
+ /** This session's role (null before the first welcome). */
+ role(): Role | null {
+ return get(this.session)?.role ?? null;
+ }
+
+ /** The character ids this session owns. */
+ ownedCharacterIds(): string[] {
+ const s = get(this.session);
+ if (!s) return [];
+ const seats = get(this.seats);
+ return Object.keys(seats).filter((id) => seats[id] === s.id);
+ }
+
+ /**
+ * A spectator has claimed no character. Derived from the live seat table
+ * (not the `welcome` role, which is only computed at handshake) so that
+ * the moment a claim is granted the UI switches to player controls —
+ * the `seats` broadcast carries the truth.
+ */
+ isSpectator(): boolean {
+ return this.ownedCharacterIds().length === 0;
+ }
+
+ // --- commands -------------------------------------------------------------
+
+ command(name: string, args: Record<string, unknown> = {}): void {
+ this.connection.sendCmd(name, args);
+ }
+
+ claim(characterId: string): void {
+ this.connection.claim(characterId);
+ }
+
+ undo(): void {
+ this.connection.undo();
+ }
+
+ redo(): void {
+ this.connection.redo();
+ }
+
+ /** Clear a surfaced protocol error (call after toasting it). */
+ clearError(): void {
+ this.lastError.set(null);
+ }
+}
+
+/**
+ * Convenience: the set of character ids owned by a given session within a
+ * seat table. Exported for unit testing.
+ */
+export function ownedIds(
+ sessionId: string | null,
+ seats: Record<string, string | null>
+): string[] {
+ if (!sessionId) return [];
+ return Object.keys(seats).filter((id) => seats[id] === sessionId);
+}