Open History to see the last commit
1import DOMPurify from "dompurify";
2import type { Mermaid } from "mermaid";
3import { use, useState } from "react";
4
5import { Button } from "../ui/button";
6
7type MermaidRenderResult =
8 | { readonly status: "rendered"; readonly svg: string }
9 | { readonly status: "error"; readonly message: string; readonly retryable: boolean };
10
11let mermaidModulePromise: Promise<Mermaid> | null = null;
12let renderQueue: Promise<unknown> = Promise.resolve();
13let nextDiagramId = 0;
14const MAX_CACHED_RENDERS = 64;
15// Pending renders are never evicted, because use() must get the same promise on
16// retry.
17const renderCache = new Map<string, Promise<MermaidRenderResult>>();
18const settledRenders = new WeakSet<Promise<MermaidRenderResult>>();
19
20function loadMermaid(): Promise<Mermaid> {
21 mermaidModulePromise ??= import("mermaid")
22 .then((module) => module.default)
23 .catch((error: unknown) => {
24 mermaidModulePromise = null;
25 throw error;
26 });
27 return mermaidModulePromise;
28}
29
30const REMOTE_CSS_URL = /url\(\s*(?!['"]?#)[^)]*\)/gi;
31let purifier: ReturnType<typeof DOMPurify> | null = null;
32
33// Mermaid renders $$...$$ labels with KaTeX's MathML output. These are KaTeX's
34// MathML element types, without annotation (Mermaid strips it), semantics (only
35// a wrapper, so its content is kept), and mglyph (a trusted-input image).
36const KATEX_MATHML_TAGS = new Set([
37 "math",
38 "menclose",
39 "mfrac",
40 "mi",
41 "mlabeledtr",
42 "mn",
43 "mo",
44 "mover",
45 "mpadded",
46 "mphantom",
47 "mroot",
48 "mrow",
49 "mspace",
50 "msqrt",
51 "mstyle",
52 "msub",
53 "msubsup",
54 "msup",
55 "mtable",
56 "mtd",
57 "mtext",
58 "mtr",
59 "munder",
60 "munderover",
61]);
62// Presentation attributes KaTeX sets on those elements. The existing profiles
63// already cover class, style, width, height, display, and xmlns.
64const KATEX_MATHML_ATTRIBUTES = new Set([
65 "accent",
66 "accentunder",
67 "columnalign",
68 "columnlines",
69 "columnspacing",
70 "depth",
71 "displaystyle",
72 "fence",
73 "largeop",
74 "linebreak",
75 "linethickness",
76 "lspace",
77 "mathbackground",
78 "mathcolor",
79 "mathsize",
80 "mathvariant",
81 "maxsize",
82 "minsize",
83 "notation",
84 "rowlines",
85 "rowspacing",
86 "rspace",
87 "scriptlevel",
88 "separator",
89 "stretchy",
90 "voffset",
91]);
92
93// Diagrams can come from untrusted PR descriptions, so strip anything that can
94// navigate, run script, or fetch remote content on top of Mermaid's own strict
95// sanitization.
96export function sanitizeMermaidSvg(svg: string): string {
97 if (!purifier) {
98 purifier = DOMPurify(window);
99 purifier.addHook("uponSanitizeElement", (node, data) => {
100 if (data.tagName === "style" && node.textContent) {
101 node.textContent = node.textContent.replace(REMOTE_CSS_URL, "none");
102 }
103 });
104 purifier.addHook("uponSanitizeAttribute", (_node, data) => {
105 if (data.attrName === "style")
106 data.attrValue = data.attrValue.replace(REMOTE_CSS_URL, "none");
107 });
108 }
109 const sanitized = purifier.sanitize(svg, {
110 // DOMPurify still only accepts <math> under an HTML parent, here the label
111 // <div> inside <foreignObject>, and checks every MathML child's namespace.
112 ADD_TAGS: ["foreignObject", ...KATEX_MATHML_TAGS],
113 ADD_ATTR: (attribute, tagName) =>
114 KATEX_MATHML_TAGS.has(tagName) && KATEX_MATHML_ATTRIBUTES.has(attribute),
115 HTML_INTEGRATION_POINTS: { foreignobject: true },
116 FORBID_ATTR: ["href", "xlink:href", "src", "srcset"],
117 FORBID_TAGS: ["a", "img", "image", "script"],
118 USE_PROFILES: { svg: true, svgFilters: true, html: true },
119 });
120 // The expanded image parses this as XML, which has no entity. KaTeX
121 // writes spaces in math as U+00A0, which HTML serialization turns into .
122 return sanitized.replaceAll(" ", " ");
123}
124
125// Mermaid also lazy-loads diagram chunks inside render(); losing the network
126// there is worth a retry, unlike a syntax error.
127const CHUNK_LOAD_ERROR = /dynamically imported module|importing a module script|failed to fetch/i;
128
129async function renderMermaid(
130 source: string,
131 theme: "light" | "dark",
132): Promise<MermaidRenderResult> {
133 const id = `mermaid-diagram-${nextDiagramId++}`;
134 let mermaid: Mermaid;
135 try {
136 mermaid = await loadMermaid();
137 } catch {
138 return { status: "error", message: "Mermaid failed to load.", retryable: true };
139 }
140 try {
141 // initialize() mutates global config, so renders run one at a time.
142 mermaid.initialize({
143 startOnLoad: false,
144 securityLevel: "strict",
145 suppressErrorRendering: true,
146 // HTML labels and theme CSS are mounted while Mermaid lays the diagram
147 // out, before sanitizing, so diagram directives must not set them.
148 secure: [
149 "secure",
150 "securityLevel",
151 "startOnLoad",
152 "maxTextSize",
153 "suppressErrorRendering",
154 "maxEdges",
155 "htmlLabels",
156 "themeCSS",
157 ],
158 htmlLabels: false,
159 flowchart: { htmlLabels: false },
160 theme: theme === "dark" ? "dark" : "default",
161 fontFamily: getComputedStyle(document.body).fontFamily,
162 });
163 const { svg } = await mermaid.render(id, source);
164 return { status: "rendered", svg: sanitizeMermaidSvg(svg) };
165 } catch (error) {
166 const message = error instanceof Error ? error.message : "The diagram could not be rendered.";
167 return { status: "error", message, retryable: CHUNK_LOAD_ERROR.test(message) };
168 } finally {
169 document.getElementById(`d${id}`)?.remove();
170 }
171}
172
173function evictSettledRenders() {
174 for (const [key, result] of renderCache) {
175 if (renderCache.size <= MAX_CACHED_RENDERS) return;
176 if (settledRenders.has(result)) renderCache.delete(key);
177 }
178}
179
180function mermaidRenderKey(source: string, theme: "light" | "dark") {
181 return `${theme}\n${source}`;
182}
183
184function mermaidRenderPromise(source: string, theme: "light" | "dark") {
185 const key = mermaidRenderKey(source, theme);
186 const cached = renderCache.get(key);
187 if (cached) {
188 renderCache.delete(key);
189 renderCache.set(key, cached);
190 return cached;
191 }
192 const result = renderQueue.then(() => renderMermaid(source, theme));
193 renderQueue = result;
194 void result.then(() => {
195 settledRenders.add(result);
196 evictSettledRenders();
197 });
198 renderCache.set(key, result);
199 evictSettledRenders();
200 return result;
201}
202
203let expandedImageUrl: string | null = null;
204
205/**
206 * A blob URL, unlike a data URL, passes the desktop connect-src policy that media
207 * save and copy actions fetch through.
208 */
209function mermaidImageUrl(svg: string): string {
210 const svgDocument = new DOMParser().parseFromString(svg, "image/svg+xml");
211 const element = svgDocument.documentElement;
212 const viewBox = element.getAttribute("viewBox")?.trim().split(/\s+/).map(Number);
213 if (viewBox?.length === 4 && viewBox.every(Number.isFinite)) {
214 element.setAttribute("width", String(viewBox[2]));
215 element.setAttribute("height", String(viewBox[3]));
216 }
217 element.setAttribute("xmlns", "http://www.w3.org/2000/svg");
218 element.style.maxWidth = "none";
219 // A standalone image inherits nothing from the page, including the text color
220 // that HTML labels such as math use.
221 const { backgroundColor, color } = getComputedStyle(document.body);
222 element.style.backgroundColor = backgroundColor;
223 element.style.color = color;
224 if (expandedImageUrl) URL.revokeObjectURL(expandedImageUrl);
225 expandedImageUrl = URL.createObjectURL(
226 new Blob([new XMLSerializer().serializeToString(element)], { type: "image/svg+xml" }),
227 );
228 return expandedImageUrl;
229}
230
231export function MermaidDiagram({
232 source,
233 theme,
234 onExpand,
235}: {
236 source: string;
237 theme: "light" | "dark";
238 onExpand: (imageUrl: string) => void;
239}) {
240 const [, setAttempt] = useState(0);
241 const result = use(mermaidRenderPromise(source.trim(), theme));
242
243 if (result.status === "error") {
244 return (
245 <div>
246 <div className="flex items-center justify-between gap-2">
247 <p className="m-0 text-xs text-destructive">Unable to render diagram: {result.message}</p>
248 {result.retryable ? (
249 <Button
250 type="button"
251 variant="ghost"
252 size="xs"
253 onClick={() => {
254 renderCache.delete(mermaidRenderKey(source.trim(), theme));
255 setAttempt((attempt) => attempt + 1);
256 }}
257 >
258 Retry
259 </Button>
260 ) : null}
261 </div>
262 <pre
263 data-thread-find-ignore
264 className="mt-2 mb-0 overflow-auto font-mono text-xs whitespace-pre-wrap"
265 >
266 {source}
267 </pre>
268 </div>
269 );
270 }
271
272 return (
273 <div className="overflow-x-auto">
274 <button
275 type="button"
276 aria-label="Expand diagram"
277 className="flex w-full cursor-zoom-in justify-center rounded-md focus-visible:outline-2 focus-visible:outline-ring [&_svg]:h-auto [&_svg]:max-w-full"
278 onClick={() => onExpand(mermaidImageUrl(result.svg))}
279 dangerouslySetInnerHTML={{ __html: result.svg }}
280 />
281 </div>
282 );
283}