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

BrowserDocumentFrame.tsx

142 lines5.3 KB

1import {
2 htmlRenderThemeFragment,
3 htmlRenderThemeMessage,
4 htmlRenderResult,
5 readHtmlRenderContentHeight,
6 readHtmlRenderLinkRequest,
7} from "@t3tools/shared/htmlRender";
8import { useEffect, useLayoutEffect, useRef, useState } from "react";
9​
10import { useHtmlRenderTheme } from "~/hooks/useHtmlRenderTheme";
11import { cn } from "~/lib/utils";
12​
13/**
14 * Chromium's viewer opens with its own toolbar, a thumbnail rail and a small
15 * zoom. The panel header is the only chrome we want, so ask for the page
16 * alone, fitted to the panel width. Pinch and keyboard zoom, scrolling, text
17 * selection and find still work inside the frame.
18 */
19const PDF_VIEWER_FRAGMENT = "#toolbar=0&view=FitH";
20​
21export const isPdfPreviewFile = (path: string): boolean =>
22 /\.pdf$/i.test(path.split(/[?#]/, 1)[0] ?? "");
23​
24/**
25 * Renders an HTML or PDF document from its URL. HTML runs in a sandboxed frame
26 * with an opaque origin, so a page cannot reach the app's session or storage.
27 * The built-in PDF viewer needs an unsandboxed frame; a PDF runs no scripts.
28 * An agent's HTML render also wears the app theme.
29 */
30export function BrowserDocumentFrame(props: {
31 readonly src: string;
32 readonly title: string;
33 readonly pdf: boolean;
34 readonly htmlRender?: boolean;
35}) {
36 const className = "min-h-0 flex-1 border-0 bg-white";
37 return props.pdf ? (
38 // oxlint-disable-next-line react/iframe-missing-sandbox -- the built-in PDF viewer needs an unsandboxed frame.
39 <iframe
40 key={props.src}
41 src={`${props.src}${PDF_VIEWER_FRAGMENT}`}
42 title={props.title}
43 className={className}
44 />
45 ) : props.htmlRender ? (
46 <HtmlRenderDocument
47 key={props.src}
48 src={props.src}
49 title={props.title}
50 className="min-h-0 flex-1"
51 />
52 ) : (
53 <iframe
54 key={props.src}
55 src={props.src}
56 title={props.title}
57 className={className}
58 sandbox="allow-scripts allow-forms allow-popups"
59 />
60 );
62​
63/**
64 * A sandboxed agent HTML render in the app theme. The page reads the theme from
65 * its URL fragment before first paint, then follows changes posted to its
66 * bootstrap. The first URL is kept for the frame's lifetime: signed asset URLs
67 * re-mint while it stays mounted, and a new src would reload the page.
68 */
69export function HtmlRenderDocument(props: {
70 readonly src: string;
71 readonly title: string;
72 readonly className?: string;
73 /** Receives the page's content height whenever it changes, so an inline frame can fit it. */
74 readonly onContentHeight?: (height: number) => void;
75}) {
76 const theme = useHtmlRenderTheme();
77 const frameRef = useRef<HTMLIFrameElement>(null);
78 const [src] = useState(() => `${props.src.split("#", 1)[0]}${htmlRenderThemeFragment(theme)}`);
79 const [loaded, setLoaded] = useState(false);
80 const postTheme = () => {
81 frameRef.current?.contentWindow?.postMessage(htmlRenderThemeMessage(theme), "*");
82 };
83 useEffect(postTheme, [theme]);
84 // The page cannot open windows itself (an inline page runs unopened, and
85 // desktop sends any window to the browser). It asks the client, which opens
86 // the link only while this frame has focus and the reader has just used the
87 // app. A page can take focus by script, so this stops opens on load, not a
88 // page that waits for the reader's next click or key.
89 useEffect(() => {
90 const openLink = (event: MessageEvent) => {
91 const frame = frameRef.current;
92 const request = readHtmlRenderLinkRequest(event.data);
93 if (
94 request === undefined ||
95 frame === null ||
96 event.source !== frame.contentWindow ||
97 document.activeElement !== frame ||
98 navigator.userActivation?.isActive === false
99 ) {
100 return;
101 }
102 window.open(request.url, "_blank", "noopener,noreferrer");
103 frame.contentWindow?.postMessage(htmlRenderResult(request.id), "*");
104 };
105 window.addEventListener("message", openLink);
106 return () => window.removeEventListener("message", openLink);
107 }, []);
108 const { onContentHeight } = props;
109 // A page posts its height once per change, so listen from the commit that
110 // inserts the frame; a passive effect could run after a fast page's first post.
111 useLayoutEffect(() => {
112 if (onContentHeight === undefined) return;
113 const resize = (event: MessageEvent) => {
114 const height = readHtmlRenderContentHeight(event.data);
115 if (height !== undefined && event.source === frameRef.current?.contentWindow) {
116 onContentHeight(height);
117 }
118 };
119 window.addEventListener("message", resize);
120 return () => window.removeEventListener("message", resize);
121 }, [onContentHeight]);
122 return (
123 <iframe
124 ref={frameRef}
125 src={src}
126 title={props.title}
127 // Never allow-same-origin: the opaque origin keeps the page out of the app's session.
128 sandbox="allow-scripts allow-forms"
129 loading="lazy"
130 onLoad={() => {
131 setLoaded(true);
132 // Covers a theme change that landed while the page was loading.
133 postTheme();
134 }}
135 // A frame whose color scheme differs from its document's paints an opaque
136 // canvas, so the blank document a frame starts with would flash white in
137 // dark mode. Once the page is in, its prefers-color-scheme follows the app.
138 className={cn("border-0 scheme-light", props.className)}
139 style={loaded ? { colorScheme: theme.appearance } : undefined}
140 />
141 );