# Code block

> Code in an answer: highlighted as it streams, copy and wrap, long files folded, and an optional Apply.

Code is where answers get used, so the block should read well mid-stream and be easy to take away. A light highlighter is built in, so lines are coloured the moment they arrive, with a caret at the end. The header carries the file name and language, a wrap toggle, and Copy: its icon blurs into a check that draws itself while the label morphs to "Copied". Long files that arrive complete show their start and "Show 42 more lines"; they open smoothly while the fade dissolves and the label becomes "Show less". Pass onApply and Apply runs your action in one motion, Applying with a spinner, then a drawn check as the button settles from blue into a quiet "Applied".

## Install

```bash
npx shadcn@latest add https://hairlineui.com/r/code-block.json
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: `lucide-react`
- Hairline UI components it needs (the CLI installs them too): `status-button`, `text-morph`
- Docs and live preview: https://hairlineui.com/ui/code-block
- Registry item (source): https://hairlineui.com/r/code-block.json

## Usage

```tsx
import { CodeBlock } from "@/components/code-block";

<CodeBlock code={code} language="ts" filename="lib/queue.ts" streaming={isStreaming} />
```

## With the AI SDK

```tsx
"use client";
import ReactMarkdown from "react-markdown";
import { CodeBlock } from "@/components/code-block";

// Fenced code in the model's markdown becomes a CodeBlock, even mid-stream.
export function Answer({ text, streaming }: { text: string; streaming: boolean }) {
  return (
    <ReactMarkdown
      components={{
        pre: ({ children }) => <>{children}</>,
        code({ className, children }) {
          const language = /language-([\w-]+)/.exec(className ?? "")?.[1];
          if (!language) return <code className="rounded bg-muted px-1 font-mono text-[0.9em]">{children}</code>;
          const code = String(children);
          // Only the block still being written gets the caret.
          return <CodeBlock code={code} language={language} streaming={streaming && text.trimEnd().endsWith(code.trimEnd())} />;
        },
      }}
    >
      {text}
    </ReactMarkdown>
  );
}

// With useChat: the last assistant message is streaming while status === "streaming".
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `code` | `string` | – | The code so far, or all of it. |
| `language / filename` | `string` | – | Shown in the header. The language also picks the comment style (// or #). |
| `streaming` | `boolean` | `false` | Shows the caret and keeps the block open. |
| `lineNumbers` | `boolean` | `true` | A sticky line-number gutter. |
| `collapseAfter` | `number` | `18` | Fold complete code longer than this many lines; 0 never folds. |
| `onApply / applyLabel` | `() => void \| Promise<void> / string` | `— / "Apply"` | Shows Apply, with progress while the promise runs and "Applied" after. |
| `highlight` | `boolean` | `true` | Turn the built-in highlighting off, e.g. for logs. |

## States

- **streaming**: Lines arrive highlighted, with a blinking caret on the last one. Long code you watched stream stays open.
- **complete**: File name and language, a wrap toggle, Copy. Line numbers stay put while you scroll sideways. Toggling wrap eases the block to its new height over 460ms.
- **copied**: The copy icon shrinks away through a 3px blur as a check draws itself in 420ms; "Copy" morphs to "Copied", keeping the letters they share, for 1.6 seconds. A blocked clipboard shakes and says "Couldn’t copy".
- **folded**: Code that arrives complete and runs past collapseAfter shows its start under a fade. "Show 42 more lines" opens it over 460ms while the fade dissolves and the label morphs to "Show less".
- **apply**: Apply → Applying with a spinner while your promise runs → a drawn check and "Applied", as the button eases from your primary colour to a quiet receipt. A rejected promise shakes and offers "Try again". It waits at 40% opacity while code streams, and when the code changes (a regenerated answer) it morphs back to Apply so the new code can go in too.

## What it handles

Code is where answers get used. The block has to read well while it is still streaming and be easy to take away.

- **Highlighted as it streams**: A built-in highlighter colours each line the moment it arrives, with a caret at the end.
- **Copy with feedback**: The icon becomes a drawn check and “Copy” becomes “Copied”. A blocked clipboard says “Couldn’t copy”.
- **Wrap and line numbers**: Toggle wrapping, with a line-number gutter that stays put and isn’t copied.
- **Long code folded**: Code that arrives complete and runs past 18 lines shows its start and “Show 42 more lines”.
- **Apply with progress**: Apply becomes Applying, then Applied. A failure shakes and offers Try again.
- **A header that says what it is**: File name and language sit in the header, in colours that follow GitHub’s light and dark palettes.

## Replaces

a syntax highlighter, a copy button, a wrap toggle, a show-more fold, an apply button with states

## Where it fits

- **AI chat answers**: Code that arrives highlighted while it streams.
- **Coding assistants**: Let people apply a suggestion straight into their project.
- **Docs and tutorials**: Snippets with a file name, a copy button and long files folded.
- **Developer landing pages**: Show the code that makes the product work, ready to copy.

## Notes

- Highlighting runs per line with no dependencies, so it’s instant while streaming. For full grammars, render Shiki output yourself and keep this frame.
- Copy and Wrap are real buttons with labels; Wrap uses aria-pressed. "Copied" and "Applied" are announced from a status region beside each button. The code area is focusable when it scrolls sideways.
- Copy and Apply are Status buttons and the fold label is a Text morph; the CLI installs both. With reduced motion, states change in place.
- Line numbers are hidden from screen readers and from copy and paste.
- The colours follow GitHub’s light and dark palettes; the frame uses your theme’s border and background.

License: MIT (https://hairlineui.com/license#components)
