diff --git a/docs/content/4.plugins/1.built-in/math.md b/docs/content/4.plugins/1.built-in/math.md index 8126fe7e..b309e3e1 100644 --- a/docs/content/4.plugins/1.built-in/math.md +++ b/docs/content/4.plugins/1.built-in/math.md @@ -150,7 +150,7 @@ Returns a `ComarkPlugin` that tokenizes `$...$` and `$$...$$` expressions. **Parameters:** - `options?` - Optional `MathConfig`: - - `throwOnError?: boolean` - Throw on parse errors instead of returning an error message. Default: `false` + - `throwOnError?: boolean` - **Deprecated**, ignored by the parser. Only affects the deprecated `renderMath()` helper and will be removed in `0.9.0`. Default: `false` - `options?: Record` - Additional [KaTeX render options](https://katex.org/docs/options.html) - `brackets?: boolean` - Also parse `\(…\)` and `\[…\]`. Default: `false` @@ -158,6 +158,32 @@ Returns a `ComarkPlugin` that tokenizes `$...$` and `$$...$$` expressions. The plugin stores LaTeX source as plain text in the AST. Rendering requires passing `Math` to the `components` prop of `` (see [Usage](#usage)). KaTeX only runs when the component mounts. +### Rendering math manually + +To render or validate LaTeX outside a `Math` component (for example in a custom component or a server-side pipeline), call KaTeX directly: + +```ts +import katex from 'katex' + +// Render to an HTML string +const inline = katex.renderToString('E = mc^2', { displayMode: false, throwOnError: false }) +const display = katex.renderToString('x^2', { displayMode: true, throwOnError: false }) + +// Validate LaTeX syntax +function isValidMath(code: string): boolean { + try { + katex.renderToString(code, { throwOnError: true }) + return true + } catch { + return false + } +} +``` + +::warning +`renderMath()` and `validateMath()` exported from `comark/plugins/math` (and every framework `plugins/math` subpath) are deprecated and will be removed in `0.9.0`. Replace them with the snippet above. +:: + --- ## Component props diff --git a/packages/comark/src/plugins/math.ts b/packages/comark/src/plugins/math.ts index 24fb08fd..c45337f5 100644 --- a/packages/comark/src/plugins/math.ts +++ b/packages/comark/src/plugins/math.ts @@ -7,6 +7,8 @@ export interface MathConfig { /** * Throw on parse errors or return error message * @default false + * @deprecated Only used by the deprecated `renderMath()`; the parser ignores it. + * Will be removed in 0.9.0. Pass KaTeX options to `katex.renderToString()` directly. */ throwOnError?: boolean @@ -30,6 +32,9 @@ export interface MathConfig { * @param config KaTeX configuration * @returns HTML string * + * @deprecated Will be removed in 0.9.0. Call `katex.renderToString()` directly, + * see https://comark.dev/plugins/built-in/math#rendering-math-manually + * * @example * ```ts * const html = await renderMath('E = mc^2', false) @@ -62,6 +67,9 @@ export async function renderMath(code: string, displayMode: boolean, config: Mat * @param code LaTeX math expression * @returns true if valid, false otherwise * + * @deprecated Will be removed in 0.9.0. Call `katex.renderToString()` with + * `throwOnError: true` directly, see https://comark.dev/plugins/built-in/math#rendering-math-manually + * * @example * ```ts * await validateMath('E = mc^2') // true diff --git a/packages/comark/test/plugins/math.test.ts b/packages/comark/test/plugins/math.test.ts index bb0fd012..704b195c 100644 --- a/packages/comark/test/plugins/math.test.ts +++ b/packages/comark/test/plugins/math.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest' import { parseMarkdown } from '../../src/parse' -import math, { renderMath, validateMath } from '../../src/plugins/math' +import math from '../../src/plugins/math' describe('math plugin', () => { it('parses inline and display math without loading katex', async () => { @@ -10,14 +10,85 @@ describe('math plugin', () => { expect(JSON.stringify(nodes)).toContain('math') }) +}) + +describe('math plugin with brackets', () => { + const parse = (markdown: string, brackets = true) => + parseMarkdown(markdown, { plugins: [math({ brackets })] }).then((tree) => tree.nodes) + + it('parses \\(…\\) as inline math', async () => { + expect(await parse('Area \\(\\pi r^2\\) here')).toEqual([ + [ + 'p', + {}, + 'Area ', + ['math', { class: 'math inline', content: '\\pi r^2', $: { markup: '\\(' } }, '\\pi r^2'], + ' here', + ], + ]) + }) + + it('parses \\[…\\] lines as display math', async () => { + expect(await parse('\\[\nx = \\frac{-b}{2a}\n\\]')).toEqual([ + ['math', { class: 'math block', content: 'x = \\frac{-b}{2a}', $: { markup: '\\[' } }, 'x = \\frac{-b}{2a}'], + ]) + expect(await parse('\\[ E = mc^2 \\]')).toEqual([ + ['math', { class: 'math block', content: ' E = mc^2 ', $: { markup: '\\[' } }, ' E = mc^2 '], + ]) + }) + + it('parses \\[…\\] inside a paragraph', async () => { + expect(await parse('so \\[x^2\\] holds')).toEqual([ + ['p', {}, 'so ', ['math', { class: 'math inline', content: 'x^2', $: { markup: '\\[' } }, 'x^2'], ' holds'], + ]) + }) + + it('keeps escaped brackets that are not math', async () => { + expect(await parse('See \\[1\\] and \\[2, 3\\].')).toEqual([['p', {}, 'See [1] and [2, 3].']]) + expect(await parse('\\[not a link\\](https://example.com)')).toEqual([ + ['p', {}, '[not a link](', ['a', { href: 'https://example.com' }, 'https://example.com'], ')'], + ]) + expect(await parse('Unclosed \\( paren')).toEqual([['p', {}, 'Unclosed ( paren']]) + expect(await parse('Escaped \\\\(x\\\\)')).toEqual([['p', {}, 'Escaped \\(x\\)']]) + }) + + it('stops display math at a blank line', async () => { + expect(await parse('\\[\nx\n\ny\n\\]')).toEqual([ + ['p', {}, '[\nx'], + ['p', {}, 'y\n]'], + ]) + }) + + it('leaves code spans and fences alone', async () => { + expect(await parse('`\\(x\\)`')).toEqual([['p', {}, ['code', {}, '\\(x\\)']]]) + expect(await parse('```\n\\[x\\]\n```')).toEqual([['pre', {}, ['code', {}, '\\[x\\]']]]) + }) + + it('treats \\( and \\[ as escapes by default', async () => { + expect(await parse('\\(x\\) and \\[y\\]', false)).toEqual([['p', {}, '(x) and [y]']]) + }) - it('renders math lazily via katex', async () => { - await expect(renderMath('E = mc^2', false)).resolves.toContain('katex') + it('keeps auto-close out of closed bracket math', async () => { + expect(await parse('Area \\(a^*\\)')).toEqual([ + ['p', {}, 'Area ', ['math', { class: 'math inline', content: 'a^*', $: { markup: '\\(' } }, 'a^*']], + ]) + expect(await parse('\\[\nx `y\n\\]')).toEqual([ + ['math', { class: 'math block', content: 'x `y', $: { markup: '\\[' } }, 'x `y'], + ]) }) - it('validates math lazily via katex', async () => { - await expect(validateMath('E = mc^2')).resolves.toBe(true) - await expect(validateMath('\\invalid')).resolves.toBe(false) + it('keeps auto-close out of indented \\[ blocks', async () => { + const block = ['math', { class: 'math block', content: 'x *y', $: { markup: '\\[' } }, 'x *y'] + expect(await parse(' \\[\n x *y\n \\]')).toEqual([block]) + expect(await parse('- step\n \\[\n x *y\n \\]')).toEqual([['ul', {}, ['li', {}, ['p', {}, 'step'], block]]]) + }) + + it('heals a \\[ span that the block rule rejects', async () => { + expect(await parse('\\[\nx *y\n\\] tail')).toEqual([['p', {}, '[\nx ', ['em', {}, 'y\n] tail']]]) + }) + + it('still heals inside \\(…\\) without brackets', async () => { + expect(await parse('Area \\(the *word\\)', false)).toEqual([['p', {}, 'Area (the ', ['em', {}, 'word)']]]) }) }) diff --git a/test/bundle.test.ts b/test/bundle.test.ts index 1b80bcd4..be490344 100644 --- a/test/bundle.test.ts +++ b/test/bundle.test.ts @@ -67,7 +67,7 @@ describe('package bundle size', { timeout: 60_000 }, () => { "@comark/react": "38.6k (76 files)", "@comark/svelte": "46.8k (84 files)", "@comark/vue": "56.4k (80 files)", - "comark": "397k (158 files)", + "comark": "398k (158 files)", } `) })