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

BrowserDocumentFrame.tsx

306 lines11.5 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 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- posts the current theme to the sandboxed iframe's window
160 useEffect(postTheme, [theme]);
161 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
162 const environmentKeybindings = useAtomValue(
163 serverEnvironment.configValueAtom(props.threadRef?.environmentId ?? null),
164 )?.keybindings;
165 // Replay only Cmd/Ctrl chords exclusive to allowed commands regardless of when; live resolution could
166 // otherwise type in the composer.
167 const mac = isMacPlatform(navigator.platform);
168 const resolve = (shortcut: KeybindingShortcut): HtmlRenderShortcut => ({
169 key: shortcut.key,
170 metaKey: shortcut.metaKey || (shortcut.modKey && mac),
171 ctrlKey: shortcut.ctrlKey || (shortcut.modKey && !mac),
172 shiftKey: shortcut.shiftKey,
173 altKey: shortcut.altKey,
174 });
175 const blocked = [...keybindings, ...(environmentKeybindings ?? [])]
176 .filter((binding) => !HTML_RENDER_SHORTCUT_COMMANDS.has(binding.command))
177 .map((binding) => resolve(binding.shortcut));
178 const shortcutsByKey = new Map<string, HtmlRenderShortcut>();
179 for (const { command, shortcut } of keybindings) {
180 if (
181 HTML_RENDER_SHORTCUT_COMMANDS.has(command) &&
182 (shortcut.metaKey || shortcut.ctrlKey || shortcut.modKey)
183 ) {
184 shortcutsByKey.set(shortcutConflictKey(shortcut), resolve(shortcut));
185 }
186 }
187 const shortcuts = [...shortcutsByKey.values()];
188 const postShortcuts = () => {
189 frameRef.current?.contentWindow?.postMessage(
190 htmlRenderShortcutsMessage(shortcuts, blocked),
191 "*",
192 );
193 };
194 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- posts allowed and blocked shortcuts to the sandboxed iframe's window
195 useEffect(postShortcuts, [blocked, shortcuts]);
196 // Pages can forge key/code pairs; reject pairs matching other bindings and require named keys to match the
197 // shortcut.
198 const isShortcut = useEffectEvent(
199 (key: NonNullable<ReturnType<typeof readHtmlRenderKeyDown>>) => {
200 const matches = (shortcut: HtmlRenderShortcut) =>
201 matchesKeybindingShortcut(key, { ...shortcut, modKey: false }, navigator.platform);
202 const allowed = shortcuts.filter(matches);
203 return (
204 allowed.length > 0 &&
205 !blocked.some(matches) &&
206 (key.key.length === 1 ||
207 key.key === "Dead" ||
208 allowed.some((shortcut) => shortcut.key === normalizeEventKey(key.key)))
209 );
210 },
211 );
212 const openChangeRequestLink = useOpenChangeRequestLink(props.threadRef);
213 const openLink = useOpenLink(props.threadRef);
214 const open = useEffectEvent((url: string, modifiers: { metaKey: boolean; ctrlKey: boolean }) => {
215 if (modifiers.metaKey || modifiers.ctrlKey) {
216 void readLocalApi()
217 ?.shell.openExternal(url)
218 .catch((cause: unknown) => console.error(cause));
219 return;
220 }
221 if (
222 props.threadRef !== undefined &&
223 openChangeRequestLink(
224 { ...modifiers, preventDefault: () => undefined, stopPropagation: () => undefined },
225 url,
226 undefined,
227 props.threadRef.environmentId,
228 )
229 ) {
230 return;
231 }
232 void openLink(url, { event: modifiers }).catch((cause: unknown) => console.error(cause));
233 });
234 const { onFullscreenChange } = props;
235 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reports fullscreen to the parent while the image viewer is open, and clears it on unmount
236 useEffect(() => {
237 if (expandedImage === null) return;
238 onFullscreenChange?.(true);
239 return () => onFullscreenChange?.(false);
240 }, [expandedImage, onFullscreenChange]);
241 // Links, keys and images require frame focus and recent reader activity: a page can take
242 // focus by script, so this blocks opens on load, though not a page that waits for the
243 // reader's next input.
244 const onFrameMessage = useEffectEvent((frame: HTMLIFrameElement, event: MessageEvent) => {
245 const height = readHtmlRenderContentHeight(event.data);
246 if (height !== undefined) {
247 props.onContentHeight?.(height);
248 return;
249 }
250 if (document.activeElement !== frame || navigator.userActivation?.isActive === false) return;
251 const linkRequest = readHtmlRenderLinkRequest(event.data);
252 if (linkRequest !== undefined) {
253 open(linkRequest.url, linkRequest);
254 frame.contentWindow?.postMessage(htmlRenderResult(linkRequest.id), "*");
255 return;
256 }
257 const key = readHtmlRenderKeyDown(event.data);
258 if (key !== undefined) {
259 if (isShortcut(key)) {
260 frame.dispatchEvent(
261 new KeyboardEvent("keydown", { ...key, bubbles: true, cancelable: true }),
262 );
263 }
264 return;
265 }
266 const imageRequest = readHtmlRenderImageRequest(event.data);
267 if (imageRequest !== undefined) {
268 setExpandedImage({ images: [{ src: imageRequest.src, name: imageRequest.name }], index: 0 });
269 }
270 });
271 // Attach at commit because a fast page may post its initial height before passive effects run.
272 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- attaches a window message listener for the iframe at commit, before its first height post
273 useLayoutEffect(() => {
274 const frame = frameRef.current;
275 if (frame === null) return;
276 const onMessage = (event: MessageEvent) => {
277 if (event.source === frame.contentWindow) onFrameMessage(frame, event);
278 };
279 window.addEventListener("message", onMessage);
280 return () => window.removeEventListener("message", onMessage);
281 }, []);
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 );