@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,24 @@
1
+ import { type AttachedForm } from '@wolffm/platform-wire/events';
2
+ import { type Fetch } from '../http.js';
3
+ export type Poll = AttachedForm;
4
+ export declare function pollsClient(fetchImpl?: Fetch): {
5
+ /** The open forms; one the page cannot read is skipped, never the whole list. A refused read throws. */
6
+ list(): Promise<Poll[]>;
7
+ };
8
+ /** Soonest to close first; a form with no closing time last. */
9
+ export declare function openPolls(polls: readonly Poll[]): Poll[];
10
+ type PollsClient = Pick<ReturnType<typeof pollsClient>, 'list'>;
11
+ /** Tests swap the client (and reset the store) here. */
12
+ export declare function setPollsClient(next: PollsClient): void;
13
+ /** Tell `listener` the polls now and on every change; answers the unsubscribe. */
14
+ export declare function subscribePolls(listener: (polls: Poll[] | null) => void): () => void;
15
+ /** Re-read the polls and tell every reader. A failed read keeps what they have; a read overtaken by a newer one changes nothing. */
16
+ export declare function refreshPolls(): Promise<void>;
17
+ /**
18
+ * A form just attached (Create event's Load form, or Rally's return trip): it shows at once, and
19
+ * the list is re-read behind it, never left to the next tick.
20
+ */
21
+ export declare function pollAttached(form: Poll): Promise<void>;
22
+ /** The open polls, kept fresh while mounted and shown (`../visible.ts`): `null` until the first read answers. */
23
+ export declare function usePolls(): Poll[] | null;
24
+ export {};
@@ -0,0 +1,95 @@
1
+ /*
2
+ * The Upcoming card's Polls page: the open Rally forms attached to events (`GET /api/events/forms`,
3
+ * `games/magic/server/src/http/events.ts`), each Rally's own summary of it plus who attached it
4
+ * (`AttachedForm`). Its Open button goes to the form on Rally.
5
+ */
6
+ import { useEffect, useState } from 'react';
7
+ import { AttachedFormSchema } from '@wolffm/platform-wire/events';
8
+ import { apiUrl, bodyOf, getJson, isRecord, serverMessage } from "../http.js";
9
+ import { rereadWhileVisible } from "../visible.js";
10
+ const defaultFetch = (input, init) => fetch(input, init);
11
+ export function pollsClient(fetchImpl = defaultFetch) {
12
+ return {
13
+ /** The open forms; one the page cannot read is skipped, never the whole list. A refused read throws. */
14
+ async list() {
15
+ const res = await getJson(apiUrl('events/forms'), fetchImpl);
16
+ const body = await bodyOf(res);
17
+ if (!res.ok)
18
+ throw new Error(serverMessage(body, res.status));
19
+ const forms = isRecord(body) && Array.isArray(body.forms) ? body.forms : [];
20
+ return forms.flatMap((f) => {
21
+ const poll = AttachedFormSchema.safeParse(f);
22
+ return poll.success && poll.data.status === 'open' ? [poll.data] : [];
23
+ });
24
+ },
25
+ };
26
+ }
27
+ /** Soonest to close first; a form with no closing time last. */
28
+ export function openPolls(polls) {
29
+ const closes = (p) => (p.closesAt === null ? Infinity : Date.parse(p.closesAt));
30
+ return [...polls].sort((a, b) => closes(a) - closes(b));
31
+ }
32
+ /** `null` until the first read answers; the last good list after a failed read. */
33
+ let current = null;
34
+ const listeners = new Set();
35
+ let client = pollsClient();
36
+ /** Bumped by every read and every attach: only the newest read may set the list, so a read begun before an attach never drops its form. */
37
+ let generation = 0;
38
+ /** Tests swap the client (and reset the store) here. */
39
+ export function setPollsClient(next) {
40
+ client = next;
41
+ current = null;
42
+ generation += 1;
43
+ }
44
+ function publish(polls) {
45
+ current = polls;
46
+ for (const listener of listeners)
47
+ listener(current);
48
+ }
49
+ /** Tell `listener` the polls now and on every change; answers the unsubscribe. */
50
+ export function subscribePolls(listener) {
51
+ listeners.add(listener);
52
+ listener(current);
53
+ return () => listeners.delete(listener);
54
+ }
55
+ /** Re-read the polls and tell every reader. A failed read keeps what they have; a read overtaken by a newer one changes nothing. */
56
+ export async function refreshPolls() {
57
+ const mine = ++generation;
58
+ let next;
59
+ try {
60
+ next = openPolls(await client.list());
61
+ }
62
+ catch {
63
+ // Not reachable for a moment: the page keeps what it showed, or says there are none.
64
+ if (current !== null || mine !== generation)
65
+ return;
66
+ next = [];
67
+ }
68
+ if (mine === generation)
69
+ publish(next);
70
+ }
71
+ /**
72
+ * A form just attached (Create event's Load form, or Rally's return trip): it shows at once, and
73
+ * the list is re-read behind it, never left to the next tick.
74
+ */
75
+ export async function pollAttached(form) {
76
+ generation += 1;
77
+ if (form.status === 'open')
78
+ publish(openPolls([...(current ?? []).filter((p) => p.id !== form.id), form]));
79
+ await refreshPolls();
80
+ }
81
+ /** How often a mounted reader re-reads the polls, so another organizer's form shows without a reload (as `./events.ts` does). */
82
+ const REFRESH_MS = 60_000;
83
+ /** The open polls, kept fresh while mounted and shown (`../visible.ts`): `null` until the first read answers. */
84
+ export function usePolls() {
85
+ const [polls, setPolls] = useState(current);
86
+ useEffect(() => {
87
+ const stop = subscribePolls(setPolls);
88
+ const stopReread = rereadWhileVisible(() => void refreshPolls(), REFRESH_MS);
89
+ return () => {
90
+ stop();
91
+ stopReread();
92
+ };
93
+ }, []);
94
+ return polls;
95
+ }
@@ -0,0 +1,11 @@
1
+ export interface FrontShape {
2
+ live: boolean;
3
+ rooms: number;
4
+ events: number;
5
+ }
6
+ /** The most room placeholders drawn: enough to fill any window; the rest of a long list is below the fold. */
7
+ export declare const MAX_ROOM_GHOSTS = 12;
8
+ export declare const FIRST_VISIT: FrontShape;
9
+ export declare function parseFrontShape(raw: string | null): FrontShape;
10
+ export declare function loadFrontShape(): FrontShape;
11
+ export declare function saveFrontShape(shape: FrontShape): void;
@@ -0,0 +1,52 @@
1
+ /*
2
+ * What the front page looked like last time, so its skeleton can stand in the same boxes before any
3
+ * read has answered: whether the live slot was there (it decides how wide every banner card is), how
4
+ * many rooms the list drew and how many events Upcoming did. Remembered per browser, written each
5
+ * time the page has shown itself. A first visit assumes the live slot is there, as it is whenever a
6
+ * replay is kept.
7
+ */
8
+ /** The most room placeholders drawn: enough to fill any window; the rest of a long list is below the fold. */
9
+ export const MAX_ROOM_GHOSTS = 12;
10
+ const STORAGE_KEY = 'cardtable:front-shape';
11
+ export const FIRST_VISIT = { live: true, rooms: 6, events: 3 };
12
+ const count = (n, max, fallback) => (typeof n === 'number' && Number.isInteger(n) && n >= 0 ? Math.min(n, max) : fallback);
13
+ export function parseFrontShape(raw) {
14
+ if (raw === null)
15
+ return FIRST_VISIT;
16
+ let body;
17
+ try {
18
+ body = JSON.parse(raw);
19
+ }
20
+ catch {
21
+ // Not ours, or from an older page: the first visit's shape.
22
+ return FIRST_VISIT;
23
+ }
24
+ if (typeof body !== 'object' || body === null)
25
+ return FIRST_VISIT;
26
+ const { live, rooms, events } = body;
27
+ return {
28
+ live: typeof live === 'boolean' ? live : FIRST_VISIT.live,
29
+ rooms: count(rooms, MAX_ROOM_GHOSTS, FIRST_VISIT.rooms),
30
+ events: count(events, 3, FIRST_VISIT.events),
31
+ };
32
+ }
33
+ /*
34
+ * Wrapped in `try`/`catch`, as `./roomFilters.ts` is: a private window, cleared site data or a blocked
35
+ * store must still draw the page, with the first visit's shape.
36
+ */
37
+ export function loadFrontShape() {
38
+ try {
39
+ return parseFrontShape(globalThis.localStorage?.getItem(STORAGE_KEY) ?? null);
40
+ }
41
+ catch {
42
+ return FIRST_VISIT;
43
+ }
44
+ }
45
+ export function saveFrontShape(shape) {
46
+ try {
47
+ globalThis.localStorage?.setItem(STORAGE_KEY, JSON.stringify(shape));
48
+ }
49
+ catch {
50
+ // Not remembered: the next visit draws the first visit's skeleton, and nothing else changes.
51
+ }
52
+ }
package/dist/http.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ /** `fetch`, narrowed to what the clients call, so a test can pass a stub. */
2
+ export type Fetch = (input: string, init?: RequestInit) => Promise<Response>;
3
+ /** The page's own transport: every client's default, and what a page-long read is kept for (`readOnce`). */
4
+ export declare const pageFetch: Fetch;
5
+ /**
6
+ * `read()`'s answer for `url`, read once for the page and shared by every caller, in flight or
7
+ * landed: for what changes only with a deploy, or with a write this page makes (`forgetRead`). A
8
+ * read that fails, or answers `null`, is not kept, so the next caller asks again. Kept per transport,
9
+ * so a test's own stub keeps its own answers.
10
+ */
11
+ export declare function readOnce<T>(fetchImpl: Fetch, url: string, read: () => Promise<T>): Promise<T>;
12
+ /** What `url` reads has changed: the next `readOnce` of it asks the server. */
13
+ export declare function forgetRead(fetchImpl: Fetch, url: string): void;
14
+ /** Where this build is served from: `/cardtable/` in production, `/` in a test. */
15
+ export declare function appBase(): string;
16
+ /** `/cardtable/` → `/cardtable/api/`. Same arithmetic as `socketPath`. */
17
+ export declare function apiBase(base?: string): string;
18
+ /** An `/api` path, `rooms/r-1`, under this build's base. */
19
+ export declare function apiUrl(path: string): string;
20
+ export declare function isRecord(v: unknown): v is Record<string, unknown>;
21
+ /** The reply's JSON, or null when it has none (a proxy's error page, a 204). */
22
+ export declare function bodyOf(res: Response): Promise<unknown>;
23
+ /** The server's own `{ error }`, or the status when the body has none. */
24
+ export declare function serverMessage(body: unknown, status: number): string;
25
+ /** A GET of an `/api` URL that wants JSON back. */
26
+ export declare function getJson(url: string, fetchImpl?: Fetch): Promise<Response>;
27
+ /** A JSON body to an `/api` URL. `init` adds to the request, never replaces the cookie or the content type. */
28
+ export declare function sendJson(url: string, method: string, body: unknown, fetchImpl?: Fetch, init?: RequestInit): Promise<Response>;
package/dist/http.js ADDED
@@ -0,0 +1,83 @@
1
+ /*
2
+ * The app's one HTTP client: where `/api/` is, and how a request goes out and a
3
+ * reply is read. Every call sends the session cookie (`credentials:
4
+ * 'same-origin'`), because every `/api` route is friend-gated at the edge.
5
+ */
6
+ /** The page's own transport: every client's default, and what a page-long read is kept for (`readOnce`). */
7
+ export const pageFetch = (input, init) => fetch(input, init);
8
+ const pageReads = new WeakMap();
9
+ /**
10
+ * `read()`'s answer for `url`, read once for the page and shared by every caller, in flight or
11
+ * landed: for what changes only with a deploy, or with a write this page makes (`forgetRead`). A
12
+ * read that fails, or answers `null`, is not kept, so the next caller asks again. Kept per transport,
13
+ * so a test's own stub keeps its own answers.
14
+ */
15
+ export function readOnce(fetchImpl, url, read) {
16
+ const reads = pageReads.get(fetchImpl) ?? new Map();
17
+ pageReads.set(fetchImpl, reads);
18
+ const kept = reads.get(url);
19
+ if (kept !== undefined)
20
+ return kept;
21
+ const reading = read();
22
+ reads.set(url, reading);
23
+ const forget = () => {
24
+ if (reads.get(url) === reading)
25
+ reads.delete(url);
26
+ };
27
+ // The caller hears the failure; this only stops keeping it.
28
+ reading.then((answer) => {
29
+ if (answer === null)
30
+ forget();
31
+ }, forget);
32
+ return reading;
33
+ }
34
+ /** What `url` reads has changed: the next `readOnce` of it asks the server. */
35
+ export function forgetRead(fetchImpl, url) {
36
+ pageReads.get(fetchImpl)?.delete(url);
37
+ }
38
+ /** Where this build is served from: `/cardtable/` in production, `/` in a test. */
39
+ export function appBase() {
40
+ const base = import.meta.env?.BASE_URL;
41
+ return typeof base === 'string' ? base : '/';
42
+ }
43
+ /** `/cardtable/` → `/cardtable/api/`. Same arithmetic as `socketPath`. */
44
+ export function apiBase(base = appBase()) {
45
+ const prefix = base === '' ? '/' : base;
46
+ return `${prefix.endsWith('/') ? prefix : `${prefix}/`}api/`;
47
+ }
48
+ /** An `/api` path, `rooms/r-1`, under this build's base. */
49
+ export function apiUrl(path) {
50
+ return `${apiBase()}${path}`;
51
+ }
52
+ export function isRecord(v) {
53
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
54
+ }
55
+ /** The reply's JSON, or null when it has none (a proxy's error page, a 204). */
56
+ export async function bodyOf(res) {
57
+ try {
58
+ return await res.json();
59
+ }
60
+ catch {
61
+ return null;
62
+ }
63
+ }
64
+ /** The server's own `{ error }`, or the status when the body has none. */
65
+ export function serverMessage(body, status) {
66
+ if (isRecord(body) && typeof body.error === 'string' && body.error !== '')
67
+ return body.error;
68
+ return `the server answered HTTP ${status}`;
69
+ }
70
+ /** A GET of an `/api` URL that wants JSON back. */
71
+ export function getJson(url, fetchImpl = pageFetch) {
72
+ return fetchImpl(url, { credentials: 'same-origin', headers: { accept: 'application/json' } });
73
+ }
74
+ /** A JSON body to an `/api` URL. `init` adds to the request, never replaces the cookie or the content type. */
75
+ export function sendJson(url, method, body, fetchImpl = pageFetch, init = {}) {
76
+ return fetchImpl(url, {
77
+ ...init,
78
+ method,
79
+ credentials: 'same-origin',
80
+ headers: { 'content-type': 'application/json', accept: 'application/json', ...init.headers },
81
+ body: JSON.stringify(body),
82
+ });
83
+ }
package/dist/idle.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** Run `fn` when the page is idle, or within two seconds. Imports nothing, so a module the server also runs may use it. */
2
+ export declare function whenIdle(fn: () => void): void;
package/dist/idle.js ADDED
@@ -0,0 +1,7 @@
1
+ /** Run `fn` when the page is idle, or within two seconds. Imports nothing, so a module the server also runs may use it. */
2
+ export function whenIdle(fn) {
3
+ if (typeof requestIdleCallback === 'function')
4
+ requestIdleCallback(fn, { timeout: 2000 });
5
+ else
6
+ setTimeout(fn, 200);
7
+ }
package/dist/lazy.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { type ComponentType, type ReactNode } from 'react';
2
+ /** A component whose module loads on first draw. `preload()` starts it early and never rejects. */
3
+ export interface LazyComponent<P> {
4
+ (props: P): ReactNode;
5
+ preload(): Promise<void>;
6
+ }
7
+ /** How soon after a reload another failed chunk is a real failure rather than a deploy. */
8
+ export declare const RELOAD_GUARD_MS = 60000;
9
+ export declare function lazyComponent<P extends object>(load: () => Promise<ComponentType<P>>): LazyComponent<P>;
package/dist/lazy.js ADDED
@@ -0,0 +1,63 @@
1
+ /*
2
+ * Code the first screen does not need, loaded when it is first drawn, or earlier on purpose.
3
+ *
4
+ * The page's entry is the lobby and the chrome around every screen; each other screen, and the
5
+ * lobby's featured board, is a chunk of its own (`screens/Screen.tsx`, `front/LiveSlot.tsx`), with
6
+ * the big data tables in long-lived chunks beside them (`vite.config.ts`). A chunk loads the first
7
+ * time its component draws, or before, from `preload()`: the screens a player opens next are warmed
8
+ * once the page is idle (`main.tsx`), so a press rarely waits on the network.
9
+ *
10
+ * `lazyComponent` is `React.lazy` with two differences:
11
+ *
12
+ * - **A module already loaded draws in the same render.** `React.lazy` suspends once on its first
13
+ * render even when `preload()` landed long ago, and a route change is a synchronous update: the
14
+ * screen would blank for a frame. Here, once the load has settled, the component is drawn
15
+ * directly and nothing suspends.
16
+ * - **A failed load reloads the page, once.** The server serves only the current build, so after a
17
+ * deploy the open page's chunk names are gone and every load of one fails. A reload fetches the
18
+ * new `index.html` (served `no-store`) and lands on the same route. A second failure within
19
+ * {@link RELOAD_GUARD_MS} is not a deploy: it is thrown, rather than reloading in a loop.
20
+ */
21
+ import { createElement, use } from 'react';
22
+ const RELOADED_AT = 'cardtable:reloaded-for-chunk';
23
+ /** How soon after a reload another failed chunk is a real failure rather than a deploy. */
24
+ export const RELOAD_GUARD_MS = 60_000;
25
+ /** Reloads the page for a new build, unless it just did. Whether it reloaded. */
26
+ function reloadForNewBuild() {
27
+ try {
28
+ const last = Number(sessionStorage.getItem(RELOADED_AT));
29
+ if (Date.now() - last < RELOAD_GUARD_MS)
30
+ return false;
31
+ sessionStorage.setItem(RELOADED_AT, String(Date.now()));
32
+ }
33
+ catch (err) {
34
+ // No storage to remember the reload in, so no way to stop a loop: fail instead.
35
+ console.warn('[cardtable] a chunk did not load and there is no session storage to guard a reload with', err);
36
+ return false;
37
+ }
38
+ location.reload();
39
+ return true;
40
+ }
41
+ export function lazyComponent(load) {
42
+ let loaded = null;
43
+ let loading = null;
44
+ /**
45
+ * The load a draw waits on, kept once it fails: React's retry reads the same promise and throws its
46
+ * error, where a fresh one would suspend again, and load again, forever. Only a draw reloads: a
47
+ * preload that fails says so and leaves the load to the draw.
48
+ */
49
+ let drawing = null;
50
+ // A failed preload is not kept: the draw loads again.
51
+ const start = () => (loading ??= load().then((component) => (loaded = component), (err) => {
52
+ loading = null;
53
+ throw err;
54
+ }));
55
+ const draw = () => (drawing ??= start().catch((err) => {
56
+ if (reloadForNewBuild())
57
+ return new Promise(() => undefined);
58
+ throw err;
59
+ }));
60
+ const Lazy = (props) => createElement(loaded ?? use(draw()), props);
61
+ Lazy.preload = () => start().then(() => undefined, (err) => console.warn('[cardtable] a chunk did not preload; it loads again when drawn', err));
62
+ return Lazy;
63
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * `at`, moved as little as needed for a span of `size` to stay `gap` inside
3
+ * `lo`…`hi`; against the low edge when it cannot fit at all.
4
+ */
5
+ export declare function clampSpan(at: number, size: number, lo: number, hi: number, gap: number): number;
6
+ /**
7
+ * Close on Escape, or on a press anywhere `keeps` does not claim — the popover
8
+ * itself, and whatever opened it when its own click toggles it. Listened in
9
+ * capture on the document, so a board gesture that stops propagation still
10
+ * closes it, and read through `eventTarget`, so a press inside the embed's
11
+ * shadow root is the element it landed on.
12
+ */
13
+ export declare function useDismiss(onClose: () => void, keeps: (target: Node) => boolean): void;
@@ -0,0 +1,39 @@
1
+ /*
2
+ * What every popover on a screen does the same way: where it stands inside the
3
+ * box it may not leave, and when it goes away.
4
+ */
5
+ import { useEffect } from 'react';
6
+ import { eventTarget } from "./dom.js";
7
+ /**
8
+ * `at`, moved as little as needed for a span of `size` to stay `gap` inside
9
+ * `lo`…`hi`; against the low edge when it cannot fit at all.
10
+ */
11
+ export function clampSpan(at, size, lo, hi, gap) {
12
+ return Math.max(lo + gap, Math.min(at, hi - gap - size));
13
+ }
14
+ /**
15
+ * Close on Escape, or on a press anywhere `keeps` does not claim — the popover
16
+ * itself, and whatever opened it when its own click toggles it. Listened in
17
+ * capture on the document, so a board gesture that stops propagation still
18
+ * closes it, and read through `eventTarget`, so a press inside the embed's
19
+ * shadow root is the element it landed on.
20
+ */
21
+ export function useDismiss(onClose, keeps) {
22
+ useEffect(() => {
23
+ const onKey = (event) => {
24
+ if (event.key === 'Escape')
25
+ onClose();
26
+ };
27
+ const onPress = (event) => {
28
+ const target = eventTarget(event);
29
+ if (target instanceof Node && !keeps(target))
30
+ onClose();
31
+ };
32
+ document.addEventListener('keydown', onKey);
33
+ document.addEventListener('pointerdown', onPress, true);
34
+ return () => {
35
+ document.removeEventListener('keydown', onKey);
36
+ document.removeEventListener('pointerdown', onPress, true);
37
+ };
38
+ }, [onClose, keeps]);
39
+ }
@@ -0,0 +1,5 @@
1
+ /** A part the game hands a generic file once, from `./composition.tsx`; read before then, it throws rather than guess. */
2
+ export declare function registered<T>(name: string): {
3
+ set(value: T): void;
4
+ get(): T;
5
+ };
@@ -0,0 +1,6 @@
1
+ /** A part the game hands a generic file once, from `./composition.tsx`; read before then, it throws rather than guess. */
2
+ export function registered(name) {
3
+ let value;
4
+ const missing = () => { throw new Error(`${name} was never registered: ./composition.tsx's composeGame() registers it`); };
5
+ return { set: (v) => void (value = v), get: () => value ?? missing() };
6
+ }
@@ -0,0 +1,20 @@
1
+ /** How long a planned restart reads as updating before it reads as reconnecting. */
2
+ export declare const QUIET_RECONNECT_MS = 8000;
3
+ /** How old a notice may be and still explain the drop that follows it. */
4
+ export declare const NOTICE_FRESH_MS = 10000;
5
+ interface Listens {
6
+ on(event: string, handler: () => void): void;
7
+ }
8
+ export interface RestartClock {
9
+ now(): number;
10
+ setTimeout(fn: () => void, ms: number): unknown;
11
+ clearTimeout(handle: unknown): void;
12
+ }
13
+ /**
14
+ * Watch `socket` for a planned restart. `onChange(updating)` runs when the
15
+ * socket drops after a notice (true) and again when it reconnects or the quiet
16
+ * window ends (false); `back` says which, since a socket back is not yet a
17
+ * screen back (a match's rejoin, `play/live/match.ts`).
18
+ */
19
+ export declare function watchRestart(socket: Listens, onChange: (updating: boolean, back: boolean) => void, clock?: RestartClock): void;
20
+ export {};
@@ -0,0 +1,54 @@
1
+ /**
2
+ * A planned restart, told apart from a lost connection.
3
+ *
4
+ * Before a deploy's SIGTERM closes its sockets, the server tells every one of
5
+ * them it is restarting (`SERVER_RESTARTING_EVENT`). A socket that heard that
6
+ * and then dropped is `updating` for the next {@link QUIET_RECONNECT_MS}: it is
7
+ * coming back on its own, so the screen says so quietly. Past that, or after a
8
+ * drop with no notice, it is an ordinary lost connection again.
9
+ */
10
+ import { SERVER_RESTARTING_EVENT } from '@wolffm/platform-wire/restarting';
11
+ /** How long a planned restart reads as updating before it reads as reconnecting. */
12
+ export const QUIET_RECONNECT_MS = 8_000;
13
+ /** How old a notice may be and still explain the drop that follows it. */
14
+ export const NOTICE_FRESH_MS = 10_000;
15
+ const realClock = {
16
+ now: () => Date.now(),
17
+ setTimeout: (fn, ms) => setTimeout(fn, ms),
18
+ clearTimeout: (handle) => clearTimeout(handle),
19
+ };
20
+ /**
21
+ * Watch `socket` for a planned restart. `onChange(updating)` runs when the
22
+ * socket drops after a notice (true) and again when it reconnects or the quiet
23
+ * window ends (false); `back` says which, since a socket back is not yet a
24
+ * screen back (a match's rejoin, `play/live/match.ts`).
25
+ */
26
+ export function watchRestart(socket, onChange, clock = realClock) {
27
+ let noticedAt = null;
28
+ let updating = false;
29
+ let quiet = null;
30
+ const set = (next, back = false) => {
31
+ if (quiet !== null)
32
+ clock.clearTimeout(quiet);
33
+ quiet = null;
34
+ if (next === updating)
35
+ return;
36
+ updating = next;
37
+ onChange(next, back);
38
+ };
39
+ socket.on(SERVER_RESTARTING_EVENT, () => {
40
+ noticedAt = clock.now();
41
+ });
42
+ socket.on('disconnect', () => {
43
+ const planned = noticedAt !== null && clock.now() - noticedAt <= NOTICE_FRESH_MS;
44
+ noticedAt = null;
45
+ if (!planned)
46
+ return set(false);
47
+ set(true);
48
+ quiet = clock.setTimeout(() => set(false), QUIET_RECONNECT_MS);
49
+ });
50
+ socket.on('connect', () => {
51
+ noticedAt = null;
52
+ set(false, true);
53
+ });
54
+ }
@@ -0,0 +1,116 @@
1
+ import { type ReactNode } from 'react';
2
+ import '@wolffm/watchparty-ui/room-chrome.css';
3
+ import { type Theme } from '@wolffm/themes';
4
+ /**
5
+ * The page's resolved theme, handed to the chrome as-is.
6
+ *
7
+ * ## Why the two disagreed, diagnosed rather than assumed (w20 §E)
8
+ *
9
+ * `RoomChrome` takes an optional `theme` prop. Left unset — which is what this
10
+ * file did until w20 — it resolves its OWN default from ITS OWN internal
11
+ * store, entirely independent of `HadokuThemeRoot` (quoted in full below).
12
+ * Measured live (a stub-`whoami` build served
13
+ * locally, `#/match/…`, no saved theme in either storage): the page resolved
14
+ * `data-theme="light"` on `.cardtable-chrome` while `.wp-room-chrome` sat at
15
+ * `data-theme="dark"` — two independent defaults, not a shared one that drifted.
16
+ * Passing our theme through removes the second default entirely; they cannot
17
+ * disagree once there is only one source.
18
+ *
19
+ * ## Why this casts instead of validating (w22 §G, found by hadoku_site)
20
+ *
21
+ * This used to filter through `THEMES` and answer `undefined` for a name it did
22
+ * not recognise. `undefined` is not a neutral value here — it is precisely what
23
+ * sends the chrome back to that second default, so the filter reintroduced the
24
+ * split-theme bug in the one case it was written to protect against.
25
+ *
26
+ * That case is unreachable today: one `@wolffm/themes` install (5.8.6), and
27
+ * `room-chrome.d.ts:3` imports `Theme` from it, so there is a single union. But
28
+ * watchparty-ui takes themes as a regular **dependency** (`^5.8.5`), not a peer,
29
+ * so a host outside that range resolves a second nested copy and two distinct
30
+ * unions exist. There, passing an unrecognised name through is strictly better
31
+ * than dropping it, and the shipped code is why — read out of the installed
32
+ * bundle, its fallback is:
33
+ *
34
+ * function Do(e) { if (e) return e; const t = ze().theme;
35
+ * return t && tn.includes(t) ? t : "dark"; }
36
+ *
37
+ * The prop is honoured VERBATIM, unvalidated, and lands on `data-theme` of the
38
+ * chrome's own `aside.wp-room-chrome` — never on the host document. Only a
39
+ * FALSY prop makes the chrome consult its own store and then hard-code `dark`.
40
+ * So an unknown name resolves against whichever `[data-theme=…]` palettes are
41
+ * loaded and otherwise falls to a neutral light base; `undefined` resolves to
42
+ * an actively wrong `dark`. `undefined` is the only value that cannot be
43
+ * ignored.
44
+ *
45
+ * Corrected against the installed bundle rather than taken on trust: the §G brief said
46
+ * `room-chrome.css` "styles only its own light/dark internals". It does not —
47
+ * it ships all 18 `[data-theme=…]` blocks under `@scope (.wp-room-chrome)`,
48
+ * with `:scope,:scope[data-theme=light]` as the fallback rule, the same 18 the
49
+ * host's `@wolffm/themes/src/style.css` carries unscoped. That changes the
50
+ * reason, not the fix: what makes the pass-through work is `if (e) return e`,
51
+ * not a gap in the chrome's own palettes.
52
+ *
53
+ * ## The trap, for whoever edits this next
54
+ *
55
+ * The cast is load-bearing twice, and only one half announces itself.
56
+ * `theme={theme}` fails typecheck — TS2322, because `useHadokuTheme()` types
57
+ * `theme` as `string` (the picker's families are data-driven) — which is what
58
+ * sends people looking for a validator in the first place. But
59
+ * `theme={filtered ?? undefined}` compiles cleanly and IS the defect. Only the
60
+ * type error is loud; the wrong fix is silent. The `Theme` return type below,
61
+ * with no `| undefined`, is what makes the silent half loud too: a re-added
62
+ * `?? undefined` stops compiling here instead of shipping a chrome that resolves
63
+ * its own theme.
64
+ */
65
+ export declare function watchpartyTheme(theme: string): Theme;
66
+ /**
67
+ * A room key for one of our pods or matches, or null when the id is not a
68
+ * shape watchparty will accept.
69
+ *
70
+ * Null means "render the table with no room" — never a guessed or coerced key,
71
+ * because two ids that collapse to the same key would put two unrelated groups
72
+ * in one room, and they would each see the other's chat.
73
+ */
74
+ export declare function roomKeyFor(id: string): string | null;
75
+ /**
76
+ * This app's own origin, on whatever host serves this page — never
77
+ * hardcoded, so PPE (built with `CARDTABLE_BASE_PREFIX=/cardtable-ppe`) gets
78
+ * PPE's own origin rather than prod's. The same derivation
79
+ * `room/socket-options.ts`'s `defaultSocketPath` uses for the draft socket's
80
+ * path, here producing an ORIGIN string: `RoomChrome` derives its socket
81
+ * path, `/cardtable[-ppe]/socket.io/`, from its pathname, so passing the
82
+ * bare base is enough — no `roomSocketPath` override needed.
83
+ */
84
+ export declare function cardtableOrigin(): string;
85
+ /**
86
+ * Wraps `children` in watchparty's room when there is a room to be in.
87
+ *
88
+ * Renders the children alone when there is no room id or when whoami failed. A
89
+ * table without chat is a degraded room; a table that will not draw because
90
+ * chat is down is an outage.
91
+ *
92
+ * The children mount ONCE, whatever the chrome does around them. Remounted, they
93
+ * lose everything they hold and open their sockets again: a match opened from a
94
+ * link joined on two sockets and hung up the first, and when the hang-up beat the
95
+ * second join the server saw the seat leave (`e2e/w69-name-card.spec.ts`, "nobody
96
+ * disconnected"); a joiner's room screen, drawn before its join and wrapped once
97
+ * the join let the chat in (`App.tsx`'s `useJoined`), dropped an open Room
98
+ * settings and connected its draft socket twice (`e2e/w83b-draft-rope.spec.ts`).
99
+ * So they are rendered through a portal from one place in this component's tree,
100
+ * into a node that moves into the chrome when it draws and out when it goes. That
101
+ * node and the slot holding it are both `.chrome-slot` (`display: contents`), and
102
+ * the chrome's rules for its content's own child reach through exactly those two
103
+ * (`@hadoku/ui-shell`'s `chrome.css`). While whoami is in flight on a room's route, before they have
104
+ * first mounted, they wait for it: their first frame is already inside.
105
+ */
106
+ export declare function RoomShell({ roomId, collapsible, inert, children, }: {
107
+ /** The room this viewer is in: the chat and roster the chrome joins, and where their avatar is asserted. */
108
+ roomId: string | null;
109
+ /** `false` keeps the chat open with no Hide chat button — the room's lobby,
110
+ * where the chat is the point. A viewer's saved collapse is ignored there,
111
+ * not cleared, so the match still opens the way they left it. */
112
+ collapsible?: boolean;
113
+ /** Behind a question the page must answer first (`./SessionPrompt.tsx`): the chat cannot be reached. */
114
+ inert?: boolean;
115
+ children: ReactNode;
116
+ }): import("react").JSX.Element;