mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-24 08:03:19 +00:00
feat(markdown): render LaTeX math with KaTeX (#4138)
Markdown views (file preview, agent chat, notebook Markdown cells, LSP/GitHub/plugin Markdown) now typeset $...$, $$...$$, \(...\), \[...\] and ```math blocks with KaTeX. The marked extension emits [data-math] placeholders that survive DOMPurify and are typeset after sanitizing (trust: false); inline $ follows Pandoc's rules, so currency like $5 and $10 stays text. The Markdown preview keeps the placeholders in its rendered HTML and typesets them after each render, like Mermaid diagrams, so its per-block sanitize cache is unaffected. New dependency: katex 0.19.1 (MIT). Co-authored-by: zzxzz12345 <8338183+zzxzz12345@users.noreply.github.com>
This commit is contained in:
@@ -1024,3 +1024,37 @@ test("aligns Mermaid diagrams in replies to their container align attribute", as
|
||||
expect(Math.abs(offsets[2]!.rightGap)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs(offsets[3]!.leftGap - offsets[3]!.rightGap)).toBeLessThanOrEqual(1.5);
|
||||
});
|
||||
|
||||
test("renders LaTeX math formulas with KaTeX and keeps wide equations scrollable", async ({ page }) => {
|
||||
const reply = await openReply(
|
||||
page,
|
||||
[
|
||||
"Inline $E = mc^2$ and \\(a^2 + b^2 = c^2\\), prices $5 and $10 stay plain.",
|
||||
"",
|
||||
"$$",
|
||||
"\\int_{-\\infty}^{\\infty} e^{-x^2} \\, dx = \\sqrt{\\pi}",
|
||||
"$$",
|
||||
"",
|
||||
"```math",
|
||||
"\\sum_{k=1}^{n} k = \\frac{n(n+1)}{2} + a_1 + a_2 + a_3 + a_4 + a_5 + a_6 + a_7 + a_8 + a_9 + a_{10}",
|
||||
"```",
|
||||
].join("\n"),
|
||||
);
|
||||
await expect(reply.locator(".katex")).toHaveCount(4);
|
||||
await expect(reply.locator(".katex-display")).toHaveCount(2);
|
||||
await expect(reply).toContainText("prices $5 and $10 stay plain.");
|
||||
|
||||
const layout = await reply.evaluate((el) => {
|
||||
const firstKatex = el.querySelector<HTMLElement>(".katex")!;
|
||||
const display = el.querySelectorAll<HTMLElement>(".katex-display");
|
||||
const font = getComputedStyle(firstKatex).fontFamily;
|
||||
return {
|
||||
font,
|
||||
height: firstKatex.getBoundingClientRect().height,
|
||||
overflowX: getComputedStyle(display[1]!).overflowX,
|
||||
};
|
||||
});
|
||||
expect(layout.font).toContain("KaTeX_Main");
|
||||
expect(layout.height).toBeGreaterThan(10);
|
||||
expect(layout.overflowX).toBe("auto");
|
||||
});
|
||||
|
||||
@@ -80,6 +80,7 @@
|
||||
"dompurify": "^3.4.17",
|
||||
"emmet": "2.4.11",
|
||||
"immer": "^11.1.21",
|
||||
"katex": "^0.19.1",
|
||||
"marked": "^18.1.1",
|
||||
"mermaid": "12.1.0",
|
||||
"react": "^19.1.0",
|
||||
|
||||
Generated
+11
@@ -119,6 +119,9 @@ importers:
|
||||
immer:
|
||||
specifier: ^11.1.21
|
||||
version: 11.1.21
|
||||
katex:
|
||||
specifier: ^0.19.1
|
||||
version: 0.19.1
|
||||
marked:
|
||||
specifier: ^18.1.1
|
||||
version: 18.1.1
|
||||
@@ -1799,6 +1802,10 @@ packages:
|
||||
resolution: {integrity: sha512-/B6p9eY9DX7aHBfpkHdpirDTZ5QH9xTwL9y837PWuzuv41O5jFdqNQwVQEQsimY0/iVNkwBY4+4hMfhQ7d4Dbw==}
|
||||
hasBin: true
|
||||
|
||||
katex@0.19.1:
|
||||
resolution: {integrity: sha512-jG8uKntjSEcm2EpQOh0XturpPuuC9r3Sq5HLHdsFdWZT27E672SF19QEi+of0/YeOy15lDgRhKvr5614uRrEfA==}
|
||||
hasBin: true
|
||||
|
||||
khroma@2.1.0:
|
||||
resolution: {integrity: sha512-Ls993zuzfayK269Svk9hzpeGUKob/sIgZzyHYdjQoAdQetRKpOLj+k/QQQ/6Qi0Yz65mlROrfd+Ev+1+7dz9Kw==}
|
||||
|
||||
@@ -3792,6 +3799,10 @@ snapshots:
|
||||
dependencies:
|
||||
commander: 15.1.0
|
||||
|
||||
katex@0.19.1:
|
||||
dependencies:
|
||||
commander: 15.1.0
|
||||
|
||||
khroma@2.1.0: {}
|
||||
|
||||
knip@6.43.0:
|
||||
|
||||
@@ -69,6 +69,14 @@ describe("markdown rendering", () => {
|
||||
expect(md.markupToHtml({ kind: "markdown", value: "`x`" })).toBe("<p><code>x</code></p>\n");
|
||||
expect(md.markupToHtml({ kind: "plaintext", value: "<b>" })).toBe('<p class="cm-lsp-plain"><b></p>');
|
||||
});
|
||||
|
||||
it("renders LaTeX math in LSP / documentation markdown", async () => {
|
||||
const md = await freshMarkdown();
|
||||
await md.loadMarkdown();
|
||||
const root = document.createElement("div");
|
||||
root.innerHTML = md.markupToHtml({ kind: "markdown", value: "Complexity $O(n \\log n)$" });
|
||||
expect(root.querySelector(".katex")).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// On Windows, opening `//server/share` signs in to that server with the user's credentials.
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
.katex {
|
||||
overflow-wrap: normal;
|
||||
}
|
||||
|
||||
.katex-display {
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
padding: 2px 0;
|
||||
}
|
||||
|
||||
.katex-error {
|
||||
color: var(--danger) !important;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Marked } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import { mathExtension, renderMath } from "./markdownMath";
|
||||
|
||||
const marked = new Marked({ gfm: true, breaks: false }).use(mathExtension());
|
||||
|
||||
function parseSafe(md: string): HTMLElement {
|
||||
const html = marked.parse(md, { async: false }) as string;
|
||||
const root = DOMPurify.sanitize(html, {
|
||||
USE_PROFILES: { html: true },
|
||||
ADD_ATTR: ["data-math"],
|
||||
FORBID_TAGS: ["style", "form"],
|
||||
FORBID_ATTR: ["style"],
|
||||
RETURN_DOM: true,
|
||||
}) as HTMLElement;
|
||||
renderMath(root);
|
||||
return root;
|
||||
}
|
||||
|
||||
describe("markdown LaTeX math", () => {
|
||||
it("renders inline $...$ and avoids currency false positives", () => {
|
||||
const root = parseSafe(
|
||||
"Energy $E = mc^2$ and CJK 设$x=1$时.\n\nPrices: $5 and $10, or $5-$10, or $ 5 $, or \\$x\\$.",
|
||||
);
|
||||
expect(root.querySelectorAll(".katex")).toHaveLength(2);
|
||||
expect(root.querySelectorAll(".katex-display")).toHaveLength(0);
|
||||
const paras = [...root.querySelectorAll("p")];
|
||||
expect(paras[1]!.textContent).toBe("Prices: $5 and $10, or $5-$10, or $ 5 $, or $x$.");
|
||||
});
|
||||
|
||||
it("prevents * and _ inside math from triggering emphasis while allowing emphasis around math", () => {
|
||||
const root = parseSafe("Formula $(a)_1 + (b)_2$ and $a * b$ and $c * d$, plus **$x^2$**.");
|
||||
expect(root.querySelector("em")).toBeNull();
|
||||
expect(root.querySelectorAll(".katex")).toHaveLength(4);
|
||||
expect(root.querySelector("strong .katex")).not.toBeNull();
|
||||
});
|
||||
|
||||
it("renders multi-line, single-line, inline, and adjacent $$...$$ blocks", () => {
|
||||
const root = parseSafe(
|
||||
"Para\n$$\n\\begin{aligned}\na &= b \\\\\nc &= d\n\\end{aligned}\n$$\n\n$$E = mc^2$$\n\n$$a$$ and $$b$$",
|
||||
);
|
||||
expect(root.querySelectorAll(".katex-display")).toHaveLength(4);
|
||||
expect(root.querySelector("p")?.textContent).toBe("Para");
|
||||
const lastP = [...root.querySelectorAll("p")].at(-1)!;
|
||||
expect(lastP.querySelectorAll(".katex-display")).toHaveLength(2);
|
||||
expect(lastP.textContent).toContain("and");
|
||||
});
|
||||
|
||||
it("renders \\(...\\) and \\[...\\] without breaking escaped links", () => {
|
||||
const root = parseSafe("Inline \\(x + y\\).\n\n\\[\nx^2 + y^2 = z^2\n\\]\n\n\\[text\\](https://example.com)");
|
||||
expect(root.querySelectorAll(".katex")).toHaveLength(2);
|
||||
expect(root.querySelectorAll(".katex-display")).toHaveLength(1);
|
||||
const lastP = [...root.querySelectorAll("p")].at(-1)!;
|
||||
expect(lastP.textContent).toBe("[text](https://example.com)");
|
||||
});
|
||||
|
||||
it("renders ```math code blocks while keeping ```latex and inline code literal", () => {
|
||||
const root = parseSafe("```math\n\\int_0^1 x^2 dx\n```\n\n```latex\n$x$\n```\n\nInline `$y$`.");
|
||||
expect(root.querySelectorAll(".katex-display")).toHaveLength(1);
|
||||
expect(root.querySelector("pre > code.language-latex")?.textContent).toBe("$x$\n");
|
||||
expect(root.querySelector("p > code")?.textContent).toBe("$y$");
|
||||
});
|
||||
|
||||
it("renders invalid LaTeX as an error node instead of throwing", () => {
|
||||
const root = parseSafe("Bad $\\unknowncommand{x}$ and $$\\frac{1$$");
|
||||
expect(root.querySelectorAll(".katex")).toHaveLength(1);
|
||||
expect(root.querySelector(".katex-error")).not.toBeNull();
|
||||
expect(root.textContent).toContain("\\unknowncommand");
|
||||
});
|
||||
|
||||
it("blocks unsafe LaTeX trust commands and raw HTML style/script injection", () => {
|
||||
const root = parseSafe(
|
||||
[
|
||||
"$\\href{javascript:alert(1)}{click}$",
|
||||
'<div style="position:fixed">x</div>',
|
||||
'<span data-math="inline"><img src=x onerror=alert(1)>a</span>',
|
||||
].join("\n\n"),
|
||||
);
|
||||
expect(root.querySelector("a")).toBeNull();
|
||||
expect(root.querySelector("img")).toBeNull();
|
||||
expect(root.querySelector("div[style]")).toBeNull();
|
||||
expect(root.querySelectorAll(".katex")).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* LaTeX math support for Markdown (`marked` + `DOMPurify` + KaTeX).
|
||||
*
|
||||
* `mathExtension()` tokenizes `$$...$$`, `$...$`, `\[...\]`, `\(...\)`, and
|
||||
* ```` ```math ```` blocks into sanitized-safe `<div|span data-math="display|inline">`
|
||||
* placeholders, which survive `DOMPurify` (with `data-math` allowed) and are
|
||||
* rendered synchronously into KaTeX DOM by `renderMath()` right after sanitization.
|
||||
*/
|
||||
import katex from "katex";
|
||||
import "katex/dist/katex.min.css";
|
||||
import "./markdownMath.css";
|
||||
import type { MarkedExtension, Tokens } from "marked";
|
||||
|
||||
interface MathToken extends Tokens.Generic {
|
||||
type: "blockMath" | "inlineMath";
|
||||
raw: string;
|
||||
text: string;
|
||||
display: boolean;
|
||||
}
|
||||
|
||||
const escapeHtml = (s: string) =>
|
||||
s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
|
||||
export function mathPlaceholder(tex: string, display: boolean, block = display): string {
|
||||
const tag = block ? "div" : "span";
|
||||
const mode = display ? "display" : "inline";
|
||||
return `<${tag} data-math="${mode}">${escapeHtml(tex)}</${tag}>`;
|
||||
}
|
||||
|
||||
/** Finds the closing `delim` (`$$`, `\)`, or `\]`) skipping `\` escapes. Returns content end index or -1. */
|
||||
function findClosingDelimiter(src: string, from: number, delim: string): number {
|
||||
for (let i = from; i < src.length; i++) {
|
||||
if (src.startsWith(delim, i)) return i;
|
||||
if (src[i] === "\\") {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches inline `$...$` from index 0 using Pandoc-style guards so currency
|
||||
* like `$5 and $10` or `$5-$10` stays plain text while `$x$`, `设$x=1$`, etc. match.
|
||||
*/
|
||||
function matchInlineDollar(src: string): { end: number; text: string } | null {
|
||||
if (src[0] !== "$" || src[1] === "$" || !src[1] || /\s/.test(src[1])) return null;
|
||||
for (let i = 1; i < src.length; i++) {
|
||||
const ch = src[i]!;
|
||||
if (ch === "\\") {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === "\n" && (src[i + 1] === "\n" || (src[i + 1] === "\r" && src[i + 2] === "\n"))) {
|
||||
return null;
|
||||
}
|
||||
if (ch === "$") {
|
||||
if (i <= 1 || /\s/.test(src[i - 1]!)) continue;
|
||||
const next = src[i + 1] ?? "";
|
||||
if (next === "$" || /\d/.test(next)) return null;
|
||||
const text = src.slice(1, i);
|
||||
if (!text.trim()) return null;
|
||||
return { end: i + 1, text };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Matches inline `$$...$$`, `$...$`, `\(...\)`, or `\[...\]` starting at index 0 of `src`. */
|
||||
function matchInlineMath(src: string): { raw: string; text: string; display: boolean } | null {
|
||||
if (src.startsWith("$$")) {
|
||||
const close = findClosingDelimiter(src, 2, "$$");
|
||||
if (close > 2) {
|
||||
const text = src.slice(2, close);
|
||||
if (text.trim()) return { raw: src.slice(0, close + 2), text, display: true };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (src[0] === "$") {
|
||||
const m = matchInlineDollar(src);
|
||||
return m ? { raw: src.slice(0, m.end), text: m.text, display: false } : null;
|
||||
}
|
||||
if (src.startsWith("\\(")) {
|
||||
const close = findClosingDelimiter(src, 2, "\\)");
|
||||
if (close > 2) {
|
||||
const text = src.slice(2, close);
|
||||
if (text.trim()) return { raw: src.slice(0, close + 2), text, display: false };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (src.startsWith("\\[")) {
|
||||
const close = findClosingDelimiter(src, 2, "\\]");
|
||||
if (close > 2 && src[close + 2] !== "(") {
|
||||
const text = src.slice(2, close);
|
||||
if (text.trim()) return { raw: src.slice(0, close + 2), text, display: true };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const BLOCK_DOLLAR_MULTI = /^ {0,3}\$\$[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*\$\$[ \t]*(?:\r?\n+|$)/;
|
||||
const BLOCK_DOLLAR_SINGLE = /^ {0,3}\$\$((?:\\[\s\S]|[^$\n]|\$(?!\$))+?)\$\$[ \t]*(?:\r?\n+|$)/;
|
||||
const BLOCK_BRACKET_MULTI = /^ {0,3}\\\[[ \t]*\r?\n([\s\S]*?)\r?\n[ \t]*\\\][ \t]*(?:\r?\n+|$)/;
|
||||
const BLOCK_BRACKET_SINGLE = /^ {0,3}\\\[((?:\\[\s\S]|[^\\\n]|\\(?!\]))+?)\\\][ \t]*(?:\r?\n+|$)/;
|
||||
|
||||
function matchBlockMath(src: string): { raw: string; text: string } | null {
|
||||
for (const re of [BLOCK_DOLLAR_MULTI, BLOCK_DOLLAR_SINGLE, BLOCK_BRACKET_MULTI, BLOCK_BRACKET_SINGLE]) {
|
||||
const m = re.exec(src);
|
||||
if (m && m[1]!.trim()) return { raw: m[0], text: m[1]! };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Masks math spans with `a`s (preserving newlines) so `*` and `_` inside math never trigger emphasis. */
|
||||
function maskInlineMath(src: string): string {
|
||||
let out = "";
|
||||
let i = 0;
|
||||
while (i < src.length) {
|
||||
if (src[i] === "\\" && src[i + 1] !== "(" && src[i + 1] !== "[") {
|
||||
out += src.slice(i, i + 2);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (src[i] === "$" || (src[i] === "\\" && (src[i + 1] === "(" || src[i + 1] === "["))) {
|
||||
const m = matchInlineMath(src.slice(i));
|
||||
if (m) {
|
||||
out += m.raw.replace(/[^\r\n]/g, "a");
|
||||
i += m.raw.length;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out += src[i]!;
|
||||
i++;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function mathExtension(): MarkedExtension {
|
||||
return {
|
||||
hooks: {
|
||||
emStrongMask(src) {
|
||||
return maskInlineMath(src);
|
||||
},
|
||||
},
|
||||
renderer: {
|
||||
code({ text, lang }) {
|
||||
if (lang?.trim().split(/\s+/)[0]?.toLowerCase() !== "math") return false;
|
||||
return `${mathPlaceholder(text, true, true)}\n`;
|
||||
},
|
||||
},
|
||||
extensions: [
|
||||
{
|
||||
name: "blockMath",
|
||||
level: "block",
|
||||
start(src) {
|
||||
const m = /\n {0,3}(?:\$\$|\\\[)/.exec(src);
|
||||
return m ? m.index : undefined;
|
||||
},
|
||||
tokenizer(src): MathToken | undefined {
|
||||
const m = matchBlockMath(src);
|
||||
if (!m) return undefined;
|
||||
return { type: "blockMath", raw: m.raw, text: m.text, display: true };
|
||||
},
|
||||
renderer(token) {
|
||||
const t = token as MathToken;
|
||||
return `${mathPlaceholder(t.text, true, true)}\n`;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "inlineMath",
|
||||
level: "inline",
|
||||
start(src) {
|
||||
for (let i = 0; i < src.length; i++) {
|
||||
const ch = src[i]!;
|
||||
if (ch === "\\") {
|
||||
const next = src[i + 1];
|
||||
if (next === "(" || next === "[") return i;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$") return i;
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
tokenizer(src): MathToken | undefined {
|
||||
const m = matchInlineMath(src);
|
||||
if (!m) return undefined;
|
||||
return { type: "inlineMath", raw: m.raw, text: m.text, display: m.display };
|
||||
},
|
||||
renderer(token) {
|
||||
const t = token as MathToken;
|
||||
return mathPlaceholder(t.text, t.display, false);
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** Renders every `[data-math]` placeholder inside `root` synchronously using KaTeX. */
|
||||
export function renderMath(root: ParentNode): void {
|
||||
root.querySelectorAll<HTMLElement>("[data-math]").forEach((el) => {
|
||||
const mode = el.getAttribute("data-math");
|
||||
el.removeAttribute("data-math");
|
||||
if (mode !== "inline" && mode !== "display") return;
|
||||
const tex = (el.textContent ?? "").trim();
|
||||
if (!tex) return;
|
||||
katex.render(tex, el, {
|
||||
displayMode: mode === "display",
|
||||
throwOnError: false,
|
||||
strict: false,
|
||||
trust: false,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,19 +1,24 @@
|
||||
/** Markdown → sanitized HTML (marked + DOMPurify); loaded on demand by `markdown.ts`. */
|
||||
import { Marked } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import { mathExtension, renderMath } from "./markdownMath";
|
||||
|
||||
/** DOMPurify's default link schemes plus `file:` and jdtls' `jdt:` (library classes). */
|
||||
const ALLOWED_URI = /^(?:(?:(?:f|ht)tps?|mailto|tel|file|jdt):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i;
|
||||
|
||||
const marked = new Marked({ gfm: true, breaks: false });
|
||||
const marked = new Marked({ gfm: true, breaks: false }).use(mathExtension());
|
||||
|
||||
export function markdownToSafeHtml(markdown: string): string {
|
||||
const html = marked.parse(markdown, { async: false }) as string;
|
||||
// Comments and docs come from anyone; a `<style>` here would restyle the whole IDE.
|
||||
return DOMPurify.sanitize(html, {
|
||||
const root = DOMPurify.sanitize(html, {
|
||||
USE_PROFILES: { html: true },
|
||||
ALLOWED_URI_REGEXP: ALLOWED_URI,
|
||||
ADD_ATTR: ["data-math"],
|
||||
FORBID_TAGS: ["style", "form"],
|
||||
FORBID_ATTR: ["style"],
|
||||
});
|
||||
RETURN_DOM: true,
|
||||
}) as HTMLElement;
|
||||
renderMath(root);
|
||||
return root.innerHTML;
|
||||
}
|
||||
|
||||
@@ -369,6 +369,17 @@ describe("streamed replies", () => {
|
||||
expect(container.querySelector("details p")?.textContent).toBe("text");
|
||||
});
|
||||
|
||||
it("renders LaTeX math across streamed blocks", () => {
|
||||
const text = "Inline $a + b$.\n\n$$\n\\frac{1}{2}\n$$\n\nTail";
|
||||
const blocks = markdownBlocks(text);
|
||||
expect(blocks).toHaveLength(3);
|
||||
expect(blocks.join("")).toBe(text);
|
||||
const { container } = render(<Markdown text={text} cwd="/repo" />);
|
||||
expect(container.querySelectorAll(".katex")).toHaveLength(2);
|
||||
expect(container.querySelector(".katex-display")).not.toBeNull();
|
||||
expect(screen.queryByRole("button", { name: "Copy Code" })).toBeNull();
|
||||
});
|
||||
|
||||
it("cuts only what streamed on after the blocks that ended", () => {
|
||||
const before = markdownBlocks("One.\n\nTwo.\n\nThr");
|
||||
const after = markdownBlocks("One.\n\nTwo.\n\nThree.\n\n- a", before);
|
||||
|
||||
@@ -11,6 +11,7 @@ import { useEffect, useLayoutEffect, useRef, useSyncExternalStore } from "react"
|
||||
import { Marked } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import { highlightInto } from "@/editor/lsp/markdown";
|
||||
import { mathExtension, renderMath } from "@/editor/lsp/markdownMath";
|
||||
import { iconNode } from "@/ui/iconNode";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { openExternalUrl } from "@/platform/openUrl";
|
||||
@@ -37,7 +38,7 @@ const marked = new Marked({
|
||||
return `<div data-mermaid=""><pre><code class="language-mermaid">${escapeHtml(text)}</code></pre></div>\n`;
|
||||
},
|
||||
},
|
||||
});
|
||||
}).use(mathExtension());
|
||||
|
||||
/** Rendered messages by text, least recently used first: reopening a conversation renders it again. */
|
||||
const rendered = new Map<string, string>();
|
||||
@@ -133,10 +134,11 @@ function renderHtml(text: string): string {
|
||||
FORBID_TAGS: ["style", "form", "source"],
|
||||
FORBID_ATTR: ["style", "srcset"],
|
||||
ALLOW_DATA_ATTR: false,
|
||||
// Only the mermaid placeholder written by the renderer above; data attributes
|
||||
// Only the mermaid and math placeholders written by the renderer above; data attributes
|
||||
// quoted in a reply stay out.
|
||||
ADD_ATTR: ["data-mermaid"],
|
||||
ADD_ATTR: ["data-mermaid", "data-math"],
|
||||
}) as HTMLElement;
|
||||
renderMath(root);
|
||||
root.querySelectorAll("li").forEach(wrapLooseText);
|
||||
// WebKit cuts controls inside <pre> out of a text selection, even when transparent.
|
||||
root.querySelectorAll("pre").forEach((pre) => {
|
||||
|
||||
@@ -104,6 +104,19 @@ describe("notebook Markdown preview", () => {
|
||||
rerender(<MarkdownCell source="plain" attachments={{}} path="/p/a.ipynb" />);
|
||||
expect(container.querySelector("p")).toBe(paragraph);
|
||||
});
|
||||
|
||||
it("renders LaTeX math in Markdown cells while blocking unsafe styles", () => {
|
||||
const { container } = render(
|
||||
<MarkdownCell
|
||||
source={'Inline $x^2$ and <div style="position:fixed">hi</div>\n\n$$\n\\sum_{i=1}^n i\n$$'}
|
||||
attachments={{}}
|
||||
path="/p/a.ipynb"
|
||||
/>,
|
||||
);
|
||||
expect(container.querySelectorAll(".katex")).toHaveLength(2);
|
||||
expect(container.querySelector(".katex-display")).not.toBeNull();
|
||||
expect(container.querySelector("div[style]")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("notebook image outputs", () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import DOMPurify from "dompurify";
|
||||
import { Marked } from "marked";
|
||||
import { mathExtension, renderMath } from "@/editor/lsp/markdownMath";
|
||||
import { mimeText, object, own } from "./outputs";
|
||||
|
||||
export const OUTPUT_CSP =
|
||||
@@ -194,7 +195,7 @@ function htmlRoot(html: string, markdown = false): HTMLElement {
|
||||
"rowspan",
|
||||
"scope",
|
||||
"align",
|
||||
...(markdown ? ["href"] : ["style"]),
|
||||
...(markdown ? ["href", "data-math"] : ["style"]),
|
||||
],
|
||||
// Attachment references are resolved by us after sanitization. No arbitrary
|
||||
// URI survives the explicit src allowlist below.
|
||||
@@ -221,13 +222,14 @@ export function staticOutputDocument(html: string): string {
|
||||
return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${OUTPUT_CSP}"><style>body{margin:8px;font:13px system-ui,sans-serif;color:#222;background:white;overflow-wrap:anywhere}table{border-collapse:collapse;max-width:100%}th,td{padding:4px 8px;border:1px solid #ddd;text-align:left}pre{white-space:pre-wrap}img{max-width:100%;height:auto}</style></head><body>${root.innerHTML}</body></html>`;
|
||||
}
|
||||
|
||||
const markdown = new Marked({ gfm: true });
|
||||
const markdown = new Marked({ gfm: true }).use(mathExtension());
|
||||
/**
|
||||
* Sanitized Markdown with inert links; link clicks are handled by the editor and
|
||||
* `attachment:` images are left for `resolveMarkdownAttachments`.
|
||||
*/
|
||||
export function markdownRoot(source: string): HTMLElement {
|
||||
const root = htmlRoot(markdown.parse(source, { async: false }) as string, true);
|
||||
renderMath(root);
|
||||
for (const link of root.querySelectorAll("a[href]")) {
|
||||
const href = link.getAttribute("href")!;
|
||||
link.removeAttribute("href");
|
||||
|
||||
@@ -41,6 +41,7 @@ import {
|
||||
import { publishPreviewSelection, publishPreviewTop, stepMarkdownPreviewFontZoom, useLiveMarkdown } from "./live";
|
||||
import { subscribeTheme, themeKey } from "@/platform/themeWatch";
|
||||
import { hasMermaid, MERMAID_SELECTOR, renderMermaidIn } from "./mermaid";
|
||||
import { renderMath } from "@/editor/lsp/markdownMath";
|
||||
import { modeOf, useMarkdownModes } from "./modes";
|
||||
import { MarkdownLayoutActions } from "./MarkdownLayoutActions";
|
||||
import {
|
||||
@@ -184,8 +185,11 @@ function MarkdownPreview({ path, sync }: { path: string; sync: boolean }) {
|
||||
});
|
||||
}, [html]);
|
||||
|
||||
// Math before the preview index: typesetting changes the blocks' heights.
|
||||
useLayoutEffect(() => {
|
||||
if (ref.current) invalidatePreviewIndex(ref.current);
|
||||
if (!ref.current) return;
|
||||
renderMath(ref.current);
|
||||
invalidatePreviewIndex(ref.current);
|
||||
}, [html]);
|
||||
|
||||
// Mermaid diagrams: before paint, so cached ones don't flash their source.
|
||||
|
||||
@@ -97,6 +97,7 @@ function collectRuns(root: Node): TextRun[] {
|
||||
const el = node as Element;
|
||||
const tag = el.tagName.toUpperCase();
|
||||
if (SKIP_TAGS.has(tag)) return;
|
||||
if (el.classList.contains("katex-mathml")) return;
|
||||
if (tag === "PRE" && el.parentElement?.getAttribute("data-mermaid-state") === "ok") return;
|
||||
const isBlock = BLOCK_TAGS.has(tag);
|
||||
if (isBlock) flush();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { renderMath } from "@/editor/lsp/markdownMath";
|
||||
import {
|
||||
createMarkdownRenderer,
|
||||
frontMatter,
|
||||
@@ -280,6 +281,17 @@ describe("markdown preview rendering", () => {
|
||||
expect(previewLineAtOffset(blocks, 5000)).toBe(20);
|
||||
expect(previewLineAtOffset([], 50)).toBe(0);
|
||||
});
|
||||
|
||||
it("renders LaTeX math blocks with source lines and inline math", () => {
|
||||
const root = document.createElement("div");
|
||||
root.innerHTML = renderMarkdown("# Heading\n\n$$\nx^2 + y^2 = z^2\n$$\n\nInline $a_1 + b_2$.\n");
|
||||
expect(root.querySelectorAll("[data-math]")).toHaveLength(2);
|
||||
renderMath(root);
|
||||
const lines = [...root.querySelectorAll<HTMLElement>(":scope > [data-line]")].map((e) => e.dataset.line);
|
||||
expect(lines).toEqual(["0", "2", "6"]);
|
||||
expect(root.querySelector(".katex-display")).not.toBeNull();
|
||||
expect(root.querySelectorAll(".katex")).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("markdown preview re-rendering", () => {
|
||||
@@ -300,6 +312,8 @@ describe("markdown preview re-rendering", () => {
|
||||
"| a | b |\n|---|---|\n| 1 | <b>2</b> |",
|
||||
'<span is="x-span">custom</span> and <body class="x"> and </body> text',
|
||||
"> quote\n> more",
|
||||
"$$\nx^2 + y^2 = z^2\n$$",
|
||||
"Inline $a_1 + b_2$ math.",
|
||||
"Last paragraph.",
|
||||
];
|
||||
const doc = (parts: readonly string[]) => parts.join("\n\n") + "\n";
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
* blocks inside one HTML container) is wrapped in an element carrying its
|
||||
* 0-based source line (`data-line`) for scroll sync; images keep their source in `data-src` and are loaded by the preview
|
||||
* (local files through the backend, as the CSP blocks file URLs). Mermaid
|
||||
* blocks become `[data-mermaid]` placeholders, drawn by `./mermaid`. YAML front matter is shown
|
||||
* blocks become `[data-mermaid]` placeholders, drawn by `./mermaid`; math becomes `[data-math]`
|
||||
* placeholders, typeset by the preview (`renderMath`). YAML front matter is shown
|
||||
* as a table of its top-level fields.
|
||||
*/
|
||||
import { Marked, type Token, type TokensList } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import { mathExtension } from "@/editor/lsp/markdownMath";
|
||||
import { opensOtherShare } from "@/platform/paths";
|
||||
|
||||
const escapeHtml = (s: string) =>
|
||||
@@ -22,7 +24,7 @@ const marked = new Marked({
|
||||
return `<div data-mermaid=""><pre><code class="language-mermaid">${escapeHtml(text)}</code></pre></div>\n`;
|
||||
},
|
||||
},
|
||||
});
|
||||
}).use(mathExtension());
|
||||
|
||||
// Own instance: hooks must not leak into the hover / documentation renderer.
|
||||
let purifier: ReturnType<typeof DOMPurify> | null = null;
|
||||
@@ -180,7 +182,7 @@ function blocks(text: string): { line: number; html: string }[] {
|
||||
|
||||
const SANITIZE = {
|
||||
USE_PROFILES: { html: true },
|
||||
ADD_ATTR: ["data-src", "data-line", "data-front-matter"],
|
||||
ADD_ATTR: ["data-src", "data-line", "data-front-matter", "data-math"],
|
||||
// The preview shares the IDE's document: a `<style>` in a file would restyle the whole IDE.
|
||||
// `srcset` and `<source>` would pick an image past the one the preview loads.
|
||||
FORBID_TAGS: ["style", "form", "source"],
|
||||
|
||||
Reference in New Issue
Block a user