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