Skip to main content

Markdown

Renders Markdown from a model as it streams, with mantle's CodeBlock, Table, and Anchor for its fences, tables, and links. Pass the text so far as children, and set streaming while more text can arrive.

Desktop viewport
Tablet viewport
Mobile viewport

When to use

  • Render Markdown that arrives at runtime, such as a model's answer, while it streams and after it ends.
  • Prefer CodeBlock when the content is one block of code.
  • Prefer Typography for prose that you write in the source, not prose that arrives at runtime.

Complete answers

Leave streaming off for an answer that is already complete, such as an answer in a chat history. Each fence still highlights in the browser after the page loads. Until then, it shows as plain text with the same layout, so nothing moves.

Desktop viewport
Tablet viewport
Mobile viewport

Read a stream

useMarkdownStream reads a stream of text chunks, such as a fetch body, and returns the text so far and a status. It renders at most once per animation frame, however fast the chunks arrive.

The hook resumes. When the stream fails, it calls read again with the length of the text so far as offset, and the answer continues where it stopped. After a reload, pass the partial answer that the server rendered as initialText, and the stream continues after it with no flash. The server must skip offset characters of the answer.

This fence needs a server that streams an answer, so no example renders it.

import { Markdown, useMarkdownStream } from "@ngrok/mantle/markdown"; function Answer({ id, partial }: { id: string; partial: string }) {	const { text, status } = useMarkdownStream({		initialText: partial,		read: async ({ offset, signal }) => {			const response = await fetch(`/answers/${id}?offset=${offset}`, { signal });			if (!response.ok || response.body == null) {				throw new Error(`The answer stream failed: ${response.status}`);			}			return response.body.pipeThrough(new TextDecoderStream());		},	});	return <Markdown streaming={status === "streaming"}>{text}</Markdown>;}

Math

Pass markdownMath() in extensions to read TeX math: $$…$$ and \[…\] as display math, and $…$ and \(…\) as inline math. A $ that reads as a price, such as in $5 and $10, stays text. Render each formula with a math component, such as with KaTeX. Without one, a formula shows its TeX source as code.

Keep extensions and components stable, such as at module scope. A new extensions array parses the whole answer again, and a new components object renders each block again.

Desktop viewport
Tablet viewport
Mobile viewport

Components

Set a component in components to replace the built-in one for a kind of token, such as code, link, table, or math. Each component gets the marked token and its content as children. extension renders each token of a marked extension that has no component of its own.

How it streams

  • Each update lexes only the unfinished block at the end, so a long answer costs the same for each update as a short one.
  • A finished block never renders again, and a block keeps its element from when it starts to stream to when it finishes.
  • Unfinished syntax, such as **bol, an open fence, or a link with no URL yet, renders closed.
  • A fence highlights in a module worker, one changed line at a time. A finished line never renders again.
  • When streaming turns off, the whole answer parses once more, so a reference link that comes before its definition resolves.

Security

The output is React elements, never innerHTML, and no part needs a CSP change beyond worker-src 'self' for the highlighter. Raw HTML shows as text, except the inline tags of GitHub's sanitize schema, such as <sub>, <kbd>, and <br>. So a placeholder such as <your-domain> stays in a command. A link may use http:, https:, mailto:, tel:, or a relative URL, and an image may use http:, https:, or a relative URL. Any other URL, such as javascript:, renders as text.

Accessibility

Markdown is not a live region, so a screen reader does not read an answer as it streams. A reading of each chunk or each block breaks into whatever the reader is doing, such as reading the main page while an answer streams in a side panel. While streaming, the root is aria-busy.

Announce the answer's state from the chat, not its text. Keep one visually hidden role="status" region in the chat for the life of the page. Set it to a short message when an answer starts, such as "Responding", and when it ends, such as "Response complete" from onStreamEnd. The reader then moves to the answer when they choose. ChatGPT and Claude work this way.

const [status, setStatus] = useState(""); <span role="status" className="sr-only">	{status}</span><Markdown streaming={isStreaming} onStreamEnd={() => setStatus("Response complete")}>	{text}</Markdown>

A task-list checkbox takes its item's text as its name. The caret and the fade-in show only when the reader allows motion.

API Reference

Markdown

PropTypeDefaultDescription
childrenstringThe Markdown so far. While it streams, each update appends to it.
streamingbooleanfalseWhether more Markdown can arrive. Closes unfinished syntax, renders once per frame, shows a caret.
componentsMarkdownComponentsThe components that replace the built-in one for a token. Keep the object stable.
extensionsreadonly MarkdownExtension[]Marked extensions, such as markdownMath(). Keep the array stable.
onBlockComplete(block: MarkdownBlockEvent) => voidCalled once for each block that finishes after mount, in order.
onStreamEnd() => voidCalled once when streaming turns from true to false.

Other props go to the root <div>.

Data AttributeValueDescription
data-slot"markdown"The root. The prose styles in mantle.css match it.
data-streaming""Present while streaming. Shows the caret.
data-streamed""Present once the answer has streamed on this page. A new block fades in.
data-task""On a task-list item, which holds a checkbox.

useMarkdownStream

OptionTypeDefaultDescription
read({ offset, signal }) => MarkdownStreamSource | Promise<…>Opens the answer's stream from offset, the length of the text so far.
initialTextstring""The text the page already shows. The stream continues after it.
enabledbooleantrueWhether to read the stream. Set false for an answer that is complete.
retriesnumber3How many times to open the stream again after it fails, from 500 ms, doubling.

It returns { text, status, error }. status is "streaming", "done", or "error".

markdownMath

Returns a marked extension that reads TeX math as math tokens, with text and display.