feat(web): render mermaid code blocks as diagrams #15067
Mergedmaria-rcksmerged 6 commits into
main fromrefs/pull/15067/headmerged by maria-rcks View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/web/src/components/chat/MermaidDiagram.tsx line 73OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +53,21 @@53+ fontFamily: getComputedStyle(document.body).fontFamily,54+ });55+ const { svg } = await mermaid.render(id, source);56+ return { status: "rendered", svg: sanitizeMermaidSvg(svg) };57+ } catch (error) {58+ return {59+ status: "error",60+ message: error instanceof Error ? error.message : "The diagram could not be rendered.",61+ };62+ } finally {63+ document.getElementById(`d${id}`)?.remove();64+ }65+}66+67+function mermaidRenderPromise(source: string, theme: "light" | "dark") {68+ const key = `${fnv1a32(source).toString(36)}:${source.length}:${theme}`;69+ const cached = renderCache.get(key);70+ if (cached) return cached;71+ const result = renderQueue.then(() => renderMermaid(source, theme));72+ renderQueue = result;73+ renderCache.set(key, result, source.length * 8);apps/web/src/components/chat/MermaidDiagram.tsx lines 68 to 68OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +48,21 @@48+ securityLevel: "strict",49+ suppressErrorRendering: true,50+ htmlLabels: false,51+ flowchart: { htmlLabels: false },52+ theme: theme === "dark" ? "dark" : "default",53+ fontFamily: getComputedStyle(document.body).fontFamily,54+ });55+ const { svg } = await mermaid.render(id, source);56+ return { status: "rendered", svg: sanitizeMermaidSvg(svg) };57+ } catch (error) {58+ return {59+ status: "error",60+ message: error instanceof Error ? error.message : "The diagram could not be rendered.",61+ };62+ } finally {63+ document.getElementById(`d${id}`)?.remove();64+ }65+}66+67+function mermaidRenderPromise(source: string, theme: "light" | "dark") {68+ const key = `${fnv1a32(source).toString(36)}:${source.length}:${theme}`;apps/web/src/components/chat/MermaidDiagram.tsx line 73OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +53,21 @@53+ fontFamily: getComputedStyle(document.body).fontFamily,54+ });55+ const { svg } = await mermaid.render(id, source);56+ return { status: "rendered", svg: sanitizeMermaidSvg(svg) };57+ } catch (error) {58+ return {59+ status: "error",60+ message: error instanceof Error ? error.message : "The diagram could not be rendered.",61+ };62+ } finally {63+ document.getElementById(`d${id}`)?.remove();64+ }65+}66+67+function mermaidRenderPromise(source: string, theme: "light" | "dark") {68+ const key = `${fnv1a32(source).toString(36)}:${source.length}:${theme}`;69+ const cached = renderCache.get(key);70+ if (cached) return cached;71+ const result = renderQueue.then(() => renderMermaid(source, theme));72+ renderQueue = result;73+ renderCache.set(key, result, source.length * 8);
juliusmarminge added labelsmacroscope-review
- apps/web/src/components/chat/MermaidDiagram.tsx line 174Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +82,21 @@82+ if (viewBox?.length === 4 && viewBox.every(Number.isFinite)) {83+ element.setAttribute("width", String(viewBox[2]));84+ element.setAttribute("height", String(viewBox[3]));85+ }86+ element.setAttribute("xmlns", "http://www.w3.org/2000/svg");87+ element.style.maxWidth = "none";88+ element.style.backgroundColor = background;89+ return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(element))}`;90+}91+92+/** Suspends until the diagram renders; failures show the parser message above the source. */93+export function MermaidDiagram({94+ source,95+ theme,96+ onExpand,97+}: {98+ source: string;99+ theme: "light" | "dark";100+ onExpand: (imageUrl: string) => void;101+}) {102+ const result = use(mermaidRenderPromise(source.trim(), theme));
- apps/web/src/components/chat/MermaidDiagram.tsx line 91Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +50,21 @@50+ mermaid = await loadMermaid();51+ } catch {52+ return { status: "error", message: "Mermaid failed to load.", retryable: true };53+ }54+ try {55+ // initialize() mutates global config, so renders run one at a time.56+ mermaid.initialize({57+ startOnLoad: false,58+ securityLevel: "strict",59+ suppressErrorRendering: true,60+ // HTML labels are mounted while Mermaid lays them out, before sanitizing,61+ // so diagram directives must not turn them back on.62+ secure: [63+ "secure",64+ "securityLevel",65+ "startOnLoad",66+ "maxTextSize",67+ "suppressErrorRendering",68+ "maxEdges",69+ "htmlLabels",70+ ],apps/web/src/components/chat/MermaidDiagram.tsx line 138OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +118,21 @@118+const imageUrls = new WeakMap<MermaidRenderResult, string>();119+120+/**121+ * Converts a rendered diagram into a standalone image with fixed size and background.122+ * A blob URL, unlike a data URL, passes the desktop connect-src policy that media123+ * save and copy actions fetch through.124+ */125+function mermaidImageUrl(result: MermaidRenderResult & { status: "rendered" }): string {126+ const cached = imageUrls.get(result);127+ if (cached) return cached;128+ const svgDocument = new DOMParser().parseFromString(result.svg, "image/svg+xml");129+ const element = svgDocument.documentElement;130+ const viewBox = element.getAttribute("viewBox")?.trim().split(/\s+/).map(Number);131+ if (viewBox?.length === 4 && viewBox.every(Number.isFinite)) {132+ element.setAttribute("width", String(viewBox[2]));133+ element.setAttribute("height", String(viewBox[3]));134+ }135+ element.setAttribute("xmlns", "http://www.w3.org/2000/svg");136+ element.style.maxWidth = "none";137+ element.style.backgroundColor = getComputedStyle(document.body).backgroundColor;138+ const url = URL.createObjectURL(
- apps/web/src/components/chat/MermaidDiagram.tsx line 40OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +20,21 @@20+ mermaidModulePromise ??= import("mermaid")21+ .then((module) => module.default)22+ .catch((error: unknown) => {23+ mermaidModulePromise = null;24+ throw error;25+ });26+ return mermaidModulePromise;27+}28+29+// Diagrams can come from untrusted PR descriptions, so strip anything that can30+// navigate, run script, or fetch remote content on top of Mermaid's own strict31+// sanitization. HTML labels inside foreignObject stay, since authors can enable32+// them per diagram. Only local url(#id) references survive in CSS.33+function sanitizeMermaidSvg(svg: string): string {34+ return DOMPurify.sanitize(svg, {35+ ADD_TAGS: ["foreignObject"],36+ HTML_INTEGRATION_POINTS: { foreignobject: true },37+ FORBID_ATTR: ["href", "xlink:href", "src", "srcset"],38+ FORBID_TAGS: ["a", "img", "image", "script"],39+ USE_PROFILES: { svg: true, svgFilters: true, html: true },40+ }).replace(/url\(\s*(?!['"]?#)[^)]*\)/gi, "none");apps/web/src/components/chat/MermaidDiagram.tsx line 107OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +87,21 @@87+}88+89+function mermaidRenderPromise(source: string, theme: "light" | "dark") {90+ const key = `${theme}\n${source}`;91+ const cached = renderCache.get(key);92+ if (cached) {93+ renderCache.delete(key);94+ renderCache.set(key, cached);95+ return cached;96+ }97+ const result = renderQueue.then(() => renderMermaid(source, theme));98+ renderQueue = result;99+ void result.then((settled) => {100+ settledRenders.add(result);101+ // A failed load retries the next time the diagram mounts.102+ if (settled.status === "error" && settled.retryable && renderCache.get(key) === result) {103+ renderCache.delete(key);104+ }105+ });106+ renderCache.set(key, result);107+ if (renderCache.size > MAX_CACHED_RENDERS) {apps/web/src/components/chat/MermaidDiagram.tsx lines 138 to 141OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +121,21 @@121+ * Converts a rendered diagram into a standalone image with fixed size and background.122+ * A blob URL, unlike a data URL, passes the desktop connect-src policy that media123+ * save and copy actions fetch through.124+ */125+function mermaidImageUrl(result: MermaidRenderResult & { status: "rendered" }): string {126+ const cached = imageUrls.get(result);127+ if (cached) return cached;128+ const svgDocument = new DOMParser().parseFromString(result.svg, "image/svg+xml");129+ const element = svgDocument.documentElement;130+ const viewBox = element.getAttribute("viewBox")?.trim().split(/\s+/).map(Number);131+ if (viewBox?.length === 4 && viewBox.every(Number.isFinite)) {132+ element.setAttribute("width", String(viewBox[2]));133+ element.setAttribute("height", String(viewBox[3]));134+ }135+ element.setAttribute("xmlns", "http://www.w3.org/2000/svg");136+ element.style.maxWidth = "none";137+ element.style.backgroundColor = getComputedStyle(document.body).backgroundColor;138+ const url = URL.createObjectURL(139+ new Blob([new XMLSerializer().serializeToString(element)], { type: "image/svg+xml" }),140+ );141+ imageUrls.set(result, url);
- apps/web/src/components/chat/MermaidDiagram.tsx lines 97 to 98Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +77,21 @@77+ startOnLoad: false,78+ securityLevel: "strict",79+ suppressErrorRendering: true,80+ // HTML labels are mounted while Mermaid lays them out, before sanitizing,81+ // so diagram directives must not turn them back on.82+ secure: [83+ "secure",84+ "securityLevel",85+ "startOnLoad",86+ "maxTextSize",87+ "suppressErrorRendering",88+ "maxEdges",89+ "htmlLabels",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) };
maria-rcks merged this5e35272
maria-rcks closed this
Sign in to join this conversation.








macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed