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