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 webview.addEventListener("did-attach", register);
160 webview.addEventListener("dom-ready", register);
161 webview.addEventListener("render-process-gone", recoverGuest);
162 register();
163 return () => {
164 disposed = true;
165 if (recoveryTimeout !== null) clearTimeout(recoveryTimeout);
166 webview.removeEventListener("did-attach", register);
167 webview.removeEventListener("dom-ready", register);
168 webview.removeEventListener("render-process-gone", recoverGuest);
169 };
170 }, [clientSettingsHydrated, config, initialSrc, runtimeTabId, webviewGeneration]);
171
172 const active = presentation.visible && presentation.rect !== null;
173 const lastRect = presentation.rect;
174 const normalizedZoomFactor = Number.isFinite(zoomFactor) && zoomFactor > 0 ? zoomFactor : 1;
175 const viewportWidth = viewport._tag === "fill" ? null : viewport.width;
176 const viewportHeight = viewport._tag === "fill" ? null : viewport.height;
177 const viewportAspectRatio =
178 viewportWidth === null || viewportHeight === null ? null : viewportWidth / viewportHeight;
179 const lockedAspectRatio =
180 aspectRatioLocked && viewportAspectRatio !== null ? viewportAspectRatio : null;
181 const handleAspectRatioChange = useCallback((aspectRatio: number | null) => {
182 setAspectRatioLocked(aspectRatio !== null);
183 }, []);
184 const hiddenContentSize = presentation.content
185 ? {
186 width: presentation.content.width / presentation.content.scale,
187 height: presentation.content.height / presentation.content.scale,
188 }
189 : null;
190 const hiddenSize =
191 viewport._tag !== "fill"
192 ? {
193 width: viewport.width * normalizedZoomFactor,
194 height: viewport.height * normalizedZoomFactor,
195 }
196 : {
197 width: hiddenContentSize?.width ?? lastRect?.width ?? 1280,
198 height: hiddenContentSize?.height ?? lastRect?.height ?? 800,
199 };
200 const containerSize = active && lastRect ? lastRect : hiddenSize;
201 const deviceToolbarVisible = active && viewport._tag !== "fill" && !presentation.fitSourceContent;
202 const {
203 activeDrag,
204 commitViewportChange,
205 effectiveViewport,
206 handleResizeKeyDown,
207 handleResizePointerDown,
208 layout: viewportLayout,
209 } = useBrowserViewportResize({
210 tabId: runtimeTabId,
211 viewport,
212 zoomFactor,
213 containerSize,
214 deviceToolbarVisible,
215 aspectRatio: lockedAspectRatio,
216 });
217 const fittedSourceViewport =
218 presentation.fitSourceContent && lastRect
219 ? resolveFittedBrowserViewport(
220 viewport,
221 presentation.fittedSourceContent,
222 normalizedZoomFactor,
223 )
224 : null;
225 const layout =
226 fittedSourceViewport && lastRect
227 ? resolveBrowserViewportLayout(lastRect, fittedSourceViewport, normalizedZoomFactor)
228 : viewportLayout;
229
230 const syncContentPresentation = useCallback(() => {
231 const wrapper = wrapperRef.current;
232 if (!wrapper) return;
233 useBrowserSurfaceStore.getState().presentContent(runtimeTabId, {
234 x: layout.viewportX,
235 y: layout.viewportY,
236 width: layout.viewportWidth,
237 height: layout.viewportHeight,
238 scale: layout.viewportScale,
239 scrollLeft: wrapper.scrollLeft,
240 scrollTop: wrapper.scrollTop,
241 });
242 }, [layout, runtimeTabId]);
243
244 useEffect(() => {
245 const frameId = window.requestAnimationFrame(syncContentPresentation);
246 return () => window.cancelAnimationFrame(frameId);
247 }, [syncContentPresentation]);
248
249 useEffect(() => {
250 const wrapper = wrapperRef.current;
251 if (!wrapper) return;
252 wrapper.scrollTo({ left: 0, top: 0 });
253 }, [runtimeTabId, viewport._tag, viewportHeight, viewportWidth]);
254
255 if (!clientSettingsHydrated || !config) return null;
256
257 const renderingActive = active || backgroundActivity || pictureInPicture || recordingActive;
258 const wrapperStyle = resolveHostedBrowserWebviewWrapperStyle({
259 active,
260 renderingActive,
261 // Electron 43 can permanently blank a macOS webview after `visibility: hidden`.
262 // Inactive macOS guests intentionally remain paintable offscreen; other platforms still
263 // suspend them, and automation continues to see the macOS guests as inactive.
264 keepPaintableWhenInactive: isMacPlatform(navigator.platform),
265 cornerRadius: presentation.cornerRadius,
266 zIndex: presentation.zIndex,
267 rect: lastRect,
268 hiddenSize,
269 });
270
271 return (
272 <div
273 ref={wrapperRef}
274 className="fixed overflow-hidden bg-muted/35"
275 style={{ ...wrapperStyle, overscrollBehavior: "contain" }}
276 onScroll={syncContentPresentation}
277 data-preview-rendering={renderingActive ? "active" : "suspended"}
278 data-preview-viewport={runtimeTabId}
279 >
280 <div className="relative" style={{ width: layout.canvasWidth, height: layout.canvasHeight }}>
281 {deviceToolbarVisible && effectiveViewport._tag !== "fill" ? (
282 <BrowserDeviceToolbar
283 setting={effectiveViewport}
284 width={Math.max(1, Math.round(containerSize.width))}
285 aspectRatio={lockedAspectRatio}
286 onAspectRatioChange={handleAspectRatioChange}
287 onChange={commitViewportChange}
288 />
289 ) : null}
290 <webview
291 key={webviewGeneration}
292 ref={setWebviewRef}
293 // Must be an attribute on the element itself: Electron reads it when the
294 // guest attaches, so setting it from the ref callback lands too late and
295 // the guest attaches with popups disabled. React types `allowpopups` as a
296 // boolean, but react-dom drops boolean values for unrecognized attributes,
297 // so the literal string has to be spread past the type.
298 {...({ allowpopups: "true" } as unknown as { readonly allowpopups?: boolean })}
299 src={webviewGeneration === 0 ? initialSrc : recoverySrc}
300 partition={config.partition}
301 webpreferences={config.webPreferences}
302 {...(config.preloadUrl ? { preload: config.preloadUrl } : {})}
303 data-preview-tab={runtimeTabId}
304 data-preview-server-tab={tabId}
305 data-preview-viewport-mode={effectiveViewport._tag}
306 data-preview-viewport-key={browserViewportSettingKey(effectiveViewport)}
307 data-preview-css-width={
308 fittedSourceViewport
309 ? fittedSourceViewport.width
310 : effectiveViewport._tag === "fill"
311 ? Math.max(1, Math.round(layout.viewportWidth / normalizedZoomFactor))
312 : effectiveViewport.width
313 }
314 data-preview-css-height={
315 fittedSourceViewport
316 ? fittedSourceViewport.height
317 : effectiveViewport._tag === "fill"
318 ? Math.max(1, Math.round(layout.viewportHeight / normalizedZoomFactor))
319 : effectiveViewport.height
320 }
321 aria-hidden={active ? undefined : true}
322 className={cn(
323 "absolute flex overflow-hidden bg-white",
324 active && !layout.fillsPanel && "ring-1 ring-border/70 shadow-sm",
325 )}
326 style={{
327 left: layout.viewportX,
328 top: layout.viewportY,
329 width: layout.viewportWidth / layout.viewportScale,
330 height: layout.viewportHeight / layout.viewportScale,
331 transform: layout.viewportScale < 1 ? `scale(${layout.viewportScale})` : undefined,
332 transformOrigin: "top left",
333 }}
334 />
335 {active && effectiveViewport._tag !== "fill" && !fittedSourceViewport ? (
336 <>
337 <BrowserViewportResizeHandles
338 layout={layout}
339 activeDirection={activeDrag?.direction ?? null}
340 onPointerDown={handleResizePointerDown}
341 onKeyDown={handleResizeKeyDown}
342 />
343 {activeDrag ? (
344 <div
345 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-[11px] font-medium tabular-nums text-foreground shadow-md backdrop-blur-sm"
346 style={{
347 left: layout.viewportX + layout.viewportWidth / 2,
348 top: layout.viewportY + 10,
349 }}
350 aria-hidden="true"
351 >
352 {activeDrag.width} × {activeDrag.height}
353 </div>
354 ) : null}
355 </>
356 ) : null}
357 </div>
358 </div>
359 );
360}