Open History to see the last commit
1import type {
2 DesktopPreviewColorScheme,
3 PreviewViewportSetting,
4 ScopedThreadRef,
5} from "@t3tools/contracts";
6import { useShallow } from "zustand/react/shallow";
7import { useEffect, useEffectEvent, useRef, useState } from "react";
8
9import { previewBridge } from "~/components/preview/previewBridge";
10import { usePreviewBridge } from "~/components/preview/usePreviewBridge";
11import { useClientSettingsHydrated } from "~/hooks/useSettings";
12import { cn, isMacPlatform } from "~/lib/utils";
13
14import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore";
15import { useActiveBrowserRecordingTabIds } from "./browserRecording";
16import {
17 browserViewportSettingKey,
18 resolveBrowserViewportLayout,
19 resolveFittedBrowserViewport,
20} from "./browserViewportLayout";
21import { BrowserDeviceToolbar } from "./BrowserDeviceToolbar";
22import { BrowserViewportResizeHandles } from "./BrowserViewportResizeHandles";
23import { acquireDesktopTab, type AcquiredDesktopTab, withDesktopTab } from "./desktopTabLifetime";
24import { resolveHostedBrowserWebviewWrapperStyle } from "./hostedBrowserWebviewStyle";
25import { usePreviewWebviewConfig } from "./previewWebviewConfigState";
26import { useBrowserLayoutZoomFactor } from "./useBrowserLayoutZoomFactor";
27import { useBrowserViewportResize } from "./useBrowserViewportResize";
28import {
29 INITIAL_WEBVIEW_CRASH_RECOVERY_STATE,
30 planWebviewCrashRecovery,
31 type WebviewCrashRecoveryState,
32} from "./webviewCrashRecovery";
33
34interface ElectronWebview extends HTMLElement {
35 src: string;
36 partition: string;
37 preload?: string;
38 webpreferences?: string;
39 getWebContentsId: () => number;
40 executeJavaScript: (code: string, userGesture?: boolean) => Promise<unknown>;
41}
42
43declare global {
44 interface HTMLElementTagNameMap {
45 webview: ElectronWebview;
46 }
47}
48
49export function HostedBrowserWebview(props: {
50 readonly threadRef: ScopedThreadRef;
51 readonly tabId: string;
52 readonly runtimeTabId: string;
53 readonly initialUrl: string | null;
54 readonly viewport: PreviewViewportSetting;
55 readonly pictureInPicture: boolean;
56 /** Fixed for the tab lifetime; Electron reads partition before guest attachment. */
57 readonly profileId: string | undefined;
58 readonly zoomFactor: number;
59 readonly serverDriven?: boolean;
60 readonly serverRendering?: {
61 readonly colorScheme: DesktopPreviewColorScheme;
62 readonly zoomFactor: number;
63 };
64}) {
65 const {
66 threadRef,
67 tabId,
68 runtimeTabId,
69 initialUrl,
70 viewport,
71 pictureInPicture,
72 zoomFactor,
73 profileId,
74 serverDriven = false,
75 serverRendering,
76 } = props;
77 const clientSettingsHydrated = useClientSettingsHydrated();
78 const config = usePreviewWebviewConfig(threadRef.environmentId, profileId);
79 const [initialSrc] = useState(() => initialUrl ?? "about:blank");
80 const tabLeaseRef = useRef<AcquiredDesktopTab | null>(null);
81 const wrapperRef = useRef<HTMLDivElement | null>(null);
82 const webviewRef = useRef<ElectronWebview | null>(null);
83 const crashRecoveryRef = useRef<WebviewCrashRecoveryState>(INITIAL_WEBVIEW_CRASH_RECOVERY_STATE);
84 const [aspectRatioLocked, setAspectRatioLocked] = useState(false);
85 const presentation = useBrowserSurfaceStore(
86 useShallow((state) => {
87 const current = state.byTabId[runtimeTabId];
88 return {
89 content: current?.content ?? null,
90 cornerRadius: current?.cornerRadius ?? 0,
91 fitSourceContent: current?.fitSourceContent ?? false,
92 fittedSourceContent: current?.fittedSourceContent ?? null,
93 rect: resolveBrowserSurfacePanelRect(state.byTabId, runtimeTabId),
94 visible: current?.visible ?? false,
95 zIndex: current?.zIndex ?? 30,
96 };
97 }),
98 );
99 const backgroundActivity = useBrowserSurfaceStore(
100 (state) => (state.activityByTabId[runtimeTabId] ?? 0) > 0,
101 );
102 const recordingActive = useActiveBrowserRecordingTabIds().has(runtimeTabId);
103 usePreviewBridge({ threadRef, tabId, runtimeTabId, serverDriven });
104
105 const serverColorScheme = serverRendering?.colorScheme;
106 const serverZoomFactor = serverRendering?.zoomFactor;
107
108 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- leases the desktop preview tab for this webview and releases it on cleanup
109 useEffect(() => {
110 if (!clientSettingsHydrated) return;
111 crashRecoveryRef.current = INITIAL_WEBVIEW_CRASH_RECOVERY_STATE;
112 const lease = acquireDesktopTab(
113 runtimeTabId,
114 serverDriven ? { threadId: threadRef.threadId, tabId } : undefined,
115 );
116 tabLeaseRef.current = lease;
117 return () => {
118 if (tabLeaseRef.current === lease) tabLeaseRef.current = null;
119 lease.release();
120 };
121 }, [clientSettingsHydrated, runtimeTabId, serverDriven, tabId, threadRef.threadId]);
122
123 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- applies the server color scheme to the desktop preview tab through the desktop bridge
124 useEffect(() => {
125 const bridge = window.desktopBridge?.preview;
126 if (!bridge || serverColorScheme === undefined) return;
127 withDesktopTab(runtimeTabId, () => bridge.setColorScheme(runtimeTabId, serverColorScheme));
128 }, [runtimeTabId, serverColorScheme]);
129 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- applies the server zoom factor to the desktop preview tab through the desktop bridge
130 useEffect(() => {
131 const bridge = window.desktopBridge?.preview;
132 if (!bridge || serverZoomFactor === undefined) return;
133 withDesktopTab(runtimeTabId, () => bridge.setZoomFactor(runtimeTabId, serverZoomFactor));
134 }, [runtimeTabId, serverZoomFactor]);
135
136 const [webviewGeneration, setWebviewGeneration] = useState(0);
137 const [recoverySrc, setRecoverySrc] = useState(initialSrc);
138 const active = presentation.visible && presentation.rect !== null;
139 const shown = active || pictureInPicture;
140 const reportedShown = useEffectEvent(() => serverDriven && shown);
141 const remountCrashedWebview = useEffectEvent(() => {
142 setRecoverySrc(initialUrl ?? initialSrc);
143 setWebviewGeneration((generation) => generation + 1);
144 });
145
146 const setWebviewRef = (node: HTMLElement | null) => {
147 webviewRef.current = node as ElectronWebview | null;
148 };
149
150 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the webview's webContents with the desktop bridge and listens for crashes and focus
151 useEffect(() => {
152 const webview = webviewRef.current;
153 const bridge = previewBridge;
154 if (!clientSettingsHydrated || !webview || !config || !bridge) return;
155 let disposed = false;
156 let recoveryTimeout: ReturnType<typeof setTimeout> | null = null;
157 const register = () => {
158 const lease = tabLeaseRef.current;
159 if (!lease) return;
160 void (async () => {
161 try {
162 // Tab creation and webview attachment use separate effects; wait to avoid PreviewTabNotFoundError.
163 await lease.ready;
164 if (disposed || webviewRef.current !== webview) return;
165 const webContentsId = webview.getWebContentsId();
166 if (Number.isInteger(webContentsId) && webContentsId > 0) {
167 await bridge.registerWebview(runtimeTabId, webContentsId);
168 withDesktopTab(runtimeTabId, () => bridge.setShown(runtimeTabId, reportedShown()));
169 }
170 } catch {}
171 })();
172 };
173 const recoverGuest = () => {
174 if (disposed || recoveryTimeout !== null) return;
175 const recovery = planWebviewCrashRecovery(crashRecoveryRef.current, Date.now());
176 if (!recovery) return;
177 crashRecoveryRef.current = recovery.state;
178 recoveryTimeout = setTimeout(() => {
179 recoveryTimeout = null;
180 if (!disposed) remountCrashedWebview();
181 }, recovery.delayMs);
182 };
183 // Guest clicks only emit focus here; replay pointerdown to dismiss host popups.
184 const dismissHostPopups = () => {
185 webview.dispatchEvent(
186 new PointerEvent("pointerdown", { bubbles: true, pointerType: "mouse" }),
187 );
188 };
189 webview.addEventListener("did-attach", register);
190 webview.addEventListener("dom-ready", register);
191 webview.addEventListener("render-process-gone", recoverGuest);
192 webview.addEventListener("focus", dismissHostPopups);
193 register();
194 return () => {
195 disposed = true;
196 if (recoveryTimeout !== null) clearTimeout(recoveryTimeout);
197 webview.removeEventListener("did-attach", register);
198 webview.removeEventListener("dom-ready", register);
199 webview.removeEventListener("render-process-gone", recoverGuest);
200 webview.removeEventListener("focus", dismissHostPopups);
201 };
202 }, [
203 clientSettingsHydrated,
204 config,
205 runtimeTabId,
206 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A crash recovery remounts the webview under a new key, so the listeners attach to the new element.
207 webviewGeneration,
208 ]);
209
210 const lastRect = presentation.rect;
211 const layoutZoomFactor = useBrowserLayoutZoomFactor(zoomFactor);
212 const viewportWidth = viewport._tag === "fill" ? null : viewport.width;
213 const viewportHeight = viewport._tag === "fill" ? null : viewport.height;
214 const viewportAspectRatio =
215 viewportWidth === null || viewportHeight === null ? null : viewportWidth / viewportHeight;
216 const lockedAspectRatio =
217 aspectRatioLocked && viewportAspectRatio !== null ? viewportAspectRatio : null;
218 const handleAspectRatioChange = (aspectRatio: number | null) => {
219 setAspectRatioLocked(aspectRatio !== null);
220 };
221 const content = presentation.content;
222 const hiddenWidth =
223 viewport._tag !== "fill"
224 ? viewport.width * layoutZoomFactor
225 : content
226 ? content.width / content.scale
227 : (lastRect?.width ?? 1280);
228 const hiddenHeight =
229 viewport._tag !== "fill"
230 ? viewport.height * layoutZoomFactor
231 : content
232 ? content.height / content.scale
233 : (lastRect?.height ?? 800);
234 // Build from primitives on each side of the resize hook to keep both objects cached.
235 const containerSize =
236 active && lastRect ? lastRect : { width: hiddenWidth, height: hiddenHeight };
237 const deviceToolbarVisible = active && viewport._tag !== "fill" && !presentation.fitSourceContent;
238 const {
239 activeDrag,
240 commitViewportChange,
241 effectiveViewport,
242 handleResizeKeyDown,
243 handleResizePointerDown,
244 layout: viewportLayout,
245 } = useBrowserViewportResize({
246 target: { threadRef, tabId, runtimeTabId },
247 viewport,
248 zoomFactor: layoutZoomFactor,
249 containerSize,
250 deviceToolbarVisible,
251 aspectRatio: lockedAspectRatio,
252 });
253 const fittedSourceViewport =
254 presentation.fitSourceContent && lastRect
255 ? resolveFittedBrowserViewport(viewport, presentation.fittedSourceContent, layoutZoomFactor)
256 : null;
257 const layout =
258 fittedSourceViewport && lastRect
259 ? resolveBrowserViewportLayout(lastRect, fittedSourceViewport, layoutZoomFactor)
260 : viewportLayout;
261
262 const syncContentPresentation = () => {
263 const wrapper = wrapperRef.current;
264 if (!wrapper) return;
265 useBrowserSurfaceStore.getState().presentContent(runtimeTabId, {
266 x: layout.viewportX,
267 y: layout.viewportY,
268 width: layout.viewportWidth,
269 height: layout.viewportHeight,
270 scale: layout.viewportScale,
271 scrollLeft: wrapper.scrollLeft,
272 scrollTop: wrapper.scrollTop,
273 });
274 };
275
276 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- schedules a frame that publishes the webview layout and scroll to the browser surface store
277 useEffect(() => {
278 const frameId = window.requestAnimationFrame(syncContentPresentation);
279 return () => window.cancelAnimationFrame(frameId);
280 }, [syncContentPresentation]);
281
282 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the webview wrapper element to its origin for a new tab or viewport size
283 useEffect(() => {
284 const wrapper = wrapperRef.current;
285 if (!wrapper) return;
286 wrapper.scrollTo({ left: 0, top: 0 });
287 }, [
288 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A new tab or viewport size starts the canvas scrolled to its origin.
289 runtimeTabId,
290 viewport._tag,
291 viewportHeight,
292 viewportWidth,
293 ]);
294
295 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Report the mounted webview's visibility to the desktop host.
296 useEffect(() => {
297 const bridge = window.desktopBridge?.preview;
298 if (!clientSettingsHydrated || !bridge || !serverDriven) return;
299 withDesktopTab(runtimeTabId, () => bridge.setShown(runtimeTabId, shown));
300 return () => withDesktopTab(runtimeTabId, () => bridge.setShown(runtimeTabId, false));
301 }, [clientSettingsHydrated, runtimeTabId, serverDriven, shown]);
302
303 if (!clientSettingsHydrated || !config) return null;
304
305 const renderingActive = active || backgroundActivity || pictureInPicture || recordingActive;
306 const wrapperStyle = resolveHostedBrowserWebviewWrapperStyle({
307 active,
308 renderingActive,
309 // Electron 43 can permanently blank a macOS webview after `visibility: hidden`.
310 keepPaintableWhenInactive: isMacPlatform(navigator.platform),
311 cornerRadius: presentation.cornerRadius,
312 zIndex: presentation.zIndex,
313 rect: lastRect,
314 hiddenSize: { width: hiddenWidth, height: hiddenHeight },
315 });
316
317 return (
318 <div
319 ref={wrapperRef}
320 className="fixed overflow-hidden bg-muted/35"
321 style={{ ...wrapperStyle, overscrollBehavior: "contain" }}
322 onScroll={syncContentPresentation}
323 data-preview-rendering={renderingActive ? "active" : "suspended"}
324 data-preview-viewport={runtimeTabId}
325 >
326 <div className="relative" style={{ width: layout.canvasWidth, height: layout.canvasHeight }}>
327 {deviceToolbarVisible && effectiveViewport._tag !== "fill" ? (
328 <BrowserDeviceToolbar
329 setting={effectiveViewport}
330 width={Math.max(1, Math.round(active && lastRect ? lastRect.width : hiddenWidth))}
331 aspectRatio={lockedAspectRatio}
332 onAspectRatioChange={handleAspectRatioChange}
333 onChange={commitViewportChange}
334 />
335 ) : null}
336 <webview
337 key={webviewGeneration}
338 ref={setWebviewRef}
339 // Electron needs allowpopups at attachment. React drops boolean values for unknown attributes.
340 {...({ allowpopups: "true" } as unknown as { readonly allowpopups?: boolean })}
341 src={webviewGeneration === 0 ? initialSrc : recoverySrc}
342 partition={config.partition}
343 webpreferences={config.webPreferences}
344 {...(config.preloadUrl ? { preload: config.preloadUrl } : {})}
345 data-preview-tab={runtimeTabId}
346 data-preview-server-tab={tabId}
347 data-preview-viewport-mode={effectiveViewport._tag}
348 data-preview-viewport-key={browserViewportSettingKey(effectiveViewport)}
349 data-preview-css-width={
350 fittedSourceViewport
351 ? fittedSourceViewport.width
352 : effectiveViewport._tag === "fill"
353 ? Math.max(1, Math.round(layout.viewportWidth / layoutZoomFactor))
354 : effectiveViewport.width
355 }
356 data-preview-css-height={
357 fittedSourceViewport
358 ? fittedSourceViewport.height
359 : effectiveViewport._tag === "fill"
360 ? Math.max(1, Math.round(layout.viewportHeight / layoutZoomFactor))
361 : effectiveViewport.height
362 }
363 aria-hidden={active ? undefined : true}
364 className={cn(
365 "absolute flex overflow-hidden bg-white",
366 active && !layout.fillsPanel && "ring-1 ring-border/70 shadow-sm",
367 )}
368 style={{
369 left: layout.viewportX,
370 top: layout.viewportY,
371 width: layout.viewportWidth / layout.viewportScale,
372 height: layout.viewportHeight / layout.viewportScale,
373 transform: layout.viewportScale < 1 ? `scale(${layout.viewportScale})` : undefined,
374 transformOrigin: "top left",
375 }}
376 />
377 {active && effectiveViewport._tag !== "fill" && !fittedSourceViewport ? (
378 <>
379 <BrowserViewportResizeHandles
380 layout={layout}
381 activeDirection={activeDrag?.direction ?? null}
382 onPointerDown={handleResizePointerDown}
383 onKeyDown={handleResizeKeyDown}
384 />
385 {activeDrag ? (
386 <div
387 className="pointer-events-none absolute z-40 -translate-x-1/2 rounded-md border border-border/80 bg-background/95 px-2 py-1 text-2xs font-medium tabular-nums text-foreground shadow-md backdrop-blur-sm"
388 style={{
389 left: layout.viewportX + layout.viewportWidth / 2,
390 top: layout.viewportY + 10,
391 }}
392 aria-hidden="true"
393 >
394 {activeDrag.width} × {activeDrag.height}
395 </div>
396 ) : null}
397 </>
398 ) : null}
399 </div>
400 </div>
401 );
402}