Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

preview-stream.browser.ts

711 lines26.7 KB

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