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

DocumentPages.tsx

168 lines6.5 KB

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 "ruby",
52 "rt",
53 "rp",
54 ],
55 ADD_ATTR: (attribute, tag) => attribute === "type" && tag === "ol",
56 ALLOWED_ATTR: [
57 "src",
58 "alt",
59 "colspan",
60 "rowspan",
61 "start",
62 "value",
63 "data-odf-whitespace",
64 "data-odf-normal-weight",
65 "data-odf-normal-style",
66 "data-rtf-whitespace",
67 ],
68 });
69 for (const image of fragment.querySelectorAll("img")) {
70 if (
71 !/^data:image\/(png|jpeg|gif|webp);base64,[a-z\d+/\t\n\f\r ]*(?:=[\t\n\f\r ]*){0,2}$/i.test(
72 image.getAttribute("src") ?? "",
73 )
74 )
75 image.remove();
76 }
77 const container = document.createElement("div");
78 container.append(fragment);
79 return container.innerHTML;
81​
82function documentColors() {
83 const style = getComputedStyle(document.documentElement);
84 return ["background", "foreground", "card", "border"].map((token) =>
85 style.getPropertyValue(`--${token}`),
86 );
88​
89export default function DocumentPages(props: {
90 readonly html: string;
91 readonly name: string;
92 readonly output?: boolean;
93 readonly estimatedOutputHeight?: number;
94 readonly details?: string;
95}) {
96 const gt = useGT();
97 const { theme, resolvedTheme, themeHalves } = useTheme();
98 const [colors, setColors] = useState(documentColors);
99 // 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.
100 useEffect(() => {
101 // The iframe cannot inherit the host palette across its sandbox boundary.
102 // oxlint-disable-next-line react/set-state-in-effect -- Read tokens after useTheme applies the selected palette.
103 setColors(documentColors());
104 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Theme values invalidate the palette read from the host DOM.
105 }, [theme, resolvedTheme, themeHalves]);
106 const [zoom, setZoom] = useState(1);
107 const [outputHeight, setOutputHeight] = useState<number>();
108 const stopObserving = useRef<(() => void) | null>(null);
109 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Disconnect the iframe body's resize observer when the document unmounts.
110 useEffect(() => () => stopObserving.current?.(), []);
111 const html = sanitizeDocumentHtml(props.html);
112 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],p[data-rtf-whitespace]{white-space:pre-wrap}span[data-odf-normal-weight]{font-weight:400}span[data-odf-normal-style]{font-style:normal}*{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>`;
113 return (
114 <>
115 {!props.output ? (
116 <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">
117 <span className="min-w-0 flex-1 text-muted-foreground tabular-nums" role="status">
118 {props.details}
119 </span>
120 <FileSurfaceAction
121 label={gt`Decrease reading size`}
122 disabled={zoom <= 0.5}
123 onPress={() => setZoom((value) => Math.max(0.5, value - 0.25))}
124 >
125 <MinusIcon className="size-3.5" />
126 </FileSurfaceAction>
127 <span className="min-w-10 text-center tabular-nums">{Math.round(zoom * 100)}%</span>
128 <FileSurfaceAction
129 label={gt`Increase reading size`}
130 disabled={zoom >= 2}
131 onPress={() => setZoom((value) => Math.min(2, value + 0.25))}
132 >
133 <PlusIcon className="size-3.5" />
134 </FileSurfaceAction>
135 <FileSurfaceAction
136 label={gt`Reset reading size`}
137 disabled={zoom === 1}
138 onPress={() => setZoom(1)}
139 >
140 <RotateCcwIcon className="size-3.5" />
141 </FileSurfaceAction>
142 </div>
143 ) : null}
144 <iframe
145 title={props.name}
146 srcDoc={srcDoc}
147 // Same-origin access lets the parent measure saved output; scripts remain blocked.
148 sandbox={props.output ? "allow-same-origin" : ""}
149 onLoad={(event) => {
150 if (!props.output) return;
151 stopObserving.current?.();
152 const body = event.currentTarget.contentDocument?.body;
153 if (!body) return;
154 const measure = () => {
155 const height = Math.ceil(body.getBoundingClientRect().height);
156 if (height > 0) setOutputHeight(height);
157 };
158 stopObserving.current = observeResize(body, measure);
159 measure();
160 }}
161 style={
162 props.output ? { height: outputHeight ?? props.estimatedOutputHeight ?? 0 } : undefined
163 }
164 className={props.output ? "block w-full border-0" : "min-h-0 flex-1 border-0"}
165 />
166 </>
167 );