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