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

preview-stream.browser.ts

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