Open History to see the last commit
1import type {
2 DesktopPreviewTabState,
3 PreviewReportStatusInput,
4 ScopedThreadRef,
5 ThreadId,
6} from "@t3tools/contracts";
7import * as Option from "effect/Option";
8import { useEffect, useEffectEvent, useRef } from "react";
9
10import {
11 flushPendingFaviconsForThread,
12 recordFaviconForThread,
13 useFaviconProjectRefForThread,
14} from "~/browserFaviconStore";
15import { useBrowserPointerStore } from "~/browser/browserPointerStore";
16import { applyPreviewDesktopState, type DesktopPreviewOverlay } from "~/previewStateStore";
17import { previewEnvironment } from "~/state/preview";
18import { usePreparedConnection } from "~/state/session";
19import { useAtomCommand } from "~/state/use-atom-command";
20
21import { previewBridge } from "./previewBridge";
22
23function originOf(url: string): string | null {
24 try {
25 return new URL(url).origin;
26 } catch {
27 return null;
28 }
29}
30
31/** ElectronBrowserHost owns webview lifetime. */
32export function usePreviewBridge(input: {
33 threadRef: ScopedThreadRef;
34 tabId: string;
35 runtimeTabId: string;
36 serverDriven?: boolean;
37}): void {
38 const { threadRef, tabId, runtimeTabId, serverDriven = false } = input;
39 const clearBrowserPointer = useBrowserPointerStore((state) => state.clear);
40 const reportStatus = useAtomCommand(previewEnvironment.reportStatus, "preview status report");
41 const { environmentId, threadId } = threadRef;
42 const stableThreadRef: ScopedThreadRef = { environmentId, threadId };
43 const projectRef = useFaviconProjectRefForThread(stableThreadRef);
44 const preparedConnection = usePreparedConnection(stableThreadRef.environmentId);
45 const environmentHostname = Option.isSome(preparedConnection)
46 ? new URL(preparedConnection.value.httpBaseUrl).hostname
47 : undefined;
48
49 const lastReportedUrl = useRef<string | null>(null);
50 const lastReportedKind = useRef<DesktopPreviewTabState["navStatus"]["kind"] | null>(null);
51 const lastDesktopNavStatus = useRef<DesktopPreviewTabState["navStatus"] | null>(null);
52 const handleStateChange = useEffectEvent(
53 (changedTabId: string, state: DesktopPreviewTabState): void => {
54 if (changedTabId !== runtimeTabId) return;
55 if (shouldClearBrowserPointer(lastDesktopNavStatus.current, state.navStatus)) {
56 clearBrowserPointer(runtimeTabId);
57 }
58 lastDesktopNavStatus.current = state.navStatus;
59 applyPreviewDesktopState(stableThreadRef, tabId, projectDesktopState(state));
60 if (state.favicon) {
61 recordFaviconForThread(stableThreadRef, state.favicon, projectRef, environmentHostname);
62 }
63 const reported = buildReportInput({
64 threadId: stableThreadRef.threadId,
65 tabId,
66 state,
67 lastReportedUrl: lastReportedUrl.current,
68 lastReportedKind: lastReportedKind.current,
69 });
70 if (!reported || serverDriven) return;
71 lastReportedUrl.current = reported.lastReportedUrl;
72 lastReportedKind.current = reported.lastReportedKind;
73 void reportStatus({
74 environmentId: stableThreadRef.environmentId,
75 input: reported.input,
76 });
77 },
78 );
79 useEffect(() => {
80 if (!previewBridge || typeof window === "undefined") return;
81 lastReportedUrl.current = null;
82 lastReportedKind.current = null;
83 lastDesktopNavStatus.current = null;
84 return previewBridge.onStateChange(handleStateChange);
85 }, [
86 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A different tab or thread starts its status reports and pointer tracking from scratch.
87 runtimeTabId,
88 stableThreadRef,
89 tabId,
90 ]);
91 useEffect(() => {
92 if (!projectRef) return;
93 flushPendingFaviconsForThread(stableThreadRef, projectRef, environmentHostname);
94 }, [environmentHostname, projectRef, stableThreadRef]);
95}
96
97function shouldClearBrowserPointer(
98 previous: DesktopPreviewTabState["navStatus"] | null,
99 current: DesktopPreviewTabState["navStatus"],
100): boolean {
101 if (!previous) return false;
102 if (current.kind === "Loading" && previous.kind !== "Loading") return true;
103 if (current.kind === "Idle" || previous.kind === "Idle") return false;
104 return current.url !== previous.url;
105}
106
107export function projectDesktopState(state: DesktopPreviewTabState): DesktopPreviewOverlay {
108 const navOrigin = state.navStatus.kind === "Idle" ? null : originOf(state.navStatus.url);
109 return {
110 hasWebContents: state.webContentsId !== null,
111 canGoBack: state.canGoBack,
112 canGoForward: state.canGoForward,
113 loading: state.navStatus.kind === "Loading",
114 zoomFactor: state.zoomFactor,
115 pictureInPicture: state.pictureInPicture,
116 colorScheme: state.colorScheme,
117 audioMuted: state.audioMuted,
118 audible: state.audible,
119 controller: state.controller,
120 favicon: state.favicon && originOf(state.favicon.pageUrl) === navOrigin ? state.favicon : null,
121 };
122}
123
124function buildReportInput(args: {
125 readonly threadId: ThreadId;
126 readonly tabId: string;
127 readonly state: DesktopPreviewTabState;
128 readonly lastReportedUrl: string | null;
129 readonly lastReportedKind: DesktopPreviewTabState["navStatus"]["kind"] | null;
130}): {
131 readonly input: PreviewReportStatusInput;
132 readonly lastReportedUrl: string;
133 readonly lastReportedKind: DesktopPreviewTabState["navStatus"]["kind"];
134} | null {
135 const { threadId, tabId, state, lastReportedUrl, lastReportedKind } = args;
136 const status = state.navStatus;
137 if (status.kind === "Idle") return null;
138
139 const sameAsLast =
140 status.kind !== "LoadFailed" &&
141 status.kind === lastReportedKind &&
142 status.url === lastReportedUrl;
143 if (sameAsLast) return null;
144
145 const base = {
146 threadId,
147 tabId,
148 canGoBack: state.canGoBack,
149 canGoForward: state.canGoForward,
150 };
151 if (status.kind === "LoadFailed") {
152 return {
153 input: {
154 ...base,
155 navStatus: {
156 _tag: "LoadFailed",
157 url: status.url,
158 title: status.title,
159 code: status.code,
160 description: status.description,
161 },
162 },
163 lastReportedUrl: status.url,
164 lastReportedKind: "LoadFailed",
165 };
166 }
167 return {
168 input: {
169 ...base,
170 navStatus: { _tag: status.kind, url: status.url, title: status.title },
171 },
172 lastReportedUrl: status.url,
173 lastReportedKind: status.kind,
174 };
175}