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

BrowserDocumentFrame.tsx

475 lines17.6 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 FilePreviewScroll,
11 filePreviewRestoreScrollMessage,
12 isFilePreviewScrollRestored,
13 readFilePreviewScroll,
14 type HtmlRenderShortcut,
15 htmlRenderShortcutsMessage,
16 HTML_RENDER_CONTAIN_SCROLL_FRAGMENT,
17 htmlRenderThemeFragment,
18 htmlRenderThemeMessage,
19 htmlRenderResult,
20 readHtmlRenderContentHeight,
21 readHtmlRenderImageRequest,
22 readHtmlRenderKeyDown,
23 readHtmlRenderLinkRequest,
24} from "@t3tools/shared/htmlRender";
25import {
26 isMacPlatform,
27 matchesKeybindingShortcut,
28 normalizeEventKey,
29} from "@t3tools/shared/keybindings";
30import {
31 lazy,
32 type ReactNode,
33 Suspense,
34 useEffect,
35 useEffectEvent,
36 useLayoutEffect,
37 useRef,
38 useState,
39} from "react";
40import { isElectron } from "~/env";
41import { FileSurfaceLoading } from "./fileSurfaceChrome";
42import type { PdfViewState } from "./PdfViewer";
43​
44import { useOpenLink } from "~/browser/useOpenLink";
45import { ExpandedImageDialog } from "~/components/chat/ExpandedImageDialog";
46import type { ExpandedImagePreview } from "~/components/chat/ExpandedImagePreview";
47import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme";
48import { shortcutConflictKey } from "~/keybindings";
49import { useOpenIssueLink } from "~/lib/openIssueLink";
50import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink";
51import { readLocalApi } from "~/localApi";
52import { cn } from "~/lib/utils";
53import { primaryServerKeybindingsAtom, serverEnvironment } from "~/state/server";
54​
55/**
56 * The page reports the keys, and a page script can report any key it likes,
57 * so only commands that change what the reader sees are here, never one that
58 * changes a thread.
59 */
60const HTML_RENDER_SHORTCUT_COMMANDS: ReadonlySet<KeybindingCommand> = new Set([
61 "commandPalette.toggle",
62 "filePicker.toggle",
63 "projectSearch.toggle",
64 "chat.find",
65 "sidebar.toggle",
66 "rightPanel.toggle",
67 "rightPanel.toggleMaximized",
68 "threadPanel.toggle",
69 "terminal.toggle",
70 "preview.toggle",
71 "navigation.back",
72 "navigation.forward",
73 "thread.previous",
74 "thread.next",
75 ...THREAD_JUMP_KEYBINDING_COMMANDS,
76 ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
77]);
78​
79export const isPdfPreviewFile = (path: string): boolean => /\.pdf$/i.test(path);
80​
81const PdfViewer = lazy(() => import("./PdfViewer"));
82​
83// The document stays mounted while each revision gets a fresh PDF.js document.
84function PdfDocument(props: {
85 src: string;
86 title: string;
87 documentKey: string;
88 threadRef: ScopedThreadRef | undefined;
89 actions?: ReactNode;
90}) {
91 const [view, setView] = useState<PdfViewState>({ page: 0, offset: 0, zoom: null, left: 0 });
92 return (
93 <PdfDocumentRevision
94 key={props.documentKey}
95 src={props.src}
96 title={props.title}
97 positionKey={props.documentKey}
98 initialView={view}
99 onViewChange={setView}
100 threadRef={props.threadRef}
101 actions={props.actions}
102 />
103 );
105​
106// Keep signed URL renewals from reloading the same revision.
107function PdfDocumentRevision(props: {
108 src: string;
109 title: string;
110 positionKey: string;
111 initialView: PdfViewState;
112 onViewChange: (view: PdfViewState) => void;
113 threadRef: ScopedThreadRef | undefined;
114 actions?: ReactNode;
115}) {
116 const [src] = useState(props.src);
117 const openLink = useOpenLink(props.threadRef);
118 // The Electron shell does not enable PDF plugins. WebKit embeds on iOS
119 // expose only the first page, even when pdfViewerEnabled reports support.
120 const native =
121 !isElectron &&
122 navigator.pdfViewerEnabled &&
123 !/iPad|iPhone|iPod/.test(navigator.userAgent) &&
124 !(navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
125 return native ? (
126 // oxlint-disable-next-line react/iframe-missing-sandbox -- Chromium's PDF plugin requires an unsandboxed frame; src is an exact-file asset grant.
127 <iframe
128 src={`${src.split("#", 1)[0]}#navpanes=0&view=FitH`}
129 title={props.title}
130 className="block h-full min-h-0 w-full flex-1 border-0 bg-white"
131 />
132 ) : (
133 <Suspense fallback={<FileSurfaceLoading />}>
134 <PdfViewer
135 src={props.src}
136 title={props.title}
137 positionKey={props.positionKey}
138 initialView={props.initialView}
139 onViewChange={props.onViewChange}
140 onOpenLink={(url, event) => {
141 void openLink(url, { event }).catch((cause: unknown) => console.error(cause));
142 }}
143 actions={props.actions}
144 />
145 </Suspense>
146 );
148​
149/**
150 * HTML runs in a sandboxed frame with an opaque origin, so a page cannot reach
151 * the app's session or storage. PDFs use a native viewer or the lazy PDF.js fallback.
152 */
153export function BrowserDocumentFrame(props: {
154 readonly src: string;
155 readonly title: string;
156 readonly pdf: boolean;
157 readonly htmlRender?: boolean;
158 readonly threadRef?: ScopedThreadRef | undefined;
159 /** Stable resource identity and revision; defaults to src for callers that reload on URL changes. */
160 readonly documentKey?: string | undefined;
161 /** Resource identity without its revision, so PDF reloads can retain the reading position. */
162 readonly documentId?: string | undefined;
163 /** Toolbar actions for the in-app PDF viewer; Chromium's own viewer brings its own. */
164 readonly pdfActions?: ReactNode;
165}) {
166 const key = props.documentKey ?? props.src;
167 return props.pdf ? (
168 <PdfDocument
169 key={props.documentId ?? key}
170 documentKey={key}
171 src={props.src}
172 title={props.title}
173 threadRef={props.threadRef}
174 actions={props.pdfActions}
175 />
176 ) : props.htmlRender ? (
177 <HtmlRenderDocument
178 key={key}
179 src={props.src}
180 title={props.title}
181 threadRef={props.threadRef}
182 className="min-h-0 flex-1"
183 />
184 ) : (
185 <FileDocument
186 key={props.documentId ?? key}
187 documentKey={key}
188 src={props.src}
189 title={props.title}
190 />
191 );
193​
194interface FileDocumentRevision {
195 readonly key: string;
196 readonly src: string;
198​
199interface FileDocumentFrames {
200 readonly shown: FileDocumentRevision;
201 readonly next: FileDocumentRevision | null;
203​
204// Identity, not key, so a late load from a replaced frame cannot uncover a newer unloaded one.
205const showRevision =
206 (next: FileDocumentRevision) =>
207 (current: FileDocumentFrames): FileDocumentFrames =>
208 current.next === next ? { shown: next, next: null } : current;
209​
210// A page whose load never fires (a stalled subresource) must not pin the previous revision.
211const FILE_DOCUMENT_SWAP_TIMEOUT_MS = 5_000;
212​
213// URL renewals keep a revision's first URL, so they do not discard form input or scroll. A new
214// revision loads beneath the page on screen, takes its scroll position and replaces it once
215// painted, so no blank frame shows and the reader keeps their place.
216function FileDocument(props: {
217 readonly documentKey: string;
218 readonly src: string;
219 readonly title: string;
220}) {
221 const [frames, setFrames] = useState<FileDocumentFrames>(() => ({
222 shown: { key: props.documentKey, src: props.src },
223 next: null,
224 }));
225 if ((frames.next ?? frames.shown).key !== props.documentKey) {
226 setFrames({
227 shown: frames.shown,
228 next:
229 frames.shown.key === props.documentKey ? null : { key: props.documentKey, src: props.src },
230 });
231 }
232 const { next } = frames;
233 const shownFrame = useRef<HTMLIFrameElement>(null);
234 const nextFrame = useRef<HTMLIFrameElement>(null);
235 // The page reports its scroll position (see FILE_PREVIEW_SCROLL_SCRIPT); the next revision
236 // scrolls there before it is uncovered.
237 const scroll = useRef<FilePreviewScroll | null>(null);
238 // Two frames let the browser paint the incoming page before it is uncovered.
239 const reveal = (revision: FileDocumentRevision) =>
240 requestAnimationFrame(() => requestAnimationFrame(() => setFrames(showRevision(revision))));
241 const onFrameMessage = useEffectEvent((event: MessageEvent) => {
242 const position = readFilePreviewScroll(event.data);
243 if (position !== undefined) {
244 if (event.source === shownFrame.current?.contentWindow) scroll.current = position;
245 } else if (
246 next !== null &&
247 event.source === nextFrame.current?.contentWindow &&
248 isFilePreviewScrollRestored(event.data)
249 ) {
250 reveal(next);
251 }
252 });
253 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- listens for the frames' scroll reports
254 useEffect(() => {
255 const onMessage = (event: MessageEvent) => onFrameMessage(event);
256 window.addEventListener("message", onMessage);
257 return () => window.removeEventListener("message", onMessage);
258 }, []);
259 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- swaps in a revision whose load event never arrives
260 useEffect(() => {
261 if (next === null) return;
262 const timer = setTimeout(() => setFrames(showRevision(next)), FILE_DOCUMENT_SWAP_TIMEOUT_MS);
263 return () => clearTimeout(timer);
264 }, [next]);
265 // The shown frame stays last so it paints on top and is never moved, which would reload it.
266 return (
267 <div className="relative min-h-0 flex-1">
268 {[next, frames.shown].map((revision) =>
269 revision === null ? null : (
270 <iframe
271 key={revision.key}
272 ref={revision === next ? nextFrame : shownFrame}
273 src={revision.src}
274 title={props.title}
275 className="absolute inset-0 size-full border-0"
276 style={{ backgroundColor: "Canvas" }}
277 sandbox="allow-scripts allow-forms allow-popups allow-downloads"
278 inert={revision === next}
279 aria-hidden={revision === next ? true : undefined}
280 onLoad={
281 revision === next
282 ? (event) => {
283 if (scroll.current === null) {
284 reveal(revision);
285 return;
286 }
287 event.currentTarget.contentWindow?.postMessage(
288 filePreviewRestoreScrollMessage(scroll.current),
289 "*",
290 );
291 }
292 : undefined
293 }
294 />
295 ),
296 )}
297 </div>
298 );
300​
301/** Keep the initial URL while mounted; re-signing must not reload the page. */
302export function HtmlRenderDocument(props: {
303 readonly src: string;
304 readonly title: string;
305 readonly className?: string;
306 readonly threadRef?: ScopedThreadRef | undefined;
307 readonly onContentHeight?: (height: number) => void;
308 /** Keeps the page's scrollIntoView calls from scrolling the host, for frames inline in the chat. */
309 readonly containScroll?: boolean | undefined;
310 /** Reports fullscreen changes so virtualized rows can stay mounted. */
311 readonly onFullscreenChange?: ((fullscreen: boolean) => void) | undefined;
312}) {
313 const theme = useHtmlRenderTheme();
314 const frameRef = useRef<HTMLIFrameElement>(null);
315 const [src] = useState(
316 () =>
317 `${props.src.split("#", 1)[0]}${htmlRenderThemeFragment(theme)}${props.containScroll ? HTML_RENDER_CONTAIN_SCROLL_FRAGMENT : ""}`,
318 );
319 const [loaded, setLoaded] = useState(false);
320 const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
321 const postTheme = () => {
322 frameRef.current?.contentWindow?.postMessage(htmlRenderThemeMessage(theme), "*");
323 };
324 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- posts the current theme to the sandboxed iframe's window
325 useEffect(postTheme, [theme]);
326 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
327 const environmentKeybindings = useAtomValue(
328 serverEnvironment.configValueAtom(props.threadRef?.environmentId ?? null),
329 )?.keybindings;
330 // Replay only Cmd/Ctrl chords exclusive to allowed commands regardless of when; live resolution could
331 // otherwise type in the composer.
332 const mac = isMacPlatform(navigator.platform);
333 const resolve = (shortcut: KeybindingShortcut): HtmlRenderShortcut => ({
334 key: shortcut.key,
335 metaKey: shortcut.metaKey || (shortcut.modKey && mac),
336 ctrlKey: shortcut.ctrlKey || (shortcut.modKey && !mac),
337 shiftKey: shortcut.shiftKey,
338 altKey: shortcut.altKey,
339 });
340 const blocked = [...keybindings, ...(environmentKeybindings ?? [])]
341 .filter((binding) => !HTML_RENDER_SHORTCUT_COMMANDS.has(binding.command))
342 .map((binding) => resolve(binding.shortcut));
343 const shortcutsByKey = new Map<string, HtmlRenderShortcut>();
344 for (const { command, shortcut } of keybindings) {
345 if (
346 HTML_RENDER_SHORTCUT_COMMANDS.has(command) &&
347 (shortcut.metaKey || shortcut.ctrlKey || shortcut.modKey)
348 ) {
349 shortcutsByKey.set(shortcutConflictKey(shortcut), resolve(shortcut));
350 }
351 }
352 const shortcuts = [...shortcutsByKey.values()];
353 const postShortcuts = () => {
354 frameRef.current?.contentWindow?.postMessage(
355 htmlRenderShortcutsMessage(shortcuts, blocked),
356 "*",
357 );
358 };
359 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- posts allowed and blocked shortcuts to the sandboxed iframe's window
360 useEffect(postShortcuts, [blocked, shortcuts]);
361 // Pages can forge key/code pairs; reject pairs matching other bindings and require named keys to match the
362 // shortcut.
363 const isShortcut = useEffectEvent(
364 (key: NonNullable<ReturnType<typeof readHtmlRenderKeyDown>>) => {
365 const matches = (shortcut: HtmlRenderShortcut) =>
366 matchesKeybindingShortcut(key, { ...shortcut, modKey: false }, navigator.platform);
367 const allowed = shortcuts.filter(matches);
368 return (
369 allowed.length > 0 &&
370 !blocked.some(matches) &&
371 (key.key.length === 1 ||
372 key.key === "Dead" ||
373 allowed.some((shortcut) => shortcut.key === normalizeEventKey(key.key)))
374 );
375 },
376 );
377 const openChangeRequestLink = useOpenChangeRequestLink(props.threadRef);
378 const openIssueLink = useOpenIssueLink(props.threadRef);
379 const openLink = useOpenLink(props.threadRef);
380 const open = useEffectEvent((url: string, modifiers: { metaKey: boolean; ctrlKey: boolean }) => {
381 if (modifiers.metaKey || modifiers.ctrlKey) {
382 void readLocalApi()
383 ?.shell.openExternal(url)
384 .catch((cause: unknown) => console.error(cause));
385 return;
386 }
387 const event = {
388 ...modifiers,
389 preventDefault: () => undefined,
390 stopPropagation: () => undefined,
391 };
392 if (
393 props.threadRef !== undefined &&
394 (openChangeRequestLink(event, url, undefined, props.threadRef.environmentId) ||
395 openIssueLink(event, url, props.threadRef.environmentId))
396 ) {
397 return;
398 }
399 void openLink(url, { event: modifiers }).catch((cause: unknown) => console.error(cause));
400 });
401 const { onFullscreenChange } = props;
402 // 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
403 useEffect(() => {
404 if (expandedImage === null) return;
405 onFullscreenChange?.(true);
406 return () => onFullscreenChange?.(false);
407 }, [expandedImage, onFullscreenChange]);
408 // Links, keys and images require frame focus and recent reader activity: a page can take
409 // focus by script, so this blocks opens on load, though not a page that waits for the
410 // reader's next input.
411 const onFrameMessage = useEffectEvent((frame: HTMLIFrameElement, event: MessageEvent) => {
412 const height = readHtmlRenderContentHeight(event.data);
413 if (height !== undefined) {
414 props.onContentHeight?.(height);
415 return;
416 }
417 if (document.activeElement !== frame || navigator.userActivation?.isActive === false) return;
418 const linkRequest = readHtmlRenderLinkRequest(event.data);
419 if (linkRequest !== undefined) {
420 open(linkRequest.url, linkRequest);
421 frame.contentWindow?.postMessage(htmlRenderResult(linkRequest.id), "*");
422 return;
423 }
424 const key = readHtmlRenderKeyDown(event.data);
425 if (key !== undefined) {
426 if (isShortcut(key)) {
427 frame.dispatchEvent(
428 new KeyboardEvent("keydown", { ...key, bubbles: true, cancelable: true }),
429 );
430 }
431 return;
432 }
433 const imageRequest = readHtmlRenderImageRequest(event.data);
434 if (imageRequest !== undefined) {
435 setExpandedImage({ images: [...imageRequest.images], index: imageRequest.index });
436 }
437 });
438 // Attach at commit because a fast page may post its initial height before passive effects run.
439 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- attaches a window message listener for the iframe at commit, before its first height post
440 useLayoutEffect(() => {
441 const frame = frameRef.current;
442 if (frame === null) return;
443 const onMessage = (event: MessageEvent) => {
444 if (event.source === frame.contentWindow) onFrameMessage(frame, event);
445 };
446 window.addEventListener("message", onMessage);
447 return () => window.removeEventListener("message", onMessage);
448 }, []);
449 return (
450 <>
451 <iframe
452 ref={frameRef}
453 src={src}
454 title={props.title}
455 // Never allow-same-origin: the opaque origin keeps the page out of the app's session.
456 sandbox="allow-scripts allow-forms"
457 // Lets a page's video or image viewer take the screen.
458 allow="fullscreen"
459 loading="lazy"
460 onLoad={() => {
461 setLoaded(true);
462 // Covers a theme change that landed while the page was loading.
463 postTheme();
464 postShortcuts();
465 }}
466 // Match the blank document's scheme to avoid dark-mode white flashes, then follow the app after load.
467 className={cn("border-0 scheme-light", props.className)}
468 style={loaded ? { colorScheme: theme.appearance } : undefined}
469 />
470 {expandedImage !== null ? (
471 <ExpandedImageDialog preview={expandedImage} onClose={() => setExpandedImage(null)} />
472 ) : null}
473 </>
474 );