Open History to see the last commit
1"use client";
2
3import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
4import { useEffect, useMemo } from "react";
5
6import { isElectron } from "~/env";
7import { useTheme } from "~/hooks/useTheme";
8import { useActivePreviewSessions } from "~/previewStateStore";
9
10import { readPreviewAnnotationTheme } from "./annotationTheme";
11import { useBrowserPointerStore } from "./browserPointerStore";
12import { HostedBrowserWebview } from "./HostedBrowserWebview";
13
14export function ElectronBrowserHost() {
15 const { resolvedTheme } = useTheme();
16 const previewByThreadKey = useActivePreviewSessions();
17 const sessions = useMemo(
18 () =>
19 Object.entries(previewByThreadKey).flatMap(([threadKey, previewState]) => {
20 const threadRef = parseScopedThreadKey(threadKey);
21 return threadRef
22 ? Object.values(previewState.sessions).map((snapshot) => ({
23 threadRef,
24 snapshot,
25 active: previewState.activeTabId === snapshot.tabId,
26 }))
27 : [];
28 }),
29 [previewByThreadKey],
30 );
31
32 useEffect(() => {
33 const preview = window.desktopBridge?.preview;
34 if (!preview) return;
35
36 let lastSerializedTheme = "";
37 const syncTheme = () => {
38 const theme = readPreviewAnnotationTheme();
39 const serializedTheme = JSON.stringify(theme);
40 if (serializedTheme === lastSerializedTheme) return;
41 lastSerializedTheme = serializedTheme;
42 void preview.setAnnotationTheme(theme).catch(() => {
43 lastSerializedTheme = "";
44 });
45 };
46 const frameId = window.requestAnimationFrame(syncTheme);
47 const observer = new MutationObserver(syncTheme);
48 observer.observe(document.documentElement, {
49 attributes: true,
50 attributeFilter: ["class", "style"],
51 });
52 const headObserver = new MutationObserver(syncTheme);
53 headObserver.observe(document.head, {
54 childList: true,
55 subtree: true,
56 characterData: true,
57 });
58 return () => {
59 window.cancelAnimationFrame(frameId);
60 observer.disconnect();
61 headObserver.disconnect();
62 };
63 }, [resolvedTheme]);
64
65 useEffect(() => {
66 const preview = window.desktopBridge?.preview;
67 if (!preview) return;
68 return preview.onPointerEvent((event) => {
69 useBrowserPointerStore.getState().apply(event);
70 });
71 }, []);
72
73 if (!isElectron) return null;
74 return (
75 <div className="contents" data-electron-browser-host>
76 {sessions.map(({ threadRef, snapshot }) => {
77 const url = snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
78 return (
79 <HostedBrowserWebview
80 key={snapshot.tabId}
81 threadRef={threadRef}
82 tabId={snapshot.tabId}
83 initialUrl={url}
84 />
85 );
86 })}
87 </div>
88 );
89}