# Markdown

A reply's Markdown, rendered safely as it streams in.

Source: [markdown.tsx](https://github.com/jakejarvis/jarvis-ui/blob/main/src/components/ui/markdown.tsx)

```tsx
import { Markdown } from "@/components/ui/markdown";

const reply = `To point **www.example.com** at your site, add a CNAME record at your DNS provider:

| Type  | Name | Value             |
| ----- | ---- | ----------------- |
| CNAME | www  | cname.example.net |

Then check that it has propagated:

\`\`\`bash
dig +short www.example.com CNAME
\`\`\`

A few things to keep in mind:

- Remove any \`A\` or \`AAAA\` records for \`www\` first, since a name can't have both.
- Verification usually takes a few minutes, but some providers cache records for up to an hour.
- See [Custom domains](#custom-domains) for the apex domain.`;

export default function MarkdownReply() {
  return <Markdown className="w-full max-w-md">{reply}</Markdown>;
}
```

## Installation

Add the registry, once per project:

```bash
npx shadcn@latest registry add @jarvis=https://ui.jarv.is/r/{name}.json
```

Then add the component:

```bash
npx shadcn@latest add @jarvis/markdown
```

## Usage

```tsx
import { Markdown } from "@/components/ui/markdown";

export function Reply({ text, streaming }: { text: string; streaming: boolean }) {
  return <Markdown streaming={streaming}>{text}</Markdown>;
}
```

Markdown renders GitHub Flavored Markdown with
[TanStack Markdown](https://tanstack.com/markdown/latest), styled by [Prose](https://ui.jarv.is/components/prose.md) and
sized for a reply: headings stay close to the text, long URLs and code wrap rather than widening the
reply, and tables scroll horizontally. Code blocks render as a [Code Block](https://ui.jarv.is/components/code-block.md),
labeled with their title, as in ` ```ts title="app.ts" `, or else their language.
[TanStack Highlight](https://tanstack.com/highlight/latest) highlights them in the theme's
[syntax colors](https://ui.jarv.is/docs/theming.md), and `lineNumbers` adds line numbers. Links render as a
[Link](https://ui.jarv.is/components/link.md), bare URLs included. Links to other sites open in a new tab with an arrow
and `rel="nofollow"`. Task lists render a read-only
[Checkbox](https://ui.jarv.is/components/checkbox.md), which screen readers announce with the item's text.

Markdown renders on the server as well as in the browser. In a project with React Server
Components, such as a Next.js app, rendering Markdown from a server component parses and
highlights it on the server. The browser receives only the parts that need it: each code block's
copy and wrap buttons, a table's scroll area and a task list's checkboxes. In a server component,
options can be functions, such as a `urlTransform` or your own `components`. For a reply that
streams in, render Markdown in a client component instead, where it parses the text as it arrives.

A model's reply can be steered by content its tools read, so Markdown renders only what Markdown
syntax produces. Raw HTML shows as text, links that would run script are dropped, and images show
as their alt text, since loading an image can send the conversation's contents to any site.

TanStack Markdown's options pass through: `extensions` for more syntax, `urlTransform` to rewrite
or drop URLs after unsafe ones are removed, and `headingIds`, `headingAnchors` and `frontmatter`,
which are off by default for replies. `allowHtml` renders raw HTML, so use it only for Markdown you
wrote yourself.

Each Markdown scopes the ids of its footnotes and headings, so several replies on one page don't
link to each other's. A reply's `#` heading is an `h1`. On a page that has its own `h1`, pass
`headingOffset` to move the reply's headings below it: with `1`, `#` renders as an `h2` that looks
the same.

## Examples

### Streaming

While a reply streams in, set `streaming` and pass all of the text received so far on each update.
Markdown shows only content that can already render in its final form. A code block appears once
its opening line, with the language, has arrived. A table appears once its header and the row of
dashes under it have arrived, and a heading or list item once it has some text. In the block still
arriving, Markdown closes bold, italics, strikethrough and code as they're typed, and shows a link
as plain text until its URL is complete. A caret follows the end of the text, or sits below a code
block that's still arriving.

While `streaming` is set, Markdown sets `aria-busy`, so screen readers wait for the finished reply.
It also parses only the end of the reply on each update. Paragraphs, lists and other blocks that a
new line can no longer change keep the result of their first parse.

```tsx
"use client";

import { RotateCcwIcon } from "lucide-react";
import * as React from "react";

import { Button } from "@/components/ui/button";
import { Markdown } from "@/components/ui/markdown";

const reply = `The build is slow because **type checking** takes 41 of its 58 seconds, as the [build profile](#build-profile) shows:

| Step       | Time |
| ---------- | ---- |
| Type check | 41s  |
| Bundle     | 17s  |

Two changes help:

1. Turn on \`incremental\` so TypeScript reuses its last run.
2. Check types in a separate step, so the bundler doesn’t wait on it.

\`\`\`json title="tsconfig.json"
{
  "compilerOptions": {
    "incremental": true
  }
}
\`\`\`

Together they bring a warm build down to about *12 seconds*.`;

export default function MarkdownStreaming() {
  const [length, setLength] = React.useState(0);
  const streaming = length < reply.length;

  React.useEffect(() => {
    if (!streaming) return;
    const timer = setInterval(() => {
      setLength((current) => Math.min(current + 4, reply.length));
    }, 30);
    return () => clearInterval(timer);
  }, [streaming]);

  return (
    <div className="flex w-full max-w-md flex-col items-start gap-4">
      <Button variant="secondary" size="sm" disabled={streaming} onClick={() => setLength(0)}>
        <RotateCcwIcon />
        Replay
      </Button>
      <Markdown streaming={streaming} className="min-h-136 w-full">
        {reply.slice(0, length)}
      </Markdown>
    </div>
  );
}
```

### More languages

The default highlighter supports the languages models write most: CSS, diffs, Go, HTML, JavaScript,
JSON, JSX, Markdown, Python, Rust, shell, SQL, TypeScript, TSX and YAML. Code in any other language
stays plain unless you pass your own highlighter, made with TanStack Highlight's
`createHighlighter`, to `highlighter`. Yours replaces the default, so list every language you want,
as in `createHighlighter({ languages: [ts, tsx, kotlin, ruby] })`. Pass `false` to leave all code
plain.

```tsx
import { createHighlighter } from "@tanstack/highlight/core";
import { kotlin, ruby } from "@tanstack/highlight/languages";

import { Markdown } from "@/components/ui/markdown";

const highlighter = createHighlighter({ languages: [kotlin, ruby] });

const reply = `Here's the same check in Kotlin:

\`\`\`kotlin
fun isExpiring(daysLeft: Int): Boolean = daysLeft < 30
\`\`\`

And in Ruby:

\`\`\`ruby
def expiring?(days_left)
  days_left < 30
end
\`\`\``;

export default function MarkdownMoreLanguages() {
  return (
    <Markdown highlighter={highlighter} className="w-full max-w-md">
      {reply}
    </Markdown>
  );
}
```

### Replacing elements

`components` replaces the elements Markdown renders, by tag name, with your own components or other
tags. The example below renders tables with a [Table](https://ui.jarv.is/components/table.md). Your components take
precedence over Markdown's own code blocks, links and images, so `{ img: "img" }` shows images
again for Markdown you trust. Define the object outside your component, as in the example, so
Markdown doesn't re-render every reply whenever your component renders.

A link component you pass still receives Markdown's scoped footnote and heading ids, and `target`
and `rel` for links to other sites. To render only some links your own way, fall back to
`MarkdownLink` for the rest, as [Citation](https://ui.jarv.is/components/citation.md) does.

```tsx
import { Markdown } from "@/components/ui/markdown";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";

const components = {
  table: Table,
  thead: TableHeader,
  tbody: TableBody,
  tr: TableRow,
  th: TableHead,
  td: TableCell,
};

const reply = `These are the records **example.com** needs:

| Type  | Name | Value                 |
| ----- | ---- | --------------------- |
| CNAME | www  | \`cname.example.net\` |
| TXT   | @    | \`verify=8f2c1a\`     |`;

export default function MarkdownCustomTable() {
  return (
    <Markdown components={components} className="w-full max-w-md">
      {reply}
    </Markdown>
  );
}
```

## Props

`MarkdownLink` is the link Markdown renders by default, a [Link](https://ui.jarv.is/components/link.md) that adds
`nofollow` to the `rel` of links to other sites. Your own link component can fall back to it.

| Part | Extends |
| --- | --- |
| `Markdown` | [`Prose`](https://ui.jarv.is/components/prose.md) |
| `MarkdownLink` | — |

### Markdown

| Prop              | Type                                                     | Default              | Description                                                                                                                                                                                                                                                                                   |
| ----------------- | -------------------------------------------------------- | -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `children`        | `MarkdownInput`                                          | —                    | The Markdown to render, or a document parsed ahead of time with `parseMarkdown` from `@tanstack/markdown/parser`. While a reply streams, pass all of its text so far on each update.                                                                                                          |
| `streaming?`      | `boolean`                                                | `false`              | Whether the text is still arriving. While it is, Markdown holds back what can't render yet, closes anything still open in the last block, and shows a caret after the text.                                                                                                                   |
| `highlighter?`    | `false \| Highlighter`                                   | `defaultHighlighter` | The [TanStack Highlight](https://tanstack.com/highlight/latest) highlighter that colors code blocks, from `createHighlighter`. The default knows CSS, diffs, Go, HTML, JavaScript, JSON, JSX, Markdown, Python, Rust, shell, SQL, TypeScript, TSX and YAML. Pass `false` to leave code plain. |
| `lineNumbers?`    | `boolean`                                                | `false`              | Numbers the lines of code blocks.                                                                                                                                                                                                                                                             |
| `components?`     | `MarkdownComponents`                                     | —                    | Replaces the elements Markdown renders, by tag name, with your own components or other tags, as in `{ a: Link }`. Yours take precedence over Markdown's own, but links you pass still get its scoped ids and new-tab attributes. Define the object outside your component, or memoize it.     |
| `extensions?`     | `MarkdownExtension[]`                                    | —                    | TanStack Markdown extensions for more syntax, such as callouts from `@tanstack/markdown/extensions/*`. Autolinks are always on.                                                                                                                                                               |
| `urlTransform?`   | `MarkdownUrlTransform`                                   | —                    | Rewrites link and image URLs, or removes one when it returns `null`. It runs after unsafe URLs, such as `javascript:` links, have been removed.                                                                                                                                               |
| `allowHtml?`      | `boolean`                                                | `false`              | Renders raw HTML in the Markdown rather than showing it as text. Leave it off for anything a model or a person wrote.                                                                                                                                                                         |
| `headingIds?`     | `boolean \| ((text: string, index: number) => string)`   | `false`              | Gives headings `id`s, from their text or from a function you pass, scoped to this Markdown. Off by default, since a streaming heading's `id` changes as it grows.                                                                                                                             |
| `headingAnchors?` | `boolean \| HeadingAnchorOptions`                        | —                    | Adds a link to each heading that has an `id`.                                                                                                                                                                                                                                                 |
| `headingOffset?`  | `number`                                                 | `0`                  | How many levels to move headings down the page's outline. With `1`, a `#` heading renders as an `h2`. Headings look the same either way.                                                                                                                                                      |
| `frontmatter?`    | `boolean`                                                | `false`              | Reads YAML frontmatter at the start of the text rather than rendering it.                                                                                                                                                                                                                     |
| `className?`      | `string`                                                 | —                    | CSS class applied to the element.                                                                                                                                                                                                                                                             |
| `style?`          | `React.CSSProperties`                                    | —                    | Style applied to the element.                                                                                                                                                                                                                                                                 |
| `render?`         | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —                    | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render.                                                                                                     |

### MarkdownLink

| Prop            | Type                                                     | Default | Description                                                                                                                                                                               |
| --------------- | -------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `variant?`      | `"default" \| "muted" \| "plain"`                        | —       |                                                                                                                                                                                           |
| `external?`     | `boolean`                                                | —       | Opens the link in a new tab and adds `noopener noreferrer` to its `rel`. Defaults to `true` when `href` is an absolute URL, such as `https://example.com`, and `false` otherwise.         |
| `externalIcon?` | `boolean`                                                | —       | Shows an arrow after a link that opens in a new tab.                                                                                                                                      |
| `newTabLabel?`  | `string`                                                 | —       | The text screen readers announce after a link that opens in a new tab. Pass an empty string to leave it out.                                                                              |
| `className?`    | `string`                                                 | —       | CSS class applied to the element.                                                                                                                                                         |
| `style?`        | `React.CSSProperties`                                    | —       | Style applied to the element.                                                                                                                                                             |
| `render?`       | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |
