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// Keyed by the full source so distinct diagrams never share an entry. Pending
16// renders are never evicted, because use() must get the same promise on retry.
17const renderCache = new Map<string, Promise<MermaidRenderResult>>();
18const settledRenders = new WeakSet<Promise<MermaidRenderResult>>();
19
20// Mermaid is ~1MB, so it only loads once a diagram is actually shown.
21function loadMermaid(): Promise<Mermaid> {
22 mermaidModulePromise ??= import("mermaid")
23 .then((module) => module.default)
24 .catch((error: unknown) => {
25 mermaidModulePromise = null;
26 throw error;
27 });
28 return mermaidModulePromise;
29}
30
31const REMOTE_CSS_URL = /url\(\s*(?!['"]?#)[^)]*\)/gi;
32let purifier: ReturnType<typeof DOMPurify> | null = null;
33
34// Diagrams can come from untrusted PR descriptions, so strip anything that can
35// navigate, run script, or fetch remote content on top of Mermaid's own strict
36// sanitization. CSS keeps only local url(#id) references; label text is untouched.
37function sanitizeMermaidSvg(svg: string): string {
38 if (!purifier) {
39 purifier = DOMPurify(window);
40 purifier.addHook("uponSanitizeElement", (node, data) => {
41 if (data.tagName === "style" && node.textContent) {
42 node.textContent = node.textContent.replace(REMOTE_CSS_URL, "none");
43 }
44 });
45 purifier.addHook("uponSanitizeAttribute", (_node, data) => {
46 if (data.attrName === "style")
47 data.attrValue = data.attrValue.replace(REMOTE_CSS_URL, "none");
48 });
49 }
50 return purifier.sanitize(svg, {
51 ADD_TAGS: ["foreignObject"],
52 HTML_INTEGRATION_POINTS: { foreignobject: true },
53 FORBID_ATTR: ["href", "xlink:href", "src", "srcset"],
54 FORBID_TAGS: ["a", "img", "image", "script"],
55 USE_PROFILES: { svg: true, svgFilters: true, html: true },
56 });
57}
58
59// Mermaid also lazy-loads diagram chunks inside render(); losing the network
60// there is worth a retry, unlike a syntax error.
61const CHUNK_LOAD_ERROR = /dynamically imported module|importing a module script|failed to fetch/i;
62
63async function renderMermaid(
64 source: string,
65 theme: "light" | "dark",
66): Promise<MermaidRenderResult> {
67 const id = `mermaid-diagram-${nextDiagramId++}`;
68 let mermaid: Mermaid;
69 try {
70 mermaid = await loadMermaid();
71 } catch {
72 return { status: "error", message: "Mermaid failed to load.", retryable: true };
73 }
74 try {
75 // initialize() mutates global config, so renders run one at a time.
76 mermaid.initialize({
77 startOnLoad: false,
78 securityLevel: "strict",
79 suppressErrorRendering: true,
80 // HTML labels and theme CSS are mounted while Mermaid lays the diagram
81 // out, before sanitizing, so diagram directives must not set them.
82 secure: [
83 "secure",
84 "securityLevel",
85 "startOnLoad",
86 "maxTextSize",
87 "suppressErrorRendering",
88 "maxEdges",
89 "htmlLabels",
90 "themeCSS",
91 ],
92 htmlLabels: false,
93 flowchart: { htmlLabels: false },
94 theme: theme === "dark" ? "dark" : "default",
95 fontFamily: getComputedStyle(document.body).fontFamily,
96 });
97 const { svg } = await mermaid.render(id, source);
98 return { status: "rendered", svg: sanitizeMermaidSvg(svg) };
99 } catch (error) {
100 const message = error instanceof Error ? error.message : "The diagram could not be rendered.";
101 return { status: "error", message, retryable: CHUNK_LOAD_ERROR.test(message) };
102 } finally {
103 document.getElementById(`d${id}`)?.remove();
104 }
105}
106
107function evictSettledRenders() {
108 for (const [key, result] of renderCache) {
109 if (renderCache.size <= MAX_CACHED_RENDERS) return;
110 if (settledRenders.has(result)) renderCache.delete(key);
111 }
112}
113
114function mermaidRenderKey(source: string, theme: "light" | "dark") {
115 return `${theme}\n${source}`;
116}
117
118function mermaidRenderPromise(source: string, theme: "light" | "dark") {
119 const key = mermaidRenderKey(source, theme);
120 const cached = renderCache.get(key);
121 if (cached) {
122 renderCache.delete(key);
123 renderCache.set(key, cached);
124 return cached;
125 }
126 const result = renderQueue.then(() => renderMermaid(source, theme));
127 renderQueue = result;
128 void result.then(() => {
129 settledRenders.add(result);
130 evictSettledRenders();
131 });
132 renderCache.set(key, result);
133 evictSettledRenders();
134 return result;
135}
136
137let expandedImageUrl: string | null = null;
138
139/**
140 * Converts a rendered diagram into a standalone image with fixed size and background.
141 * A blob URL, unlike a data URL, passes the desktop connect-src policy that media
142 * save and copy actions fetch through. Only one diagram is expanded at a time, so
143 * the previous URL is released.
144 */
145function mermaidImageUrl(svg: string): string {
146 const svgDocument = new DOMParser().parseFromString(svg, "image/svg+xml");
147 const element = svgDocument.documentElement;
148 const viewBox = element.getAttribute("viewBox")?.trim().split(/\s+/).map(Number);
149 if (viewBox?.length === 4 && viewBox.every(Number.isFinite)) {
150 element.setAttribute("width", String(viewBox[2]));
151 element.setAttribute("height", String(viewBox[3]));
152 }
153 element.setAttribute("xmlns", "http://www.w3.org/2000/svg");
154 element.style.maxWidth = "none";
155 element.style.backgroundColor = getComputedStyle(document.body).backgroundColor;
156 if (expandedImageUrl) URL.revokeObjectURL(expandedImageUrl);
157 expandedImageUrl = URL.createObjectURL(
158 new Blob([new XMLSerializer().serializeToString(element)], { type: "image/svg+xml" }),
159 );
160 return expandedImageUrl;
161}
162
163/** Suspends until the diagram renders; failures show the parser message above the source. */
164export function MermaidDiagram({
165 source,
166 theme,
167 onExpand,
168}: {
169 source: string;
170 theme: "light" | "dark";
171 onExpand: (imageUrl: string) => void;
172}) {
173 const [, setAttempt] = useState(0);
174 const result = use(mermaidRenderPromise(source.trim(), theme));
175
176 if (result.status === "error") {
177 return (
178 <div>
179 <div className="flex items-center justify-between gap-2">
180 <p className="m-0 text-xs text-destructive">Unable to render diagram: {result.message}</p>
181 {result.retryable ? (
182 <Button
183 type="button"
184 variant="ghost"
185 size="xs"
186 onClick={() => {
187 renderCache.delete(mermaidRenderKey(source.trim(), theme));
188 setAttempt((attempt) => attempt + 1);
189 }}
190 >
191 Retry
192 </Button>
193 ) : null}
194 </div>
195 {/* Find matches the source through the hidden copy beside the diagram. */}
196 <pre
197 data-thread-find-ignore
198 className="mt-2 mb-0 overflow-auto font-mono text-xs whitespace-pre-wrap"
199 >
200 {source}
201 </pre>
202 </div>
203 );
204 }
205
206 return (
207 <div className="overflow-x-auto">
208 <button
209 type="button"
210 aria-label="Expand diagram"
211 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"
212 onClick={() => onExpand(mermaidImageUrl(result.svg))}
213 dangerouslySetInnerHTML={{ __html: result.svg }}
214 />
215 </div>
216 );
217}