@hadoku/game-ui 0.1.106 → 0.1.107

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.
@@ -0,0 +1,189 @@
1
+ import { type ReactNode } from 'react';
2
+ import { type RoomFeed } from '../rooms/feed.js';
3
+ import type { Look } from '@wolffm/platform-wire/look';
4
+ import './RoomFront.css';
5
+ export interface RoomFrontMember {
6
+ id: string;
7
+ name: string;
8
+ avatarId?: string;
9
+ /** Their picture and cosmetics: drawn instead of the character, as chat and the seats draw them. */
10
+ look?: Look;
11
+ }
12
+ /** Every number and label a row draws besides its name, its lock and its roster — a game's own derivation, computed before the room reaches this file. */
13
+ export interface RoomFrontView {
14
+ seatsFilled: number;
15
+ /** `null` draws the count alone: a room whose seats grow (a tournament) has no capacity worth showing. */
16
+ seatsCapacity: number | null;
17
+ state: {
18
+ key: string;
19
+ label: string;
20
+ detail: string | null;
21
+ };
22
+ primaryAction: 'Join' | 'Watch';
23
+ /** A second, explicit Watch beside the primary action (the room is in progress, say). */
24
+ extraWatch: boolean;
25
+ }
26
+ export interface RoomFrontRoom {
27
+ id: string;
28
+ name: string;
29
+ gameType: string;
30
+ locked: boolean;
31
+ /** An admin-seeded testing room: its own section, folded by default preference, never sent to a non-admin at all. */
32
+ testing?: boolean;
33
+ members: readonly RoomFrontMember[];
34
+ you: {
35
+ id: string;
36
+ };
37
+ view: RoomFrontView;
38
+ }
39
+ export type RoomFrontJoinOutcome<V> = {
40
+ ok: true;
41
+ room: V;
42
+ } | {
43
+ ok: false;
44
+ reason: 'refused';
45
+ } | {
46
+ ok: false;
47
+ reason: 'rate-limited';
48
+ } | {
49
+ ok: false;
50
+ reason: 'error';
51
+ message: string;
52
+ };
53
+ export type RoomFrontCreateOutcome<V> = {
54
+ ok: true;
55
+ room: V;
56
+ } | {
57
+ ok: false;
58
+ message: string;
59
+ };
60
+ /** A client over game-server's generic room routes (`GET/POST /api/rooms`, the room view as `room-core.ts` answers it) — no Magic types. */
61
+ export interface RoomFrontClient<V extends RoomFrontRoom> {
62
+ list(): Promise<{
63
+ rooms: readonly V[];
64
+ }>;
65
+ create(body: Record<string, unknown> & {
66
+ name: string;
67
+ gameType: string;
68
+ }): Promise<RoomFrontCreateOutcome<V>>;
69
+ join(roomId: string, password?: string): Promise<RoomFrontJoinOutcome<V>>;
70
+ /** An admin's reset of a seeded testing room; omitted when a caller offers no testing rooms at all. */
71
+ reset?(roomId: string): Promise<{
72
+ ok: true;
73
+ } | {
74
+ ok: false;
75
+ message: string;
76
+ }>;
77
+ }
78
+ /**
79
+ * What says the list changed, without polling it. Defaults to the page's room feed
80
+ * (`../rooms/feed.ts`'s `roomFeed()`: game-server's `attachRoomFeed` pings, a read when the tab is
81
+ * shown again, and a long resilience read), so a game that attached the feed server-side needs no
82
+ * timer of its own.
83
+ */
84
+ export type RoomFrontFeed = RoomFeed;
85
+ export interface RoomFrontGameType {
86
+ id: string;
87
+ label: string;
88
+ }
89
+ export interface RoomFrontCreateSlot {
90
+ node?: ReactNode;
91
+ /**
92
+ * Takes over this kind's whole creation — a wholly different write than the generic
93
+ * `rooms.create()` (Magic's Challenge, say, which is whole-born from an event rather than named
94
+ * and typed). When set, the generic name field and the generic POST are both skipped for this kind.
95
+ */
96
+ submit?: () => Promise<RoomFrontCreateOutcome<never>>;
97
+ /** No generic name field for this kind (set together with `submit` for a whole-born kind). */
98
+ nameless?: boolean;
99
+ /** The submit button stays disabled until this is true (default true — ready at once). */
100
+ ready?: boolean;
101
+ /** Extra fields merged into the generic POST body, alongside `name` and `gameType` (ignored when `submit` is set). */
102
+ body?: Record<string, unknown>;
103
+ }
104
+ export interface RoomFrontRowExtras {
105
+ /** The room's own background scene, large and faint behind the row's info. */
106
+ scene?: ReactNode;
107
+ /** The room's own type glyph, beside its name. */
108
+ typeIcon?: ReactNode;
109
+ trophy?: ReactNode;
110
+ modeChip?: ReactNode;
111
+ seriesChip?: ReactNode;
112
+ /** The row's trailing, screen-reader-mostly line (a streamed client's own label, say). */
113
+ legacyMeta?: ReactNode;
114
+ /** `data-family` on the row: the game's own name for its kind (a format family, say), for its tests and its telemetry. */
115
+ family?: string;
116
+ /**
117
+ * The row's own custom properties (`./RoomFront.css`): `--room-front-tint` (the card's wash),
118
+ * `--room-front-dot` (its state's dot), `--room-front-state-ink` (its state's label). A game's own
119
+ * reading of its room, so the colours of a "drafting" or a "done" room are the game's, not this module's.
120
+ */
121
+ vars?: Readonly<Record<`--room-front-${string}`, string>>;
122
+ }
123
+ export interface RoomFrontProps<V extends RoomFrontRoom> {
124
+ rooms: RoomFrontClient<V>;
125
+ /** The create form's own radio: every type a caller may make, id and label, at least one. With only one, no radio is drawn. */
126
+ gameTypes: readonly RoomFrontGameType[];
127
+ createFields?: (kind: string) => RoomFrontCreateSlot | null;
128
+ rowExtras?: (room: V) => RoomFrontRowExtras;
129
+ /** A Twitch-like banner above the list — omitted draws none of its markup (no wrapper element). */
130
+ banner?: ReactNode;
131
+ /** The header's own tools row — omitted draws no `<nav>` at all. */
132
+ navTools?: ReactNode;
133
+ /** A slot beside `banner`, for a caller with no fused banner of its own — omitted draws nothing. */
134
+ featured?: ReactNode;
135
+ onOpenRoom: (id: string) => void;
136
+ /** Extra content in the list's own head row, beside the title and before Create room (a game's own filter bar, say). */
137
+ headExtras?: ReactNode;
138
+ /**
139
+ * Extra content beside Create room, in the same actions group (a game's own "Create event", say).
140
+ * A button or link given `className="room-front__go"` draws exactly as Create room does.
141
+ */
142
+ actionsExtras?: ReactNode;
143
+ feed?: RoomFrontFeed;
144
+ /**
145
+ * Whether `room` matches every filter the caller is tracking that is currently ON — recomputed
146
+ * fresh every render (a filter toggle lives in the caller's own state, outside this list's own),
147
+ * never baked into a room at the time it was read. Rooms are never hidden by a filter, only
148
+ * sorted and dimmed: unset or always-true never dims anything.
149
+ */
150
+ matches?: (room: V) => boolean;
151
+ /**
152
+ * A chance to do something other than `onOpenRoom` once a room is freshly joined or created (Magic
153
+ * starts a scenario room against the AI directly, say, rather than opening the room screen for it).
154
+ * `true`: handled, `onOpenRoom` is skipped for this one.
155
+ */
156
+ beforeOpenRoom?: (room: V) => Promise<boolean> | boolean;
157
+ nameMaxLength?: number;
158
+ passwordMaxLength?: number;
159
+ /** The key `localStorage` remembers the Testing section's fold under. A caller with no testing rooms never reads it. */
160
+ testingStorageKey?: string;
161
+ /**
162
+ * The create form's name field starts prefilled with this (the viewer's own name, from the
163
+ * platform's own `useWhoami`, and a fresh random draw, so a word drawn once per opening) rather
164
+ * than empty. `viewerName` is `null` until the fleet has answered or has none for this viewer.
165
+ */
166
+ defaultName?: (viewerName: string | null, random: () => number) => string;
167
+ /** The list's own `<section>`, the moment it mounts and again on unmount — a caller's own tooltip or scroll mechanism attaches here, same as it would to any other section it owns. */
168
+ onSectionRef?: (el: HTMLElement | null) => void;
169
+ /**
170
+ * Classes added to the create dialog's panel, after its own `room-front-create` (which lays it
171
+ * out and draws a plain surface `./RoomFront.css` keeps low enough for these to draw over). A
172
+ * caller with its own "raised surface" convention supplies it here rather than this file
173
+ * hard-coding one: Magic's `RoomList.tsx` passes `"ct-surface ct-panel"`, from the one file
174
+ * `css-ownership.test.ts` already knows reaches the tree that owns `.ct-surface`.
175
+ *
176
+ * Named `createPanelClassName`, not the bare `className` an earlier draft of this prop used
177
+ * (`docs/planning/s3-2026-11-17.md` §G.5): a plain `className` on a component that is not a
178
+ * simple DOM wrapper reads as "the root element's own class", when this is actually one nested
179
+ * CREATE DIALOG panel's — a different, narrower thing a careless caller could otherwise pass
180
+ * believing it styled the whole list. `css-ownership.test.ts`'s own "is this really a class
181
+ * list" check (`CLASS_AT`) used to recognise ONLY a literal sitting right after a bare
182
+ * `className=`/`class=`, which is exactly why that draft kept the confusing name — any camelCase
183
+ * prefix broke the check. `CLASS_AT` now also matches `\w*ClassName=` generically, so a
184
+ * caller's own call-site literal (`<RoomFront createPanelClassName="ct-surface ct-panel" />`)
185
+ * is still recognised as a real class list, the same as a bare `className=` is.
186
+ */
187
+ createPanelClassName?: string;
188
+ }
189
+ export declare function RoomFront<V extends RoomFrontRoom>({ rooms: client, gameTypes, createFields, rowExtras, banner, navTools, featured, onOpenRoom, headExtras, actionsExtras, feed, matches: matchesFilter, beforeOpenRoom, nameMaxLength, passwordMaxLength, testingStorageKey, defaultName, onSectionRef, createPanelClassName, }: RoomFrontProps<V>): import("react").JSX.Element;
@@ -0,0 +1,313 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ /*
3
+ * The front-page module, settled for every game cardtable or another site hosts (wave 120 §F; the
4
+ * contract is frozen in `docs/planning/wave120-2026-11-17.md` — bomberman's own wave `bm1` consumes
5
+ * this from npmjs the moment it publishes, so its exported names and prop shapes may not drift
6
+ * without the tracker's say).
7
+ *
8
+ * This is the generic list/filter/sort/follow/create-dialog machinery that used to live, entangled
9
+ * with Magic's own fields, in `games/magic/ui/src/rooms/RoomList.tsx` (`RoomRow` and
10
+ * `CreateRoomDialog`). What is Magic's stays Magic's: the mode chip's icon, the room's background
11
+ * scene, the trophy, the series chip and the "legacy" streamed-client line are all drawn by
12
+ * `rowExtras`; a game's own create-form fields (and a wholly different creation, such as Magic's
13
+ * Challenge) are drawn and may be submitted by `createFields`. A room arrives here already carrying
14
+ * its own computed `view` (seats, state, the primary action) — that derivation is a game's own (a
15
+ * pod's phase, a table's series), never this file's.
16
+ *
17
+ * Platform: imports nothing from `@hadoku/magic-ui`, any `games/**` package, or `@hadoku/shared`
18
+ * (the layer ratchet resolves that package as Magic even through `/platform`, bar the handful of
19
+ * files it whitelists itself). Its paint is `./RoomFront.css`, imported here: a game tunes it with
20
+ * that file's custom properties (on the page for the list, on `:root` for the dialog, which portals
21
+ * into `<body>`) and a row's own colours with `RoomFrontRowExtras.vars`, never with a copy of it.
22
+ */
23
+ import { useCallback, useContext, useEffect, useRef, useState } from 'react';
24
+ import { Icon } from '@wolffm/themes';
25
+ import { Avatar, faceOf } from "../components/Avatar.js";
26
+ import { OverPage } from "../components/OverPage.js";
27
+ import { RadioCards } from "../components/RadioCards.js";
28
+ import { TopLayer } from "../topLayer.js";
29
+ import { uiLength } from '@wolffm/ui-shell/settings';
30
+ import { Reveal } from '@wolffm/ui-shell/components';
31
+ import { FrontGateContext, usePartShown } from "./gate.js";
32
+ import { MAX_ROOM_GHOSTS } from "./shape.js";
33
+ import { ConstructedIcon, LockIcon, PersonIcon } from "./icons.js";
34
+ import { useWhoami } from "../room/whoami.js";
35
+ import { playRole } from "../sound/index.js";
36
+ import { roomFeed } from "../rooms/feed.js";
37
+ import './RoomFront.css';
38
+ const DEFAULT_NAME_MAX = 60;
39
+ const DEFAULT_PASSWORD_MAX = 200;
40
+ const DEFAULT_TESTING_KEY = 'room-front.testingFolded';
41
+ /**
42
+ * Whether `node` is one of React's own "renders nothing" values — `null`, `undefined`, `false`,
43
+ * `''`, or an array holding only such values — rather than merely `!== undefined`. The settled
44
+ * contract's own words: "empty or absent renders nothing (no wrapper element)" for `banner`,
45
+ * `navTools` and `featured` — `undefined` is one way a caller omits a slot, but `null`, `false`
46
+ * and `[]` are the others a caller passes when it computes the slot conditionally (`cond && <X/>`,
47
+ * or `cond ? <X/> : null`), and each must draw no wrapper of its own either.
48
+ */
49
+ function isRenderable(node) {
50
+ if (node === null || node === undefined || node === false || node === '')
51
+ return false;
52
+ if (Array.isArray(node))
53
+ return node.some(isRenderable);
54
+ return true;
55
+ }
56
+ /** Whether the viewer is already a member — a room never hides its own occupant's name from them. */
57
+ const isMine = (room) => room.members.some((m) => m.id === room.you.id);
58
+ const normalRooms = (rooms) => rooms.filter((r) => r.testing !== true);
59
+ const testingRooms = (rooms) => rooms.filter((r) => r.testing === true);
60
+ /** `rooms`, with every matching one (by `matches`) moved ahead of every room that is not — a stable partition. */
61
+ function orderByMatch(rooms, matches) {
62
+ return [...rooms.filter(matches), ...rooms.filter((r) => !matches(r))];
63
+ }
64
+ function loadTestingFolded(key) {
65
+ try {
66
+ return globalThis.localStorage?.getItem(key) === '1';
67
+ }
68
+ catch {
69
+ return false;
70
+ }
71
+ }
72
+ function saveTestingFolded(key, folded) {
73
+ try {
74
+ if (folded)
75
+ globalThis.localStorage?.setItem(key, '1');
76
+ else
77
+ globalThis.localStorage?.removeItem(key);
78
+ }
79
+ catch {
80
+ // Unremembered is the whole fallback; nothing else to do.
81
+ }
82
+ }
83
+ export function RoomFront({ rooms: client, gameTypes, createFields, rowExtras, banner, navTools, featured, onOpenRoom, headExtras, actionsExtras, feed = roomFeed(), matches: matchesFilter, beforeOpenRoom, nameMaxLength = DEFAULT_NAME_MAX, passwordMaxLength = DEFAULT_PASSWORD_MAX, testingStorageKey = DEFAULT_TESTING_KEY, defaultName, onSectionRef, createPanelClassName, }) {
84
+ const [state, setState] = useState({ kind: 'loading' });
85
+ const [creating, setCreating] = useState(false);
86
+ const [testingFolded, setTestingFolded] = useState(() => loadTestingFolded(testingStorageKey));
87
+ const toggleTesting = () => {
88
+ playRole('ui.select');
89
+ setTestingFolded((was) => {
90
+ saveTestingFolded(testingStorageKey, !was);
91
+ return !was;
92
+ });
93
+ };
94
+ // Latest-wins: a read the server answers after a newer one has already landed changes nothing —
95
+ // never an older list overwriting a newer one, and never a late failure marking a fresh list stale.
96
+ const generation = useRef(0);
97
+ const refresh = useCallback(async () => {
98
+ const gen = ++generation.current;
99
+ try {
100
+ const { rooms: next } = await client.list();
101
+ if (gen !== generation.current)
102
+ return;
103
+ setState({ kind: 'ready', rooms: next, stale: null });
104
+ }
105
+ catch (err) {
106
+ if (gen !== generation.current)
107
+ return;
108
+ const message = err instanceof Error ? err.message : String(err);
109
+ setState((prev) => (prev.kind === 'ready' ? { ...prev, stale: message } : { kind: 'failed', message }));
110
+ }
111
+ }, [client]);
112
+ useEffect(() => {
113
+ let live = true;
114
+ const stop = feed.follow('list', () => {
115
+ if (live)
116
+ void refresh();
117
+ });
118
+ return () => {
119
+ live = false;
120
+ stop();
121
+ };
122
+ }, [refresh, feed]);
123
+ const retry = () => {
124
+ playRole('ui.select');
125
+ setState({ kind: 'loading' });
126
+ void refresh();
127
+ };
128
+ const normal = state.kind === 'ready' ? normalRooms(state.rooms) : [];
129
+ const testing = state.kind === 'ready' ? testingRooms(state.rooms) : [];
130
+ const matches = (room) => matchesFilter?.(room) ?? true;
131
+ const ordered = (list) => orderByMatch(orderByMatch(list, isMine), matches);
132
+ const orderedNormal = ordered(normal);
133
+ const orderedTesting = ordered(testing);
134
+ const { shape, remember } = useContext(FrontGateContext);
135
+ const shown = usePartShown('rooms', state.kind !== 'loading');
136
+ const drawnRooms = state.kind === 'ready' ? Math.min(normal.length, MAX_ROOM_GHOSTS) : null;
137
+ useEffect(() => {
138
+ if (drawnRooms !== null)
139
+ remember({ rooms: drawnRooms });
140
+ }, [drawnRooms, remember]);
141
+ return (_jsxs(_Fragment, { children: [isRenderable(navTools) && _jsx("nav", { className: "shell__tools", children: navTools }), isRenderable(featured) && featured, isRenderable(banner) && banner, _jsxs("section", { className: "rooms ct-panel", "data-testid": "rooms", "aria-labelledby": "rooms-title", "aria-busy": !shown, ref: onSectionRef, children: [_jsxs("div", { className: "rooms__head", children: [_jsx("h2", { id: "rooms-title", className: "rooms__title ct-panel__title", children: "Rooms" }), headExtras, _jsxs("span", { className: "rooms__actions", children: [_jsx("button", { type: "button", className: "room-front__go", "data-testid": "room-create-open", "aria-haspopup": "dialog", onClick: () => {
142
+ playRole('ui.select');
143
+ setCreating(true);
144
+ }, children: "Create room" }), actionsExtras] })] }), _jsxs(Reveal, { name: "rooms", shown: shown, skeleton: _jsx(RoomGhosts, { count: shape.rooms }), layerClassName: "rooms__layer", children: [state.kind === 'failed' && (_jsxs("div", { className: "rooms__status rooms__status--bad", role: "alert", "data-testid": "rooms-error", children: [_jsx("p", { children: state.message }), _jsx("button", { type: "button", "data-testid": "rooms-retry", onClick: retry, children: "Retry" })] })), state.kind === 'ready' && normal.length === 0 && testing.length === 0 && (_jsx("p", { className: "rooms__status", "data-testid": "rooms-empty", children: "No rooms yet." })), state.kind === 'ready' && normal.length > 0 && (_jsx("ul", { className: "rooms__list", "data-testid": "room-list", children: orderedNormal.map((room) => (_jsx(RoomRow, { room: room, client: client, rowExtras: rowExtras, matches: matches, onGone: () => void refresh(), onOpenRoom: onOpenRoom, beforeOpenRoom: beforeOpenRoom, passwordMaxLength: passwordMaxLength }, room.id))) })), state.kind === 'ready' && testing.length > 0 && (_jsxs("div", { "data-testid": "rooms-testing", children: [_jsx("h3", { className: "rooms__title ct-panel__title", children: _jsxs("button", { type: "button", className: "rooms__fold", "aria-expanded": !testingFolded, "aria-controls": "room-list-testing", "data-testid": "rooms-testing-fold", onClick: toggleTesting, children: [_jsx("svg", { className: "rooms__fold-chevron", width: "14", height: "14", viewBox: "0 0 24 24", "aria-hidden": "true", children: _jsx("path", { d: "M9 5l7 7-7 7" }) }), "Testing"] }) }), !testingFolded && (_jsx("ul", { className: "rooms__list", id: "room-list-testing", "data-testid": "room-list-testing", children: orderedTesting.map((room) => (_jsx(RoomRow, { room: room, client: client, rowExtras: rowExtras, matches: matches, onGone: () => void refresh(), onOpenRoom: onOpenRoom, beforeOpenRoom: beforeOpenRoom, passwordMaxLength: passwordMaxLength }, room.id))) }))] })), state.kind === 'ready' && state.stale !== null && (_jsx("p", { className: "rooms__stale", "data-testid": "rooms-stale", children: "List may be out of date." }))] }), creating && (_jsx(CreateRoomDialog, { client: client, gameTypes: gameTypes, createFields: createFields, onClose: () => setCreating(false), onOpenRoom: onOpenRoom, beforeOpenRoom: beforeOpenRoom, nameMaxLength: nameMaxLength, defaultName: defaultName, surfaceClassName: createPanelClassName === undefined ? 'room-front-create' : `room-front-create ${createPanelClassName}` })), _jsx(TopLayer, { fixed: true })] })] }));
145
+ }
146
+ /* ── until the list arrives ─────────────────────────────────────────── */
147
+ function RoomGhosts({ count }) {
148
+ if (count === 0) {
149
+ return (_jsx("p", { className: "rooms__status", "data-testid": "rooms-loading", children: _jsx("span", { className: "ghost ghost--text", children: "No rooms yet." }) }));
150
+ }
151
+ return (_jsx("ul", { className: "rooms__list", "data-testid": "rooms-loading", children: Array.from({ length: count }, (_, i) => (_jsx("li", { className: "room-card", "data-skeleton": `room-${i}`, children: _jsxs("div", { className: "room-card__body", children: [_jsxs("div", { className: "room-card__row1", children: [_jsx("span", { className: "room-card__type-icon ghost", children: _jsx(ConstructedIcon, {}) }), _jsx("span", { className: "room-card__name", children: _jsx("span", { className: "ghost ghost--text", children: "A room's name" }) }), _jsxs("span", { className: "room-card__seats ghost", children: [_jsx(PersonIcon, {}), "0/2"] })] }), _jsxs("div", { className: "room-card__row2", children: [_jsx("span", { className: "room-card__mode-chip ghost", children: _jsx("span", { className: "room-card__mode-text", children: "Mode unset" }) }), _jsx("span", { className: "room-card__series-chip ghost", children: "Bo1" })] }), _jsxs("div", { className: "room-card__row3", children: [_jsx("span", { className: "room-card__state ghost", children: "Lobby" }), _jsx("span", { className: "room-card__state-detail", children: _jsx("span", { className: "ghost ghost--text", children: "Waiting for players" }) })] }), _jsx("div", { className: "room-card__row4", children: _jsx("button", { type: "button", className: "rooms__enter room-card__go ghost", tabIndex: -1, disabled: true, children: "Join" }) })] }) }, i))) }));
152
+ }
153
+ /* ── one row ─────────────────────────────────────────────────────────── */
154
+ function RoomRow({ room, client, rowExtras, matches, onGone, onOpenRoom, beforeOpenRoom, passwordMaxLength, }) {
155
+ const [asking, setAsking] = useState(false);
156
+ const [password, setPassword] = useState('');
157
+ const [busy, setBusy] = useState(false);
158
+ const [error, setError] = useState(null);
159
+ const nameRef = useRef(null);
160
+ const [nameTruncated, setNameTruncated] = useState(false);
161
+ useEffect(() => {
162
+ const el = nameRef.current;
163
+ if (el === null || typeof ResizeObserver === 'undefined')
164
+ return undefined;
165
+ const check = () => setNameTruncated(el.scrollWidth > el.clientWidth);
166
+ check();
167
+ const ro = new ResizeObserver(check);
168
+ ro.observe(el);
169
+ return () => ro.disconnect();
170
+ }, [room.name]);
171
+ const enter = async (withPassword) => {
172
+ setBusy(true);
173
+ setError(null);
174
+ const outcome = await client.join(room.id, withPassword);
175
+ if (outcome.ok) {
176
+ // Still busy: the room is warmed (and a scenario's vs-bot start tried) before this row ever
177
+ // reconsiders it, so the button never flashes "not busy" between the join and leaving the page.
178
+ const handled = beforeOpenRoom === undefined ? false : await beforeOpenRoom(outcome.room);
179
+ setBusy(false);
180
+ if (!handled)
181
+ onOpenRoom(outcome.room.id);
182
+ return;
183
+ }
184
+ setBusy(false);
185
+ // Every arm below is a refusal, and `deny` is the cue for exactly that — raised once, here,
186
+ // rather than in each arm, so a new failure reason cannot arrive without it.
187
+ playRole('ui.deny');
188
+ switch (outcome.reason) {
189
+ case 'refused':
190
+ setError(room.locked ? 'No room with that name and password.' : 'No such room.');
191
+ onGone();
192
+ return;
193
+ case 'rate-limited':
194
+ setError('Too many attempts.');
195
+ return;
196
+ case 'error':
197
+ setError(outcome.message);
198
+ }
199
+ };
200
+ const onEnterClick = () => {
201
+ // `select` for the press itself, whichever branch it takes.
202
+ playRole('ui.select');
203
+ if (room.locked && !isMine(room)) {
204
+ setAsking(true);
205
+ setError(null);
206
+ return;
207
+ }
208
+ void enter();
209
+ };
210
+ const onResetClick = async () => {
211
+ if (client.reset === undefined)
212
+ return;
213
+ playRole('ui.select');
214
+ setBusy(true);
215
+ setError(null);
216
+ const outcome = await client.reset(room.id);
217
+ setBusy(false);
218
+ if (!outcome.ok) {
219
+ playRole('ui.deny');
220
+ setError(outcome.message);
221
+ }
222
+ onGone();
223
+ };
224
+ const onPassword = (e) => {
225
+ e.preventDefault();
226
+ if (password === '') {
227
+ playRole('ui.deny');
228
+ setError('Password required.');
229
+ return;
230
+ }
231
+ playRole('ui.select');
232
+ void enter(password);
233
+ };
234
+ const names = room.members.map((m) => m.name);
235
+ const view = room.view;
236
+ const extras = rowExtras?.(room) ?? {};
237
+ return (_jsxs("li", { className: "room-card", "data-testid": "room-row", "data-room-id": room.id, "data-mine": isMine(room) ? '' : undefined, "data-match": matches(room) ? undefined : 'false', "data-family": extras.family, style: extras.vars, children: [extras.scene !== undefined && (_jsx("span", { className: "room-card__mark", "aria-hidden": "true", children: extras.scene })), _jsxs("div", { className: "room-card__body", children: [_jsxs("div", { className: "room-card__row1", children: [extras.typeIcon !== undefined && (_jsx("span", { className: "room-card__type-icon", "aria-hidden": "true", children: extras.typeIcon })), _jsx("span", { ref: nameRef, className: "room-card__name", "data-testid": "room-name", "data-tip": nameTruncated ? room.name : undefined, tabIndex: nameTruncated ? 0 : undefined, children: room.name }), extras.trophy !== undefined && _jsx("span", { className: "room-card__trophy", children: extras.trophy }), _jsxs("span", { className: "room-card__seats", "data-testid": "room-seats", children: [_jsx(PersonIcon, {}), view.seatsCapacity === null ? view.seatsFilled : `${view.seatsFilled}/${view.seatsCapacity}`] })] }), (extras.modeChip !== undefined || extras.seriesChip !== undefined) && (_jsxs("div", { className: "room-card__row2", children: [extras.modeChip, extras.seriesChip] })), _jsxs("div", { className: "room-card__row3", children: [_jsxs("span", { className: "room-card__state", "data-testid": "room-state", "data-state": view.state.key, children: [_jsx("span", { className: "room-card__dot", "aria-hidden": "true" }), view.state.label] }), view.state.detail !== null && _jsx("span", { className: "room-card__state-detail", children: view.state.detail })] }), _jsxs("span", { className: "rooms__members rooms__sr", "data-testid": "room-members", children: [room.members.map((m) => (_jsx(Avatar, { ...faceOf(m), fallback: "none", className: "rooms__face", "data-testid": "room-face", "data-avatar-id": m.avatarId, title: m.name, width: 18, height: 18, loading: "lazy" }, m.id))), names.join(', ')] }), _jsxs("div", { className: "room-card__row4", children: [!asking && (_jsxs("button", { type: "button", className: "rooms__enter room-card__go", "data-testid": "room-enter", "aria-label": `${view.primaryAction} ${room.name}`, disabled: busy, onClick: onEnterClick, children: [room.locked && (_jsx("span", { className: "room-card__lock", "data-testid": "room-locked", "aria-hidden": "true", children: _jsx(LockIcon, {}) })), view.primaryAction] })), !asking && view.extraWatch && (_jsx("button", { type: "button", className: "rooms__enter room-card__go room-card__go--watch", "data-testid": "room-watch", "aria-label": `Watch ${room.name}`, disabled: busy, onClick: onEnterClick, children: "Watch" })), !asking && room.testing === true && client.reset !== undefined && (_jsx("button", { type: "button", className: "rooms__enter room-card__go", "data-testid": "room-reset", "aria-label": `Reset ${room.name}`, disabled: busy, onClick: () => void onResetClick(), children: "Reset" })), extras.legacyMeta !== undefined && _jsx("div", { className: "room-card__legacy", children: extras.legacyMeta })] })] }), asking && (_jsxs("form", { className: "rooms__password", onSubmit: onPassword, children: [_jsxs("label", { htmlFor: `room-password-${room.id}`, children: ["Password for ", room.name] }), _jsx("input", { id: `room-password-${room.id}`, "data-testid": "room-password", type: "password", maxLength: passwordMaxLength, autoComplete: "off", autoFocus: true, value: password, onChange: (e) => {
238
+ setPassword(e.target.value);
239
+ setError(null);
240
+ } }), _jsx("button", { type: "submit", "data-testid": "room-password-submit", "aria-label": `Enter ${room.name}`, disabled: busy, children: "Enter" }), _jsx("button", { type: "button", className: "rooms__cancel", onClick: () => {
241
+ setAsking(false);
242
+ setPassword('');
243
+ setError(null);
244
+ }, children: "Cancel" })] })), error !== null && (_jsx("p", { className: "ct-error rooms__error", role: "alert", "data-testid": "room-join-error", children: error }))] }));
245
+ }
246
+ /* ── create ──────────────────────────────────────────────────────────── */
247
+ function CreateRoomDialog({ client, gameTypes, createFields, onClose, onOpenRoom, beforeOpenRoom, nameMaxLength, defaultName, surfaceClassName, }) {
248
+ // The word half of the prefill is drawn once per opening (this component remounts fresh each
249
+ // time `creating` turns true) and stays put across re-renders; the viewer's own name half keeps
250
+ // tracking `who` until it resolves, same as the viewer's own name would if typed by hand — except
251
+ // nothing here has been typed yet.
252
+ const who = useWhoami();
253
+ const [draw] = useState(Math.random);
254
+ const [typed, setTyped] = useState(null);
255
+ const viewerName = who === 'pending' ? null : (who?.name ?? null);
256
+ const name = typed ?? (who === 'pending' || defaultName === undefined ? '' : defaultName(viewerName, () => draw));
257
+ const [kind, setKind] = useState(gameTypes[0]?.id ?? '');
258
+ const [busy, setBusy] = useState(false);
259
+ const [error, setError] = useState(null);
260
+ const slot = createFields?.(kind) ?? null;
261
+ const nameless = slot?.nameless === true;
262
+ const ready = slot?.ready ?? true;
263
+ // `RadioCards` wants `{ value, label }`; the settled contract wants `{ id, label }` — this is the
264
+ // one place the two meet.
265
+ const kindOptions = gameTypes.map((g) => ({ value: g.id, label: g.label }));
266
+ useEffect(() => {
267
+ const onKey = (event) => {
268
+ if (event.key === 'Escape')
269
+ onClose();
270
+ };
271
+ globalThis.document?.addEventListener('keydown', onKey);
272
+ return () => globalThis.document?.removeEventListener('keydown', onKey);
273
+ }, [onClose]);
274
+ const opened = async (outcome) => {
275
+ if (!outcome.ok) {
276
+ setBusy(false);
277
+ playRole('ui.deny');
278
+ setError(outcome.message);
279
+ return;
280
+ }
281
+ const handled = beforeOpenRoom === undefined ? false : await beforeOpenRoom(outcome.room);
282
+ setBusy(false);
283
+ if (!handled)
284
+ onOpenRoom(outcome.room.id);
285
+ };
286
+ const submit = async (e) => {
287
+ e.preventDefault();
288
+ if (slot?.submit !== undefined) {
289
+ playRole('ui.select');
290
+ setBusy(true);
291
+ setError(null);
292
+ await opened(await slot.submit());
293
+ return;
294
+ }
295
+ const trimmed = name.trim();
296
+ if (!nameless && trimmed === '') {
297
+ playRole('ui.deny');
298
+ setError('Name required.');
299
+ return;
300
+ }
301
+ playRole('ui.select');
302
+ setBusy(true);
303
+ setError(null);
304
+ await opened(await client.create({ name: trimmed, gameType: kind, ...(slot?.body ?? {}) }));
305
+ };
306
+ return (_jsx(OverPage, { children: _jsx("div", { className: "rooms__backdrop", "data-testid": "room-create-backdrop", onPointerDown: (e) => {
307
+ if (e.target === e.currentTarget)
308
+ onClose();
309
+ }, children: _jsxs("form", { className: surfaceClassName, "data-testid": "room-create", role: "dialog", "aria-modal": "true", "aria-labelledby": "room-create-title", autoComplete: "off", onSubmit: (e) => void submit(e), children: [_jsxs("div", { className: "rooms__create-head", children: [_jsx("h3", { id: "room-create-title", children: "Create a room" }), _jsx("button", { type: "button", className: "rooms__create-close", "aria-label": "Close", "data-testid": "room-create-close", onClick: onClose, children: _jsx(Icon, { name: "close", size: uiLength('1rem') }) })] }), kindOptions.length > 1 && (_jsxs(_Fragment, { children: [_jsx("span", { className: "rooms__caption", children: "Game type" }), _jsx(RadioCards, { name: "room-create-type", label: "Game type", options: kindOptions, value: kind, onChange: setKind, testId: "room-create-type" })] })), !nameless && (_jsxs(_Fragment, { children: [_jsx("label", { htmlFor: "room-create-name", children: "Name" }), _jsx("input", { id: "room-create-name", "data-testid": "room-create-name", value: name, maxLength: nameMaxLength, placeholder: "Friday night", autoComplete: "nickname", autoFocus: true, onChange: (e) => {
310
+ setTyped(e.target.value);
311
+ setError(null);
312
+ } })] })), slot?.node, _jsx("button", { type: "submit", className: "room-front__go", "data-testid": "room-create-submit", disabled: busy || !ready, children: "Create room" }), error !== null && (_jsx("p", { className: "ct-error rooms__error", role: "alert", "data-testid": "room-create-error", children: error }))] }) }) }));
313
+ }
@@ -0,0 +1,134 @@
1
+ import { type ReactNode } from 'react';
2
+ import type { RoomChrome as RoomChromeComponent, RoomChromeToolbar } from '@wolffm/watchparty-ui/room-chrome';
3
+ import '@wolffm/watchparty-ui/room-chrome.css';
4
+ import { type Theme } from '@wolffm/themes';
5
+ type RoomChromeType = typeof RoomChromeComponent;
6
+ /** Starts loading the chrome's chunk, once per page; a front door may call it to fetch it early. */
7
+ export declare function loadRoomChrome(): Promise<RoomChromeType>;
8
+ /**
9
+ * The page's resolved theme, handed to the chrome as-is.
10
+ *
11
+ * ## Why the two disagreed, diagnosed rather than assumed (w20 §E)
12
+ *
13
+ * `RoomChrome` takes an optional `theme` prop. Left unset — which is what this
14
+ * file did until w20 — it resolves its OWN default from ITS OWN internal
15
+ * store, entirely independent of `HadokuThemeRoot` (quoted in full below).
16
+ * Measured live (a stub-`whoami` build served
17
+ * locally, `#/match/…`, no saved theme in either storage): the page resolved
18
+ * `data-theme="light"` on `.cardtable-chrome` while `.wp-room-chrome` sat at
19
+ * `data-theme="dark"` — two independent defaults, not a shared one that drifted.
20
+ * Passing our theme through removes the second default entirely; they cannot
21
+ * disagree once there is only one source.
22
+ *
23
+ * ## Why this casts instead of validating (w22 §G, found by hadoku_site)
24
+ *
25
+ * This used to filter through `THEMES` and answer `undefined` for a name it did
26
+ * not recognise. `undefined` is not a neutral value here — it is precisely what
27
+ * sends the chrome back to that second default, so the filter reintroduced the
28
+ * split-theme bug in the one case it was written to protect against.
29
+ *
30
+ * That case is unreachable today: one `@wolffm/themes` install (5.8.6), and
31
+ * `room-chrome.d.ts:3` imports `Theme` from it, so there is a single union. But
32
+ * watchparty-ui takes themes as a regular **dependency** (`^5.8.5`), not a peer,
33
+ * so a host outside that range resolves a second nested copy and two distinct
34
+ * unions exist. There, passing an unrecognised name through is strictly better
35
+ * than dropping it, and the shipped code is why — read out of the installed
36
+ * bundle, its fallback is:
37
+ *
38
+ * function Do(e) { if (e) return e; const t = ze().theme;
39
+ * return t && tn.includes(t) ? t : "dark"; }
40
+ *
41
+ * The prop is honoured VERBATIM, unvalidated, and lands on `data-theme` of the
42
+ * chrome's own `aside.wp-room-chrome` — never on the host document. Only a
43
+ * FALSY prop makes the chrome consult its own store and then hard-code `dark`.
44
+ * So an unknown name resolves against whichever `[data-theme=…]` palettes are
45
+ * loaded and otherwise falls to a neutral light base; `undefined` resolves to
46
+ * an actively wrong `dark`. `undefined` is the only value that cannot be
47
+ * ignored.
48
+ *
49
+ * Corrected against the installed bundle rather than taken on trust: the §G brief said
50
+ * `room-chrome.css` "styles only its own light/dark internals". It does not —
51
+ * it ships all 18 `[data-theme=…]` blocks under `@scope (.wp-room-chrome)`,
52
+ * with `:scope,:scope[data-theme=light]` as the fallback rule, the same 18 the
53
+ * host's `@wolffm/themes/src/style.css` carries unscoped. That changes the
54
+ * reason, not the fix: what makes the pass-through work is `if (e) return e`,
55
+ * not a gap in the chrome's own palettes.
56
+ *
57
+ * ## The trap, for whoever edits this next
58
+ *
59
+ * The cast is load-bearing twice, and only one half announces itself.
60
+ * `theme={theme}` fails typecheck — TS2322, because `useHadokuTheme()` types
61
+ * `theme` as `string` (the picker's families are data-driven) — which is what
62
+ * sends people looking for a validator in the first place. But
63
+ * `theme={filtered ?? undefined}` compiles cleanly and IS the defect. Only the
64
+ * type error is loud; the wrong fix is silent. The `Theme` return type below,
65
+ * with no `| undefined`, is what makes the silent half loud too: a re-added
66
+ * `?? undefined` stops compiling here instead of shipping a chrome that resolves
67
+ * its own theme.
68
+ */
69
+ export declare function watchpartyTheme(theme: string): Theme;
70
+ /**
71
+ * A room key for one of our pods or matches, or null when the id is not a
72
+ * shape watchparty will accept.
73
+ *
74
+ * Null means "render the table with no room" — never a guessed or coerced key,
75
+ * because two ids that collapse to the same key would put two unrelated groups
76
+ * in one room, and they would each see the other's chat.
77
+ */
78
+ export declare function roomKeyFor(id: string): string | null;
79
+ /**
80
+ * This app's own origin, on whatever host serves this page — never
81
+ * hardcoded, so PPE (built with `CARDTABLE_BASE_PREFIX=/cardtable-ppe`) gets
82
+ * PPE's own origin rather than prod's. The same derivation
83
+ * `room/socket-options.ts`'s `defaultSocketPath` uses for the draft socket's
84
+ * path, here producing an ORIGIN string: `RoomChrome` derives its socket
85
+ * path, `/cardtable[-ppe]/socket.io/`, from its pathname, so passing the
86
+ * bare base is enough — no `roomSocketPath` override needed.
87
+ */
88
+ export declare function appOrigin(): string;
89
+ /**
90
+ * Wraps `children` in watchparty's room when there is a room to be in.
91
+ *
92
+ * Renders the children alone when there is no room id or when whoami failed. A
93
+ * table without chat is a degraded room; a table that will not draw because
94
+ * chat is down is an outage.
95
+ *
96
+ * The children mount ONCE, whatever the chrome does around them. Remounted, they
97
+ * lose everything they hold and open their sockets again: a match opened from a
98
+ * link joined on two sockets and hung up the first, and when the hang-up beat the
99
+ * second join the server saw the seat leave (`e2e/w69-name-card.spec.ts`, "nobody
100
+ * disconnected"); a joiner's room screen, drawn before its join and wrapped once
101
+ * the join let the chat in (`App.tsx`'s `useJoined`), dropped an open Room
102
+ * settings and connected its draft socket twice (`e2e/w83b-draft-rope.spec.ts`).
103
+ * So they are rendered through a portal from one place in this component's tree,
104
+ * into a node that moves into the chrome when it draws and out when it goes. That
105
+ * node and the slot holding it are both `.chrome-slot` (`display: contents`), and
106
+ * the chrome's rules for its content's own child reach through exactly those two
107
+ * (`@hadoku/ui-shell`'s `chrome.css`; `display: contents` is also set on them here, for a game
108
+ * that loads no such sheet). While whoami or the chrome's chunk is in flight on a room's route,
109
+ * before they have first mounted, they wait for it, showing `fallback`: their first frame is already
110
+ * inside. After that, they show bare while the chrome is not drawn.
111
+ */
112
+ export declare function RoomShell({ roomId, collapsible, inert, fallback, requireIdentified, toolbar, pending, children, }: {
113
+ /** The room this viewer is in: the chat and roster the chrome joins, and where their avatar is asserted. */
114
+ roomId: string | null;
115
+ /** `false` keeps the chat open with no Hide chat button — the room's lobby,
116
+ * where the chat is the point. A viewer's saved collapse is ignored there,
117
+ * not cleared, so the match still opens the way they left it. */
118
+ collapsible?: boolean;
119
+ /** Behind a question the page must answer first (`./SessionPrompt.tsx`): the chat cannot be reached. */
120
+ inert?: boolean;
121
+ /** What a room's route shows while it waits, before its content first mounts. Default: nothing. */
122
+ fallback?: ReactNode;
123
+ /**
124
+ * No chrome for a viewer the fleet could not name (`ANON_USER_ID`): the room's server turns an
125
+ * anonymous join away, and a chat column that can only fail reads as a broken room. Default off.
126
+ */
127
+ requireIdentified?: boolean;
128
+ /** The chat's toolbar on a page with no top bar (`../chrome/toolbarPage.tsx`): drawn only while a screen has opted in. */
129
+ toolbar?: RoomChromeToolbar;
130
+ /** The page does not know its room yet: `roomId` is null for now, and says nothing about whether a chat will draw. */
131
+ pending?: boolean;
132
+ children: ReactNode;
133
+ }): import("react").JSX.Element;
134
+ export {};