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

usePreviewBridge.ts

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