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

BrowserDocumentFrame.tsx

306 lines10.9 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/** Keep the initial URL while mounted; re-signing must not reload the page. */
113export function HtmlRenderDocument(props: {
114 readonly src: string;
115 readonly title: string;
116 readonly className?: string;
117 readonly threadRef?: ScopedThreadRef | undefined;
118 readonly onContentHeight?: (height: number) => void;
119 /** Reports fullscreen changes so virtualized rows can stay mounted. */
120 readonly onFullscreenChange?: ((fullscreen: boolean) => void) | undefined;
121}) {
122 const theme = useHtmlRenderTheme();
123 const frameRef = useRef<HTMLIFrameElement>(null);
124 const [src] = useState(() => `${props.src.split("#", 1)[0]}${htmlRenderThemeFragment(theme)}`);
125 const [loaded, setLoaded] = useState(false);
126 const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
127 const postTheme = () => {
128 frameRef.current?.contentWindow?.postMessage(htmlRenderThemeMessage(theme), "*");
129 };
130 useEffect(postTheme, [theme]);
131 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
132 const environmentKeybindings = useAtomValue(
133 serverEnvironment.configValueAtom(props.threadRef?.environmentId ?? null),
134 )?.keybindings;
135 // Replay only Cmd/Ctrl chords exclusive to allowed commands regardless of when; live resolution could
136 // otherwise type in the composer.
137 const mac = isMacPlatform(navigator.platform);
138 const resolve = (shortcut: KeybindingShortcut): HtmlRenderShortcut => ({
139 key: shortcut.key,
140 metaKey: shortcut.metaKey || (shortcut.modKey && mac),
141 ctrlKey: shortcut.ctrlKey || (shortcut.modKey && !mac),
142 shiftKey: shortcut.shiftKey,
143 altKey: shortcut.altKey,
144 });
145 const blocked = [...keybindings, ...(environmentKeybindings ?? [])]
146 .filter((binding) => !HTML_RENDER_SHORTCUT_COMMANDS.has(binding.command))
147 .map((binding) => resolve(binding.shortcut));
148 const shortcutsByKey = new Map<string, HtmlRenderShortcut>();
149 for (const { command, shortcut } of keybindings) {
150 if (
151 HTML_RENDER_SHORTCUT_COMMANDS.has(command) &&
152 (shortcut.metaKey || shortcut.ctrlKey || shortcut.modKey)
153 ) {
154 shortcutsByKey.set(shortcutConflictKey(shortcut), resolve(shortcut));
155 }
156 }
157 const shortcuts = [...shortcutsByKey.values()];
158 const postShortcuts = () => {
159 frameRef.current?.contentWindow?.postMessage(
160 htmlRenderShortcutsMessage(shortcuts, blocked),
161 "*",
162 );
163 };
164 useEffect(postShortcuts, [blocked, shortcuts]);
165 // Pages can forge key/code pairs; reject pairs matching other bindings and require named keys to match the
166 // shortcut.
167 const isShortcut = useEffectEvent(
168 (key: NonNullable<ReturnType<typeof readHtmlRenderKeyDown>>) => {
169 const matches = (shortcut: HtmlRenderShortcut) =>
170 matchesKeybindingShortcut(key, { ...shortcut, modKey: false }, navigator.platform);
171 const allowed = shortcuts.filter(matches);
172 return (
173 allowed.length > 0 &&
174 !blocked.some(matches) &&
175 (key.key.length === 1 ||
176 key.key === "Dead" ||
177 allowed.some((shortcut) => shortcut.key === normalizeEventKey(key.key)))
178 );
179 },
180 );
181 const openChangeRequestLink = useOpenChangeRequestLink(props.threadRef);
182 const openLink = useOpenLink(props.threadRef);
183 const open = useEffectEvent((url: string, modifiers: { metaKey: boolean; ctrlKey: boolean }) => {
184 if (modifiers.metaKey || modifiers.ctrlKey) {
185 void readLocalApi()
186 ?.shell.openExternal(url)
187 .catch((cause: unknown) => console.error(cause));
188 return;
189 }
190 if (
191 props.threadRef !== undefined &&
192 openChangeRequestLink(
193 { ...modifiers, preventDefault: () => undefined, stopPropagation: () => undefined },
194 url,
195 undefined,
196 props.threadRef.environmentId,
197 )
198 ) {
199 return;
200 }
201 void openLink(url, { event: modifiers }).catch((cause: unknown) => console.error(cause));
202 });
203 // Require frame focus and recent app use to block opens on load; scripts can still wait for the reader's
204 // next input.
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 useEffect(() => {
246 const openImage = (event: MessageEvent) => {
247 const frame = frameRef.current;
248 const request = readHtmlRenderImageRequest(event.data);
249 if (
250 request === undefined ||
251 frame === null ||
252 event.source !== frame.contentWindow ||
253 document.activeElement !== frame ||
254 navigator.userActivation?.isActive === false
255 ) {
256 return;
257 }
258 setExpandedImage({ images: [{ src: request.src, name: request.name }], index: 0 });
259 };
260 window.addEventListener("message", openImage);
261 return () => window.removeEventListener("message", openImage);
262 }, []);
263 const { onFullscreenChange } = props;
264 useEffect(() => {
265 if (expandedImage === null) return;
266 onFullscreenChange?.(true);
267 return () => onFullscreenChange?.(false);
268 }, [expandedImage, onFullscreenChange]);
269 const { onContentHeight } = props;
270 // Listen at commit because a fast page may post its initial height before passive effects run.
271 useLayoutEffect(() => {
272 if (onContentHeight === undefined) return;
273 const resize = (event: MessageEvent) => {
274 const height = readHtmlRenderContentHeight(event.data);
275 if (height !== undefined && event.source === frameRef.current?.contentWindow) {
276 onContentHeight(height);
277 }
278 };
279 window.addEventListener("message", resize);
280 return () => window.removeEventListener("message", resize);
281 }, [onContentHeight]);
282 return (
283 <>
284 <iframe
285 ref={frameRef}
286 src={src}
287 title={props.title}
288 // Never allow-same-origin: the opaque origin keeps the page out of the app's session.
289 sandbox="allow-scripts allow-forms"
290 loading="lazy"
291 onLoad={() => {
292 setLoaded(true);
293 // Covers a theme change that landed while the page was loading.
294 postTheme();
295 postShortcuts();
296 }}
297 // Match the blank document's scheme to avoid dark-mode white flashes, then follow the app after load.
298 className={cn("border-0 scheme-light", props.className)}
299 style={loaded ? { colorScheme: theme.appearance } : undefined}
300 />
301 {expandedImage !== null ? (
302 <ExpandedImageDialog preview={expandedImage} onClose={() => setExpandedImage(null)} />
303 ) : null}
304 </>
305 );