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