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 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 { useEffect, useEffectEvent, useLayoutEffect, useMemo, useRef, useState } from "react";
26
27import { useOpenLink } from "~/browser/useOpenLink";
28import { ExpandedImageDialog } from "~/components/chat/ExpandedImageDialog";
29import type { ExpandedImagePreview } from "~/components/chat/ExpandedImagePreview";
30import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme";
31import { shortcutConflictKey } from "~/keybindings";
32import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink";
33import { readLocalApi } from "~/localApi";
34import { cn } from "~/lib/utils";
35import { primaryServerKeybindingsAtom, serverEnvironment } from "~/state/server";
36
37const PDF_VIEWER_FRAGMENT = "#toolbar=0&view=FitH";
38
39/**
40 * The page reports the keys, and a page script can report any key it likes,
41 * so only commands that change what the reader sees are here, never one that
42 * changes a thread.
43 */
44const HTML_RENDER_SHORTCUT_COMMANDS: ReadonlySet<KeybindingCommand> = new Set([
45 "commandPalette.toggle",
46 "filePicker.toggle",
47 "projectSearch.toggle",
48 "chat.find",
49 "sidebar.toggle",
50 "rightPanel.toggle",
51 "rightPanel.toggleMaximized",
52 "threadPanel.toggle",
53 "terminal.toggle",
54 "preview.toggle",
55 "navigation.back",
56 "navigation.forward",
57 "thread.previous",
58 "thread.next",
59 ...THREAD_JUMP_KEYBINDING_COMMANDS,
60 ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
61]);
62
63export const isPdfPreviewFile = (path: string): boolean =>
64 /\.pdf$/i.test(path.split(/[?#]/, 1)[0] ?? "");
65
66/**
67 * HTML runs in a sandboxed frame with an opaque origin, so a page cannot reach
68 * the app's session or storage. The built-in PDF viewer needs an unsandboxed
69 * frame; a PDF runs no scripts.
70 */
71export function BrowserDocumentFrame(props: {
72 readonly src: string;
73 readonly title: string;
74 readonly pdf: boolean;
75 readonly htmlRender?: boolean;
76 readonly threadRef?: ScopedThreadRef | undefined;
77}) {
78 const className = "min-h-0 flex-1 border-0 bg-white";
79 return props.pdf ? (
80 // oxlint-disable-next-line react/iframe-missing-sandbox -- the built-in PDF viewer needs an unsandboxed frame.
81 <iframe
82 key={props.src}
83 src={`${props.src}${PDF_VIEWER_FRAGMENT}`}
84 title={props.title}
85 className={className}
86 />
87 ) : props.htmlRender ? (
88 <HtmlRenderDocument
89 key={props.src}
90 src={props.src}
91 title={props.title}
92 threadRef={props.threadRef}
93 className="min-h-0 flex-1"
94 />
95 ) : (
96 <iframe
97 key={props.src}
98 src={props.src}
99 title={props.title}
100 className={className}
101 sandbox="allow-scripts allow-forms allow-popups allow-downloads"
102 />
103 );
104}
105
106/**
107 * The first URL is kept for the frame's lifetime: signed asset URLs re-mint
108 * while it stays mounted, and a new src would reload the page.
109 */
110export function HtmlRenderDocument(props: {
111 readonly src: string;
112 readonly title: string;
113 readonly className?: string;
114 readonly threadRef?: ScopedThreadRef | undefined;
115 readonly onContentHeight?: (height: number) => void;
116 /** Reports the image viewer opening and closing, so a virtualized row can stay mounted. */
117 readonly onFullscreenChange?: ((fullscreen: boolean) => void) | undefined;
118 /** Called when the page has loaded. */
119 readonly onLoad?: () => void;
120}) {
121 const theme = useHtmlRenderTheme();
122 const frameRef = useRef<HTMLIFrameElement>(null);
123 const [src] = useState(() => `${props.src.split("#", 1)[0]}${htmlRenderThemeFragment(theme)}`);
124 const [loaded, setLoaded] = useState(false);
125 const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
126 const postTheme = () => {
127 frameRef.current?.contentWindow?.postMessage(htmlRenderThemeMessage(theme), "*");
128 };
129 useEffect(postTheme, [theme]);
130 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
131 const environmentKeybindings = useAtomValue(
132 serverEnvironment.configValueAtom(props.threadRef?.environmentId ?? null),
133 )?.keybindings;
134 // The app resolves a replayed key in its live context, so every allowed
135 // binding counts whatever its `when`, and a key that any binding gives to
136 // another command stays with the page. Only Cmd/Ctrl chords: a printable key
137 // would type into the composer instead.
138 const { shortcuts, blocked } = useMemo(() => {
139 const mac = isMacPlatform(navigator.platform);
140 const resolve = (shortcut: KeybindingShortcut): HtmlRenderShortcut => ({
141 key: shortcut.key,
142 metaKey: shortcut.metaKey || (shortcut.modKey && mac),
143 ctrlKey: shortcut.ctrlKey || (shortcut.modKey && !mac),
144 shiftKey: shortcut.shiftKey,
145 altKey: shortcut.altKey,
146 });
147 const blocked = [...keybindings, ...(environmentKeybindings ?? [])]
148 .filter((binding) => !HTML_RENDER_SHORTCUT_COMMANDS.has(binding.command))
149 .map((binding) => resolve(binding.shortcut));
150 const shortcuts = new Map<string, HtmlRenderShortcut>();
151 for (const { command, shortcut } of keybindings) {
152 if (
153 HTML_RENDER_SHORTCUT_COMMANDS.has(command) &&
154 (shortcut.metaKey || shortcut.ctrlKey || shortcut.modKey)
155 ) {
156 shortcuts.set(shortcutConflictKey(shortcut), resolve(shortcut));
157 }
158 }
159 return { shortcuts: [...shortcuts.values()], blocked };
160 }, [environmentKeybindings, keybindings]);
161 const postShortcuts = () => {
162 frameRef.current?.contentWindow?.postMessage(
163 htmlRenderShortcutsMessage(shortcuts, blocked),
164 "*",
165 );
166 };
167 useEffect(postShortcuts, [blocked, shortcuts]);
168 // The page reports the key and code, and a page script can report any pair,
169 // so a key that could match another command's binding is never replayed. A
170 // named key (Backspace, Enter) must be the shortcut's own, since some app
171 // handlers read `event.key` directly.
172 const isShortcut = useEffectEvent(
173 (key: NonNullable<ReturnType<typeof readHtmlRenderKeyDown>>) => {
174 const matches = (shortcut: HtmlRenderShortcut) =>
175 matchesKeybindingShortcut(key, { ...shortcut, modKey: false }, navigator.platform);
176 const allowed = shortcuts.filter(matches);
177 return (
178 allowed.length > 0 &&
179 !blocked.some(matches) &&
180 (key.key.length === 1 ||
181 key.key === "Dead" ||
182 allowed.some((shortcut) => shortcut.key === normalizeEventKey(key.key)))
183 );
184 },
185 );
186 const openChangeRequestLink = useOpenChangeRequestLink(props.threadRef);
187 const openLink = useOpenLink(props.threadRef);
188 const open = useEffectEvent((url: string, modifiers: { metaKey: boolean; ctrlKey: boolean }) => {
189 if (modifiers.metaKey || modifiers.ctrlKey) {
190 void readLocalApi()
191 ?.shell.openExternal(url)
192 .catch((cause: unknown) => console.error(cause));
193 return;
194 }
195 if (
196 props.threadRef !== undefined &&
197 openChangeRequestLink(
198 { ...modifiers, preventDefault: () => undefined, stopPropagation: () => undefined },
199 url,
200 undefined,
201 props.threadRef.environmentId,
202 )
203 ) {
204 return;
205 }
206 void openLink(url, { event: modifiers }).catch((cause: unknown) => console.error(cause));
207 });
208 // It asks the client, which opens the link only while this frame has focus
209 // and the reader has just used the app. A page can take focus by script, so
210 // this stops opens on load, not a page that waits for the reader's next click
211 // or key.
212 useEffect(() => {
213 const openLink = (event: MessageEvent) => {
214 const frame = frameRef.current;
215 const request = readHtmlRenderLinkRequest(event.data);
216 if (
217 request === undefined ||
218 frame === null ||
219 event.source !== frame.contentWindow ||
220 document.activeElement !== frame ||
221 navigator.userActivation?.isActive === false
222 ) {
223 return;
224 }
225 open(request.url, request);
226 frame.contentWindow?.postMessage(htmlRenderResult(request.id), "*");
227 };
228 window.addEventListener("message", openLink);
229 return () => window.removeEventListener("message", openLink);
230 }, []);
231 useEffect(() => {
232 const replayKey = (event: MessageEvent) => {
233 const frame = frameRef.current;
234 const key = readHtmlRenderKeyDown(event.data);
235 if (
236 key === undefined ||
237 frame === null ||
238 event.source !== frame.contentWindow ||
239 document.activeElement !== frame ||
240 navigator.userActivation?.isActive === false
241 ) {
242 return;
243 }
244 if (!isShortcut(key)) return;
245 frame.dispatchEvent(
246 new KeyboardEvent("keydown", { ...key, bubbles: true, cancelable: true }),
247 );
248 };
249 window.addEventListener("message", replayKey);
250 return () => window.removeEventListener("message", replayKey);
251 }, []);
252 // A clicked page image opens in the same viewer as chat images, gated like a link.
253 useEffect(() => {
254 const openImage = (event: MessageEvent) => {
255 const frame = frameRef.current;
256 const request = readHtmlRenderImageRequest(event.data);
257 if (
258 request === undefined ||
259 frame === null ||
260 event.source !== frame.contentWindow ||
261 document.activeElement !== frame ||
262 navigator.userActivation?.isActive === false
263 ) {
264 return;
265 }
266 setExpandedImage({ images: [{ src: request.src, name: request.name }], index: 0 });
267 };
268 window.addEventListener("message", openImage);
269 return () => window.removeEventListener("message", openImage);
270 }, []);
271 const { onFullscreenChange } = props;
272 useEffect(() => {
273 if (expandedImage === null) return;
274 onFullscreenChange?.(true);
275 return () => onFullscreenChange?.(false);
276 }, [expandedImage, onFullscreenChange]);
277 const { onContentHeight } = props;
278 // A page posts its height once per change, so listen from the commit that
279 // inserts the frame; a passive effect could run after a fast page's first post.
280 useLayoutEffect(() => {
281 if (onContentHeight === undefined) return;
282 const resize = (event: MessageEvent) => {
283 const height = readHtmlRenderContentHeight(event.data);
284 if (height !== undefined && event.source === frameRef.current?.contentWindow) {
285 onContentHeight(height);
286 }
287 };
288 window.addEventListener("message", resize);
289 return () => window.removeEventListener("message", resize);
290 }, [onContentHeight]);
291 return (
292 <>
293 <iframe
294 ref={frameRef}
295 src={src}
296 title={props.title}
297 // Never allow-same-origin: the opaque origin keeps the page out of the app's session.
298 sandbox="allow-scripts allow-forms"
299 loading="lazy"
300 onLoad={() => {
301 setLoaded(true);
302 // Covers a theme change that landed while the page was loading.
303 postTheme();
304 postShortcuts();
305 props.onLoad?.();
306 }}
307 // A frame whose color scheme differs from its document's paints an opaque
308 // canvas, so the blank document a frame starts with would flash white in
309 // dark mode. Once the page is in, its prefers-color-scheme follows the app.
310 className={cn("border-0 scheme-light", props.className)}
311 style={loaded ? { colorScheme: theme.appearance } : undefined}
312 />
313 {expandedImage !== null ? (
314 <ExpandedImageDialog preview={expandedImage} onClose={() => setExpandedImage(null)} />
315 ) : null}
316 </>
317 );
318}