Open History to see the last commit
1import {
2 createPreviewFramePainter,
3 createPreviewStreamClient,
4 previewStreamModifiers,
5 type PreviewStreamClient,
6 type PreviewStreamControl,
7 type PreviewStreamInput,
8 type PreviewStreamPointer,
9 type PreviewStreamViewport,
10} from "@t3tools/client-runtime/preview/server-browser-stream";
11
12import type { PreviewStreamConfiguration, PreviewStreamMessage } from "./preview-stream-document";
13
14declare global {
15 interface Window {
16 ReactNativeWebView: { postMessage: (message: string) => void };
17 }
18}
19
20interface PresentationVideo extends HTMLVideoElement {
21 webkitSetPresentationMode?: (mode: "inline" | "picture-in-picture") => void;
22 webkitPresentationMode?: string;
23}
24
25type WheelInput = Extract<PreviewStreamInput, { type: "wheel" }>;
26type MouseInput = Extract<PreviewStreamInput, { type: "mouse" }>;
27const mouseButton = (button: number): MouseInput["button"] =>
28 button === 0 ? "left" : button === 1 ? "middle" : button === 2 ? "right" : "none";
29
30const RESIZE_DEBOUNCE_MS = 150;
31const TAP_SLOP_PX = 8;
32const MULTI_CLICK_MS = 500;
33const MULTI_CLICK_SLOP_PX = 4;
34const WHEEL_LINE_PX = 16;
35const MAX_PIXEL_RATIO = 2;
36// A tap this close to an answered probe, this soon, reuses its answer. On a slow
37// link the answer lands after touch end, too late for iOS to raise the keyboard.
38const PROBE_REUSE_PX = 24;
39const PROBE_REUSE_MS = 10_000;
40// Kept in the hidden textarea so a soft keyboard's backspace has something to
41// delete and fires `input`; Gboard's keydown carries keyCode 229 and no key.
42const SENTINEL = "\u200b";
43const AGENT_CURSOR_ACTIVE_MS = 700;
44const AGENT_CURSOR_SVG =
45 '<svg width="20" height="20" viewBox="0 0 24 24" fill="#fff" stroke="#3b82f6" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z"/></svg>';
46
47interface Viewer {
48 readonly stop: () => void;
49 readonly command: (input: PreviewStreamInput) => void;
50 readonly togglePictureInPicture: () => void;
51}
52
53let activeViewer: Viewer | null = null;
54
55export function stop() {
56 activeViewer?.stop();
57 activeViewer = null;
58}
59
60export function command(input: PreviewStreamInput) {
61 activeViewer?.command(input);
62}
63
64export function pictureInPicture() {
65 activeViewer?.togglePictureInPicture();
66}
67
68export function start(configuration: PreviewStreamConfiguration) {
69 stop();
70 const post = (message: PreviewStreamMessage) => {
71 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- The native WebView bridge takes one string.
72 window.ReactNativeWebView.postMessage(JSON.stringify(message));
73 };
74 const { interactive } = configuration;
75 document.body.style.background = configuration.background;
76 const container = document.createElement("div");
77 const canvas = document.createElement("canvas");
78 canvas.setAttribute("role", "img");
79 canvas.setAttribute("aria-label", "Browser page");
80 const agentCursor = document.createElement("div");
81 agentCursor.className = "agent-cursor";
82 agentCursor.setAttribute("aria-hidden", "true");
83 agentCursor.innerHTML = AGENT_CURSOR_SVG;
84 container.append(canvas, agentCursor);
85 const input = document.createElement("textarea");
86 input.setAttribute("aria-label", "Browser page input");
87 input.autocapitalize = "off";
88 input.autocomplete = "off";
89 input.spellcheck = false;
90 input.setAttribute("autocorrect", "off");
91 input.disabled = true;
92 document.body.replaceChildren(container, ...(interactive ? [input] : []));
93
94 let stopped = false;
95 let streaming = false;
96 let viewport: PreviewStreamViewport | null = null;
97 let size: { width: number; height: number } | null = null;
98 let cap: { width: number; height: number } | null = null;
99 let client: PreviewStreamClient | null = null;
100 let control: PreviewStreamControl | null = null;
101 let resizeTimer: ReturnType<typeof setTimeout> | null = null;
102 let wheelFrame: number | null = null;
103 let pendingWheel: WheelInput | null = null;
104 let mouseFrame: number | null = null;
105 let pendingMouse: MouseInput | null = null;
106 let mouseButtons = 0;
107 const mouseClicks = { left: 1, middle: 1, right: 1, none: 1 };
108 let probe: {
109 readonly x: number;
110 readonly y: number;
111 readonly clientX: number;
112 readonly clientY: number;
113 editable: boolean | null;
114 end: "touching" | "acted" | "late" | "panned";
115 } | null = null;
116 let probeCache: {
117 readonly clientX: number;
118 readonly clientY: number;
119 readonly editable: boolean;
120 readonly time: number;
121 } | null = null;
122 let keySent = false;
123 let touch: {
124 start: PointerEvent;
125 last: PointerEvent;
126 panning: boolean;
127 } | null = null;
128 let lastTap: {
129 time: number;
130 x: number;
131 y: number;
132 count: number;
133 button: MouseInput["button"];
134 } | null = null;
135
136 const reportStatus = (status: "connecting" | "streaming") => {
137 streaming = status === "streaming";
138 post({ type: "status", status });
139 };
140 const painter = createPreviewFramePainter(canvas, () => {
141 if (!streaming && !stopped) reportStatus("streaming");
142 sendPictureInPictureFrame();
143 });
144 const send = (message: PreviewStreamInput) => client?.send(message) ?? false;
145 const clearInput = () => {
146 if (wheelFrame !== null) cancelAnimationFrame(wheelFrame);
147 if (mouseFrame !== null) cancelAnimationFrame(mouseFrame);
148 wheelFrame = mouseFrame = null;
149 pendingWheel = pendingMouse = null;
150 mouseButtons = 0;
151 Object.assign(mouseClicks, { left: 1, middle: 1, right: 1, none: 1 });
152 probe = probeCache = touch = lastTap = null;
153 keySent = false;
154 input.value = SENTINEL;
155 input.disabled = true;
156 input.blur();
157 };
158
159 const connect = () => {
160 if (client) reportStatus("connecting");
161 client?.stop();
162 control = null;
163 clearInput();
164 if (!cap || stopped) return;
165 const next = createPreviewStreamClient(
166 {
167 access: configuration.access,
168 threadId: configuration.threadId,
169 tabId: configuration.tabId,
170 maxWidth: cap.width,
171 maxHeight: cap.height,
172 interactive,
173 },
174 {
175 onFrame: (jpeg) => painter.paint(jpeg),
176 onPointer: showAgentCursor,
177 onClipboard: (text) => post({ type: "clipboard", text }),
178 onDownload: (download) => post({ type: "download", ...download }),
179 onFileChooser: (chooser) => post({ type: "fileChooser", chooser }),
180 onViewport: (page) => {
181 if (viewport?.width === page.width && viewport.height === page.height) return;
182 viewport = page;
183 post({ type: "viewport", width: page.width, height: page.height });
184 },
185 onProbe: (result) => {
186 if (control?.controller !== "you") return;
187 const current = probe;
188 if (!current || current.x !== result.x || current.y !== result.y) return;
189 probeCache = {
190 clientX: current.clientX,
191 clientY: current.clientY,
192 editable: result.editable,
193 time: performance.now(),
194 };
195 if (current.end === "touching") {
196 current.editable = result.editable;
197 return;
198 }
199 probe = null;
200 if (current.end === "panned") return;
201 if (current.end === "acted" && current.editable === result.editable) return;
202 // Late or corrected answer: Android still raises the keyboard; iOS waits
203 // for the next tap, which can reuse this answer.
204 if (result.editable) input.focus({ preventScroll: true });
205 else input.blur();
206 },
207 onControl: (nextControl) => {
208 const previous = control;
209 control = nextControl;
210 post({ type: "control", ...nextControl });
211 if (nextControl.controller === "you") agentCursor.style.opacity = "0";
212 if (nextControl.controller !== "you") clearInput();
213 else {
214 input.disabled = !interactive;
215 if (interactive && size && previous?.controller !== "you")
216 next.send({ type: "resize", ...size });
217 }
218 },
219 onConnectedChange: (connected) => {
220 if (!connected) {
221 control = null;
222 clearInput();
223 if (streaming) reportStatus("connecting");
224 return;
225 }
226 },
227 onUnauthorized: () => post({ type: "unauthorized" }),
228 onGone: () => post({ type: "gone" }),
229 onHostSetup: (setup) => post({ type: "hostSetup", ...setup }),
230 },
231 );
232 client = next;
233 };
234
235 const measure = () => {
236 resizeTimer = null;
237 const rect = container.getBoundingClientRect();
238 if (rect.width < 1 || rect.height < 1) return;
239 const next = { width: Math.round(rect.width), height: Math.round(rect.height) };
240 if (size?.width === next.width && size.height === next.height) return;
241 size = next;
242 if (interactive) send({ type: "resize", ...next });
243 const ratio = Math.min(window.devicePixelRatio || 1, MAX_PIXEL_RATIO);
244 const side = Math.max(next.width, next.height);
245 const width = Math.round((interactive ? next.width : side) * ratio);
246 const height = Math.round((interactive ? next.height : side) * ratio);
247 if (cap && cap.width >= width && cap.height >= height) return;
248 cap = { width: Math.max(width, cap?.width ?? 0), height: Math.max(height, cap?.height ?? 0) };
249 connect();
250 };
251 const observer = new ResizeObserver(() => {
252 if (resizeTimer !== null) clearTimeout(resizeTimer);
253 resizeTimer = setTimeout(measure, size === null ? 0 : RESIZE_DEBOUNCE_MS);
254 });
255 observer.observe(container);
256
257 // iOS keeps the layout viewport under the soft keyboard; follow the visible area
258 // so the page resizes above it.
259 const visualViewport = window.visualViewport;
260 const followVisualViewport = () => {
261 if (!visualViewport) return;
262 container.style.top = `${visualViewport.offsetTop}px`;
263 container.style.height = `${visualViewport.height}px`;
264 };
265 if (interactive) {
266 visualViewport?.addEventListener("resize", followVisualViewport);
267 visualViewport?.addEventListener("scroll", followVisualViewport);
268 }
269
270 let agentCursorTimer: ReturnType<typeof setTimeout> | null = null;
271 const showAgentCursor = (pointer: PreviewStreamPointer) => {
272 if (!viewport || canvas.width === 0 || canvas.height === 0 || control?.controller === "you")
273 return;
274 const box = { width: canvas.clientWidth, height: canvas.clientHeight };
275 const fit = Math.min(box.width / canvas.width, box.height / canvas.height);
276 const width = canvas.width * fit;
277 const height = canvas.height * fit;
278 const left = (box.width - width) / 2 + (pointer.x * width) / viewport.width;
279 const top = (box.height - height) / 2 + (pointer.y * height) / viewport.height;
280 agentCursor.style.transform = `translate3d(${left}px, ${top}px, 0)`;
281 agentCursor.style.opacity = "1";
282 if (pointer.phase === "click") {
283 agentCursor.querySelector(".ping")?.remove();
284 const ping = document.createElement("span");
285 ping.className = "ping";
286 agentCursor.prepend(ping);
287 }
288 if (agentCursorTimer !== null) clearTimeout(agentCursorTimer);
289 agentCursorTimer = setTimeout(() => {
290 agentCursor.style.opacity = control?.controller === "agent" ? "0.35" : "0";
291 }, AGENT_CURSOR_ACTIVE_MS);
292 };
293
294 const pagePoint = (clientX: number, clientY: number, clamp: boolean) => {
295 if (!viewport || canvas.width === 0 || canvas.height === 0 || control?.controller !== "you")
296 return null;
297 const rect = canvas.getBoundingClientRect();
298 const fit = Math.min(rect.width / canvas.width, rect.height / canvas.height);
299 const width = canvas.width * fit;
300 const height = canvas.height * fit;
301 if (!(width > 0 && height > 0)) return null;
302 const scale = viewport.width / width;
303 const x = (clientX - rect.left - (rect.width - width) / 2) * scale;
304 const y = (clientY - rect.top - (rect.height - height) / 2) * (viewport.height / height);
305 const inside = x >= 0 && y >= 0 && x <= viewport.width && y <= viewport.height;
306 if (!inside && !clamp) return null;
307 return {
308 x: Math.min(Math.max(x, 0), viewport.width),
309 y: Math.min(Math.max(y, 0), viewport.height),
310 scale,
311 };
312 };
313
314 const flushWheel = () => {
315 if (wheelFrame !== null) cancelAnimationFrame(wheelFrame);
316 wheelFrame = null;
317 const wheel = pendingWheel;
318 pendingWheel = null;
319 if (wheel) send(wheel);
320 };
321 const queueWheel = (point: { x: number; y: number }, deltaX: number, deltaY: number) => {
322 pendingWheel = {
323 type: "wheel",
324 x: point.x,
325 y: point.y,
326 deltaX: (pendingWheel?.deltaX ?? 0) + deltaX,
327 deltaY: (pendingWheel?.deltaY ?? 0) + deltaY,
328 modifiers: 0,
329 };
330 wheelFrame ??= requestAnimationFrame(flushWheel);
331 };
332
333 const flushMouse = () => {
334 if (mouseFrame !== null) cancelAnimationFrame(mouseFrame);
335 mouseFrame = null;
336 if (pendingMouse) send(pendingMouse);
337 pendingMouse = null;
338 };
339 const countClick = (event: PointerEvent, button: MouseInput["button"]) => {
340 const last = lastTap;
341 const count =
342 last &&
343 last.button === button &&
344 event.timeStamp - last.time < MULTI_CLICK_MS &&
345 Math.hypot(event.clientX - last.x, event.clientY - last.y) < MULTI_CLICK_SLOP_PX
346 ? last.count + 1
347 : 1;
348 lastTap = { time: event.timeStamp, x: event.clientX, y: event.clientY, count, button };
349 return count;
350 };
351 const mouseInput = (
352 event: PointerEvent,
353 point: { x: number; y: number },
354 action: MouseInput["action"],
355 button: MouseInput["button"],
356 buttons = event.buttons,
357 clickCount = mouseClicks[button],
358 ): MouseInput => ({
359 type: "mouse",
360 action,
361 x: point.x,
362 y: point.y,
363 button,
364 buttons,
365 clickCount,
366 modifiers: previewStreamModifiers(event),
367 });
368 const onPointerDown = (event: PointerEvent) => {
369 if (control?.controller !== "you") return;
370 if (!event.isPrimary) return;
371 event.preventDefault();
372 if (event.pointerType !== "touch") {
373 const point = pagePoint(event.clientX, event.clientY, false);
374 if (!point) return;
375 canvas.setPointerCapture(event.pointerId);
376 input.focus({ preventScroll: true });
377 flushMouse();
378 flushWheel();
379 mouseButtons = event.buttons & 7;
380 const button = mouseButton(event.button);
381 mouseClicks[button] = countClick(event, button);
382 send(mouseInput(event, point, "down", button));
383 return;
384 }
385 touch = { start: event, last: event, panning: false };
386 const point = pagePoint(event.clientX, event.clientY, false);
387 if (!point) {
388 probe = null;
389 return;
390 }
391 const cached = probeCache;
392 const reuse =
393 cached !== null &&
394 performance.now() - cached.time < PROBE_REUSE_MS &&
395 Math.hypot(event.clientX - cached.clientX, event.clientY - cached.clientY) <= PROBE_REUSE_PX;
396 probe = {
397 x: point.x,
398 y: point.y,
399 clientX: event.clientX,
400 clientY: event.clientY,
401 editable: reuse ? cached.editable : null,
402 end: "touching",
403 };
404 send({ type: "probe", x: point.x, y: point.y });
405 };
406 const onPointerMove = (event: PointerEvent) => {
407 if (control?.controller !== "you") return;
408 if (event.pointerType !== "touch") {
409 const point = pagePoint(event.clientX, event.clientY, mouseButtons !== 0);
410 if (!point) return;
411 // Chorded presses and releases arrive as pointermove while another button is held.
412 const changed = mouseButtons ^ (event.buttons & 7);
413 if (mouseButtons !== 0 && changed !== 0) {
414 flushMouse();
415 flushWheel();
416 for (const bit of [1, 2, 4]) {
417 if (!(changed & bit)) continue;
418 const button = bit === 1 ? "left" : bit === 2 ? "right" : "middle";
419 const down = (event.buttons & bit) !== 0;
420 mouseButtons ^= bit;
421 if (down) mouseClicks[button] = countClick(event, button);
422 send(mouseInput(event, point, down ? "down" : "up", button, mouseButtons));
423 }
424 }
425 const button =
426 mouseButtons & 1
427 ? "left"
428 : mouseButtons & 2
429 ? "right"
430 : mouseButtons & 4
431 ? "middle"
432 : "none";
433 pendingMouse = mouseInput(event, point, "move", button, event.buttons, 0);
434 mouseFrame ??= requestAnimationFrame(flushMouse);
435 return;
436 }
437 if (!touch || touch.start.pointerId !== event.pointerId) return;
438 if (
439 !touch.panning &&
440 Math.hypot(event.clientX - touch.start.clientX, event.clientY - touch.start.clientY) <
441 TAP_SLOP_PX
442 ) {
443 return;
444 }
445 touch.panning = true;
446 const point = pagePoint(event.clientX, event.clientY, true);
447 if (point) {
448 queueWheel(
449 point,
450 (touch.last.clientX - event.clientX) * point.scale,
451 (touch.last.clientY - event.clientY) * point.scale,
452 );
453 }
454 touch.last = event;
455 };
456 const releaseMouse = (event: PointerEvent, cancelled: boolean) => {
457 let buttons = mouseButtons;
458 if (buttons === 0) return;
459 mouseButtons = cancelled ? 0 : event.buttons & 7;
460 flushMouse();
461 flushWheel();
462 const point = pagePoint(event.clientX, event.clientY, true);
463 if (!point) return;
464 for (const bit of [1, 2, 4]) {
465 if (!(buttons & bit) || (mouseButtons & bit) !== 0) continue;
466 buttons &= ~bit;
467 const button = bit === 1 ? "left" : bit === 2 ? "right" : "middle";
468 send(mouseInput(event, point, "up", button, buttons));
469 }
470 };
471 const onPointerEnd = (event: PointerEvent) => {
472 const cancelled = event.type === "pointercancel";
473 if (event.pointerType !== "touch") {
474 releaseMouse(event, cancelled);
475 return;
476 }
477 const ended = touch;
478 if (!ended || ended.start.pointerId !== event.pointerId) return;
479 touch = null;
480 const answered = probe;
481 if (cancelled || ended.panning) {
482 if (answered) answered.end = "panned";
483 return;
484 }
485 const point = pagePoint(event.clientX, event.clientY, false);
486 if (!point) return;
487 // Focusing inside the tap's user activation is what lets iOS raise the keyboard.
488 if (answered?.editable === true) input.focus({ preventScroll: true });
489 else if (answered?.editable === false) input.blur();
490 if (answered) answered.end = answered.editable === null ? "late" : "acted";
491 flushWheel();
492 const clickCount = countClick(event, "left");
493 const at = { x: point.x, y: point.y, modifiers: 0 };
494 send({ type: "mouse", action: "move", ...at, button: "none", buttons: 0, clickCount: 0 });
495 send({ type: "mouse", action: "down", ...at, button: "left", buttons: 1, clickCount });
496 send({ type: "mouse", action: "up", ...at, button: "left", buttons: 0, clickCount });
497 };
498 const onWheel = (event: WheelEvent) => {
499 const point = pagePoint(event.clientX, event.clientY, false);
500 if (!point) return;
501 event.preventDefault();
502 const unit =
503 event.deltaMode === WheelEvent.DOM_DELTA_LINE
504 ? WHEEL_LINE_PX
505 : event.deltaMode === WheelEvent.DOM_DELTA_PAGE
506 ? (viewport?.height ?? 0)
507 : 1;
508 queueWheel(point, event.deltaX * unit, event.deltaY * unit);
509 };
510 const preventDefault = (event: Event) => event.preventDefault();
511
512 const onKey = (action: "down" | "up", event: KeyboardEvent) => {
513 if (control?.controller !== "you") return;
514 if (
515 event.isComposing ||
516 event.keyCode === 229 ||
517 event.key === "Process" ||
518 event.key === "Unidentified"
519 ) {
520 return;
521 }
522 const shortcut = event.ctrlKey || event.metaKey;
523 if (shortcut && event.key.toLowerCase() === "v") return;
524 if (event.shiftKey && event.key === "Insert") return;
525 // Enter carries "\r" like Puppeteer's key table, so forms submit and textareas break lines.
526 const text = shortcut
527 ? undefined
528 : [...event.key].length === 1
529 ? event.key
530 : event.key === "Enter"
531 ? "\r"
532 : undefined;
533 send({
534 type: "key",
535 action,
536 key: event.key,
537 code: event.code,
538 keyCode: event.keyCode,
539 ...(action === "down" && text !== undefined ? { text } : {}),
540 modifiers: previewStreamModifiers(event),
541 });
542 // Some Android keyboards edit the textarea even when keydown is prevented.
543 keySent =
544 action === "down" &&
545 !shortcut &&
546 (text !== undefined || event.key === "Backspace" || event.key === "Delete");
547 if (!shortcut) event.preventDefault();
548 };
549 const resetInput = () => {
550 input.value = SENTINEL;
551 input.setSelectionRange(SENTINEL.length, SENTINEL.length);
552 };
553 const pressKey = (key: "Backspace" | "Delete", keyCode: number) => {
554 for (const action of ["down", "up"] as const) {
555 send({ type: "key", action, key, code: key, keyCode, modifiers: 0 });
556 }
557 };
558 const onInput = (event: Event) => {
559 if (event instanceof InputEvent && event.isComposing) return;
560 const inputType = event instanceof InputEvent ? event.inputType : "";
561 if (keySent) keySent = false;
562 else if (inputType === "deleteContentBackward") pressKey("Backspace", 8);
563 else if (inputType === "deleteContentForward") pressKey("Delete", 46);
564 else {
565 const value = input.value;
566 const text = value.startsWith(SENTINEL) ? value.slice(SENTINEL.length) : value;
567 if (text) send({ type: "text", text });
568 }
569 resetInput();
570 };
571 const onCompositionEnd = (event: CompositionEvent) => {
572 const text = event.data.startsWith(SENTINEL) ? event.data.slice(SENTINEL.length) : event.data;
573 if (text) send({ type: "text", text });
574 resetInput();
575 };
576
577 if (interactive) {
578 canvas.addEventListener("pointerdown", onPointerDown);
579 canvas.addEventListener("pointermove", onPointerMove);
580 canvas.addEventListener("pointerup", onPointerEnd);
581 canvas.addEventListener("pointercancel", onPointerEnd);
582 canvas.addEventListener("wheel", onWheel, { passive: false });
583 canvas.addEventListener("mousedown", preventDefault);
584 canvas.addEventListener("contextmenu", preventDefault);
585 input.addEventListener("keydown", (event) => onKey("down", event));
586 input.addEventListener("keyup", (event) => onKey("up", event));
587 input.addEventListener("input", onInput);
588 input.addEventListener("compositionend", onCompositionEnd);
589 input.addEventListener("focus", resetInput);
590 // Copying the input would put its sentinel on this device's clipboard.
591 input.addEventListener("copy", preventDefault);
592 input.addEventListener("cut", preventDefault);
593 resetInput();
594 }
595
596 // WebKit reports no support on a video that has not loaded yet; check the prototype.
597 const videoPrototype: PresentationVideo = HTMLVideoElement.prototype;
598 const pictureInPictureSupported =
599 interactive &&
600 typeof canvas.captureStream === "function" &&
601 typeof CanvasCaptureMediaStreamTrack === "function" &&
602 ((document.pictureInPictureEnabled === true &&
603 typeof videoPrototype.requestPictureInPicture === "function") ||
604 typeof videoPrototype.webkitSetPresentationMode === "function");
605 // Since the iOS 17 SDK, WebKit revokes the activation it grants an injected script when
606 // the script returns, so the native button's request must start before any await. The
607 // video is ready ahead of the tap: paused, and fed a frame only when it has none or
608 // floats, so the inline view captures nothing.
609 let video: PresentationVideo | null = null;
610 let track: CanvasCaptureMediaStreamTrack | null = null;
611 const pictureInPictureActive = () =>
612 video !== null &&
613 (document.pictureInPictureElement === video ||
614 video.webkitPresentationMode === "picture-in-picture");
615 const reportPictureInPicture = (detail?: string) =>
616 post({
617 type: "pictureInPicture",
618 supported: pictureInPictureSupported,
619 active: pictureInPictureActive(),
620 ...(detail ? { detail } : {}),
621 });
622 // Called after each paint. A frame drawn before the player attached is lost, so retry.
623 const sendPictureInPictureFrame = () => {
624 if (video && (video.readyState === HTMLMediaElement.HAVE_NOTHING || pictureInPictureActive())) {
625 track?.requestFrame();
626 }
627 };
628 if (pictureInPictureSupported) {
629 const stream = canvas.captureStream(0);
630 const [captured] = stream.getVideoTracks();
631 const element: PresentationVideo = document.createElement("video");
632 element.muted = true;
633 element.playsInline = true;
634 // Under the canvas at full size: WebKit pauses muted video it considers off screen.
635 element.srcObject = stream;
636 for (const name of [
637 "enterpictureinpicture",
638 "leavepictureinpicture",
639 "webkitpresentationmodechanged",
640 ]) {
641 element.addEventListener(name, () => {
642 if (!pictureInPictureActive()) element.pause();
643 reportPictureInPicture();
644 });
645 }
646 container.prepend(element);
647 canvas.style.background = configuration.background;
648 video = element;
649 track = captured instanceof CanvasCaptureMediaStreamTrack ? captured : null;
650 }
651 const togglePictureInPicture = () => {
652 const element = video;
653 if (!element) return;
654 if (pictureInPictureActive()) {
655 if (document.pictureInPictureElement) void document.exitPictureInPicture().catch(() => {});
656 else element.webkitSetPresentationMode?.("inline");
657 return;
658 }
659 if (element.readyState === HTMLMediaElement.HAVE_NOTHING) {
660 reportPictureInPicture("The page has not shown yet. Try again in a moment.");
661 return;
662 }
663 // The page may have changed since the video's last frame. WebKit captures only on a draw.
664 track?.requestFrame();
665 canvas.getContext("2d")?.drawImage(canvas, 0, 0);
666 const fail = (error: unknown) => {
667 element.pause();
668 reportPictureInPicture(
669 error instanceof Error ? error.message : "Picture in picture is unavailable.",
670 );
671 };
672 if (document.pictureInPictureEnabled) {
673 const entering = element.requestPictureInPicture();
674 void Promise.all([entering, element.play()]).catch(fail);
675 } else {
676 element.webkitSetPresentationMode?.("picture-in-picture");
677 void element.play().catch(fail);
678 }
679 };
680
681 activeViewer = {
682 stop: () => {
683 stopped = true;
684 observer.disconnect();
685 visualViewport?.removeEventListener("resize", followVisualViewport);
686 visualViewport?.removeEventListener("scroll", followVisualViewport);
687 if (resizeTimer !== null) clearTimeout(resizeTimer);
688 if (wheelFrame !== null) cancelAnimationFrame(wheelFrame);
689 if (mouseFrame !== null) cancelAnimationFrame(mouseFrame);
690 if (agentCursorTimer !== null) clearTimeout(agentCursorTimer);
691 painter.stop();
692 client?.stop();
693 client = null;
694 track?.stop();
695 if (video) video.srcObject = null;
696 },
697 command: (message) => {
698 send(message);
699 },
700 togglePictureInPicture,
701 };
702 window.addEventListener("pagehide", stop, { once: true });
703 reportStatus("connecting");
704 if (interactive) reportPictureInPicture();
705}