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

BrowserDocumentFrame.tsx

473 lines17.4 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 { useOpenChangeRequestLink } from "~/lib/openPullRequestLink";
50import { readLocalApi } from "~/localApi";
51import { cn } from "~/lib/utils";
52import { primaryServerKeybindingsAtom, serverEnvironment } from "~/state/server";
53​
54/**
55 * The page reports the keys, and a page script can report any key it likes,
56 * so only commands that change what the reader sees are here, never one that
57 * changes a thread.
58 */
59const HTML_RENDER_SHORTCUT_COMMANDS: ReadonlySet<KeybindingCommand> = new Set([
60 "commandPalette.toggle",
61 "filePicker.toggle",
62 "projectSearch.toggle",
63 "chat.find",
64 "sidebar.toggle",
65 "rightPanel.toggle",
66 "rightPanel.toggleMaximized",
67 "threadPanel.toggle",
68 "terminal.toggle",
69 "preview.toggle",
70 "navigation.back",
71 "navigation.forward",
72 "thread.previous",
73 "thread.next",
74 ...THREAD_JUMP_KEYBINDING_COMMANDS,
75 ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
76]);
77​
78export const isPdfPreviewFile = (path: string): boolean =>
79 /\.pdf$/i.test(path.split(/[?#]/, 1)[0] ?? "");
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={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 openLink = useOpenLink(props.threadRef);
379 const open = useEffectEvent((url: string, modifiers: { metaKey: boolean; ctrlKey: boolean }) => {
380 if (modifiers.metaKey || modifiers.ctrlKey) {
381 void readLocalApi()
382 ?.shell.openExternal(url)
383 .catch((cause: unknown) => console.error(cause));
384 return;
385 }
386 if (
387 props.threadRef !== undefined &&
388 openChangeRequestLink(
389 { ...modifiers, preventDefault: () => undefined, stopPropagation: () => undefined },
390 url,
391 undefined,
392 props.threadRef.environmentId,
393 )
394 ) {
395 return;
396 }
397 void openLink(url, { event: modifiers }).catch((cause: unknown) => console.error(cause));
398 });
399 const { onFullscreenChange } = props;
400 // 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
401 useEffect(() => {
402 if (expandedImage === null) return;
403 onFullscreenChange?.(true);
404 return () => onFullscreenChange?.(false);
405 }, [expandedImage, onFullscreenChange]);
406 // Links, keys and images require frame focus and recent reader activity: a page can take
407 // focus by script, so this blocks opens on load, though not a page that waits for the
408 // reader's next input.
409 const onFrameMessage = useEffectEvent((frame: HTMLIFrameElement, event: MessageEvent) => {
410 const height = readHtmlRenderContentHeight(event.data);
411 if (height !== undefined) {
412 props.onContentHeight?.(height);
413 return;
414 }
415 if (document.activeElement !== frame || navigator.userActivation?.isActive === false) return;
416 const linkRequest = readHtmlRenderLinkRequest(event.data);
417 if (linkRequest !== undefined) {
418 open(linkRequest.url, linkRequest);
419 frame.contentWindow?.postMessage(htmlRenderResult(linkRequest.id), "*");
420 return;
421 }
422 const key = readHtmlRenderKeyDown(event.data);
423 if (key !== undefined) {
424 if (isShortcut(key)) {
425 frame.dispatchEvent(
426 new KeyboardEvent("keydown", { ...key, bubbles: true, cancelable: true }),
427 );
428 }
429 return;
430 }
431 const imageRequest = readHtmlRenderImageRequest(event.data);
432 if (imageRequest !== undefined) {
433 setExpandedImage({ images: [...imageRequest.images], index: imageRequest.index });
434 }
435 });
436 // Attach at commit because a fast page may post its initial height before passive effects run.
437 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- attaches a window message listener for the iframe at commit, before its first height post
438 useLayoutEffect(() => {
439 const frame = frameRef.current;
440 if (frame === null) return;
441 const onMessage = (event: MessageEvent) => {
442 if (event.source === frame.contentWindow) onFrameMessage(frame, event);
443 };
444 window.addEventListener("message", onMessage);
445 return () => window.removeEventListener("message", onMessage);
446 }, []);
447 return (
448 <>
449 <iframe
450 ref={frameRef}
451 src={src}
452 title={props.title}
453 // Never allow-same-origin: the opaque origin keeps the page out of the app's session.
454 sandbox="allow-scripts allow-forms"
455 // Lets a page's video or image viewer take the screen.
456 allow="fullscreen"
457 loading="lazy"
458 onLoad={() => {
459 setLoaded(true);
460 // Covers a theme change that landed while the page was loading.
461 postTheme();
462 postShortcuts();
463 }}
464 // Match the blank document's scheme to avoid dark-mode white flashes, then follow the app after load.
465 className={cn("border-0 scheme-light", props.className)}
466 style={loaded ? { colorScheme: theme.appearance } : undefined}
467 />
468 {expandedImage !== null ? (
469 <ExpandedImageDialog preview={expandedImage} onClose={() => setExpandedImage(null)} />
470 ) : null}
471 </>
472 );