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

BrowserDocumentFrame.tsx

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