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

usePreviewBridge.ts

194 lines7.0 KB

1"use client";
2​
3import type {
4 DesktopPreviewTabState,
5 PreviewReportStatusInput,
6 ScopedThreadRef,
7 ThreadId,
8} from "@t3tools/contracts";
9import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment";
10import * as Option from "effect/Option";
11import { useEffect, useEffectEvent, useMemo, useRef } from "react";
12​
13import {
14 flushPendingFaviconsForThread,
15 recordFaviconForThread,
16 useFaviconProjectRefForThread,
17} from "~/browserFaviconStore";
18import { useBrowserPointerStore } from "~/browser/browserPointerStore";
19import { applyPreviewDesktopState, type DesktopPreviewOverlay } from "~/previewStateStore";
20import { previewEnvironment } from "~/state/preview";
21import { usePreparedConnection } from "~/state/session";
22import { useAtomCommand } from "~/state/use-atom-command";
23​
24import { previewBridge } from "./previewBridge";
25​
26function originOf(url: string): string | null {
27 try {
28 return new URL(url).origin;
29 } catch {
30 return null;
31 }
33​
34/**
35 * Mirrors low-latency desktop state into the store and reflects navigation
36 * events back to the server. Webview lifetime is owned by ElectronBrowserHost.
37 */
38export function usePreviewBridge(input: {
39 threadRef: ScopedThreadRef;
40 tabId: string;
41 runtimeTabId: string;
42}): void {
43 const { threadRef, tabId, runtimeTabId } = input;
44 const clearBrowserPointer = useBrowserPointerStore((state) => state.clear);
45 const reportStatus = useAtomCommand(previewEnvironment.reportStatus, "preview status report");
46 const bridge = previewBridge;
47 const threadKey = scopedThreadKey(threadRef);
48 const stableThreadRef = useMemo(() => {
49 const parsed = parseScopedThreadKey(threadKey);
50 if (!parsed) throw new Error(`Invalid scoped thread key: ${threadKey}`);
51 return parsed;
52 }, [threadKey]);
53 const projectRef = useFaviconProjectRefForThread(stableThreadRef);
54 const preparedConnection = usePreparedConnection(stableThreadRef.environmentId);
55 const environmentHostname = Option.isSome(preparedConnection)
56 ? new URL(preparedConnection.value.httpBaseUrl).hostname
57 : undefined;
58​
59 // One bridge subscription does both jobs (mirror state + forward to
60 // server) so the desktop bridge keeps a single listener entry per tab.
61 const lastReportedUrl = useRef<string | null>(null);
62 const lastReportedKind = useRef<DesktopPreviewTabState["navStatus"]["kind"] | null>(null);
63 const lastDesktopNavStatus = useRef<DesktopPreviewTabState["navStatus"] | null>(null);
64 const handleStateChange = useEffectEvent(
65 (changedTabId: string, state: DesktopPreviewTabState): void => {
66 if (changedTabId !== runtimeTabId) return;
67 if (shouldClearBrowserPointer(lastDesktopNavStatus.current, state.navStatus)) {
68 clearBrowserPointer(runtimeTabId);
69 }
70 lastDesktopNavStatus.current = state.navStatus;
71 applyPreviewDesktopState(stableThreadRef, tabId, projectDesktopState(state));
72 if (state.favicon) {
73 recordFaviconForThread(stableThreadRef, state.favicon, projectRef, environmentHostname);
74 }
75 const reported = buildReportInput({
76 threadId: stableThreadRef.threadId,
77 tabId,
78 state,
79 lastReportedUrl: lastReportedUrl.current,
80 lastReportedKind: lastReportedKind.current,
81 });
82 if (!reported) return;
83 lastReportedUrl.current = reported.lastReportedUrl;
84 lastReportedKind.current = reported.lastReportedKind;
85 void reportStatus({
86 environmentId: stableThreadRef.environmentId,
87 input: reported.input,
88 });
89 },
90 );
91 useEffect(() => {
92 if (!bridge || typeof window === "undefined") return;
93 lastReportedUrl.current = null;
94 lastReportedKind.current = null;
95 lastDesktopNavStatus.current = null;
96 return bridge.onStateChange(handleStateChange);
97 }, [bridge, runtimeTabId, stableThreadRef, tabId]);
98 useEffect(() => {
99 if (!projectRef) return;
100 flushPendingFaviconsForThread(stableThreadRef, projectRef, environmentHostname);
101 }, [environmentHostname, projectRef, stableThreadRef]);
103​
104function shouldClearBrowserPointer(
105 previous: DesktopPreviewTabState["navStatus"] | null,
106 current: DesktopPreviewTabState["navStatus"],
107): boolean {
108 if (!previous) return false;
109 if (current.kind === "Loading" && previous.kind !== "Loading") return true;
110 if (current.kind === "Idle" || previous.kind === "Idle") return false;
111 return current.url !== previous.url;
113​
114export function projectDesktopState(state: DesktopPreviewTabState): DesktopPreviewOverlay {
115 const navOrigin = state.navStatus.kind === "Idle" ? null : originOf(state.navStatus.url);
116 return {
117 hasWebContents: state.webContentsId !== null,
118 canGoBack: state.canGoBack,
119 canGoForward: state.canGoForward,
120 loading: state.navStatus.kind === "Loading",
121 zoomFactor: state.zoomFactor,
122 pictureInPicture: state.pictureInPicture,
123 colorScheme: state.colorScheme,
124 audioMuted: state.audioMuted,
125 audible: state.audible,
126 controller: state.controller,
127 favicon: state.favicon && originOf(state.favicon.pageUrl) === navOrigin ? state.favicon : null,
128 };
130​
131/**
132 * Decide whether a state change warrants an RPC to the server, and shape
133 * the report payload.
134 *
135 * - Idle never reports — the tab is post-close or pre-load and the server
136 * already knows the canonical state from `open` / `closed`.
137 * - We dedupe on (kind, url): consecutive Loading→Loading→Loading for the
138 * same URL collapses to a single RPC, ditto Success.
139 * - LoadFailed always reports (the server uses it to emit `failed`).
140 */
141function buildReportInput(args: {
142 readonly threadId: ThreadId;
143 readonly tabId: string;
144 readonly state: DesktopPreviewTabState;
145 readonly lastReportedUrl: string | null;
146 readonly lastReportedKind: DesktopPreviewTabState["navStatus"]["kind"] | null;
147}): {
148 readonly input: PreviewReportStatusInput;
149 readonly lastReportedUrl: string;
150 readonly lastReportedKind: DesktopPreviewTabState["navStatus"]["kind"];
151} | null {
152 const { threadId, tabId, state, lastReportedUrl, lastReportedKind } = args;
153 const status = state.navStatus;
154 if (status.kind === "Idle") return null;
155​
156 // Skip if we've already reported the same kind+url. LoadFailed always
157 // reports (rapid duplicate failures are unusual and worth surfacing).
158 const sameAsLast =
159 status.kind !== "LoadFailed" &&
160 status.kind === lastReportedKind &&
161 status.url === lastReportedUrl;
162 if (sameAsLast) return null;
163​
164 const base = {
165 threadId,
166 tabId,
167 canGoBack: state.canGoBack,
168 canGoForward: state.canGoForward,
169 };
170 if (status.kind === "LoadFailed") {
171 return {
172 input: {
173 ...base,
174 navStatus: {
175 _tag: "LoadFailed",
176 url: status.url,
177 title: status.title,
178 code: status.code,
179 description: status.description,
180 },
181 },
182 lastReportedUrl: status.url,
183 lastReportedKind: "LoadFailed",
184 };
185 }
186 return {
187 input: {
188 ...base,
189 navStatus: { _tag: status.kind, url: status.url, title: status.title },
190 },
191 lastReportedUrl: status.url,
192 lastReportedKind: status.kind,
193 };