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

BrowserDocumentFrame.tsx

302 lines11.0 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 const { onFullscreenChange } = props;
233 useEffect(() => {
234 if (expandedImage === null) return;
235 onFullscreenChange?.(true);
236 return () => onFullscreenChange?.(false);
237 }, [expandedImage, onFullscreenChange]);
238 // Links, keys and images require frame focus and recent reader activity: a page can take
239 // focus by script, so this blocks opens on load, though not a page that waits for the
240 // reader's next input.
241 const onFrameMessage = useEffectEvent((frame: HTMLIFrameElement, event: MessageEvent) => {
242 const height = readHtmlRenderContentHeight(event.data);
243 if (height !== undefined) {
244 props.onContentHeight?.(height);
245 return;
246 }
247 if (document.activeElement !== frame || navigator.userActivation?.isActive === false) return;
248 const linkRequest = readHtmlRenderLinkRequest(event.data);
249 if (linkRequest !== undefined) {
250 open(linkRequest.url, linkRequest);
251 frame.contentWindow?.postMessage(htmlRenderResult(linkRequest.id), "*");
252 return;
253 }
254 const key = readHtmlRenderKeyDown(event.data);
255 if (key !== undefined) {
256 if (isShortcut(key)) {
257 frame.dispatchEvent(
258 new KeyboardEvent("keydown", { ...key, bubbles: true, cancelable: true }),
259 );
260 }
261 return;
262 }
263 const imageRequest = readHtmlRenderImageRequest(event.data);
264 if (imageRequest !== undefined) {
265 setExpandedImage({ images: [{ src: imageRequest.src, name: imageRequest.name }], index: 0 });
266 }
267 });
268 // Attach at commit because a fast page may post its initial height before passive effects run.
269 useLayoutEffect(() => {
270 const frame = frameRef.current;
271 if (frame === null) return;
272 const onMessage = (event: MessageEvent) => {
273 if (event.source === frame.contentWindow) onFrameMessage(frame, event);
274 };
275 window.addEventListener("message", onMessage);
276 return () => window.removeEventListener("message", onMessage);
277 }, []);
278 return (
279 <>
280 <iframe
281 ref={frameRef}
282 src={src}
283 title={props.title}
284 // Never allow-same-origin: the opaque origin keeps the page out of the app's session.
285 sandbox="allow-scripts allow-forms"
286 loading="lazy"
287 onLoad={() => {
288 setLoaded(true);
289 // Covers a theme change that landed while the page was loading.
290 postTheme();
291 postShortcuts();
292 }}
293 // Match the blank document's scheme to avoid dark-mode white flashes, then follow the app after load.
294 className={cn("border-0 scheme-light", props.className)}
295 style={loaded ? { colorScheme: theme.appearance } : undefined}
296 />
297 {expandedImage !== null ? (
298 <ExpandedImageDialog preview={expandedImage} onClose={() => setExpandedImage(null)} />
299 ) : null}
300 </>
301 );