From e0797b421a7e737740e8bbafd52e4c4c0e287595 Mon Sep 17 00:00:00 2001 From: onmax Date: Tue, 17 Nov 2026 10:17:33 +0100 Subject: [PATCH 1/6] fix(math,lint): keep formulas through Comark's security plugin, and lint display math clean comark-mathml carried each formula's MathML in an `html` prop. Comark's security plugin removes every `*html` prop as a markup sink, so with `security({ allowedTags })`, the setup the docs recommend, every formula fell back to its TeX. The MathML now reaches the renderers as the formula's children, elements that security checks one by one, and `comarkUi().tags` lists them. A formula a document writes itself loses its content, as its `html` already did. comark-linter counted the block comark-mathml makes from `$$` and math fences as an authored component, so a host that lints with its components refused display math as `::comark-mathml-2`. Only a block whose line writes `:name` is checked now. Co-Authored-By: Claude Opus 5.5 --- packages/lint/src/index.ts | 13 +++--- packages/lint/src/rules/math.ts | 2 +- packages/lint/test/lint.test.ts | 11 +++++ packages/math/docs/index.md | 12 +++++ packages/math/src/html.ts | 31 ++++++++++--- packages/math/src/index.ts | 32 +++++++++----- packages/math/src/markup.ts | 59 +++++++++++++++++++++++++ packages/math/src/react.ts | 16 +++---- packages/math/src/svelte/Formula.svelte | 7 ++- packages/math/src/svelte/index.d.ts | 6 +-- packages/math/src/svelte/index.js | 2 +- packages/math/src/vue.ts | 17 +++---- packages/math/test/frameworks.test.ts | 4 +- packages/math/test/math.test.ts | 24 ++++++++++ packages/ui/src/index.ts | 7 ++- 15 files changed, 191 insertions(+), 52 deletions(-) create mode 100644 packages/math/src/markup.ts diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index d4234286a..e951f42fa 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -489,11 +489,14 @@ 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` is the author's. + const used: { name: string; written: string; line: number; column?: number }[] = blocks.flatMap( + (block) => { + const text = source.lines[block.line - 1] ?? ""; + if (!text.includes(`:${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..4699bc34f 100644 --- a/packages/lint/test/lint.test.ts +++ b/packages/lint/test/lint.test.ts @@ -114,6 +114,17 @@ 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]]); + }); + 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/src/html.ts b/packages/math/src/html.ts index 948a5f961..c770bdc30 100644 --- a/packages/math/src/html.ts +++ b/packages/math/src/html.ts @@ -1,21 +1,40 @@ -import type { NodeHandler } from "comark"; +import type { Node, NodeHandler } from "comark"; import { escapeHtml } from "comark/utils"; 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"; +/** + * 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 escapeHtml(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}="${escapeHtml(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) : escapeHtml(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..6446335a1 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`, and `display` for display math. The typeset MathML is + * the formula's children, as elements, so a host's `security` plugin checks them like the rest of the document. A + * formula with no children couldn't be typeset, and renders its TeX. */ -export type FormulaAttributes = { tex?: string; display?: boolean; html?: string }; +export type FormulaAttributes = { tex?: string; display?: boolean }; const DOLLAR = 0x24; const BACKSLASH = 0x5c; @@ -208,13 +211,16 @@ 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 || node.length > 2)) { delete attrs.html; + 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 +244,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, ...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..4c4a847d4 --- /dev/null +++ b/packages/math/src/markup.ts @@ -0,0 +1,59 @@ +import type { Node } from "comark"; + +/** The elements Temml writes, so a host's `security` allowlist keeps a formula's MathML. */ +export const MATHML_TAGS = ( + "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 double-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 = () => { + 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(); + else if (tag) { + const attrs = Object.fromEntries( + [...attributes.matchAll(ATTRIBUTE)].map(([, name = "", value = ""]) => [ + name, + decode(value), + ]), + ); + 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..aec2e6a53 100644 --- a/packages/math/src/svelte/Formula.svelte +++ b/packages/math/src/svelte/Formula.svelte @@ -1,11 +1,10 @@ - + - -{#if html}{@html html}{:else}{tex ?? ""}{/if} +{#if children}{@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/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 with the tags it exports", async () => { + const { default: security } = await import("comark/plugins/security"); + const { MATHML_TAGS } = await import("../src/html.ts"); + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const html = await createHtmlRenderer({ + plugins: [math(), security({ allowedTags: ["p", "formula", ...MATHML_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("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/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 = From 6a8471384564a6e865e2cd328636eb9a65057a27 Mon Sep 17 00:00:00 2001 From: onmax Date: Tue, 17 Nov 2026 10:18:47 +0100 Subject: [PATCH 2/6] test(math): allow the formula's elements by name in the security test Co-Authored-By: Claude Opus 5.5 --- packages/math/test/math.test.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/math/test/math.test.ts b/packages/math/test/math.test.ts index 0b60a5597..602f9d925 100644 --- a/packages/math/test/math.test.ts +++ b/packages/math/test/math.test.ts @@ -194,12 +194,12 @@ describe("comark-mathml", () => { expect(Object.values(meta.issueRules ?? {})).toEqual(["comark/math/authored-html"]); }); - it("keeps its MathML through Comark's security plugin with the tags it exports", async () => { + it("keeps its MathML through Comark's security plugin when its elements are allowed", async () => { const { default: security } = await import("comark/plugins/security"); - const { MATHML_TAGS } = await import("../src/html.ts"); + 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", ...MATHML_TAGS] })], + plugins: [math(), security({ allowedTags: ["p", "formula", ...tags] })], components, })("Mass $E = mc^2$\n\n$$\n\\frac{a}{b}\n$$\n"); expect(warn).not.toHaveBeenCalled(); From 24bf309ed04a98f5688764a8d5234e100da44ce0 Mon Sep 17 00:00:00 2001 From: onmax Date: Tue, 17 Nov 2026 10:54:09 +0100 Subject: [PATCH 3/6] fix(math,lint): Svelte formulas, literal entities, references, and cased components - Svelte: a typeset formula carries `typeset`, since @comark/svelte always passes a children snippet, so a formula that didn't typeset shows its TeX again. @comark/svelte's gives MathML's tags the HTML namespace in the browser, so a formula made there is parsed again into a MathML copy shown in place of Svelte's own. - The HTML renderer escapes every `&` in a formula's decoded text and its TeX, so `\verb|<|` shows `<`. - The markup reader takes single-quoted attributes, as Temml writes for `\ref`, and closes only the element that's open, so a reference no longer breaks the rest of its formula. `a` joins MATHML_TAGS. - The linter compares a block with the names its line writes in kebab case, so `::Screnshot` and `:Screnshot[x]` are still reported. Co-Authored-By: Claude Opus 5.5 --- packages/lint/src/index.ts | 5 +- packages/lint/test/lint.test.ts | 5 + packages/math/package.json | 1 + packages/math/src/html.ts | 12 +- packages/math/src/index.ts | 13 ++- packages/math/src/markup.ts | 19 ++-- packages/math/src/svelte/Formula.svelte | 24 +++- packages/math/test/fixtures/svelte-client.ts | 7 ++ packages/math/test/fixtures/svelte-server.ts | 7 ++ packages/math/test/math.test.ts | 15 +++ packages/math/test/svelte.test.ts | 112 +++++++++++++++++++ pnpm-lock.yaml | 3 + 12 files changed, 199 insertions(+), 24 deletions(-) create mode 100644 packages/math/test/fixtures/svelte-client.ts create mode 100644 packages/math/test/fixtures/svelte-server.ts create mode 100644 packages/math/test/svelte.test.ts diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index e951f42fa..735e40f65 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -490,11 +490,12 @@ function unknownComponents( ].sort(); const known = new Set([...names, ...htmlTags]); // 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` is the author's. + // 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] ?? ""; - if (!text.includes(`:${block.name}`)) return []; + 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}` }]; }, ); diff --git a/packages/lint/test/lint.test.ts b/packages/lint/test/lint.test.ts index 4699bc34f..2d9f6e3d4 100644 --- a/packages/lint/test/lint.test.ts +++ b/packages/lint/test/lint.test.ts @@ -123,6 +123,11 @@ describe("comark/unknown-component", () => { 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 () => { 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 c770bdc30..e53776050 100644 --- a/packages/math/src/html.ts +++ b/packages/math/src/html.ts @@ -1,5 +1,4 @@ import type { Node, NodeHandler } from "comark"; -import { escapeHtml } from "comark/utils"; import { classOf } from "./client.ts"; import { css } from "./styles.ts"; import { isElement } from "../../../shared/nodes.ts"; @@ -8,6 +7,11 @@ import { rawText } from "../../../shared/text.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. @@ -15,12 +19,12 @@ export type { FormulaAttributes, MathMeta, MathOptions, MathOutput } from "./ind const markup = (nodes: Node[]): string => nodes .map((node) => { - if (!Array.isArray(node)) return escapeHtml(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}="${escapeHtml(String(value))}"`) + .map(([name, value]) => ` ${name}="${escape(String(value))}"`) .join(""); return `<${tag}${attributes}>${markup(children)}`; }) @@ -33,7 +37,7 @@ const formula: NodeHandler = ([, attrs, ...children], state) => { const styles = styled.has(state.context) ? "" : ``; styled.add(state.context); const typeset = children.length > 0; - const body = typeset ? markup(children) : escapeHtml(rawText(attrs.tex)); + const body = typeset ? markup(children) : escape(rawText(attrs.tex)); return `${styles}${body}`; }; diff --git a/packages/math/src/index.ts b/packages/math/src/index.ts index 6446335a1..8ace4b3f9 100644 --- a/packages/math/src/index.ts +++ b/packages/math/src/index.ts @@ -35,11 +35,11 @@ export type MathMeta = { type Issue = { rule: `comark/math/${string}`; message: string }; /** - * What a formula becomes, and all its renderers read: its `tex`, and `display` for display math. The typeset MathML is - * the formula's children, as elements, so a host's `security` plugin checks them like the rest of the document. A - * formula with no children 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 }; +export type FormulaAttributes = { tex?: string; display?: boolean; typeset?: boolean }; const DOLLAR = 0x24; const BACKSLASH = 0x5c; @@ -213,8 +213,9 @@ export default defineComarkPlugin((options = const [tag, attrs] = node; // 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 || node.length > 2)) { + 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", @@ -245,7 +246,7 @@ export default defineComarkPlugin((options = const result = typeset(tex, display); const attrs: FormulaAttributes = display ? { tex, display } : { tex }; if ("html" in result) { - list[index] = ["formula", attrs, ...markupToNodes(result.html)]; + list[index] = ["formula", { ...attrs, typeset: true }, ...markupToNodes(result.html)]; continue; } issues.push({ diff --git a/packages/math/src/markup.ts b/packages/math/src/markup.ts index 4c4a847d4..59536986c 100644 --- a/packages/math/src/markup.ts +++ b/packages/math/src/markup.ts @@ -1,8 +1,8 @@ import type { Node } from "comark"; -/** The elements Temml writes, so a host's `security` allowlist keeps a formula's MathML. */ +/** The elements Temml writes, so a host's `security` allowlist keeps a formula's MathML: `a` is a `\ref`. */ export const MATHML_TAGS = ( - "annotation math menclose merror mfrac mglyph mi mmultiscripts mn mo mover mpadded mphantom mprescripts mroot mrow ms " + + "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. */ @@ -23,31 +23,32 @@ const decode = (text: string) => return String.fromCodePoint(code); }); -const TOKEN = /<\/([\w:-]+)\s*>|<([\w:-]+)((?:\s+[\w:-]+="[^"]*")*)\s*(\/?)>|([^<]+)/g; -const ATTRIBUTE = /([\w:-]+)="([^"]*)"/g; +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 double-quoted attributes and escaped text, which is all this reads. + * 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 = () => { + 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(); + else if (closing) close(closing); else if (tag) { const attrs = Object.fromEntries( - [...attributes.matchAll(ATTRIBUTE)].map(([, name = "", value = ""]) => [ + [...attributes.matchAll(ATTRIBUTE)].map(([, name = "", double, single]) => [ name, - decode(value), + decode(double ?? single ?? ""), ]), ); if (selfClosing) childrenOf().push([tag, attrs]); diff --git a/packages/math/src/svelte/Formula.svelte b/packages/math/src/svelte/Formula.svelte index aec2e6a53..92b69de9c 100644 --- a/packages/math/src/svelte/Formula.svelte +++ b/packages/math/src/svelte/Formula.svelte @@ -3,8 +3,26 @@ import { onMount } from "svelte"; import { addStyles, classOf } from "comark-mathml/client"; - let { tex = undefined, display = false, children = undefined } = $props(); - onMount(addStyles); + let { tex = undefined, display = false, typeset = false, children = undefined } = $props(); + + // @comark/svelte creates elements with , which gives MathML's tags the HTML namespace, where they + // don't lay out as math. A server render is parsed as MathML, so this only happens to a formula made in the browser: + // its markup is then parsed again into a copy, shown in place of Svelte's own, and kept in step with it. + const MATHML = "http://www.w3.org/1998/Math/MathML"; + let drawn = $state(); + let copy = $state(""); + onMount(() => { + addStyles(); + if (!drawn) return; + const sync = () => { + const math = drawn.querySelector("math"); + copy = math && math.namespaceURI !== MATHML ? drawn.innerHTML : ""; + }; + sync(); + const observer = new MutationObserver(sync); + observer.observe(drawn, { subtree: true, childList: true, characterData: true, attributes: true }); + return () => observer.disconnect(); + }); -{#if children}{@render children()}{:else}{tex ?? ""}{/if} +{#if typeset}{#if copy}{@html copy}{/if}{@render children?.()}{:else}{tex ?? ""}{/if} diff --git a/packages/math/test/fixtures/svelte-client.ts b/packages/math/test/fixtures/svelte-client.ts new file mode 100644 index 000000000..a879a0db3 --- /dev/null +++ b/packages/math/test/fixtures/svelte-client.ts @@ -0,0 +1,7 @@ +import { MarkdownDocument } from "@comark/svelte"; +import type { MarkdownDocument as Document } from "comark"; +import { mount } from "svelte"; +import { components } from "../../src/svelte/index.js"; + +export const mountDocument = (value: Document) => + mount(MarkdownDocument, { target: document.body, props: { value, components } }); 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/math.test.ts b/packages/math/test/math.test.ts index 602f9d925..ea99367cd 100644 --- a/packages/math/test/math.test.ts +++ b/packages/math/test/math.test.ts @@ -208,6 +208,21 @@ describe("comark-mathml", () => { 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.test.ts b/packages/math/test/svelte.test.ts new file mode 100644 index 000000000..f4a18b224 --- /dev/null +++ b/packages/math/test/svelte.test.ts @@ -0,0 +1,112 @@ +import { chromium } from "@playwright/test"; +import { parseMarkdown } from "comark"; +import { fileURLToPath } from "node:url"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { compile } from "svelte/compiler"; +import { build } from "vite"; +import { afterAll, describe, expect, it } from "vite-plus/test"; +import math from "../src/index.ts"; + +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. +async function bundle(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!; +} + +const markdown = "Mass $\\frac{a}{b}$, and a broken $\\frac{a}$.\n\n$$\n\\sum_i i\n$$\n"; +const browser = chromium.launch(); +afterAll(async () => (await browser).close()); + +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 bundle("./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 }); + } + }); + + it("gives formulas made in the browser MathML's namespace", async () => { + const page = await (await browser).newPage(); + try { + await page.setContent(""); + await page.addScriptTag({ content: await bundle("./fixtures/svelte-client.ts", "client") }); + // The document goes as JSON, the form a page receives it in. + await page.evaluate( + (json) => + ( + window as unknown as { fixture: { mountDocument: (document: unknown) => void } } + ).fixture.mountDocument(JSON.parse(json)), + JSON.stringify(value), + ); + await page.waitForFunction(() => document.querySelectorAll(".cmh").length === 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, + ]), + }; + }), + ); + const MATHML = "http://www.w3.org/1998/Math/MathML"; + expect(shown).toEqual([ + { source: null, namespaces: [[MATHML, MATHML]] }, + { source: "\\frac{a}", namespaces: [] }, + { source: null, namespaces: [[MATHML, MATHML]] }, + ]); + } finally { + await page.close(); + } + }); +}); 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)) From 530747c01827f34511893f0f779d0d9dc0d18162 Mon Sep 17 00:00:00 2001 From: onmax Date: Tue, 17 Nov 2026 11:03:28 +0100 Subject: [PATCH 4/6] test(math): check Svelte's browser formulas in the e2e suite, where Chromium is installed Co-Authored-By: Claude Opus 5.5 --- e2e/math-svelte.e2e.ts | 48 +++++++++++++++ packages/math/test/svelte-bundle.ts | 40 +++++++++++++ packages/math/test/svelte.test.ts | 90 ++--------------------------- 3 files changed, 93 insertions(+), 85 deletions(-) create mode 100644 e2e/math-svelte.e2e.ts create mode 100644 packages/math/test/svelte-bundle.ts diff --git a/e2e/math-svelte.e2e.ts b/e2e/math-svelte.e2e.ts new file mode 100644 index 000000000..1f63a2b92 --- /dev/null +++ b/e2e/math-svelte.e2e.ts @@ -0,0 +1,48 @@ +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) => + ( + window as unknown as { fixture: { mountDocument: (document: unknown) => void } } + ).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]] }, + ]); +}); 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 index f4a18b224..5bbdba806 100644 --- a/packages/math/test/svelte.test.ts +++ b/packages/math/test/svelte.test.ts @@ -1,55 +1,14 @@ -import { chromium } from "@playwright/test"; -import { parseMarkdown } from "comark"; -import { fileURLToPath } from "node:url"; import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; -import { compile } from "svelte/compiler"; -import { build } from "vite"; -import { afterAll, describe, expect, it } from "vite-plus/test"; +import { parseMarkdown } from "comark"; +import { describe, expect, it } from "vite-plus/test"; import math from "../src/index.ts"; +import { svelteBundle } from "./svelte-bundle.ts"; -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. -async function bundle(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!; -} - +// 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"; -const browser = chromium.launch(); -afterAll(async () => (await browser).close()); describe("comark-mathml in @comark/svelte", async () => { const value = await parseMarkdown(markdown, { plugins: [math()] }); @@ -58,7 +17,7 @@ describe("comark-mathml in @comark/svelte", async () => { const dir = await mkdtemp(join(tmpdir(), "comark-mathml-svelte-")); try { const file = join(dir, "render.mjs"); - await writeFile(file, await bundle("./fixtures/svelte-server.ts", "server")); + 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; }; @@ -70,43 +29,4 @@ describe("comark-mathml in @comark/svelte", async () => { await rm(dir, { recursive: true, force: true }); } }); - - it("gives formulas made in the browser MathML's namespace", async () => { - const page = await (await browser).newPage(); - try { - await page.setContent(""); - await page.addScriptTag({ content: await bundle("./fixtures/svelte-client.ts", "client") }); - // The document goes as JSON, the form a page receives it in. - await page.evaluate( - (json) => - ( - window as unknown as { fixture: { mountDocument: (document: unknown) => void } } - ).fixture.mountDocument(JSON.parse(json)), - JSON.stringify(value), - ); - await page.waitForFunction(() => document.querySelectorAll(".cmh").length === 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, - ]), - }; - }), - ); - const MATHML = "http://www.w3.org/1998/Math/MathML"; - expect(shown).toEqual([ - { source: null, namespaces: [[MATHML, MATHML]] }, - { source: "\\frac{a}", namespaces: [] }, - { source: null, namespaces: [[MATHML, MATHML]] }, - ]); - } finally { - await page.close(); - } - }); }); From 6044e046f5a35ddae82faa68b04aa860e3be1508 Mon Sep 17 00:00:00 2001 From: onmax Date: Tue, 17 Nov 2026 11:11:02 +0100 Subject: [PATCH 5/6] fix(math): give a Svelte formula typeset on update MathML's namespace too The copy that fixes the namespace now follows the span with Svelte's render through an effect, so a formula that starts as TeX and typesets after an update gets it as well. Co-Authored-By: Claude Opus 5.5 --- e2e/math-svelte.e2e.ts | 32 +++++++++++++++---- packages/math/src/svelte/Formula.svelte | 17 ++++++---- packages/math/test/fixtures/SvelteHost.svelte | 13 ++++++++ packages/math/test/fixtures/svelte-client.ts | 13 +++++--- 4 files changed, 57 insertions(+), 18 deletions(-) create mode 100644 packages/math/test/fixtures/SvelteHost.svelte diff --git a/e2e/math-svelte.e2e.ts b/e2e/math-svelte.e2e.ts index 1f63a2b92..5202ae4d9 100644 --- a/e2e/math-svelte.e2e.ts +++ b/e2e/math-svelte.e2e.ts @@ -18,13 +18,13 @@ test("@comark/svelte gives formulas made in the browser MathML's namespace", asy await page.setContent(""); await page.addScriptTag({ content: bundle }); // The document goes as JSON, the form a page receives it in. - await page.evaluate( - (json) => - ( - window as unknown as { fixture: { mountDocument: (document: unknown) => void } } - ).fixture.mountDocument(JSON.parse(json)), - JSON.stringify(value), - ); + 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) => { @@ -45,4 +45,22 @@ test("@comark/svelte gives formulas made in the browser MathML's namespace", asy { 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]); }); diff --git a/packages/math/src/svelte/Formula.svelte b/packages/math/src/svelte/Formula.svelte index 92b69de9c..c1bc1a94c 100644 --- a/packages/math/src/svelte/Formula.svelte +++ b/packages/math/src/svelte/Formula.svelte @@ -11,16 +11,21 @@ const MATHML = "http://www.w3.org/1998/Math/MathML"; let drawn = $state(); let copy = $state(""); - onMount(() => { - addStyles(); - if (!drawn) return; + onMount(addStyles); + // The span that holds Svelte's own render appears whenever the formula is typeset, on mount or on a later update. + $effect(() => { + const box = drawn; + if (!box) { + copy = ""; + return; + } const sync = () => { - const math = drawn.querySelector("math"); - copy = math && math.namespaceURI !== MATHML ? drawn.innerHTML : ""; + const math = box.querySelector("math"); + copy = math && math.namespaceURI !== MATHML ? box.innerHTML : ""; }; sync(); const observer = new MutationObserver(sync); - observer.observe(drawn, { subtree: true, childList: true, characterData: true, attributes: true }); + observer.observe(box, { subtree: true, childList: true, characterData: true, attributes: true }); return () => observer.disconnect(); }); 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 index a879a0db3..06b41e345 100644 --- a/packages/math/test/fixtures/svelte-client.ts +++ b/packages/math/test/fixtures/svelte-client.ts @@ -1,7 +1,10 @@ -import { MarkdownDocument } from "@comark/svelte"; -import type { MarkdownDocument as Document } from "comark"; import { mount } from "svelte"; -import { components } from "../../src/svelte/index.js"; +import Host from "./SvelteHost.svelte"; -export const mountDocument = (value: Document) => - mount(MarkdownDocument, { target: document.body, props: { value, components } }); +/** 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); +}; From c883574977e9513b6cf0f75558a2f8fca24d280e Mon Sep 17 00:00:00 2001 From: onmax Date: Tue, 17 Nov 2026 11:14:44 +0100 Subject: [PATCH 6/6] test(math): a Svelte formula that goes to TeX and back shows its new MathML Co-Authored-By: Claude Opus 5.5 --- e2e/math-svelte.e2e.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/e2e/math-svelte.e2e.ts b/e2e/math-svelte.e2e.ts index 5202ae4d9..47f08b08d 100644 --- a/e2e/math-svelte.e2e.ts +++ b/e2e/math-svelte.e2e.ts @@ -63,4 +63,27 @@ test("@comark/svelte gives formulas made in the browser MathML's namespace", asy ), ); 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"]]); });