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

BrowserDocumentFrame.tsx

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