Markdown

An answer written in Markdown, drawn as headings, lists, tables and code while it is still arriving.

Brew assistant

A pour-over suits the Huila beans. They rested nine days, so they are ready.

Recipe for one cup

StepWaterTime
Bloom30 g0:30
First pour150 g1:15
Final pour250 g3:00
  1. Grind 15 g like coarse sand
  2. Heat the water to 94 °C1
  3. Pour in three stages
  • Rinse the filter
  • Warm the cup

For another dose, brewRatio works out the water:

ts
brewRatio(15); // { water: 240, bloom: 30 }

Sour cup? Grind a little finer next time. The chat thread shows the whole conversation.

  1. Just off the boil. Darker roasts like it a few degrees cooler.
'use client';

import { useEffect, useState } from 'react';
import { Button, ChatMessage, Markdown } from '@brand-studio/ui';

const answer = [
  'A pour-over suits the **Huila** beans. They rested nine days, so they are *ready*.',
  '## Recipe for one cup',
  '| Step | Water | Time |\n|---|--:|--:|\n| Bloom | 30 g | 0:30 |\n| First pour | 150 g | 1:15 |\n| Final pour | 250 g | 3:00 |',
  '1. Grind **15 g** like coarse sand\n2. Heat the water to 94 °C[^1]\n3. Pour in three stages',
  '- [x] Rinse the filter\n- [ ] Warm the cup',
  'For another dose, `brewRatio` works out the water:',
  '```ts\nbrewRatio(15); // { water: 240, bloom: 30 }\n```',
  '> Sour cup? Grind a little finer next time. The [chat thread](/docs/components/chat-thread/) shows the whole conversation.',
  '[^1]: Just off the boil. Darker roasts like it a few degrees cooler.',
].join('\n\n');

export default function MarkdownDemo() {
  const [shown, setShown] = useState(answer.length);
  const streaming = shown < answer.length;
  useEffect(() => {
    if (!streaming) return;
    const timer = setTimeout(() => setShown(length => Math.min(answer.length, length + 4)), 20);
    return () => clearTimeout(timer);
  }, [shown, streaming]);
  return (
    <div style={{ width: '100%', maxWidth: 620, display: 'grid', gap: 12, justifyItems: 'end' }}>
      <div style={{ width: '100%' }}>
        <ChatMessage name="Brew assistant" avatar="B"><Markdown text={answer.slice(0, shown)} streaming={streaming} /></ChatMessage>
      </div>
      <Button tone="secondary" disabled={streaming} onClick={() => setShown(0)}>{streaming ? 'Writing' : 'Replay as a stream'}</Button>
    </div>
  );
}

Installation

pnpm add @brand-studio/ui

Usage

import { Markdown } from '@brand-studio/ui';
<Markdown text={answer} streaming={busy} />

It reads CommonMark and GitHub's additions: tables, task lists, strikethrough, bare links and footnotes. Fenced code goes to Code Block and a table scrolls sideways inside its own frame.

Streaming

Pass the text you have so far and set streaming until the last piece lands. Text that stops mid-sentence ends inside a bold run, a link or a table, so the component closes what is open at the end: half a bold run shows bold, an unfinished link shows its words, and an image, table or list marker waits until it is whole. Raw symbols never flash on screen.

Each top-level block redraws only when its own source changes, so a long answer redraws its last block and leaves the rest alone.

Safe by default

Treat a model's answer as text from a stranger.

  • HTML in the source is shown as written. It never becomes elements.
  • A link is used only when it is relative or starts with http, https, mailto or tel. Anything else, javascript: included, renders as plain words. Links to another site open in a new tab.
  • An image loads only from a relative address or an origin you list in imageOrigins. Others show as a link. A remote image is a request to someone else's server, and a prompt hidden in a document can make a model put private text in that address.
  • Text built to stall the page is bounded. Past 1,000 emphasis marks they show as written, and quotes and lists stop nesting at 16 levels.
<Markdown text={answer} imageOrigins={['https://cdn.example.com']} />

Drawn blocks

blocks hands a fenced block to a renderer, keyed by the word after the fence. The model writes data and the page decides how to draw it, so an answer can hold a chart without the model ever sending markup or code.

Brew assistant

Saturday is your busiest day, so roast on Thursday.

Cups sold

Saturday was the busiest day: 74 cups.

Hot
Mon42 cups
Tue38 cups
Wed45 cups
Thu51 cups
Fri58 cups
Sat74 cups
Sun61 cups

The beans need two days of rest. Here is the plan:

Before Saturday
  1. YouRoast on ThursdayNext: Rest the beans two days
  2. Rest the beans two daysNext: Enough for 80 cups?
  3. Enough for 80 cups?Next: Open as usual (Yes), Order a second bag (No)
  4. Open as usual
  5. AgentOrder a second bag

Want me to place the order if stock runs short?

'use client';

import { useEffect, useState } from 'react';
import { Button, ChatMessage, Markdown, visualBlocks } from '@brand-studio/ui';

const chart = { title: 'Cups sold', unit: ' cups', labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], series: [{ name: 'Hot', values: [42, 38, 45, 51, 58, 74, 61] }], lit: 'Sat', note: 'Saturday was the busiest day: 74 cups.' };
const flow = {
  title: 'Before Saturday',
  nodes: [{ id: 'roast', label: 'Roast on Thursday', tag: 'You' }, { id: 'rest', label: 'Rest the beans two days' }, { id: 'stock', label: 'Enough for 80 cups?', kind: 'decision' }, { id: 'open', label: 'Open as usual' }, { id: 'order', label: 'Order a second bag', tag: 'Agent' }],
  edges: [{ from: 'roast', to: 'rest' }, { from: 'rest', to: 'stock' }, { from: 'stock', to: 'open', label: 'Yes' }, { from: 'stock', to: 'order', label: 'No' }],
  lit: ['roast', 'rest', 'stock', 'open'],
};
const answer = [
  'Saturday is your busiest day, so roast on **Thursday**.',
  '```chart\n' + JSON.stringify(chart, null, 1) + '\n```',
  'The beans need two days of rest. Here is the plan:',
  '```flow\n' + JSON.stringify(flow, null, 1) + '\n```',
  'Want me to place the order if stock runs short?',
].join('\n\n');

export default function MarkdownBlocksDemo() {
  const [shown, setShown] = useState(answer.length);
  const streaming = shown < answer.length;
  useEffect(() => {
    if (!streaming) return;
    const timer = setTimeout(() => setShown(length => Math.min(answer.length, length + 12)), 20);
    return () => clearTimeout(timer);
  }, [shown, streaming]);
  return (
    <div style={{ width: '100%', maxWidth: 620, display: 'grid', gap: 12, justifyItems: 'end' }}>
      <div style={{ width: '100%' }}>
        <ChatMessage name="Brew assistant" avatar="B"><Markdown text={answer.slice(0, shown)} streaming={streaming} blocks={visualBlocks} /></ChatMessage>
      </div>
      <Button tone="secondary" disabled={streaming} onClick={() => setShown(0)}>{streaming ? 'Writing' : 'Replay as a stream'}</Button>
    </div>
  );
}

visualBlocks is a ready-made set: a chart block becomes a Chart and a flow block a Flow Diagram.

import { Markdown, visualBlocks } from '@brand-studio/ui';

<Markdown text={answer} streaming={busy} blocks={visualBlocks} />

Tell the model the shapes in your system prompt:

```chart
{ "title": "Cups sold", "kind": "bar", "unit": " cups", "labels": ["Fri", "Sat"],
  "series": [{ "name": "Hot", "values": [58, 74] }], "lit": "Sat", "note": "Saturday was busiest." }
```

```flow
{ "title": "Before Saturday", "nodes": [{ "id": "a", "label": "Roast" }, { "id": "b", "label": "Rest", "kind": "step" }],
  "edges": [{ "from": "a", "to": "b", "label": "Then" }], "lit": ["a", "b"] }
```

kind is bar, line or area for a chart and step or decision for a node. A unit that starts with a currency sign goes before the number; any other follows it.

Add your own renderers beside them:

const blocks = { ...visualBlocks, map: (source: string) => <StoreMap {...JSON.parse(source)} /> };

While the fence is still open the block shows a placeholder, so a renderer only ever gets the whole source. If it throws, for example on JSON the model got wrong or a field of the wrong shape, the source shows as a code block. Define blocks outside the component or memoise it, so finished blocks are not redrawn.

Headings

A single # becomes an h2 and deeper headings follow, which keeps an answer under the page's own title. Set headings={1} when the text is the page.

Accessibility

  • Headings, lists, tables and quotes are the native elements, so screen readers can move by them.
  • A table's scroll frame takes focus and is named by its column headings.
  • A task shows a drawn box that reads "Done" or "To do"; change the words with doneLabel and todoLabel.
  • The container is marked busy while streaming is set.

API Reference

PropTypeDefault
textstring–
streaming?boolean–
blocks?Record<string, (source: string) => React.ReactNode>–
imageOrigins?string[]–
headings?1 | 2 | 3 | 4–
notesLabel?string–
doneLabel?string–
todoLabel?string–
drawingLabel?string–
className?string–

Still, Deskhand and Hollis are fictional brands. The coffee photographs are original generated artwork. @brand-studio/ui is MIT licensed.