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 {
11 preventThumbButtonFocus,
12 takeThumbButtonNavigation,
13} from "~/components/preview/thumbButtons";
14import { usePreviewBridge } from "~/components/preview/usePreviewBridge";
15import { useClientSettingsHydrated } from "~/hooks/useSettings";
16import { cn, isMacPlatform } from "~/lib/utils";
17
18import { resolveBrowserSurfacePanelRect, useBrowserSurfaceStore } from "./browserSurfaceStore";
19import { useActiveBrowserRecordingTabIds } from "./browserRecording";
20import {
21 browserViewportSettingKey,
22 resolveBrowserViewportLayout,
23 resolveFittedBrowserViewport,
24} from "./browserViewportLayout";
25import { BrowserDeviceToolbar } from "./BrowserDeviceToolbar";
26import { BrowserViewportResizeHandles } from "./BrowserViewportResizeHandles";
27import { acquireDesktopTab, type AcquiredDesktopTab, withDesktopTab } from "./desktopTabLifetime";
28import { resolveHostedBrowserWebviewWrapperStyle } from "./hostedBrowserWebviewStyle";
29import { usePreviewWebviewConfig } from "./previewWebviewConfigState";
30import { useBrowserLayoutZoomFactor } from "./useBrowserLayoutZoomFactor";
31import { useBrowserViewportResize } from "./useBrowserViewportResize";
32import {
33 INITIAL_WEBVIEW_CRASH_RECOVERY_STATE,
34 planWebviewCrashRecovery,
35 type WebviewCrashRecoveryState,
36} from "./webviewCrashRecovery";
37
38interface ElectronWebview extends HTMLElement {
39 src: string;
40 partition: string;
41 preload?: string;
42 webpreferences?: string;
43 getWebContentsId: () => number;
44 executeJavaScript: (code: string, userGesture?: boolean) => Promise<unknown>;
45}
46
47declare global {
48 interface HTMLElementTagNameMap {
49 webview: ElectronWebview;
50 }
51}
52
53export function HostedBrowserWebview(props: {
54 readonly threadRef: ScopedThreadRef;
55 readonly tabId: string;
56 readonly runtimeTabId: string;
57 readonly initialUrl: string | null;
58 readonly viewport: PreviewViewportSetting;
59 readonly pictureInPicture: boolean;
60 /** Fixed for the tab lifetime; Electron reads partition before guest attachment. */
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 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- leases the desktop preview tab for this webview and releases it on cleanup
113 useEffect(() => {
114 if (!clientSettingsHydrated) return;
115 crashRecoveryRef.current = INITIAL_WEBVIEW_CRASH_RECOVERY_STATE;
116 const lease = acquireDesktopTab(
117 runtimeTabId,
118 serverDriven ? { threadId: threadRef.threadId, tabId } : undefined,
119 );
120 tabLeaseRef.current = lease;
121 return () => {
122 if (tabLeaseRef.current === lease) tabLeaseRef.current = null;
123 lease.release();
124 };
125 }, [clientSettingsHydrated, runtimeTabId, serverDriven, tabId, threadRef.threadId]);
126
127 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- applies the server color scheme to the desktop preview tab through the desktop bridge
128 useEffect(() => {
129 const bridge = window.desktopBridge?.preview;
130 if (!bridge || serverColorScheme === undefined) return;
131 withDesktopTab(runtimeTabId, () => bridge.setColorScheme(runtimeTabId, serverColorScheme));
132 }, [runtimeTabId, serverColorScheme]);
133 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- applies the server zoom factor to the desktop preview tab through the desktop bridge
134 useEffect(() => {
135 const bridge = window.desktopBridge?.preview;
136 if (!bridge || serverZoomFactor === undefined) return;
137 withDesktopTab(runtimeTabId, () => bridge.setZoomFactor(runtimeTabId, serverZoomFactor));
138 }, [runtimeTabId, serverZoomFactor]);
139
140 const [webviewGeneration, setWebviewGeneration] = useState(0);
141 const [recoverySrc, setRecoverySrc] = useState(initialSrc);
142 const active = presentation.visible && presentation.rect !== null;
143 const shown = active || pictureInPicture;
144 const reportedShown = useEffectEvent(() => serverDriven && shown);
145 const remountCrashedWebview = useEffectEvent(() => {
146 setRecoverySrc(initialUrl ?? initialSrc);
147 setWebviewGeneration((generation) => generation + 1);
148 });
149
150 const setWebviewRef = (node: HTMLElement | null) => {
151 webviewRef.current = node as ElectronWebview | null;
152 };
153
154 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the webview's webContents with the desktop bridge and listens for crashes and focus
155 useEffect(() => {
156 const webview = webviewRef.current;
157 const bridge = previewBridge;
158 if (!clientSettingsHydrated || !webview || !config || !bridge) return;
159 let disposed = false;
160 let recoveryTimeout: ReturnType<typeof setTimeout> | null = null;
161 const register = () => {
162 const lease = tabLeaseRef.current;
163 if (!lease) return;
164 void (async () => {
165 try {
166 // Tab creation and webview attachment use separate effects; wait to avoid PreviewTabNotFoundError.
167 await lease.ready;
168 if (disposed || webviewRef.current !== webview) return;
169 const webContentsId = webview.getWebContentsId();
170 if (Number.isInteger(webContentsId) && webContentsId > 0) {
171 await bridge.registerWebview(runtimeTabId, webContentsId);
172 withDesktopTab(runtimeTabId, () => bridge.setShown(runtimeTabId, reportedShown()));
173 }
174 } catch {}
175 })();
176 };
177 const recoverGuest = () => {
178 if (disposed || recoveryTimeout !== null) return;
179 const recovery = planWebviewCrashRecovery(crashRecoveryRef.current, Date.now());
180 if (!recovery) return;
181 crashRecoveryRef.current = recovery.state;
182 recoveryTimeout = setTimeout(() => {
183 recoveryTimeout = null;
184 if (!disposed) remountCrashedWebview();
185 }, recovery.delayMs);
186 };
187 // Guest clicks only emit focus here; replay pointerdown to dismiss host popups.
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 }, [
207 clientSettingsHydrated,
208 config,
209 runtimeTabId,
210 // 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.
211 webviewGeneration,
212 ]);
213
214 const lastRect = presentation.rect;
215 const layoutZoomFactor = useBrowserLayoutZoomFactor(zoomFactor);
216 const viewportWidth = viewport._tag === "fill" ? null : viewport.width;
217 const viewportHeight = viewport._tag === "fill" ? null : viewport.height;
218 const viewportAspectRatio =
219 viewportWidth === null || viewportHeight === null ? null : viewportWidth / viewportHeight;
220 const lockedAspectRatio =
221 aspectRatioLocked && viewportAspectRatio !== null ? viewportAspectRatio : null;
222 const handleAspectRatioChange = (aspectRatio: number | null) => {
223 setAspectRatioLocked(aspectRatio !== null);
224 };
225 const content = presentation.content;
226 const hiddenWidth =
227 viewport._tag !== "fill"
228 ? viewport.width * layoutZoomFactor
229 : content
230 ? content.width / content.scale
231 : (lastRect?.width ?? 1280);
232 const hiddenHeight =
233 viewport._tag !== "fill"
234 ? viewport.height * layoutZoomFactor
235 : content
236 ? content.height / content.scale
237 : (lastRect?.height ?? 800);
238 // Build from primitives on each side of the resize hook to keep both objects cached.
239 const containerSize =
240 active && lastRect ? lastRect : { width: hiddenWidth, height: hiddenHeight };
241 const deviceToolbarVisible = active && viewport._tag !== "fill" && !presentation.fitSourceContent;
242 const {
243 activeDrag,
244 commitViewportChange,
245 effectiveViewport,
246 handleResizeKeyDown,
247 handleResizePointerDown,
248 layout: viewportLayout,
249 } = useBrowserViewportResize({
250 target: { threadRef, tabId, runtimeTabId },
251 viewport,
252 zoomFactor: layoutZoomFactor,
253 containerSize,
254 deviceToolbarVisible,
255 aspectRatio: lockedAspectRatio,
256 });
257 const fittedSourceViewport =
258 presentation.fitSourceContent && lastRect
259 ? resolveFittedBrowserViewport(viewport, presentation.fittedSourceContent, layoutZoomFactor)
260 : null;
261 const layout =
262 fittedSourceViewport && lastRect
263 ? resolveBrowserViewportLayout(lastRect, fittedSourceViewport, layoutZoomFactor)
264 : viewportLayout;
265
266 const syncContentPresentation = () => {
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 };
279
280 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- schedules a frame that publishes the webview layout and scroll to the browser surface store
281 useEffect(() => {
282 const frameId = window.requestAnimationFrame(syncContentPresentation);
283 return () => window.cancelAnimationFrame(frameId);
284 }, [syncContentPresentation]);
285
286 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- scrolls the webview wrapper element to its origin for a new tab or viewport size
287 useEffect(() => {
288 const wrapper = wrapperRef.current;
289 if (!wrapper) return;
290 wrapper.scrollTo({ left: 0, top: 0 });
291 }, [
292 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A new tab or viewport size starts the canvas scrolled to its origin.
293 runtimeTabId,
294 viewport._tag,
295 viewportHeight,
296 viewportWidth,
297 ]);
298
299 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Report the mounted webview's visibility to the desktop host.
300 useEffect(() => {
301 const bridge = window.desktopBridge?.preview;
302 if (!clientSettingsHydrated || !bridge || !serverDriven) return;
303 withDesktopTab(runtimeTabId, () => bridge.setShown(runtimeTabId, shown));
304 return () => withDesktopTab(runtimeTabId, () => bridge.setShown(runtimeTabId, false));
305 }, [clientSettingsHydrated, runtimeTabId, serverDriven, shown]);
306
307 if (!clientSettingsHydrated || !config) return null;
308
309 // This fixed wrapper sits outside the right panel shell, so it takes thumb presses itself.
310 const navigateThumb = (direction: "back" | "forward") => {
311 if (direction === "back") void previewBridge?.goBack(runtimeTabId);
312 else void previewBridge?.goForward(runtimeTabId);
313 };
314
315 const renderingActive = active || backgroundActivity || pictureInPicture || recordingActive;
316 const wrapperStyle = resolveHostedBrowserWebviewWrapperStyle({
317 active,
318 renderingActive,
319 // Electron 43 can permanently blank a macOS webview after `visibility: hidden`.
320 keepPaintableWhenInactive: isMacPlatform(navigator.platform),
321 cornerRadius: presentation.cornerRadius,
322 zIndex: presentation.zIndex,
323 rect: lastRect,
324 hiddenSize: { width: hiddenWidth, height: hiddenHeight },
325 });
326
327 return (
328 <div
329 ref={wrapperRef}
330 className="fixed overflow-hidden bg-muted/35"
331 style={{ ...wrapperStyle, overscrollBehavior: "contain" }}
332 onScroll={syncContentPresentation}
333 onMouseDown={preventThumbButtonFocus}
334 onMouseUp={(event) => takeThumbButtonNavigation(event, navigateThumb)}
335 data-preview-rendering={renderingActive ? "active" : "suspended"}
336 data-preview-viewport={runtimeTabId}
337 >
338 <div className="relative" style={{ width: layout.canvasWidth, height: layout.canvasHeight }}>
339 {deviceToolbarVisible && effectiveViewport._tag !== "fill" ? (
340 <BrowserDeviceToolbar
341 setting={effectiveViewport}
342 width={Math.max(1, Math.round(active && lastRect ? lastRect.width : hiddenWidth))}
343 aspectRatio={lockedAspectRatio}
344 onAspectRatioChange={handleAspectRatioChange}
345 onChange={commitViewportChange}
346 />
347 ) : null}
348 <webview
349 key={webviewGeneration}
350 ref={setWebviewRef}
351 // Electron needs allowpopups at attachment. React drops boolean values for unknown attributes.
352 {...({ allowpopups: "true" } as unknown as { readonly allowpopups?: boolean })}
353 src={webviewGeneration === 0 ? initialSrc : recoverySrc}
354 partition={config.partition}
355 webpreferences={config.webPreferences}
356 {...(config.preloadUrl ? { preload: config.preloadUrl } : {})}
357 data-preview-tab={runtimeTabId}
358 data-preview-server-tab={tabId}
359 data-preview-viewport-mode={effectiveViewport._tag}
360 data-preview-viewport-key={browserViewportSettingKey(effectiveViewport)}
361 data-preview-css-width={
362 fittedSourceViewport
363 ? fittedSourceViewport.width
364 : effectiveViewport._tag === "fill"
365 ? Math.max(1, Math.round(layout.viewportWidth / layoutZoomFactor))
366 : effectiveViewport.width
367 }
368 data-preview-css-height={
369 fittedSourceViewport
370 ? fittedSourceViewport.height
371 : effectiveViewport._tag === "fill"
372 ? Math.max(1, Math.round(layout.viewportHeight / layoutZoomFactor))
373 : effectiveViewport.height
374 }
375 aria-hidden={active ? undefined : true}
376 className={cn(
377 "absolute flex overflow-hidden bg-white",
378 active && !layout.fillsPanel && "ring-1 ring-border/70 shadow-sm",
379 )}
380 style={{
381 left: layout.viewportX,
382 top: layout.viewportY,
383 width: layout.viewportWidth / layout.viewportScale,
384 height: layout.viewportHeight / layout.viewportScale,
385 transform: layout.viewportScale < 1 ? `scale(${layout.viewportScale})` : undefined,
386 transformOrigin: "top left",
387 }}
388 />
389 {active && effectiveViewport._tag !== "fill" && !fittedSourceViewport ? (
390 <>
391 <BrowserViewportResizeHandles
392 layout={layout}
393 activeDirection={activeDrag?.direction ?? null}
394 onPointerDown={handleResizePointerDown}
395 onKeyDown={handleResizeKeyDown}
396 />
397 {activeDrag ? (
398 <div
399 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"
400 style={{
401 left: layout.viewportX + layout.viewportWidth / 2,
402 top: layout.viewportY + 10,
403 }}
404 aria-hidden="true"
405 >
406 {activeDrag.width} × {activeDrag.height}
407 </div>
408 ) : null}
409 </>
410 ) : null}
411 </div>
412 </div>
413 );
414}