Markdown
Overview
The Markdown component renders markdown, such as a model's reply, as it streams in.
It comes from the @allxsmith/bestax-ai package, the AI kit, and renders a
reply as React elements inside Bulma's Content, with code blocks in
CodeBlock and tables in Table. Its parser
is written for streaming: while a reply arrives, each update parses again only the block still
arriving, and half-written markup waits rather than flashing on screen. Whatever the reply says is
treated as untrusted, so raw HTML shows as text and every address is checked before it becomes a
link.
Import
import { Markdown } from '@allxsmith/bestax-ai';
The package takes React, React DOM and @allxsmith/bestax-bulma as peers, the copies your app
already has, and installs nothing else.
- pnpm
- npm
- yarn
- bun
pnpm add @allxsmith/bestax-ai
npm install @allxsmith/bestax-ai
yarn add @allxsmith/bestax-ai
bun add @allxsmith/bestax-ai
Usage
Basic Usage
Pass the markdown as content. A top-level # heading renders as an h2, since a reply sits
inside a page that has its own h1.
<Markdown content={`# Trip plan Three days in **Lisbon**, with time for the _coast_: 1. Belém and the river 2. Alfama, then a tram up the hill 3. A day in Sintra | Day | Area | Getting there | | --- | --- | --- | | 1 | Belém | Tram 15 | | 2 | Alfama | On foot | | 3 | Sintra | Train from Rossio | > Book the Sintra palaces a day ahead.`} />
Streaming
Set isStreaming while the reply is still arriving, and clear it when it ends. Each update that
adds to the end parses again only the last block, so a long reply costs about as much per chunk as
its last block. Half-written markup waits: a link shows its text and no address until its )
arrives, and markers that don't mean anything yet are held back. showCaret draws a caret after
the text while the reply streams.
function example() { const reply = `## Making cold brew Coarsely grind **100 g** of coffee, then stir it into a litre of _cold_ water. Steep it for 12 to 18 hours, then strain it twice. The [ratio guide](https://bestax.io) has more on strength. ~~~text 100 g coffee : 1 l water ~~~ - [x] Grind - [ ] Steep - [ ] Strain`; const [length, setLength] = useState(reply.length); useEffect(() => { if (length >= reply.length) return; const timer = setTimeout(() => setLength(n => n + 5), 40); return () => clearTimeout(timer); }, [length, reply.length]); return ( <> <Button size="small" mb="3" onClick={() => setLength(0)}> Stream it again </Button> <Markdown content={reply.slice(0, length)} isStreaming={length < reply.length} showCaret /> </> ); }
Heading Levels
topHeadingAs sets the element a # heading renders as, and shifts every level with it. In a chat
whose messages carry their own headings, start a reply's at h3. A level past h6 stays h6.
<Markdown topHeadingAs="h3" content={'# Summary\n\n## Details\n\nThe body.'} />
Code Blocks
Code renders in CodeBlock, with the fence's language as its label.
codeBlockProps passes props to every block, and highlighter takes a highlighter as CodeBlock
does. Left out, it's the one a ConfigProvider sets with codeHighlighter, so one highlighter
serves the docs and the chat alike. The CodeBlock page
shows highlighters built on Prism and Shiki.
<Markdown codeBlockProps={{ showLineNumbers: true, showWrapToggle: true }} content={`Start the server: ~~~js import { createServer } from 'node:http'; createServer((req, res) => res.end('ok')).listen(3000); ~~~`} />
Links
Links open in a new tab, with visually hidden text that says so, and every link gets
rel="noopener noreferrer". linkTarget="_self" opens them in place. An address must use http,
https or mailto, or the schemes you list in allowedProtocols, and allowUrl can narrow that
further. A relative address, such as a link to one of your own pages, is dropped unless allowUrl
admits it, and only one rooted at the site (/docs), or only a fragment (#top), can be. A path
relative to the page (docs/x) is refused, and so is a query on its own (?page=2): it renders
relative, so the browser resolves it when the link is followed, against whatever page it's on then,
which in an app that changes pages without reloading may be one allowUrl never saw. One that
resolves to another site, such as //host, is refused before allowUrl is asked. A relative
address resolves against the page's base URL, the document's baseURI, which a <base> element
moves. A refused link renders its text.
When Markdown renders on the server, which has no base URL, a relative address resolves against a
placeholder origin. There, an allowUrl that can't know the page's should refuse relative
addresses, or render the reply on the client. Otherwise, with showImages, a root-relative image on
an http page can be in the server's HTML and load over http before hydration takes it out. One
that runs on both must still check the origin of an absolute address, since an image in the
server's HTML loads before the page hydrates.
<Markdown linkTarget="_self" allowedProtocols={['https', 'mailto', 'tel']} allowUrl={(url, kind) => kind === 'link' && (url.protocol !== 'https:' || url.hostname === 'bestax.io') } content={`- [The docs](https://bestax.io/docs/api/ai/overview) link. - [Another site](https://example.com) doesn't, since allowUrl refuses it. - [Call us](tel:+15550100) links, since allowedProtocols lists tel. - [This](javascript:alert(1)) never links, whatever the options say.`} />
Images
Images are off by default: an image shows as a link to it, with its description as the text. Set
showImages to load them. Only https images load, with no referrer, and allowUrl decides which.
Here it admits the site's own pictures. It checks the origin as well as the path, since a reply's
https://another.example/img/… has the same path on someone else's site.
<Markdown showImages allowUrl={url => url.origin === window.location.origin && url.pathname.startsWith('/img/') } content="" />
Your Own Components
components renders elements with your own components, by the element's name: a for links,
pre for code blocks, p, h1 to h6, table and the rest. Each gets the props Markdown would
give the element, its children included, plus isPending, which is true while the block it's
in is still arriving. A code block's pre gets the props Markdown would give CodeBlock. Define
the object at module scope or in a useMemo, so each render passes the same components.
import type { MarkdownComponents } from '@allxsmith/bestax-ai'; function example() { const [components] = useState<MarkdownComponents>(() => ({ pre: ({ isPending, ...props }) => ( <CodeBlock {...props} title={isPending ? 'Writing…' : 'Ready to copy'} /> ), })); return ( <Markdown components={components} content={'Run it:\n\n~~~bash\npnpm add @allxsmith/bestax-ai\n~~~'} /> ); }
Size
size sizes the text, as it does on Content.
<Markdown size="small" content="A **small** reply, for a narrow side panel." />
What It Renders
All of CommonMark except raw HTML, plus GitHub's tables, strikethrough, task lists and bare-URL links.
- Raw HTML shows as the text it was written as. The one exception is a bare
<br>, which breaks the line, since that's how a table cell holds more than one line. - Character references such as
©and©are read for the HTML 4 set of names and every number. A name outside that set stays as written. - Tables fill out a row with fewer cells than the header with empty ones, up to 10,000 of them in a table. Past that the table ends and the rest reads as text, so a wide header over many short rows can't make work out of proportion to the reply.
- Not yet: footnotes, math and Mermaid diagrams. They show as the markdown they're written in.
- Conformance: the parser is checked against the CommonMark spec's own examples in CI, and an example it passes must keep passing.
Streaming Behavior
While isStreaming is set, the end of the reply is read with care, so nothing flashes and nothing
loads early:
| The end of the reply so far | What shows |
|---|---|
**bold, *emphasis, ~~gone after a marker that opens | Styled to the end |
A run of *, _, ~ or backticks, a \, or & | Nothing, until the next character says what it is |
`code with no closing backtick | Code to the end |
[text, [text](https://exa | The text, never a link |
. A build without Bulma's helpers has no such class, so there givecomponents.aa link that underlines itself. - New tabs say so: a link that opens in a new tab ends with visually hidden text, "(opens in a
new tab)", which
labels.newTabtranslates. - Tables: a table is Bulma's responsive table, which, while it's wider than the reply, is a
region the keyboard can scroll, named by
labels.table. Each header cell is athwithscope="col". - Task lists: each item's checkbox is disabled, shows its state, and is named by the item's
text through
aria-labelledby. - The caret is decoration: it's
aria-hidden, doesn't blink, and isn't text, so a copy of the reply leaves it out. - Images: an image that loads takes its description as
alt. Off, its description is the link's text, andlabels.imagenames a link to an image that has none. - Stable elements: finished blocks keep their elements as the reply grows, so a link someone has focused stays focused.
Related Components
CodeBlock: The code blocks a reply's fences render in.Content: Bulma's typography for the prose, which Markdown renders in.Table: The responsive table a reply's tables render in.ConfigProvider: Sets the highlighter for every code block inside.- Helper Props: Bulma helper props for spacing, color, etc.
Additional Resources
- Storybook: Markdown Stories
- CommonMark Spec 0.31.2
- GitHub Flavored Markdown Spec
- OWASP: Improper Output Handling in LLM applications
Props
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | — | Additional CSS classes to apply. |
content | string | — | Required. The markdown, such as a model's reply so far. It renders as React elements and text, never as HTML: raw HTML in it shows as the text it was written as, except a bare <br>, which breaks the line. |
isStreaming | boolean | false | Set while content is still arriving. Each update that only adds to the end parses again just the last block, and markup that's half-written waits: a link shows its text and no address until its ) arrives, an image shows nothing until then, and markers that don't mean anything yet are held back. The root says it's busy through aria-busy, so a screen reader doesn't read each change. Clear it when the reply ends, which renders the whole of it as written. |
topHeadingAs | 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'h2' | The element a top-level # heading renders as, which shifts every level with it: with 'h3', ## is an h4. A level past h6 stays h6. Headings get no ids, so a reply can't take one the page uses. |
components | MarkdownComponents | — | Components to render elements with in place of Markdown's own, by the element's name, such as a for links or pre for code blocks. Each gets the element's props plus isPending. Pass an object that stays the same from render to render, defined at module scope or in a useMemo, or one whose components do: a new component each render remounts what it renders. |
highlighter | { tokenize: CodeBlockTokenize; load?: (language: string) => Promise<unknown> } | CodeBlockTokenize | null | — | The highlighter for code blocks, as CodeBlock's highlighter takes it. Left out, it's the ConfigProvider's codeHighlighter, and null renders code plain. Pass one that stays the same from render to render, or every block renders again on each update. |
codeBlockProps | MarkdownCodeBlockProps | — | Props for every code block, such as showLineNumbers or maxHeight. |
linkTarget | '_blank' | '_self' | '_blank' | Where links open. A new tab, the default, adds visually hidden text that says so. Every link gets rel="noopener noreferrer" either way, so the page it opens can't reach back to the chat or learn its address. |
allowedProtocols | string[] | ['http', 'https', 'mailto'] | The schemes a link may use, such as ['https', 'mailto', 'tel']. javascript, vbscript, data, file and blob are refused whatever this says, and an image takes https only. |
allowUrl | (url: URL, kind: MarkdownUrlKind) => boolean | — | Decides whether an address may be a link's href or an image's src, after the scheme checks pass, given the URL the element will use. It can only narrow them, except that a relative address is dropped unless it returns true: a reply shouldn't link into the app's own pages unasked. Only an address rooted at the site (/docs), or only a fragment (#top), can be admitted. A path relative to the page (docs/x, ../x) is refused, and so is a query on its own (?page=2), which the browser resolves against whatever page it's on when the link is followed, as is one that resolves to another site, such as //host, before it's asked. A relative address reaches it resolved against the page's base URL: the document's baseURI, which a <base> element moves. To admit only your own site's addresses, check the origin as well as the pathname, since an absolute address elsewhere can have the same path. On the server, which has no base URL, a relative address resolves against a placeholder origin, so there a check that can't know the page's should refuse relative addresses, or the app renders the reply on the client. Otherwise, with showImages, a root-relative image on an http page can be in the server's HTML and load over http before hydration takes it out. A check that runs on both must still check an absolute address's origin, since an image in the server's HTML loads before the page hydrates. A refused address renders the link's text, or the image's description, as plain text. Pass one that stays the same from render to render. |
showImages | boolean | false | Loads images. Off, an image is a link to it with its description as the text, since an image loads with no click and its address can carry what a reply was tricked into leaking. On, only https images load, with no referrer, after allowUrl passes them. A relative one is https only when the page's base URL is. |
showCaret | boolean | false | Draws a caret after the text while isStreaming is set. It doesn't blink, and screen readers don't see it. |
size | 'small' | 'medium' | 'large' | — | Text size, as Content takes it. |
labels | { newTab?: string; table?: string; image?: string } | — | Translations for the text Markdown adds for assistive technology. |
textColor | Bulma color | 'inherit' | 'current' | — | Text color helper. |
bgColor | Bulma color | 'inherit' | 'current' | — | Background color helper. |
... | All standard <div> attributes and Bulma helper props | — | See Helper Props |
Types:
CodeBlockToken: A run of text in one line of code, and what it is. Its fields:content:string— Required. The text, rendered as text, never as HTML.type:CodeBlockTokenType— What the text is, which picks its color. Without one, or with a type CodeBlock doesn't know, the text renders in the code's own color.
CodeBlockTokenType:'keyword'|'string'|'number'|'comment'|'function'|'type'|'property'|'tag'|'attribute'|'operator'|'punctuation'|'variable'— What a token is, which picks its color: each has a class of CodeBlock's own,code-block-token-<type>, colored by a--bulma-code-block-token-<type>-colorvariable.CodeBlockTokenize:( code: string, language: string, state?: unknown ) => CodeBlockTokenizeResult | null— Splits code in a language into lines of typed tokens, or returnsnullfor a language it doesn't know, which renders the code plain. It's called while CodeBlock renders, so it must not wait on anything: a language that loads later goes in the highlighter'sload.stateis what an earlier call returned for the lines before this code, orundefinedat the start.CodeBlockTokenizeResult: What a highlighter'stokenizereturns for the code it was given. Its fields:lines:CodeBlockToken[][]— Required. The tokens of each line of the code, one array per line and in order, so there are as many as the code has lines. A line's tokens together hold its text, without the newline that ends it. A result with a different number of lines renders that code plain.state:unknown— Where the grammar stopped at the end of the code, such as inside a block comment. CodeBlock hands it back with the lines that follow, so as the code grows, while it streams in, only the new lines are tokenized. Return one,nullincluded, whenever lines tokenized from it come out as they would inside the whole code, such as when no line depends on the ones before it. Left out, CodeBlock tokenizes the whole code each time it changes.
MarkdownCodeBlockProps:Pick< CodeBlockProps, | 'showLanguage' | 'showLineNumbers' | 'showWrapToggle' | 'showCopyButton' | 'defaultWrap' | 'maxHeight' | 'size' | 'labels' >— The CodeBlock props Markdown passes to every code block it renders.MarkdownComponents: Components that render elements in place of the ones Markdown uses, by the element's name. Each gets the props Markdown would give the element, itschildrenincluded, plusisPending. Its fields:a:MarkdownPart<React.ComponentPropsWithoutRef<'a'>>— A link, with its checkedhref,relandtarget.blockquote:MarkdownPart<React.ComponentPropsWithoutRef<'blockquote'>>— A block quote.code:MarkdownPart<React.ComponentPropsWithoutRef<'code'>>— Inline code. A code block ispre.del:MarkdownPart<React.ComponentPropsWithoutRef<'del'>>— Strikethrough text.em:MarkdownPart<React.ComponentPropsWithoutRef<'em'>>— Emphasis.h1:MarkdownPart<React.ComponentPropsWithoutRef<'h1'>>— A heading of the top level, aftertopHeadingAsshifts it.h2:MarkdownPart<React.ComponentPropsWithoutRef<'h2'>>— A second-level heading.h3:MarkdownPart<React.ComponentPropsWithoutRef<'h3'>>— A third-level heading.h4:MarkdownPart<React.ComponentPropsWithoutRef<'h4'>>— A fourth-level heading.h5:MarkdownPart<React.ComponentPropsWithoutRef<'h5'>>— A fifth-level heading.h6:MarkdownPart<React.ComponentPropsWithoutRef<'h6'>>— A sixth-level heading, which deeper ones stay at.hr:MarkdownPart<React.ComponentPropsWithoutRef<'hr'>>— A thematic break.img:MarkdownPart<React.ComponentPropsWithoutRef<'img'>>— An image, whileshowImagesis set, with its checkedsrc.li:MarkdownPart<React.ComponentPropsWithoutRef<'li'>>— A list item.ol:MarkdownPart<React.ComponentPropsWithoutRef<'ol'>>— A numbered list.p:MarkdownPart<React.ComponentPropsWithoutRef<'p'>>— A paragraph.pre:MarkdownPart<CodeBlockProps>— A code block, given the props Markdown would giveCodeBlock.strong:MarkdownPart<React.ComponentPropsWithoutRef<'strong'>>— Strong emphasis.table:MarkdownPart<React.ComponentPropsWithoutRef<'table'>>— A table, given its name and its head and body as children.td:MarkdownPart<React.ComponentPropsWithoutRef<'td'>>— A body cell.th:MarkdownPart<React.ComponentPropsWithoutRef<'th'>>— A header cell.ul:MarkdownPart<React.ComponentPropsWithoutRef<'ul'>>— A bulleted list.
MarkdownUrlKind:'link'|'image'— What an address is for, asallowUrlis told.