Open History to see the last commit
1import {
2 createPreviewFramePainter,
3 createPreviewStreamClient,
4 type PreviewStreamClient,
5} from "@t3tools/client-runtime/preview/server-browser-stream";
6import type { EnvironmentId } from "@t3tools/contracts";
7import { useSyncExternalStore } from "react";
8
9import { readPreviewStreamAccess } from "~/state/previewStream";
10
11interface WebKitVideo {
12 webkitSetPresentationMode?: (mode: string) => void;
13 webkitPresentationMode?: string;
14}
15
16interface ActivePictureInPicture {
17 readonly key: string;
18 readonly stop: () => void;
19}
20
21// Owns its stream outside React so the floating window survives panel unmounts.
22let active: ActivePictureInPicture | null = null;
23const listeners = new Set<() => void>();
24
25const emit = () => {
26 for (const listener of listeners) listener();
27};
28
29const subscribe = (listener: () => void) => {
30 listeners.add(listener);
31 return () => listeners.delete(listener);
32};
33
34export const serverPictureInPictureKey = (threadId: string, tabId: string) =>
35 JSON.stringify([threadId, tabId]);
36
37export function supportsServerPictureInPicture(): boolean {
38 if (typeof document === "undefined") return false;
39 if (typeof HTMLCanvasElement.prototype.captureStream !== "function") return false;
40 const video = HTMLVideoElement.prototype as HTMLVideoElement & WebKitVideo;
41 return (
42 (document.pictureInPictureEnabled && typeof video.requestPictureInPicture === "function") ||
43 typeof video.webkitSetPresentationMode === "function"
44 );
45}
46
47export function useServerPictureInPictureKey(): string | null {
48 return useSyncExternalStore(
49 subscribe,
50 () => active?.key ?? null,
51 () => null,
52 );
53}
54
55export function closeServerPictureInPicture(): void {
56 const current = active;
57 active = null;
58 current?.stop();
59 emit();
60}
61
62/** Open during user activation, seeding the video with the currently visible frame. */
63export async function openServerPictureInPicture(input: {
64 readonly environmentId: EnvironmentId;
65 readonly threadId: string;
66 readonly tabId: string;
67 readonly seed: HTMLCanvasElement | null;
68}): Promise<void> {
69 closeServerPictureInPicture();
70 const canvas = document.createElement("canvas");
71 const context = canvas.getContext("2d");
72 const seed = input.seed && input.seed.width > 0 && input.seed.height > 0 ? input.seed : null;
73 canvas.width = seed?.width ?? 640;
74 canvas.height = seed?.height ?? 400;
75 // The capture emits a frame per draw, so the seed is drawn after it starts.
76 const stream = canvas.captureStream();
77 if (seed) context?.drawImage(seed, 0, 0);
78 else context?.fillRect(0, 0, canvas.width, canvas.height);
79 const video = document.createElement("video") as HTMLVideoElement & WebKitVideo;
80 video.muted = true;
81 video.playsInline = true;
82 video.srcObject = stream;
83 // Safari only floats a video that is in the document.
84 video.style.cssText =
85 "position:fixed;right:0;bottom:0;width:1px;height:1px;opacity:0;pointer-events:none";
86 document.body.append(video);
87
88 const painter = createPreviewFramePainter(canvas);
89 let client: PreviewStreamClient | null = null;
90 let stopped = false;
91 let refusals = 0;
92 let retryTimer: ReturnType<typeof setTimeout> | null = null;
93 const onLeave = () => {
94 if (active === current) closeServerPictureInPicture();
95 };
96 const connect = async (refresh: boolean) => {
97 const access = await readPreviewStreamAccess(input.environmentId, refresh);
98 if (stopped) return;
99 if (!access) {
100 closeServerPictureInPicture();
101 return;
102 }
103 client = createPreviewStreamClient(
104 {
105 access,
106 threadId: input.threadId,
107 tabId: input.tabId,
108 maxWidth: 1280,
109 maxHeight: 1280,
110 interactive: false,
111 },
112 {
113 onFrame: (jpeg) => {
114 refusals = 0;
115 painter.paint(jpeg);
116 },
117 onViewport: () => undefined,
118 onConnectedChange: () => undefined,
119 onUnauthorized: () => {
120 if (stopped) return;
121 if (refusals >= 5) {
122 onLeave();
123 return;
124 }
125 retryTimer = setTimeout(() => void connect(true), 1_000 * 2 ** refusals++);
126 },
127 onGone: onLeave,
128 },
129 );
130 };
131
132 const onPresentationMode = () => {
133 if (video.webkitPresentationMode !== "picture-in-picture") onLeave();
134 };
135 const current: ActivePictureInPicture = {
136 key: serverPictureInPictureKey(input.threadId, input.tabId),
137 stop: () => {
138 stopped = true;
139 if (retryTimer !== null) clearTimeout(retryTimer);
140 client?.stop();
141 painter.stop();
142 video.removeEventListener("leavepictureinpicture", onLeave);
143 video.removeEventListener("webkitpresentationmodechanged", onPresentationMode);
144 if (document.pictureInPictureElement === video) {
145 void document.exitPictureInPicture().catch(() => undefined);
146 } else if (video.webkitPresentationMode === "picture-in-picture") {
147 video.webkitSetPresentationMode?.("inline");
148 }
149 for (const track of stream.getTracks()) track.stop();
150 video.srcObject = null;
151 video.remove();
152 },
153 };
154 active = current;
155 emit();
156
157 try {
158 await video.play();
159 if (video.readyState < HTMLMediaElement.HAVE_METADATA) {
160 await new Promise((resolve) =>
161 video.addEventListener("loadedmetadata", resolve, { once: true }),
162 );
163 }
164 if (document.pictureInPictureEnabled && typeof video.requestPictureInPicture === "function") {
165 video.addEventListener("leavepictureinpicture", onLeave);
166 await video.requestPictureInPicture();
167 } else {
168 video.addEventListener("webkitpresentationmodechanged", onPresentationMode);
169 video.webkitSetPresentationMode?.("picture-in-picture");
170 }
171 } catch (error) {
172 onLeave();
173 throw error;
174 }
175 if (active === current) void connect(false);
176}