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