diff --git a/e2e/math-svelte.e2e.ts b/e2e/math-svelte.e2e.ts new file mode 100644 index 000000000..47f08b08d --- /dev/null +++ b/e2e/math-svelte.e2e.ts @@ -0,0 +1,89 @@ +import { expect, test } from "@playwright/test"; +import { parseMarkdown } from "comark"; +import math from "../packages/math/src/index.ts"; +import { svelteBundle } from "../packages/math/test/svelte-bundle.ts"; + +const MATHML = "http://www.w3.org/1998/Math/MathML"; +const markdown = "Mass $\\frac{a}{b}$, and a broken $\\frac{a}$.\n\n$$\n\\sum_i i\n$$\n"; + +let bundle: string; +test.beforeAll(async () => { + bundle = await svelteBundle("./fixtures/svelte-client.ts", "client"); +}); + +// @comark/svelte creates elements in the browser with , which gives MathML's tags the HTML +// namespace; a server render doesn't show it, since the page's parser makes them MathML. +test("@comark/svelte gives formulas made in the browser MathML's namespace", async ({ page }) => { + const value = await parseMarkdown(markdown, { plugins: [math()] }); + await page.setContent(""); + await page.addScriptTag({ content: bundle }); + // The document goes as JSON, the form a page receives it in. + await page.evaluate((json) => { + const app = window as unknown as { + fixture: { mountDocument: (document: unknown) => (next: unknown) => void }; + update: (next: unknown) => void; + }; + app.update = app.fixture.mountDocument(JSON.parse(json)); + }, JSON.stringify(value)); + await expect(page.locator(".cmh")).toHaveCount(3); + const shown = await page.evaluate(() => + [...document.querySelectorAll(".cmh")].map((formula) => { + const visible = [...formula.querySelectorAll("math")].filter( + (math) => math.getBoundingClientRect().width > 0, + ); + return { + source: formula.classList.contains("cmh-source") ? formula.textContent : null, + namespaces: visible.map((math) => [ + math.namespaceURI, + math.querySelector("mi, mn, mo")?.namespaceURI, + ]), + }; + }), + ); + expect(shown).toEqual([ + { source: null, namespaces: [[MATHML, MATHML]] }, + { source: "\\frac{a}", namespaces: [] }, + { source: null, namespaces: [[MATHML, MATHML]] }, + ]); + + // A formula that didn't typeset becomes one that does, in the same component, as while someone fixes their TeX. + const fixed = await parseMarkdown(markdown.replace("\\frac{a}$", "\\frac{a}{c}$"), { + plugins: [math()], + }); + await page.evaluate( + (json) => (window as unknown as { update: (next: unknown) => void }).update(JSON.parse(json)), + JSON.stringify(fixed), + ); + await expect(page.locator(".cmh-source")).toHaveCount(0); + const updated = await page.evaluate(() => + [...document.querySelectorAll(".cmh")].map( + (formula) => + [...formula.querySelectorAll("math")].find((math) => math.getBoundingClientRect().width > 0) + ?.namespaceURI, + ), + ); + expect(updated).toEqual([MATHML, MATHML, MATHML]); + + // A formula that goes to TeX and comes back shows its new MathML, not the copy of the one before. + const update = (source: string) => + parseMarkdown(source, { plugins: [math()] }).then((next) => + page.evaluate( + (json) => + (window as unknown as { update: (next: unknown) => void }).update(JSON.parse(json)), + JSON.stringify(next), + ), + ); + await update("$a$"); + await update("$\\frac{a}$"); + await expect(page.locator(".cmh-source")).toHaveCount(1); + await update("$b$"); + await expect(page.locator(".cmh")).toHaveCount(1); + const last = await page + .locator(".cmh") + .evaluate((formula) => + [...formula.querySelectorAll("math")] + .filter((math) => math.getBoundingClientRect().width > 0) + .map((math) => [math.namespaceURI, math.querySelector("mi")?.textContent]), + ); + expect(last).toEqual([[MATHML, "b"]]); +}); diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index d4234286a..735e40f65 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -489,11 +489,15 @@ function unknownComponents( ...new Set((Array.isArray(components) ? components : Object.keys(components)).map(kebab)), ].sort(); const known = new Set([...names, ...htmlTags]); - const used: { name: string; written: string; line: number; column?: number }[] = blocks.map( - (block) => ({ - ...block, - written: `${source.lines[block.line - 1]?.trim().match(/^:+/)?.[0] ?? "::"}${block.name}`, - }), + // A plugin can turn its own syntax into a block while parsing, as comark-mathml does with `$$`, under a name the + // document never writes. Only a block whose line writes `:name`, in any case Comark reads, is the author's. + const used: { name: string; written: string; line: number; column?: number }[] = blocks.flatMap( + (block) => { + const text = source.lines[block.line - 1] ?? ""; + const written = [...text.matchAll(/:([A-Za-z][\w-]*)/g)].map(([, name = ""]) => kebab(name)); + if (!written.includes(kebab(block.name))) return []; + return [{ ...block, written: `${text.trim().match(/^:+/)?.[0] ?? "::"}${block.name}` }]; + }, ); let range: [number, number] | null = null; for (const token of tokens) { diff --git a/packages/lint/src/rules/math.ts b/packages/lint/src/rules/math.ts index 50a6b1228..7f665cf01 100644 --- a/packages/lint/src/rules/math.ts +++ b/packages/lint/src/rules/math.ts @@ -9,6 +9,6 @@ export default { }, "comark/math/authored-html": { code: "COMARK4103", - title: "Write math between `$` signs, not as a formula's `html`", + title: "Write math between `$` signs, not as a `formula` element", }, } satisfies Record<`comark/math/${string}`, RuleInfo>; diff --git a/packages/lint/test/lint.test.ts b/packages/lint/test/lint.test.ts index 941d894e0..2d9f6e3d4 100644 --- a/packages/lint/test/lint.test.ts +++ b/packages/lint/test/lint.test.ts @@ -114,6 +114,22 @@ describe("comark/unknown-component", () => { ]); }); + it("leaves out the blocks a plugin makes from its own syntax, such as display math", async () => { + const { default: math, components: mathComponents } = await import("comark-mathml/html"); + const markdown = + "Mass $E = mc^2$.\n\n$$\n\\frac{a}{b}\n$$\n\n```math\n\\sum_i i\n```\n\n::mystery\n::"; + const found = await lint(markdown, { + plugins: [math()], + components: [...Object.keys(mathComponents), "screenshot"], + }); + expect(found.map(({ rule, line }) => [rule, line])).toEqual([["comark/unknown-component", 11]]); + const cased = await lint("::Screnshot\n::\n\n:Screnshot[x]\n\n::UnknownThing\n::", { + plugins: [math()], + components: ["Screenshot"], + }); + expect(cased.map(({ line }) => line)).toEqual([1, 4, 6]); + }); + it("is off without components, since any name could be valid", async () => { expect(await lint("::anything\n::")).toEqual([]); }); diff --git a/packages/math/docs/index.md b/packages/math/docs/index.md index 1bff06388..43f0ad645 100644 --- a/packages/math/docs/index.md +++ b/packages/math/docs/index.md @@ -155,6 +155,18 @@ import math, { components } from "comark-mathml/html"; const render = createHtmlRenderer({ plugins: [math()], components }); ``` +With Comark's `security` plugin, allow `formula` and the MathML elements the package exports as `MATHML_TAGS`, and `KATEX_TAGS` too for KaTeX's HTML. `comarkUi()` already lists them in its `tags`. + +```ts +import security from "comark/plugins/security"; +import math, { components, MATHML_TAGS } from "comark-mathml/html"; + +const render = createHtmlRenderer({ + plugins: [math(), security({ allowedTags: ["p", "formula", ...MATHML_TAGS] })], + components, +}); +``` + For Vue, React, or Svelte, import from `comark-mathml/vue`, `comark-mathml/react`, or `comark-mathml/svelte`. The components add the styles on mount. On a server-rendered page, also import `comark-mathml/style.css` so it doesn't shift. [Renderers](/guide/renderers) covers using it with other plugins. ## Theme diff --git a/packages/math/package.json b/packages/math/package.json index 3a105188d..91979280f 100644 --- a/packages/math/package.json +++ b/packages/math/package.json @@ -60,6 +60,7 @@ "devDependencies": { "@comark/html": "catalog:", "@comark/react": "catalog:", + "@comark/svelte": "catalog:", "@comark/vue": "catalog:", "@types/react": "catalog:", "@types/react-dom": "catalog:", diff --git a/packages/math/src/html.ts b/packages/math/src/html.ts index 948a5f961..e53776050 100644 --- a/packages/math/src/html.ts +++ b/packages/math/src/html.ts @@ -1,21 +1,44 @@ -import type { NodeHandler } from "comark"; -import { escapeHtml } from "comark/utils"; +import type { Node, NodeHandler } from "comark"; import { classOf } from "./client.ts"; import { css } from "./styles.ts"; +import { isElement } from "../../../shared/nodes.ts"; import { rawText } from "../../../shared/text.ts"; -export { default } from "./index.ts"; +export { default, KATEX_TAGS, MATHML_TAGS } from "./index.ts"; export type { FormulaAttributes, MathMeta, MathOptions, MathOutput } from "./index.ts"; +// The nodes hold decoded text, so every `&` is escaped, including one that looks like an entity, as `<` in +// `\verb|<|` does. Comark's `escapeHtml` leaves those as they are. +const escape = (text: string) => + text.replace(/[&<>"]/g, (char) => `&${{ "&": "amp", "<": "lt", ">": "gt", '"': "quot" }[char]};`); + +/** + * A formula's MathML as markup, with no whitespace added: Comark's renderer indents elements it doesn't know, which + * would pad each `` and the TeX that copying reads. + */ +const markup = (nodes: Node[]): string => + nodes + .map((node) => { + if (!Array.isArray(node)) return escape(node); + if (!isElement(node)) return ""; + const [tag, attrs, ...children] = node; + const attributes = Object.entries(attrs) + .filter(([name, value]) => name !== "$" && value !== undefined && value !== null) + .map(([name, value]) => ` ${name}="${escape(String(value))}"`) + .join(""); + return `<${tag}${attributes}>${markup(children)}`; + }) + .join(""); + // Each render gets a fresh `state.context`, so a document carries the styles once. const styled = new WeakSet(); -const formula: NodeHandler = ([, attrs], state) => { - const html = rawText(attrs.html); +const formula: NodeHandler = ([, attrs, ...children], state) => { const styles = styled.has(state.context) ? "" : ``; styled.add(state.context); - // The plugin typeset `html` itself, with links and other trusted commands off. - return `${styles}${html || escapeHtml(rawText(attrs.tex))}`; + const typeset = children.length > 0; + const body = typeset ? markup(children) : escape(rawText(attrs.tex)); + return `${styles}${body}`; }; /** The HTML renderer for math. Pass it as `components`; it inlines the styles once per document. */ diff --git a/packages/math/src/index.ts b/packages/math/src/index.ts index 3c2893dc2..8ace4b3f9 100644 --- a/packages/math/src/index.ts +++ b/packages/math/src/index.ts @@ -7,10 +7,12 @@ import { type StateInline, type Token, } from "../../../shared/markdown-it.ts"; +import { markupToNodes } from "./markup.ts"; import { type MathOutput, typesetter } from "./typeset.ts"; import { isElement } from "../../../shared/nodes.ts"; export type { MathOutput } from "./typeset.ts"; +export { KATEX_TAGS, MATHML_TAGS } from "./markup.ts"; export interface MathOptions { /** @@ -33,10 +35,11 @@ export type MathMeta = { type Issue = { rule: `comark/math/${string}`; message: string }; /** - * What a formula becomes, and all its renderers read: its `tex`, `display` for display math, and `html`, the typeset - * markup. A formula with no `html` couldn't be typeset, and renders its TeX. + * What a formula becomes, and all its renderers read: its `tex`, `display` for display math, and `typeset` when its + * children are its MathML, as elements, so a host's `security` plugin checks them like the rest of the document. A + * formula that couldn't be typeset has no children, and renders its TeX. */ -export type FormulaAttributes = { tex?: string; display?: boolean; html?: string }; +export type FormulaAttributes = { tex?: string; display?: boolean; typeset?: boolean }; const DOLLAR = 0x24; const BACKSLASH = 0x5c; @@ -208,13 +211,17 @@ export default defineComarkPlugin((options = const node = nodes[index]; if (!node || !isElement(node)) continue; const [tag, attrs] = node; - // The renderers print `html` as it is, so only markup this plugin typeset may reach them. - if (tag === "formula" && "html" in attrs) { + // A formula's children are MathML that the renderers print as it is, so only formulas this plugin typeset + // may have any. A document that writes a `formula` with content, or the `html` it once carried, hears so. + if (tag === "formula" && ("html" in attrs || "typeset" in attrs || node.length > 2)) { delete attrs.html; + delete attrs.typeset; + node.length = 2; issues.push({ rule: "comark/math/authored-html", - message: `A \`formula\` element sets \`html\`, which only comark-mathml writes, so it's ignored. Write the formula between \`$\` signs instead.`, + message: `A \`formula\` element has content of its own, which only comark-mathml writes, so it's ignored. Write the formula between \`$\` signs instead.`, }); + continue; } const inHtml = html || !!attrs.$?.html; if (!inHtml && tag === source.tag) { @@ -238,12 +245,14 @@ export default defineComarkPlugin((options = for (const { list, index, tex, display } of found) { const result = typeset(tex, display); const attrs: FormulaAttributes = display ? { tex, display } : { tex }; - if ("html" in result) attrs.html = result.html; - else - issues.push({ - rule: "comark/math/invalid-tex", - message: `Math \`${quoted(tex)}\` failed to typeset: ${result.reason}. Fix the TeX or wrap it in code.`, - }); + if ("html" in result) { + list[index] = ["formula", { ...attrs, typeset: true }, ...markupToNodes(result.html)]; + continue; + } + issues.push({ + rule: "comark/math/invalid-tex", + message: `Math \`${quoted(tex)}\` failed to typeset: ${result.reason}. Fix the TeX or wrap it in code.`, + }); list[index] = ["formula", attrs]; } if (!issues.length) return; diff --git a/packages/math/src/markup.ts b/packages/math/src/markup.ts new file mode 100644 index 000000000..59536986c --- /dev/null +++ b/packages/math/src/markup.ts @@ -0,0 +1,60 @@ +import type { Node } from "comark"; + +/** The elements Temml writes, so a host's `security` allowlist keeps a formula's MathML: `a` is a `\ref`. */ +export const MATHML_TAGS = ( + "a annotation math menclose merror mfrac mglyph mi mmultiscripts mn mo mover mpadded mphantom mprescripts mroot mrow ms " + + "mspace msqrt mstyle msub msubsup msup mtable mtd mtext mtr munder munderover none semantics" +).split(" "); +/** The elements KaTeX's `"html"` and `"htmlAndMathml"` output add to MathML's: its boxes, and its SVG for stretchy marks. */ +export const KATEX_TAGS = "line path span svg".split(" "); + +const ENTITIES = new Map([ + ["amp", "&"], + ["lt", "<"], + ["gt", ">"], + ["quot", '"'], + ["apos", "'"], +]); +const decode = (text: string) => + text.replace(/&(#x[\da-f]+|#\d+|\w+);/gi, (entity, name: string) => { + if (name[0] !== "#") return ENTITIES.get(name) ?? entity; + const code = + name[1] === "x" || name[1] === "X" ? parseInt(name.slice(2), 16) : Number(name.slice(1)); + return String.fromCodePoint(code); + }); + +const TOKEN = /<\/([\w:-]+)\s*>|<([\w:-]+)((?:\s+[\w:-]+=(?:"[^"]*"|'[^']*'))*)\s*(\/?)>|([^<]+)/g; +const ATTRIBUTE = /([\w:-]+)=(?:"([^"]*)"|'([^']*)')/g; + +/** + * The typesetter's markup as Comark nodes, so a formula reaches the renderers as elements a host's `security` plugin + * checks one by one, rather than as a string of HTML they would have to trust. Temml and KaTeX write well-formed + * markup with quoted attributes and escaped text, which is all this reads. + */ +export function markupToNodes(markup: string): Node[] { + type Frame = { tag: string; attrs: Record; children: Node[] }; + const root: Node[] = []; + const open: Frame[] = []; + const childrenOf = () => open.at(-1)?.children ?? root; + const close = (tag?: string) => { + if (tag !== undefined && open.at(-1)?.tag !== tag) return; + const frame = open.pop(); + if (frame) childrenOf().push([frame.tag, frame.attrs, ...frame.children]); + }; + for (const [, closing, tag, attributes = "", selfClosing, text] of markup.matchAll(TOKEN)) { + if (text !== undefined) childrenOf().push(decode(text)); + else if (closing) close(closing); + else if (tag) { + const attrs = Object.fromEntries( + [...attributes.matchAll(ATTRIBUTE)].map(([, name = "", double, single]) => [ + name, + decode(double ?? single ?? ""), + ]), + ); + if (selfClosing) childrenOf().push([tag, attrs]); + else open.push({ tag, attrs, children: [] }); + } + } + while (open.length) close(); + return root; +} diff --git a/packages/math/src/react.ts b/packages/math/src/react.ts index 80a7d485d..9f904fb6b 100644 --- a/packages/math/src/react.ts +++ b/packages/math/src/react.ts @@ -1,19 +1,15 @@ -import { createElement, useEffect } from "react"; +import { Children, createElement, type ReactNode, useEffect } from "react"; import { addStyles, classOf } from "./client.ts"; import type { FormulaAttributes } from "./index.ts"; -export { default } from "./index.ts"; +export { default, KATEX_TAGS, MATHML_TAGS } from "./index.ts"; export type { FormulaAttributes, MathMeta, MathOptions, MathOutput } from "./index.ts"; -/** Math for `@comark/react`. */ -export function Formula({ tex, display, html }: FormulaAttributes) { +/** Math for `@comark/react`. The typeset MathML arrives as its children. */ +export function Formula({ tex, display, children }: FormulaAttributes & { children?: ReactNode }) { useEffect(addStyles, []); - return html - ? // The plugin typeset `html` itself, with links and other trusted commands off. - createElement("span", { - className: classOf(display, true), - dangerouslySetInnerHTML: { __html: html }, - }) + return Children.count(children) + ? createElement("span", { className: classOf(display, true) }, children) : createElement("span", { className: classOf(display, false) }, tex ?? ""); } diff --git a/packages/math/src/svelte/Formula.svelte b/packages/math/src/svelte/Formula.svelte index 27d9a07a0..c1bc1a94c 100644 --- a/packages/math/src/svelte/Formula.svelte +++ b/packages/math/src/svelte/Formula.svelte @@ -1,11 +1,33 @@ - + - -{#if html}{@html html}{:else}{tex ?? ""}{/if} +{#if typeset}{#if copy}{@html copy}{/if}{@render children?.()}{:else}{tex ?? ""}{/if} diff --git a/packages/math/src/svelte/index.d.ts b/packages/math/src/svelte/index.d.ts index b3967f39a..17a099da0 100644 --- a/packages/math/src/svelte/index.d.ts +++ b/packages/math/src/svelte/index.d.ts @@ -1,8 +1,8 @@ -import type { Component } from "svelte"; +import type { Component, Snippet } from "svelte"; import type { FormulaAttributes } from "comark-mathml"; -export { default } from "comark-mathml"; +export { default, KATEX_TAGS, MATHML_TAGS } from "comark-mathml"; export type { FormulaAttributes, MathMeta, MathOptions, MathOutput } from "comark-mathml"; -export declare const Formula: Component; +export declare const Formula: Component; export declare const components: { Formula: typeof Formula }; diff --git a/packages/math/src/svelte/index.js b/packages/math/src/svelte/index.js index 94dcbfef8..e8a05bcf0 100644 --- a/packages/math/src/svelte/index.js +++ b/packages/math/src/svelte/index.js @@ -1,6 +1,6 @@ // Math for `@comark/svelte`. Pass `components` to it; the parse plugin comes from `comark-mathml`. import Formula from "./Formula.svelte"; -export { default } from "comark-mathml"; +export { default, KATEX_TAGS, MATHML_TAGS } from "comark-mathml"; export { Formula }; export const components = { Formula }; diff --git a/packages/math/src/vue.ts b/packages/math/src/vue.ts index c19186cb3..beb29251d 100644 --- a/packages/math/src/vue.ts +++ b/packages/math/src/vue.ts @@ -1,21 +1,22 @@ import { defineComponent, h, onMounted } from "vue"; import { addStyles, classOf } from "./client.ts"; -export { default } from "./index.ts"; +export { default, KATEX_TAGS, MATHML_TAGS } from "./index.ts"; export type { FormulaAttributes, MathMeta, MathOptions, MathOutput } from "./index.ts"; -/** Math for `@comark/vue`. */ +/** Math for `@comark/vue`. The typeset MathML arrives as its default slot. */ export const Formula = defineComponent({ name: "Formula", inheritAttrs: false, - props: { tex: String, display: Boolean, html: String }, - setup(props) { + props: { tex: String, display: Boolean }, + setup(props, { slots }) { onMounted(addStyles); - return () => - props.html - ? // The plugin typeset `html` itself, with links and other trusted commands off. - h("span", { class: classOf(props.display, true), innerHTML: props.html }) + return () => { + const math = slots.default?.(); + return math?.length + ? h("span", { class: classOf(props.display, true) }, math) : h("span", { class: classOf(props.display, false) }, props.tex ?? ""); + }; }, }); diff --git a/packages/math/test/fixtures/SvelteHost.svelte b/packages/math/test/fixtures/SvelteHost.svelte new file mode 100644 index 000000000..22b74ebe6 --- /dev/null +++ b/packages/math/test/fixtures/SvelteHost.svelte @@ -0,0 +1,13 @@ + + + + diff --git a/packages/math/test/fixtures/svelte-client.ts b/packages/math/test/fixtures/svelte-client.ts new file mode 100644 index 000000000..06b41e345 --- /dev/null +++ b/packages/math/test/fixtures/svelte-client.ts @@ -0,0 +1,10 @@ +import { mount } from "svelte"; +import Host from "./SvelteHost.svelte"; + +/** Mounts a document and returns a function that replaces it. */ +export const mountDocument = (value: unknown) => { + const host = mount(Host, { target: document.body, props: { initial: value } }) as { + update: (next: unknown) => void; + }; + return (next: unknown) => host.update(next); +}; diff --git a/packages/math/test/fixtures/svelte-server.ts b/packages/math/test/fixtures/svelte-server.ts new file mode 100644 index 000000000..79325eb3f --- /dev/null +++ b/packages/math/test/fixtures/svelte-server.ts @@ -0,0 +1,7 @@ +import { MarkdownDocument } from "@comark/svelte"; +import type { MarkdownDocument as Document } from "comark"; +import { render as ssr } from "svelte/server"; +import { components } from "../../src/svelte/index.js"; + +export const render = (value: Document) => + ssr(MarkdownDocument, { props: { value, components } }).body; diff --git a/packages/math/test/frameworks.test.ts b/packages/math/test/frameworks.test.ts index 2cce7fdd2..d28de1888 100644 --- a/packages/math/test/frameworks.test.ts +++ b/packages/math/test/frameworks.test.ts @@ -15,11 +15,13 @@ import { components as reactComponents } from "../src/react.ts"; import { components as vueComponents } from "../src/vue.ts"; const markdown = "Mass $E = mc^2$, a broken $\\frac{a}$, and $a < b$.\n\n$$\n\\sum_{i=1}^n i\n$$\n"; -// Drops what differs only in serialization: comments, whitespace between tags, and the HTML renderer's inline styles. +// Drops what differs only in serialization: comments, whitespace between tags, the HTML renderer's inline styles, and +// the `;` that ends a `style` attribute, which React leaves out. const normalize = (html: string) => html .replace(//g, "") .replace(/]*>.*?<\/style>/g, "") + .replace(/;"/g, '"') .replace(/>\s+/g, ">") .replace(/\s+ { expect(meta.issues).toHaveLength(2); }); + it("ignores the content a document writes in a formula itself", async () => { + const markdown = + '
\n\n
\n\nand $y$'; + const html = await render(markdown); + expect(html).not.toContain("x'); + const { meta } = await parse(markdown); + expect(Object.values(meta.issueRules ?? {})).toEqual(["comark/math/authored-html"]); + }); + + it("keeps its MathML through Comark's security plugin when its elements are allowed", async () => { + const { default: security } = await import("comark/plugins/security"); + const tags = "annotation math mfrac mi mn mo mrow msup semantics".split(" "); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const html = await createHtmlRenderer({ + plugins: [math(), security({ allowedTags: ["p", "formula", ...tags] })], + components, + })("Mass $E = mc^2$\n\n$$\n\\frac{a}{b}\n$$\n"); + expect(warn).not.toHaveBeenCalled(); + expect(html).toContain("E="); + expect(html).toContain("ab"); + expect(html).not.toContain('class="cmh cmh-source"'); + }); + + it("keeps text that looks like an entity literal, in every output", async () => { + for (const output of ["mathml", "html", "htmlAndMathml"] as const) { + const html = await render("$\\verb|<|$", { output }); + expect(html).toContain("&lt;"); + expect(html).not.toMatch(/>< { + const html = await render("$x+\\ref{eq1}+y$"); + expect(html).not.toContain("href='"); + expect(html).toMatch(//); + expect(html).toMatch(/y<\/mi><\/mrow>/); + }); + it("takes the place of Comark's math plugin", async () => { const { default: core } = await import("comark/plugins/math"); expect(math().name).toBe(core().name); diff --git a/packages/math/test/svelte-bundle.ts b/packages/math/test/svelte-bundle.ts new file mode 100644 index 000000000..f17a88750 --- /dev/null +++ b/packages/math/test/svelte-bundle.ts @@ -0,0 +1,40 @@ +import { fileURLToPath } from "node:url"; +import { compile } from "svelte/compiler"; +import { build } from "vite"; + +const source = (path: string) => fileURLToPath(new URL(path, import.meta.url)); + +// Bundles @comark/svelte with this package's Formula, so both share Svelte's internals, for the server or the browser. +export async function svelteBundle(entry: string, generate: "server" | "client") { + const result = await build({ + configFile: false, + logLevel: "error", + resolve: { + alias: { + "comark-mathml/client": source("../src/client.ts"), + "comark-mathml": source("../src/index.ts"), + }, + conditions: ["svelte", "browser"], + }, + ssr: { noExternal: true, resolve: { conditions: ["svelte"] } }, + plugins: [ + { + name: "math-test-svelte", + transform(code, id) { + if (id.endsWith(".svelte")) return compile(code, { filename: id, generate }).js; + }, + }, + ], + build: { + write: false, + minify: false, + ...(generate === "server" + ? { ssr: source(entry), rollupOptions: { output: { format: "es" as const } } } + : { lib: { entry: source(entry), formats: ["iife" as const], name: "fixture" } }), + }, + }); + const output = (Array.isArray(result) ? result[0]! : result) as { + output: { type: string; code?: string }[]; + }; + return output.output.find((chunk) => chunk.type === "chunk")!.code!; +} diff --git a/packages/math/test/svelte.test.ts b/packages/math/test/svelte.test.ts new file mode 100644 index 000000000..5bbdba806 --- /dev/null +++ b/packages/math/test/svelte.test.ts @@ -0,0 +1,32 @@ +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { parseMarkdown } from "comark"; +import { describe, expect, it } from "vite-plus/test"; +import math from "../src/index.ts"; +import { svelteBundle } from "./svelte-bundle.ts"; + +// e2e/math-svelte.e2e.ts mounts the same document in a browser. +const markdown = "Mass $\\frac{a}{b}$, and a broken $\\frac{a}$.\n\n$$\n\\sum_i i\n$$\n"; + +describe("comark-mathml in @comark/svelte", async () => { + const value = await parseMarkdown(markdown, { plugins: [math()] }); + + it("server-renders typeset formulas as MathML and a broken one as its TeX", async () => { + const dir = await mkdtemp(join(tmpdir(), "comark-mathml-svelte-")); + try { + const file = join(dir, "render.mjs"); + await writeFile(file, await svelteBundle("./fixtures/svelte-server.ts", "server")); + const { render } = (await import(/* @vite-ignore */ pathToFileURL(file).href)) as { + render: (document: typeof value) => string; + }; + const html = render(value); + expect(html).toContain('\\frac{a}'); + expect(html.match(//g)).toHaveLength(2); + expect(html).toContain(""); + } finally { + await rm(dir, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts index 9ee2588bc..f6311ff4d 100644 --- a/packages/ui/src/index.ts +++ b/packages/ui/src/index.ts @@ -25,7 +25,7 @@ import { createIcons, type IconOptions, type Icons } from "comark-icon"; import include, { type IncludeOptions } from "comark-include"; import keys, { type KeysOptions } from "comark-keys"; import type { AnchorsOptions, ExternalOptions } from "comark-links"; -import type { MathOptions } from "comark-mathml"; +import { KATEX_TAGS, MATHML_TAGS, type MathOptions } from "comark-mathml"; import type { MediaOptions } from "comark-media"; import type { OutlineOptions } from "comark-outline"; import type { PeleConfig } from "comark-pele"; @@ -413,6 +413,11 @@ export function preset(renderer: Renderer, options: PresetOptions = {}): P ...MARKDOWN_TAGS, ...(on(options.github) && on(optionsOf(options.github)?.html) ? HTML_TAGS : []), ...TAGS.flatMap(([key, list]) => (enabled(key) ? list : [])), + // A formula's MathML, and KaTeX's boxes when the math is typeset as its HTML. + ...(enabled("math") ? MATHML_TAGS : []), + ...(enabled("math") && (optionsOf(options.math)?.output ?? "mathml") !== "mathml" + ? KATEX_TAGS + : []), ]); const calloutOptions = optionsOf(options.github)?.callouts; const calloutBlocks = diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index cdfc005c1..c3dcb95e6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -1720,6 +1720,9 @@ importers: '@comark/react': specifier: ^0.9.0 version: 0.9.0(katex@0.19.1)(react@19.3.1)(shiki@4.5.0) + '@comark/svelte': + specifier: ^0.9.0 + version: 0.9.0(katex@0.19.1)(shiki@4.5.0)(svelte@5.57.2(@typescript-eslint/types@8.71.1)) '@comark/vue': specifier: ^0.9.0 version: 0.9.0(katex@0.19.1)(shiki@4.5.0)(vue@3.5.44(typescript@6.0.3))