fix: Math formulas not rendering correctly in HTML/PDF output (#12939)

* fix: Math formulas not rendering correctly in HTML/PDF output

* Fix version exactly.

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Tom MoorandCopilot Autofix powered by AI authored and GitHub committed 2026-07-08 08:50:57 +00:00
1 parent db1d93f9b5
commit d67e682594
2 files changed
+31

No files matched your search

@@ -126,6 +126,23 @@ describe("DocumentHelper", () => {
expect(result).not.toMatch(/<script[^>]*nonce="/);
});
it("should render math and include the KaTeX stylesheet", async () => {
const document = await buildDocument({
text: "Inline $E=mc^2$ and block:\n\n$$\n\\frac{1}{2}\n$$\n",
});
const result = await DocumentHelper.toHTML(document);
expect(result).toContain('class="katex"');
expect(result).toContain("katex.min.css");
});
it("should not include the KaTeX stylesheet without math", async () => {
const document = await buildDocument({
text: "This is a test paragraph",
});
const result = await DocumentHelper.toHTML(document);
expect(result).not.toContain("katex.min.css");
});
it("should render diff classes when changes provided", async () => {
const doc1 = await buildDocument({ text: "Hello world" });
const doc2 = await buildDocument({ text: "Hello modified world" });
@@ -77,6 +77,11 @@ export type MentionAttrs = {
const pluginsWithSafeDecorations = new WeakSet<Plugin>();
// KaTeX renders math server-side during HTML export, but relies on this
// stylesheet (loaded dynamically in the app) to position glyphs correctly.
const katexStylesheetUrl =
"https://cdn.jsdelivr.net/npm/katex@0.16.45/dist/katex.min.css";
function isDecorationSource(value: unknown): value is DecorationSource {
if (typeof value !== "object" || value === null) {
return false;
@@ -683,6 +688,15 @@ export class ProsemirrorHelper extends SharedProsemirrorHelper {
dom.window.document.body.appendChild(element);
}
// Include the KaTeX stylesheet if the document contains rendered math, so
// that formulas display correctly in the exported HTML/PDF.
if (doc.querySelector(".katex")) {
const link = doc.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("href", katexStylesheetUrl);
doc.head.appendChild(link);
}
const output = dom.serialize();
if (options?.includeHead === false) {