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

BrowserDocumentFrame.tsx

335 lines11.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 {
26 lazy,
27 Suspense,
28 useEffect,
29 useEffectEvent,
30 useLayoutEffect,
31 useRef,
32 useState,
33} from "react";
34import { isElectron } from "~/env";
35import { FileSurfaceLoading } from "./fileSurfaceChrome";
36​
37import { useOpenLink } from "~/browser/useOpenLink";
38import { ExpandedImageDialog } from "~/components/chat/ExpandedImageDialog";
39import type { ExpandedImagePreview } from "~/components/chat/ExpandedImagePreview";
40import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme";
41import { shortcutConflictKey } from "~/keybindings";
42import { useOpenChangeRequestLink } from "~/lib/openPullRequestLink";
43import { readLocalApi } from "~/localApi";
44import { cn } from "~/lib/utils";
45import { primaryServerKeybindingsAtom, serverEnvironment } from "~/state/server";
46​
47/**
48 * The page reports the keys, and a page script can report any key it likes,
49 * so only commands that change what the reader sees are here, never one that
50 * changes a thread.
51 */
52const HTML_RENDER_SHORTCUT_COMMANDS: ReadonlySet<KeybindingCommand> = new Set([
53 "commandPalette.toggle",
54 "filePicker.toggle",
55 "projectSearch.toggle",
56 "chat.find",
57 "sidebar.toggle",
58 "rightPanel.toggle",
59 "rightPanel.toggleMaximized",
60 "threadPanel.toggle",
61 "terminal.toggle",
62 "preview.toggle",
63 "navigation.back",
64 "navigation.forward",
65 "thread.previous",
66 "thread.next",
67 ...THREAD_JUMP_KEYBINDING_COMMANDS,
68 ...MODEL_PICKER_JUMP_KEYBINDING_COMMANDS,
69]);
70​
71export const isPdfPreviewFile = (path: string): boolean =>
72 /\.pdf$/i.test(path.split(/[?#]/, 1)[0] ?? "");
73​
74const PdfViewer = lazy(() => import("./PdfViewer"));
75​
76function PdfDocument(props: { src: string; title: string }) {
77 const [src] = useState(props.src);
78 // The Electron shell does not enable PDF plugins. WebKit embeds on iOS
79 // expose only the first page, even when pdfViewerEnabled reports support.
80 const native =
81 !isElectron &&
82 navigator.pdfViewerEnabled &&
83 !/iPad|iPhone|iPod/.test(navigator.userAgent) &&
84 !(navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1);
85 return native ? (
86 // oxlint-disable-next-line react/iframe-missing-sandbox -- Chromium's PDF plugin requires an unsandboxed frame; src is an exact-file asset grant.
87 <iframe
88 src={`${src.split("#", 1)[0]}#navpanes=0&view=FitH`}
89 title={props.title}
90 className="block h-full min-h-0 w-full flex-1 border-0 bg-white"
91 />
92 ) : (
93 <Suspense fallback={<FileSurfaceLoading />}>
94 <PdfViewer src={src} title={props.title} />
95 </Suspense>
96 );
98​
99/**
100 * HTML runs in a sandboxed frame with an opaque origin, so a page cannot reach
101 * the app's session or storage. PDFs use a native viewer or the lazy PDF.js fallback.
102 */
103export function BrowserDocumentFrame(props: {
104 readonly src: string;
105 readonly title: string;
106 readonly pdf: boolean;
107 readonly htmlRender?: boolean;
108 readonly threadRef?: ScopedThreadRef | undefined;
109 /** Stable resource identity and revision; defaults to src for callers that reload on URL changes. */
110 readonly documentKey?: string | undefined;
111}) {
112 const key = props.documentKey ?? props.src;
113 return props.pdf ? (
114 <PdfDocument key={key} src={props.src} title={props.title} />
115 ) : props.htmlRender ? (
116 <HtmlRenderDocument
117 key={key}
118 src={props.src}
119 title={props.title}
120 threadRef={props.threadRef}
121 className="min-h-0 flex-1"
122 />
123 ) : (
124 <FileDocument key={key} src={props.src} title={props.title} />
125 );
127​
128// URL renewals must not discard form input or scroll; a new key mounts a fresh document.
129function FileDocument(props: { readonly src: string; readonly title: string }) {
130 const [src] = useState(props.src);
131 return (
132 <iframe
133 src={src}
134 title={props.title}
135 className="min-h-0 flex-1 border-0 bg-white"
136 sandbox="allow-scripts allow-forms allow-popups allow-downloads"
137 />
138 );
140​
141/** Keep the initial URL while mounted; re-signing must not reload the page. */
142export function HtmlRenderDocument(props: {
143 readonly src: string;
144 readonly title: string;
145 readonly className?: string;
146 readonly threadRef?: ScopedThreadRef | undefined;
147 readonly onContentHeight?: (height: number) => void;
148 /** Reports fullscreen changes so virtualized rows can stay mounted. */
149 readonly onFullscreenChange?: ((fullscreen: boolean) => void) | undefined;
150}) {
151 const theme = useHtmlRenderTheme();
152 const frameRef = useRef<HTMLIFrameElement>(null);
153 const [src] = useState(() => `${props.src.split("#", 1)[0]}${htmlRenderThemeFragment(theme)}`);
154 const [loaded, setLoaded] = useState(false);
155 const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
156 const postTheme = () => {
157 frameRef.current?.contentWindow?.postMessage(htmlRenderThemeMessage(theme), "*");
158 };
159 useEffect(postTheme, [theme]);
160 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
161 const environmentKeybindings = useAtomValue(
162 serverEnvironment.configValueAtom(props.threadRef?.environmentId ?? null),
163 )?.keybindings;
164 // Replay only Cmd/Ctrl chords exclusive to allowed commands regardless of when; live resolution could
165 // otherwise type in the composer.
166 const mac = isMacPlatform(navigator.platform);
167 const resolve = (shortcut: KeybindingShortcut): HtmlRenderShortcut => ({
168 key: shortcut.key,
169 metaKey: shortcut.metaKey || (shortcut.modKey && mac),
170 ctrlKey: shortcut.ctrlKey || (shortcut.modKey && !mac),
171 shiftKey: shortcut.shiftKey,
172 altKey: shortcut.altKey,
173 });
174 const blocked = [...keybindings, ...(environmentKeybindings ?? [])]
175 .filter((binding) => !HTML_RENDER_SHORTCUT_COMMANDS.has(binding.command))
176 .map((binding) => resolve(binding.shortcut));
177 const shortcutsByKey = new Map<string, HtmlRenderShortcut>();
178 for (const { command, shortcut } of keybindings) {
179 if (
180 HTML_RENDER_SHORTCUT_COMMANDS.has(command) &&
181 (shortcut.metaKey || shortcut.ctrlKey || shortcut.modKey)
182 ) {
183 shortcutsByKey.set(shortcutConflictKey(shortcut), resolve(shortcut));
184 }
185 }
186 const shortcuts = [...shortcutsByKey.values()];
187 const postShortcuts = () => {
188 frameRef.current?.contentWindow?.postMessage(
189 htmlRenderShortcutsMessage(shortcuts, blocked),
190 "*",
191 );
192 };
193 useEffect(postShortcuts, [blocked, shortcuts]);
194 // Pages can forge key/code pairs; reject pairs matching other bindings and require named keys to match the
195 // shortcut.
196 const isShortcut = useEffectEvent(
197 (key: NonNullable<ReturnType<typeof readHtmlRenderKeyDown>>) => {
198 const matches = (shortcut: HtmlRenderShortcut) =>
199 matchesKeybindingShortcut(key, { ...shortcut, modKey: false }, navigator.platform);
200 const allowed = shortcuts.filter(matches);
201 return (
202 allowed.length > 0 &&
203 !blocked.some(matches) &&
204 (key.key.length === 1 ||
205 key.key === "Dead" ||
206 allowed.some((shortcut) => shortcut.key === normalizeEventKey(key.key)))
207 );
208 },
209 );
210 const openChangeRequestLink = useOpenChangeRequestLink(props.threadRef);
211 const openLink = useOpenLink(props.threadRef);
212 const open = useEffectEvent((url: string, modifiers: { metaKey: boolean; ctrlKey: boolean }) => {
213 if (modifiers.metaKey || modifiers.ctrlKey) {
214 void readLocalApi()
215 ?.shell.openExternal(url)
216 .catch((cause: unknown) => console.error(cause));
217 return;
218 }
219 if (
220 props.threadRef !== undefined &&
221 openChangeRequestLink(
222 { ...modifiers, preventDefault: () => undefined, stopPropagation: () => undefined },
223 url,
224 undefined,
225 props.threadRef.environmentId,
226 )
227 ) {
228 return;
229 }
230 void openLink(url, { event: modifiers }).catch((cause: unknown) => console.error(cause));
231 });
232 // Require frame focus and recent app use to block opens on load; scripts can still wait for the reader's
233 // next input.
234 useEffect(() => {
235 const openLink = (event: MessageEvent) => {
236 const frame = frameRef.current;
237 const request = readHtmlRenderLinkRequest(event.data);
238 if (
239 request === undefined ||
240 frame === null ||
241 event.source !== frame.contentWindow ||
242 document.activeElement !== frame ||
243 navigator.userActivation?.isActive === false
244 ) {
245 return;
246 }
247 open(request.url, request);
248 frame.contentWindow?.postMessage(htmlRenderResult(request.id), "*");
249 };
250 window.addEventListener("message", openLink);
251 return () => window.removeEventListener("message", openLink);
252 }, []);
253 useEffect(() => {
254 const replayKey = (event: MessageEvent) => {
255 const frame = frameRef.current;
256 const key = readHtmlRenderKeyDown(event.data);
257 if (
258 key === undefined ||
259 frame === null ||
260 event.source !== frame.contentWindow ||
261 document.activeElement !== frame ||
262 navigator.userActivation?.isActive === false
263 ) {
264 return;
265 }
266 if (!isShortcut(key)) return;
267 frame.dispatchEvent(
268 new KeyboardEvent("keydown", { ...key, bubbles: true, cancelable: true }),
269 );
270 };
271 window.addEventListener("message", replayKey);
272 return () => window.removeEventListener("message", replayKey);
273 }, []);
274 useEffect(() => {
275 const openImage = (event: MessageEvent) => {
276 const frame = frameRef.current;
277 const request = readHtmlRenderImageRequest(event.data);
278 if (
279 request === undefined ||
280 frame === null ||
281 event.source !== frame.contentWindow ||
282 document.activeElement !== frame ||
283 navigator.userActivation?.isActive === false
284 ) {
285 return;
286 }
287 setExpandedImage({ images: [{ src: request.src, name: request.name }], index: 0 });
288 };
289 window.addEventListener("message", openImage);
290 return () => window.removeEventListener("message", openImage);
291 }, []);
292 const { onFullscreenChange } = props;
293 useEffect(() => {
294 if (expandedImage === null) return;
295 onFullscreenChange?.(true);
296 return () => onFullscreenChange?.(false);
297 }, [expandedImage, onFullscreenChange]);
298 const { onContentHeight } = props;
299 // Listen at commit because a fast page may post its initial height before passive effects run.
300 useLayoutEffect(() => {
301 if (onContentHeight === undefined) return;
302 const resize = (event: MessageEvent) => {
303 const height = readHtmlRenderContentHeight(event.data);
304 if (height !== undefined && event.source === frameRef.current?.contentWindow) {
305 onContentHeight(height);
306 }
307 };
308 window.addEventListener("message", resize);
309 return () => window.removeEventListener("message", resize);
310 }, [onContentHeight]);
311 return (
312 <>
313 <iframe
314 ref={frameRef}
315 src={src}
316 title={props.title}
317 // Never allow-same-origin: the opaque origin keeps the page out of the app's session.
318 sandbox="allow-scripts allow-forms"
319 loading="lazy"
320 onLoad={() => {
321 setLoaded(true);
322 // Covers a theme change that landed while the page was loading.
323 postTheme();
324 postShortcuts();
325 }}
326 // Match the blank document's scheme to avoid dark-mode white flashes, then follow the app after load.
327 className={cn("border-0 scheme-light", props.className)}
328 style={loaded ? { colorScheme: theme.appearance } : undefined}
329 />
330 {expandedImage !== null ? (
331 <ExpandedImageDialog preview={expandedImage} onClose={() => setExpandedImage(null)} />
332 ) : null}
333 </>
334 );