The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 147 lines 5.96 KB
Raw
1 import DOMPurify from "dompurify";
2 import { MinusIcon, PlusIcon, RotateCcwIcon } from "lucide-react";
3 import { FileSurfaceAction } from "./fileSurfaceChrome";
4 import { useGT } from "gt-react";
5 import { useEffect, useRef, useState } from "react";
6 import { useTheme } from "~/hooks/useTheme";
7 import { observeResize } from "~/lib/observeResize";
8
9 export 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
67 function documentColors() {
68 const style = getComputedStyle(document.documentElement);
69 return ["background", "foreground", "card", "border"].map((token) =>
70 style.getPropertyValue(`--${token}`),
71 );
72 }
73
74 export default function DocumentPages(props: {
75 readonly html: string;
76 readonly name: string;
77 readonly output?: boolean;
78 readonly details?: string;
79 }) {
80 const gt = useGT();
81 const { theme, resolvedTheme, themeHalves } = useTheme();
82 const [colors, setColors] = useState(documentColors);
83 // 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.
84 useEffect(() => {
85 // The iframe cannot inherit the host palette across its sandbox boundary.
86 // oxlint-disable-next-line react/set-state-in-effect -- Read tokens after useTheme applies the selected palette.
87 setColors(documentColors());
88 // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Theme values invalidate the palette read from the host DOM.
89 }, [theme, resolvedTheme, themeHalves]);
90 const [zoom, setZoom] = useState(1);
91 const [outputHeight, setOutputHeight] = useState(0);
92 const stopObserving = useRef<(() => void) | null>(null);
93 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Disconnect the iframe body's resize observer when the document unmounts.
94 useEffect(() => () => stopObserving.current?.(), []);
95 const html = sanitizeDocumentHtml(props.html);
96 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>`;
97 return (
98 <>
99 {!props.output ? (
100 <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">
101 <span className="min-w-0 flex-1 text-muted-foreground tabular-nums" role="status">
102 {props.details}
103 </span>
104 <FileSurfaceAction
105 label={gt("Decrease reading size")}
106 disabled={zoom <= 0.5}
107 onPress={() => setZoom((value) => Math.max(0.5, value - 0.25))}
108 >
109 <MinusIcon className="size-3.5" />
110 </FileSurfaceAction>
111 <span className="min-w-10 text-center tabular-nums">{Math.round(zoom * 100)}%</span>
112 <FileSurfaceAction
113 label={gt("Increase reading size")}
114 disabled={zoom >= 2}
115 onPress={() => setZoom((value) => Math.min(2, value + 0.25))}
116 >
117 <PlusIcon className="size-3.5" />
118 </FileSurfaceAction>
119 <FileSurfaceAction
120 label={gt("Reset reading size")}
121 disabled={zoom === 1}
122 onPress={() => setZoom(1)}
123 >
124 <RotateCcwIcon className="size-3.5" />
125 </FileSurfaceAction>
126 </div>
127 ) : null}
128 <iframe
129 title={props.name}
130 srcDoc={srcDoc}
131 // Same-origin access lets the parent measure saved output; scripts remain blocked.
132 sandbox={props.output ? "allow-same-origin" : ""}
133 onLoad={(event) => {
134 if (!props.output) return;
135 stopObserving.current?.();
136 const body = event.currentTarget.contentDocument?.body;
137 if (!body) return;
138 const measure = () => setOutputHeight(Math.ceil(body.getBoundingClientRect().height));
139 stopObserving.current = observeResize(body, measure);
140 measure();
141 }}
142 style={props.output ? { height: outputHeight } : undefined}
143 className={props.output ? "block w-full border-0" : "min-h-0 flex-1 border-0"}
144 />
145 </>
146 );
147 }