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

main
tsx 326 lines 9.89 KB
Raw
1 import DOMPurify from "dompurify";
2 import type { DiagramType, MathResolver } from "pele/lazy";
3 import { T, useGT, Var } from "gt-react";
4 import { use, useState } from "react";
5
6 import { serializeCodeBlockToMarkdown } from "../../markdown-clipboard";
7 import { Button } from "../ui/button";
8
9 type Pele = typeof import("pele/lazy");
10 type PeleLoad = { readonly status: "loaded"; readonly pele: Pele } | { readonly status: "failed" };
11
12 let coreLoad: Promise<PeleLoad> | null = null;
13 // Each diagram type is its own chunk, so a chat with one flowchart loads only
14 // the flowchart parser and layout.
15 const diagramLoads = new Map<DiagramType, Promise<PeleLoad>>();
16
17 function loadCore(): Promise<PeleLoad> {
18 coreLoad ??= import("pele/lazy").then(
19 (pele): PeleLoad => ({ status: "loaded", pele }),
20 (): PeleLoad => ({ status: "failed" }),
21 );
22 return coreLoad;
23 }
24
25 function loadDiagramType(pele: Pele, type: DiagramType): Promise<PeleLoad> {
26 let load = diagramLoads.get(type);
27 if (!load) {
28 load = pele.load(type).then(
29 (): PeleLoad => ({ status: "loaded", pele }),
30 (): PeleLoad => ({ status: "failed" }),
31 );
32 diagramLoads.set(type, load);
33 }
34 return load;
35 }
36
37 function detectDiagramType(pele: Pele, source: string): DiagramType | null {
38 try {
39 return pele.detectType(source);
40 } catch {
41 return null;
42 }
43 }
44
45 let mathLoad: Promise<MathResolver | null> | null = null;
46
47 // Pele has no typesetter, so $$...$$ labels go through the KaTeX the chat
48 // already uses for math. It only loads for diagrams that contain math.
49 function loadMath(): Promise<MathResolver | null> {
50 mathLoad ??= import("katex").then(
51 ({ default: katex }) => {
52 const typeset = new Map<string, ReturnType<MathResolver>>();
53 let probe: HTMLDivElement | null = null;
54 // Pele calls this on every layout, including resizes.
55 return (tex, size) => {
56 const key = `${size}:${tex}`;
57 if (typeset.has(key)) return typeset.get(key);
58 let markup: ReturnType<MathResolver> = null;
59 try {
60 if (!probe) {
61 probe = document.createElement("div");
62 probe.style.cssText =
63 "position:absolute;left:-9999px;visibility:hidden;display:inline-block;white-space:nowrap";
64 document.body.append(probe);
65 }
66 probe.style.fontSize = `${size}px`;
67 probe.innerHTML = katex.renderToString(tex, {
68 displayMode: true,
69 output: "mathml",
70 throwOnError: true,
71 // No \href, \url, \htmlClass, or other commands that emit active HTML.
72 trust: false,
73 strict: "ignore",
74 maxSize: 20,
75 maxExpand: 1000,
76 });
77 const expression = probe.querySelector("math");
78 // The annotation repeats the TeX source; the sanitizer would keep its text.
79 expression?.querySelector("annotation")?.remove();
80 if (expression) {
81 const { width, height } = expression.getBoundingClientRect();
82 markup = { html: expression.outerHTML, width, height };
83 }
84 } catch {
85 // Unsupported TeX stays readable as its source.
86 }
87 typeset.set(key, markup);
88 return markup;
89 };
90 },
91 () => null,
92 );
93 return mathLoad;
94 }
95
96 // MathML element types KaTeX emits, without annotation (the resolver removes it),
97 // semantics (only a wrapper, so its content is kept), and mglyph (an image).
98 const KATEX_MATHML_TAGS = new Set([
99 "math",
100 "menclose",
101 "mfrac",
102 "mi",
103 "mlabeledtr",
104 "mn",
105 "mo",
106 "mover",
107 "mpadded",
108 "mphantom",
109 "mroot",
110 "mrow",
111 "mspace",
112 "msqrt",
113 "mstyle",
114 "msub",
115 "msubsup",
116 "msup",
117 "mtable",
118 "mtd",
119 "mtext",
120 "mtr",
121 "munder",
122 "munderover",
123 ]);
124 // Presentation attributes KaTeX sets on those elements. The profiles already
125 // cover class, style, width, height, display, and xmlns.
126 const KATEX_MATHML_ATTRIBUTES = new Set([
127 "accent",
128 "accentunder",
129 "columnalign",
130 "columnlines",
131 "columnspacing",
132 "depth",
133 "displaystyle",
134 "fence",
135 "largeop",
136 "linebreak",
137 "linethickness",
138 "lspace",
139 "mathbackground",
140 "mathcolor",
141 "mathsize",
142 "mathvariant",
143 "maxsize",
144 "minsize",
145 "notation",
146 "rowlines",
147 "rowspacing",
148 "rspace",
149 "scriptlevel",
150 "separator",
151 "stretchy",
152 "voffset",
153 ]);
154
155 let purifier: ReturnType<typeof DOMPurify> | null = null;
156
157 // Diagrams can come from untrusted PR descriptions. Pele escapes labels and
158 // links and images are off, so this is defense in depth against anything that
159 // could navigate, run script, or fetch remote content.
160 function sanitizeDiagramSvg(svg: string): Node {
161 purifier ??= DOMPurify(window);
162 return purifier.sanitize(svg, {
163 FORBID_ATTR: ["href", "xlink:href", "src", "srcset"],
164 FORBID_TAGS: ["a", "image", "foreignObject", "style"],
165 USE_PROFILES: { svg: true, svgFilters: true },
166 RETURN_DOM_FRAGMENT: true,
167 });
168 }
169
170 // Pele puts MathML labels in a <foreignObject> with an HTML <div> around them.
171 function sanitizeMathDiagramSvg(svg: string): Node {
172 purifier ??= DOMPurify(window);
173 return purifier.sanitize(svg, {
174 // DOMPurify still only accepts <math> under an HTML parent and checks every
175 // MathML child's namespace.
176 ADD_TAGS: ["foreignObject", ...KATEX_MATHML_TAGS],
177 ADD_ATTR: (attribute, tagName) =>
178 KATEX_MATHML_TAGS.has(tagName) && KATEX_MATHML_ATTRIBUTES.has(attribute),
179 HTML_INTEGRATION_POINTS: { foreignobject: true },
180 FORBID_ATTR: ["href", "xlink:href", "src", "srcset"],
181 FORBID_TAGS: ["a", "img", "image", "script", "style"],
182 USE_PROFILES: { svg: true, svgFilters: true, html: true },
183 RETURN_DOM_FRAGMENT: true,
184 });
185 }
186
187 // Pele colors diagrams through these, which a standalone image cannot inherit.
188 const PELE_COLOR_VARIABLES = [
189 "--pele-bg",
190 "--pele-fg",
191 "--pele-muted",
192 "--pele-line",
193 "--pele-surface",
194 "--pele-surface-alt",
195 "--pele-border",
196 "--pele-accent",
197 "--pele-critical",
198 ...Array.from({ length: 8 }, (_, index) => `--pele-series-${index + 1}`),
199 ];
200
201 let expandedImageUrl: string | null = null;
202
203 /**
204 * A blob URL, unlike a data URL, passes the desktop connect-src policy that media
205 * save and copy actions fetch through.
206 */
207 function diagramImageUrl(svg: SVGSVGElement): string {
208 const element = svg.cloneNode(true) as SVGSVGElement;
209 const computed = getComputedStyle(svg);
210 for (const name of PELE_COLOR_VARIABLES) {
211 const value = computed.getPropertyValue(name).trim();
212 if (value) element.style.setProperty(name, value);
213 }
214 element.style.maxWidth = "none";
215 element.style.backgroundColor = getComputedStyle(document.body).backgroundColor;
216 if (expandedImageUrl) URL.revokeObjectURL(expandedImageUrl);
217 expandedImageUrl = URL.createObjectURL(
218 new Blob([new XMLSerializer().serializeToString(element)], { type: "image/svg+xml" }),
219 );
220 return expandedImageUrl;
221 }
222
223 export function MermaidDiagram({
224 source,
225 onExpand,
226 }: {
227 source: string;
228 onExpand: (imageUrl: string) => void;
229 }) {
230 const gt = useGT();
231 const [, setAttempt] = useState(0);
232 const [renderError, setRenderError] = useState<string | null>(null);
233 const trimmedSource = source.trim();
234 const core = use(loadCore());
235 const type = core.status === "loaded" ? detectDiagramType(core.pele, trimmedSource) : null;
236 const load = core.status === "loaded" && type ? use(loadDiagramType(core.pele, type)) : core;
237 const math = trimmedSource.includes("$$") ? use(loadMath()) : null;
238
239 // Re-created, and so remounted, whenever the renderer, math support or source changes.
240 const mountDiagram = (container: HTMLSpanElement) => {
241 if (load.status !== "loaded") return;
242 const mounted = load.pele.mount(container, trimmedSource, {
243 links: false,
244 images: false,
245 zoom: false,
246 // Keep the author's direction; a wide diagram scales down to fit instead of turning vertical.
247 autoDirection: false,
248 ...(math ? { math, sanitize: sanitizeMathDiagramSvg } : { sanitize: sanitizeDiagramSvg }),
249 onRender: () => setRenderError(null),
250 onError: (error) =>
251 setRenderError(
252 error instanceof Error ? error.message : gt("The diagram could not be rendered."),
253 ),
254 });
255 return () => mounted.destroy();
256 };
257
258 if (load.status === "failed") {
259 return (
260 <DiagramError
261 message={gt("The diagram renderer failed to load.")}
262 source={source}
263 onRetry={() => {
264 if (core.status === "failed") coreLoad = null;
265 if (type) diagramLoads.delete(type);
266 setAttempt((attempt) => attempt + 1);
267 }}
268 />
269 );
270 }
271
272 return (
273 <div
274 className="chat-markdown-mermaid overflow-x-auto"
275 data-markdown-mermaid=""
276 data-markdown-copy={serializeCodeBlockToMarkdown(source, "mermaid")}
277 >
278 {renderError ? <DiagramError message={renderError} source={source} /> : null}
279 <button
280 type="button"
281 aria-label={gt("Expand diagram")}
282 hidden={renderError !== null}
283 className="block w-full cursor-zoom-in rounded-md focus-visible:outline-2 focus-visible:outline-ring"
284 onClick={(event) => {
285 const svg = event.currentTarget.querySelector("svg");
286 if (svg) onExpand(diagramImageUrl(svg));
287 }}
288 >
289 <span ref={mountDiagram} className="flex w-full justify-center" />
290 </button>
291 </div>
292 );
293 }
294
295 function DiagramError({
296 message,
297 source,
298 onRetry,
299 }: {
300 message: string;
301 source: string;
302 onRetry?: () => void;
303 }) {
304 return (
305 <div>
306 <div className="flex items-center justify-between gap-2">
307 <p className="m-0 text-xs text-destructive">
308 <T>
309 Unable to render diagram: <Var>{message}</Var>
310 </T>
311 </p>
312 {onRetry ? (
313 <Button type="button" variant="ghost" size="xs" onClick={onRetry}>
314 <T>Retry</T>
315 </Button>
316 ) : null}
317 </div>
318 <pre
319 data-thread-find-ignore
320 className="mt-2 mb-0 overflow-auto font-mono text-xs whitespace-pre-wrap"
321 >
322 {source}
323 </pre>
324 </div>
325 );
326 }