Open History to see the last commit
1"use client";
2
3import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
4import {
5 AuthPreviewOperateScope,
6 type DesktopPreviewOpenLinkEvent,
7 FILL_PREVIEW_VIEWPORT,
8} from "@t3tools/contracts";
9import { useAtomValue } from "@effect/atom-react";
10import { type ComponentProps, useEffect, useEffectEvent, useState } from "react";
11
12import { primaryEnvironmentIdAtom } from "~/state/primaryEnvironment";
13
14import { isElectron } from "~/env";
15import { useClientSettingsHydrated } from "~/hooks/useSettings";
16import { useDesktopHostedPreviewSessions } from "~/components/preview/usePreviewSession";
17import { useActivePreviewSessions } from "~/previewStateStore";
18import { previewEnvironment } from "~/state/preview";
19import { useEnvironmentScope } from "~/state/session";
20import { useAtomCommand } from "~/state/use-atom-command";
21
22import { readPreviewAnnotationTheme } from "./annotationTheme";
23import { useBrowserDefaults } from "./browserDefaults";
24import { useBrowserPointerStore } from "./browserPointerStore";
25import { HostedBrowserWebview } from "./HostedBrowserWebview";
26import { openUrlInPreview } from "./openFileInPreview";
27import { rendersServerTabNatively } from "./previewRuntime";
28import { previewRuntimeTabId } from "./previewRuntimeTabId";
29
30export function ElectronBrowserHost() {
31 const previewByThreadKey = useActivePreviewSessions();
32 const primaryEnvironmentId = useAtomValue(primaryEnvironmentIdAtom);
33 useDesktopHostedPreviewSessions(primaryEnvironmentId);
34 const activeSessions = Object.entries(previewByThreadKey).flatMap(([threadKey, previewState]) => {
35 const threadRef = parseScopedThreadKey(threadKey);
36 return threadRef
37 ? Object.values(previewState.sessions)
38 .filter(
39 (snapshot) =>
40 snapshot.runtime !== "server" ||
41 rendersServerTabNatively(threadRef.environmentId, primaryEnvironmentId, snapshot),
42 )
43 .map((snapshot) => ({
44 threadRef,
45 snapshot,
46 runtimeTabId: previewRuntimeTabId(threadRef, previewState.serverEpoch, snapshot.tabId),
47 pictureInPicture:
48 previewState.desktopByTabId[snapshot.tabId]?.pictureInPicture ?? false,
49 zoomFactor: previewState.desktopByTabId[snapshot.tabId]?.zoomFactor ?? 1,
50 }))
51 : [];
52 });
53 // Electron destroys a moved webview's guest, so the render order must not follow the server's
54 // updatedAt order. Any fixed order works; this one is not a display order.
55 const sessions = activeSessions.toSorted((left, right) =>
56 left.runtimeTabId < right.runtimeTabId ? -1 : left.runtimeTabId > right.runtimeTabId ? 1 : 0,
57 );
58
59 useEffect(() => {
60 const preview = window.desktopBridge?.preview;
61 if (!preview) return;
62
63 let lastSerializedTheme = "";
64 const syncTheme = () => {
65 const theme = readPreviewAnnotationTheme();
66 const serializedTheme = JSON.stringify(theme);
67 if (serializedTheme === lastSerializedTheme) return;
68 lastSerializedTheme = serializedTheme;
69 void preview.setAnnotationTheme(theme).catch(() => {
70 lastSerializedTheme = "";
71 });
72 };
73 const frameId = window.requestAnimationFrame(syncTheme);
74 const observer = new MutationObserver(syncTheme);
75 observer.observe(document.documentElement, {
76 attributes: true,
77 attributeFilter: ["class", "style"],
78 });
79 const headObserver = new MutationObserver(syncTheme);
80 headObserver.observe(document.head, {
81 childList: true,
82 subtree: true,
83 characterData: true,
84 });
85 return () => {
86 window.cancelAnimationFrame(frameId);
87 observer.disconnect();
88 headObserver.disconnect();
89 };
90 }, []);
91
92 useEffect(() => {
93 const preview = window.desktopBridge?.preview;
94 if (!preview) return;
95 return preview.onPointerEvent((event) => {
96 useBrowserPointerStore.getState().apply(event);
97 });
98 }, []);
99
100 const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: true });
101 const onOpenLink = useEffectEvent(({ tabId, url, background }: DesktopPreviewOpenLinkEvent) => {
102 const source = sessions.find((session) => session.runtimeTabId === tabId);
103 if (!source) return;
104 void openUrlInPreview({
105 threadRef: source.threadRef,
106 url,
107 openPreview,
108 profileId: source.snapshot.profileId,
109 background,
110 });
111 });
112 useEffect(() => {
113 const preview = window.desktopBridge?.preview;
114 if (!preview) return;
115 return preview.onOpenLink(onOpenLink);
116 }, []);
117
118 if (!isElectron) return null;
119 return (
120 <div className="contents" data-electron-browser-host>
121 {sessions.map(({ threadRef, snapshot, runtimeTabId, pictureInPicture, zoomFactor }) => {
122 const url = snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
123 return (
124 <AuthorizedBrowserWebview
125 key={runtimeTabId}
126 threadRef={threadRef}
127 tabId={snapshot.tabId}
128 runtimeTabId={runtimeTabId}
129 initialUrl={url}
130 viewport={snapshot.viewport ?? FILL_PREVIEW_VIEWPORT}
131 pictureInPicture={pictureInPicture}
132 profileId={snapshot.profileId}
133 zoomFactor={zoomFactor}
134 serverDriven={snapshot.runtime === "server"}
135 {...(snapshot.runtime === "server"
136 ? {
137 serverRendering: {
138 colorScheme: snapshot.colorScheme ?? "system",
139 zoomFactor: snapshot.zoomFactor ?? 1,
140 },
141 }
142 : {})}
143 />
144 );
145 })}
146 </div>
147 );
148}
149
150function AuthorizedBrowserWebview(props: ComponentProps<typeof HostedBrowserWebview>) {
151 const canOperatePreview = useEnvironmentScope(
152 props.threadRef.environmentId,
153 AuthPreviewOperateScope,
154 );
155 const profileId = useTabProfileId(props.profileId);
156 return canOperatePreview ? <HostedBrowserWebview {...props} profileId={profileId} /> : null;
157}
158
159/**
160 * It is latched once settings load: Electron fixes the partition when the guest attaches, so a
161 * later settings change must not move a live tab.
162 */
163function useTabProfileId(profileId: string | undefined): string | undefined {
164 const hydrated = useClientSettingsHydrated();
165 const defaultProfileId = useBrowserDefaults().profileId;
166 const [fallback, setFallback] = useState<string | undefined>(undefined);
167 if (profileId === undefined && hydrated && fallback === undefined) {
168 setFallback(defaultProfileId);
169 }
170 return profileId ?? fallback;
171}