Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/content/4.plugins/1.built-in/math.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<Markdown>` (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 `<Markdown>` (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

Expand Down
45 changes: 37 additions & 8 deletions packages/comark-angular/src/components/math.component.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,28 @@
import { Component, Input, OnChanges, SimpleChanges, ChangeDetectionStrategy, ElementRef, inject } from '@angular/core'
import katex from 'katex'

let katex: typeof import('katex').default | undefined
let loading: Promise<unknown> | undefined

function loadKatex(): Promise<unknown> {
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.
Expand Down Expand Up @@ -44,13 +67,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 html = typeset(this.content, !isInline)
if (html) {
wrapper.innerHTML = html
} else {
// Unfinished or invalid TeX, and TeX before KaTeX loads, stays readable as its source.
wrapper.textContent = this.content
if (html === undefined) {
const content = this.content
loadKatex().then(
() => content === this.content && this.renderMath(),
() => {}
)
}
}

hostEl.appendChild(wrapper)
Expand Down
1 change: 1 addition & 0 deletions packages/comark-react/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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:"
Expand Down
105 changes: 86 additions & 19 deletions packages/comark-react/src/components/Math.tsx
Original file line number Diff line number Diff line change
@@ -1,40 +1,107 @@
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<unknown> | undefined

function loadKatex(): Promise<unknown> {
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<string>('...')

useEffect(() => {
try {
const rendered = katex.renderToString(content, {
throwOnError: true,
displayMode: !isInline,
})
setMathml(rendered)
} catch {
// Keep loading state on error
}
}, [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<boolean> | undefined
let failedAt: number | undefined

function waitForKatex(): Promise<boolean> {
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 (
<Source
content={content}
isInline={isInline}
/>
)

if (isInline) {
return (
<span
className="math inline"
dangerouslySetInnerHTML={{ __html: mathml }}
dangerouslySetInnerHTML={{ __html: html }}
/>
)
}

return (
<div
className="math block"
dangerouslySetInnerHTML={{ __html: mathml }}
dangerouslySetInnerHTML={{ __html: html }}
/>
)
})

function Source({ content, isInline }: { content: string; isInline: boolean }) {
return isInline ? <span className="math inline">{content}</span> : <div className="math block">{content}</div>
}

export function Math({ content, className = '' }: MathProps) {
const isInline = className.includes('inline')

return (
<Suspense
fallback={
<Source
content={content}
isInline={isInline}
/>
}
>
<Typeset
content={content}
isInline={isInline}
/>
</Suspense>
)
}
35 changes: 35 additions & 0 deletions packages/comark-react/test/plugin-math.client.test.tsx
Original file line number Diff line number Diff line change
@@ -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(
<StrictMode>
<Math
content="x^2"
className="math inline"
/>
</StrictMode>
)
})
await act(() => new Promise((resolve) => setTimeout(resolve, 100)))

expect(container.innerHTML).toBe('<span class="math inline">x^2</span>')
expect(attempts).toBe(1)

act(() => root.unmount())
vi.doUnmock('katex')
})
76 changes: 73 additions & 3 deletions packages/comark-react/test/plugin-math.test.tsx
Original file line number Diff line number Diff line change
@@ -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 <span class="math inline">', async () => {
Expand All @@ -31,4 +30,75 @@ describe('@comark/react plugins/math — Math component', () => {
)
expect(html).toContain('<div class="math block"')
})

it('shows the escaped TeX source when KaTeX cannot parse it', async () => {
const tree = await parseMarkdown('$\\frac{<b>}{$', { plugins: [math()] })
const html = renderToString(
<MarkdownDocument
value={tree}
components={{ math: Math }}
/>
)
expect(html).toContain('<span class="math inline">\\frac{&lt;b&gt;}{</span>')
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(
<Math
content="x^2"
className="math inline"
/>
)
).toContain('<span class="math inline">x^2</span>')

const stream = await renderToReadableStream(
<Math
content="x^2"
className="math inline"
/>
)
await stream.allReady
const html = await new Response(stream).text()

expect(html).toContain('<span class="math inline"><span class="katex">')
})

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(
<Math
content="x^2"
className="math inline"
/>
)
await stream.allReady
return new Response(stream).text()
}

vi.useFakeTimers({ toFake: ['Date'] })
try {
expect(await render()).toContain('<span class="math inline">x^2</span>')
fail = false
expect(await render()).toContain('<span class="math inline">x^2</span>')
vi.advanceTimersByTime(5000)
expect(await render()).toContain('<span class="math inline"><span class="katex">')
} finally {
vi.useRealTimers()
vi.doUnmock('katex')
}
})
})
50 changes: 36 additions & 14 deletions packages/comark-svelte/src/components/Math.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,33 @@ determines inline vs display mode (display when class does NOT contain "inline")
<Markdown value="$E = mc^2$" plugins={[math()]} components={{ math: Math }} />
```
-->
<script lang="ts">
import katex from 'katex'
<script module lang="ts">
let katex: typeof import('katex').default | undefined
let loading: Promise<unknown> | undefined

function loadKatex(): Promise<unknown> {
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 ''
}
}
</script>

<script lang="ts">
let {
content,
class: className = '',
Expand All @@ -28,22 +52,20 @@ determines inline vs display mode (display when class does NOT contain "inline")

let isInline = $derived(className.split(' ').includes('inline'))

let mathml = $derived.by(() => {
try {
return katex.renderToString(content, {
throwOnError: true,
displayMode: !isInline,
})
}
catch {
return '...'
}
let loaded = $state(false)
let html = $derived.by(() => {
void loaded
return typeset(content, !isInline)
})

$effect(() => {
if (html === undefined) loadKatex().then(() => (loaded = true), () => {})
})
</script>

<!-- eslint-disable svelte/no-at-html-tags -- KaTeX output is safe rendered HTML -->
{#if isInline}
<span class="math inline">{@html mathml}</span>
<span class="math inline">{#if html}{@html html}{:else}{content}{/if}</span>
{:else}
<div class="math block">{@html mathml}</div>
<div class="math block">{#if html}{@html html}{:else}{content}{/if}</div>
{/if}
Loading
Loading