@aperture-browser/session-react 0.0.0-nightly.99.75d2f316d627 → 1.0.0-beta.2

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.
@@ -1,2228 +0,0 @@
1
- import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
2
- import * as Effect from "effect/Effect";
3
- import * as Stream from "effect/Stream";
4
- import { DEFAULT_VIEWPORT, LiveSessionConnection, LiveSessionError, LiveSessionError as LiveSessionError$1, computeRenderMetrics, createViewportPreset, downloadSessionRecording, evdevKeycodeByCode, getSessionStatus, getTargetThumbnail, keyboardInputMessage, keyboardModifiers, shouldForwardBrowserShortcut, strictParseOptions, windowsVirtualKeyCodeForCodeOrKey } from "@aperture-browser/live-session";
5
- import * as Option from "effect/Option";
6
- import * as PubSub from "effect/PubSub";
7
- import * as Schema from "effect/Schema";
8
- import * as SubscriptionRef from "effect/SubscriptionRef";
9
- import * as Data from "effect/Data";
10
- import { jsx, jsxs } from "react/jsx-runtime";
11
- import * as Layer from "effect/Layer";
12
- import * as ManagedRuntime from "effect/ManagedRuntime";
13
- import * as FetchHttpClient from "effect/http/FetchHttpClient";
14
- import * as HttpClient from "effect/http/HttpClient";
15
- import { apiClientLayer, baseUrlLayer } from "@aperture-browser/api-client";
16
- import * as Redacted from "effect/Redacted";
17
- //#region src/effect.tsx
18
- const RuntimeContext = createContext(null);
19
- /** A hook below needed the app runtime, but no RuntimeProvider is above the component. */
20
- var RuntimeProviderMissingError = class extends Data.TaggedError("RuntimeProviderMissingError") {
21
- message = "useRuntime must be used inside RuntimeProvider";
22
- };
23
- function RuntimeProvider({ runtime, baseUrl, children }) {
24
- const value = useMemo(() => ({
25
- runtime,
26
- baseUrl
27
- }), [runtime, baseUrl]);
28
- return /* @__PURE__ */ jsx(RuntimeContext.Provider, {
29
- value,
30
- children
31
- });
32
- }
33
- function useRuntimeContext() {
34
- const context = useContext(RuntimeContext);
35
- if (!context) throw new RuntimeProviderMissingError();
36
- return context;
37
- }
38
- function useRuntime() {
39
- return useRuntimeContext().runtime;
40
- }
41
- function useBaseUrl() {
42
- return useRuntimeContext().baseUrl;
43
- }
44
- /**
45
- * Runs an effect while the component is mounted, restarting it when `deps` change, like
46
- * `useEffect`. Return `undefined` to run nothing. The fiber is interrupted synchronously
47
- * on cleanup, so its synchronous finalizers have run before the next effect starts.
48
- */
49
- function useFork(effect, deps) {
50
- const runtime = useRuntime();
51
- useEffect(() => {
52
- const program = effect();
53
- if (!program) return;
54
- const fiber = runtime.runFork(program);
55
- return () => fiber.interruptUnsafe();
56
- }, [runtime, ...deps]);
57
- }
58
- /**
59
- * Returns an event handler that forks the effect `callback` builds. Fibers still running
60
- * when the component unmounts are interrupted.
61
- */
62
- function useEffectCallback(callback, deps) {
63
- const runtime = useRuntime();
64
- const fibers = useRef(/* @__PURE__ */ new Set());
65
- useEffect(() => {
66
- const running = fibers.current;
67
- return () => {
68
- for (const fiber of running) fiber.interruptUnsafe();
69
- running.clear();
70
- };
71
- }, []);
72
- return useCallback((...args) => {
73
- const fiber = runtime.runFork(callback(...args));
74
- if (fiber.pollUnsafe()) return;
75
- fibers.current.add(fiber);
76
- fiber.addObserver(() => fibers.current.delete(fiber));
77
- }, [runtime, ...deps]);
78
- }
79
- /**
80
- * Returns a function that runs an API call for promise-based callers such as TanStack
81
- * Query. Aborting the signal interrupts the request.
82
- */
83
- function useRunApi() {
84
- const runtime = useRuntime();
85
- return useCallback((call, options) => runtime.runPromise(call, options), [runtime]);
86
- }
87
- //#endregion
88
- //#region src/hooks/use-live-session.ts
89
- const heartbeatIntervalMs = 2e3;
90
- const transportUnavailable = () => new LiveSessionConnection.LiveSessionError({ message: "live session transport is unavailable" });
91
- const cursorIntervalMs = 40;
92
- const collaborationPaintLifetimeMs = 7e3;
93
- const pointerButtonCode = {
94
- left: 272,
95
- right: 273,
96
- middle: 274
97
- };
98
- function useLiveSession({ access, displayName = null, enabled, webrtcSupported, iceServers, autoSize }) {
99
- const identity = useMemo(() => collaborationIdentity(displayName), [displayName]);
100
- const [role, setRole] = useState("viewer");
101
- const runtime = useRuntime();
102
- const frameRef = useMemo(() => runtime.runSync(SubscriptionRef.make(null)), [runtime]);
103
- const paintPubSub = useMemo(() => runtime.runSync(PubSub.unbounded()), [runtime]);
104
- const frames = useMemo(() => SubscriptionRef.changes(frameRef), [frameRef]);
105
- const paintEvents = useMemo(() => Stream.fromPubSub(paintPubSub), [paintPubSub]);
106
- const publishFrame = useCallback((frame) => runtime.runSync(SubscriptionRef.set(frameRef, frame)), [frameRef, runtime]);
107
- const publishPaint = useCallback((event) => PubSub.publishUnsafe(paintPubSub, event), [paintPubSub]);
108
- const connectionRef = useRef(null);
109
- const holderClientIdRef = useRef(null);
110
- const clientIdRef = useRef("");
111
- const claimPendingRef = useRef(false);
112
- const releasePendingRef = useRef(false);
113
- const cursorVisibleRef = useRef(false);
114
- const lastCursorSentAtRef = useRef(0);
115
- const participantsRef = useRef([]);
116
- const followingClientIdRef = useRef(null);
117
- const mediaSizeRef = useRef(null);
118
- const transportRef = useRef(null);
119
- const presentationRef = useRef(null);
120
- const presentationSelectionRef = useRef(false);
121
- const [phase, setPhase] = useState("idle");
122
- const [targets, setTargets] = useState([]);
123
- const [activeTargetId, setActiveTargetId] = useState(null);
124
- const [mediaStream, setMediaStream] = useState(null);
125
- const [mediaSize, setMediaSize] = useState(null);
126
- const [transport, setTransport] = useState(null);
127
- const [targetSwitching, setTargetSwitching] = useState(false);
128
- const [presentationSwitching, setPresentationSwitching] = useState(false);
129
- const [presentation, setPresentation] = useState(null);
130
- const [recordings, setRecordings] = useState([]);
131
- const [viewportOwnership, setViewportOwnership] = useState(null);
132
- const [clientId, setClientId] = useState("");
133
- const [holderClientId, setHolderClientId] = useState(null);
134
- const [leaseMode, setLeaseMode] = useState(null);
135
- const [participants, setParticipants] = useState([]);
136
- const [cursors, setCursors] = useState(() => /* @__PURE__ */ new Map());
137
- const [lastError, setLastError] = useState(null);
138
- mediaSizeRef.current = mediaSize;
139
- transportRef.current = transport;
140
- presentationRef.current = presentation;
141
- const handleMessage = useCallback((message) => {
142
- switch (message.type) {
143
- case "session.snapshot":
144
- setRole(message.role);
145
- clientIdRef.current = message.clientId;
146
- setClientId(message.clientId);
147
- holderClientIdRef.current = message.holderClientId ?? null;
148
- setHolderClientId(message.holderClientId ?? null);
149
- setLeaseMode(message.mode ?? null);
150
- participantsRef.current = message.participants;
151
- setParticipants(message.participants);
152
- followingClientIdRef.current = message.participants.find((participant) => participant.clientId === message.clientId)?.followingClientId ?? null;
153
- setTargets(message.targets);
154
- setActiveTargetId(message.activeTargetId ?? null);
155
- setMediaSize(resolveMediaSize(message.targets, message.activeTargetId));
156
- setRecordings(message.recordings);
157
- setPresentation(message.presentation ?? null);
158
- setViewportOwnership(message.autoSize === void 0 ? null : {
159
- ownerClientId: message.viewportOwnerClientId ?? null,
160
- autoSize: message.autoSize
161
- });
162
- setLastError(null);
163
- return;
164
- case "targets.state":
165
- setTargets(message.targets);
166
- setActiveTargetId(message.activeTargetId ?? null);
167
- setMediaSize(resolveMediaSize(message.targets, message.activeTargetId));
168
- setTargetSwitching(false);
169
- return;
170
- case "presence.state":
171
- participantsRef.current = message.participants;
172
- setParticipants(message.participants);
173
- followingClientIdRef.current = message.participants.find((participant) => participant.clientId === clientIdRef.current)?.followingClientId ?? null;
174
- setCursors((current) => {
175
- const followed = followingClientIdRef.current;
176
- if (!followed) return current.size === 0 ? current : /* @__PURE__ */ new Map();
177
- const cursor = current.get(followed);
178
- return cursor ? /* @__PURE__ */ new Map([[followed, cursor]]) : /* @__PURE__ */ new Map();
179
- });
180
- return;
181
- case "input.state":
182
- holderClientIdRef.current = message.holderClientId ?? null;
183
- setHolderClientId(message.holderClientId ?? null);
184
- setLeaseMode(message.mode ?? null);
185
- claimPendingRef.current = false;
186
- releasePendingRef.current = false;
187
- setLastError((current) => current?.code === "input_busy" || current?.code === "input_not_owned" ? null : current);
188
- return;
189
- case "viewport.state":
190
- setViewportOwnership({
191
- ownerClientId: message.viewportOwnerClientId ?? null,
192
- autoSize: message.autoSize
193
- });
194
- return;
195
- case "presence.cursor":
196
- if (message.clientId !== followingClientIdRef.current) return;
197
- setCursors((current) => new Map(current).set(message.clientId, message));
198
- return;
199
- case "presence.cursor.clear":
200
- setCursors((current) => {
201
- if (!current.has(message.clientId)) return current;
202
- const next = new Map(current);
203
- next.delete(message.clientId);
204
- return next;
205
- });
206
- return;
207
- case "paint.point":
208
- if (participantsRef.current.some((participant) => participant.clientId === message.clientId)) publishPaint({
209
- type: "point",
210
- message
211
- });
212
- return;
213
- case "recordings.state":
214
- setRecordings(message.recordings);
215
- return;
216
- case "presentation.state":
217
- setPresentation(message.presentation);
218
- return;
219
- case "error":
220
- claimPendingRef.current = false;
221
- releasePendingRef.current = false;
222
- setLastError({
223
- code: message.code,
224
- message: message.message
225
- });
226
- return;
227
- default:
228
- if (message.presentation) setPresentation(message.presentation);
229
- if (!message.ok) setLastError({
230
- code: message.code ?? "request_rejected",
231
- message: message.message ?? "Live session command failed."
232
- });
233
- }
234
- }, [publishPaint]);
235
- useFork(() => {
236
- if (!enabled || access === null) {
237
- connectionRef.current = null;
238
- setPhase("idle");
239
- setRole("viewer");
240
- setTargets([]);
241
- setActiveTargetId(null);
242
- setMediaStream(null);
243
- setMediaSize(null);
244
- setTransport(null);
245
- setPresentation(null);
246
- setTargetSwitching(false);
247
- setPresentationSwitching(false);
248
- setParticipants([]);
249
- setCursors(/* @__PURE__ */ new Map());
250
- setRecordings([]);
251
- setViewportOwnership(null);
252
- publishFrame(null);
253
- publishPaint({ type: "clear" });
254
- return;
255
- }
256
- setRole("viewer");
257
- return Effect.gen(function* () {
258
- const connection = yield* LiveSessionConnection.make({
259
- access,
260
- identity,
261
- autoSize,
262
- iceServers,
263
- webrtcSupported,
264
- callbacks: {
265
- onPhase: setPhase,
266
- onMessage: handleMessage,
267
- onFrame: publishFrame,
268
- onStream: setMediaStream,
269
- onTransport: setTransport,
270
- onError: (message) => setLastError({
271
- code: "connection_failed",
272
- message
273
- })
274
- }
275
- });
276
- connectionRef.current = connection;
277
- yield* Effect.addFinalizer(() => Effect.sync(() => {
278
- if (connectionRef.current === connection) connectionRef.current = null;
279
- }));
280
- return yield* Effect.never;
281
- }).pipe(Effect.scoped, Effect.ensuring(Effect.sync(() => {
282
- publishFrame(null);
283
- publishPaint({ type: "clear" });
284
- })));
285
- }, [
286
- autoSize,
287
- access,
288
- enabled,
289
- handleMessage,
290
- iceServers,
291
- identity,
292
- publishFrame,
293
- publishPaint,
294
- webrtcSupported
295
- ]);
296
- const sendReliable = useCallback((message) => connectionRef.current?.sendReliable(message) ?? false, []);
297
- const sendRealtime = useCallback((message) => connectionRef.current?.sendRealtime(message) ?? false, []);
298
- const runCommand = useEffectCallback((connection, type, payload) => connection.command(type, payload).pipe(Effect.catch((error) => Effect.sync(() => {
299
- setTargetSwitching(false);
300
- setLastError({
301
- code: "request_rejected",
302
- message: error.message
303
- });
304
- }))), []);
305
- const command = useCallback((type, payload = {}) => {
306
- const connection = connectionRef.current;
307
- if (!connection) return false;
308
- runCommand(connection, type, payload);
309
- return true;
310
- }, [runCommand]);
311
- const request = useCallback((type, payload = {}) => Effect.suspend(() => connectionRef.current ? connectionRef.current.command(type, payload) : Effect.fail(transportUnavailable())), []);
312
- const runSelectTarget = useEffectCallback((connection, targetId) => connection.command("target.select", { targetId }).pipe(Effect.match({
313
- onSuccess: () => setActiveTargetId(targetId),
314
- onFailure: (error) => setLastError({
315
- code: "request_rejected",
316
- message: error.message
317
- })
318
- }), Effect.ensuring(Effect.sync(() => setTargetSwitching(false)))), []);
319
- const requestSelectTarget = useCallback((targetId) => Effect.suspend(() => {
320
- const connection = connectionRef.current;
321
- if (!connection) return Effect.fail(transportUnavailable());
322
- setTargetSwitching(true);
323
- return connection.command("target.select", { targetId }).pipe(Effect.tap(() => Effect.sync(() => setActiveTargetId(targetId))), Effect.tapError((error) => Effect.sync(() => setLastError({
324
- code: "request_rejected",
325
- message: error.message
326
- }))), Effect.ensuring(Effect.sync(() => setTargetSwitching(false))), Effect.asVoid);
327
- }), []);
328
- const selectTarget = useCallback((targetId) => {
329
- const connection = connectionRef.current;
330
- if (!connection) return false;
331
- setTargetSwitching(true);
332
- runSelectTarget(connection, targetId);
333
- return true;
334
- }, [runSelectTarget]);
335
- const selectPresentation = useCallback((selection) => Effect.suspend(() => {
336
- const connection = connectionRef.current;
337
- if (!connection) return Effect.fail(transportUnavailable());
338
- if (presentationSelectionRef.current) return Effect.fail(new LiveSessionConnection.LiveSessionError({ message: "another presentation update is already in progress" }));
339
- presentationSelectionRef.current = true;
340
- setPresentationSwitching(true);
341
- return Effect.gen(function* () {
342
- switch (selection.kind) {
343
- case "jpeg": return yield* connection.selectTransport("websocket");
344
- case "webrtc-retry": return yield* connection.selectTransport("webrtc");
345
- case "webrtc": {
346
- const size = mediaSizeRef.current;
347
- if (!size) return yield* new LiveSessionConnection.LiveSessionError({ message: "presentation size is unavailable" });
348
- const restoreWebRTC = presentationRef.current?.quality?.profile !== selection.quality.profile && transportRef.current === "webrtc";
349
- if (restoreWebRTC) yield* connection.selectTransport("websocket");
350
- const result = yield* connection.command("presentation.quality.set", {
351
- profile: selection.quality.profile,
352
- width: size.canvasWidth,
353
- height: size.canvasHeight,
354
- fps: selection.quality.fps,
355
- bitrateKbps: selection.quality.bitrateKbps
356
- }).pipe(Effect.tapError(() => restoreWebRTC ? Effect.ignore(connection.selectTransport("webrtc")) : Effect.void));
357
- if (result.presentation) setPresentation(result.presentation);
358
- return yield* connection.selectTransport("webrtc");
359
- }
360
- default: return selection;
361
- }
362
- }).pipe(Effect.tapError((error) => Effect.sync(() => setLastError({
363
- code: "presentation_update_failed",
364
- message: error.message
365
- }))), Effect.ensuring(Effect.sync(() => {
366
- presentationSelectionRef.current = false;
367
- setPresentationSwitching(false);
368
- })));
369
- }), []);
370
- const claim = useCallback((targetId, mode) => {
371
- if (role === "viewer" || !sendReliable({
372
- type: "input.claim",
373
- targetId,
374
- mode
375
- })) return false;
376
- claimPendingRef.current = true;
377
- releasePendingRef.current = false;
378
- return true;
379
- }, [role, sendReliable]);
380
- const release = useCallback(() => {
381
- if (releasePendingRef.current || holderClientIdRef.current !== clientIdRef.current || !sendReliable({ type: "input.release" })) return false;
382
- releasePendingRef.current = true;
383
- claimPendingRef.current = false;
384
- return true;
385
- }, [sendReliable]);
386
- const setActiveTarget = useCallback((targetId) => targetId ? selectTarget(targetId) : false, [selectTarget]);
387
- const follow = useCallback((followingClientId) => sendReliable({
388
- type: "follow.set",
389
- followingClientId: followingClientId ?? ""
390
- }), [sendReliable]);
391
- const sendCursor = useCallback((targetId, x, y, dimensions) => {
392
- const now = performance.now();
393
- if (now - lastCursorSentAtRef.current < cursorIntervalMs) return false;
394
- lastCursorSentAtRef.current = now;
395
- const sent = sendRealtime({
396
- type: "presence.cursor",
397
- targetId,
398
- x: normalizedCoordinate(x, dimensions.width),
399
- y: normalizedCoordinate(y, dimensions.height)
400
- });
401
- if (sent) cursorVisibleRef.current = true;
402
- return sent;
403
- }, [sendRealtime]);
404
- const sendPaintPoint = useCallback((point) => point.phase === "move" ? sendRealtime({
405
- type: "paint.point",
406
- ...point
407
- }) : sendReliable({
408
- type: "paint.point",
409
- ...point
410
- }), [sendRealtime, sendReliable]);
411
- const clearCursor = useCallback(() => {
412
- if (!cursorVisibleRef.current || !sendReliable({ type: "presence.cursor.clear" })) return false;
413
- cursorVisibleRef.current = false;
414
- return true;
415
- }, [sendReliable]);
416
- const sendInputEvent = useCallback((message, realtime = false) => realtime ? sendRealtime(message) : sendReliable(message), [sendRealtime, sendReliable]);
417
- const sendBrowserInput = useCallback((message, dimensions) => {
418
- if (role === "viewer" || holderClientIdRef.current !== clientIdRef.current && !claimPendingRef.current) return false;
419
- switch (message.type) {
420
- case "input.mouse": {
421
- const x = normalizedCoordinate(message.x, dimensions.width);
422
- const y = normalizedCoordinate(message.y, dimensions.height);
423
- if (message.action === "move") return sendInputEvent({
424
- type: "input.pointer.motion.absolute",
425
- targetId: message.targetId,
426
- x,
427
- y,
428
- width: dimensions.width,
429
- height: dimensions.height,
430
- modifiers: message.modifiers ?? 0
431
- }, true);
432
- if (message.button === "none") return true;
433
- const buttonCode = pointerButtonCode[message.button ?? "left"];
434
- const sendButton = (pressed, clickCount) => sendInputEvent({
435
- type: "input.pointer.button",
436
- targetId: message.targetId,
437
- x,
438
- y,
439
- width: dimensions.width,
440
- height: dimensions.height,
441
- buttonCode,
442
- pressed,
443
- clickCount,
444
- modifiers: message.modifiers ?? 0
445
- });
446
- if (message.action === "down" || message.action === "up") return sendButton(message.action === "down", message.clickCount ?? 1);
447
- const count = message.action === "doubleClick" ? 2 : 1;
448
- for (let index = 0; index < count; index += 1) {
449
- const clickCount = message.action === "doubleClick" ? index + 1 : 1;
450
- sendButton(true, clickCount);
451
- sendButton(false, clickCount);
452
- }
453
- return true;
454
- }
455
- case "input.wheel": {
456
- const x = normalizedCoordinate(message.x, dimensions.width);
457
- const y = normalizedCoordinate(message.y, dimensions.height);
458
- sendInputEvent({
459
- type: "input.pointer.scroll",
460
- targetId: message.targetId,
461
- x,
462
- y,
463
- width: dimensions.width,
464
- height: dimensions.height,
465
- horizontal: message.deltaX,
466
- vertical: message.deltaY,
467
- stopHorizontal: false,
468
- stopVertical: false,
469
- modifiers: message.modifiers ?? 0
470
- });
471
- return sendInputEvent({
472
- type: "input.pointer.scroll",
473
- targetId: message.targetId,
474
- x,
475
- y,
476
- width: dimensions.width,
477
- height: dimensions.height,
478
- horizontal: 0,
479
- vertical: 0,
480
- stopHorizontal: message.deltaX !== 0,
481
- stopVertical: message.deltaY !== 0,
482
- modifiers: message.modifiers ?? 0
483
- });
484
- }
485
- case "input.key": {
486
- if (message.action === "char") return message.text ? sendInputEvent({
487
- type: "input.keyboard.text",
488
- targetId: message.targetId,
489
- text: message.text
490
- }) : false;
491
- const keycode = evdevKeycodeByCode[message.code ?? ""];
492
- if (!keycode) return false;
493
- const windowsVirtualKeyCode = message.windowsVirtualKeyCode ?? windowsVirtualKeyCodeForCodeOrKey(message.code, message.key);
494
- return sendInputEvent({
495
- type: "input.keyboard.key",
496
- targetId: message.targetId,
497
- keycode,
498
- pressed: message.action === "down",
499
- key: message.key,
500
- code: message.code,
501
- text: message.text,
502
- unmodifiedText: message.unmodifiedText,
503
- modifiers: message.modifiers ?? 0,
504
- windowsVirtualKeyCode,
505
- nativeVirtualKeyCode: message.nativeVirtualKeyCode ?? windowsVirtualKeyCode,
506
- location: message.location ?? 0,
507
- autoRepeat: message.autoRepeat ?? false,
508
- isKeypad: message.isKeypad ?? false
509
- });
510
- }
511
- case "clipboard.copy": return sendShortcut(sendInputEvent, message.targetId, "KeyC");
512
- case "clipboard.cut": return sendShortcut(sendInputEvent, message.targetId, "KeyX");
513
- case "clipboard.paste": {
514
- const item = message.items.find((candidate) => candidate.mimeType === "text/plain");
515
- return item ? sendInputEvent({
516
- type: "input.keyboard.text",
517
- targetId: message.targetId,
518
- text: item.data
519
- }) : false;
520
- }
521
- default: return message;
522
- }
523
- }, [role, sendInputEvent]);
524
- const hasControl = holderClientId === clientId && clientId !== "";
525
- const followingClientId = participants.find((participant) => participant.clientId === clientId)?.followingClientId ?? null;
526
- useFork(() => hasControl ? Effect.sleep(heartbeatIntervalMs).pipe(Effect.andThen(Effect.sync(() => {
527
- if (holderClientIdRef.current === clientIdRef.current) sendReliable({ type: "input.heartbeat" });
528
- })), Effect.forever) : void 0, [hasControl, sendReliable]);
529
- return {
530
- phase,
531
- targets,
532
- activeTargetId,
533
- frames,
534
- mediaStream,
535
- mediaSize,
536
- transport,
537
- presentation,
538
- mediaSwitching: targetSwitching || presentationSwitching,
539
- recordings,
540
- viewportOwnership,
541
- sendBrowserInput,
542
- selectTarget,
543
- requestSelectTarget,
544
- command,
545
- request,
546
- selectPresentation,
547
- reconnect: () => {
548
- const connection = connectionRef.current;
549
- if (connection) runtime.runSync(connection.reconnect);
550
- },
551
- collaboration: {
552
- phase: phase === "error" ? "disconnected" : phase,
553
- role,
554
- clientId,
555
- holderClientId,
556
- leaseMode,
557
- hasControl,
558
- canRequestControl: role !== "viewer" && phase === "connected",
559
- lastError,
560
- participants,
561
- cursors,
562
- paintEvents,
563
- followingClientId,
564
- claim,
565
- release,
566
- setActiveTarget,
567
- follow,
568
- sendCursor,
569
- sendPaintPoint,
570
- clearCursor,
571
- sendInput: sendBrowserInput
572
- }
573
- };
574
- }
575
- const StoredIdentity = Schema.Struct({
576
- name: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(48)),
577
- avatarHash: Schema.String.check(Schema.isPattern(/^[0-9a-f]{32}$/))
578
- });
579
- const decodeStoredIdentity = Schema.decodeUnknownOption(Schema.fromJsonString(StoredIdentity), strictParseOptions);
580
- function collaborationIdentity(accountName) {
581
- const anonymous = loadAnonymousIdentity();
582
- if (!accountName?.trim()) return anonymous;
583
- return {
584
- ...anonymous,
585
- name: Array.from(accountName.trim()).slice(0, 48).join("")
586
- };
587
- }
588
- function loadAnonymousIdentity() {
589
- const storageKey = "aperture.collaboration.identity";
590
- try {
591
- const stored = window.localStorage.getItem(storageKey);
592
- if (stored) {
593
- const parsed = decodeStoredIdentity(stored);
594
- if (Option.isSome(parsed)) return parsed.value;
595
- }
596
- const created = createAnonymousIdentity();
597
- window.localStorage.setItem(storageKey, JSON.stringify(created));
598
- return created;
599
- } catch {
600
- return createAnonymousIdentity();
601
- }
602
- }
603
- function createAnonymousIdentity() {
604
- const adjectives = [
605
- "Amber",
606
- "Brisk",
607
- "Calm",
608
- "Clever",
609
- "Misty",
610
- "Quiet",
611
- "Swift",
612
- "Warm"
613
- ];
614
- const animals = [
615
- "Badger",
616
- "Falcon",
617
- "Fox",
618
- "Koala",
619
- "Otter",
620
- "Panda",
621
- "Raven",
622
- "Tiger"
623
- ];
624
- const random = /* @__PURE__ */ new Uint8Array(18);
625
- crypto.getRandomValues(random);
626
- return {
627
- name: `${adjectives[(random.at(0) ?? 0) % adjectives.length] ?? "Quiet"} ${animals[(random.at(1) ?? 0) % animals.length] ?? "Otter"}`,
628
- avatarHash: Array.from(random.slice(2), (value) => value.toString(16).padStart(2, "0")).join("")
629
- };
630
- }
631
- function resolveMediaSize(targets, activeTargetId) {
632
- const viewport = targets.find((target) => target.id === activeTargetId)?.viewport;
633
- return viewport ? {
634
- width: viewport.width,
635
- height: viewport.height,
636
- canvasWidth: viewport.canvasWidth,
637
- canvasHeight: viewport.canvasHeight,
638
- deviceScaleFactor: viewport.deviceScaleFactor
639
- } : null;
640
- }
641
- function normalizedCoordinate(value, length) {
642
- if (length <= 1) return 0;
643
- return Math.min(1, Math.max(0, value / length));
644
- }
645
- function sendShortcut(sendInputEvent, targetId, code) {
646
- const controlKeycode = evdevKeycodeByCode.ControlLeft;
647
- const shortcutKeycode = evdevKeycodeByCode[code];
648
- if (!controlKeycode || !shortcutKeycode) return false;
649
- const controlVirtualKeyCode = windowsVirtualKeyCodeForCodeOrKey("ControlLeft", "Control");
650
- const shortcutKey = code === "KeyC" ? "c" : "x";
651
- const shortcutVirtualKeyCode = windowsVirtualKeyCodeForCodeOrKey(code, shortcutKey);
652
- sendInputEvent({
653
- type: "input.keyboard.key",
654
- targetId,
655
- keycode: controlKeycode,
656
- pressed: true,
657
- key: "Control",
658
- code: "ControlLeft",
659
- windowsVirtualKeyCode: controlVirtualKeyCode,
660
- nativeVirtualKeyCode: controlVirtualKeyCode,
661
- modifiers: 2
662
- });
663
- sendInputEvent({
664
- type: "input.keyboard.key",
665
- targetId,
666
- keycode: shortcutKeycode,
667
- pressed: true,
668
- key: shortcutKey,
669
- code,
670
- windowsVirtualKeyCode: shortcutVirtualKeyCode,
671
- nativeVirtualKeyCode: shortcutVirtualKeyCode,
672
- modifiers: 2
673
- });
674
- sendInputEvent({
675
- type: "input.keyboard.key",
676
- targetId,
677
- keycode: shortcutKeycode,
678
- pressed: false,
679
- key: shortcutKey,
680
- code,
681
- windowsVirtualKeyCode: shortcutVirtualKeyCode,
682
- nativeVirtualKeyCode: shortcutVirtualKeyCode,
683
- modifiers: 2
684
- });
685
- return sendInputEvent({
686
- type: "input.keyboard.key",
687
- targetId,
688
- keycode: controlKeycode,
689
- pressed: false,
690
- key: "Control",
691
- code: "ControlLeft",
692
- windowsVirtualKeyCode: controlVirtualKeyCode,
693
- nativeVirtualKeyCode: controlVirtualKeyCode,
694
- modifiers: 0
695
- });
696
- }
697
- //#endregion
698
- //#region src/components/collaboration-paint-overlay.tsx
699
- const paintColors = [
700
- "#f43f5e",
701
- "#f97316",
702
- "#eab308",
703
- "#22c55e",
704
- "#06b6d4",
705
- "#8b5cf6"
706
- ];
707
- const paintWidth = 4;
708
- const paintSendIntervalMs = 24;
709
- const maximumPaintPoints = 2048;
710
- const maximumPaintStrokes = 512;
711
- function CollaborationPaintOverlay({ collaboration, targetId, enabled, visible, left, top, width, height }) {
712
- const canvasRef = useRef(null);
713
- const activeStrokeIdRef = useRef(null);
714
- const activePointerIdRef = useRef(null);
715
- const lastPointSentAtRef = useRef(0);
716
- const strokesRef = useRef(/* @__PURE__ */ new Map());
717
- const color = colorForClient(collaboration.clientId);
718
- useFork(() => {
719
- const canvas = canvasRef.current;
720
- if (!canvas) return;
721
- const pixelRatio = window.devicePixelRatio || 1;
722
- canvas.width = Math.max(1, Math.round(width * pixelRatio));
723
- canvas.height = Math.max(1, Math.round(height * pixelRatio));
724
- const context = canvas.getContext("2d");
725
- if (!context) return;
726
- let animationFrame = null;
727
- const participantIds = new Set(collaboration.participants.map((participant) => participant.clientId));
728
- const disconnectedAt = Date.now();
729
- for (const [key, stroke] of strokesRef.current) if (!stroke.ended && !participantIds.has(stroke.clientId)) strokesRef.current.set(key, {
730
- ...stroke,
731
- updatedAt: disconnectedAt,
732
- ended: true
733
- });
734
- const draw = () => {
735
- animationFrame = null;
736
- context.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
737
- context.clearRect(0, 0, width, height);
738
- const now = Date.now();
739
- let fadingStrokeCount = 0;
740
- for (const [key, stroke] of strokesRef.current) {
741
- const age = now - stroke.updatedAt;
742
- if (stroke.ended && age >= 7e3) {
743
- strokesRef.current.delete(key);
744
- continue;
745
- }
746
- if (stroke.ended) fadingStrokeCount += 1;
747
- if (stroke.targetId !== targetId || stroke.points.length === 0) continue;
748
- const opacity = stroke.ended ? 1 - age / collaborationPaintLifetimeMs : 1;
749
- context.globalAlpha = opacity;
750
- context.strokeStyle = stroke.color;
751
- context.fillStyle = stroke.color;
752
- context.lineWidth = stroke.width;
753
- context.lineCap = "round";
754
- context.lineJoin = "round";
755
- const first = stroke.points[0];
756
- if (!first) continue;
757
- if (stroke.points.length === 1) {
758
- context.beginPath();
759
- context.arc(first.x * width, first.y * height, stroke.width / 2, 0, Math.PI * 2);
760
- context.fill();
761
- continue;
762
- }
763
- context.beginPath();
764
- context.moveTo(first.x * width, first.y * height);
765
- for (let index = 1; index < stroke.points.length - 1; index += 1) {
766
- const point = stroke.points[index];
767
- const next = stroke.points[index + 1];
768
- if (!point || !next) continue;
769
- context.quadraticCurveTo(point.x * width, point.y * height, (point.x + next.x) / 2 * width, (point.y + next.y) / 2 * height);
770
- }
771
- const last = stroke.points[stroke.points.length - 1];
772
- if (last) context.lineTo(last.x * width, last.y * height);
773
- context.stroke();
774
- }
775
- context.globalAlpha = 1;
776
- if (fadingStrokeCount > 0) animationFrame = window.requestAnimationFrame(draw);
777
- };
778
- const requestDraw = () => {
779
- if (animationFrame === null) animationFrame = window.requestAnimationFrame(draw);
780
- };
781
- const onPaint = (event) => {
782
- if (event.type === "clear") {
783
- strokesRef.current.clear();
784
- requestDraw();
785
- return;
786
- }
787
- const message = event.message;
788
- const key = `${message.clientId}:${message.targetId}:${message.strokeId}`;
789
- const existing = strokesRef.current.get(key);
790
- if (message.phase !== "start" && !existing || existing?.ended && message.phase !== "start") return;
791
- const updatedAt = Date.now();
792
- if (message.phase === "start") {
793
- for (const [candidateKey, stroke] of strokesRef.current) if (!stroke.ended && stroke.clientId === message.clientId) strokesRef.current.set(candidateKey, {
794
- ...stroke,
795
- updatedAt,
796
- ended: true
797
- });
798
- }
799
- let points = message.phase === "start" || !existing ? [{
800
- x: message.x,
801
- y: message.y
802
- }] : [...existing.points, {
803
- x: message.x,
804
- y: message.y
805
- }];
806
- if (points.length > maximumPaintPoints) points = points.filter((_, index) => index % 2 === 0);
807
- if (!existing && strokesRef.current.size >= maximumPaintStrokes) {
808
- let oldestKey = null;
809
- let oldestUpdatedAt = Number.POSITIVE_INFINITY;
810
- for (const [candidateKey, stroke] of strokesRef.current) {
811
- if (!stroke.ended) continue;
812
- if (stroke.updatedAt < oldestUpdatedAt) {
813
- oldestKey = candidateKey;
814
- oldestUpdatedAt = stroke.updatedAt;
815
- }
816
- }
817
- if (oldestKey) strokesRef.current.delete(oldestKey);
818
- }
819
- strokesRef.current.set(key, {
820
- clientId: message.clientId,
821
- targetId: message.targetId,
822
- color: message.color,
823
- width: message.width,
824
- points,
825
- updatedAt,
826
- ended: message.phase === "end"
827
- });
828
- requestDraw();
829
- };
830
- draw();
831
- return Stream.runForEach(collaboration.paintEvents, (event) => Effect.sync(() => onPaint(event))).pipe(Effect.ensuring(Effect.sync(() => {
832
- if (animationFrame !== null) window.cancelAnimationFrame(animationFrame);
833
- })));
834
- }, [
835
- collaboration.paintEvents,
836
- collaboration.participants,
837
- height,
838
- targetId,
839
- width
840
- ]);
841
- useEffect(() => {
842
- activeStrokeIdRef.current = null;
843
- activePointerIdRef.current = null;
844
- }, [enabled, targetId]);
845
- function sendPoint(event, phase) {
846
- const strokeId = activeStrokeIdRef.current;
847
- const point = normalizedPointer(event);
848
- if (!strokeId || !point) return;
849
- collaboration.sendPaintPoint({
850
- targetId,
851
- strokeId,
852
- color,
853
- width: paintWidth,
854
- phase,
855
- x: point.x,
856
- y: point.y
857
- });
858
- }
859
- function handlePointerDown(event) {
860
- stopPointerEvent(event);
861
- if (!event.isPrimary || event.button !== 0 || activePointerIdRef.current !== null) return;
862
- event.currentTarget.focus();
863
- activeStrokeIdRef.current = crypto.randomUUID();
864
- activePointerIdRef.current = event.pointerId;
865
- lastPointSentAtRef.current = performance.now();
866
- try {
867
- event.currentTarget.setPointerCapture(event.pointerId);
868
- } catch {}
869
- const point = normalizedPointer(event);
870
- if (point) collaboration.sendCursor(targetId, point.x * width, point.y * height, {
871
- width,
872
- height
873
- });
874
- sendPoint(event, "start");
875
- }
876
- function handlePointerMove(event) {
877
- stopPointerEvent(event);
878
- if (activePointerIdRef.current !== null && event.pointerId !== activePointerIdRef.current) return;
879
- const point = normalizedPointer(event);
880
- if (point) collaboration.sendCursor(targetId, point.x * width, point.y * height, {
881
- width,
882
- height
883
- });
884
- if (!activeStrokeIdRef.current || performance.now() - lastPointSentAtRef.current < paintSendIntervalMs) return;
885
- lastPointSentAtRef.current = performance.now();
886
- sendPoint(event, "move");
887
- }
888
- function finishStroke(event) {
889
- stopPointerEvent(event);
890
- if (!activeStrokeIdRef.current || activePointerIdRef.current !== event.pointerId) return;
891
- sendPoint(event, "end");
892
- activeStrokeIdRef.current = null;
893
- activePointerIdRef.current = null;
894
- if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
895
- }
896
- return /* @__PURE__ */ jsx("canvas", {
897
- ref: canvasRef,
898
- tabIndex: -1,
899
- style: {
900
- position: "absolute",
901
- zIndex: 20,
902
- touchAction: "none",
903
- cursor: enabled ? "crosshair" : void 0,
904
- pointerEvents: enabled ? void 0 : "none",
905
- visibility: visible ? void 0 : "hidden",
906
- left,
907
- top,
908
- width,
909
- height
910
- },
911
- "aria-label": "Shared drawing overlay",
912
- onPointerDown: handlePointerDown,
913
- onPointerMove: handlePointerMove,
914
- onPointerUp: finishStroke,
915
- onPointerCancel: finishStroke,
916
- onWheel: stopPointerEvent,
917
- onContextMenu: stopPointerEvent
918
- });
919
- }
920
- function normalizedPointer(event) {
921
- const rect = event.currentTarget.getBoundingClientRect();
922
- if (rect.width === 0 || rect.height === 0) return null;
923
- return {
924
- x: Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width)),
925
- y: Math.max(0, Math.min(1, (event.clientY - rect.top) / rect.height))
926
- };
927
- }
928
- function stopPointerEvent(event) {
929
- event.preventDefault();
930
- event.stopPropagation();
931
- }
932
- function colorForClient(clientId) {
933
- let hash = 0;
934
- for (const character of clientId) hash = hash * 31 + character.charCodeAt(0) >>> 0;
935
- return paintColors[hash % paintColors.length] ?? "#f43f5e";
936
- }
937
- //#endregion
938
- //#region src/components/session-viewport.tsx
939
- const MULTI_CLICK_MS = 500;
940
- const MULTI_CLICK_DISTANCE = 5;
941
- function SessionViewport({ control, viewport = control.viewport, localCursorEnabled = true, paintingEnabled = false, onPaintingEnabledChange, onNotice, className, style, renderOverlay }) {
942
- const containerRef = useRef(null);
943
- const imageRef = useRef(null);
944
- const videoRef = useRef(null);
945
- const rasterDecoderRef = useRef({
946
- decodingFrame: null,
947
- generation: 0,
948
- pending: null
949
- });
950
- const frameMetadataRef = useRef(null);
951
- const pressedKeysRef = useRef(/* @__PURE__ */ new Map());
952
- const releasedKeysRef = useRef(/* @__PURE__ */ new Set());
953
- const pointerCaptureRef = useRef(null);
954
- const dragCleanupRef = useRef(null);
955
- const implicitControlDesiredRef = useRef(false);
956
- const cursorHintPointRef = useRef(null);
957
- const lastClickRef = useRef(null);
958
- const [cursorHintPoint, setCursorHintPoint] = useState(null);
959
- const [frameMetadata, setFrameMetadata] = useState(null);
960
- const [presentedMedia, setPresentedMedia] = useState(null);
961
- const showingWebRTC = control.mediaPath === "webrtc-live" && control.mediaPhase === "live" && Boolean(control.mediaStream) && Boolean(control.activeTargetId);
962
- const mediaTransitioning = showingWebRTC && (control.mediaSwitching || control.mediaTargetId !== control.activeTargetId || presentedMedia?.stream !== control.mediaStream || presentedMedia?.targetId !== control.activeTargetId);
963
- const paintOverlayEnabled = paintingEnabled && (showingWebRTC || frameMetadata !== null) && control.collaboration.phase === "connected" && !control.mediaSwitching && !mediaTransitioning;
964
- const inputDisabled = paintingEnabled || control.mediaSwitching || mediaTransitioning || control.collaboration.phase !== "connected" || control.collaboration.role === "viewer";
965
- const displayedMediaSize = mediaTransitioning && presentedMedia ? presentedMedia.size : control.mediaSize;
966
- const renderWidth = showingWebRTC ? displayedMediaSize?.width ?? viewport.width : frameMetadata?.width ?? viewport.width;
967
- const renderHeight = showingWebRTC ? displayedMediaSize?.height ?? viewport.height : frameMetadata?.height ?? viewport.height;
968
- const inputWidth = showingWebRTC ? renderWidth : viewport.width;
969
- const inputHeight = showingWebRTC ? renderHeight : viewport.height;
970
- const contentWidth = showingWebRTC ? Math.min(displayedMediaSize?.canvasWidth ?? renderWidth, Math.round(renderWidth * (displayedMediaSize?.deviceScaleFactor ?? 1))) : renderWidth;
971
- const contentHeight = showingWebRTC ? Math.min(displayedMediaSize?.canvasHeight ?? renderHeight, Math.round(renderHeight * (displayedMediaSize?.deviceScaleFactor ?? 1))) : renderHeight;
972
- const displayMetrics = computeRenderMetrics(control.browserViewportSize?.width ?? renderWidth, control.browserViewportSize?.height ?? renderHeight, renderWidth, renderHeight);
973
- const disconnectedHint = resolveDisconnectedHint(control.phase);
974
- const collaborationHint = resolveCollaborationHint(control.collaboration);
975
- const cursorHint = disconnectedHint ?? collaborationHint;
976
- const displayedCursorHintPoint = cursorHint ? cursorHintPointRef.current ?? cursorHintPoint : null;
977
- const followedParticipant = control.collaboration.followingClientId ? control.collaboration.participants.find((participant) => participant.clientId === control.collaboration.followingClientId) : null;
978
- const followedCursor = followedParticipant ? control.collaboration.cursors.get(followedParticipant.clientId) : null;
979
- const followedCursorPoint = followedCursor?.targetId === control.activeTargetId ? {
980
- x: displayMetrics.offsetX + followedCursor.x * displayMetrics.renderedWidth,
981
- y: displayMetrics.offsetY + followedCursor.y * displayMetrics.renderedHeight
982
- } : null;
983
- useEffect(() => {
984
- control.setInputDimensions({
985
- width: inputWidth,
986
- height: inputHeight
987
- });
988
- }, [
989
- control.setInputDimensions,
990
- inputHeight,
991
- inputWidth
992
- ]);
993
- const releasePressedKeys = useCallback(() => {
994
- const pressedKeys = [...pressedKeysRef.current.entries()].reverse();
995
- pressedKeysRef.current.clear();
996
- for (const [keyId, pressedKey] of pressedKeys) if (control.sendInput({
997
- type: "input.key",
998
- targetId: pressedKey.targetId,
999
- action: "up",
1000
- ...pressedKey.input,
1001
- text: void 0,
1002
- modifiers: 0,
1003
- autoRepeat: false
1004
- })) releasedKeysRef.current.add(keyId);
1005
- }, [control.sendInput]);
1006
- useFork(() => {
1007
- const onFrame = (frame) => {
1008
- if (!frame) {
1009
- if (imageRef.current) resetImageFrames(imageRef.current, rasterDecoderRef.current);
1010
- else resetRasterFrameDecoder(rasterDecoderRef.current);
1011
- if (frameMetadataRef.current !== null) {
1012
- frameMetadataRef.current = null;
1013
- setFrameMetadata(null);
1014
- }
1015
- return;
1016
- }
1017
- if (frame.targetId !== control.activeTargetId) return;
1018
- if (imageRef.current && !showingWebRTC) enqueueImageFrame(imageRef.current, rasterDecoderRef.current, frame);
1019
- else rasterDecoderRef.current.pending = frame;
1020
- const currentMetadata = frameMetadataRef.current;
1021
- if (currentMetadata?.width !== frame.width || currentMetadata?.height !== frame.height) {
1022
- const nextMetadata = {
1023
- width: frame.width,
1024
- height: frame.height
1025
- };
1026
- frameMetadataRef.current = nextMetadata;
1027
- setFrameMetadata(nextMetadata);
1028
- }
1029
- };
1030
- return Stream.runForEach(control.frames, (frame) => Effect.sync(() => onFrame(frame))).pipe(Effect.ensuring(Effect.sync(() => {
1031
- if (imageRef.current) resetImageFrames(imageRef.current, rasterDecoderRef.current);
1032
- else resetRasterFrameDecoder(rasterDecoderRef.current);
1033
- })));
1034
- }, [
1035
- control.activeTargetId,
1036
- control.frames,
1037
- showingWebRTC
1038
- ]);
1039
- useLayoutEffect(() => {
1040
- const decoder = rasterDecoderRef.current;
1041
- const targetId = control.activeTargetId;
1042
- const targetFrame = decoder.pending?.targetId === targetId ? decoder.pending : decoder.decodingFrame?.targetId === targetId ? decoder.decodingFrame : null;
1043
- const image = imageRef.current;
1044
- if (image) resetImageFrames(image, decoder);
1045
- else resetRasterFrameDecoder(decoder);
1046
- if (targetFrame) {
1047
- decoder.pending = targetFrame;
1048
- const nextMetadata = {
1049
- width: targetFrame.width,
1050
- height: targetFrame.height
1051
- };
1052
- frameMetadataRef.current = nextMetadata;
1053
- setFrameMetadata(nextMetadata);
1054
- if (image) decodeNextImageFrame(image, decoder);
1055
- } else if (frameMetadataRef.current !== null) {
1056
- frameMetadataRef.current = null;
1057
- setFrameMetadata(null);
1058
- }
1059
- }, [control.activeTargetId]);
1060
- useEffect(() => {
1061
- const image = imageRef.current;
1062
- if (showingWebRTC || !image) return;
1063
- decodeNextImageFrame(image, rasterDecoderRef.current);
1064
- }, [frameMetadata, showingWebRTC]);
1065
- useEffect(() => {
1066
- if (!videoRef.current) return;
1067
- videoRef.current.srcObject = showingWebRTC ? control.mediaStream : null;
1068
- }, [control.mediaStream, showingWebRTC]);
1069
- useEffect(() => {
1070
- const video = videoRef.current;
1071
- const stream = control.mediaStream;
1072
- const targetId = control.activeTargetId;
1073
- const size = control.mediaSize;
1074
- if (!showingWebRTC || !video || !stream || !targetId || !size || control.mediaSwitching || control.mediaTargetId !== targetId || presentedMedia?.stream === stream && presentedMedia.targetId === targetId) return;
1075
- const callback = video.requestVideoFrameCallback(() => {
1076
- setPresentedMedia({
1077
- stream,
1078
- targetId,
1079
- size
1080
- });
1081
- });
1082
- return () => video.cancelVideoFrameCallback(callback);
1083
- }, [
1084
- control.activeTargetId,
1085
- control.mediaSize,
1086
- control.mediaStream,
1087
- control.mediaSwitching,
1088
- control.mediaTargetId,
1089
- presentedMedia,
1090
- showingWebRTC
1091
- ]);
1092
- useEffect(() => {
1093
- const element = containerRef.current;
1094
- if (!element) return;
1095
- const syncSize = (width, height) => {
1096
- control.setBrowserViewportSize({
1097
- width,
1098
- height
1099
- });
1100
- };
1101
- const rect = element.getBoundingClientRect();
1102
- syncSize(rect.width, rect.height);
1103
- const observer = new ResizeObserver((entries) => {
1104
- const entry = entries[0];
1105
- if (entry) syncSize(entry.contentRect.width, entry.contentRect.height);
1106
- });
1107
- observer.observe(element);
1108
- return () => observer.disconnect();
1109
- }, [control.setBrowserViewportSize]);
1110
- useEffect(() => {
1111
- return () => {
1112
- dragCleanupRef.current?.();
1113
- releasePressedKeys();
1114
- };
1115
- }, [releasePressedKeys]);
1116
- useEffect(() => {
1117
- const handleWindowBlur = () => {
1118
- releasePressedKeys();
1119
- releaseImplicitControl();
1120
- };
1121
- const handleVisibilityChange = () => {
1122
- if (document.visibilityState === "hidden") {
1123
- releasePressedKeys();
1124
- releaseImplicitControl();
1125
- }
1126
- };
1127
- window.addEventListener("blur", handleWindowBlur);
1128
- document.addEventListener("visibilitychange", handleVisibilityChange);
1129
- return () => {
1130
- window.removeEventListener("blur", handleWindowBlur);
1131
- document.removeEventListener("visibilitychange", handleVisibilityChange);
1132
- };
1133
- }, [releasePressedKeys, control.collaboration]);
1134
- useEffect(() => {
1135
- if (inputDisabled) {
1136
- dragCleanupRef.current?.();
1137
- releasePressedKeys();
1138
- releaseImplicitControl();
1139
- }
1140
- }, [inputDisabled, releasePressedKeys]);
1141
- useEffect(() => {
1142
- if (paintingEnabled) {
1143
- control.setCaptured(false);
1144
- implicitControlDesiredRef.current = false;
1145
- }
1146
- if (control.collaboration.hasControl && control.collaboration.leaseMode === "implicit" && !implicitControlDesiredRef.current) control.collaboration.release();
1147
- }, [
1148
- control.collaboration.hasControl,
1149
- control.collaboration.leaseMode,
1150
- control.collaboration.release,
1151
- control.setCaptured,
1152
- paintingEnabled
1153
- ]);
1154
- function mapPointer(event, clamp) {
1155
- const rect = containerRef.current?.getBoundingClientRect();
1156
- if (!rect) return null;
1157
- const metrics = computeRenderMetrics(rect.width, rect.height, renderWidth, renderHeight);
1158
- const localX = event.clientX - rect.left - metrics.offsetX;
1159
- const localY = event.clientY - rect.top - metrics.offsetY;
1160
- if (!clamp && (localX < 0 || localY < 0 || localX > metrics.renderedWidth || localY > metrics.renderedHeight)) return null;
1161
- const x = localX / metrics.scale * (inputWidth / renderWidth);
1162
- const y = localY / metrics.scale * (inputHeight / renderHeight);
1163
- if (clamp) return {
1164
- x: Math.round(clampNumber(x, 0, Math.max(inputWidth - 1, 0))),
1165
- y: Math.round(clampNumber(y, 0, Math.max(inputHeight - 1, 0)))
1166
- };
1167
- return {
1168
- x: Math.round(x),
1169
- y: Math.round(y)
1170
- };
1171
- }
1172
- function resolveInputTarget() {
1173
- if (control.phase !== "connected" || !control.activeTargetId || inputDisabled) return null;
1174
- if (!control.captured) control.setCaptured(true);
1175
- requestImplicitControl(control.activeTargetId);
1176
- containerRef.current?.focus();
1177
- return control.activeTargetId;
1178
- }
1179
- function requestImplicitControl(targetId) {
1180
- implicitControlDesiredRef.current = true;
1181
- if (!control.collaboration.hasControl) control.collaboration.claim(targetId, "implicit");
1182
- }
1183
- function releaseImplicitControl() {
1184
- implicitControlDesiredRef.current = false;
1185
- if (control.collaboration.hasControl && control.collaboration.leaseMode === "implicit") control.collaboration.release();
1186
- }
1187
- function preventViewportDefault(event) {
1188
- event.preventDefault();
1189
- event.stopPropagation();
1190
- }
1191
- function preventNativeDefault(event) {
1192
- if (event.cancelable) event.preventDefault();
1193
- event.stopPropagation();
1194
- }
1195
- function handleCaptureClick() {
1196
- if (control.phase !== "connected" || inputDisabled) return;
1197
- control.setCaptured(true);
1198
- if (control.activeTargetId) requestImplicitControl(control.activeTargetId);
1199
- containerRef.current?.focus();
1200
- }
1201
- function handlePointerEnter(event) {
1202
- updateCursorHint(event);
1203
- if (inputDisabled || !control.activeTargetId) return;
1204
- control.setCaptured(true);
1205
- requestImplicitControl(control.activeTargetId);
1206
- }
1207
- function handlePointerLeave() {
1208
- cursorHintPointRef.current = null;
1209
- setCursorHintPoint(null);
1210
- control.collaboration.clearCursor();
1211
- if (!pointerCaptureRef.current) {
1212
- releasePressedKeys();
1213
- releaseImplicitControl();
1214
- control.setCaptured(false);
1215
- }
1216
- }
1217
- function handlePointerClick() {
1218
- if (!control.captured) handleCaptureClick();
1219
- }
1220
- function handlePointerMove(event) {
1221
- updateCursorHint(event);
1222
- const point = mapPointer(event, false);
1223
- if (control.activeTargetId && point) control.collaboration.sendCursor(control.activeTargetId, point.x, point.y, {
1224
- width: inputWidth,
1225
- height: inputHeight
1226
- });
1227
- else if (!point) control.collaboration.clearCursor();
1228
- if (inputDisabled) return;
1229
- if (pointerCaptureRef.current?.pointerId === event.pointerId) return;
1230
- const targetId = control.captured && event.buttons === 0 ? control.activeTargetId : null;
1231
- if (!targetId) return;
1232
- if (!point) return;
1233
- preventViewportDefault(event);
1234
- control.sendInput({
1235
- type: "input.mouse",
1236
- targetId,
1237
- action: "move",
1238
- x: point.x,
1239
- y: point.y,
1240
- button: "none",
1241
- buttons: 0,
1242
- clickCount: 0,
1243
- modifiers: keyboardModifiers(event.nativeEvent)
1244
- });
1245
- }
1246
- function handlePointerDown(event) {
1247
- updateCursorHint(event);
1248
- const targetId = resolveInputTarget();
1249
- if (!targetId) return;
1250
- const point = mapPointer(event, false);
1251
- if (!point) return;
1252
- const element = containerRef.current;
1253
- if (!element) return;
1254
- const button = resolveMouseButton(event.button);
1255
- const now = Date.now();
1256
- const clickCount = resolveClickCount(targetId, button, point, now, lastClickRef.current);
1257
- lastClickRef.current = {
1258
- targetId,
1259
- button,
1260
- point,
1261
- time: now,
1262
- clickCount
1263
- };
1264
- preventViewportDefault(event);
1265
- pointerCaptureRef.current = {
1266
- pointerId: event.pointerId,
1267
- targetId,
1268
- button,
1269
- clickCount
1270
- };
1271
- dragCleanupRef.current?.();
1272
- try {
1273
- event.currentTarget.setPointerCapture(event.pointerId);
1274
- } catch {}
1275
- bindDragListeners({
1276
- pointerId: event.pointerId,
1277
- targetId,
1278
- button,
1279
- clickCount,
1280
- element
1281
- });
1282
- control.sendInput({
1283
- type: "input.mouse",
1284
- targetId,
1285
- action: "down",
1286
- x: point.x,
1287
- y: point.y,
1288
- button,
1289
- buttons: event.buttons,
1290
- clickCount,
1291
- modifiers: keyboardModifiers(event.nativeEvent)
1292
- });
1293
- }
1294
- function handlePointerUp(event) {
1295
- if (inputDisabled) return;
1296
- const capturedPointer = pointerCaptureRef.current;
1297
- const targetId = capturedPointer?.pointerId === event.pointerId ? capturedPointer.targetId : control.activeTargetId;
1298
- if (!targetId) return;
1299
- const point = mapPointer(event, capturedPointer?.pointerId === event.pointerId);
1300
- if (!point) return;
1301
- preventViewportDefault(event);
1302
- control.sendInput({
1303
- type: "input.mouse",
1304
- targetId,
1305
- action: "up",
1306
- x: point.x,
1307
- y: point.y,
1308
- button: capturedPointer?.button ?? resolveMouseButton(event.button),
1309
- buttons: event.buttons,
1310
- clickCount: capturedPointer?.clickCount ?? 1,
1311
- modifiers: keyboardModifiers(event.nativeEvent)
1312
- });
1313
- if (capturedPointer?.pointerId === event.pointerId) {
1314
- pointerCaptureRef.current = null;
1315
- if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
1316
- }
1317
- }
1318
- function handlePointerCancel(event) {
1319
- const capturedPointer = pointerCaptureRef.current;
1320
- if (capturedPointer?.pointerId !== event.pointerId) return;
1321
- const point = mapPointer(event, true);
1322
- pointerCaptureRef.current = null;
1323
- if (event.currentTarget.hasPointerCapture(event.pointerId)) event.currentTarget.releasePointerCapture(event.pointerId);
1324
- if (!point || inputDisabled) return;
1325
- preventViewportDefault(event);
1326
- control.sendInput({
1327
- type: "input.mouse",
1328
- targetId: capturedPointer.targetId,
1329
- action: "up",
1330
- x: point.x,
1331
- y: point.y,
1332
- button: capturedPointer.button,
1333
- buttons: 0,
1334
- clickCount: capturedPointer.clickCount,
1335
- modifiers: keyboardModifiers(event.nativeEvent)
1336
- });
1337
- }
1338
- function bindDragListeners({ pointerId, targetId, button, clickCount, element }) {
1339
- const handleMove = (event) => {
1340
- if (event.pointerId !== pointerId) return;
1341
- const point = mapPointer(event, true);
1342
- preventNativeDefault(event);
1343
- if (!point) return;
1344
- control.collaboration.sendCursor(targetId, point.x, point.y, {
1345
- width: inputWidth,
1346
- height: inputHeight
1347
- });
1348
- control.sendInput({
1349
- type: "input.mouse",
1350
- targetId,
1351
- action: "move",
1352
- x: point.x,
1353
- y: point.y,
1354
- button,
1355
- buttons: event.buttons || mouseButtonsForButton(button),
1356
- clickCount,
1357
- modifiers: keyboardModifiers(event)
1358
- });
1359
- };
1360
- const finish = (event, canceled) => {
1361
- if (event.pointerId !== pointerId) return;
1362
- const point = mapPointer(event, true);
1363
- if (!mapPointer(event, false)) control.collaboration.clearCursor();
1364
- preventNativeDefault(event);
1365
- if (point) {
1366
- control.sendInput({
1367
- type: "input.mouse",
1368
- targetId,
1369
- action: "up",
1370
- x: point.x,
1371
- y: point.y,
1372
- button,
1373
- buttons: 0,
1374
- clickCount,
1375
- modifiers: keyboardModifiers(event)
1376
- });
1377
- if (!canceled) lastClickRef.current = {
1378
- targetId,
1379
- button,
1380
- point,
1381
- time: Date.now(),
1382
- clickCount
1383
- };
1384
- }
1385
- cleanup();
1386
- };
1387
- const handleUp = (event) => finish(event, false);
1388
- const handleCancel = (event) => finish(event, true);
1389
- const cleanup = () => {
1390
- window.removeEventListener("pointermove", handleMove, true);
1391
- window.removeEventListener("pointerup", handleUp, true);
1392
- window.removeEventListener("pointercancel", handleCancel, true);
1393
- try {
1394
- if (element.hasPointerCapture(pointerId)) element.releasePointerCapture(pointerId);
1395
- } catch {}
1396
- if (pointerCaptureRef.current?.pointerId === pointerId) pointerCaptureRef.current = null;
1397
- if (dragCleanupRef.current === cleanup) dragCleanupRef.current = null;
1398
- };
1399
- dragCleanupRef.current = cleanup;
1400
- window.addEventListener("pointermove", handleMove, true);
1401
- window.addEventListener("pointerup", handleUp, true);
1402
- window.addEventListener("pointercancel", handleCancel, true);
1403
- }
1404
- function handleWheel(event) {
1405
- const targetId = resolveInputTarget();
1406
- if (!targetId) return;
1407
- const point = mapPointer(event, false);
1408
- if (!point) return;
1409
- preventViewportDefault(event);
1410
- const wheelScale = wheelDeltaScale(event.deltaMode, inputHeight);
1411
- control.sendInput({
1412
- type: "input.wheel",
1413
- targetId,
1414
- x: point.x,
1415
- y: point.y,
1416
- deltaX: event.deltaX * wheelScale,
1417
- deltaY: event.deltaY * wheelScale,
1418
- modifiers: keyboardModifiers(event.nativeEvent)
1419
- });
1420
- }
1421
- function handleKeyDown(event) {
1422
- if (event.key === "Escape" && paintingEnabled) {
1423
- event.preventDefault();
1424
- event.stopPropagation();
1425
- onPaintingEnabledChange?.(false);
1426
- return;
1427
- }
1428
- if (event.key === "Escape") {
1429
- if (control.captured) {
1430
- event.preventDefault();
1431
- event.stopPropagation();
1432
- control.setCaptured(false);
1433
- releaseImplicitControl();
1434
- }
1435
- return;
1436
- }
1437
- const keyId = event.code || event.key;
1438
- if (event.repeat && releasedKeysRef.current.has(keyId)) {
1439
- event.preventDefault();
1440
- event.stopPropagation();
1441
- return;
1442
- }
1443
- const targetId = control.activeTargetId;
1444
- if (inputDisabled || !targetId || !control.captured && focusedElement(containerRef.current) !== containerRef.current && !containerRef.current?.contains(event.target)) return;
1445
- event.preventDefault();
1446
- event.stopPropagation();
1447
- const clipboardShortcut = resolveClipboardShortcut(event.nativeEvent);
1448
- if (clipboardShortcut === "copy") {
1449
- control.sendInput({
1450
- type: "clipboard.copy",
1451
- targetId
1452
- });
1453
- return;
1454
- }
1455
- if (clipboardShortcut === "cut") {
1456
- control.sendInput({
1457
- type: "clipboard.cut",
1458
- targetId
1459
- });
1460
- return;
1461
- }
1462
- if (clipboardShortcut === "paste") {
1463
- pasteClipboard(control, onNotice);
1464
- return;
1465
- }
1466
- if (!shouldForwardBrowserShortcut(event.nativeEvent)) return;
1467
- const input = keyboardInputMessage(event.nativeEvent, "down");
1468
- if (control.sendInput({
1469
- type: "input.key",
1470
- targetId,
1471
- action: "down",
1472
- ...input
1473
- })) {
1474
- releasedKeysRef.current.delete(keyId);
1475
- pressedKeysRef.current.set(keyId, {
1476
- targetId,
1477
- input
1478
- });
1479
- }
1480
- }
1481
- function handleKeyUp(event) {
1482
- const keyId = event.code || event.key;
1483
- if (releasedKeysRef.current.delete(keyId)) {
1484
- event.preventDefault();
1485
- event.stopPropagation();
1486
- return;
1487
- }
1488
- const pressedKey = pressedKeysRef.current.get(keyId);
1489
- const targetId = pressedKey?.targetId ?? control.activeTargetId;
1490
- const canForwardUntrackedKey = !inputDisabled && (control.captured || focusedElement(containerRef.current) === containerRef.current || Boolean(containerRef.current?.contains(event.target)));
1491
- if (!targetId || !pressedKey && !canForwardUntrackedKey) return;
1492
- if (event.key === "Escape") return;
1493
- event.preventDefault();
1494
- event.stopPropagation();
1495
- if (!pressedKey && resolveClipboardShortcut(event.nativeEvent)) return;
1496
- if (!pressedKey && !shouldForwardBrowserShortcut(event.nativeEvent)) return;
1497
- if (control.sendInput({
1498
- type: "input.key",
1499
- targetId,
1500
- action: "up",
1501
- ...keyboardInputMessage(event.nativeEvent, "up")
1502
- })) pressedKeysRef.current.delete(keyId);
1503
- }
1504
- function handleBlur(event) {
1505
- if (event.relatedTarget instanceof Node && event.currentTarget.contains(event.relatedTarget)) return;
1506
- releasePressedKeys();
1507
- releaseImplicitControl();
1508
- control.setCaptured(false);
1509
- }
1510
- function updateCursorHint(event) {
1511
- const rect = containerRef.current?.getBoundingClientRect();
1512
- if (!rect) return;
1513
- const point = {
1514
- x: event.clientX - rect.left,
1515
- y: event.clientY - rect.top
1516
- };
1517
- cursorHintPointRef.current = point;
1518
- if (cursorHint) setCursorHintPoint(point);
1519
- }
1520
- const status = resolveViewportStatus(control.phase, frameMetadata !== null, control.mediaPhase, control.mediaPath, showingWebRTC);
1521
- const placeholder = resolveViewportPlaceholder(control.phase, control.mediaPhase, control.mediaSwitching);
1522
- const visibleCollaborationError = collaborationHint || isInputOwnershipError(control.collaboration.lastError) ? null : control.collaboration.lastError;
1523
- return /* @__PURE__ */ jsxs("div", {
1524
- ref: containerRef,
1525
- tabIndex: 0,
1526
- onKeyDown: handleKeyDown,
1527
- onKeyUp: handleKeyUp,
1528
- onBlur: handleBlur,
1529
- onClick: handlePointerClick,
1530
- onPointerMove: handlePointerMove,
1531
- onFocus: () => {
1532
- if (!inputDisabled && control.activeTargetId) requestImplicitControl(control.activeTargetId);
1533
- },
1534
- onPointerEnter: handlePointerEnter,
1535
- onPointerLeave: handlePointerLeave,
1536
- onPointerDown: handlePointerDown,
1537
- onPointerUp: handlePointerUp,
1538
- onPointerCancel: handlePointerCancel,
1539
- onWheel: handleWheel,
1540
- onContextMenu: (event) => {
1541
- if (control.captured) event.preventDefault();
1542
- },
1543
- "aria-busy": mediaTransitioning,
1544
- "aria-disabled": inputDisabled,
1545
- className,
1546
- style: {
1547
- position: "relative",
1548
- display: "flex",
1549
- flex: "1 1 0%",
1550
- minHeight: 0,
1551
- alignItems: "center",
1552
- justifyContent: "center",
1553
- overflow: "hidden",
1554
- outline: "none",
1555
- touchAction: "none",
1556
- cursor: localCursorEnabled ? void 0 : "none",
1557
- ...style
1558
- },
1559
- children: [
1560
- showingWebRTC ? /* @__PURE__ */ jsx("div", {
1561
- style: {
1562
- position: "relative",
1563
- overflow: "hidden",
1564
- background: "black",
1565
- transition: "opacity 150ms",
1566
- opacity: mediaTransitioning ? .75 : 1,
1567
- width: displayMetrics.renderedWidth,
1568
- height: displayMetrics.renderedHeight
1569
- },
1570
- children: /* @__PURE__ */ jsx("video", {
1571
- ref: videoRef,
1572
- autoPlay: true,
1573
- muted: true,
1574
- playsInline: true,
1575
- "data-viewport-width": renderWidth,
1576
- "data-viewport-height": renderHeight,
1577
- style: {
1578
- position: "absolute",
1579
- top: 0,
1580
- left: 0,
1581
- maxWidth: "none",
1582
- objectFit: "fill",
1583
- width: displayMetrics.renderedWidth * ((displayedMediaSize?.canvasWidth ?? contentWidth) / contentWidth),
1584
- height: displayMetrics.renderedHeight * ((displayedMediaSize?.canvasHeight ?? contentHeight) / contentHeight)
1585
- }
1586
- })
1587
- }) : frameMetadata ? /* @__PURE__ */ jsx("div", {
1588
- style: {
1589
- position: "relative",
1590
- overflow: "hidden",
1591
- background: "black",
1592
- width: displayMetrics.renderedWidth,
1593
- height: displayMetrics.renderedHeight
1594
- },
1595
- children: /* @__PURE__ */ jsx("img", {
1596
- ref: imageRef,
1597
- alt: "",
1598
- draggable: false,
1599
- style: {
1600
- position: "absolute",
1601
- inset: 0,
1602
- width: "100%",
1603
- height: "100%",
1604
- objectFit: "contain"
1605
- }
1606
- })
1607
- }) : null,
1608
- control.activeTargetId ? /* @__PURE__ */ jsx(CollaborationPaintOverlay, {
1609
- collaboration: control.collaboration,
1610
- targetId: control.activeTargetId,
1611
- enabled: paintOverlayEnabled,
1612
- visible: !control.mediaSwitching && !mediaTransitioning && (showingWebRTC || frameMetadata !== null),
1613
- left: displayMetrics.offsetX,
1614
- top: displayMetrics.offsetY,
1615
- width: displayMetrics.renderedWidth,
1616
- height: displayMetrics.renderedHeight
1617
- }) : null,
1618
- renderOverlay?.({
1619
- status,
1620
- placeholder: showingWebRTC || frameMetadata ? null : placeholder,
1621
- cursorHint: cursorHint && displayedCursorHintPoint ? {
1622
- text: cursorHint,
1623
- ...displayedCursorHintPoint
1624
- } : null,
1625
- followedCursor: followedCursorPoint && followedParticipant ? {
1626
- name: followedParticipant.name,
1627
- ...followedCursorPoint
1628
- } : null,
1629
- collaborationError: visibleCollaborationError?.message ?? null
1630
- })
1631
- ]
1632
- });
1633
- }
1634
- function resolveDisconnectedHint(phase) {
1635
- if (phase === "disconnected" || phase === "error") return "Session disconnected";
1636
- return null;
1637
- }
1638
- function resolveCollaborationHint(collaboration) {
1639
- if (collaboration.holderClientId !== null && collaboration.holderClientId !== collaboration.clientId) return "Input in use";
1640
- if (collaboration.hasControl) return null;
1641
- if (collaboration.lastError?.code === "input_busy" || collaboration.lastError?.code === "input_not_owned") return "Input in use";
1642
- if (collaboration.lastError?.code === "input_unavailable") return "Input unavailable";
1643
- return null;
1644
- }
1645
- function isInputOwnershipError(error) {
1646
- return error?.code === "input_busy" || error?.code === "input_not_owned";
1647
- }
1648
- function enqueueImageFrame(image, decoder, frame) {
1649
- decoder.pending = frame;
1650
- decodeNextImageFrame(image, decoder);
1651
- }
1652
- function decodeNextImageFrame(image, decoder) {
1653
- if (decoder.decodingFrame !== null || decoder.pending === null) return;
1654
- const frame = decoder.pending;
1655
- const generation = decoder.generation;
1656
- decoder.pending = null;
1657
- decoder.decodingFrame = frame;
1658
- setImageFrame(image, frame).then(() => {
1659
- if (decoder.generation !== generation) return;
1660
- decoder.decodingFrame = null;
1661
- decodeNextImageFrame(image, decoder);
1662
- });
1663
- }
1664
- async function setImageFrame(image, frame) {
1665
- const previousSource = image.src;
1666
- const source = URL.createObjectURL(frame.data);
1667
- image.src = source;
1668
- try {
1669
- await image.decode();
1670
- } catch {} finally {
1671
- if (previousSource.startsWith("blob:")) URL.revokeObjectURL(previousSource);
1672
- if (image.src !== source) URL.revokeObjectURL(source);
1673
- }
1674
- }
1675
- function resetImageFrames(image, decoder) {
1676
- resetRasterFrameDecoder(decoder);
1677
- const source = image.src;
1678
- image.removeAttribute("src");
1679
- if (source.startsWith("blob:")) URL.revokeObjectURL(source);
1680
- }
1681
- function resetRasterFrameDecoder(decoder) {
1682
- decoder.generation += 1;
1683
- decoder.decodingFrame = null;
1684
- decoder.pending = null;
1685
- }
1686
- function resolveViewportPlaceholder(phase, mediaPhase, switching) {
1687
- if (phase === "connecting") return "connecting";
1688
- if (phase === "connected" && mediaPhase === "connecting") return "connecting-media";
1689
- if (phase === "connected" && switching) return "switching";
1690
- if (phase === "disconnected" || phase === "error") return "disconnected";
1691
- return "waiting";
1692
- }
1693
- function resolveClipboardShortcut(event) {
1694
- if (!(event.metaKey || event.ctrlKey) || event.altKey) return null;
1695
- switch (event.code) {
1696
- case "KeyC": return "copy";
1697
- case "KeyX": return "cut";
1698
- case "KeyV": return "paste";
1699
- default: return null;
1700
- }
1701
- }
1702
- function resolveMouseButton(button) {
1703
- if (button === 0) return "left";
1704
- if (button === 1) return "middle";
1705
- if (button === 2) return "right";
1706
- return "none";
1707
- }
1708
- function resolveClickCount(targetId, button, point, time, previous) {
1709
- if (previous && previous.targetId === targetId && previous.button === button && time - previous.time <= MULTI_CLICK_MS && Math.abs(previous.point.x - point.x) <= MULTI_CLICK_DISTANCE && Math.abs(previous.point.y - point.y) <= MULTI_CLICK_DISTANCE) return Math.min(previous.clickCount + 1, 3);
1710
- return 1;
1711
- }
1712
- function mouseButtonsForButton(button) {
1713
- switch (button) {
1714
- case "left": return 1;
1715
- case "right": return 2;
1716
- case "middle": return 4;
1717
- case "none": return 0;
1718
- default: return button;
1719
- }
1720
- }
1721
- function clampNumber(value, min, max) {
1722
- return Math.min(Math.max(value, min), max);
1723
- }
1724
- function wheelDeltaScale(deltaMode, viewportHeight) {
1725
- if (deltaMode === WheelEvent.DOM_DELTA_LINE) return 16;
1726
- if (deltaMode === WheelEvent.DOM_DELTA_PAGE) return viewportHeight;
1727
- return 1;
1728
- }
1729
- async function pasteClipboard(control, onNotice) {
1730
- if (!control.activeTargetId) return;
1731
- let text = "";
1732
- try {
1733
- text = await navigator.clipboard.readText();
1734
- } catch (error) {
1735
- console.warn("Clipboard read failed", error);
1736
- onNotice?.({
1737
- level: "error",
1738
- message: "Clipboard read failed"
1739
- });
1740
- return;
1741
- }
1742
- if (!text) return;
1743
- control.sendInput({
1744
- type: "clipboard.paste",
1745
- targetId: control.activeTargetId,
1746
- items: [{
1747
- mimeType: "text/plain",
1748
- data: text
1749
- }]
1750
- });
1751
- }
1752
- function resolveViewportStatus(phase, hasFrame, mediaPhase, mediaPath, showingWebRTC) {
1753
- if (phase !== "connected") return "offline";
1754
- if (mediaPhase === "live" && showingWebRTC) return "webrtc";
1755
- if (!hasFrame) return "offline";
1756
- return mediaPath === "websocket-live" ? "websocket" : "webrtc";
1757
- }
1758
- function focusedElement(node) {
1759
- const root = node?.getRootNode();
1760
- return root instanceof Document || root instanceof ShadowRoot ? root.activeElement : null;
1761
- }
1762
- //#endregion
1763
- //#region src/hooks/use-browser-control.ts
1764
- const emptyIceServers$1 = [];
1765
- const AUTO_SIZE_DEFAULT_STORAGE_KEY = "aperture.viewport.auto-size-default";
1766
- function useBrowserControl({ access, displayName, enabled = true, webrtcProducerSupported = false, webrtcIceServers = emptyIceServers$1, onNotice }) {
1767
- const runtime = useRuntime();
1768
- const onNoticeRef = useRef(onNotice);
1769
- onNoticeRef.current = onNotice;
1770
- const notify = (level, message) => Effect.sync(() => onNoticeRef.current?.({
1771
- level,
1772
- message
1773
- }));
1774
- const [viewportAutoSizeDefault, setViewportAutoSizeDefaultState] = useState(loadAutoSizeDefault);
1775
- const [viewportAutoSync, setViewportAutoSyncState] = useState(() => viewportAutoSizeDefault);
1776
- const viewportAutoSyncRef = useRef(viewportAutoSync);
1777
- viewportAutoSyncRef.current = viewportAutoSync;
1778
- const autoSizePreference = useCallback(() => viewportAutoSyncRef.current, []);
1779
- const live = useLiveSession({
1780
- access,
1781
- displayName,
1782
- enabled: enabled && access !== null,
1783
- webrtcSupported: webrtcProducerSupported,
1784
- iceServers: webrtcIceServers,
1785
- autoSize: autoSizePreference
1786
- });
1787
- const collaborationRole = live.collaboration.role;
1788
- const [targetOrder, setTargetOrder] = useState([]);
1789
- const targets = useMemo(() => mergeTargetsInCurrentOrder(targetOrder, live.targets), [live.targets, targetOrder]);
1790
- const liveTargetsRef = useRef(live.targets);
1791
- liveTargetsRef.current = live.targets;
1792
- const phaseRef = useRef(live.phase);
1793
- phaseRef.current = live.phase;
1794
- const [viewport, setViewportState] = useState(DEFAULT_VIEWPORT);
1795
- const [browserViewportSize, setBrowserViewportSizeState] = useState(null);
1796
- const [captured, setCaptured] = useState(false);
1797
- const [recordingBusy, setRecordingBusy] = useState(false);
1798
- const canRecord = collaborationRole === "owner" || collaborationRole === "editor";
1799
- const loadTargetThumbnail = useMemo(() => access === null ? null : (targetId) => getTargetThumbnail(access, targetId), [access]);
1800
- const activeTargetIdRef = useRef(null);
1801
- const viewportRef = useRef(viewport);
1802
- const inputDimensionsRef = useRef(DEFAULT_VIEWPORT);
1803
- const browserViewportSizeRef = useRef(null);
1804
- activeTargetIdRef.current = live.activeTargetId;
1805
- viewportRef.current = viewport;
1806
- browserViewportSizeRef.current = browserViewportSize;
1807
- useEffect(() => {
1808
- if (live.phase !== "connected") setCaptured(false);
1809
- }, [live.phase]);
1810
- useEffect(() => {
1811
- if (!live.mediaSize) return;
1812
- const current = viewportRef.current;
1813
- if (current.width === live.mediaSize.width && current.height === live.mediaSize.height && current.deviceScaleFactor === live.mediaSize.deviceScaleFactor) return;
1814
- setViewportState(createBrowserViewport(live.mediaSize, live.mediaSize.deviceScaleFactor));
1815
- }, [live.mediaSize]);
1816
- const sendInput = useCallback((message) => {
1817
- if (!enabled || access === null) return false;
1818
- return live.sendBrowserInput(message, inputDimensionsRef.current);
1819
- }, [
1820
- access,
1821
- enabled,
1822
- live
1823
- ]);
1824
- const activateTarget = useCallback((targetId) => {
1825
- live.selectTarget(targetId);
1826
- }, [live]);
1827
- const reorderTargets = useCallback((sourceTargetId, destinationTargetId, placement) => {
1828
- if (sourceTargetId === destinationTargetId) return;
1829
- setTargetOrder((order) => {
1830
- const current = mergeTargetsInCurrentOrder(order, liveTargetsRef.current).map((target) => target.id);
1831
- const sourceIndex = current.indexOf(sourceTargetId);
1832
- const destinationIndex = current.indexOf(destinationTargetId);
1833
- const source = current[sourceIndex];
1834
- if (sourceIndex === -1 || destinationIndex === -1 || !source) return order;
1835
- const next = [...current];
1836
- next.splice(sourceIndex, 1);
1837
- const requestedIndex = placement === "after" ? destinationIndex + 1 : destinationIndex;
1838
- const nextIndex = sourceIndex < requestedIndex ? requestedIndex - 1 : requestedIndex;
1839
- if (nextIndex === sourceIndex) return order;
1840
- next.splice(nextIndex, 0, source);
1841
- return next;
1842
- });
1843
- }, []);
1844
- const createAndSelectTarget = useCallback((url) => runtime.runPromise(live.request("target.create", { url }).pipe(Effect.map((result) => result.targetId ?? null), Effect.catch((error) => notify("error", errorMessage(error, "Tab could not be created")).pipe(Effect.as(null))))), [live, runtime]);
1845
- const createTarget = useCallback((url = "about:blank") => {
1846
- createAndSelectTarget(url);
1847
- }, [createAndSelectTarget]);
1848
- const duplicateTarget = useCallback((target) => {
1849
- createAndSelectTarget(target.url || "about:blank").then((targetId) => {
1850
- if (targetId) reorderTargets(targetId, target.id, "after");
1851
- });
1852
- }, [createAndSelectTarget, reorderTargets]);
1853
- const closeTarget = useCallback((targetId) => {
1854
- live.command("target.close", { targetId });
1855
- }, [live]);
1856
- const navigate = useCallback((url) => {
1857
- const targetId = activeTargetIdRef.current;
1858
- if (targetId) live.command("page.navigate", {
1859
- targetId,
1860
- url
1861
- });
1862
- }, [live]);
1863
- const reload = useCallback((targetId) => {
1864
- live.command("page.reload", { targetId });
1865
- }, [live]);
1866
- const stopLoading = useCallback(() => {
1867
- const targetId = activeTargetIdRef.current;
1868
- if (targetId) live.command("page.stop-loading", { targetId });
1869
- }, [live]);
1870
- const historyBack = useCallback(() => {
1871
- const targetId = activeTargetIdRef.current;
1872
- if (targetId) live.command("page.history-back", { targetId });
1873
- }, [live]);
1874
- const historyForward = useCallback(() => {
1875
- const targetId = activeTargetIdRef.current;
1876
- if (targetId) live.command("page.history-forward", { targetId });
1877
- }, [live]);
1878
- const viewportOwnership = live.viewportOwnership;
1879
- const viewportOwnershipRef = useRef(viewportOwnership);
1880
- viewportOwnershipRef.current = viewportOwnership;
1881
- const viewportAutoSizeActive = viewportAutoSync && (viewportOwnership === null || viewportOwnership.ownerClientId === live.collaboration.clientId);
1882
- const viewportAutoSizeActiveRef = useRef(viewportAutoSizeActive);
1883
- viewportAutoSizeActiveRef.current = viewportAutoSizeActive;
1884
- useEffect(() => {
1885
- if (viewportOwnership !== null) {
1886
- viewportAutoSyncRef.current = viewportOwnership.autoSize;
1887
- setViewportAutoSyncState(viewportOwnership.autoSize);
1888
- }
1889
- }, [viewportOwnership]);
1890
- const runAutoSizeViewport = useEffectCallback((payload) => live.request("viewport.set", payload).pipe(Effect.ignore), [live.request]);
1891
- const commitViewport = useCallback((preset, autoSize) => {
1892
- setViewportState(preset);
1893
- const targetId = activeTargetIdRef.current;
1894
- if (targetId === null) return;
1895
- const payload = {
1896
- targetId,
1897
- width: preset.width,
1898
- height: preset.height,
1899
- deviceScaleFactor: preset.deviceScaleFactor
1900
- };
1901
- if (autoSize && viewportOwnershipRef.current !== null) runAutoSizeViewport({
1902
- ...payload,
1903
- autoSize: true
1904
- });
1905
- else live.command("viewport.set", payload);
1906
- }, [live.command, runAutoSizeViewport]);
1907
- const setViewportAutoSync = useCallback((nextEnabled) => {
1908
- if (viewportAutoSyncRef.current === nextEnabled) return;
1909
- viewportAutoSyncRef.current = nextEnabled;
1910
- setViewportAutoSyncState(nextEnabled);
1911
- if (viewportOwnershipRef.current !== null) live.command("viewport.auto-size.set", { enabled: nextEnabled });
1912
- }, [live.command]);
1913
- useEffect(() => {
1914
- const size = browserViewportSizeRef.current;
1915
- if (viewportAutoSizeActive && live.phase === "connected" && live.activeTargetId !== null && size !== null) commitViewport(createBrowserViewport(size, viewportRef.current.deviceScaleFactor), true);
1916
- }, [
1917
- commitViewport,
1918
- live.activeTargetId,
1919
- live.phase,
1920
- viewportAutoSizeActive
1921
- ]);
1922
- const setViewport = useCallback((preset) => {
1923
- setViewportAutoSync(false);
1924
- commitViewport(preset, false);
1925
- }, [commitViewport, setViewportAutoSync]);
1926
- const setBrowserViewportSize = useCallback((size) => {
1927
- const next = {
1928
- width: Math.round(size.width),
1929
- height: Math.round(size.height)
1930
- };
1931
- if (next.width < 1 || next.height < 1) return;
1932
- const current = browserViewportSizeRef.current;
1933
- if (current?.width === next.width && current.height === next.height) return;
1934
- browserViewportSizeRef.current = next;
1935
- setBrowserViewportSizeState(next);
1936
- if (viewportAutoSizeActiveRef.current) commitViewport(createBrowserViewport(next, viewportRef.current.deviceScaleFactor), true);
1937
- }, [commitViewport]);
1938
- const setViewportToBrowserSize = useCallback(() => {
1939
- const size = browserViewportSizeRef.current;
1940
- if (!size) return;
1941
- setViewportAutoSync(false);
1942
- commitViewport(createBrowserViewport(size, viewportRef.current.deviceScaleFactor), false);
1943
- }, [commitViewport, setViewportAutoSync]);
1944
- const takeOverViewport = useCallback(() => {
1945
- viewportAutoSyncRef.current = true;
1946
- setViewportAutoSyncState(true);
1947
- live.command("viewport.owner.claim");
1948
- }, [live.command]);
1949
- const setViewportAutoSizeDefault = useCallback((nextEnabled) => {
1950
- setViewportAutoSizeDefaultState(nextEnabled);
1951
- try {
1952
- window.localStorage.setItem(AUTO_SIZE_DEFAULT_STORAGE_KEY, String(nextEnabled));
1953
- } catch {}
1954
- }, []);
1955
- const settleRecording = (effect, failure) => effect.pipe(Effect.catch((error) => notify("error", errorMessage(error, failure))), Effect.ensuring(Effect.sync(() => setRecordingBusy(false))));
1956
- const runStartRecording = useEffectCallback((mode, targetId) => settleRecording(live.request("recording.start", {
1957
- mode,
1958
- targetId
1959
- }), "Recording failed to start"), [live]);
1960
- const startRecording = useCallback((mode) => {
1961
- const targetId = activeTargetIdRef.current;
1962
- if (!targetId || !canRecord || recordingBusy) return;
1963
- setRecordingBusy(true);
1964
- runStartRecording(mode, targetId);
1965
- }, [
1966
- canRecord,
1967
- recordingBusy,
1968
- runStartRecording
1969
- ]);
1970
- const runStopRecording = useEffectCallback((access, recordingId) => settleRecording(live.request("recording.stop", { recordingId }).pipe(Effect.andThen(downloadSessionRecording(access, recordingId)), Effect.flatMap(({ blob, filename }) => {
1971
- const recording = live.recordings.find((candidate) => candidate.recordingId === recordingId);
1972
- return downloadBlob(blob, filename ?? `${access.sessionId}-${recording?.targetId ?? "target"}-${recordingId}.webm`);
1973
- }), Effect.andThen(notify("success", "Recording saved"))), "Recording failed to stop"), [live]);
1974
- const stopRecording = useCallback((recordingId) => {
1975
- if (access === null || recordingBusy) return;
1976
- setRecordingBusy(true);
1977
- runStopRecording(access, recordingId);
1978
- }, [
1979
- access,
1980
- recordingBusy,
1981
- runStopRecording
1982
- ]);
1983
- const runCancelRecording = useEffectCallback((recordingId) => settleRecording(live.request("recording.cancel", { recordingId }).pipe(Effect.andThen(notify("success", "Recording stopped"))), "Recording failed to stop"), [live]);
1984
- const cancelRecording = useCallback((recordingId) => {
1985
- if (recordingBusy) return;
1986
- setRecordingBusy(true);
1987
- runCancelRecording(recordingId);
1988
- }, [recordingBusy, runCancelRecording]);
1989
- const runSetRemoteCursor = useEffectCallback((visible) => live.request("presentation.cursor.set", { visible }).pipe(Effect.catch((error) => notify("error", errorMessage(error, "Remote cursor could not be updated")))), [live]);
1990
- const setRemoteCursorEnabled = useCallback((visible) => {
1991
- if (access !== null) runSetRemoteCursor(visible);
1992
- }, [access, runSetRemoteCursor]);
1993
- const [watchableAutomation, setWatchableAutomation] = useState(false);
1994
- const commandRef = useRef(live.command);
1995
- commandRef.current = live.command;
1996
- useEffect(() => {
1997
- if (live.phase === "connected" && canRecord) commandRef.current("automation.pacing.set", { pacing: watchableAutomation ? "watchable" : "normal" });
1998
- }, [
1999
- live.phase,
2000
- canRecord,
2001
- watchableAutomation
2002
- ]);
2003
- const runSelectPresentation = useEffectCallback((selection) => live.selectPresentation(selection).pipe(Effect.catch((error) => notify("error", errorMessage(error, "Presentation could not be updated")))), [live]);
2004
- const selectMediaStream = useCallback((selection) => {
2005
- if (!enabled || access === null || live.mediaSwitching) return false;
2006
- runSelectPresentation(selection);
2007
- return true;
2008
- }, [
2009
- access,
2010
- enabled,
2011
- live.mediaSwitching,
2012
- runSelectPresentation
2013
- ]);
2014
- const setWebRTCStreamSettings = useCallback((settings) => selectMediaStream({
2015
- kind: "webrtc",
2016
- quality: settings
2017
- }), [selectMediaStream]);
2018
- const commands = useMemo(() => {
2019
- const connected = (effect) => Effect.suspend(() => phaseRef.current === "connected" ? effect : Effect.fail(new LiveSessionError({ message: "the session is not connected" })));
2020
- const request = (type, payload) => connected(live.request(type, payload));
2021
- const onActiveTarget = (type, payload = {}) => connected(Effect.suspend(() => {
2022
- const targetId = activeTargetIdRef.current;
2023
- return targetId ? live.request(type, {
2024
- targetId,
2025
- ...payload
2026
- }) : Effect.fail(new LiveSessionError({ message: "no tab is active" }));
2027
- })).pipe(Effect.asVoid);
2028
- return {
2029
- navigate: (url) => onActiveTarget("page.navigate", { url }),
2030
- historyBack: () => onActiveTarget("page.history-back"),
2031
- historyForward: () => onActiveTarget("page.history-forward"),
2032
- reload: (targetId) => targetId ? request("page.reload", { targetId }).pipe(Effect.asVoid) : onActiveTarget("page.reload"),
2033
- stopLoading: () => onActiveTarget("page.stop-loading"),
2034
- createTarget: (url = "about:blank") => request("target.create", { url }).pipe(Effect.map((result) => result.targetId ?? null)),
2035
- closeTarget: (targetId) => request("target.close", { targetId }).pipe(Effect.asVoid),
2036
- activateTarget: (targetId) => connected(live.requestSelectTarget(targetId))
2037
- };
2038
- }, [live.request, live.requestSelectTarget]);
2039
- const activeTarget = useMemo(() => targets.find((target) => target.id === live.activeTargetId) ?? null, [live.activeTargetId, targets]);
2040
- const mediaPath = live.transport === "webrtc" ? "webrtc-live" : "websocket-live";
2041
- const mediaPhase = live.phase === "connected" ? "live" : live.phase === "connecting" ? "connecting" : live.phase === "error" ? "failed" : "idle";
2042
- return {
2043
- phase: live.phase,
2044
- targets,
2045
- activeTargetId: live.activeTargetId,
2046
- activeTarget,
2047
- frames: live.frames,
2048
- mediaPhase,
2049
- mediaStream: live.mediaStream,
2050
- mediaStreamSettings: live.presentation?.quality ?? null,
2051
- mediaVideoProfiles: live.presentation?.profiles ?? [],
2052
- mediaSize: live.mediaSize,
2053
- mediaPath,
2054
- mediaTargetId: live.activeTargetId,
2055
- mediaSwitching: live.mediaSwitching,
2056
- viewport,
2057
- browserViewportSize,
2058
- viewportAutoSync,
2059
- viewportAutoSizeActive,
2060
- viewportOwnership,
2061
- viewportAutoSizeDefault,
2062
- captured,
2063
- recordings: live.recordings,
2064
- canRecord,
2065
- loadTargetThumbnail,
2066
- recordingBusy,
2067
- remoteCursorEnabled: live.presentation?.cursorVisible ?? true,
2068
- watchableAutomation,
2069
- collaboration: live.collaboration,
2070
- commands,
2071
- setCaptured,
2072
- setInputDimensions: (size) => {
2073
- inputDimensionsRef.current = size;
2074
- },
2075
- setViewport,
2076
- setBrowserViewportSize,
2077
- setViewportAutoSync,
2078
- setViewportToBrowserSize,
2079
- setViewportAutoSizeDefault,
2080
- takeOverViewport,
2081
- setWebRTCStreamSettings,
2082
- selectMediaStream,
2083
- sendInput,
2084
- activateTarget,
2085
- reorderTargets,
2086
- createTarget,
2087
- duplicateTarget,
2088
- closeTarget,
2089
- navigate,
2090
- reload,
2091
- stopLoading,
2092
- historyBack,
2093
- historyForward,
2094
- startRecording,
2095
- stopRecording,
2096
- cancelRecording,
2097
- setRemoteCursorEnabled,
2098
- setWatchableAutomation,
2099
- reconnect: live.reconnect
2100
- };
2101
- }
2102
- function mergeTargetsInCurrentOrder(order, nextTargets) {
2103
- const nextById = new Map(nextTargets.map((target) => [target.id, target]));
2104
- const seen = /* @__PURE__ */ new Set();
2105
- const ordered = [];
2106
- for (const targetId of order) {
2107
- const nextTarget = nextById.get(targetId);
2108
- if (nextTarget) {
2109
- ordered.push(nextTarget);
2110
- seen.add(nextTarget.id);
2111
- }
2112
- }
2113
- for (const nextTarget of nextTargets) if (!seen.has(nextTarget.id)) ordered.push(nextTarget);
2114
- return ordered;
2115
- }
2116
- function loadAutoSizeDefault() {
2117
- try {
2118
- return window.localStorage.getItem(AUTO_SIZE_DEFAULT_STORAGE_KEY) === "true";
2119
- } catch {
2120
- return false;
2121
- }
2122
- }
2123
- function createBrowserViewport(size, deviceScaleFactor) {
2124
- return createViewportPreset(size.width, size.height, deviceScaleFactor);
2125
- }
2126
- const downloadBlob = (blob, filename) => Effect.acquireUseRelease(Effect.sync(() => URL.createObjectURL(blob)), (url) => Effect.sync(() => {
2127
- const link = document.createElement("a");
2128
- link.href = url;
2129
- link.download = filename;
2130
- link.click();
2131
- }), (url) => Effect.sync(() => URL.revokeObjectURL(url)).pipe(Effect.delay(0)));
2132
- function errorMessage(cause, fallback) {
2133
- return cause instanceof Error && cause.message ? cause.message : fallback;
2134
- }
2135
- //#endregion
2136
- //#region src/runtime.ts
2137
- const makeApertureRuntime = (options = {}) => ManagedRuntime.make(Layer.mergeAll(FetchHttpClient.layer, apiClientLayer.pipe(Layer.provide(options.baseUrl ? baseUrlLayer(options.baseUrl) : Layer.empty), Layer.provide(FetchHttpClient.layer)), Layer.succeed(HttpClient.TracerPropagationEnabled, false)));
2138
- //#endregion
2139
- //#region src/provider.tsx
2140
- function ApertureProvider({ baseUrl, children }) {
2141
- const [runtime, setRuntime] = useState(null);
2142
- useEffect(() => {
2143
- const created = makeApertureRuntime({ baseUrl });
2144
- setRuntime(created);
2145
- return () => {
2146
- setRuntime(null);
2147
- created.dispose();
2148
- };
2149
- }, [baseUrl]);
2150
- return runtime ? /* @__PURE__ */ jsx(RuntimeProvider, {
2151
- runtime,
2152
- baseUrl,
2153
- children
2154
- }) : null;
2155
- }
2156
- //#endregion
2157
- //#region src/session.ts
2158
- /** Convert an editor/viewer share link into direct session access. */
2159
- function shareSessionAccess(token, baseUrl) {
2160
- const sessionId = token.slice(4, 40);
2161
- if (!(token.startsWith("ape_") || token.startsWith("apv_")) || token[40] !== "_" || token.length <= 41) return null;
2162
- return {
2163
- kind: "direct",
2164
- baseUrl,
2165
- sessionId,
2166
- credentials: {
2167
- kind: "bearer",
2168
- token: Redacted.make(token),
2169
- authorityType: null,
2170
- tenantId: null,
2171
- selectedTenantId: null
2172
- }
2173
- };
2174
- }
2175
- const emptyIceServers = [];
2176
- function failedStatus(httpStatus) {
2177
- if (httpStatus === 401 || httpStatus === 403) return "denied";
2178
- if (httpStatus === 410) return "expired";
2179
- return "unavailable";
2180
- }
2181
- function useSession({ access, displayName, onNotice }) {
2182
- const [state, setState] = useState({
2183
- access: null,
2184
- status: "loading",
2185
- browser: null
2186
- });
2187
- useFork(() => {
2188
- if (access === null) return;
2189
- setState({
2190
- access,
2191
- status: "loading",
2192
- browser: null
2193
- });
2194
- return getSessionStatus(access).pipe(Effect.match({
2195
- onFailure: (error) => setState({
2196
- access,
2197
- status: failedStatus(error.status),
2198
- browser: null
2199
- }),
2200
- onSuccess: (browser) => setState(access.kind === "direct" && browser.sessionId !== access.sessionId ? {
2201
- access,
2202
- status: "unavailable",
2203
- browser: null
2204
- } : {
2205
- access,
2206
- status: "ready",
2207
- browser
2208
- })
2209
- }));
2210
- }, [access]);
2211
- const browser = state.access === access ? state.browser : null;
2212
- const control = useBrowserControl({
2213
- access: browser === null ? null : access,
2214
- displayName,
2215
- webrtcProducerSupported: browser?.media.mode === "auto" && browser.media.webrtcProducer,
2216
- webrtcIceServers: browser?.media.iceServers ?? emptyIceServers,
2217
- onNotice
2218
- });
2219
- return {
2220
- status: access === null ? "invalid" : state.access !== access ? "loading" : state.status,
2221
- browser,
2222
- control
2223
- };
2224
- }
2225
- //#endregion
2226
- export { makeApertureRuntime as a, collaborationPaintLifetimeMs as c, RuntimeProviderMissingError as d, useBaseUrl as f, useRuntime as g, useRunApi as h, ApertureProvider as i, useLiveSession as l, useFork as m, shareSessionAccess as n, useBrowserControl as o, useEffectCallback as p, useSession as r, SessionViewport as s, LiveSessionError$1 as t, RuntimeProvider as u };
2227
-
2228
- //# sourceMappingURL=headless-CPoXwbFz.js.map