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

usePreviewBridge.ts

147 lines5.1 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: { threadRef: ScopedThreadRef; tabId: string }): void {
23 const { threadRef, tabId } = input;
24 const clearBrowserPointer = useBrowserPointerStore((state) => state.clear);
25 const reportStatus = useAtomCommand(previewEnvironment.reportStatus, "preview status report");
26 const bridge = previewBridge;
27​
28 // One bridge subscription does both jobs (mirror state + forward to
29 // server) so the desktop bridge keeps a single listener entry per tab.
30 const lastReportedUrl = useRef<string | null>(null);
31 const lastReportedKind = useRef<DesktopPreviewTabState["navStatus"]["kind"] | null>(null);
32 const lastDesktopNavStatus = useRef<DesktopPreviewTabState["navStatus"] | null>(null);
33 useEffect(() => {
34 if (!bridge || typeof window === "undefined") return;
35 lastReportedUrl.current = null;
36 lastReportedKind.current = null;
37 lastDesktopNavStatus.current = null;
38 const unsubscribe = bridge.onStateChange((changedTabId, state) => {
39 if (changedTabId !== tabId) return;
40 if (shouldClearBrowserPointer(lastDesktopNavStatus.current, state.navStatus)) {
41 clearBrowserPointer(tabId);
42 }
43 lastDesktopNavStatus.current = state.navStatus;
44 applyPreviewDesktopState(threadRef, tabId, projectDesktopState(state));
45 const reported = buildReportInput({
46 threadId: threadRef.threadId,
47 tabId,
48 state,
49 lastReportedUrl: lastReportedUrl.current,
50 lastReportedKind: lastReportedKind.current,
51 });
52 if (!reported) return;
53 lastReportedUrl.current = reported.lastReportedUrl;
54 lastReportedKind.current = reported.lastReportedKind;
55 void reportStatus({
56 environmentId: threadRef.environmentId,
57 input: reported.input,
58 });
59 });
60 return unsubscribe;
61 }, [bridge, clearBrowserPointer, reportStatus, tabId, threadRef]);
63​
64function shouldClearBrowserPointer(
65 previous: DesktopPreviewTabState["navStatus"] | null,
66 current: DesktopPreviewTabState["navStatus"],
67): boolean {
68 if (!previous) return false;
69 if (current.kind === "Loading" && previous.kind !== "Loading") return true;
70 if (current.kind === "Idle" || previous.kind === "Idle") return false;
71 return current.url !== previous.url;
73​
74function projectDesktopState(state: DesktopPreviewTabState): DesktopPreviewOverlay {
75 return {
76 canGoBack: state.canGoBack,
77 canGoForward: state.canGoForward,
78 loading: state.navStatus.kind === "Loading",
79 zoomFactor: state.zoomFactor,
80 controller: state.controller,
81 };
83​
84/**
85 * Decide whether a state change warrants an RPC to the server, and shape
86 * the report payload.
87 *
88 * - Idle never reports — the tab is post-close or pre-load and the server
89 * already knows the canonical state from `open` / `closed`.
90 * - We dedupe on (kind, url): consecutive Loading→Loading→Loading for the
91 * same URL collapses to a single RPC, ditto Success.
92 * - LoadFailed always reports (the server uses it to emit `failed`).
93 */
94function buildReportInput(args: {
95 readonly threadId: ThreadId;
96 readonly tabId: string;
97 readonly state: DesktopPreviewTabState;
98 readonly lastReportedUrl: string | null;
99 readonly lastReportedKind: DesktopPreviewTabState["navStatus"]["kind"] | null;
100}): {
101 readonly input: PreviewReportStatusInput;
102 readonly lastReportedUrl: string;
103 readonly lastReportedKind: DesktopPreviewTabState["navStatus"]["kind"];
104} | null {
105 const { threadId, tabId, state, lastReportedUrl, lastReportedKind } = args;
106 const status = state.navStatus;
107 if (status.kind === "Idle") return null;
108​
109 // Skip if we've already reported the same kind+url. LoadFailed always
110 // reports (rapid duplicate failures are unusual and worth surfacing).
111 const sameAsLast =
112 status.kind !== "LoadFailed" &&
113 status.kind === lastReportedKind &&
114 status.url === lastReportedUrl;
115 if (sameAsLast) return null;
116​
117 const base = {
118 threadId,
119 tabId,
120 canGoBack: state.canGoBack,
121 canGoForward: state.canGoForward,
122 };
123 if (status.kind === "LoadFailed") {
124 return {
125 input: {
126 ...base,
127 navStatus: {
128 _tag: "LoadFailed",
129 url: status.url,
130 title: status.title,
131 code: status.code,
132 description: status.description,
133 },
134 },
135 lastReportedUrl: status.url,
136 lastReportedKind: "LoadFailed",
137 };
138 }
139 return {
140 input: {
141 ...base,
142 navStatus: { _tag: status.kind, url: status.url, title: status.title },
143 },
144 lastReportedUrl: status.url,
145 lastReportedKind: status.kind,
146 };