Code Block

Displays code, terminal output and diffs with an optional header, line numbers and a copy button.

app/api/chat/route.ts
import { streamText } from "ai"

export async function POST(request: Request) {
  const { messages } = await request.json()

  const result = streamText({
    model: "anthropic/claude-sonnet-4.5",
    system: "You are a helpful assistant. Answer in one short paragraph.",
    messages,
  })

  return result.toUIMessageStreamResponse()
}
<script lang="ts">
  import { Button } from '#lib/components/ui/button';
  import {

CodeBlock displays code, terminal output, logs and diffs. It has a header with a title and actions, line numbers, wrapping, diff and highlighted lines, and a small size for tool output in a Trace.

Syntax highlighting is optional and lives in a separate function, so a block that only shows plain output stays small.

Installation

pnpm dlx @sveltery/ui@latest add code-block

code-block also installs useHighlightedCode for syntax highlighting.

Usage

<script lang="ts">
  import {
    CodeBlock,
    CodeBlockActions,
    CodeBlockContent,
    CodeBlockCopyButton,
    CodeBlockFooter,
    CodeBlockHeader,
    CodeBlockLine,
    CodeBlockTitle,
  } from '#lib/components/ui/code-block';
</script>
<CodeBlock>
  <CodeBlockHeader>
    <CodeBlockTitle>Terminal</CodeBlockTitle>
    <CodeBlockActions>
      <CodeBlockCopyButton value={output} />
    </CodeBlockActions>
  </CodeBlockHeader>
  <CodeBlockContent code={output} />
</CodeBlock>

Composition

CodeBlock
├── CodeBlockHeader
│   ├── CodeBlockTitle
│   └── CodeBlockActions
│       └── CodeBlockCopyButton
├── CodeBlockActions (floating, when there is no header)
├── CodeBlockContent
│   └── CodeBlockLine
└── CodeBlockFooter

CodeBlockContent takes a string in code, or a list of CodeBlockLine as children. Use lines when you need line variants or highlighted tokens.

Features

  • It streams cheaply. A code string renders as one text node, and the highlighter tokenizes only the new lines as code arrives.
  • It copies cleanly. Line numbers and diff markers are left out of a selection, and blank lines survive the copy.
  • It reads left to right. The content is always dir="ltr". The header follows the page direction.
  • It highlights without WASM. useHighlightedCode uses Shiki's JavaScript engine, loads each language on first use and renders ANSI colors in terminal output. On the server, highlightCode keeps Shiki out of the client bundle.
  • It fits where code shows up. Use it in a message, a Trace line, Tabs or a Dialog.
  • It scrolls by keyboard. The content is focusable, and floating actions show on focus as well as on hover.

Basic

Pass a string to code on CodeBlockContent. It renders as one text node, so it stays cheap while output streams.

$ pnpm build
> next build

 ✓ Compiled successfully in 4.2s
 ✓ Generating static pages (12/12)

Route (app)                Size  First Load JS
┌ ○ /                    1.9 kB         112 kB
├ ○ /_not-found           993 B         103 kB
└ ƒ /api/chat             141 B         102 kB
<script lang="ts">
  import { CodeBlock, CodeBlockContent } from '#lib/components/ui/code-block';

CodeBlockHeader holds a CodeBlockTitle and CodeBlockActions. CodeBlockCopyButton copies its value.

Terminal
$ pnpm add ai @ai-sdk/react zod
Packages: +14
Progress: resolved 412, reused 398, downloaded 14, added 14, done
Done in 2.8s using pnpm v10.18.0
<script lang="ts">
  import { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton, CodeBlockHeader, CodeBlockTitle } from '#lib/components/ui/code-block';
  import TerminalIcon from '@lucide/svelte/icons/terminal';

A long title truncates. To link the title to a file, wrap CodeBlockTitle in an anchor.

<CodeBlockHeader>
  <a href="/files/route.ts">
    <CodeBlockTitle>app/api/chat/route.ts</CodeBlockTitle>
  </a>
</CodeBlockHeader>

Actions

CodeBlockActions holds any number of buttons. For a wrap toggle, keep the state yourself and pass it to wrap.

Terminal
$ pnpm lint
apps/web/components/message-list.tsx
  18:22  error  'messages' is possibly 'undefined'. Add a guard before calling map  @typescript-eslint/no-unsafe-call
  42:7   warning  React Hook React.useEffect has a missing dependency: 'scrollToBottom'  react-hooks/exhaustive-deps

✖ 2 problems (1 error, 1 warning)
<script lang="ts">
  import { Button } from '#lib/components/ui/button';
  import { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton, CodeBlockHeader, CodeBlockTitle } from '#lib/components/ui/code-block';
<script lang="ts">
  let wrap = $state(false);
</script>

<CodeBlockActions>
  <Button variant="ghost" size="icon-xs" aria-label="Wrap lines" aria-pressed={wrap} onclick={() => (wrap = !wrap)}>
    <WrapTextIcon />
  </Button>
  <CodeBlockCopyButton value={output} />
</CodeBlockActions>
<CodeBlockContent {wrap} code={output} />

Floating Actions

Without a header, put CodeBlockActions directly inside CodeBlock. The actions float at the top end and stay hidden until the block is hovered or focused. They always show on touch screens.

$ pnpm add ai @ai-sdk/react zod
Progress: resolved 412, reused 398, downloaded 14, added 14, done
dependencies:
+ @ai-sdk/react 3.0.12
+ ai 6.0.12
+ zod 4.1.12
Done in 2.8s using pnpm v10.18.0
<script lang="ts">
  import { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton } from '#lib/components/ui/code-block';

Line Numbers

Add lineNumbers to CodeBlockContent. A code string is split into lines, and the numbers are not copied with a selection.

{
  "name": "chat",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build"
  }
}
<script lang="ts">
  import { CodeBlock, CodeBlockContent } from '#lib/components/ui/code-block';

Start Line

Set startLine to number lines from a given line, for a snippet from the middle of a file. The gutter grows to fit the widest number.

app/dashboard/page.tsx
  if (!session) {
    redirect("/login")
  }

  const projects = await db.project.findMany({
    where: { ownerId: session.user.id },
    orderBy: { updatedAt: "desc" },
  })

  return <ProjectList projects={projects} />
}
<script lang="ts">
  import { CodeBlock, CodeBlockContent, CodeBlockHeader, CodeBlockLine, CodeBlockTitle, useHighlightedCode } from '#lib/components/ui/code-block';

Wrap

Long lines scroll by default. Add wrap to wrap them, which suits tool output and error messages. To let the reader toggle it, see Actions.

Error: The model "anthropic/claude-sonnet-4.5" returned an error: Request too large. The prompt is 212,431 tokens and the context window is 200,000 tokens. Remove some messages or summarize the conversation and try again.
Error: The model "anthropic/claude-sonnet-4.5" returned an error: Request too large. The prompt is 212,431 tokens and the context window is 200,000 tokens. Remove some messages or summarize the conversation and try again.
<script lang="ts">
  import { CodeBlock, CodeBlockContent } from '#lib/components/ui/code-block';

Highlighted Lines

Render each line as a CodeBlockLine and set variant="highlighted" on the lines to call out.

export default {
  experimental: {
    reactCompiler: true,
    viewTransition: true,
  },
  images: {
    remotePatterns: [{ hostname: "avatars.githubusercontent.com" }],
  },
}
<script lang="ts">
  import { CodeBlock, CodeBlockContent, CodeBlockLine } from '#lib/components/ui/code-block';

Diff

Set variant="added" or variant="removed" on a CodeBlockLine. Each one adds a + or − marker.

components/greeting.tsx
export function Greeting({ name }: { name: string }) {
  return <p>Hello, {name}</p>
  return <p className="text-sm text-muted-foreground">
    Hello, {name}!
  </p>
}
<script lang="ts">
  import { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton, CodeBlockHeader, CodeBlockLine, CodeBlockTitle } from '#lib/components/ui/code-block';

Height

Cap the height with a max-h-* class on CodeBlockContent. The content scrolls inside the block.

Logs
[01] GET /api/chat 200 in 12ms
[02] GET /api/chat 200 in 19ms
[03] GET /api/chat 200 in 26ms
[04] GET /api/chat 200 in 33ms
[05] GET /api/chat 200 in 40ms
[06] GET /api/chat 200 in 47ms
[07] GET /api/chat 200 in 14ms
[08] GET /api/chat 200 in 21ms
[09] GET /api/chat 200 in 28ms
[10] GET /api/chat 200 in 35ms
[11] GET /api/chat 200 in 42ms
[12] GET /api/chat 200 in 49ms
[13] GET /api/chat 200 in 16ms
[14] GET /api/chat 200 in 23ms
[15] GET /api/chat 200 in 30ms
[16] GET /api/chat 200 in 37ms
[17] GET /api/chat 200 in 44ms
[18] GET /api/chat 200 in 51ms
[19] GET /api/chat 200 in 18ms
[20] GET /api/chat 200 in 25ms
[21] GET /api/chat 200 in 32ms
[22] GET /api/chat 200 in 39ms
[23] GET /api/chat 200 in 46ms
[24] GET /api/chat 200 in 13ms
[25] GET /api/chat 200 in 20ms
[26] GET /api/chat 200 in 27ms
[27] GET /api/chat 200 in 34ms
[28] GET /api/chat 200 in 41ms
[29] GET /api/chat 200 in 48ms
[30] GET /api/chat 200 in 15ms
[31] GET /api/chat 200 in 22ms
[32] GET /api/chat 200 in 29ms
[33] GET /api/chat 200 in 36ms
[34] GET /api/chat 200 in 43ms
[35] GET /api/chat 200 in 50ms
[36] GET /api/chat 200 in 17ms
[37] GET /api/chat 200 in 24ms
[38] GET /api/chat 200 in 31ms
[39] GET /api/chat 200 in 38ms
[40] GET /api/chat 200 in 45ms
<script lang="ts">
  import { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton, CodeBlockHeader, CodeBlockTitle } from '#lib/components/ui/code-block';

CodeBlockContent fades its edges with scroll-fade as it scrolls: left and right by default, top and bottom when it wraps. Add scroll-fade-y to a capped block that does not wrap.

Show More

CodeBlockFooter is a slot below the content. For Show More, cap the content while it is collapsed and put a ghost xs Button in the footer.

components/chat.tsx
"use client"

import * as React from "react"
import { useChat } from "@ai-sdk/react"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"

export function Chat() {
  const [input, setInput] = React.useState("")
  const { messages, sendMessage, status } = useChat()

  return (
    <div className="flex flex-col gap-4">
      {messages.map((message) => (
        <div key={message.id}>
          {message.parts.map((part, index) =>
            part.type === "text" ? <p key={index}>{part.text}</p> : null
          )}
        </div>
      ))}
      <form
        onSubmit={(event) => {
          event.preventDefault()
          sendMessage({ text: input })
          setInput("")
        }}
      >
        <Input value={input} onChange={(event) => setInput(event.target.value)} />
        <Button disabled={status !== "ready"}>Send</Button>
      </form>
    </div>
  )
}
<script lang="ts">
  import { Button } from '#lib/components/ui/button';
  import { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton, CodeBlockFooter, CodeBlockHeader, CodeBlockLine, CodeBlockTitle, useHighlightedCode } from '#lib/components/ui/code-block';
<script lang="ts">
  let expanded = $state(false);
  const id = $props.id();
</script>

<CodeBlockContent {id} class={expanded ? undefined : 'max-h-64 overflow-y-hidden scroll-fade-y'} {code} />
<CodeBlockFooter class="justify-center">
  <Button variant="ghost" size="xs" aria-expanded={expanded} aria-controls={id} onclick={() => (expanded = !expanded)}>
    {expanded ? 'Show less' : 'Show more'}
  </Button>
</CodeBlockFooter>

Max Height

To keep a long block from taking over the page, raise the cap instead of removing it. The expanded content scrolls, and the edges fade as you scroll.

components/chat.tsx
"use client"

import * as React from "react"
import { useChat } from "@ai-sdk/react"

import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"

export function Chat() {
  const [input, setInput] = React.useState("")
  const { messages, sendMessage, status } = useChat()

  return (
    <div className="flex flex-col gap-4">
      {messages.map((message) => (
        <div key={message.id}>
          {message.parts.map((part, index) =>
            part.type === "text" ? <p key={index}>{part.text}</p> : null
          )}
        </div>
      ))}
      <form
        onSubmit={(event) => {
          event.preventDefault()
          sendMessage({ text: input })
          setInput("")
        }}
      >
        <Input value={input} onChange={(event) => setInput(event.target.value)} />
        <Button disabled={status !== "ready"}>Send</Button>
      </form>
    </div>
  )
}
<script lang="ts">
  import { Button } from '#lib/components/ui/button';
  import { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton, CodeBlockFooter, CodeBlockHeader, CodeBlockLine, CodeBlockTitle, useHighlightedCode } from '#lib/components/ui/code-block';

Size

Use size="sm" for tool and Trace output. It has tighter padding and text-xs text.

Terminal
$ pnpm add ai @ai-sdk/react zod
Progress: resolved 412, reused 398, downloaded 14, added 14, done
Done in 2.8s using pnpm v10.18.0
Terminal
$ pnpm add ai @ai-sdk/react zod
Progress: resolved 412, reused 398, downloaded 14, added 14, done
Done in 2.8s using pnpm v10.18.0
<script lang="ts">
  import { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton, CodeBlockHeader, CodeBlockTitle } from '#lib/components/ui/code-block';
  import TerminalIcon from '@lucide/svelte/icons/terminal';

Destructive

Use variant="destructive" for errors and failed output.

Error
TypeError: Cannot read properties of undefined (reading 'map')
    at MessageList (components/message-list.tsx:18:22)
    at renderWithHooks (react-dom.development.js:16305:18)
<script lang="ts">
  import { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton, CodeBlockHeader, CodeBlockTitle } from '#lib/components/ui/code-block';

Trace

Put a CodeBlock with size="sm" in TraceCollapsibleContent for tool and terminal output. Add wrap and a max-h-64 class to CodeBlockContent so long output wraps and scrolls inside the trace. The block sets its own text color, so TraceCollapsibleContent does not mute it.

$ node --version
v24.18.0
$ pnpm dev
Error: listen EADDRINUSE: address already in use :::3000
    at Server.setupListenHandle [as _listen2] (node:net:1908:16)
<script lang="ts">
  import { CodeBlock, CodeBlockContent } from '#lib/components/ui/code-block';
  import TerminalIcon from '@lucide/svelte/icons/terminal';

Tabs

Show several files with Tabs, one CodeBlock in each TabsContent.

app/api/chat/route.ts
import { streamText } from "ai"

export async function POST(request: Request) {
  const { messages } = await request.json()
  const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages })

  return result.toUIMessageStreamResponse()
}
<script lang="ts">
  import { CodeBlock, CodeBlockActions, CodeBlockCopyButton, CodeBlockHeader, CodeBlockTitle } from '#lib/components/ui/code-block';
  import { Tabs, TabsContent, TabsList, TabsTrigger } from '#lib/components/ui/tabs';

Message

Put a CodeBlock between paragraphs inside a Message.

How do I stream a response?

Create a route handler that returns the stream:

app/api/chat/route.ts
import { streamText } from "ai"

export async function POST(request: Request) {
  const { messages } = await request.json()

  const result = streamText({
    model: "anthropic/claude-sonnet-4.5",
    messages,
  })

  return result.toUIMessageStreamResponse()
}

The client reads it with useChat.

<script lang="ts">
  import { Bubble, BubbleContent } from '#lib/components/ui/bubble';
  import { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton, CodeBlockHeader, CodeBlockLine, CodeBlockTitle, useHighlightedCode } from '#lib/components/ui/code-block';

RTL

Wrap the content in a DirectionProvider to lay it out right to left. Code always reads left to right. The header follows the page direction. Use the buttons to switch the language.

ثبّت الحزم، ثم شغّل خادم التطوير.

الطرفية
pnpm add ai @ai-sdk/react zod
pnpm dev
<script lang="ts">
  import { Button } from '#lib/components/ui/button';
  import { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton, CodeBlockHeader, CodeBlockLine, CodeBlockTitle, useHighlightedCode } from '#lib/components/ui/code-block';

Syntax Highlighting

useHighlightedCode highlights with Shiki and returns one HTML string per line for CodeBlockLine.

getWeather output
{
  "location": "San Francisco",
  "temperature": 18,
  "unit": "celsius",
  "conditions": ["fog", "wind"]
}
<script lang="ts">
  import { CodeBlock, CodeBlockContent, CodeBlockHeader, CodeBlockLine, CodeBlockTitle, useHighlightedCode } from '#lib/components/ui/code-block';
<script lang="ts">
  const highlighted = useHighlightedCode(() => code, () => 'json');
</script>

<CodeBlock>
  <CodeBlockContent>
    {#each highlighted.lines as line, index (index)}
      <CodeBlockLine>{@html line}</CodeBlockLine>
    {/each}
  </CodeBlockContent>
</CodeBlock>

Shiki uses its JavaScript regex engine, so there is no WASM to load. The highlighter escapes the code, so {@html} renders the tokens and never markup from the code.

Languages

Each language loads the first time it is used. Edit the list in highlighter.ts. A language that is not in the list renders as plain text.

app/globals.css
@import "tailwindcss";

:root {
  --radius: 0.625rem;
}
main.py
def greet(name: str) -> str:
    return f"Hello, {name}!"
notes.txt
A language that is not in the list renders as plain text.
<script lang="ts">
  import { CodeBlock, CodeBlockHeader, CodeBlockTitle } from '#lib/components/ui/code-block';
  import Sample from './code-block/Sample.svelte';

The list ships with bash, css, diff, html, javascript, json, jsx, markdown, python, sql, tsx, typescript and yaml, plus aliases such as ts, js, sh and yml.

Terminal Output

Pass "ansi" as the language to render the colors in terminal output. Without it, escape codes show as text.

Terminal
$ pnpm test
✓ src/format.test.ts (4 tests)
✓ src/parse.test.ts (7 tests)
✗ src/stream.test.ts (3 tests | 1 failed)

AssertionError: expected 'hello' to be 'hello world'

Tests  1 failed | 13 passed (14)
<script lang="ts">
  import { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton, CodeBlockHeader, CodeBlockLine, CodeBlockTitle, useHighlightedCode } from '#lib/components/ui/code-block';
  import TerminalIcon from '@lucide/svelte/icons/terminal';

ANSI colors do not carry from one line to the next.

Server Rendering

highlightCode is async, so it can run in a load function on the server and Shiki stays out of the client bundle.

src/routes/+page.server.ts
import { highlightCode } from '#lib/components/ui/code-block';

export async function load() {
  const code = 'export const answer = 42;';
  return { code, lines: await highlightCode(code, 'tsx') };
}
src/routes/+page.svelte
<script lang="ts">
  import { CodeBlock, CodeBlockContent, CodeBlockLine } from '#lib/components/ui/code-block';

  let { data } = $props();
</script>

<CodeBlock>
  <CodeBlockContent lineNumbers>
    {#each data.lines as line, index (index)}
      <CodeBlockLine>{@html line}</CodeBlockLine>
    {/each}
  </CodeBlockContent>
</CodeBlock>

Streaming

While the code streams, useHighlightedCode tokenizes only the new lines, starting where the last line left off. Lines that did not change keep the same strings, so Svelte leaves their DOM alone.

hooks/use-debounce.ts
export function useDebounce<T>(value: T, delay = 300) {
  const [debounced, setDebounced] = React.useState(value)

  React.useEffect(() => {
    const timeout = setTimeout(() => setDebounced(value), delay)
    return () => clearTimeout(timeout)
  }, [value, delay])

  return debounced
}
pnpm dlx shadcn@latest add code-block
components/search.tsx
export function Search() {
  const [query, setQuery] = React.useState("")
  const results = useSearch(query)
  const debounced = useDebounce(query, 300)
  const results = useSearch(debounced)

  return <SearchResults results={results} />
}
app/api/chat/route.ts
import { streamText } from "ai"

export async function POST(request: Request) {
  const { messages } = await request.json()

  const result = streamText({
    model: "anthropic/claude-sonnet-4.5",
    messages,
  })

  return result.toUIMessageStreamResponse()
}
.env.local
AI_GATEWAY_API_KEY=your-api-key
<script lang="ts">
  import type { ComponentProps } from 'svelte';
  import { Button } from '#lib/components/ui/button';

Accessibility

  • CodeBlockContent is a pre with a code element and always sets dir="ltr", so code reads left to right on an RTL page.
  • CodeBlockContent has tabindex="0", so keyboard users can focus it and scroll it. Pass tabindex={-1} to remove the tab stop.
  • Floating actions show when focus is inside the block, not only on hover, so keyboard users can reach them.
  • Line numbers are hidden from screen readers.
  • Diff lines carry a + or − marker as well as a tint, so the change does not rely on color.
  • CodeBlockCopyButton is labelled "Copy", and a polite live region announces "Copied" after a successful copy.
  • Give a wrap toggle aria-pressed so its state is announced.
  • Give a Show More button aria-expanded and point aria-controls at the id of CodeBlockContent.

API reference

CodeBlock

The surface that holds the header, the content and the footer.

PropTypeDefaultDescription
variant"default" \| "destructive""default"The tone of the block.
size"default" \| "sm""default""sm" has tighter padding and text-xs code, for tool output.
classstring-Additional classes to apply to the block.

CodeBlockHeader

A row above the content for a title and actions.

PropTypeDefaultDescription
classstring-Additional classes to apply to the header.

CodeBlockTitle

A filename or a label, with an optional icon. It truncates.

PropTypeDefaultDescription
classstring-Additional classes to apply to the title.

CodeBlockActions

Holds buttons at the end of the header. As a direct child of CodeBlock, it floats.

PropTypeDefaultDescription
classstring-Additional classes to apply to the actions.

CodeBlockCopyButton

A ghost icon button that copies value to the clipboard. It accepts the props of Button.

PropTypeDefaultDescription
valuestring-Required. The text to copy.
classstring-Additional classes to apply to the button.

CodeBlockContent

The pre that scrolls or wraps.

PropTypeDefaultDescription
codestring-Plain text to show. Leave it out and pass CodeBlockLine children instead.
wrapbooleanfalseWrap long lines instead of scrolling.
lineNumbersbooleanfalseNumber each line. A code string is split into lines.
startLinenumber1The number of the first line, when lineNumbers is set.
tabindexnumber0Makes the content focusable so it can be scrolled by keyboard.
classstring-Additional classes to apply to the content, such as max-h-72.

CodeBlockLine

One line of code.

PropTypeDefaultDescription
variant"default" \| "added" \| "removed" \| "highlighted""default"The state of the line.
classstring-Additional classes to apply to the line.

CodeBlockFooter

A row below the content, such as for a Show More button.

PropTypeDefaultDescription
classstring-Additional classes to apply to the footer.

useHighlightedCode

const highlighted = useHighlightedCode(() => code, () => language);

Returns an object whose lines holds one HTML string per line. It holds escaped plain lines until the first pass finishes, and for a language that is not in the list. Call it while a component initializes, because it loads the language in an effect.

ArgumentTypeDescription
code() => stringReturns the code to highlight. A trailing newline is ignored.
language() => stringReturns a language or alias from highlighter.ts, or "ansi".