Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ElectronBrowserHost.tsx

232 lines8.3 KB

1"use client";
2​
3import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
4import {
5 AuthPreviewOperateScope,
6 FILL_PREVIEW_VIEWPORT,
7 type ScopedThreadRef,
8} from "@t3tools/contracts";
9import { useAtomValue } from "@effect/atom-react";
10import { type ComponentProps, useEffect, useMemo, useRef, useState } from "react";
11​
12import { primaryEnvironmentIdAtom } from "~/state/primaryEnvironment";
13​
14import { isElectron } from "~/env";
15import { useClientSettingsHydrated } from "~/hooks/useSettings";
16import { useTheme } from "~/hooks/useTheme";
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 { hostsServerTabProfile } from "./previewRuntime";
28import { previewRuntimeTabId } from "./previewRuntimeTabId";
29import { acquireDesktopTab } from "./desktopTabLifetime";
30import { usePreviewBridge } from "~/components/preview/usePreviewBridge";
31​
32export function ElectronBrowserHost() {
33 const { resolvedTheme } = useTheme();
34 const previewByThreadKey = useActivePreviewSessions();
35 const primaryEnvironmentId = useAtomValue(primaryEnvironmentIdAtom);
36 const sessions = useMemo(
37 () =>
38 Object.entries(previewByThreadKey).flatMap(([threadKey, previewState]) => {
39 const threadRef = parseScopedThreadKey(threadKey);
40 // Local server tabs keep their desktop profile in isolated pages; remote ones run there.
41 return threadRef
42 ? Object.values(previewState.sessions)
43 .filter(
44 (snapshot) =>
45 snapshot.runtime !== "server" ||
46 hostsServerTabProfile(threadRef.environmentId, primaryEnvironmentId, snapshot),
47 )
48 .map((snapshot) => ({
49 threadRef,
50 snapshot,
51 runtimeTabId: previewRuntimeTabId(
52 threadRef,
53 previewState.serverEpoch,
54 snapshot.tabId,
55 ),
56 pictureInPicture:
57 previewState.desktopByTabId[snapshot.tabId]?.pictureInPicture ?? false,
58 zoomFactor: previewState.desktopByTabId[snapshot.tabId]?.zoomFactor ?? 1,
59 }))
60 : [];
61 }),
62 [previewByThreadKey, primaryEnvironmentId],
63 );
64​
65 useEffect(() => {
66 const preview = window.desktopBridge?.preview;
67 if (!preview) return;
68​
69 let lastSerializedTheme = "";
70 const syncTheme = () => {
71 const theme = readPreviewAnnotationTheme();
72 const serializedTheme = JSON.stringify(theme);
73 if (serializedTheme === lastSerializedTheme) return;
74 lastSerializedTheme = serializedTheme;
75 void preview.setAnnotationTheme(theme).catch(() => {
76 lastSerializedTheme = "";
77 });
78 };
79 const frameId = window.requestAnimationFrame(syncTheme);
80 const observer = new MutationObserver(syncTheme);
81 observer.observe(document.documentElement, {
82 attributes: true,
83 attributeFilter: ["class", "style"],
84 });
85 const headObserver = new MutationObserver(syncTheme);
86 headObserver.observe(document.head, {
87 childList: true,
88 subtree: true,
89 characterData: true,
90 });
91 return () => {
92 window.cancelAnimationFrame(frameId);
93 observer.disconnect();
94 headObserver.disconnect();
95 };
96 }, [resolvedTheme]);
97​
98 useEffect(() => {
99 const preview = window.desktopBridge?.preview;
100 if (!preview) return;
101 return preview.onPointerEvent((event) => {
102 useBrowserPointerStore.getState().apply(event);
103 });
104 }, []);
105​
106 // A `target="_blank"` link inside a hosted page opens as another tab of the
107 // same thread, so the page that held the link stays where it is.
108 const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: true });
109 const sessionByRuntimeTabId = useRef(new Map<string, (typeof sessions)[number]>());
110 useEffect(() => {
111 sessionByRuntimeTabId.current = new Map(
112 sessions.map((session) => [session.runtimeTabId, session]),
113 );
114 }, [sessions]);
115 useEffect(() => {
116 const preview = window.desktopBridge?.preview;
117 if (!preview) return;
118 return preview.onOpenLink(({ tabId, url, background }) => {
119 const source = sessionByRuntimeTabId.current.get(tabId);
120 if (!source) return;
121 // The new tab keeps the source tab's profile so its cookies carry over.
122 void openUrlInPreview({
123 threadRef: source.threadRef,
124 url,
125 openPreview,
126 profileId: source.snapshot.profileId,
127 background,
128 });
129 });
130 }, [openPreview]);
131​
132 if (!isElectron) return null;
133 return (
134 <div className="contents" data-electron-browser-host>
135 {sessions.map(({ threadRef, snapshot, runtimeTabId, pictureInPicture, zoomFactor }) => {
136 const url = snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
137 if (snapshot.runtime === "server") {
138 return (
139 <AuthorizedIsolatedBrowserTab
140 key={runtimeTabId}
141 threadRef={threadRef}
142 tabId={snapshot.tabId}
143 runtimeTabId={runtimeTabId}
144 url={url}
145 profileId={snapshot.profileId}
146 />
147 );
148 }
149 return (
150 <AuthorizedBrowserWebview
151 key={runtimeTabId}
152 threadRef={threadRef}
153 tabId={snapshot.tabId}
154 runtimeTabId={runtimeTabId}
155 initialUrl={url}
156 viewport={snapshot.viewport ?? FILL_PREVIEW_VIEWPORT}
157 pictureInPicture={pictureInPicture}
158 profileId={snapshot.profileId}
159 zoomFactor={zoomFactor}
160 />
161 );
162 })}
163 </div>
164 );
166​
167function AuthorizedIsolatedBrowserTab(props: {
168 readonly threadRef: ScopedThreadRef;
169 readonly tabId: string;
170 readonly runtimeTabId: string;
171 readonly url: string | null;
172 readonly profileId: string | undefined;
173}) {
174 const canOperatePreview = useEnvironmentScope(
175 props.threadRef.environmentId,
176 AuthPreviewOperateScope,
177 );
178 const profileId = useTabProfileId(props.profileId);
179 const hydrated = useClientSettingsHydrated();
180 const { threadRef, tabId, runtimeTabId, url } = props;
181 usePreviewBridge({ threadRef, tabId, runtimeTabId, serverDriven: true });
182 // The initial URL belongs to creation; subsequent navigation is server-owned.
183 const initialUrl = useRef(url);
184 useEffect(() => {
185 if (!hydrated || !canOperatePreview) return;
186 const lease = acquireDesktopTab(
187 runtimeTabId,
188 { threadId: threadRef.threadId, tabId },
189 {
190 environmentId: threadRef.environmentId,
191 profileId,
192 ...(initialUrl.current === null ? {} : { url: initialUrl.current }),
193 },
194 );
195 return lease.release;
196 }, [
197 canOperatePreview,
198 hydrated,
199 profileId,
200 runtimeTabId,
201 tabId,
202 threadRef.environmentId,
203 threadRef.threadId,
204 ]);
205 return null;
207​
208function AuthorizedBrowserWebview(props: ComponentProps<typeof HostedBrowserWebview>) {
209 const canOperatePreview = useEnvironmentScope(
210 props.threadRef.environmentId,
211 AuthPreviewOperateScope,
212 );
213 const profileId = useTabProfileId(props.profileId);
214 return canOperatePreview ? <HostedBrowserWebview {...props} profileId={profileId} /> : null;
216​
217/**
218 * Agent `preview_open` normally carries the profile clients reported (see
219 * BrowserProfileReporter). An agent tab opened before any client reported has
220 * none, so it falls back to the configured default here. It is latched once
221 * settings load: Electron fixes the partition when the guest attaches, so a
222 * later settings change must not move a live tab.
223 */
224function useTabProfileId(profileId: string | undefined): string | undefined {
225 const hydrated = useClientSettingsHydrated();
226 const defaultProfileId = useBrowserDefaults().profileId;
227 const [fallback, setFallback] = useState<string | undefined>(undefined);
228 if (profileId === undefined && hydrated && fallback === undefined) {
229 setFallback(defaultProfileId);
230 }
231 return profileId ?? fallback;