diff --git a/docs/content/4.plugins/1.built-in/math.md b/docs/content/4.plugins/1.built-in/math.md index f14a2bdc..427c9d4d 100644 --- a/docs/content/4.plugins/1.built-in/math.md +++ b/docs/content/4.plugins/1.built-in/math.md @@ -156,7 +156,7 @@ Returns a `ComarkPlugin` that tokenizes `$...$` and `$$...$$` expressions. **Returns:** `ComarkPlugin` -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. +The plugin stores LaTeX source as plain text in the AST. Rendering requires passing `Math` to the `components` prop of `` (see [Usage](#usage)). The `Math` components load KaTeX on first use, so pages without math don't load it. A formula KaTeX can't typeset, such as one still streaming in, shows as its TeX source. Vue and React server rendering waits for KaTeX; Svelte and Angular render the source on the server and typeset in the browser. ### Rendering math manually diff --git a/packages/comark-angular/plugins/math/math.component.ts b/packages/comark-angular/plugins/math/math.component.ts index dbe2f031..9bc812a1 100644 --- a/packages/comark-angular/plugins/math/math.component.ts +++ b/packages/comark-angular/plugins/math/math.component.ts @@ -1,5 +1,28 @@ import { Component, OnChanges, SimpleChanges, ChangeDetectionStrategy, ElementRef, inject, input } from '@angular/core' -import katex from 'katex' + +let katex: typeof import('katex').default | undefined +let loading: Promise | undefined + +function loadKatex(): Promise { + loading ??= import('katex').then( + (module) => (katex = module.default), + (error) => { + loading = undefined + throw error + } + ) + return loading +} + +// HTML, `''` when KaTeX can't typeset the formula, or `undefined` before KaTeX loads. +function typeset(tex: string, displayMode: boolean): string | undefined { + if (!katex) return undefined + try { + return katex.renderToString(tex, { throwOnError: true, displayMode }) + } catch { + return '' + } +} /** * Math rendering component for Angular. @@ -43,13 +66,19 @@ export class Math implements OnChanges { const wrapper = document.createElement(isInline ? 'span' : 'div') wrapper.className = isInline ? 'math inline' : 'math block' - try { - wrapper.innerHTML = katex.renderToString(this.content(), { - throwOnError: true, - displayMode: !isInline, - }) - } catch { - wrapper.textContent = '...' + const content = this.content() + const html = typeset(content, !isInline) + if (html) { + wrapper.innerHTML = html + } else { + // Unfinished or invalid TeX, and TeX before KaTeX loads, stays readable as its source. + wrapper.textContent = content + if (html === undefined) { + loadKatex().then( + () => content === this.content() && this.renderMath(), + () => {} + ) + } } hostEl.appendChild(wrapper) diff --git a/packages/comark-react/package.json b/packages/comark-react/package.json index 577c3224..4ff06669 100644 --- a/packages/comark-react/package.json +++ b/packages/comark-react/package.json @@ -62,6 +62,7 @@ "@types/react": "catalog:", "@types/react-dom": "catalog:", "@vitest/browser-playwright": "catalog:", + "happy-dom": "catalog:", "react": "catalog:", "react-dom": "catalog:", "vitest": "catalog:" diff --git a/packages/comark-react/src/components/Math.tsx b/packages/comark-react/src/components/Math.tsx index abd5d277..5d8cee2f 100644 --- a/packages/comark-react/src/components/Math.tsx +++ b/packages/comark-react/src/components/Math.tsx @@ -1,32 +1,75 @@ -import { useState, useEffect } from 'react' -import katex from 'katex' +import { Suspense, memo, use } from 'react' + +let katex: typeof import('katex').default | undefined +let loading: Promise | undefined + +function loadKatex(): Promise { + loading ??= import('katex').then( + (module) => (katex = module.default), + (error) => { + loading = undefined + throw error + } + ) + return loading +} + +// HTML, `''` when KaTeX can't typeset the formula, or `undefined` before KaTeX loads. +function typeset(tex: string, displayMode: boolean): string | undefined { + if (!katex) return undefined + try { + return katex.renderToString(tex, { throwOnError: true, displayMode }) + } catch { + return '' + } +} export interface MathProps { content: string className?: string } -export function Math({ content, className = '' }: MathProps) { - const isInline = className.includes('inline') - const [mathml, setMathml] = useState('...') - - useEffect(() => { - try { - const rendered = katex.renderToString(content, { - throwOnError: true, - displayMode: !isInline, - }) - setMathml(rendered) - } catch { - // Keep previous output while expression is incomplete - } - }, [content, isInline]) +// A render this long after a failed load tries KaTeX again. +const RETRY_DELAY = 5000 + +// One promise for every formula, since `use` needs the same one on each render. +let katexReady: Promise | undefined +let failedAt: number | undefined + +function waitForKatex(): Promise { + if (!katexReady || (failedAt !== undefined && Date.now() - failedAt >= RETRY_DELAY)) { + failedAt = undefined + katexReady = loadKatex().then( + () => true, + () => { + failedAt = Date.now() + return false + } + ) + } + return katexReady +} + +// Memoized because streaming re-renders every formula on each chunk. +const Typeset = memo(function Typeset({ content, isInline }: { content: string; isInline: boolean }) { + let html = typeset(content, !isInline) + if (html === undefined) { + use(waitForKatex()) + html = typeset(content, !isInline) + } + if (!html) + return ( + + ) if (isInline) { return ( ) } @@ -34,7 +77,31 @@ export function Math({ content, className = '' }: MathProps) { return (
) +}) + +function Source({ content, isInline }: { content: string; isInline: boolean }) { + return isInline ? {content} :
{content}
+} + +export function Math({ content, className = '' }: MathProps) { + const isInline = className.includes('inline') + + return ( + + } + > + + + ) } diff --git a/packages/comark-react/test/plugin-math.client.test.tsx b/packages/comark-react/test/plugin-math.client.test.tsx new file mode 100644 index 00000000..2fb20c82 --- /dev/null +++ b/packages/comark-react/test/plugin-math.client.test.tsx @@ -0,0 +1,35 @@ +// @vitest-environment happy-dom +import { StrictMode, act } from 'react' +import { createRoot } from 'react-dom/client' +import { expect, it, vi } from 'vitest' + +;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true + +it('shows the TeX source and stops loading KaTeX after a failed load in StrictMode', async () => { + let attempts = 0 + vi.doMock('katex', () => { + attempts++ + throw new Error('Failed to fetch dynamically imported module') + }) + const { Math } = await import('../src/plugins/math') + const container = document.createElement('div') + const root = createRoot(container) + + await act(async () => { + root.render( + + + + ) + }) + await act(() => new Promise((resolve) => setTimeout(resolve, 100))) + + expect(container.innerHTML).toBe('x^2') + expect(attempts).toBe(1) + + act(() => root.unmount()) + vi.doUnmock('katex') +}) diff --git a/packages/comark-react/test/plugin-math.test.tsx b/packages/comark-react/test/plugin-math.test.tsx index 17f2e020..4e9d5898 100644 --- a/packages/comark-react/test/plugin-math.test.tsx +++ b/packages/comark-react/test/plugin-math.test.tsx @@ -1,12 +1,11 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { renderToString } from 'react-dom/server' import { parseMarkdown } from 'comark' import { MarkdownDocument } from '../src/components/MarkdownDocument' import math, { Math } from '../src/plugins/math' // `Math` derives its wrapper markup from the incoming class string, so the -// `class` -> `className` renderer remap is observable under SSR alone; -// `useEffect` (katex) never runs here. +// `class` -> `className` renderer remap is observable under SSR alone. describe('@comark/react plugins/math — Math component', () => { it('renders inline math as an inline ', async () => { @@ -31,4 +30,75 @@ describe('@comark/react plugins/math — Math component', () => { ) expect(html).toContain('
{ + const tree = await parseMarkdown('$\\frac{}{$', { plugins: [math()] }) + const html = renderToString( + + ) + expect(html).toContain('\\frac{<b>}{') + expect(html).not.toContain('...') + }) + + it('waits for KaTeX in streaming server rendering', async () => { + vi.resetModules() + const { Math } = await import('../src/plugins/math') + const { renderToReadableStream, renderToString } = await import('react-dom/server') + + expect( + renderToString( + + ) + ).toContain('x^2') + + const stream = await renderToReadableStream( + + ) + await stream.allReady + const html = await new Response(stream).text() + + expect(html).toContain('') + }) + + it('loads KaTeX again after a failed load', async () => { + vi.resetModules() + let fail = true + vi.doMock('katex', async (importOriginal) => { + if (fail) throw new Error('Failed to fetch dynamically imported module') + return importOriginal() + }) + const { Math } = await import('../src/plugins/math') + const { renderToReadableStream } = await import('react-dom/server') + const render = async () => { + const stream = await renderToReadableStream( + + ) + await stream.allReady + return new Response(stream).text() + } + + vi.useFakeTimers({ toFake: ['Date'] }) + try { + expect(await render()).toContain('x^2') + fail = false + expect(await render()).toContain('x^2') + vi.advanceTimersByTime(5000) + expect(await render()).toContain('') + } finally { + vi.useRealTimers() + vi.doUnmock('katex') + } + }) }) diff --git a/packages/comark-svelte/src/components/Math.svelte b/packages/comark-svelte/src/components/Math.svelte index 7ff4088f..330b17ab 100644 --- a/packages/comark-svelte/src/components/Math.svelte +++ b/packages/comark-svelte/src/components/Math.svelte @@ -15,9 +15,33 @@ determines inline vs display mode (display when class does NOT contain "inline") ``` --> - + {#if isInline} - {@html mathml} + {#if html}{@html html}{:else}{content}{/if} {:else} -
{@html mathml}
+
{#if html}{@html html}{:else}{content}{/if}
{/if} diff --git a/packages/comark-svelte/test/math/index.svelte.test.ts b/packages/comark-svelte/test/math/index.svelte.test.ts index 6ea3c00f..114f586a 100644 --- a/packages/comark-svelte/test/math/index.svelte.test.ts +++ b/packages/comark-svelte/test/math/index.svelte.test.ts @@ -10,20 +10,21 @@ describe('Math component', () => { const screen = await render(Math, { content: 'x^2', class: 'inline' }) const wrapper = screen.container.querySelector('.math.inline')! expect(wrapper).not.toBeNull() - expect(wrapper.querySelector('.katex')).not.toBeNull() + await expect.poll(() => wrapper.querySelector('.katex')).not.toBeNull() }) it('renders display math with KaTeX', async () => { const screen = await render(Math, { content: 'E = mc^2', class: '' }) const wrapper = screen.container.querySelector('.math.block')! expect(wrapper).not.toBeNull() - expect(wrapper.querySelector('.katex')).not.toBeNull() + await expect.poll(() => wrapper.querySelector('.katex')).not.toBeNull() }) - it('handles invalid LaTeX gracefully', async () => { + it('shows the TeX source for invalid LaTeX', async () => { const screen = await render(Math, { content: '\\invalid{', class: '' }) const wrapper = screen.container.querySelector('.math.block')! expect(wrapper).not.toBeNull() + expect(wrapper.textContent).toBe('\\invalid{') }) }) diff --git a/packages/comark-svelte/test/math/index.test.ts b/packages/comark-svelte/test/math/index.test.ts index 8a9aa1df..dbfa6d41 100644 --- a/packages/comark-svelte/test/math/index.test.ts +++ b/packages/comark-svelte/test/math/index.test.ts @@ -10,22 +10,20 @@ function html(body: string): string { } describe('Math component (server)', () => { - it('renders inline math', () => { + it('renders inline math as its source', () => { const { body } = render(Math, { props: { content: 'x^2', class: 'inline' }, }) const output = html(body) - expect(output).toContain('') - expect(output).toContain('katex') + expect(output).toContain('x^2') }) - it('renders display math', () => { + it('renders display math as its source', () => { const { body } = render(Math, { props: { content: 'E = mc^2', class: '' }, }) const output = html(body) - expect(output).toContain('
') - expect(output).toContain('katex') + expect(output).toContain('
E = mc^2
') }) it('handles invalid LaTeX gracefully', () => { @@ -33,7 +31,7 @@ describe('Math component (server)', () => { props: { content: '\\invalid{', class: '' }, }) const output = html(body) - expect(output).toContain('
') + expect(output).toContain('
\\invalid{
') }) }) @@ -54,8 +52,7 @@ describe('Math + MarkdownDocument integration (server)', () => { props: { value: tree, components: { math: Math } }, }) const output = html(body) - expect(output).toContain('') - expect(output).toContain('katex') + expect(output).toContain('x^2') expect(output).toContain('The formula') }) @@ -67,8 +64,7 @@ describe('Math + MarkdownDocument integration (server)', () => { props: { value: tree, components: { math: Math } }, }) const output = html(body) - expect(output).toContain('
') - expect(output).toContain('katex') + expect(output).toContain('
E = mc^2
') }) it('renders mixed inline and display math', async () => { diff --git a/packages/comark-vue/src/components/Math.ts b/packages/comark-vue/src/components/Math.ts index 5e8e0931..d44bb8fa 100644 --- a/packages/comark-vue/src/components/Math.ts +++ b/packages/comark-vue/src/components/Math.ts @@ -1,7 +1,30 @@ -import { defineComponent, h, computed, watch, ref } from 'vue' -import katex from 'katex' +import { defineAsyncComponent, defineComponent, h, onMounted, onServerPrefetch, ref } from 'vue' -export const Math = defineComponent({ +let katex: typeof import('katex').default | undefined +let loading: Promise | undefined + +function loadKatex(): Promise { + loading ??= import('katex').then( + (module) => (katex = module.default), + (error) => { + loading = undefined + throw error + } + ) + return loading +} + +// HTML, `''` when KaTeX can't typeset the formula, or `undefined` before KaTeX loads. +function typeset(tex: string, displayMode: boolean): string | undefined { + if (!katex) return undefined + try { + return katex.renderToString(tex, { throwOnError: true, displayMode }) + } catch { + return '' + } +} + +const Typeset = defineComponent({ name: 'Math', props: { content: { @@ -18,38 +41,38 @@ export const Math = defineComponent({ }, }, setup(props) { - const isInline = computed(() => { - return props.class?.includes('inline') - }) - const mathml = ref('...') - - watch( - () => props.content, - () => { - try { - mathml.value = katex.renderToString(props.content, { - throwOnError: true, - displayMode: !isInline.value, - }) - } catch { - // Keep previous output while expression is incomplete - } - }, - { immediate: true } - ) - - if (isInline.value) { - return () => - h('span', { - class: 'math inline', - innerHTML: mathml.value, - }) + // KaTeX failed to load earlier: retry, and typeset once it loads. + const loaded = ref(katex !== undefined) + if (!loaded.value) { + const retry = () => + loadKatex().then( + () => (loaded.value = true), + () => {} + ) + onServerPrefetch(retry) + onMounted(retry) } - return () => - h('div', { - class: 'math block', - innerHTML: mathml.value, - }) + return () => { + void loaded.value + const isInline = props.class?.includes('inline') + const tag = isInline ? 'span' : 'div' + const className = isInline ? 'math inline' : 'math block' + const html = typeset(props.content, !isInline) + // Unfinished or invalid TeX, and TeX before KaTeX loads, stays readable as its source. + return html ? h(tag, { class: className, innerHTML: html }) : h(tag, { class: className }, props.content) + } }, }) + +export const Math = defineAsyncComponent({ + loader: () => + loadKatex().then( + () => Typeset, + () => Typeset + ), + // A copy, since Vue doesn't render the same component again with the same props. + loadingComponent: { ...Typeset }, + delay: 0, + suspensible: false, +}) diff --git a/packages/comark-vue/test/plugin-math.test.ts b/packages/comark-vue/test/plugin-math.test.ts new file mode 100644 index 00000000..cbec6533 --- /dev/null +++ b/packages/comark-vue/test/plugin-math.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it, vi } from 'vitest' +import { createSSRApp, h } from 'vue' +import { renderToString } from '@vue/server-renderer' +import { parseMarkdown } from 'comark' +import { MarkdownDocument } from '../src/components/MarkdownDocument' +import math, { Math } from '../src/plugins/math' + +describe('@comark/vue plugins/math — Math component', () => { + it('waits for KaTeX in server rendering', async () => { + const html = await renderToString(createSSRApp({ render: () => h(Math, { content: 'x^2', class: 'math inline' }) })) + + expect(html).toContain('') + }) + + it('shows the escaped TeX source when KaTeX cannot parse it', async () => { + const tree = await parseMarkdown('$\\frac{}{$', { plugins: [math()] }) + const app = createSSRApp({ + setup: () => () => h(MarkdownDocument, { value: tree, components: { math: Math } }), + }) + + expect(await renderToString(app)).toContain('\\frac{<b>}{') + }) + + it('loads KaTeX again after a failed load', async () => { + vi.resetModules() + let fail = true + vi.doMock('katex', async (importOriginal) => { + if (fail) throw new Error('Failed to fetch dynamically imported module') + return importOriginal() + }) + const { Math } = await import('../src/plugins/math') + const { createSSRApp, h } = await import('vue') + const { renderToString } = await import('@vue/server-renderer') + const render = () => + renderToString(createSSRApp({ render: () => h(Math, { content: 'x^2', class: 'math inline' }) })) + + try { + expect(await render()).toContain('x^2') + fail = false + expect(await render()).toContain('') + } finally { + vi.doUnmock('katex') + } + }) +}) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b4e1f680..6bcf397c 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -344,6 +344,9 @@ catalogs: github-slugger: specifier: ^2.0.0 version: 2.0.0 + happy-dom: + specifier: ^21.0.4 + version: 21.0.4 hast-util-to-string: specifier: ^3.0.1 version: 3.0.1 @@ -1662,6 +1665,9 @@ importers: '@vitest/browser-playwright': specifier: 'catalog:' version: 5.1.0(playwright@1.65.1)(vite@8.3.8(@types/node@26.6.6)(esbuild@0.28.2)(jiti@2.7.0)(less@4.9.1(supports-color@10.2.2))(sass-embedded@1.104.1)(sass@1.104.1)(terser@5.51.2)(tsx@4.23.15)(yaml@2.9.1))(vitest@5.1.0) + happy-dom: + specifier: 'catalog:' + version: 21.0.4 react: specifier: 'catalog:' version: 19.3.1 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 6be96ec1..07c49016 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -166,6 +166,7 @@ catalog: # Testing "@codspeed/vitest-plugin": ^6.1.1 + happy-dom: ^21.0.4 tinybench: ^6.2.3 vitest: ^5.1.0 vitest-browser-svelte: ^3.1.0 diff --git a/test/bundle.test.ts b/test/bundle.test.ts index 19cff971..6cf3cb97 100644 --- a/test/bundle.test.ts +++ b/test/bundle.test.ts @@ -70,14 +70,14 @@ describe('package bundle size', { timeout: 60_000 }, () => { expect(report).toMatchInlineSnapshot(` { - "@comark/angular": "70.1k (63 files)", + "@comark/angular": "70.5k (63 files)", "@comark/ansi": "42.1k (109 files)", "@comark/html": "17.7k (69 files)", "@comark/nuxt": "11.0k (69 files)", - "@comark/react": "43.3k (87 files)", - "@comark/svelte": "51.0k (95 files)", - "@comark/vue": "62.7k (93 files)", - "comark": "457k (177 files)", + "@comark/react": "44.4k (87 files)", + "@comark/svelte": "51.7k (95 files)", + "@comark/vue": "63.3k (93 files)", + "comark": "458k (177 files)", } `) })