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