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

BrowserDocumentFrame.tsx

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