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

usePreviewBridge.ts

179 lines6.2 KB

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 }
30​
31/**
32 * Webview lifetime is owned by ElectronBrowserHost.
33 */
34export function usePreviewBridge(input: {
35 threadRef: ScopedThreadRef;
36 tabId: string;
37 runtimeTabId: string;
38 serverDriven?: boolean;
39}): void {
40 const { threadRef, tabId, runtimeTabId, serverDriven = false } = input;
41 const clearBrowserPointer = useBrowserPointerStore((state) => state.clear);
42 const reportStatus = useAtomCommand(previewEnvironment.reportStatus, "preview status report");
43 // Callers pass a fresh threadRef each render; rebuilding it from its ids keeps the ref
44 // stable for the effects.
45 const { environmentId, threadId } = threadRef;
46 const stableThreadRef: ScopedThreadRef = { environmentId, threadId };
47 const projectRef = useFaviconProjectRefForThread(stableThreadRef);
48 const preparedConnection = usePreparedConnection(stableThreadRef.environmentId);
49 const environmentHostname = Option.isSome(preparedConnection)
50 ? new URL(preparedConnection.value.httpBaseUrl).hostname
51 : undefined;
52​
53 const lastReportedUrl = useRef<string | null>(null);
54 const lastReportedKind = useRef<DesktopPreviewTabState["navStatus"]["kind"] | null>(null);
55 const lastDesktopNavStatus = useRef<DesktopPreviewTabState["navStatus"] | null>(null);
56 const handleStateChange = useEffectEvent(
57 (changedTabId: string, state: DesktopPreviewTabState): void => {
58 if (changedTabId !== runtimeTabId) return;
59 if (shouldClearBrowserPointer(lastDesktopNavStatus.current, state.navStatus)) {
60 clearBrowserPointer(runtimeTabId);
61 }
62 lastDesktopNavStatus.current = state.navStatus;
63 applyPreviewDesktopState(stableThreadRef, tabId, projectDesktopState(state));
64 if (state.favicon) {
65 recordFaviconForThread(stableThreadRef, state.favicon, projectRef, environmentHostname);
66 }
67 const reported = buildReportInput({
68 threadId: stableThreadRef.threadId,
69 tabId,
70 state,
71 lastReportedUrl: lastReportedUrl.current,
72 lastReportedKind: lastReportedKind.current,
73 });
74 if (!reported || serverDriven) return;
75 lastReportedUrl.current = reported.lastReportedUrl;
76 lastReportedKind.current = reported.lastReportedKind;
77 void reportStatus({
78 environmentId: stableThreadRef.environmentId,
79 input: reported.input,
80 });
81 },
82 );
83 useEffect(() => {
84 if (!previewBridge || typeof window === "undefined") return;
85 lastReportedUrl.current = null;
86 lastReportedKind.current = null;
87 lastDesktopNavStatus.current = null;
88 return previewBridge.onStateChange(handleStateChange);
89 }, [
90 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- A different tab or thread starts its status reports and pointer tracking from scratch.
91 runtimeTabId,
92 stableThreadRef,
93 tabId,
94 ]);
95 useEffect(() => {
96 if (!projectRef) return;
97 flushPendingFaviconsForThread(stableThreadRef, projectRef, environmentHostname);
98 }, [environmentHostname, projectRef, stableThreadRef]);
100​
101function shouldClearBrowserPointer(
102 previous: DesktopPreviewTabState["navStatus"] | null,
103 current: DesktopPreviewTabState["navStatus"],
104): boolean {
105 if (!previous) return false;
106 if (current.kind === "Loading" && previous.kind !== "Loading") return true;
107 if (current.kind === "Idle" || previous.kind === "Idle") return false;
108 return current.url !== previous.url;
110​
111export function projectDesktopState(state: DesktopPreviewTabState): DesktopPreviewOverlay {
112 const navOrigin = state.navStatus.kind === "Idle" ? null : originOf(state.navStatus.url);
113 return {
114 hasWebContents: state.webContentsId !== null,
115 canGoBack: state.canGoBack,
116 canGoForward: state.canGoForward,
117 loading: state.navStatus.kind === "Loading",
118 zoomFactor: state.zoomFactor,
119 pictureInPicture: state.pictureInPicture,
120 colorScheme: state.colorScheme,
121 audioMuted: state.audioMuted,
122 audible: state.audible,
123 controller: state.controller,
124 favicon: state.favicon && originOf(state.favicon.pageUrl) === navOrigin ? state.favicon : null,
125 };
127​
128function buildReportInput(args: {
129 readonly threadId: ThreadId;
130 readonly tabId: string;
131 readonly state: DesktopPreviewTabState;
132 readonly lastReportedUrl: string | null;
133 readonly lastReportedKind: DesktopPreviewTabState["navStatus"]["kind"] | null;
134}): {
135 readonly input: PreviewReportStatusInput;
136 readonly lastReportedUrl: string;
137 readonly lastReportedKind: DesktopPreviewTabState["navStatus"]["kind"];
138} | null {
139 const { threadId, tabId, state, lastReportedUrl, lastReportedKind } = args;
140 const status = state.navStatus;
141 if (status.kind === "Idle") return null;
142​
143 const sameAsLast =
144 status.kind !== "LoadFailed" &&
145 status.kind === lastReportedKind &&
146 status.url === lastReportedUrl;
147 if (sameAsLast) return null;
148​
149 const base = {
150 threadId,
151 tabId,
152 canGoBack: state.canGoBack,
153 canGoForward: state.canGoForward,
154 };
155 if (status.kind === "LoadFailed") {
156 return {
157 input: {
158 ...base,
159 navStatus: {
160 _tag: "LoadFailed",
161 url: status.url,
162 title: status.title,
163 code: status.code,
164 description: status.description,
165 },
166 },
167 lastReportedUrl: status.url,
168 lastReportedKind: "LoadFailed",
169 };
170 }
171 return {
172 input: {
173 ...base,
174 navStatus: { _tag: status.kind, url: status.url, title: status.title },
175 },
176 lastReportedUrl: status.url,
177 lastReportedKind: status.kind,
178 };