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

BrowserDocumentFrame.tsx

316 lines11.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 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, 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 );
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 mac = isMacPlatform(navigator.platform);
139 const resolve = (shortcut: KeybindingShortcut): HtmlRenderShortcut => ({
140 key: shortcut.key,
141 metaKey: shortcut.metaKey || (shortcut.modKey && mac),
142 ctrlKey: shortcut.ctrlKey || (shortcut.modKey && !mac),
143 shiftKey: shortcut.shiftKey,
144 altKey: shortcut.altKey,
145 });
146 const blocked = [...keybindings, ...(environmentKeybindings ?? [])]
147 .filter((binding) => !HTML_RENDER_SHORTCUT_COMMANDS.has(binding.command))
148 .map((binding) => resolve(binding.shortcut));
149 const shortcutsByKey = new Map<string, HtmlRenderShortcut>();
150 for (const { command, shortcut } of keybindings) {
151 if (
152 HTML_RENDER_SHORTCUT_COMMANDS.has(command) &&
153 (shortcut.metaKey || shortcut.ctrlKey || shortcut.modKey)
154 ) {
155 shortcutsByKey.set(shortcutConflictKey(shortcut), resolve(shortcut));
156 }
157 }
158 const shortcuts = [...shortcutsByKey.values()];
159 const postShortcuts = () => {
160 frameRef.current?.contentWindow?.postMessage(
161 htmlRenderShortcutsMessage(shortcuts, blocked),
162 "*",
163 );
164 };
165 useEffect(postShortcuts, [blocked, shortcuts]);
166 // The page reports the key and code, and a page script can report any pair,
167 // so a key that could match another command's binding is never replayed. A
168 // named key (Backspace, Enter) must be the shortcut's own, since some app
169 // handlers read `event.key` directly.
170 const isShortcut = useEffectEvent(
171 (key: NonNullable<ReturnType<typeof readHtmlRenderKeyDown>>) => {
172 const matches = (shortcut: HtmlRenderShortcut) =>
173 matchesKeybindingShortcut(key, { ...shortcut, modKey: false }, navigator.platform);
174 const allowed = shortcuts.filter(matches);
175 return (
176 allowed.length > 0 &&
177 !blocked.some(matches) &&
178 (key.key.length === 1 ||
179 key.key === "Dead" ||
180 allowed.some((shortcut) => shortcut.key === normalizeEventKey(key.key)))
181 );
182 },
183 );
184 const openChangeRequestLink = useOpenChangeRequestLink(props.threadRef);
185 const openLink = useOpenLink(props.threadRef);
186 const open = useEffectEvent((url: string, modifiers: { metaKey: boolean; ctrlKey: boolean }) => {
187 if (modifiers.metaKey || modifiers.ctrlKey) {
188 void readLocalApi()
189 ?.shell.openExternal(url)
190 .catch((cause: unknown) => console.error(cause));
191 return;
192 }
193 if (
194 props.threadRef !== undefined &&
195 openChangeRequestLink(
196 { ...modifiers, preventDefault: () => undefined, stopPropagation: () => undefined },
197 url,
198 undefined,
199 props.threadRef.environmentId,
200 )
201 ) {
202 return;
203 }
204 void openLink(url, { event: modifiers }).catch((cause: unknown) => console.error(cause));
205 });
206 // It asks the client, which opens the link only while this frame has focus
207 // and the reader has just used the app. A page can take focus by script, so
208 // this stops opens on load, not a page that waits for the reader's next click
209 // or key.
210 useEffect(() => {
211 const openLink = (event: MessageEvent) => {
212 const frame = frameRef.current;
213 const request = readHtmlRenderLinkRequest(event.data);
214 if (
215 request === undefined ||
216 frame === null ||
217 event.source !== frame.contentWindow ||
218 document.activeElement !== frame ||
219 navigator.userActivation?.isActive === false
220 ) {
221 return;
222 }
223 open(request.url, request);
224 frame.contentWindow?.postMessage(htmlRenderResult(request.id), "*");
225 };
226 window.addEventListener("message", openLink);
227 return () => window.removeEventListener("message", openLink);
228 }, []);
229 useEffect(() => {
230 const replayKey = (event: MessageEvent) => {
231 const frame = frameRef.current;
232 const key = readHtmlRenderKeyDown(event.data);
233 if (
234 key === undefined ||
235 frame === null ||
236 event.source !== frame.contentWindow ||
237 document.activeElement !== frame ||
238 navigator.userActivation?.isActive === false
239 ) {
240 return;
241 }
242 if (!isShortcut(key)) return;
243 frame.dispatchEvent(
244 new KeyboardEvent("keydown", { ...key, bubbles: true, cancelable: true }),
245 );
246 };
247 window.addEventListener("message", replayKey);
248 return () => window.removeEventListener("message", replayKey);
249 }, []);
250 // A clicked page image opens in the same viewer as chat images, gated like a link.
251 useEffect(() => {
252 const openImage = (event: MessageEvent) => {
253 const frame = frameRef.current;
254 const request = readHtmlRenderImageRequest(event.data);
255 if (
256 request === undefined ||
257 frame === null ||
258 event.source !== frame.contentWindow ||
259 document.activeElement !== frame ||
260 navigator.userActivation?.isActive === false
261 ) {
262 return;
263 }
264 setExpandedImage({ images: [{ src: request.src, name: request.name }], index: 0 });
265 };
266 window.addEventListener("message", openImage);
267 return () => window.removeEventListener("message", openImage);
268 }, []);
269 const { onFullscreenChange } = props;
270 useEffect(() => {
271 if (expandedImage === null) return;
272 onFullscreenChange?.(true);
273 return () => onFullscreenChange?.(false);
274 }, [expandedImage, onFullscreenChange]);
275 const { onContentHeight } = props;
276 // A page posts its height once per change, so listen from the commit that
277 // inserts the frame; a passive effect could run after a fast page's first post.
278 useLayoutEffect(() => {
279 if (onContentHeight === undefined) return;
280 const resize = (event: MessageEvent) => {
281 const height = readHtmlRenderContentHeight(event.data);
282 if (height !== undefined && event.source === frameRef.current?.contentWindow) {
283 onContentHeight(height);
284 }
285 };
286 window.addEventListener("message", resize);
287 return () => window.removeEventListener("message", resize);
288 }, [onContentHeight]);
289 return (
290 <>
291 <iframe
292 ref={frameRef}
293 src={src}
294 title={props.title}
295 // Never allow-same-origin: the opaque origin keeps the page out of the app's session.
296 sandbox="allow-scripts allow-forms"
297 loading="lazy"
298 onLoad={() => {
299 setLoaded(true);
300 // Covers a theme change that landed while the page was loading.
301 postTheme();
302 postShortcuts();
303 props.onLoad?.();
304 }}
305 // A frame whose color scheme differs from its document's paints an opaque
306 // canvas, so the blank document a frame starts with would flash white in
307 // dark mode. Once the page is in, its prefers-color-scheme follows the app.
308 className={cn("border-0 scheme-light", props.className)}
309 style={loaded ? { colorScheme: theme.appearance } : undefined}
310 />
311 {expandedImage !== null ? (
312 <ExpandedImageDialog preview={expandedImage} onClose={() => setExpandedImage(null)} />
313 ) : null}
314 </>
315 );