The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 23, 04:15 UTC
fix(web): show math labels in Mermaid diagrams (#16198)
Nikita Maximilian Grimm committed
Oct 18, 2026 at 21:22 UTC
7b25aed54f31ec211c63b8cf173cb4a31df12768
2 files changed
+143
-4
apps/web/src/components/chat/MermaidDiagram.test.tsx
new
+68
@@ -0,0 +1,68 @@
1
+// @vitest-environment jsdom
2
+
3
+import { describe, expect, it } from "vite-plus/test";
4
+
5
+import { sanitizeMermaidSvg } from "./MermaidDiagram";
6
+
7
+// The label markup Mermaid's sequence diagrams emit for $$...$$ text.
8
+function noteSvg(label: string) {
9
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><foreignObject height="34" width="35" x="57" y="85"><div style="width: fit-content;" xmlns="http://www.w3.org/1999/xhtml"><div style="display: flex; align-items: center; justify-content: center; white-space: nowrap;"><span class="katex">${label}</span></div></div></foreignObject></svg>`;
10
+}
11
+
12
+function sanitize(svg: string) {
13
+ const host = document.createElement("div");
14
+ host.innerHTML = sanitizeMermaidSvg(svg);
15
+ return host;
16
+}
17
+
18
+describe("sanitizeMermaidSvg", () => {
19
+ it("keeps the MathML Mermaid renders for math labels", () => {
20
+ const host = sanitize(
21
+ noteSvg(
22
+ '<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><mrow><mfrac><mi>d</mi><mrow><mi>d</mi><mi>x</mi></mrow></mfrac><mrow><mo fence="true">(</mo><mi mathvariant="bold">v</mi><mo fence="true">)</mo></mrow><msqrt><mn>2</mn></msqrt></mrow></math>',
23
+ ),
24
+ );
25
+
26
+ const math = host.querySelector(".katex > math");
27
+ expect(math?.namespaceURI).toBe("http://www.w3.org/1998/Math/MathML");
28
+ expect(math?.getAttribute("display")).toBe("block");
29
+ expect(math?.querySelector("mfrac")?.textContent).toBe("ddx");
30
+ expect(math?.querySelector("msqrt")?.textContent).toBe("2");
31
+ expect(math?.querySelector("mi[mathvariant='bold']")?.textContent).toBe("v");
32
+ expect(math?.querySelectorAll("mo[fence='true']")).toHaveLength(2);
33
+ });
34
+
35
+ it("keeps spaced math labels parseable as an SVG image", () => {
36
+ // KaTeX renders \text{total cost} with a no-break space.
37
+ const svg = sanitizeMermaidSvg(noteSvg("<math><mrow><mtext>total cost</mtext></mrow></math>"));
38
+
39
+ const image = new DOMParser().parseFromString(svg, "image/svg+xml");
40
+ expect(image.documentElement.localName).toBe("svg");
41
+ expect(image.querySelector("mtext")?.textContent).toBe("total cost");
42
+ });
43
+
44
+ it("strips links, scripts, and MathML outside what KaTeX emits", () => {
45
+ const host = sanitize(
46
+ noteSvg(
47
+ '<math href="javascript:alert(1)"><mi href="javascript:alert(1)" onclick="alert(1)">x</mi><maction actiontype="toggle"><mi>a</mi></maction><mglyph src="https://example.com/a.png"></mglyph><annotation-xml encoding="text/html"><img src="x" onerror="alert(1)"></annotation-xml><semantics><mi>y</mi><annotation encoding="application/x-tex">y</annotation></semantics></math>',
48
+ ),
49
+ );
50
+
51
+ const math = host.querySelector("math");
52
+ expect(math).not.toBeNull();
53
+ expect(math?.querySelector("mi")?.textContent).toBe("x");
54
+ expect(host.querySelector("[href], [onclick], [src], [onerror]")).toBeNull();
55
+ expect(host.querySelector("maction, mglyph, annotation-xml, annotation, semantics, img")).toBe(
56
+ null,
57
+ );
58
+ });
59
+
60
+ it("only accepts math as an HTML label and keeps its attributes on MathML", () => {
61
+ const host = sanitize(
62
+ '<svg xmlns="http://www.w3.org/2000/svg"><math><mi>x</mi></math><text mathvariant="bold" fence="true">label</text></svg>',
63
+ );
64
+
65
+ expect(host.querySelector("math, mi")).toBeNull();
66
+ expect(host.querySelector("text")?.getAttributeNames()).toEqual([]);
67
+ });
68
+});
apps/web/src/components/chat/MermaidDiagram.tsx
+75
-4
@@ -30,10 +30,70 @@ function loadMermaid(): Promise<Mermaid> {
30
const REMOTE_CSS_URL = /url\(\s*(?!['"]?#)[^)]*\)/gi;
31
let 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).
36
+const 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.
64
+const 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.
36
-function sanitizeMermaidSvg(svg: string): string {
96
+export function sanitizeMermaidSvg(svg: string): string {
97
if (!purifier) {
98
purifier = DOMPurify(window);
99
purifier.addHook("uponSanitizeElement", (node, data) => {
@@ -46,13 +106,20 @@ function sanitizeMermaidSvg(svg: string): string {
106
data.attrValue = data.attrValue.replace(REMOTE_CSS_URL, "none");
107
});
108
}
49
- return purifier.sanitize(svg, {
50
- ADD_TAGS: ["foreignObject"],
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
@@ -149,7 +216,11 @@ function mermaidImageUrl(svg: string): string {
216
}
217
element.setAttribute("xmlns", "http://www.w3.org/2000/svg");
218
element.style.maxWidth = "none";
152
- element.style.backgroundColor = getComputedStyle(document.body).backgroundColor;
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" }),