@hadoku/game-ui 0.0.0-stage → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/LICENSE +21 -0
  2. package/dist/chrome/HeaderLinks.d.ts +16 -0
  3. package/dist/chrome/HeaderLinks.js +24 -0
  4. package/dist/components/ActionButton.d.ts +9 -0
  5. package/dist/components/ActionButton.js +49 -0
  6. package/dist/components/Avatar.d.ts +43 -0
  7. package/dist/components/Avatar.js +53 -0
  8. package/dist/components/ConnectionBanner.css +77 -0
  9. package/dist/components/ConnectionBanner.d.ts +33 -0
  10. package/dist/components/ConnectionBanner.js +33 -0
  11. package/dist/components/Modal.css +69 -0
  12. package/dist/components/Modal.d.ts +12 -0
  13. package/dist/components/Modal.js +31 -0
  14. package/dist/components/OverPage.d.ts +4 -0
  15. package/dist/components/OverPage.js +21 -0
  16. package/dist/components/Popover.css +58 -0
  17. package/dist/components/Popover.d.ts +20 -0
  18. package/dist/components/Popover.js +63 -0
  19. package/dist/components/RadioCards.css +178 -0
  20. package/dist/components/RadioCards.d.ts +33 -0
  21. package/dist/components/RadioCards.js +41 -0
  22. package/dist/components/StatusPill.d.ts +16 -0
  23. package/dist/components/StatusPill.js +17 -0
  24. package/dist/components/connection-state.d.ts +32 -0
  25. package/dist/components/connection-state.js +5 -0
  26. package/dist/dom.d.ts +17 -0
  27. package/dist/dom.js +57 -0
  28. package/dist/front/Gallery.d.ts +22 -0
  29. package/dist/front/Gallery.js +48 -0
  30. package/dist/front/PatchNotesCard.d.ts +1 -0
  31. package/dist/front/PatchNotesCard.js +59 -0
  32. package/dist/front/camera.d.ts +80 -0
  33. package/dist/front/camera.js +120 -0
  34. package/dist/front/countdown.d.ts +2 -0
  35. package/dist/front/countdown.js +16 -0
  36. package/dist/front/discordChat.d.ts +22 -0
  37. package/dist/front/discordChat.js +52 -0
  38. package/dist/front/gallery.d.ts +13 -0
  39. package/dist/front/gallery.js +32 -0
  40. package/dist/front/gate.d.ts +23 -0
  41. package/dist/front/gate.js +55 -0
  42. package/dist/front/icons.d.ts +43 -0
  43. package/dist/front/icons.js +99 -0
  44. package/dist/front/patchNotes.d.ts +37 -0
  45. package/dist/front/patchNotes.js +95 -0
  46. package/dist/front/polls.d.ts +24 -0
  47. package/dist/front/polls.js +95 -0
  48. package/dist/front/shape.d.ts +11 -0
  49. package/dist/front/shape.js +52 -0
  50. package/dist/http.d.ts +28 -0
  51. package/dist/http.js +83 -0
  52. package/dist/idle.d.ts +2 -0
  53. package/dist/idle.js +7 -0
  54. package/dist/lazy.d.ts +9 -0
  55. package/dist/lazy.js +63 -0
  56. package/dist/popover.d.ts +13 -0
  57. package/dist/popover.js +39 -0
  58. package/dist/registered.d.ts +5 -0
  59. package/dist/registered.js +6 -0
  60. package/dist/restart-notice.d.ts +20 -0
  61. package/dist/restart-notice.js +54 -0
  62. package/dist/room/RoomShell.d.ts +116 -0
  63. package/dist/room/RoomShell.js +222 -0
  64. package/dist/room/SessionPrompt.d.ts +12 -0
  65. package/dist/room/SessionPrompt.js +54 -0
  66. package/dist/room/avatar.d.ts +31 -0
  67. package/dist/room/avatar.js +60 -0
  68. package/dist/room/look.css +13 -0
  69. package/dist/room/look.d.ts +35 -0
  70. package/dist/room/look.js +189 -0
  71. package/dist/room/seatsOpen.d.ts +7 -0
  72. package/dist/room/seatsOpen.js +37 -0
  73. package/dist/room/session.d.ts +26 -0
  74. package/dist/room/session.js +108 -0
  75. package/dist/room/socket-options.d.ts +33 -0
  76. package/dist/room/socket-options.js +40 -0
  77. package/dist/room/tab-id.d.ts +6 -0
  78. package/dist/room/tab-id.js +90 -0
  79. package/dist/room/whoami.d.ts +15 -0
  80. package/dist/room/whoami.js +48 -0
  81. package/dist/rooms/bundle-slot.fixture.d.ts +11 -0
  82. package/dist/rooms/bundle-slot.fixture.js +21 -0
  83. package/dist/rooms/game-clients.d.ts +12 -0
  84. package/dist/rooms/game-clients.js +30 -0
  85. package/dist/rooms/game-setup.d.ts +63 -0
  86. package/dist/rooms/game-setup.js +33 -0
  87. package/dist/rooms/relay-channel.d.ts +29 -0
  88. package/dist/rooms/relay-channel.js +123 -0
  89. package/dist/rooms/screen/RoomShell.d.ts +33 -0
  90. package/dist/rooms/screen/RoomShell.js +7 -0
  91. package/dist/screens/route.d.ts +143 -0
  92. package/dist/screens/route.js +359 -0
  93. package/dist/settings/Settings.d.ts +39 -0
  94. package/dist/settings/Settings.js +131 -0
  95. package/dist/settings/TrimScreen.d.ts +2 -0
  96. package/dist/settings/TrimScreen.js +29 -0
  97. package/dist/settings/settings.css +116 -0
  98. package/dist/settings/siteTrim.d.ts +3 -0
  99. package/dist/settings/siteTrim.js +9 -0
  100. package/dist/settings/trim-screen.css +30 -0
  101. package/dist/sound/index.d.ts +12 -0
  102. package/dist/sound/index.js +34 -0
  103. package/dist/stale-build.d.ts +16 -0
  104. package/dist/stale-build.js +59 -0
  105. package/dist/top-layer.css +22 -0
  106. package/dist/topLayer.d.ts +19 -0
  107. package/dist/topLayer.js +44 -0
  108. package/dist/usage.d.ts +5 -0
  109. package/dist/usage.js +17 -0
  110. package/dist/visible.d.ts +14 -0
  111. package/dist/visible.js +35 -0
  112. package/package.json +42 -4
  113. package/README.md +0 -3
@@ -0,0 +1,123 @@
1
+ /*
2
+ * `MatchChannel` (`@wolffm/rooms-protocol`'s `game-bundle.d.ts`, the contract `BundleSlot.tsx`
3
+ * hands a bundle as `ctx.channel`) implemented over the relay socket
4
+ * (`packages/game-server/src/play/relay-socket.ts`): a socket.io connection on the SAME path and origin
5
+ * every other socket on this page already uses (`../room/socket-options.ts`), joined with
6
+ * `{ matchId: roomKey }`.
7
+ *
8
+ * Identity, the gate and the seal are the server's own `relay-socket.ts`'s job, exactly as the
9
+ * play socket's own `attachPlay` — nothing here carries a credential of its own, same as
10
+ * `play/live/match.ts`'s `socketIoMatchTransport`, whose connection shape this one mirrors.
11
+ *
12
+ * Ordering and at-most-once delivery are `runtimes/relay.ts`'s `RelaySession`'s own guarantees;
13
+ * this file adds nothing to either — it only opens the connection, joins, rejoins on every
14
+ * reconnect and after every match's end, and relays `relay:message` both ways. A watcher's own `send` is a silent no-op from
15
+ * out here too, but only because the SERVER drops it without an error — nothing here tracks
16
+ * whether this socket holds a seat.
17
+ */
18
+ import { io } from 'socket.io-client';
19
+ import { defaultSocketPath, socketOptions } from "../room/socket-options.js";
20
+ /**
21
+ * Mirrors `packages/game-server/src/play/relay-socket.ts`'s own `RELAY_EVENTS`. The client has no package
22
+ * of the server's to import these from (the server is not a dependency of the UI bundle), so the
23
+ * two literal event names are repeated here rather than re-derived — if they ever drift, every
24
+ * `relay:join` the server answers would simply go unrecognised at the join ack's own shape,
25
+ * which `relay-fixture.spec.ts` (e2e) exercises end to end.
26
+ */
27
+ const RELAY_EVENTS = { join: 'relay:join', message: 'relay:message', ended: 'relay:ended' };
28
+ function winnersOf(raw) {
29
+ return Array.isArray(raw) && raw.every((w) => typeof w === 'number') ? raw : null;
30
+ }
31
+ /**
32
+ * Opens one relay connection for `matchId` (a relay-runtime room's own id — there is no separate
33
+ * match id for this kind of room; see `rooms/BundleSlot.tsx`'s own doc) and returns it as a
34
+ * `MatchChannel`. `close()` disconnects the socket for good; call it once, on unmount.
35
+ */
36
+ export function openRelayChannel(matchId, options = {}) {
37
+ const path = options.path ?? defaultSocketPath();
38
+ const settings = socketOptions(path);
39
+ const socket = options.url === undefined ? io(settings) : io(options.url, settings);
40
+ const handlers = new Set();
41
+ const endedHandlers = new Set();
42
+ const resultHandlers = new Set();
43
+ let closed = false;
44
+ /** A result is shown: the next message sent or heard clears it. */
45
+ let showing = false;
46
+ const tellResult = (winners) => {
47
+ showing = winners !== null;
48
+ for (const handler of [...resultHandlers])
49
+ handler(winners);
50
+ };
51
+ const underway = () => {
52
+ if (showing)
53
+ tellResult(null);
54
+ };
55
+ const join = () => {
56
+ if (closed)
57
+ return;
58
+ // A match that ended before this join answers with its result (`relay-socket.ts`'s ack).
59
+ socket.emit(RELAY_EVENTS.join, { matchId }, (ack) => {
60
+ if (closed || ack?.ok !== true || ack.ended === undefined)
61
+ return;
62
+ tellResult(winnersOf(ack.ended.winners));
63
+ });
64
+ };
65
+ // A fresh connection joins once it opens; a later reconnect (a dropped network, a deploy) joins
66
+ // again on the new one — `relay-socket.ts` treats that exactly like a brand new peer.
67
+ socket.on('connect', join);
68
+ socket.on(RELAY_EVENTS.message, (msg) => {
69
+ if (closed)
70
+ return;
71
+ underway();
72
+ // Snapshotted first: a handler that subscribes or unsubscribes while running must not change
73
+ // who else receives THIS message — the same rule `createInMemoryMatchChannels` documents.
74
+ for (const handler of [...handlers])
75
+ handler(msg);
76
+ });
77
+ socket.on(RELAY_EVENTS.ended, (word) => {
78
+ if (closed)
79
+ return;
80
+ const winners = winnersOf(word?.winners);
81
+ // The room's next match is already registered under the same id: join it on this socket,
82
+ // before anyone is told, so nothing the bundle sends after hearing the end is lost.
83
+ join();
84
+ for (const handler of [...endedHandlers])
85
+ handler(winners);
86
+ tellResult(winners);
87
+ });
88
+ return {
89
+ onEnded(handler) {
90
+ if (closed)
91
+ return () => { };
92
+ endedHandlers.add(handler);
93
+ return () => endedHandlers.delete(handler);
94
+ },
95
+ onResult(handler) {
96
+ if (closed)
97
+ return () => { };
98
+ resultHandlers.add(handler);
99
+ return () => resultHandlers.delete(handler);
100
+ },
101
+ send(msg) {
102
+ if (closed)
103
+ return;
104
+ underway();
105
+ socket.emit(RELAY_EVENTS.message, msg);
106
+ },
107
+ on(handler) {
108
+ if (closed)
109
+ return () => { };
110
+ handlers.add(handler);
111
+ return () => handlers.delete(handler);
112
+ },
113
+ close() {
114
+ if (closed)
115
+ return;
116
+ closed = true;
117
+ handlers.clear();
118
+ endedHandlers.clear();
119
+ resultHandlers.clear();
120
+ socket.disconnect();
121
+ },
122
+ };
123
+ }
@@ -0,0 +1,33 @@
1
+ import type { ReactNode, RefCallback } from 'react';
2
+ export interface RoomShellProps {
3
+ shellRef: RefCallback<HTMLElement>;
4
+ /** `view.members.length` once the room record has one; the room screen's own `data-members`. */
5
+ dataMembers: number | undefined;
6
+ /** The room's own name, once either read has it. */
7
+ roomTitle: string | undefined;
8
+ /** The room answered with a refusal rather than useful data: nothing more to wait for, so the
9
+ * title falls back to "Room" instead of staying a skeleton. */
10
+ settled: boolean;
11
+ /** Close, Settings, and whatever the game type's own settings panel wants beside them. */
12
+ headerTools: ReactNode;
13
+ streamed: boolean;
14
+ /** A streamed room says so under its name; absent for a builtin one. */
15
+ streamedSubLine: ReactNode;
16
+ /** The room record has answered, success or failure. */
17
+ resolved: boolean;
18
+ /** Neither read has answered enough to draw anything real yet. */
19
+ pending: boolean;
20
+ /** What a loading room draws while `pending`. */
21
+ pendingBody: ReactNode;
22
+ /** A streamed room's own body — one container per seat, each a stream. */
23
+ streamedBody: ReactNode;
24
+ locked: 'need' | 'wrong' | 'rate-limited' | null;
25
+ password: string;
26
+ onPasswordChange: (value: string) => void;
27
+ onPasswordSubmit: () => void;
28
+ /** The table could not be read at all, and no password prompt is standing between here and it. */
29
+ roomMissingMessage: string | null;
30
+ /** The game type's own content: its setup, its game, in that order. */
31
+ children: ReactNode;
32
+ }
33
+ export declare function RoomShell({ shellRef, dataMembers, roomTitle, settled, headerTools, streamed, streamedSubLine, resolved, pending, pendingBody, streamedBody, locked, password, onPasswordChange, onPasswordSubmit, roomMissingMessage, children, }: RoomShellProps): import("react").JSX.Element;
@@ -0,0 +1,7 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ export function RoomShell({ shellRef, dataMembers, roomTitle, settled, headerTools, streamed, streamedSubLine, resolved, pending, pendingBody, streamedBody, locked, password, onPasswordChange, onPasswordSubmit, roomMissingMessage, children, }) {
3
+ return (_jsxs("div", { ref: shellRef, className: "shell shell--fit", "data-testid": "constructed", "data-members": dataMembers, children: [_jsxs("header", { className: "shell__head", children: [roomTitle !== undefined ? (_jsx("h1", { className: "shell__title", "data-testid": "room-name", children: roomTitle })) : settled ? (_jsx("h1", { className: "shell__title", children: "Room" })) : (_jsx("span", { className: "skeleton skeleton--title" })), _jsx("div", { className: "shell__tools", children: headerTools }), resolved && streamed && streamedSubLine] }), _jsxs("main", { className: "lobby lobby--room", "aria-busy": pending ? 'true' : undefined, children: [pending && pendingBody, streamed && streamedBody, !streamed && resolved && (_jsxs(_Fragment, { children: [locked !== null && (_jsxs("form", { className: "lobby__locked ct-panel", "data-testid": "room-locked", onSubmit: (e) => {
4
+ e.preventDefault();
5
+ onPasswordSubmit();
6
+ }, children: [_jsx("p", { role: "alert", children: locked === 'need' ? 'This room needs a password.' : locked === 'wrong' ? 'Wrong password.' : 'Too many attempts.' }), _jsx("label", { htmlFor: "room-password", children: "Password" }), _jsx("input", { id: "room-password", "data-testid": "room-password", type: "password", autoComplete: "off", value: password, onChange: (e) => onPasswordChange(e.target.value) }), _jsx("button", { type: "submit", "data-testid": "room-password-submit", disabled: locked === 'rate-limited', children: "Join" })] })), locked === null && roomMissingMessage !== null && (_jsx("p", { className: "ct-error", role: "alert", "data-testid": "room-missing", children: roomMissingMessage })), children] }))] })] }));
7
+ }
@@ -0,0 +1,143 @@
1
+ export declare const registerEmbedAddress: (value: (catalogue: string, view: string) => boolean) => void;
2
+ /** Where the app is. The single source of truth for what gets rendered. */
3
+ export type Route = {
4
+ kind: 'lobby';
5
+ }
6
+ /** LEGACY. `App.tsx` redirects it to `room`; nothing renders it. See the header. */
7
+ | {
8
+ kind: 'draft';
9
+ draftId: string;
10
+ } | {
11
+ kind: 'deck';
12
+ draftId: string;
13
+ } | {
14
+ kind: 'play';
15
+ } | {
16
+ kind: 'match';
17
+ matchId: string;
18
+ }
19
+ /** A recorded match, played back through the transport bar (wave 77 §B). */
20
+ | {
21
+ kind: 'replay';
22
+ matchId: string;
23
+ }
24
+ /** `tableId` is one table of the room's rounds (`screens/room/TablePage.tsx`); absent is the room itself. */
25
+ | {
26
+ kind: 'room';
27
+ roomId: string;
28
+ tableId?: string;
29
+ }
30
+ /** Friend tier and above: each screen renders nothing until the server's `/api/sounds` answers (`canView`). */
31
+ | {
32
+ kind: 'sounds';
33
+ } | {
34
+ kind: 'sounds-sandbox';
35
+ } | {
36
+ kind: 'sounds-music';
37
+ } | {
38
+ kind: 'ui';
39
+ }
40
+ /** The stats page (`stats/StatsPage.tsx`): no `tab` is its Leaderboard; `player`, a registry name, is that player's profile. */
41
+ | {
42
+ kind: 'stats';
43
+ tab?: 'profile' | 'tournaments';
44
+ player?: never;
45
+ } | {
46
+ kind: 'stats';
47
+ player: string;
48
+ tab?: never;
49
+ }
50
+ /** `draftId` opens that deck in the editor; absent is the list. */
51
+ | {
52
+ kind: 'decks';
53
+ draftId?: string;
54
+ } | {
55
+ kind: 'inventory';
56
+ }
57
+ /** A Rally pick option's page in Rally's frame: no header, no room (cardtable#24). */
58
+ | {
59
+ kind: 'rally-embed';
60
+ catalogue: string;
61
+ id: string;
62
+ view: string;
63
+ };
64
+ /**
65
+ * `#/room/r-1a2b3c` → `{ kind: 'room', roomId: 'r-1a2b3c' }`.
66
+ *
67
+ * Tolerant on the way in — a missing `#`, a missing leading `/`, a trailing
68
+ * `/`, and percent-encoding are all accepted — because this parses a string a
69
+ * person may have typed or an app may have mangled. Strict about the result:
70
+ * an empty draft id is not a draft route, it is the lobby.
71
+ */
72
+ export declare function parseRoute(hash: string): Route;
73
+ /** The inverse of `parseRoute`. Round-trips, and that is asserted. */
74
+ export declare function routeHash(route: Route): string;
75
+ /**
76
+ * Where a route lives under `base`, as `{ path, hash }`: a room's page at the path `room/<id>`,
77
+ * everything else at `base` with its hash, the lobby with none.
78
+ */
79
+ export declare function routeAddress(route: Route, base: string): {
80
+ path: string;
81
+ hash: string;
82
+ };
83
+ /**
84
+ * The link you send a friend: the route's own address, on the app's base.
85
+ *
86
+ * Built from `origin` + `base` rather than from `href`, because `href` carries
87
+ * whatever path and hash it is already on. Takes both as arguments so the
88
+ * `/cardtable/` prefix case is a test and not a deployment surprise.
89
+ */
90
+ export declare function routeUrl(route: Route, location: {
91
+ origin: string;
92
+ pathname: string;
93
+ }): string;
94
+ /** The route the address bar names under `base`: its hash when it has one, else its path. */
95
+ export declare function locationRoute(location: {
96
+ pathname: string;
97
+ hash: string;
98
+ }, base: string): Route;
99
+ /**
100
+ * The address this page should be on, or null when it already is.
101
+ *
102
+ * The server answers any path under the prefix with the app, so a page can be on a path that
103
+ * is not its route's (`/cardtable/sounds/music`), and a hash navigation keeps that stray path.
104
+ * A route named by the hash keeps its hash verbatim (a `#cam=` knob included) on the base, unless
105
+ * it is a room's page, which moves to its path. A route named only by the path moves to its own
106
+ * address. The query stays.
107
+ */
108
+ export declare function canonicalAddress(location: {
109
+ pathname: string;
110
+ search: string;
111
+ hash: string;
112
+ }, base: string): string | null;
113
+ /** Puts this page on its route's own address, before anything reads the route and after each move. */
114
+ export declare function canonicalizeAddress(): void;
115
+ /**
116
+ * Route in memory from here on, starting at `start`; the returned function
117
+ * gives the address bar back. The embed calls this before it renders.
118
+ */
119
+ export declare function routeInMemory(start: Route): () => void;
120
+ /** The page an invite link is built on: the app's own base, standalone or embedded (`routeUrl`). */
121
+ export declare function appLocation(): {
122
+ origin: string;
123
+ pathname: string;
124
+ };
125
+ /**
126
+ * Go somewhere.
127
+ *
128
+ * Writing the route's address with `history.pushState` is what puts it in the address bar and in
129
+ * the back/forward history; the browser dispatches nothing for that, so this tells the subscribers
130
+ * itself. Back and Forward arrive as `popstate` (and `hashchange`), which `moved` handles.
131
+ *
132
+ * `replace` swaps the current history entry instead of adding one, for a
133
+ * screen that forwards on its own: Back from where it forwarded to must not
134
+ * land on it again and be forwarded straight back. Arriving at the route this page already
135
+ * shows only corrects its address, and adds no entry.
136
+ */
137
+ export declare function navigate(route: Route, { replace }?: {
138
+ replace?: boolean;
139
+ }): void;
140
+ /** The route this page is on now, read once: what `useRoute` renders, for a caller outside React. */
141
+ export declare function currentRoute(): Route;
142
+ /** The current route, re-rendering the caller when it changes. */
143
+ export declare function useRoute(): Route;
@@ -0,0 +1,359 @@
1
+ /*
2
+ * Hash routing, and the two pure functions the app's links are built out of.
3
+ *
4
+ * ## Why the hash and not the path, except for a room
5
+ *
6
+ * The app is served under `hadoku.me/cardtable/` behind the member gate, by a
7
+ * server that SPA-falls-back every path (`apps/server/src/index.ts`). Either
8
+ * scheme would therefore *work*. The hash wins because it needs no server
9
+ * change at all, no base-prefix arithmetic in the client, and no router
10
+ * dependency: a `hashchange` listener plus a switch is the whole mechanism, and
11
+ * every route is the same document.
12
+ *
13
+ * A room's own page is the exception: its address is the PATH
14
+ * `/cardtable/room/<roomId>`. A link pasted into Discord unfurls from what the
15
+ * edge can see, and a browser never sends the hash (the operator, 2026-11-08:
16
+ * the address bar is the invite link). So the edge reads the room from the path
17
+ * and shows its preview (`games/magic/server/src/http/preview.ts`). `#/room/<id>` still
18
+ * opens it, and is moved to the path (`canonicalAddress`). Its tables, and every
19
+ * other route, stay in the hash.
20
+ *
21
+ * ## The routes
22
+ *
23
+ * `#/` the lobby — the list of rooms, and the only front door
24
+ * `room/<roomId>` a room, at that PATH: who is here, readiness, and the game it is for; once rounds start, the hub
25
+ * `#/room/<roomId>/table/<tableId>` one match of a room's rounds: its deck pick, Ready, sideboard and game
26
+ * `#/draft/<draftId>` LEGACY — redirects to `#/room/<draftId>`. See below.
27
+ * `#/deck/<draftId>` the deck built out of that draft's pool
28
+ * `#/play` constructed: pick a format and a deck, start a match
29
+ * `#/match/<matchId>` a match: the invite link for the other seat, and the board
30
+ * `#/replay/<matchId>` a recorded match, through the transport bar (wave 77 §B) — no invite, nothing to join
31
+ * `#/sounds` the sound builder (wave 50) — friend tier and above; editing is admin-only
32
+ * `#/sounds/sandbox` the sound sandbox — scenarios played through the mixer, friend tier and above
33
+ * `#/sounds/music` the match-music review — compare, pick and submit, friend tier and above
34
+ * `#/ui` the trim composer (`settings/TrimScreen.tsx`) — admin only, linked from nowhere
35
+ * `#/stats` the stats page's Leaderboard: the rankings, winning decks, colours, everyone's matches
36
+ * `#/profile` the stats page's Your profile: your rating, unfinished games, matches, decks, colours
37
+ * `#/stats/<name>` another player's profile, by registry name
38
+ * `#/tournaments` the stats page's Tournaments tab: every past pod's standings
39
+ * `#/decks` your decks: every draft you finished
40
+ * `#/decks/<draftId>` that deck in the editor, outside any game
41
+ * `#/inventory` imported cubes: refresh, delete, import (AF305 §B) — shortlist cubes aren't managed here
42
+ * `#/embed/<catalogue>/<id>/<view>` one Rally pick option's page, chromeless, for Rally's frame (`rally/RallyEmbed.tsx`, cardtable#24)
43
+ *
44
+ * An unrecognised hash is the lobby. That is deliberate: a mistyped invite link
45
+ * lands on the room list, which offers a way in, rather than on an error page
46
+ * that offers nothing.
47
+ *
48
+ * ## `#/draft/<id>` is a legacy alias, and that is all it is
49
+ *
50
+ * Wave 23 made a draft a room: the room list is the one front door, the server
51
+ * mints the id, and `#/room/<id>` is what an invite link says. The client used
52
+ * to mint `adjective-noun-suffix` pod ids here and hand them out in links, so
53
+ * those links exist in people's chat windows. `parseRoute` and `routeHash` keep
54
+ * the draft route so `App.tsx` can redirect it to `#/room/<draftId>` — the draft
55
+ * id and the room id are now one id, so the redirect is the whole translation.
56
+ * A link to a pod id that was never a room lands on the room screen's own "no
57
+ * such room", which is the honest answer. `DeckScreen`'s "back to the pod" goes
58
+ * through the same alias for the same reason.
59
+ *
60
+ * Nothing mints an id here any more, and nothing parses a pasted link: the join
61
+ * box those served is gone with the pod section (`LobbyScreen.tsx`).
62
+ *
63
+ * ## Everything here that can be pure, is
64
+ *
65
+ * `parseRoute`, `routeHash`, `routeAddress`, `routeUrl` and `canonicalAddress`
66
+ * take their inputs as arguments and touch no globals, so the interesting behaviour — what a mangled hash means,
67
+ * what an invite URL looks like under the `/cardtable/` prefix — is testable
68
+ * without a DOM. Only `navigate`, `subscribeToHash`, `currentHash` and
69
+ * `appLocation` know `window` exists — and `routeInMemory` is how the embed
70
+ * (D21) tells them the address bar is not the app's.
71
+ */
72
+ import { useMemo, useSyncExternalStore } from 'react';
73
+ import { registered } from "../registered.js";
74
+ /** Whether `#/embed/<catalogue>/<id>/<view>` is one of the game's pages; any other is the lobby. */
75
+ const embedAddress = registered('embed address');
76
+ export const registerEmbedAddress = embedAddress.set;
77
+ /**
78
+ * `#/room/r-1a2b3c` → `{ kind: 'room', roomId: 'r-1a2b3c' }`.
79
+ *
80
+ * Tolerant on the way in — a missing `#`, a missing leading `/`, a trailing
81
+ * `/`, and percent-encoding are all accepted — because this parses a string a
82
+ * person may have typed or an app may have mangled. Strict about the result:
83
+ * an empty draft id is not a draft route, it is the lobby.
84
+ */
85
+ export function parseRoute(hash) {
86
+ const path = hash.replace(/^#/, '').replace(/^\/+/, '').replace(/\/+$/, '');
87
+ if (path === '')
88
+ return { kind: 'lobby' };
89
+ if (path === 'play')
90
+ return { kind: 'play' };
91
+ if (path === 'sounds')
92
+ return { kind: 'sounds' };
93
+ if (path === 'sounds/sandbox')
94
+ return { kind: 'sounds-sandbox' };
95
+ if (path === 'sounds/music')
96
+ return { kind: 'sounds-music' };
97
+ if (path === 'ui')
98
+ return { kind: 'ui' };
99
+ if (path === 'stats')
100
+ return { kind: 'stats' };
101
+ if (path === 'profile')
102
+ return { kind: 'stats', tab: 'profile' };
103
+ if (path === 'tournaments')
104
+ return { kind: 'stats', tab: 'tournaments' };
105
+ if (path === 'decks')
106
+ return { kind: 'decks' };
107
+ if (path === 'inventory')
108
+ return { kind: 'inventory' };
109
+ const parts = path.split('/');
110
+ if (parts.length === 4 && parts[0] === 'embed') {
111
+ const [catalogue, view] = [parts[1], parts[3]];
112
+ const id = decodeSegment(parts[2]);
113
+ return embedAddress.get()(catalogue, view) && id !== '' ? { kind: 'rally-embed', catalogue, id, view } : { kind: 'lobby' };
114
+ }
115
+ if (parts.length === 4 && parts[0] === 'room' && parts[2] === 'table') {
116
+ const [roomId, tableId] = [decodeSegment(parts[1]), decodeSegment(parts[3])];
117
+ return roomId === '' ? { kind: 'lobby' } : tableId === '' ? { kind: 'room', roomId } : { kind: 'room', roomId, tableId };
118
+ }
119
+ if (parts.length !== 2)
120
+ return { kind: 'lobby' };
121
+ const [head, raw] = parts;
122
+ const id = decodeSegment(raw);
123
+ if (id === '')
124
+ return { kind: 'lobby' };
125
+ switch (head) {
126
+ case 'draft':
127
+ return { kind: 'draft', draftId: id };
128
+ case 'deck':
129
+ return { kind: 'deck', draftId: id };
130
+ case 'match':
131
+ return { kind: 'match', matchId: id };
132
+ case 'replay':
133
+ return { kind: 'replay', matchId: id };
134
+ case 'room':
135
+ return { kind: 'room', roomId: id };
136
+ case 'stats':
137
+ return { kind: 'stats', player: id };
138
+ case 'decks':
139
+ return { kind: 'decks', draftId: id };
140
+ default:
141
+ return { kind: 'lobby' };
142
+ }
143
+ }
144
+ /**
145
+ * A malformed percent-escape throws out of `decodeURIComponent`. A pasted link
146
+ * is exactly where one comes from, so the raw segment is the answer rather than
147
+ * a crash.
148
+ */
149
+ function decodeSegment(raw) {
150
+ try {
151
+ return decodeURIComponent(raw).trim();
152
+ }
153
+ catch {
154
+ return raw.trim();
155
+ }
156
+ }
157
+ /** The inverse of `parseRoute`. Round-trips, and that is asserted. */
158
+ export function routeHash(route) {
159
+ switch (route.kind) {
160
+ case 'lobby':
161
+ return '#/';
162
+ case 'sounds':
163
+ return '#/sounds';
164
+ case 'sounds-sandbox':
165
+ return '#/sounds/sandbox';
166
+ case 'sounds-music':
167
+ return '#/sounds/music';
168
+ case 'ui':
169
+ return '#/ui';
170
+ case 'draft':
171
+ return `#/draft/${encodeURIComponent(route.draftId)}`;
172
+ case 'deck':
173
+ return `#/deck/${encodeURIComponent(route.draftId)}`;
174
+ case 'play':
175
+ return '#/play';
176
+ case 'match':
177
+ return `#/match/${encodeURIComponent(route.matchId)}`;
178
+ case 'replay':
179
+ return `#/replay/${encodeURIComponent(route.matchId)}`;
180
+ case 'room':
181
+ return `#/room/${encodeURIComponent(route.roomId)}${route.tableId === undefined ? '' : `/table/${encodeURIComponent(route.tableId)}`}`;
182
+ case 'stats':
183
+ if (route.player !== undefined)
184
+ return `#/stats/${encodeURIComponent(route.player)}`;
185
+ return route.tab === undefined ? '#/stats' : `#/${route.tab}`;
186
+ case 'decks':
187
+ return route.draftId === undefined ? '#/decks' : `#/decks/${encodeURIComponent(route.draftId)}`;
188
+ case 'inventory':
189
+ return '#/inventory';
190
+ case 'rally-embed':
191
+ return `#/embed/${route.catalogue}/${encodeURIComponent(route.id)}/${route.view}`;
192
+ }
193
+ }
194
+ /** A room's own page, not one of its tables: the one route whose address is a path. */
195
+ function roomPage(route) {
196
+ return route.kind === 'room' && route.tableId === undefined ? route.roomId : null;
197
+ }
198
+ /** Whether a hash names anything: `#` and `#/` are the same as none. */
199
+ function hasHash(hash) {
200
+ return hash.replace(/^#\/?/, '') !== '';
201
+ }
202
+ /**
203
+ * Where a route lives under `base`, as `{ path, hash }`: a room's page at the path `room/<id>`,
204
+ * everything else at `base` with its hash, the lobby with none.
205
+ */
206
+ export function routeAddress(route, base) {
207
+ const room = roomPage(route);
208
+ if (room !== null)
209
+ return { path: `${base}room/${encodeURIComponent(room)}`, hash: '' };
210
+ return { path: base, hash: route.kind === 'lobby' ? '' : routeHash(route) };
211
+ }
212
+ /**
213
+ * The link you send a friend: the route's own address, on the app's base.
214
+ *
215
+ * Built from `origin` + `base` rather than from `href`, because `href` carries
216
+ * whatever path and hash it is already on. Takes both as arguments so the
217
+ * `/cardtable/` prefix case is a test and not a deployment surprise.
218
+ */
219
+ export function routeUrl(route, location) {
220
+ const { path, hash } = routeAddress(route, location.pathname);
221
+ return `${location.origin}${path}${hash}`;
222
+ }
223
+ /** The route the address bar names under `base`: its hash when it has one, else its path. */
224
+ export function locationRoute(location, base) {
225
+ if (hasHash(location.hash))
226
+ return parseRoute(location.hash);
227
+ return parseRoute(location.pathname.startsWith(base) ? location.pathname.slice(base.length) : '');
228
+ }
229
+ /**
230
+ * The address this page should be on, or null when it already is.
231
+ *
232
+ * The server answers any path under the prefix with the app, so a page can be on a path that
233
+ * is not its route's (`/cardtable/sounds/music`), and a hash navigation keeps that stray path.
234
+ * A route named by the hash keeps its hash verbatim (a `#cam=` knob included) on the base, unless
235
+ * it is a room's page, which moves to its path. A route named only by the path moves to its own
236
+ * address. The query stays.
237
+ */
238
+ export function canonicalAddress(location, base) {
239
+ const route = locationRoute(location, base);
240
+ const want = roomPage(route) !== null || !hasHash(location.hash) ? routeAddress(route, base) : { path: base, hash: location.hash };
241
+ const next = `${want.path}${location.search}${want.hash}`;
242
+ return next === `${location.pathname}${location.search}${location.hash}` ? null : next;
243
+ }
244
+ /** Puts this page on its route's own address, before anything reads the route and after each move. */
245
+ export function canonicalizeAddress() {
246
+ const next = canonicalAddress(globalThis.location, import.meta.env.BASE_URL);
247
+ if (next !== null)
248
+ globalThis.history.replaceState(globalThis.history.state, '', next);
249
+ }
250
+ /* ── the browser half ────────────────────────────────────────────────── */
251
+ const listeners = new Set();
252
+ /**
253
+ * The route when the app does not own the address bar, or null when it does.
254
+ *
255
+ * Embedded in a watchparty room (D21) the URL is watchparty's: a hash written
256
+ * there would rewrite THEIR page's route and land in their history. So the
257
+ * embed holds its route here instead, and `navigate` / `useRoute` read and
258
+ * write this rather than `location.hash`. One per page, like everything else
259
+ * the chrome owns ("exactly one chrome per page", `chrome/AppChrome.tsx`).
260
+ */
261
+ let inMemory = null;
262
+ function notify() {
263
+ for (const listener of [...listeners])
264
+ listener();
265
+ }
266
+ /** The address bar moved on its own (Back, Forward, a `#` link): put it on its route's address, then re-read it. */
267
+ function moved() {
268
+ canonicalizeAddress();
269
+ notify();
270
+ }
271
+ /** Whether `hashchange` and `popstate` are subscribed — only ever while the address bar is ours. */
272
+ let listening = false;
273
+ function syncHashListener() {
274
+ const want = inMemory === null && listeners.size > 0;
275
+ if (want === listening)
276
+ return;
277
+ listening = want;
278
+ for (const event of ['hashchange', 'popstate']) {
279
+ if (want)
280
+ globalThis.addEventListener(event, moved);
281
+ else
282
+ globalThis.removeEventListener(event, moved);
283
+ }
284
+ }
285
+ function subscribeToHash(listener) {
286
+ listeners.add(listener);
287
+ syncHashListener();
288
+ return () => {
289
+ listeners.delete(listener);
290
+ syncHashListener();
291
+ };
292
+ }
293
+ /** The current route as its hash: one string, so the snapshot compares by value. */
294
+ function currentHash() {
295
+ if (inMemory !== null)
296
+ return inMemory.hash;
297
+ const location = globalThis.location;
298
+ if (location === undefined)
299
+ return '';
300
+ return routeHash(locationRoute(location, import.meta.env.BASE_URL));
301
+ }
302
+ /**
303
+ * Route in memory from here on, starting at `start`; the returned function
304
+ * gives the address bar back. The embed calls this before it renders.
305
+ */
306
+ export function routeInMemory(start) {
307
+ const mine = { hash: routeHash(start) };
308
+ inMemory = mine;
309
+ syncHashListener();
310
+ notify();
311
+ return () => {
312
+ if (inMemory !== mine)
313
+ return;
314
+ inMemory = null;
315
+ syncHashListener();
316
+ };
317
+ }
318
+ /** The page an invite link is built on: the app's own base, standalone or embedded (`routeUrl`). */
319
+ export function appLocation() {
320
+ return { origin: globalThis.location?.origin ?? '', pathname: import.meta.env?.BASE_URL ?? '/' };
321
+ }
322
+ /**
323
+ * Go somewhere.
324
+ *
325
+ * Writing the route's address with `history.pushState` is what puts it in the address bar and in
326
+ * the back/forward history; the browser dispatches nothing for that, so this tells the subscribers
327
+ * itself. Back and Forward arrive as `popstate` (and `hashchange`), which `moved` handles.
328
+ *
329
+ * `replace` swaps the current history entry instead of adding one, for a
330
+ * screen that forwards on its own: Back from where it forwarded to must not
331
+ * land on it again and be forwarded straight back. Arriving at the route this page already
332
+ * shows only corrects its address, and adds no entry.
333
+ */
334
+ export function navigate(route, { replace = false } = {}) {
335
+ if (inMemory !== null)
336
+ inMemory.hash = routeHash(route);
337
+ else {
338
+ const location = globalThis.location;
339
+ const { path, hash } = routeAddress(route, import.meta.env.BASE_URL);
340
+ const next = `${path}${location.search}${hash}`;
341
+ if (next !== `${location.pathname}${location.search}${location.hash}`) {
342
+ const same = currentHash() === routeHash(route);
343
+ if (replace || same)
344
+ globalThis.history.replaceState(globalThis.history.state, '', next);
345
+ else
346
+ globalThis.history.pushState(null, '', next);
347
+ }
348
+ }
349
+ notify();
350
+ }
351
+ /** The route this page is on now, read once: what `useRoute` renders, for a caller outside React. */
352
+ export function currentRoute() {
353
+ return parseRoute(currentHash());
354
+ }
355
+ /** The current route, re-rendering the caller when it changes. */
356
+ export function useRoute() {
357
+ const hash = useSyncExternalStore(subscribeToHash, currentHash, () => '');
358
+ return useMemo(() => parseRoute(hash), [hash]);
359
+ }