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

usePreviewBridge.ts

154 lines5.3 KB

1"use client";
2​
3import type {
4 DesktopPreviewTabState,
5 PreviewReportStatusInput,
6 ScopedThreadRef,
7 ThreadId,
8} from "@t3tools/contracts";
9import { useEffect, useRef } from "react";
10​
11import { useBrowserPointerStore } from "~/browser/browserPointerStore";
12import { applyPreviewDesktopState, type DesktopPreviewOverlay } from "~/previewStateStore";
13import { previewEnvironment } from "~/state/preview";
14import { useAtomCommand } from "~/state/use-atom-command";
15​
16import { previewBridge } from "./previewBridge";
17​
18/**
19 * Mirrors low-latency desktop state into the store and reflects navigation
20 * events back to the server. Webview lifetime is owned by ElectronBrowserHost.
21 */
22export function usePreviewBridge(input: {
23 threadRef: ScopedThreadRef;
24 tabId: string;
25 runtimeTabId: string;
26}): void {
27 const { threadRef, tabId, runtimeTabId } = input;
28 const clearBrowserPointer = useBrowserPointerStore((state) => state.clear);
29 const reportStatus = useAtomCommand(previewEnvironment.reportStatus, "preview status report");
30 const bridge = previewBridge;
31​
32 // One bridge subscription does both jobs (mirror state + forward to
33 // server) so the desktop bridge keeps a single listener entry per tab.
34 const lastReportedUrl = useRef<string | null>(null);
35 const lastReportedKind = useRef<DesktopPreviewTabState["navStatus"]["kind"] | null>(null);
36 const lastDesktopNavStatus = useRef<DesktopPreviewTabState["navStatus"] | null>(null);
37 useEffect(() => {
38 if (!bridge || typeof window === "undefined") return;
39 lastReportedUrl.current = null;
40 lastReportedKind.current = null;
41 lastDesktopNavStatus.current = null;
42 const unsubscribe = bridge.onStateChange((changedTabId, state) => {
43 if (changedTabId !== runtimeTabId) return;
44 if (shouldClearBrowserPointer(lastDesktopNavStatus.current, state.navStatus)) {
45 clearBrowserPointer(runtimeTabId);
46 }
47 lastDesktopNavStatus.current = state.navStatus;
48 applyPreviewDesktopState(threadRef, tabId, projectDesktopState(state));
49 const reported = buildReportInput({
50 threadId: threadRef.threadId,
51 tabId,
52 state,
53 lastReportedUrl: lastReportedUrl.current,
54 lastReportedKind: lastReportedKind.current,
55 });
56 if (!reported) return;
57 lastReportedUrl.current = reported.lastReportedUrl;
58 lastReportedKind.current = reported.lastReportedKind;
59 void reportStatus({
60 environmentId: threadRef.environmentId,
61 input: reported.input,
62 });
63 });
64 return unsubscribe;
65 }, [bridge, clearBrowserPointer, reportStatus, runtimeTabId, tabId, threadRef]);
67​
68function shouldClearBrowserPointer(
69 previous: DesktopPreviewTabState["navStatus"] | null,
70 current: DesktopPreviewTabState["navStatus"],
71): boolean {
72 if (!previous) return false;
73 if (current.kind === "Loading" && previous.kind !== "Loading") return true;
74 if (current.kind === "Idle" || previous.kind === "Idle") return false;
75 return current.url !== previous.url;
77​
78function projectDesktopState(state: DesktopPreviewTabState): DesktopPreviewOverlay {
79 return {
80 hasWebContents: state.webContentsId !== null,
81 canGoBack: state.canGoBack,
82 canGoForward: state.canGoForward,
83 loading: state.navStatus.kind === "Loading",
84 zoomFactor: state.zoomFactor,
85 pictureInPicture: state.pictureInPicture,
86 colorScheme: state.colorScheme,
87 controller: state.controller,
88 };
90​
91/**
92 * Decide whether a state change warrants an RPC to the server, and shape
93 * the report payload.
94 *
95 * - Idle never reports — the tab is post-close or pre-load and the server
96 * already knows the canonical state from `open` / `closed`.
97 * - We dedupe on (kind, url): consecutive Loading→Loading→Loading for the
98 * same URL collapses to a single RPC, ditto Success.
99 * - LoadFailed always reports (the server uses it to emit `failed`).
100 */
101function buildReportInput(args: {
102 readonly threadId: ThreadId;
103 readonly tabId: string;
104 readonly state: DesktopPreviewTabState;
105 readonly lastReportedUrl: string | null;
106 readonly lastReportedKind: DesktopPreviewTabState["navStatus"]["kind"] | null;
107}): {
108 readonly input: PreviewReportStatusInput;
109 readonly lastReportedUrl: string;
110 readonly lastReportedKind: DesktopPreviewTabState["navStatus"]["kind"];
111} | null {
112 const { threadId, tabId, state, lastReportedUrl, lastReportedKind } = args;
113 const status = state.navStatus;
114 if (status.kind === "Idle") return null;
115​
116 // Skip if we've already reported the same kind+url. LoadFailed always
117 // reports (rapid duplicate failures are unusual and worth surfacing).
118 const sameAsLast =
119 status.kind !== "LoadFailed" &&
120 status.kind === lastReportedKind &&
121 status.url === lastReportedUrl;
122 if (sameAsLast) return null;
123​
124 const base = {
125 threadId,
126 tabId,
127 canGoBack: state.canGoBack,
128 canGoForward: state.canGoForward,
129 };
130 if (status.kind === "LoadFailed") {
131 return {
132 input: {
133 ...base,
134 navStatus: {
135 _tag: "LoadFailed",
136 url: status.url,
137 title: status.title,
138 code: status.code,
139 description: status.description,
140 },
141 },
142 lastReportedUrl: status.url,
143 lastReportedKind: "LoadFailed",
144 };
145 }
146 return {
147 input: {
148 ...base,
149 navStatus: { _tag: status.kind, url: status.url, title: status.title },
150 },
151 lastReportedUrl: status.url,
152 lastReportedKind: status.kind,
153 };