Open History to see the last commit
1import DOMPurify from "dompurify";
2import type { DiagramType, MathResolver } from "pele/lazy";
3import { use, 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 trimmedSource = source.trim();
232 const core = use(loadCore());
233 const type = core.status === "loaded" ? detectDiagramType(core.pele, trimmedSource) : null;
234 const load = core.status === "loaded" && type ? use(loadDiagramType(core.pele, type)) : core;
235 const math = trimmedSource.includes("$$") ? use(loadMath()) : null;
236
237 // Re-created, and so remounted, whenever the renderer, math support or source changes.
238 const mountDiagram = (container: HTMLSpanElement) => {
239 if (load.status !== "loaded") return;
240 const mounted = load.pele.mount(container, trimmedSource, {
241 links: false,
242 images: false,
243 zoom: false,
244 // Keep the author's direction; a wide diagram scales down to fit instead of turning vertical.
245 autoDirection: false,
246 ...(math ? { math, sanitize: sanitizeMathDiagramSvg } : { sanitize: sanitizeDiagramSvg }),
247 onRender: () => setRenderError(null),
248 onError: (error) =>
249 setRenderError(
250 error instanceof Error ? error.message : "The diagram could not be rendered.",
251 ),
252 });
253 return () => mounted.destroy();
254 };
255
256 if (load.status === "failed") {
257 return (
258 <DiagramError
259 message="The diagram renderer failed to load."
260 source={source}
261 onRetry={() => {
262 if (core.status === "failed") coreLoad = null;
263 if (type) diagramLoads.delete(type);
264 setAttempt((attempt) => attempt + 1);
265 }}
266 />
267 );
268 }
269
270 return (
271 <div
272 className="chat-markdown-mermaid overflow-x-auto"
273 data-markdown-mermaid=""
274 data-markdown-copy={serializeCodeBlockToMarkdown(source, "mermaid")}
275 >
276 {renderError ? <DiagramError message={renderError} source={source} /> : null}
277 <button
278 type="button"
279 aria-label="Expand diagram"
280 hidden={renderError !== null}
281 className="block w-full cursor-zoom-in rounded-md focus-visible:outline-2 focus-visible:outline-ring"
282 onClick={(event) => {
283 const svg = event.currentTarget.querySelector("svg");
284 if (svg) onExpand(diagramImageUrl(svg));
285 }}
286 >
287 <span ref={mountDiagram} className="flex w-full justify-center" />
288 </button>
289 </div>
290 );
291}
292
293function DiagramError({
294 message,
295 source,
296 onRetry,
297}: {
298 message: string;
299 source: string;
300 onRetry?: () => void;
301}) {
302 return (
303 <div>
304 <div className="flex items-center justify-between gap-2">
305 <p className="m-0 text-xs text-destructive">Unable to render diagram: {message}</p>
306 {onRetry ? (
307 <Button type="button" variant="ghost" size="xs" onClick={onRetry}>
308 Retry
309 </Button>
310 ) : null}
311 </div>
312 <pre
313 data-thread-find-ignore
314 className="mt-2 mb-0 overflow-auto font-mono text-xs whitespace-pre-wrap"
315 >
316 {source}
317 </pre>
318 </div>
319 );
320}