Math / LaTeX support ($…$ / $$…$$) — community extension available, two extension API gaps #13
Send to my agentSummary#
@tanstack/markdown (0.0.13) has no math support, and math is a common need for technical/docs content. I built and published tanstack-markdown-math (npm), a KaTeX extension built on the current extension API. It works today, and writing it surfaced two API gaps that force workarounds which a first-class design could remove.
This issue is half "show and tell", half design discussion: would built-in math support — or the two API additions below — be welcome?
What the extension does#
- Block
$$…$$(multi-line and single-line) viaparseBlock, emitted as anhtmlnode - Inline
$…$in paragraphs, headings, strong/emphasis/strike, links, blockquotes, callouts, list items (recursive), table cells (recursive) - Strict-by-default inline matching (avoids
$5 and $10false positives), opt-in permissive mode - Streaming-safe: an unclosed
$$block still produces a rendered partial node instead of crashing - Pluggable renderer (
renderoption), KaTeX by default - Validated on a dense-math, 900+ page corpus through the streaming pipeline
import { Markdown } from '@tanstack/markdown/react'
import { mathExtension } from 'tanstack-markdown-math'
<Markdown extensions={mathExtension()} allowHtml>
{`The energy is $E = mc^2$.`}
</Markdown>
What works well#
parseBlockruns before built-in block parsers (extensions are earlier in the array), so$$fences take precedence cleanlytransformInlineis called once per inline container with the container's top-level nodes, nested typed nodes included — enough to run a recursive inline pass during parsing- The extension API covers this use case end-to-end; no forks or patches needed
Gap 1: closed AST node unions force html injection#
BlockNode / InlineNode are closed unions, so an extension cannot emit a semantic node — it must pre-render to a string and emit html / inlineHtml. Consequences:
- The AST is no longer serialization-clean (rendered KaTeX HTML embedded in it)
- React consumers get
dangerouslySetInnerHTMLinstead of a real KaTeX component tree (no SSR-safe hydration, no CSS scoping choices) allowHtml: truebecomes mandatory for math to appear at all, which loosens the document's security posture just to display math
A first-class math / inlineMath node type (raw TeX as payload), with renderers knowing how to draw it, would fix all three. That requires renderer cooperation, which the current API doesn't offer — hence gap 2.
Gap 2: no renderer-level extension hook for React#
renderHtml covers the HTML renderer, but the React renderer has no equivalent: an extension cannot influence how a node becomes React elements. Any extension that needs React semantics today has to inject HTML strings.
Something like a renderReact?: (node, ctx) => ReactElement | undefined hook (mirroring renderHtml) would let extensions participate in both renderers symmetrically — and would make a first-class math node trivial to render as a KaTeX component.
Proposal#
Either or both:
- Built-in math support — I'm happy to contribute the parsing/delimiter logic upstream (MIT); the strict-by-default inline rules and streaming behavior are already battle-tested
- Extension API additions — open the AST to extension-defined node types (or add
math/inlineMath), and add a React renderer hook for extensions
Happy to split this into separate issues / PRs if that's easier to triage. Would love feedback on which direction fits the roadmap.
- Repo: https://github.com/bertrandgressier/tanstack-markdown-math
- npm: https://www.npmjs.com/package/tanstack-markdown-math
- Tested against:
@tanstack/markdown0.0.13
tannerlinsley added labelsduplicate
tannerlinsley closed this
Thanks a lot @tannerlinsley for the detailed response — really appreciated, and super helpful for steering this in the right direction. 🙏
Following your remarks, we shipped tanstack-markdown-math 0.2.0 aligned with the direction you described:
- Block math via
ComponentNode, noallowHtml— new opt-inoutput: 'component'mode emits exactly the pattern you validated: raw TeX inproperties.tex, customtagName(defaultMathBlock) resolved through the Reactcomponentsmap. The HTML renderer path works with zero config via the extension'srenderHtmlhook (raw HTML only for the KaTeX island). Verified against the HTML renderer, React SSR (renderToStaticMarkup+componentsmap), and JSON round-trip of the AST. - Everything stays opt-in — math remains a separate package, no KaTeX dependency in core, no built-in node types, no bundle impact.
- Peer range widened to support 0.0.14.
- Inline math still uses
inlineHtmlfor now, pending #9. If theInlineComponentNodeidea is ever revisited, we'd be happy to help test it against a dense-math, 900+ page corpus — the constraints from #7 are clear, and even a documented workaround pattern (like the block-level one above) would go a long way.
Thanks again — closing the loop here since this is consolidated into #9. 👍
- Block math via
The inline component support has now landed in #17 and is queued for 0.0.15. It is not on npm yet.
Extensions can emit an
InlineComponentNodewithtype: 'inlineComponent',tagName: 'MathInline',properties: { tex },attributes: {}, andchildren: []. Setnameto your extension's component name. React and Octane resolve the tag through theircomponentsmaps, and the HTML renderer supports the existingrenderHtmlhook. This does not requireallowHtmlfor the Markdown source.Math stays in your opt-in package. Once 0.0.15 is available, testing this path against your corpus would be useful.
Following up on this with some good news —
tanstack-markdown-math@0.3.0is out, built directly on theinlineComponentpath you shipped in #17.Thanks a lot for the follow-up and the pointers — the design worked exactly as described:
- Inline math now emits
inlineComponentnodes (name: 'math',tagName: 'MathInline'by default, raw TeX inproperties.tex) whenoutput: 'component'is set. Block + inline math both render withoutallowHtml: the extension'srenderHtmlhook covers the HTML renderer with zero config, and React consumers mapMathInline/MathBlockvia thecomponentsoption (both exported from atanstack-markdown-math/reactsubpath, memoized on(tex, displayMode)). - AST is serialization-clean in component mode — on our test corpus (262 KB of dense medical notes, ~1150 formulas) the AST JSON drops from ~3 MB to ~680 KB, and streaming re-parses get ~6.5x cheaper since KaTeX output is no longer embedded in the AST.
- Perf: a transparent LRU render cache (keyed by
(tex, displayMode), opt-out viacache: false/ custom size) cuts parse+render on that corpus from ~44 ms to ~8–11 ms depending on mode. 37% of our formulas repeat, so this pays off quickly. - Everything stays opt-in (
output: 'html'default unchanged, works back to 0.0.13; the inline component path requires >=0.0.15, which the peer range expresses).
As you suggested, this was validated against the dense-math corpus through the streaming pipeline — 88 tests including real-world formula extraction from those notes (chemistry brackets, French decimal commas, prose-dollar false positives).
Happy to keep testing upstream changes against the corpus whenever useful — and thanks again for taking the time to walk us through the constraints. It made the design decisions much easier. 🙏
- Inline math now emits
Sign in to join this conversation.
The community extension is a useful direction, but math parsing and KaTeX will remain opt-in rather than becoming core dependencies or built-in node types.
There is a genuine custom-inline gap here, and we are tracking it in #9. For block output, the existing ComponentNode can already carry raw TeX in properties and select a React or Octane component through tagName and the components map, without allowHtml. I verified that route against HTML, React SSR, and Octane SSR. The same portable model for inline output is the missing piece.
Two clarifications: an AST containing HTML strings is still JSON-serializable, and dangerouslySetInnerHTML does not by itself prevent deterministic SSR/hydration. Requiring allowHtml for a math extension does broaden the raw-source trust boundary, so avoiding that requirement remains worthwhile.
Closing this discussion to consolidate the actionable inline API work in #9, which remains open. This is not a rejection of the extension or a claim that its inline limitation is fixed. We are not accepting bundle growth for this feature.