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

BrowserDocumentFrame.tsx

358 lines13.3 KB

1import { useAtomValue } from "@effect/atom-react";
2import {
3 type KeybindingCommand,
4 type KeybindingShortcut,
5 MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
6 type ScopedThreadRef,
7 THREAD_JUMP_KEYBINDING_COMMANDS,
8} from "@t3tools/contracts";
9import {
10 type HtmlRenderShortcut,
11 htmlRenderShortcutsMessage,
12 htmlRenderThemeFragment,
13 htmlRenderThemeMessage,
14 htmlRenderResult,
15 readHtmlRenderContentHeight,
16 readHtmlRenderImageRequest,
17 readHtmlRenderKeyDown,
18 readHtmlRenderLinkRequest,
19} from "@t3tools/shared/htmlRender";
20import {
21 isMacPlatform,
22 matchesKeybindingShortcut,
23 normalizeEventKey,
24} from "@t3tools/shared/keybindings";
25import {
26 lazy,
27 Suspense,
28 useEffect,
29 useEffectEvent,
30 useLayoutEffect,
31 useRef,
32 useState,
33} from "react";
34import { isElectron } from "~/env";
35import { FileSurfaceLoading } from "./fileSurfaceChrome";
36import type { PdfViewState } from "./PdfViewer";
37​
38import { useOpenLink } from "~/browser/useOpenLink";
39import { ExpandedImageDialog } from "~/components/chat/ExpandedImageDialog";
40import type { ExpandedImagePreview } from "~/components/chat/ExpandedImagePreview";
41import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme";
42import { shortcutConflictKey } from "~/keybindings";
43import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink";
44import { readLocalApi } from "~/localApi";
45import { cn } from "~/lib/utils";
46import { primaryServerKeybindingsAtom, serverEnvironment } from "~/state/server";
47​
48/**
49 * The page reports the keys, and a page script can report any key it likes,
50 * so only commands that change what the reader sees are here, never one that
51 * changes a thread.
52 */
53const HTML_RENDER_SHORTCUT_COMMANDS: ReadonlySet<KeybindingCommand> = new Set([
54 "commandPalette.toggle",
55 "filePicker.toggle",
56 "projectSearch.toggle",
57 "chat.find",
58 "sidebar.toggle",
59 "rightPanel.toggle",
60 "rightPanel.toggleMaximized",
61 "threadPanel.toggle",
62 "terminal.toggle",
63 "preview.toggle",
64 "navigation.back",
65 "navigation.forward",
66 "thread.previous",
67 "thread.next",
68 ...THREAD_JUMP_KEYBINDING_COMMANDS,
69 ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
70]);
71​
72export const isPdfPreviewFile = (path: string): boolean =>
73 /\.pdf$/i.test(path.split(/[?#]/, 1)[0] ?? "");
74​
75const PdfViewer = lazy(() => import("./PdfViewer"));
76​
77// The document stays mounted while each revision gets a fresh PDF.js document.
78function PdfDocument(props: { src: string; title: string; documentKey: string }) {
79 const [view, setView] = useState<PdfViewState>({ page: 0, offset: 0, zoom: null, left: 0 });
80 return (
81 <PdfDocumentRevision
82 key={props.documentKey}
83 src={props.src}
84 title={props.title}
85 initialView={view}
86 onViewChange={setView}
87 />
88 );
90​
91// Keep signed URL renewals from reloading the same revision.
92function PdfDocumentRevision(props: {
93 src: string;
94 title: string;
95 initialView: PdfViewState;
96 onViewChange: (view: PdfViewState) => void;
97}) {
98 const [src] = useState(props.src);
99 // The Electron shell does not enable PDF plugins. WebKit embeds on iOS
100 // expose only the first page, even when pdfViewerEnabled reports support.
101 const native =
102 !isElectron &&
103 navigator.pdfViewerEnabled &&
104 !/iPad|iPhone|iPod/.test(navigator.userAgent) &&
105 !(navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
106 return native ? (
107 // oxlint-disable-next-line react/iframe-missing-sandbox -- Chromium's PDF plugin requires an unsandboxed frame; src is an exact-file asset grant.
108 <iframe
109 src={`${src.split("#", 1)[0]}#navpanes=0&view=FitH`}
110 title={props.title}
111 className="block h-full min-h-0 w-full flex-1 border-0 bg-white"
112 />
113 ) : (
114 <Suspense fallback={<FileSurfaceLoading />}>
115 <PdfViewer
116 src={src}
117 title={props.title}
118 initialView={props.initialView}
119 onViewChange={props.onViewChange}
120 />
121 </Suspense>
122 );
124​
125/**
126 * HTML runs in a sandboxed frame with an opaque origin, so a page cannot reach
127 * the app's session or storage. PDFs use a native viewer or the lazy PDF.js fallback.
128 */
129export function BrowserDocumentFrame(props: {
130 readonly src: string;
131 readonly title: string;
132 readonly pdf: boolean;
133 readonly htmlRender?: boolean;
134 readonly threadRef?: ScopedThreadRef | undefined;
135 /** Stable resource identity and revision; defaults to src for callers that reload on URL changes. */
136 readonly documentKey?: string | undefined;
137 /** Resource identity without its revision, so PDF reloads can retain the reading position. */
138 readonly documentId?: string | undefined;
139}) {
140 const key = props.documentKey ?? props.src;
141 return props.pdf ? (
142 <PdfDocument
143 key={props.documentId ?? key}
144 documentKey={key}
145 src={props.src}
146 title={props.title}
147 />
148 ) : props.htmlRender ? (
149 <HtmlRenderDocument
150 key={key}
151 src={props.src}
152 title={props.title}
153 threadRef={props.threadRef}
154 className="min-h-0 flex-1"
155 />
156 ) : (
157 <FileDocument key={key} src={props.src} title={props.title} />
158 );
160​
161// URL renewals must not discard form input or scroll; a new key mounts a fresh document.
162function FileDocument(props: { readonly src: string; readonly title: string }) {
163 const [src] = useState(props.src);
164 return (
165 <iframe
166 src={src}
167 title={props.title}
168 className="min-h-0 flex-1 border-0 bg-white"
169 sandbox="allow-scripts allow-forms allow-popups allow-downloads"
170 />
171 );
173​
174/** Keep the initial URL while mounted; re-signing must not reload the page. */
175export function HtmlRenderDocument(props: {
176 readonly src: string;
177 readonly title: string;
178 readonly className?: string;
179 readonly threadRef?: ScopedThreadRef | undefined;
180 readonly onContentHeight?: (height: number) => void;
181 /** Reports fullscreen changes so virtualized rows can stay mounted. */
182 readonly onFullscreenChange?: ((fullscreen: boolean) => void) | undefined;
183 /** Called when the page has loaded. */
184 readonly onLoad?: () => void;
185 readonly selectionBridge?: boolean;
186}) {
187 const theme = useHtmlRenderTheme();
188 const frameRef = useRef<HTMLIFrameElement>(null);
189 const [src] = useState(() => {
190 const url = new URL(props.src, window.location.href);
191 if (props.selectionBridge && (url.protocol === "http:" || url.protocol === "https:")) {
192 url.searchParams.set("t3-html-selection", "1");
193 }
194 return `${url.href.split("#", 1)[0]}${htmlRenderThemeFragment(theme)}`;
195 });
196 const [loaded, setLoaded] = useState(false);
197 const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
198 const postTheme = () => {
199 frameRef.current?.contentWindow?.postMessage(htmlRenderThemeMessage(theme), "*");
200 };
201 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- posts the current theme to the sandboxed iframe's window
202 useEffect(postTheme, [theme]);
203 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
204 const environmentKeybindings = useAtomValue(
205 serverEnvironment.configValueAtom(props.threadRef?.environmentId ?? null),
206 )?.keybindings;
207 // Replay only Cmd/Ctrl chords exclusive to allowed commands regardless of when; live resolution could
208 // otherwise type in the composer.
209 const mac = isMacPlatform(navigator.platform);
210 const resolve = (shortcut: KeybindingShortcut): HtmlRenderShortcut => ({
211 key: shortcut.key,
212 metaKey: shortcut.metaKey || (shortcut.modKey && mac),
213 ctrlKey: shortcut.ctrlKey || (shortcut.modKey && !mac),
214 shiftKey: shortcut.shiftKey,
215 altKey: shortcut.altKey,
216 });
217 const blocked = [...keybindings, ...(environmentKeybindings ?? [])]
218 .filter((binding) => !HTML_RENDER_SHORTCUT_COMMANDS.has(binding.command))
219 .map((binding) => resolve(binding.shortcut));
220 const shortcutsByKey = new Map<string, HtmlRenderShortcut>();
221 for (const { command, shortcut } of keybindings) {
222 if (
223 HTML_RENDER_SHORTCUT_COMMANDS.has(command) &&
224 (shortcut.metaKey || shortcut.ctrlKey || shortcut.modKey)
225 ) {
226 shortcutsByKey.set(shortcutConflictKey(shortcut), resolve(shortcut));
227 }
228 }
229 const shortcuts = [...shortcutsByKey.values()];
230 const postShortcuts = () => {
231 frameRef.current?.contentWindow?.postMessage(
232 htmlRenderShortcutsMessage(shortcuts, blocked),
233 "*",
234 );
235 };
236 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- posts allowed and blocked shortcuts to the sandboxed iframe's window
237 useEffect(postShortcuts, [blocked, shortcuts]);
238 // Pages can forge key/code pairs; reject pairs matching other bindings and require named keys to match the
239 // shortcut.
240 const isShortcut = useEffectEvent(
241 (key: NonNullable<ReturnType<typeof readHtmlRenderKeyDown>>) => {
242 const matches = (shortcut: HtmlRenderShortcut) =>
243 matchesKeybindingShortcut(key, { ...shortcut, modKey: false }, navigator.platform);
244 const allowed = shortcuts.filter(matches);
245 return (
246 allowed.length > 0 &&
247 !blocked.some(matches) &&
248 (key.key.length === 1 ||
249 key.key === "Dead" ||
250 allowed.some((shortcut) => shortcut.key === normalizeEventKey(key.key)))
251 );
252 },
253 );
254 const openChangeRequestLink = useOpenChangeRequestLink(props.threadRef);
255 const openLink = useOpenLink(props.threadRef);
256 const open = useEffectEvent((url: string, modifiers: { metaKey: boolean; ctrlKey: boolean }) => {
257 if (modifiers.metaKey || modifiers.ctrlKey) {
258 void readLocalApi()
259 ?.shell.openExternal(url)
260 .catch((cause: unknown) => console.error(cause));
261 return;
262 }
263 if (
264 props.threadRef !== undefined &&
265 openChangeRequestLink(
266 { ...modifiers, preventDefault: () => undefined, stopPropagation: () => undefined },
267 url,
268 undefined,
269 props.threadRef.environmentId,
270 )
271 ) {
272 return;
273 }
274 void openLink(url, { event: modifiers }).catch((cause: unknown) => console.error(cause));
275 });
276 const { onFullscreenChange } = props;
277 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports fullscreen to the parent while the image viewer is open, and clears it on unmount
278 useEffect(() => {
279 if (expandedImage === null) return;
280 onFullscreenChange?.(true);
281 return () => onFullscreenChange?.(false);
282 }, [expandedImage, onFullscreenChange]);
283 // Links, keys and images require frame focus and recent reader activity: a page can take
284 // focus by script, so this blocks opens on load, though not a page that waits for the
285 // reader's next input.
286 const onFrameMessage = useEffectEvent((frame: HTMLIFrameElement, event: MessageEvent) => {
287 const height = readHtmlRenderContentHeight(event.data);
288 if (height !== undefined) {
289 props.onContentHeight?.(height);
290 return;
291 }
292 if (document.activeElement !== frame || navigator.userActivation?.isActive === false) return;
293 const linkRequest = readHtmlRenderLinkRequest(event.data);
294 if (linkRequest !== undefined) {
295 open(linkRequest.url, linkRequest);
296 frame.contentWindow?.postMessage(htmlRenderResult(linkRequest.id), "*");
297 return;
298 }
299 const key = readHtmlRenderKeyDown(event.data);
300 if (key !== undefined) {
301 if (isShortcut(key)) {
302 frame.dispatchEvent(
303 new KeyboardEvent("keydown", { ...key, bubbles: true, cancelable: true }),
304 );
305 }
306 return;
307 }
308 const imageRequest = readHtmlRenderImageRequest(event.data);
309 if (imageRequest !== undefined) {
310 setExpandedImage({ images: [{ src: imageRequest.src, name: imageRequest.name }], index: 0 });
311 }
312 });
313 // Attach at commit because a fast page may post its initial height before passive effects run.
314 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- attaches a window message listener for the iframe at commit, before its first height post
315 useLayoutEffect(() => {
316 const frame = frameRef.current;
317 if (frame === null) return;
318 const onMessage = (event: MessageEvent) => {
319 if (event.source === frame.contentWindow) onFrameMessage(frame, event);
320 };
321 window.addEventListener("message", onMessage);
322 return () => window.removeEventListener("message", onMessage);
323 }, []);
324 return (
325 <>
326 <iframe
327 ref={frameRef}
328 src={src}
329 data-html-selection-bridge={props.selectionBridge || undefined}
330 title={props.title}
331 // Never allow-same-origin: the opaque origin keeps the page out of the app's session.
332 sandbox="allow-scripts allow-forms"
333 // Lets a page's video or image viewer take the screen.
334 allow="fullscreen"
335 loading={props.selectionBridge ? "eager" : "lazy"}
336 onLoad={() => {
337 setLoaded(true);
338 // Covers a theme change that landed while the page was loading.
339 postTheme();
340 postShortcuts();
341 props.onLoad?.();
342 if (props.selectionBridge) {
343 frameRef.current?.setAttribute("data-html-selection-ready", "true");
344 frameRef.current?.dispatchEvent(
345 new Event("t3-html-selection-ready", { bubbles: true }),
346 );
347 }
348 }}
349 // Match the blank document's scheme to avoid dark-mode white flashes, then follow the app after load.
350 className={cn("border-0 scheme-light", props.className)}
351 style={loaded ? { colorScheme: theme.appearance } : undefined}
352 />
353 {expandedImage !== null ? (
354 <ExpandedImageDialog preview={expandedImage} onClose={() => setExpandedImage(null)} />
355 ) : null}
356 </>
357 );