Skip to main content

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 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 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="![Portrait of Ada Lovelace](/img/portrait-ada-lovelace.jpg)"
/>

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 &copy; and &#169; 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 farWhat shows
**bold, *emphasis, ~~gone after a marker that opensStyled to the end
A run of *, _, ~ or backticks, a \, or &ampNothing, until the next character says what it is
`code with no closing backtickCode to the end
[text, [text](https://exaThe text, never a link
![alt](https://imgNothing, so no request goes out for half an address
A bare https://exa as the last wordText, until a space or the end of the line
A line of only #, -, 1., >, === or ---Nothing, until the line says what it starts
A table's header before its delimiter row, or a partial rowNothing, until the line ends
A fence's opening lineNothing, until its language is whole
An open fenceA CodeBlock with isStreaming set

When isStreaming clears, the reply renders exactly as a one-shot render of it would.


Security​

A reply is untrusted: a prompt injection can put anything in it. Markdown renders React elements and text only, and never hands a string to the browser's HTML parser.

  • Raw HTML is text, so <script>, <img onerror> and their kind show as written.
  • Addresses are checked after the browser's own URL parser reads them, which strips the tabs, line breaks and control characters that would otherwise hide a scheme, and after character references are read, so &#106;avascript: is caught. javascript, vbscript, data, file and blob are refused whatever allowedProtocols says.
  • Relative addresses are dropped unless allowUrl admits them, so a reply can't link into your app's own pages unasked. Only one rooted at the site, or only a fragment, can be admitted, and one that resolves to another site, such as //host or /\host, is refused outright. What renders resolves to exactly the URL allowUrl was shown, and an address that wouldn't, such as a path that dot segments leave starting with //, is refused, so a \ or a .. can't make the element load something else.
  • Images don't load unless you set showImages, since an image loads with no click and its address can carry what a reply was tricked into leaking. With it set, only https images load, with referrerPolicy="no-referrer".
  • Nothing from a reply becomes an id, a name or a class, and headings get no ids, so a reply can't take one the page uses.
  • Nesting is capped, so a reply of thousands of > or * can't build a tree that freezes the tab or overflows the stack.

Accessibility​

  • Headings follow the page: a # heading renders as an h2 by default, below the page's own h1, and topHeadingAs moves every level together so the outline stays in order.
  • Busy while streaming: the root carries aria-busy while isStreaming is set, so a screen reader doesn't read each change, and an open code block is busy too. Announcing when a reply starts and ends is the chat thread's job.
  • Links are underlined, with Bulma's is-underlined helper, so a link in a sentence is told apart from the words around it by more than its color (WCAG 1.4.1). A build without Bulma's helpers has no such class, so there give components.a a 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.newTab translates.
  • 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 a th with scope="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, and labels.image names 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.

  • 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​


Props​

PropTypeDefaultDescription
classNamestring—Additional CSS classes to apply.
contentstring—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.
isStreamingbooleanfalseSet 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.
componentsMarkdownComponents—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.
codeBlockPropsMarkdownCodeBlockProps—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.
allowedProtocolsstring[]['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.
showImagesbooleanfalseLoads 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.
showCaretbooleanfalseDraws 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.
textColorBulma color | 'inherit' | 'current'—Text color helper.
bgColorBulma 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>-color variable.
  • CodeBlockTokenize: ( code: string, language: string, state?: unknown ) => CodeBlockTokenizeResult | null — Splits code in a language into lines of typed tokens, or returns null for 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's load. state is what an earlier call returned for the lines before this code, or undefined at the start.
  • CodeBlockTokenizeResult: What a highlighter's tokenize returns 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, null included, 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, its children included, plus isPending. Its fields:
    • a: MarkdownPart<React.ComponentPropsWithoutRef<'a'>> — A link, with its checked href, rel and target.
    • blockquote: MarkdownPart<React.ComponentPropsWithoutRef<'blockquote'>> — A block quote.
    • code: MarkdownPart<React.ComponentPropsWithoutRef<'code'>> — Inline code. A code block is pre.
    • del: MarkdownPart<React.ComponentPropsWithoutRef<'del'>> — Strikethrough text.
    • em: MarkdownPart<React.ComponentPropsWithoutRef<'em'>> — Emphasis.
    • h1: MarkdownPart<React.ComponentPropsWithoutRef<'h1'>> — A heading of the top level, after topHeadingAs shifts 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, while showImages is set, with its checked src.
    • 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 give CodeBlock.
    • 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, as allowUrl is told.