@mostra/react 0.10.0 → 0.12.0
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.
- package/dist/form.js +1 -1
- package/dist/{hooks-C0SVZDl4.js → hooks-BfV824_7.js} +362 -20
- package/dist/hooks-BfV824_7.js.map +1 -0
- package/dist/index.d.ts +115 -36
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +100 -3
- package/dist/index.js.map +1 -1
- package/dist/{mount-BCj41qky.js → mount-DmfrLZvk.js} +2 -2
- package/dist/{mount-BCj41qky.js.map → mount-DmfrLZvk.js.map} +1 -1
- package/dist/router.js +1 -1
- package/package.json +4 -4
- package/src/hooks.ts +33 -10
- package/src/index.ts +17 -1
- package/src/runtime/server-client.ts +3 -1
- package/src/runtime/store.ts +27 -1
- package/src/runtime/team.ts +388 -0
- package/src/runtime/transport.ts +33 -0
- package/src/team-hooks.ts +151 -0
- package/dist/hooks-C0SVZDl4.js.map +0 -1
|
@@ -0,0 +1,388 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The client side of team features (D168; CO-03, CO-04): the roster as this page may see it, and
|
|
3
|
+
* who is present with the cursors and selections they share. Both are ephemeral: read on demand,
|
|
4
|
+
* followed through the page's stream, and never journaled or kept. A page that never calls the
|
|
5
|
+
* hooks never asks for either, so it is never sent one.
|
|
6
|
+
*
|
|
7
|
+
* - The roster is read when the first `useRespondents` mounts and every 20 s while one is mounted
|
|
8
|
+
* (the gateway follows it for a minute), and the stream brings each change between.
|
|
9
|
+
* - Presence starts when the first `usePresence` mounts: the page posts at most 10 updates a second
|
|
10
|
+
* (the latest wins), every 10 s even when nothing changed, and leaves when the last one unmounts
|
|
11
|
+
* or the page goes away, joining again when the browser brings it back from its back/forward
|
|
12
|
+
* cache. Cursor and selection are shared only while a mounted hook asks for them.
|
|
13
|
+
* - Every presence post carries the page's own count (`seq`), a leave included: the gateway takes
|
|
14
|
+
* no post older than the newest it has, so an update still in flight when the page left never
|
|
15
|
+
* brings it back, and the page takes no answer to a post it made before its last leave.
|
|
16
|
+
*/
|
|
17
|
+
import type {
|
|
18
|
+
PresenceCursor,
|
|
19
|
+
PresenceRequest,
|
|
20
|
+
PresenceSelection,
|
|
21
|
+
PresenceState,
|
|
22
|
+
RosterForPage,
|
|
23
|
+
} from "@mostra/protocol";
|
|
24
|
+
import { MostraError } from "./errors.ts";
|
|
25
|
+
import type { Transport } from "./transport.ts";
|
|
26
|
+
|
|
27
|
+
/** How often the roster is read again while a hook shows it (the gateway follows it a minute). */
|
|
28
|
+
export const RESPONDENTS_RENEW_MS = 20_000;
|
|
29
|
+
|
|
30
|
+
/** How often a present page posts though nothing changed (the gateway keeps it 30 s). */
|
|
31
|
+
export const PRESENCE_HEARTBEAT_MS = 10_000;
|
|
32
|
+
|
|
33
|
+
/** The shortest time between two presence posts: at most 10 a second (the gateway allows 20). */
|
|
34
|
+
export const PRESENCE_THROTTLE_MS = 100;
|
|
35
|
+
|
|
36
|
+
/** Timers, injectable for tests. */
|
|
37
|
+
interface Timers {
|
|
38
|
+
setTimeout(fn: () => void, ms: number): unknown;
|
|
39
|
+
clearTimeout(handle: unknown): void;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** What a mounted `usePresence` shares. */
|
|
43
|
+
interface Sharing {
|
|
44
|
+
readonly cursor: boolean;
|
|
45
|
+
readonly selection: boolean;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The page's team state: its roster and its presence. */
|
|
49
|
+
export class TeamClient {
|
|
50
|
+
readonly #transport: Transport | undefined;
|
|
51
|
+
readonly #viewId: string | undefined;
|
|
52
|
+
readonly #timers: Timers;
|
|
53
|
+
readonly #listeners = new Set<() => void>();
|
|
54
|
+
#version = 0;
|
|
55
|
+
|
|
56
|
+
#roster: RosterForPage | undefined;
|
|
57
|
+
#rosterError: MostraError | undefined;
|
|
58
|
+
#rosterWatchers = 0;
|
|
59
|
+
#rosterTimer: unknown;
|
|
60
|
+
|
|
61
|
+
#presence: PresenceState | undefined;
|
|
62
|
+
readonly #sharing = new Map<symbol, Sharing>();
|
|
63
|
+
#cursor: PresenceCursor | null = null;
|
|
64
|
+
#selection: PresenceSelection | null = null;
|
|
65
|
+
/** What the gateway was last told, so an unchanged state is sent only as a heartbeat. */
|
|
66
|
+
#sent: { cursor: string; selection: string } = { cursor: "null", selection: "null" };
|
|
67
|
+
#sendTimer: unknown;
|
|
68
|
+
#heartbeat: unknown;
|
|
69
|
+
#lastSend = 0;
|
|
70
|
+
#inFlight = false;
|
|
71
|
+
#again = false;
|
|
72
|
+
#blockedUntil = 0;
|
|
73
|
+
/** This page's count of its presence posts (`seq`), a leave included. */
|
|
74
|
+
#seq = 0;
|
|
75
|
+
/** The count of the page's last leave: an answer to an earlier post is no longer its own. */
|
|
76
|
+
#leftAt = -1;
|
|
77
|
+
#stopTracking: (() => void) | undefined;
|
|
78
|
+
|
|
79
|
+
constructor(options: {
|
|
80
|
+
readonly transport?: Transport;
|
|
81
|
+
readonly viewId?: string;
|
|
82
|
+
readonly timers?: Timers;
|
|
83
|
+
}) {
|
|
84
|
+
this.#transport = options.transport;
|
|
85
|
+
this.#viewId = options.viewId;
|
|
86
|
+
this.#timers = options.timers ?? {
|
|
87
|
+
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
88
|
+
clearTimeout: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Whether this page can reach the gateway's team routes (a live page; not a static export). */
|
|
93
|
+
get available(): boolean {
|
|
94
|
+
return this.#transport?.respondents !== undefined && this.#viewId !== undefined;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
subscribe = (listener: () => void): (() => void) => {
|
|
98
|
+
this.#listeners.add(listener);
|
|
99
|
+
return () => this.#listeners.delete(listener);
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
version = (): number => this.#version;
|
|
103
|
+
|
|
104
|
+
#changed(): void {
|
|
105
|
+
this.#version += 1;
|
|
106
|
+
for (const listener of [...this.#listeners]) listener();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// ── The roster ─────────────────────────────────────────────────────────────────────────
|
|
110
|
+
|
|
111
|
+
roster(): RosterForPage | undefined {
|
|
112
|
+
return this.#roster;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
rosterError(): MostraError | undefined {
|
|
116
|
+
return this.#rosterError;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** A `useRespondents` mounted: reads the roster now and keeps it followed; returns the stop. */
|
|
120
|
+
watchRespondents(): () => void {
|
|
121
|
+
this.#rosterWatchers += 1;
|
|
122
|
+
if (this.#rosterWatchers === 1) void this.#readRoster();
|
|
123
|
+
let stopped = false;
|
|
124
|
+
return () => {
|
|
125
|
+
if (stopped) return;
|
|
126
|
+
stopped = true;
|
|
127
|
+
this.#rosterWatchers -= 1;
|
|
128
|
+
if (this.#rosterWatchers === 0 && this.#rosterTimer !== undefined) {
|
|
129
|
+
this.#timers.clearTimeout(this.#rosterTimer);
|
|
130
|
+
this.#rosterTimer = undefined;
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async #readRoster(): Promise<void> {
|
|
136
|
+
if (this.#rosterTimer !== undefined) this.#timers.clearTimeout(this.#rosterTimer);
|
|
137
|
+
this.#rosterTimer = undefined;
|
|
138
|
+
const transport = this.#transport;
|
|
139
|
+
if (!transport?.respondents || this.#viewId === undefined || this.#rosterWatchers === 0) return;
|
|
140
|
+
try {
|
|
141
|
+
this.#roster = await transport.respondents({ viewId: this.#viewId });
|
|
142
|
+
this.#rosterError = undefined;
|
|
143
|
+
} catch (error) {
|
|
144
|
+
if (error instanceof MostraError) this.#rosterError = error;
|
|
145
|
+
}
|
|
146
|
+
this.#changed();
|
|
147
|
+
if (this.#rosterWatchers > 0) {
|
|
148
|
+
this.#rosterTimer = this.#timers.setTimeout(
|
|
149
|
+
() => void this.#readRoster(),
|
|
150
|
+
RESPONDENTS_RENEW_MS,
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// ── Presence ───────────────────────────────────────────────────────────────────────────
|
|
156
|
+
|
|
157
|
+
presence(): PresenceState | undefined {
|
|
158
|
+
return this.#presence;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** A `usePresence` mounted with what it shares: joins presence; returns the leave. */
|
|
162
|
+
joinPresence(sharing: Sharing): () => void {
|
|
163
|
+
const id = Symbol("presence");
|
|
164
|
+
this.#sharing.set(id, sharing);
|
|
165
|
+
this.#retrack();
|
|
166
|
+
this.#schedule(0);
|
|
167
|
+
return () => {
|
|
168
|
+
if (!this.#sharing.delete(id)) return;
|
|
169
|
+
this.#retrack();
|
|
170
|
+
if (this.#sharing.size === 0) this.#leave(false);
|
|
171
|
+
else this.#schedule(0);
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
#shares(): Sharing {
|
|
176
|
+
let cursor = false;
|
|
177
|
+
let selection = false;
|
|
178
|
+
for (const entry of this.#sharing.values()) {
|
|
179
|
+
cursor ||= entry.cursor;
|
|
180
|
+
selection ||= entry.selection;
|
|
181
|
+
}
|
|
182
|
+
return { cursor, selection };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Follows the pointer and the selection as far as a mounted hook shares them. */
|
|
186
|
+
#retrack(): void {
|
|
187
|
+
this.#stopTracking?.();
|
|
188
|
+
this.#stopTracking = undefined;
|
|
189
|
+
const { cursor, selection } = this.#shares();
|
|
190
|
+
if (!cursor) this.#cursor = null;
|
|
191
|
+
if (!selection) this.#selection = null;
|
|
192
|
+
if (typeof document === "undefined" || this.#sharing.size === 0) return;
|
|
193
|
+
const stops: (() => void)[] = [];
|
|
194
|
+
if (cursor) {
|
|
195
|
+
const move = (event: PointerEvent): void => {
|
|
196
|
+
this.#cursor = { x: Math.round(event.pageX), y: Math.round(event.pageY) };
|
|
197
|
+
this.#schedule();
|
|
198
|
+
};
|
|
199
|
+
const away = (): void => {
|
|
200
|
+
this.#cursor = null;
|
|
201
|
+
this.#schedule();
|
|
202
|
+
};
|
|
203
|
+
document.addEventListener("pointermove", move, { passive: true });
|
|
204
|
+
document.documentElement.addEventListener("pointerleave", away);
|
|
205
|
+
stops.push(() => {
|
|
206
|
+
document.removeEventListener("pointermove", move);
|
|
207
|
+
document.documentElement.removeEventListener("pointerleave", away);
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
if (selection) {
|
|
211
|
+
const read = (): void => {
|
|
212
|
+
this.#selection = selectionNow();
|
|
213
|
+
this.#schedule();
|
|
214
|
+
};
|
|
215
|
+
document.addEventListener("focusin", read);
|
|
216
|
+
document.addEventListener("focusout", read);
|
|
217
|
+
document.addEventListener("selectionchange", read);
|
|
218
|
+
stops.push(() => {
|
|
219
|
+
document.removeEventListener("focusin", read);
|
|
220
|
+
document.removeEventListener("focusout", read);
|
|
221
|
+
document.removeEventListener("selectionchange", read);
|
|
222
|
+
});
|
|
223
|
+
}
|
|
224
|
+
// Leaving with the page: a closed tab is gone at once, not when its lease ends. A page the
|
|
225
|
+
// browser brings back from its back/forward cache, hooks still mounted, joins again (Opus
|
|
226
|
+
// review 8): its old state is stale, and nothing else would post for it.
|
|
227
|
+
const gone = (): void => this.#leave(true);
|
|
228
|
+
const back = (event: PageTransitionEvent): void => {
|
|
229
|
+
if (!event.persisted || this.#sharing.size === 0) return;
|
|
230
|
+
this.#presence = undefined;
|
|
231
|
+
this.#changed();
|
|
232
|
+
this.#schedule(0);
|
|
233
|
+
};
|
|
234
|
+
window.addEventListener("pagehide", gone);
|
|
235
|
+
window.addEventListener("pageshow", back);
|
|
236
|
+
stops.push(() => {
|
|
237
|
+
window.removeEventListener("pagehide", gone);
|
|
238
|
+
window.removeEventListener("pageshow", back);
|
|
239
|
+
});
|
|
240
|
+
this.#stopTracking = () => {
|
|
241
|
+
for (const stop of stops) stop();
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** Posts soon: at once when the throttle allows, else when it does; the latest state wins. */
|
|
246
|
+
#schedule(delay?: number): void {
|
|
247
|
+
if (!this.#transport?.presence || this.#viewId === undefined || this.#sharing.size === 0)
|
|
248
|
+
return;
|
|
249
|
+
if (this.#sendTimer !== undefined) return;
|
|
250
|
+
const now = Date.now();
|
|
251
|
+
const wait = Math.max(
|
|
252
|
+
delay ?? 0,
|
|
253
|
+
this.#lastSend + PRESENCE_THROTTLE_MS - now,
|
|
254
|
+
this.#blockedUntil - now,
|
|
255
|
+
0,
|
|
256
|
+
);
|
|
257
|
+
this.#sendTimer = this.#timers.setTimeout(() => {
|
|
258
|
+
this.#sendTimer = undefined;
|
|
259
|
+
void this.#send();
|
|
260
|
+
}, wait);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
async #send(): Promise<void> {
|
|
264
|
+
const transport = this.#transport;
|
|
265
|
+
if (!transport?.presence || this.#viewId === undefined || this.#sharing.size === 0) return;
|
|
266
|
+
if (this.#inFlight) {
|
|
267
|
+
this.#again = true;
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
this.#inFlight = true;
|
|
271
|
+
this.#lastSend = Date.now();
|
|
272
|
+
const cursor = JSON.stringify(this.#cursor);
|
|
273
|
+
const selection = JSON.stringify(this.#selection);
|
|
274
|
+
this.#seq += 1;
|
|
275
|
+
const seq = this.#seq;
|
|
276
|
+
const request: PresenceRequest = {
|
|
277
|
+
viewId: this.#viewId,
|
|
278
|
+
...(cursor !== this.#sent.cursor ? { cursor: this.#cursor } : {}),
|
|
279
|
+
...(selection !== this.#sent.selection ? { selection: this.#selection } : {}),
|
|
280
|
+
seq,
|
|
281
|
+
};
|
|
282
|
+
try {
|
|
283
|
+
const answer = await transport.presence(request);
|
|
284
|
+
// The page left while this post was on its way: its answer is no longer the page's.
|
|
285
|
+
if (this.#leftAt > seq) return;
|
|
286
|
+
this.#presence = answer;
|
|
287
|
+
this.#sent = { cursor, selection };
|
|
288
|
+
this.#changed();
|
|
289
|
+
} catch (error) {
|
|
290
|
+
// Past the rate, wait as the gateway says; a network failure tries again at the heartbeat.
|
|
291
|
+
if (error instanceof MostraError && error.code === "MOSTRA_TEAM_PRESENCE_RATE_LIMITED") {
|
|
292
|
+
this.#blockedUntil = Date.now() + 1_000;
|
|
293
|
+
this.#again = true;
|
|
294
|
+
}
|
|
295
|
+
} finally {
|
|
296
|
+
this.#inFlight = false;
|
|
297
|
+
}
|
|
298
|
+
if (this.#leftAt > seq) return;
|
|
299
|
+
if (this.#heartbeat !== undefined) this.#timers.clearTimeout(this.#heartbeat);
|
|
300
|
+
this.#heartbeat =
|
|
301
|
+
this.#sharing.size > 0
|
|
302
|
+
? this.#timers.setTimeout(() => this.#schedule(0), PRESENCE_HEARTBEAT_MS)
|
|
303
|
+
: undefined;
|
|
304
|
+
if (
|
|
305
|
+
this.#again ||
|
|
306
|
+
JSON.stringify(this.#cursor) !== this.#sent.cursor ||
|
|
307
|
+
JSON.stringify(this.#selection) !== this.#sent.selection
|
|
308
|
+
) {
|
|
309
|
+
this.#again = false;
|
|
310
|
+
this.#schedule();
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
#leave(closing: boolean): void {
|
|
315
|
+
for (const timer of [this.#sendTimer, this.#heartbeat]) {
|
|
316
|
+
if (timer !== undefined) this.#timers.clearTimeout(timer);
|
|
317
|
+
}
|
|
318
|
+
this.#sendTimer = undefined;
|
|
319
|
+
this.#heartbeat = undefined;
|
|
320
|
+
this.#sent = { cursor: "null", selection: "null" };
|
|
321
|
+
this.#again = false;
|
|
322
|
+
const transport = this.#transport;
|
|
323
|
+
if (!transport?.presence || this.#viewId === undefined) return;
|
|
324
|
+
this.#seq += 1;
|
|
325
|
+
this.#leftAt = this.#seq;
|
|
326
|
+
void transport
|
|
327
|
+
.presence({ viewId: this.#viewId, leave: true, seq: this.#seq }, { keepalive: closing })
|
|
328
|
+
.catch(() => undefined);
|
|
329
|
+
if (!closing) {
|
|
330
|
+
this.#presence = undefined;
|
|
331
|
+
this.#changed();
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** The stream reconnected: read the roster again and post presence, since messages were lost. */
|
|
336
|
+
resync(): void {
|
|
337
|
+
if (this.#rosterWatchers > 0) void this.#readRoster();
|
|
338
|
+
if (this.#sharing.size > 0) this.#schedule(0);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** One ephemeral message of the page's stream. */
|
|
342
|
+
receive(
|
|
343
|
+
message:
|
|
344
|
+
| { readonly kind: "respondents"; readonly respondents: RosterForPage }
|
|
345
|
+
| {
|
|
346
|
+
readonly kind: "presence";
|
|
347
|
+
readonly presence: PresenceState;
|
|
348
|
+
},
|
|
349
|
+
): void {
|
|
350
|
+
if (message.kind === "respondents") {
|
|
351
|
+
if (this.#rosterWatchers === 0) return;
|
|
352
|
+
this.#roster = message.respondents;
|
|
353
|
+
} else {
|
|
354
|
+
if (this.#sharing.size === 0) return;
|
|
355
|
+
this.#presence = message.presence;
|
|
356
|
+
}
|
|
357
|
+
this.#changed();
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
stop(): void {
|
|
361
|
+
this.#stopTracking?.();
|
|
362
|
+
for (const timer of [this.#sendTimer, this.#heartbeat, this.#rosterTimer]) {
|
|
363
|
+
if (timer !== undefined) this.#timers.clearTimeout(timer);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* The viewer's selection as presence shares it: the focused element's `data-presence-id`, `id` or
|
|
370
|
+
* `name` (the nearest one that has one), and in a text input its selected range.
|
|
371
|
+
*/
|
|
372
|
+
function selectionNow(): PresenceSelection | null {
|
|
373
|
+
const active = document.activeElement;
|
|
374
|
+
if (!active || active === document.body) return null;
|
|
375
|
+
const named = active.closest("[data-presence-id]");
|
|
376
|
+
const element =
|
|
377
|
+
named?.getAttribute("data-presence-id") ??
|
|
378
|
+
(active.id !== "" ? active.id : undefined) ??
|
|
379
|
+
active.getAttribute("name") ??
|
|
380
|
+
undefined;
|
|
381
|
+
if (element === undefined || element === "") return null;
|
|
382
|
+
const input = active as HTMLInputElement | HTMLTextAreaElement;
|
|
383
|
+
const range =
|
|
384
|
+
typeof input.selectionStart === "number" && typeof input.selectionEnd === "number"
|
|
385
|
+
? { start: input.selectionStart, end: input.selectionEnd }
|
|
386
|
+
: {};
|
|
387
|
+
return { element: element.slice(0, 256), ...range };
|
|
388
|
+
}
|
package/src/runtime/transport.ts
CHANGED
|
@@ -16,6 +16,9 @@ import {
|
|
|
16
16
|
type LiveUpdate,
|
|
17
17
|
type MutationResult,
|
|
18
18
|
type PollResult,
|
|
19
|
+
type PresenceRequest,
|
|
20
|
+
type PresenceState,
|
|
21
|
+
type RosterForPage,
|
|
19
22
|
type RunAttachRequest,
|
|
20
23
|
type RunDelta,
|
|
21
24
|
type RunRequest,
|
|
@@ -72,6 +75,16 @@ export interface Transport {
|
|
|
72
75
|
cancelRun?(runId: string, viewId: string): Promise<RunState>;
|
|
73
76
|
/** Reads live sources and keeps them produced for a minute (D56). */
|
|
74
77
|
live?(request: LiveRequest): Promise<{ readonly sources: readonly LiveState[] }>;
|
|
78
|
+
/** Reads the roster as the page may see it, and follows it for a minute (D168). */
|
|
79
|
+
respondents?(request: { readonly viewId: string }): Promise<RosterForPage>;
|
|
80
|
+
/**
|
|
81
|
+
* Joins presence, shares a cursor and a selection, or leaves (D168); `keepalive` lets a leave
|
|
82
|
+
* outlive the page.
|
|
83
|
+
*/
|
|
84
|
+
presence?(
|
|
85
|
+
request: PresenceRequest,
|
|
86
|
+
options?: { readonly keepalive?: boolean },
|
|
87
|
+
): Promise<PresenceState>;
|
|
75
88
|
}
|
|
76
89
|
|
|
77
90
|
/** The longest body `fetch` sends with `keepalive` (the Fetch standard's 64 KiB budget). */
|
|
@@ -280,6 +293,17 @@ export class HttpTransport implements Transport {
|
|
|
280
293
|
return this.#post("/live", request) as Promise<{ sources: LiveState[] }>;
|
|
281
294
|
}
|
|
282
295
|
|
|
296
|
+
respondents(request: { readonly viewId: string }): Promise<RosterForPage> {
|
|
297
|
+
return this.#post("/respondents", request) as Promise<RosterForPage>;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
presence(
|
|
301
|
+
request: PresenceRequest,
|
|
302
|
+
options?: { readonly keepalive?: boolean },
|
|
303
|
+
): Promise<PresenceState> {
|
|
304
|
+
return this.#post("/presence", request, options?.keepalive === true) as Promise<PresenceState>;
|
|
305
|
+
}
|
|
306
|
+
|
|
283
307
|
subscribe(cursor: string | undefined, handlers: StreamHandlers): () => void {
|
|
284
308
|
let closed = false;
|
|
285
309
|
let last = cursor;
|
|
@@ -378,6 +402,15 @@ export class HttpTransport implements Transport {
|
|
|
378
402
|
const live = JSON.parse((event as MessageEvent<string>).data) as LiveUpdate;
|
|
379
403
|
handlers.onEphemeral?.({ kind: "live", live });
|
|
380
404
|
});
|
|
405
|
+
// The roster and presence (D168) reach only a page that asked for them.
|
|
406
|
+
source.addEventListener("respondents", (event) => {
|
|
407
|
+
const respondents = JSON.parse((event as MessageEvent<string>).data) as RosterForPage;
|
|
408
|
+
handlers.onEphemeral?.({ kind: "respondents", respondents });
|
|
409
|
+
});
|
|
410
|
+
source.addEventListener("presence", (event) => {
|
|
411
|
+
const presence = JSON.parse((event as MessageEvent<string>).data) as PresenceState;
|
|
412
|
+
handlers.onEphemeral?.({ kind: "presence", presence });
|
|
413
|
+
});
|
|
381
414
|
source.addEventListener("error", () => {
|
|
382
415
|
if (closed) return;
|
|
383
416
|
failures += 1;
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Team hooks (D121, D168; INTERFACES §2.3): who is expected to answer and where each stands, and
|
|
5
|
+
* who is here now with the cursor and selection they share. Both are data for the page to show in
|
|
6
|
+
* its own design: the shell draws nothing (D121). What a viewer sees of others is the artifact's
|
|
7
|
+
* `team.visibility` (`private` unless the manifest opts in); the artifact's owner sees everyone.
|
|
8
|
+
* Outside a live page (a static export) both say `unavailable`.
|
|
9
|
+
*/
|
|
10
|
+
import type {
|
|
11
|
+
PresencePeer,
|
|
12
|
+
RespondentForPage,
|
|
13
|
+
RosterCounts,
|
|
14
|
+
TeamVisibility,
|
|
15
|
+
} from "@mostra/protocol";
|
|
16
|
+
import { useEffect, useMemo, useSyncExternalStore } from "react";
|
|
17
|
+
import { useStore } from "./hooks.ts";
|
|
18
|
+
|
|
19
|
+
export type {
|
|
20
|
+
Peer,
|
|
21
|
+
PresenceCursor,
|
|
22
|
+
PresencePeer,
|
|
23
|
+
PresenceSelection,
|
|
24
|
+
RespondentForPage,
|
|
25
|
+
RespondentStatus,
|
|
26
|
+
RosterCounts,
|
|
27
|
+
TeamVisibility,
|
|
28
|
+
} from "@mostra/protocol";
|
|
29
|
+
|
|
30
|
+
/** What `useRespondents` returns (CO-03). */
|
|
31
|
+
export interface Respondents {
|
|
32
|
+
/** `loading` until the roster first arrives; `unavailable` outside a live page. */
|
|
33
|
+
readonly status: "loading" | "ready" | "unavailable";
|
|
34
|
+
/** What viewers see of each other on this artifact (its manifest's `team.visibility`). */
|
|
35
|
+
readonly visibility?: TeamVisibility;
|
|
36
|
+
/** Whether this viewer is the artifact's owner, who sees everyone whatever the visibility. */
|
|
37
|
+
readonly owner: boolean;
|
|
38
|
+
/** The roster's round: 1 under `once`; under `epochs`, one more after each time everyone answered. */
|
|
39
|
+
readonly round: number;
|
|
40
|
+
/** This viewer's own entry, when they are an expected respondent. */
|
|
41
|
+
readonly self?: RespondentForPage;
|
|
42
|
+
/** How many stand where; under `counts` and `names` visibility, and for the owner. */
|
|
43
|
+
readonly counts?: RosterCounts;
|
|
44
|
+
/** Whether everyone expected answered in this round; under `counts` and `names`, and for the owner. */
|
|
45
|
+
readonly complete?: boolean;
|
|
46
|
+
/** Every expected respondent, in the order they joined; under `names`, and for the owner. */
|
|
47
|
+
readonly respondents: readonly RespondentForPage[];
|
|
48
|
+
/** Why the roster couldn't be read, when it couldn't. */
|
|
49
|
+
readonly error?: { readonly code: string; readonly message: string };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The people this artifact expects answers from, and where each stands in the round: not opened,
|
|
54
|
+
* drafting or submitted (CO-03). It follows changes as they happen.
|
|
55
|
+
*
|
|
56
|
+
* ```tsx
|
|
57
|
+
* const { counts, respondents } = useRespondents();
|
|
58
|
+
* // "3 of 5 answered", and who is drafting, in the page's own design.
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
61
|
+
export function useRespondents(): Respondents {
|
|
62
|
+
const store = useStore();
|
|
63
|
+
const team = store.team;
|
|
64
|
+
useSyncExternalStore(team.subscribe, team.version, team.version);
|
|
65
|
+
useEffect(() => (team.available ? team.watchRespondents() : undefined), [team]);
|
|
66
|
+
const roster = team.roster();
|
|
67
|
+
const error = team.rosterError();
|
|
68
|
+
return useMemo((): Respondents => {
|
|
69
|
+
if (!team.available) return { status: "unavailable", owner: false, round: 1, respondents: [] };
|
|
70
|
+
if (!roster) {
|
|
71
|
+
return {
|
|
72
|
+
status: "loading",
|
|
73
|
+
owner: false,
|
|
74
|
+
round: 1,
|
|
75
|
+
respondents: [],
|
|
76
|
+
...(error ? { error: { code: error.code, message: error.message } } : {}),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
return {
|
|
80
|
+
status: "ready",
|
|
81
|
+
visibility: roster.visibility,
|
|
82
|
+
owner: roster.owner,
|
|
83
|
+
round: roster.round,
|
|
84
|
+
...(roster.self ? { self: roster.self } : {}),
|
|
85
|
+
...(roster.counts ? { counts: roster.counts } : {}),
|
|
86
|
+
...(roster.complete !== undefined ? { complete: roster.complete } : {}),
|
|
87
|
+
respondents: roster.respondents ?? [],
|
|
88
|
+
...(error ? { error: { code: error.code, message: error.message } } : {}),
|
|
89
|
+
};
|
|
90
|
+
}, [team, roster, error]);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** What `usePresence` shares of this viewer (CO-04): nothing unless the page asks. */
|
|
94
|
+
export interface PresenceOptions {
|
|
95
|
+
/** Share this viewer's pointer, in the page's document coordinates. */
|
|
96
|
+
readonly cursor?: boolean;
|
|
97
|
+
/**
|
|
98
|
+
* Share where this viewer is: the focused element's `data-presence-id`, `id` or `name`, and the
|
|
99
|
+
* selected range in a text input.
|
|
100
|
+
*/
|
|
101
|
+
readonly selection?: boolean;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** What `usePresence` returns (CO-04). */
|
|
105
|
+
export interface Presence {
|
|
106
|
+
/** `joining` until the first answer; `unavailable` outside a live page. */
|
|
107
|
+
readonly status: "joining" | "present" | "unavailable";
|
|
108
|
+
/** What viewers see of each other on this artifact (its manifest's `team.visibility`). */
|
|
109
|
+
readonly visibility?: TeamVisibility;
|
|
110
|
+
/** This viewer, as others see them. */
|
|
111
|
+
readonly self?: PresencePeer;
|
|
112
|
+
/** Everyone else here now, most recently active first; under `names`, and for the owner. */
|
|
113
|
+
readonly others: readonly PresencePeer[];
|
|
114
|
+
/** How many others are here now; under `counts` and `names`, and for the owner. */
|
|
115
|
+
readonly count?: number;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Who is viewing this artifact now (CO-04), as data for the page to draw. With `cursor` and
|
|
120
|
+
* `selection`, this viewer shares their pointer and where they are, ephemerally: never stored,
|
|
121
|
+
* at most 10 updates a second, gone when they leave. Without the hook, nothing is shared.
|
|
122
|
+
*
|
|
123
|
+
* ```tsx
|
|
124
|
+
* const { others } = usePresence({ cursor: true });
|
|
125
|
+
* return others.map((peer) => peer.cursor && <Cursor key={peer.key} name={peer.name} at={peer.cursor} />);
|
|
126
|
+
* ```
|
|
127
|
+
*/
|
|
128
|
+
export function usePresence(options: PresenceOptions = {}): Presence {
|
|
129
|
+
const store = useStore();
|
|
130
|
+
const team = store.team;
|
|
131
|
+
useSyncExternalStore(team.subscribe, team.version, team.version);
|
|
132
|
+
const cursor = options.cursor === true;
|
|
133
|
+
const selection = options.selection === true;
|
|
134
|
+
useEffect(
|
|
135
|
+
() => (team.available ? team.joinPresence({ cursor, selection }) : undefined),
|
|
136
|
+
[team, cursor, selection],
|
|
137
|
+
);
|
|
138
|
+
const state = team.presence();
|
|
139
|
+
return useMemo((): Presence => {
|
|
140
|
+
if (!team.available) return { status: "unavailable", others: [] };
|
|
141
|
+
if (!state) return { status: "joining", others: [] };
|
|
142
|
+
const self = state.peers.find((peer) => peer.self);
|
|
143
|
+
return {
|
|
144
|
+
status: "present",
|
|
145
|
+
visibility: state.visibility,
|
|
146
|
+
...(self ? { self } : {}),
|
|
147
|
+
others: state.peers.filter((peer) => !peer.self),
|
|
148
|
+
...(state.others !== undefined ? { count: state.others } : {}),
|
|
149
|
+
};
|
|
150
|
+
}, [team, state]);
|
|
151
|
+
}
|