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 remountCrashedWebview = useEffectEvent(() => {
139 setRecoverySrc(initialUrl ?? initialSrc);
140 setWebviewGeneration((generation) => generation + 1);
141 });
142
143 const setWebviewRef = (node: HTMLElement | null) => {
144 webviewRef.current = node as ElectronWebview | null;
145 };
146
147 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the webview's webContents with the desktop bridge and listens for crashes and focus
148 useEffect(() => {
149 const webview = webviewRef.current;
150 const bridge = previewBridge;
151 if (!clientSettingsHydrated || !webview || !config || !bridge) return;
152 let disposed = false;
153 let recoveryTimeout: ReturnType<typeof setTimeout> | null = null;
154 const register = () => {
155 const lease = tabLeaseRef.current;
156 if (!lease) return;
157 void (async () => {
158 try {
159 // Tab creation and webview attachment use separate effects; wait to avoid PreviewTabNotFoundError.
160 await lease.ready;
161 if (disposed || webviewRef.current !== webview) return;
162 const webContentsId = webview.getWebContentsId();
163 if (Number.isInteger(webContentsId) && webContentsId > 0) {
164 await bridge.registerWebview(runtimeTabId, webContentsId);
165 }
166 } catch {}
167 })();
168 };
169 const recoverGuest = () => {
170 if (disposed || recoveryTimeout !== null) return;
171 const recovery = planWebviewCrashRecovery(crashRecoveryRef.current, Date.now());
172 if (!recovery) return;
173 crashRecoveryRef.current = recovery.state;
174 recoveryTimeout = setTimeout(() => {
175 recoveryTimeout = null;
176 if (!disposed) remountCrashedWebview();
177 }, recovery.delayMs);
178 };
179 // Guest clicks only emit focus here; replay pointerdown to dismiss host popups.
180 const dismissHostPopups = () => {
181 webview.dispatchEvent(
182 new PointerEvent("pointerdown", { bubbles: true, pointerType: "mouse" }),
183 );
184 };
185 webview.addEventListener("did-attach", register);
186 webview.addEventListener("dom-ready", register);
187 webview.addEventListener("render-process-gone", recoverGuest);
188 webview.addEventListener("focus", dismissHostPopups);
189 register();
190 return () => {
191 disposed = true;
192 if (recoveryTimeout !== null) clearTimeout(recoveryTimeout);
193 webview.removeEventListener("did-attach", register);
194 webview.removeEventListener("dom-ready", register);
195 webview.removeEventListener("render-process-gone", recoverGuest);
196 webview.removeEventListener("focus", dismissHostPopups);
197 };
198 }, [
199 clientSettingsHydrated,
200 config,
201 runtimeTabId,
202 // 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.
203 webviewGeneration,
204 ]);
205
206 const active = presentation.visible && presentation.rect !== null;
207 const lastRect = presentation.rect;
208 const layoutZoomFactor = useBrowserLayoutZoomFactor(zoomFactor);
209 const viewportWidth = viewport._tag === "fill" ? null : viewport.width;
210 const viewportHeight = viewport._tag === "fill" ? null : viewport.height;
211 const viewportAspectRatio =
212 viewportWidth === null || viewportHeight === null ? null : viewportWidth / viewportHeight;
213 const lockedAspectRatio =
214 aspectRatioLocked && viewportAspectRatio !== null ? viewportAspectRatio : null;
215 const handleAspectRatioChange = (aspectRatio: number | null) => {
216 setAspectRatioLocked(aspectRatio !== null);
217 };
218 const content = presentation.content;
219 const hiddenWidth =
220 viewport._tag !== "fill"
221 ? viewport.width * layoutZoomFactor
222 : content
223 ? content.width / content.scale
224 : (lastRect?.width ?? 1280);
225 const hiddenHeight =
226 viewport._tag !== "fill"
227 ? viewport.height * layoutZoomFactor
228 : content
229 ? content.height / content.scale
230 : (lastRect?.height ?? 800);
231 // Build from primitives on each side of the resize hook to keep both objects cached.
232 const containerSize =
233 active && lastRect ? lastRect : { width: hiddenWidth, height: hiddenHeight };
234 const deviceToolbarVisible = active && viewport._tag !== "fill" && !presentation.fitSourceContent;
235 const {
236 activeDrag,
237 commitViewportChange,
238 effectiveViewport,
239 handleResizeKeyDown,
240 handleResizePointerDown,
241 layout: viewportLayout,
242 } = useBrowserViewportResize({
243 target: { threadRef, tabId, runtimeTabId },
244 viewport,
245 zoomFactor: layoutZoomFactor,
246 containerSize,
247 deviceToolbarVisible,
248 aspectRatio: lockedAspectRatio,
249 });
250 const fittedSourceViewport =
251 presentation.fitSourceContent && lastRect
252 ? resolveFittedBrowserViewport(viewport, presentation.fittedSourceContent, layoutZoomFactor)
253 : null;
254 const layout =
255 fittedSourceViewport && lastRect
256 ? resolveBrowserViewportLayout(lastRect, fittedSourceViewport, layoutZoomFactor)
257 : viewportLayout;
258
259 const syncContentPresentation = () => {
260 const wrapper = wrapperRef.current;
261 if (!wrapper) return;
262 useBrowserSurfaceStore.getState().presentContent(runtimeTabId, {
263 x: layout.viewportX,
264 y: layout.viewportY,
265 width: layout.viewportWidth,
266 height: layout.viewportHeight,
267 scale: layout.viewportScale,
268 scrollLeft: wrapper.scrollLeft,
269 scrollTop: wrapper.scrollTop,
270 });
271 };
272
273 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- schedules a frame that publishes the webview layout and scroll to the browser surface store
274 useEffect(() => {
275 const frameId = window.requestAnimationFrame(syncContentPresentation);
276 return () => window.cancelAnimationFrame(frameId);
277 }, [syncContentPresentation]);
278
279 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the webview wrapper element to its origin for a new tab or viewport size
280 useEffect(() => {
281 const wrapper = wrapperRef.current;
282 if (!wrapper) return;
283 wrapper.scrollTo({ left: 0, top: 0 });
284 }, [
285 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A new tab or viewport size starts the canvas scrolled to its origin.
286 runtimeTabId,
287 viewport._tag,
288 viewportHeight,
289 viewportWidth,
290 ]);
291
292 if (!clientSettingsHydrated || !config) return null;
293
294 const renderingActive = active || backgroundActivity || pictureInPicture || recordingActive;
295 const wrapperStyle = resolveHostedBrowserWebviewWrapperStyle({
296 active,
297 renderingActive,
298 // Electron 43 can permanently blank a macOS webview after `visibility: hidden`.
299 keepPaintableWhenInactive: isMacPlatform(navigator.platform),
300 cornerRadius: presentation.cornerRadius,
301 zIndex: presentation.zIndex,
302 rect: lastRect,
303 hiddenSize: { width: hiddenWidth, height: hiddenHeight },
304 });
305
306 return (
307 <div
308 ref={wrapperRef}
309 className="fixed overflow-hidden bg-muted/35"
310 style={{ ...wrapperStyle, overscrollBehavior: "contain" }}
311 onScroll={syncContentPresentation}
312 data-preview-rendering={renderingActive ? "active" : "suspended"}
313 data-preview-viewport={runtimeTabId}
314 >
315 <div className="relative" style={{ width: layout.canvasWidth, height: layout.canvasHeight }}>
316 {deviceToolbarVisible && effectiveViewport._tag !== "fill" ? (
317 <BrowserDeviceToolbar
318 setting={effectiveViewport}
319 width={Math.max(1, Math.round(active && lastRect ? lastRect.width : hiddenWidth))}
320 aspectRatio={lockedAspectRatio}
321 onAspectRatioChange={handleAspectRatioChange}
322 onChange={commitViewportChange}
323 />
324 ) : null}
325 <webview
326 key={webviewGeneration}
327 ref={setWebviewRef}
328 // Electron needs allowpopups at attachment. React drops boolean values for unknown attributes.
329 {...({ allowpopups: "true" } as unknown as { readonly allowpopups?: boolean })}
330 src={webviewGeneration === 0 ? initialSrc : recoverySrc}
331 partition={config.partition}
332 webpreferences={config.webPreferences}
333 {...(config.preloadUrl ? { preload: config.preloadUrl } : {})}
334 data-preview-tab={runtimeTabId}
335 data-preview-server-tab={tabId}
336 data-preview-viewport-mode={effectiveViewport._tag}
337 data-preview-viewport-key={browserViewportSettingKey(effectiveViewport)}
338 data-preview-css-width={
339 fittedSourceViewport
340 ? fittedSourceViewport.width
341 : effectiveViewport._tag === "fill"
342 ? Math.max(1, Math.round(layout.viewportWidth / layoutZoomFactor))
343 : effectiveViewport.width
344 }
345 data-preview-css-height={
346 fittedSourceViewport
347 ? fittedSourceViewport.height
348 : effectiveViewport._tag === "fill"
349 ? Math.max(1, Math.round(layout.viewportHeight / layoutZoomFactor))
350 : effectiveViewport.height
351 }
352 aria-hidden={active ? undefined : true}
353 className={cn(
354 "absolute flex overflow-hidden bg-white",
355 active && !layout.fillsPanel && "ring-1 ring-border/70 shadow-sm",
356 )}
357 style={{
358 left: layout.viewportX,
359 top: layout.viewportY,
360 width: layout.viewportWidth / layout.viewportScale,
361 height: layout.viewportHeight / layout.viewportScale,
362 transform: layout.viewportScale < 1 ? `scale(${layout.viewportScale})` : undefined,
363 transformOrigin: "top left",
364 }}
365 />
366 {active && effectiveViewport._tag !== "fill" && !fittedSourceViewport ? (
367 <>
368 <BrowserViewportResizeHandles
369 layout={layout}
370 activeDirection={activeDrag?.direction ?? null}
371 onPointerDown={handleResizePointerDown}
372 onKeyDown={handleResizeKeyDown}
373 />
374 {activeDrag ? (
375 <div
376 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"
377 style={{
378 left: layout.viewportX + layout.viewportWidth / 2,
379 top: layout.viewportY + 10,
380 }}
381 aria-hidden="true"
382 >
383 {activeDrag.width} × {activeDrag.height}
384 </div>
385 ) : null}
386 </>
387 ) : null}
388 </div>
389 </div>
390 );
391}