Skip to content

Commit 27aeb7d

Browse files
committed
feat(web): typeset math in Mermaid labels with pele 1.8
1 parent 359c76c commit 27aeb7d

4 files changed

Lines changed: 138 additions & 9 deletions

File tree

‎apps/web/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@
6666
"lucide": "^0.564.0",
6767
"lucide-react": "^0.564.0",
6868
"morphicons": "^1.7.1",
69-
"pele": "^1.6.0",
69+
"pele": "^1.8.0",
7070
"react": "catalog:",
7171
"react-dom": "catalog:",
7272
"react-markdown": "^10.1.0",

‎apps/web/src/components/chat/MermaidDiagram.tsx‎

Lines changed: 131 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import DOMPurify from "dompurify";
2-
import type { DiagramType } from "pele/lazy";
2+
import type { DiagramType, MathResolver } from "pele/lazy";
33
import { use, useLayoutEffect, useRef, useState } from "react";
44

55
import { serializeCodeBlockToMarkdown } from "../../markdown-clipboard";
@@ -41,6 +41,116 @@ function detectDiagramType(pele: Pele, source: string): DiagramType | null {
4141
}
4242
}
4343

44+
let mathLoad: Promise<MathResolver | null> | null = null;
45+
46+
// Pele has no typesetter, so $$...$$ labels go through the KaTeX the chat
47+
// already uses for math. It only loads for diagrams that contain math.
48+
function loadMath(): Promise<MathResolver | null> {
49+
mathLoad ??= import("katex").then(
50+
({ default: katex }) => {
51+
const typeset = new Map<string, ReturnType<MathResolver>>();
52+
let probe: HTMLDivElement | null = null;
53+
// Pele calls this on every layout, including resizes.
54+
return (tex, size) => {
55+
const key = `${size}:${tex}`;
56+
if (typeset.has(key)) return typeset.get(key);
57+
let markup: ReturnType<MathResolver> = null;
58+
try {
59+
if (!probe) {
60+
probe = document.createElement("div");
61+
probe.style.cssText =
62+
"position:absolute;left:-9999px;visibility:hidden;display:inline-block;white-space:nowrap";
63+
document.body.append(probe);
64+
}
65+
probe.style.fontSize = `${size}px`;
66+
probe.innerHTML = katex.renderToString(tex, {
67+
displayMode: true,
68+
output: "mathml",
69+
throwOnError: true,
70+
// No \href, \url, \htmlClass, or other commands that emit active HTML.
71+
trust: false,
72+
strict: "ignore",
73+
maxSize: 20,
74+
maxExpand: 1000,
75+
});
76+
const expression = probe.querySelector("math");
77+
// The annotation repeats the TeX source; the sanitizer would keep its text.
78+
expression?.querySelector("annotation")?.remove();
79+
if (expression) {
80+
const { width, height } = expression.getBoundingClientRect();
81+
markup = { html: expression.outerHTML, width, height };
82+
}
83+
} catch {
84+
// Unsupported TeX stays readable as its source.
85+
}
86+
typeset.set(key, markup);
87+
return markup;
88+
};
89+
},
90+
() => null,
91+
);
92+
return mathLoad;
93+
}
94+
95+
// MathML element types KaTeX emits, without annotation (the resolver removes it),
96+
// semantics (only a wrapper, so its content is kept), and mglyph (an image).
97+
const KATEX_MATHML_TAGS = new Set([
98+
"math",
99+
"menclose",
100+
"mfrac",
101+
"mi",
102+
"mlabeledtr",
103+
"mn",
104+
"mo",
105+
"mover",
106+
"mpadded",
107+
"mphantom",
108+
"mroot",
109+
"mrow",
110+
"mspace",
111+
"msqrt",
112+
"mstyle",
113+
"msub",
114+
"msubsup",
115+
"msup",
116+
"mtable",
117+
"mtd",
118+
"mtext",
119+
"mtr",
120+
"munder",
121+
"munderover",
122+
]);
123+
// Presentation attributes KaTeX sets on those elements. The profiles already
124+
// cover class, style, width, height, display, and xmlns.
125+
const KATEX_MATHML_ATTRIBUTES = new Set([
126+
"accent",
127+
"accentunder",
128+
"columnalign",
129+
"columnlines",
130+
"columnspacing",
131+
"depth",
132+
"displaystyle",
133+
"fence",
134+
"largeop",
135+
"linebreak",
136+
"linethickness",
137+
"lspace",
138+
"mathbackground",
139+
"mathcolor",
140+
"mathsize",
141+
"mathvariant",
142+
"maxsize",
143+
"minsize",
144+
"notation",
145+
"rowlines",
146+
"rowspacing",
147+
"rspace",
148+
"scriptlevel",
149+
"separator",
150+
"stretchy",
151+
"voffset",
152+
]);
153+
44154
let purifier: ReturnType<typeof DOMPurify> | null = null;
45155

46156
// Diagrams can come from untrusted PR descriptions. Pele escapes labels and
@@ -56,6 +166,23 @@ function sanitizeDiagramSvg(svg: string): Node {
56166
});
57167
}
58168

169+
// Pele puts MathML labels in a <foreignObject> with an HTML <div> around them.
170+
function sanitizeMathDiagramSvg(svg: string): Node {
171+
purifier ??= DOMPurify(window);
172+
return purifier.sanitize(svg, {
173+
// DOMPurify still only accepts <math> under an HTML parent and checks every
174+
// MathML child's namespace.
175+
ADD_TAGS: ["foreignObject", ...KATEX_MATHML_TAGS],
176+
ADD_ATTR: (attribute, tagName) =>
177+
KATEX_MATHML_TAGS.has(tagName) && KATEX_MATHML_ATTRIBUTES.has(attribute),
178+
HTML_INTEGRATION_POINTS: { foreignobject: true },
179+
FORBID_ATTR: ["href", "xlink:href", "src", "srcset"],
180+
FORBID_TAGS: ["a", "img", "image", "script", "style"],
181+
USE_PROFILES: { svg: true, svgFilters: true, html: true },
182+
RETURN_DOM_FRAGMENT: true,
183+
});
184+
}
185+
59186
// Pele colors diagrams through these, which a standalone image cannot inherit.
60187
const PELE_COLOR_VARIABLES = [
61188
"--pele-bg",
@@ -106,6 +233,7 @@ export function MermaidDiagram({
106233
const core = use(loadCore());
107234
const type = core.status === "loaded" ? detectDiagramType(core.pele, trimmedSource) : null;
108235
const load = core.status === "loaded" && type ? use(loadDiagramType(core.pele, type)) : core;
236+
const math = trimmedSource.includes("$$") ? use(loadMath()) : null;
109237

110238
useLayoutEffect(() => {
111239
const container = containerRef.current;
@@ -116,15 +244,15 @@ export function MermaidDiagram({
116244
zoom: false,
117245
// Keep the author's direction; a wide diagram scales down to fit instead of turning vertical.
118246
autoDirection: false,
119-
sanitize: sanitizeDiagramSvg,
247+
...(math ? { math, sanitize: sanitizeMathDiagramSvg } : { sanitize: sanitizeDiagramSvg }),
120248
onRender: () => setRenderError(null),
121249
onError: (error) =>
122250
setRenderError(
123251
error instanceof Error ? error.message : "The diagram could not be rendered.",
124252
),
125253
});
126254
return () => mounted.destroy();
127-
}, [load, trimmedSource]);
255+
}, [load, math, trimmedSource]);
128256

129257
if (load.status === "failed") {
130258
return (

‎pnpm-lock.yaml‎

Lines changed: 5 additions & 5 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎pnpm-workspace.yaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,7 @@ minimumReleaseAgeExclude:
218218
- "@react-native/[email protected]"
219219
220220
221+
221222

222223
overrides:
223224
# Keep on the patched version. A fresh resolution would take a newer release and

0 commit comments

Comments
 (0)