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 { useEffect, useEffectEvent, 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 remountCrashedWebview = useEffectEvent(() => {
140 setRecoverySrc(initialUrl ?? initialSrc);
141 setWebviewGeneration((generation) => generation + 1);
142 });
143
144 const setWebviewRef = (node: HTMLElement | null) => {
145 webviewRef.current = node as ElectronWebview | null;
146 };
147
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 // The main-process tab and the DOM webview are created by separate
160 // effects. Wait for the former so registration cannot race and fail
161 // with PreviewTabNotFoundError on a fast about:blank attachment.
162 await lease.ready;
163 if (disposed || webviewRef.current !== webview) return;
164 const webContentsId = webview.getWebContentsId();
165 if (Number.isInteger(webContentsId) && webContentsId > 0) {
166 await bridge.registerWebview(runtimeTabId, webContentsId);
167 }
168 } catch {}
169 })();
170 };
171 const recoverGuest = () => {
172 if (disposed || recoveryTimeout !== null) return;
173 const recovery = planWebviewCrashRecovery(crashRecoveryRef.current, Date.now());
174 if (!recovery) return;
175 crashRecoveryRef.current = recovery.state;
176 recoveryTimeout = setTimeout(() => {
177 recoveryTimeout = null;
178 if (!disposed) remountCrashedWebview();
179 }, recovery.delayMs);
180 };
181 // A click inside the guest only reaches this document as a webview focus
182 // event, so open menus and popovers never see the outside press that
183 // would dismiss them. Replay it as a pointerdown on the webview itself.
184 const dismissHostPopups = () => {
185 webview.dispatchEvent(
186 new PointerEvent("pointerdown", { bubbles: true, pointerType: "mouse" }),
187 );
188 };
189 webview.addEventListener("did-attach", register);
190 webview.addEventListener("dom-ready", register);
191 webview.addEventListener("render-process-gone", recoverGuest);
192 webview.addEventListener("focus", dismissHostPopups);
193 register();
194 return () => {
195 disposed = true;
196 if (recoveryTimeout !== null) clearTimeout(recoveryTimeout);
197 webview.removeEventListener("did-attach", register);
198 webview.removeEventListener("dom-ready", register);
199 webview.removeEventListener("render-process-gone", recoverGuest);
200 webview.removeEventListener("focus", dismissHostPopups);
201 };
202 }, [
203 clientSettingsHydrated,
204 config,
205 runtimeTabId,
206 // 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.
207 webviewGeneration,
208 ]);
209
210 const active = presentation.visible && presentation.rect !== null;
211 const lastRect = presentation.rect;
212 const normalizedZoomFactor = Number.isFinite(zoomFactor) && zoomFactor > 0 ? zoomFactor : 1;
213 const viewportWidth = viewport._tag === "fill" ? null : viewport.width;
214 const viewportHeight = viewport._tag === "fill" ? null : viewport.height;
215 const viewportAspectRatio =
216 viewportWidth === null || viewportHeight === null ? null : viewportWidth / viewportHeight;
217 const lockedAspectRatio =
218 aspectRatioLocked && viewportAspectRatio !== null ? viewportAspectRatio : null;
219 const handleAspectRatioChange = (aspectRatio: number | null) => {
220 setAspectRatioLocked(aspectRatio !== null);
221 };
222 const content = presentation.content;
223 const hiddenWidth =
224 viewport._tag !== "fill"
225 ? viewport.width * normalizedZoomFactor
226 : content
227 ? content.width / content.scale
228 : (lastRect?.width ?? 1280);
229 const hiddenHeight =
230 viewport._tag !== "fill"
231 ? viewport.height * normalizedZoomFactor
232 : content
233 ? content.height / content.scale
234 : (lastRect?.height ?? 800);
235 // Built from primitives on each side of the resize hook, so neither object is
236 // shared across it and both stay cached; the hook's layout keys the sync effect.
237 const containerSize =
238 active && lastRect ? lastRect : { width: hiddenWidth, height: hiddenHeight };
239 const deviceToolbarVisible = active && viewport._tag !== "fill" && !presentation.fitSourceContent;
240 const {
241 activeDrag,
242 commitViewportChange,
243 effectiveViewport,
244 handleResizeKeyDown,
245 handleResizePointerDown,
246 layout: viewportLayout,
247 } = useBrowserViewportResize({
248 tabId: runtimeTabId,
249 viewport,
250 zoomFactor,
251 containerSize,
252 deviceToolbarVisible,
253 aspectRatio: lockedAspectRatio,
254 });
255 const fittedSourceViewport =
256 presentation.fitSourceContent && lastRect
257 ? resolveFittedBrowserViewport(
258 viewport,
259 presentation.fittedSourceContent,
260 normalizedZoomFactor,
261 )
262 : null;
263 const layout =
264 fittedSourceViewport && lastRect
265 ? resolveBrowserViewportLayout(lastRect, fittedSourceViewport, normalizedZoomFactor)
266 : viewportLayout;
267
268 const syncContentPresentation = () => {
269 const wrapper = wrapperRef.current;
270 if (!wrapper) return;
271 useBrowserSurfaceStore.getState().presentContent(runtimeTabId, {
272 x: layout.viewportX,
273 y: layout.viewportY,
274 width: layout.viewportWidth,
275 height: layout.viewportHeight,
276 scale: layout.viewportScale,
277 scrollLeft: wrapper.scrollLeft,
278 scrollTop: wrapper.scrollTop,
279 });
280 };
281
282 useEffect(() => {
283 const frameId = window.requestAnimationFrame(syncContentPresentation);
284 return () => window.cancelAnimationFrame(frameId);
285 }, [syncContentPresentation]);
286
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 if (!clientSettingsHydrated || !config) return null;
300
301 const renderingActive = active || backgroundActivity || pictureInPicture || recordingActive;
302 const wrapperStyle = resolveHostedBrowserWebviewWrapperStyle({
303 active,
304 renderingActive,
305 // Electron 43 can permanently blank a macOS webview after `visibility: hidden`.
306 keepPaintableWhenInactive: isMacPlatform(navigator.platform),
307 cornerRadius: presentation.cornerRadius,
308 zIndex: presentation.zIndex,
309 rect: lastRect,
310 hiddenSize: { width: hiddenWidth, height: hiddenHeight },
311 });
312
313 return (
314 <div
315 ref={wrapperRef}
316 className="fixed overflow-hidden bg-muted/35"
317 style={{ ...wrapperStyle, overscrollBehavior: "contain" }}
318 onScroll={syncContentPresentation}
319 data-preview-rendering={renderingActive ? "active" : "suspended"}
320 data-preview-viewport={runtimeTabId}
321 >
322 <div className="relative" style={{ width: layout.canvasWidth, height: layout.canvasHeight }}>
323 {deviceToolbarVisible && effectiveViewport._tag !== "fill" ? (
324 <BrowserDeviceToolbar
325 setting={effectiveViewport}
326 width={Math.max(1, Math.round(active && lastRect ? lastRect.width : hiddenWidth))}
327 aspectRatio={lockedAspectRatio}
328 onAspectRatioChange={handleAspectRatioChange}
329 onChange={commitViewportChange}
330 />
331 ) : null}
332 <webview
333 key={webviewGeneration}
334 ref={setWebviewRef}
335 // Must be an attribute on the element itself: Electron reads it when the
336 // guest attaches, so setting it from the ref callback lands too late and
337 // the guest attaches with popups disabled. React types `allowpopups` as a
338 // boolean, but react-dom drops boolean values for unrecognized attributes,
339 // so the literal string has to be spread past the type.
340 {...({ allowpopups: "true" } as unknown as { readonly allowpopups?: boolean })}
341 src={webviewGeneration === 0 ? initialSrc : recoverySrc}
342 partition={config.partition}
343 webpreferences={config.webPreferences}
344 {...(config.preloadUrl ? { preload: config.preloadUrl } : {})}
345 data-preview-tab={runtimeTabId}
346 data-preview-server-tab={tabId}
347 data-preview-viewport-mode={effectiveViewport._tag}
348 data-preview-viewport-key={browserViewportSettingKey(effectiveViewport)}
349 data-preview-css-width={
350 fittedSourceViewport
351 ? fittedSourceViewport.width
352 : effectiveViewport._tag === "fill"
353 ? Math.max(1, Math.round(layout.viewportWidth / normalizedZoomFactor))
354 : effectiveViewport.width
355 }
356 data-preview-css-height={
357 fittedSourceViewport
358 ? fittedSourceViewport.height
359 : effectiveViewport._tag === "fill"
360 ? Math.max(1, Math.round(layout.viewportHeight / normalizedZoomFactor))
361 : effectiveViewport.height
362 }
363 aria-hidden={active ? undefined : true}
364 className={cn(
365 "absolute flex overflow-hidden bg-white",
366 active && !layout.fillsPanel && "ring-1 ring-border/70 shadow-sm",
367 )}
368 style={{
369 left: layout.viewportX,
370 top: layout.viewportY,
371 width: layout.viewportWidth / layout.viewportScale,
372 height: layout.viewportHeight / layout.viewportScale,
373 transform: layout.viewportScale < 1 ? `scale(${layout.viewportScale})` : undefined,
374 transformOrigin: "top left",
375 }}
376 />
377 {active && effectiveViewport._tag !== "fill" && !fittedSourceViewport ? (
378 <>
379 <BrowserViewportResizeHandles
380 layout={layout}
381 activeDirection={activeDrag?.direction ?? null}
382 onPointerDown={handleResizePointerDown}
383 onKeyDown={handleResizeKeyDown}
384 />
385 {activeDrag ? (
386 <div
387 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"
388 style={{
389 left: layout.viewportX + layout.viewportWidth / 2,
390 top: layout.viewportY + 10,
391 }}
392 aria-hidden="true"
393 >
394 {activeDrag.width} × {activeDrag.height}
395 </div>
396 ) : null}
397 </>
398 ) : null}
399 </div>
400 </div>
401 );
402}