Open History to see the last commit
1import DOMPurify from "dompurify";
2import { MinusIcon, PlusIcon, RotateCcwIcon } from "lucide-react";
3import { FileSurfaceAction } from "./fileSurfaceChrome";
4import { useGT } from "gt-react";
5import { useEffect, useRef, useState } from "react";
6import { useTheme } from "~/hooks/useTheme";
7import { observeResize } from "~/lib/observeResize";
8
9export function sanitizeDocumentHtml(source: string): string {
10 const fragment = DOMPurify.sanitize(source, {
11 RETURN_DOM_FRAGMENT: true,
12 ALLOWED_TAGS: [
13 "p",
14 "h1",
15 "h2",
16 "h3",
17 "h4",
18 "h5",
19 "h6",
20 "div",
21 "span",
22 "strong",
23 "b",
24 "em",
25 "i",
26 "u",
27 "s",
28 "ul",
29 "ol",
30 "li",
31 "blockquote",
32 "pre",
33 "code",
34 "table",
35 "thead",
36 "tbody",
37 "tr",
38 "th",
39 "td",
40 "caption",
41 "figure",
42 "figcaption",
43 "br",
44 "hr",
45 "sub",
46 "sup",
47 "dl",
48 "dt",
49 "dd",
50 "img",
51 ],
52 ALLOWED_ATTR: ["src", "alt", "colspan", "rowspan", "data-odf-whitespace"],
53 });
54 for (const image of fragment.querySelectorAll("img")) {
55 if (
56 !/^data:image\/(png|jpeg|gif|webp);base64,[a-z\d+/]*={0,2}$/i.test(
57 image.getAttribute("src") ?? "",
58 )
59 )
60 image.remove();
61 }
62 const container = document.createElement("div");
63 container.append(fragment);
64 return container.innerHTML;
65}
66
67function documentColors() {
68 const style = getComputedStyle(document.documentElement);
69 return ["background", "foreground", "card", "border"].map((token) =>
70 style.getPropertyValue(`--${token}`),
71 );
72}
73
74export default function DocumentPages(props: {
75 readonly html: string;
76 readonly name: string;
77 readonly output?: boolean;
78 readonly estimatedOutputHeight?: number;
79 readonly details?: string;
80}) {
81 const gt = useGT();
82 const { theme, resolvedTheme, themeHalves } = useTheme();
83 const [colors, setColors] = useState(documentColors);
84 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Read the host DOM's applied theme tokens so the sandboxed document receives the current palette.
85 useEffect(() => {
86 // The iframe cannot inherit the host palette across its sandbox boundary.
87 // oxlint-disable-next-line react/set-state-in-effect -- Read tokens after useTheme applies the selected palette.
88 setColors(documentColors());
89 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Theme values invalidate the palette read from the host DOM.
90 }, [theme, resolvedTheme, themeHalves]);
91 const [zoom, setZoom] = useState(1);
92 const [outputHeight, setOutputHeight] = useState<number>();
93 const stopObserving = useRef<(() => void) | null>(null);
94 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Disconnect the iframe body's resize observer when the document unmounts.
95 useEffect(() => () => stopObserving.current?.(), []);
96 const html = sanitizeDocumentHtml(props.html);
97 const srcDoc = `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'"><style>:root{color-scheme:${resolvedTheme}}html{background:${colors[0]};color:${colors[1]};font:${15 * zoom}px/1.65 system-ui,sans-serif}body{box-sizing:border-box;margin:${props.output ? "0" : "20px auto"};padding:${props.output ? "16px" : "32px"};width:${props.output ? "100%" : "calc(100% - 40px)"};max-width:${860 * zoom}px;min-height:${props.output ? "0" : "calc(100vh - 40px)"};display:flow-root;background:${colors[2]};overflow-wrap:anywhere}h1,h2,h3{line-height:1.25}img{max-width:100%;height:auto}table{border-collapse:collapse;min-width:100%;max-width:100%}td,th{border:1px solid ${colors[3]};padding:6px 12px;text-align:left}th{background:${colors[0]}}tr:nth-child(even){background:${colors[0]}}pre,span[data-odf-whitespace]{white-space:pre-wrap}*{scrollbar-width:thin}${props.output ? "" : "@media(max-width:420px){body{padding:20px;width:calc(100% - 24px);margin:12px auto}}"}</style></head><body>${html}</body></html>`;
98 return (
99 <>
100 {!props.output ? (
101 <div className="flex min-h-10 shrink-0 flex-wrap items-center gap-1 border-b border-border/60 px-3 py-1 text-xs text-muted-foreground">
102 <span className="min-w-0 flex-1 text-muted-foreground tabular-nums" role="status">
103 {props.details}
104 </span>
105 <FileSurfaceAction
106 label={gt("Decrease reading size")}
107 disabled={zoom <= 0.5}
108 onPress={() => setZoom((value) => Math.max(0.5, value - 0.25))}
109 >
110 <MinusIcon className="size-3.5" />
111 </FileSurfaceAction>
112 <span className="min-w-10 text-center tabular-nums">{Math.round(zoom * 100)}%</span>
113 <FileSurfaceAction
114 label={gt("Increase reading size")}
115 disabled={zoom >= 2}
116 onPress={() => setZoom((value) => Math.min(2, value + 0.25))}
117 >
118 <PlusIcon className="size-3.5" />
119 </FileSurfaceAction>
120 <FileSurfaceAction
121 label={gt("Reset reading size")}
122 disabled={zoom === 1}
123 onPress={() => setZoom(1)}
124 >
125 <RotateCcwIcon className="size-3.5" />
126 </FileSurfaceAction>
127 </div>
128 ) : null}
129 <iframe
130 title={props.name}
131 srcDoc={srcDoc}
132 // Same-origin access lets the parent measure saved output; scripts remain blocked.
133 sandbox={props.output ? "allow-same-origin" : ""}
134 onLoad={(event) => {
135 if (!props.output) return;
136 stopObserving.current?.();
137 const body = event.currentTarget.contentDocument?.body;
138 if (!body) return;
139 const measure = () => {
140 const height = Math.ceil(body.getBoundingClientRect().height);
141 if (height > 0) setOutputHeight(height);
142 };
143 stopObserving.current = observeResize(body, measure);
144 measure();
145 }}
146 style={
147 props.output ? { height: outputHeight ?? props.estimatedOutputHeight ?? 0 } : undefined
148 }
149 className={props.output ? "block w-full border-0" : "min-h-0 flex-1 border-0"}
150 />
151 </>
152 );
153}