diff --git a/server/models/helpers/DocumentHelper.test.ts b/server/models/helpers/DocumentHelper.test.ts index 321b030ccc..fd307ea023 100644 --- a/server/models/helpers/DocumentHelper.test.ts +++ b/server/models/helpers/DocumentHelper.test.ts @@ -126,6 +126,23 @@ describe("DocumentHelper", () => { expect(result).not.toMatch(/]*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" }); diff --git a/server/models/helpers/ProsemirrorHelper.tsx b/server/models/helpers/ProsemirrorHelper.tsx index 63135ee7f2..e391c7206d 100644 --- a/server/models/helpers/ProsemirrorHelper.tsx +++ b/server/models/helpers/ProsemirrorHelper.tsx @@ -77,6 +77,11 @@ export type MentionAttrs = { const pluginsWithSafeDecorations = new WeakSet(); +// 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) {