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

usePreviewBridge.ts

181 lines6.2 KB

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