Open History to see the last commit
1"use client";
2
3import type { PreviewViewportSetting, ScopedThreadRef } from "@t3tools/contracts";
4import { useShallow } from "zustand/react/shallow";
5import { useCallback, useEffect, useRef, useState } from "react";
6
7import { previewBridge } from "~/components/preview/previewBridge";
8import { usePreviewBridge } from "~/components/preview/usePreviewBridge";
9import { useClientSettingsHydrated } from "~/hooks/useSettings";
10import { cn, isMacPlatform } from "~/lib/utils";
11
12import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore";
13import { useActiveBrowserRecordingTabIds } from "./browserRecording";
14import {
15 browserViewportSettingKey,
16 resolveBrowserViewportLayout,
17 resolveFittedBrowserViewport,
18} from "./browserViewportLayout";
19import { BrowserDeviceToolbar } from "./BrowserDeviceToolbar";
20import { BrowserViewportResizeHandles } from "./BrowserViewportResizeHandles";
21import { acquireDesktopTab, type AcquiredDesktopTab } from "./desktopTabLifetime";
22import { resolveHostedBrowserWebviewWrapperStyle } from "./hostedBrowserWebviewStyle";
23import { usePreviewWebviewConfig } from "./previewWebviewConfigState";
24import { useBrowserViewportResize } from "./useBrowserViewportResize";
25import {
26 INITIAL_WEBVIEW_CRASH_RECOVERY_STATE,
27 planWebviewCrashRecovery,
28 type WebviewCrashRecoveryState,
29} from "./webviewCrashRecovery";
30
31interface ElectronWebview extends HTMLElement {
32 src: string;
33 partition: string;
34 preload?: string;
35 webpreferences?: string;
36 getWebContentsId: () => number;
37 executeJavaScript: (code: string, userGesture?: boolean) => Promise<unknown>;
38}
39
40declare global {
41 interface HTMLElementTagNameMap {
42 webview: ElectronWebview;
43 }
44}
45
46export function HostedBrowserWebview(props: {
47 readonly threadRef: ScopedThreadRef;
48 readonly tabId: string;
49 readonly runtimeTabId: string;
50 readonly initialUrl: string | null;
51 readonly viewport: PreviewViewportSetting;
52 readonly pictureInPicture: boolean;
53 /**
54 * Fixed for the tab's lifetime: Electron only honours `partition` before the
55 * guest attaches, so a live change here would not move the tab anyway.
56 */
57 readonly profileId: string | undefined;
58 readonly zoomFactor: number;
59}) {
60 const {
61 threadRef,
62 tabId,
63 runtimeTabId,
64 initialUrl,
65 viewport,
66 pictureInPicture,
67 zoomFactor,
68 profileId,
69 } = props;
70 const clientSettingsHydrated = useClientSettingsHydrated();
71 const config = usePreviewWebviewConfig(threadRef.environmentId, profileId);
72 const [initialSrc] = useState(() => initialUrl ?? "about:blank");
73 const tabLeaseRef = useRef<AcquiredDesktopTab | null>(null);
74 const wrapperRef = useRef<HTMLDivElement | null>(null);
75 const webviewRef = useRef<ElectronWebview | null>(null);
76 const crashRecoveryRef = useRef<WebviewCrashRecoveryState>(INITIAL_WEBVIEW_CRASH_RECOVERY_STATE);
77 const [aspectRatioLocked, setAspectRatioLocked] = useState(false);
78 const presentation = useBrowserSurfaceStore(
79 useShallow((state) => {
80 const current = state.byTabId[runtimeTabId];
81 return {
82 content: current?.content ?? null,
83 cornerRadius: current?.cornerRadius ?? 0,
84 fitSourceContent: current?.fitSourceContent ?? false,
85 fittedSourceContent: current?.fittedSourceContent ?? null,
86 rect: resolveBrowserSurfacePanelRect(state.byTabId, runtimeTabId),
87 visible: current?.visible ?? false,
88 zIndex: current?.zIndex ?? 30,
89 };
90 }),
91 );
92 const backgroundActivity = useBrowserSurfaceStore(
93 (state) => (state.activityByTabId[runtimeTabId] ?? 0) > 0,
94 );
95 const recordingActive = useActiveBrowserRecordingTabIds().has(runtimeTabId);
96 usePreviewBridge({ threadRef, tabId, runtimeTabId });
97
98 useEffect(() => {
99 if (!clientSettingsHydrated) return;
100 crashRecoveryRef.current = INITIAL_WEBVIEW_CRASH_RECOVERY_STATE;
101 const lease = acquireDesktopTab(runtimeTabId);
102 tabLeaseRef.current = lease;
103 return () => {
104 if (tabLeaseRef.current === lease) tabLeaseRef.current = null;
105 lease.release();
106 };
107 }, [clientSettingsHydrated, runtimeTabId]);
108
109 const [webviewGeneration, setWebviewGeneration] = useState(0);
110 const [recoverySrc, setRecoverySrc] = useState(initialSrc);
111 const latestUrlRef = useRef(initialUrl);
112
113 useEffect(() => {
114 latestUrlRef.current = initialUrl;
115 }, [initialUrl]);
116
117 const setWebviewRef = useCallback((node: HTMLElement | null) => {
118 webviewRef.current = node as ElectronWebview | null;
119 }, []);
120
121 useEffect(() => {
122 const webview = webviewRef.current;
123 const bridge = previewBridge;
124 if (!clientSettingsHydrated || !webview || !config || !bridge) return;
125 let disposed = false;
126 let recoveryTimeout: ReturnType<typeof setTimeout> | null = null;
127 const register = () => {
128 const lease = tabLeaseRef.current;
129 if (!lease) return;
130 void (async () => {
131 try {
132 // The main-process tab and the DOM webview are created by separate
133 // effects. Wait for the former so registration cannot race and fail
134 // with PreviewTabNotFoundError on a fast about:blank attachment.
135 await lease.ready;
136 if (disposed || webviewRef.current !== webview) return;
137 const webContentsId = webview.getWebContentsId();
138 if (Number.isInteger(webContentsId) && webContentsId > 0) {
139 await bridge.registerWebview(runtimeTabId, webContentsId);
140 }
141 } catch {
142 // did-attach/dom-ready will retry if the guest was not ready yet.
143 }
144 })();
145 };
146 const recoverGuest = () => {
147 if (disposed || recoveryTimeout !== null) return;
148 const recovery = planWebviewCrashRecovery(crashRecoveryRef.current, Date.now());
149 if (!recovery) return;
150 crashRecoveryRef.current = recovery.state;
151 recoveryTimeout = setTimeout(() => {
152 recoveryTimeout = null;
153 if (!disposed) {
154 setRecoverySrc(latestUrlRef.current ?? initialSrc);
155 setWebviewGeneration((generation) => generation + 1);
156 }
157 }, recovery.delayMs);
158 };
159 // A click inside the guest only reaches this document as a webview focus
160 // event, so open menus and popovers never see the outside press that
161 // would dismiss them. Replay it as a pointerdown on the webview itself.
162 const dismissHostPopups = () => {
163 webview.dispatchEvent(
164 new PointerEvent("pointerdown", { bubbles: true, pointerType: "mouse" }),
165 );
166 };
167 webview.addEventListener("did-attach", register);
168 webview.addEventListener("dom-ready", register);
169 webview.addEventListener("render-process-gone", recoverGuest);
170 webview.addEventListener("focus", dismissHostPopups);
171 register();
172 return () => {
173 disposed = true;
174 if (recoveryTimeout !== null) clearTimeout(recoveryTimeout);
175 webview.removeEventListener("did-attach", register);
176 webview.removeEventListener("dom-ready", register);
177 webview.removeEventListener("render-process-gone", recoverGuest);
178 webview.removeEventListener("focus", dismissHostPopups);
179 };
180 }, [clientSettingsHydrated, config, initialSrc, runtimeTabId, webviewGeneration]);
181
182 const active = presentation.visible && presentation.rect !== null;
183 const lastRect = presentation.rect;
184 const normalizedZoomFactor = Number.isFinite(zoomFactor) && zoomFactor > 0 ? zoomFactor : 1;
185 const viewportWidth = viewport._tag === "fill" ? null : viewport.width;
186 const viewportHeight = viewport._tag === "fill" ? null : viewport.height;
187 const viewportAspectRatio =
188 viewportWidth === null || viewportHeight === null ? null : viewportWidth / viewportHeight;
189 const lockedAspectRatio =
190 aspectRatioLocked && viewportAspectRatio !== null ? viewportAspectRatio : null;
191 const handleAspectRatioChange = useCallback((aspectRatio: number | null) => {
192 setAspectRatioLocked(aspectRatio !== null);
193 }, []);
194 const hiddenContentSize = presentation.content
195 ? {
196 width: presentation.content.width / presentation.content.scale,
197 height: presentation.content.height / presentation.content.scale,
198 }
199 : null;
200 const hiddenSize =
201 viewport._tag !== "fill"
202 ? {
203 width: viewport.width * normalizedZoomFactor,
204 height: viewport.height * normalizedZoomFactor,
205 }
206 : {
207 width: hiddenContentSize?.width ?? lastRect?.width ?? 1280,
208 height: hiddenContentSize?.height ?? lastRect?.height ?? 800,
209 };
210 const containerSize = active && lastRect ? lastRect : hiddenSize;
211 const deviceToolbarVisible = active && viewport._tag !== "fill" && !presentation.fitSourceContent;
212 const {
213 activeDrag,
214 commitViewportChange,
215 effectiveViewport,
216 handleResizeKeyDown,
217 handleResizePointerDown,
218 layout: viewportLayout,
219 } = useBrowserViewportResize({
220 tabId: runtimeTabId,
221 viewport,
222 zoomFactor,
223 containerSize,
224 deviceToolbarVisible,
225 aspectRatio: lockedAspectRatio,
226 });
227 const fittedSourceViewport =
228 presentation.fitSourceContent && lastRect
229 ? resolveFittedBrowserViewport(
230 viewport,
231 presentation.fittedSourceContent,
232 normalizedZoomFactor,
233 )
234 : null;
235 const layout =
236 fittedSourceViewport && lastRect
237 ? resolveBrowserViewportLayout(lastRect, fittedSourceViewport, normalizedZoomFactor)
238 : viewportLayout;
239
240 const syncContentPresentation = useCallback(() => {
241 const wrapper = wrapperRef.current;
242 if (!wrapper) return;
243 useBrowserSurfaceStore.getState().presentContent(runtimeTabId, {
244 x: layout.viewportX,
245 y: layout.viewportY,
246 width: layout.viewportWidth,
247 height: layout.viewportHeight,
248 scale: layout.viewportScale,
249 scrollLeft: wrapper.scrollLeft,
250 scrollTop: wrapper.scrollTop,
251 });
252 }, [layout, runtimeTabId]);
253
254 useEffect(() => {
255 const frameId = window.requestAnimationFrame(syncContentPresentation);
256 return () => window.cancelAnimationFrame(frameId);
257 }, [syncContentPresentation]);
258
259 useEffect(() => {
260 const wrapper = wrapperRef.current;
261 if (!wrapper) return;
262 wrapper.scrollTo({ left: 0, top: 0 });
263 }, [runtimeTabId, viewport._tag, viewportHeight, viewportWidth]);
264
265 if (!clientSettingsHydrated || !config) return null;
266
267 const renderingActive = active || backgroundActivity || pictureInPicture || recordingActive;
268 const wrapperStyle = resolveHostedBrowserWebviewWrapperStyle({
269 active,
270 renderingActive,
271 // Electron 43 can permanently blank a macOS webview after `visibility: hidden`.
272 // Inactive macOS guests intentionally remain paintable offscreen; other platforms still
273 // suspend them, and automation continues to see the macOS guests as inactive.
274 keepPaintableWhenInactive: isMacPlatform(navigator.platform),
275 cornerRadius: presentation.cornerRadius,
276 zIndex: presentation.zIndex,
277 rect: lastRect,
278 hiddenSize,
279 });
280
281 return (
282 <div
283 ref={wrapperRef}
284 className="fixed overflow-hidden bg-muted/35"
285 style={{ ...wrapperStyle, overscrollBehavior: "contain" }}
286 onScroll={syncContentPresentation}
287 data-preview-rendering={renderingActive ? "active" : "suspended"}
288 data-preview-viewport={runtimeTabId}
289 >
290 <div className="relative" style={{ width: layout.canvasWidth, height: layout.canvasHeight }}>
291 {deviceToolbarVisible && effectiveViewport._tag !== "fill" ? (
292 <BrowserDeviceToolbar
293 setting={effectiveViewport}
294 width={Math.max(1, Math.round(containerSize.width))}
295 aspectRatio={lockedAspectRatio}
296 onAspectRatioChange={handleAspectRatioChange}
297 onChange={commitViewportChange}
298 />
299 ) : null}
300 <webview
301 key={webviewGeneration}
302 ref={setWebviewRef}
303 // Must be an attribute on the element itself: Electron reads it when the
304 // guest attaches, so setting it from the ref callback lands too late and
305 // the guest attaches with popups disabled. React types `allowpopups` as a
306 // boolean, but react-dom drops boolean values for unrecognized attributes,
307 // so the literal string has to be spread past the type.
308 {...({ allowpopups: "true" } as unknown as { readonly allowpopups?: boolean })}
309 src={webviewGeneration === 0 ? initialSrc : recoverySrc}
310 partition={config.partition}
311 webpreferences={config.webPreferences}
312 {...(config.preloadUrl ? { preload: config.preloadUrl } : {})}
313 data-preview-tab={runtimeTabId}
314 data-preview-server-tab={tabId}
315 data-preview-viewport-mode={effectiveViewport._tag}
316 data-preview-viewport-key={browserViewportSettingKey(effectiveViewport)}
317 data-preview-css-width={
318 fittedSourceViewport
319 ? fittedSourceViewport.width
320 : effectiveViewport._tag === "fill"
321 ? Math.max(1, Math.round(layout.viewportWidth / normalizedZoomFactor))
322 : effectiveViewport.width
323 }
324 data-preview-css-height={
325 fittedSourceViewport
326 ? fittedSourceViewport.height
327 : effectiveViewport._tag === "fill"
328 ? Math.max(1, Math.round(layout.viewportHeight / normalizedZoomFactor))
329 : effectiveViewport.height
330 }
331 aria-hidden={active ? undefined : true}
332 className={cn(
333 "absolute flex overflow-hidden bg-white",
334 active && !layout.fillsPanel && "ring-1 ring-border/70 shadow-sm",
335 )}
336 style={{
337 left: layout.viewportX,
338 top: layout.viewportY,
339 width: layout.viewportWidth / layout.viewportScale,
340 height: layout.viewportHeight / layout.viewportScale,
341 transform: layout.viewportScale < 1 ? `scale(${layout.viewportScale})` : undefined,
342 transformOrigin: "top left",
343 }}
344 />
345 {active && effectiveViewport._tag !== "fill" && !fittedSourceViewport ? (
346 <>
347 <BrowserViewportResizeHandles
348 layout={layout}
349 activeDirection={activeDrag?.direction ?? null}
350 onPointerDown={handleResizePointerDown}
351 onKeyDown={handleResizeKeyDown}
352 />
353 {activeDrag ? (
354 <div
355 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"
356 style={{
357 left: layout.viewportX + layout.viewportWidth / 2,
358 top: layout.viewportY + 10,
359 }}
360 aria-hidden="true"
361 >
362 {activeDrag.width} × {activeDrag.height}
363 </div>
364 ) : null}
365 </>
366 ) : null}
367 </div>
368 </div>
369 );
370}