Displays code, terminal output and diffs with an optional header, line numbers and a copy button.
Epicenter
Local-first, open source apps
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()}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 hook, so a block that only shows plain output stays small.
Installation
Install shiki:
Install the required shadcn-svelte dependencies:
Copy and paste the following code into your project.
code-block also installs useHighlightedCode for syntax highlighting.
Usage
<script lang="ts">
import * as CodeBlock from "$lib/components/ui/code-block/index.js";
</script> <CodeBlock.Root>
<CodeBlock.Header>
<CodeBlock.Title>Terminal</CodeBlock.Title>
<CodeBlock.Actions>
<CodeBlock.CopyButton value={output} />
</CodeBlock.Actions>
</CodeBlock.Header>
<CodeBlock.Content code={output} />
</CodeBlock.Root> Composition
CodeBlock.Root
├── CodeBlock.Header
│ ├── CodeBlock.Title
│ └── CodeBlock.Actions
│ └── CodeBlock.CopyButton
├── CodeBlock.Actions (floating, when there is no header)
├── CodeBlock.Content
│ └── CodeBlock.Line
└── CodeBlock.Footer CodeBlock.Content takes a code string or a list of CodeBlock.Line children. Use lines when you need line variants or highlighted tokens. Each CodeBlock.Line takes its own code: a string, or the tokens of a highlighted line.
Features
- It streams cheaply. A
codestring 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.
useHighlightedCodeuses Shiki's JavaScript engine, loads each language on first use and renders ANSI colors in terminal output. - 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 the code prop of CodeBlock.Content. 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 kBHeader
CodeBlock.Header holds a CodeBlock.Title and CodeBlock.Actions. CodeBlock.CopyButton copies its value.
$ 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.0A long title truncates. To link the title to a file, wrap CodeBlock.Title in an anchor.
<CodeBlock.Header>
<a href="/files/route.ts">
<CodeBlock.Title>app/api/chat/route.ts</CodeBlock.Title>
</a>
</CodeBlock.Header> Actions
CodeBlock.Actions holds any number of buttons. For a wrap toggle, keep the state yourself and pass it to wrap.
$ 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">
let wrap = $state(false);
</script>
<CodeBlock.Actions>
<Button
variant="ghost"
size="icon-xs"
aria-label="Wrap lines"
aria-pressed={wrap}
onclick={() => (wrap = !wrap)}
>
<WrapTextIcon />
</Button>
<CodeBlock.CopyButton value={output} />
</CodeBlock.Actions>
<CodeBlock.Content {wrap} code={output} /> Floating Actions
Without a header, put CodeBlock.Actions directly inside CodeBlock.Root. 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.0Line Numbers
Add lineNumbers to CodeBlock.Content. 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" }}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.
if (!session) { redirect("/login") }
const projects = await db.project.findMany({ where: { ownerId: session.user.id }, orderBy: { updatedAt: "desc" }, })
return <ProjectList projects={projects} />}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.Highlighted Lines
Render each line as a CodeBlock.Line and set variant="highlighted" on the lines to call out.
export default { experimental: { reactCompiler: true, viewTransition: true, }, images: { remotePatterns: [{ hostname: "avatars.githubusercontent.com" }], },}Diff
Set variant="added" or variant="removed" on a CodeBlock.Line. Each one adds a + or − marker.
export function Greeting({ name }: { name: string }) { return <p>Hello, {name}</p> return <p className="text-sm text-muted-foreground"> Hello, {name}! </p>}Height
Cap the height with a max-h-* class on CodeBlock.Content. The content scrolls inside the block.
[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 45msCodeBlock.Content 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
CodeBlock.Footer 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.
"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">
let expanded = $state(false);
const id = $props.id();
</script>
<CodeBlock.Content
{id}
class={expanded ? undefined : "max-h-64 overflow-y-hidden scroll-fade-y"}
{code}
/>
<CodeBlock.Footer class="justify-center">
<Button
variant="ghost"
size="xs"
aria-expanded={expanded}
aria-controls={id}
onclick={() => (expanded = !expanded)}
>
{expanded ? "Show less" : "Show more"}
</Button>
</CodeBlock.Footer> 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.
"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> )} Size
Use size="sm" for tool and Trace output. It has tighter padding and text-xs text.
$ 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$ 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.0Destructive
Use variant="destructive" for errors and failed output.
TypeError: Cannot read properties of undefined (reading 'map')
at MessageList (components/message-list.tsx:18:22)
at renderWithHooks (react-dom.development.js:16305:18)Trace
Put a CodeBlock.Root with size="sm" in Trace.CollapsibleContent for tool and terminal output. Add wrap and a max-h-64 class to CodeBlock.Content so long output wraps and scrolls inside the trace. The block sets its own text color, so Trace.CollapsibleContent 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)See Tool, Terminal and Stack Trace for more examples.
Tabs
Show several files with Tabs, one CodeBlock.Root in each Tabs.Content.
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()}"use client"
import { useChat } from "@ai-sdk/react"
export function Chat() { const { messages } = useChat()
return <MessageList messages={messages} />}AI_GATEWAY_API_KEY=your-api-keyMessage
Put a CodeBlock.Root between paragraphs inside a Message.
Syntax Highlighting
useHighlightedCode highlights with Shiki. Its current property has one entry per line. Pass each one to the code prop of a CodeBlock.Line.
{ "location": "San Francisco", "temperature": 18, "unit": "celsius", "conditions": ["fog", "wind"]}<script lang="ts">
import { useHighlightedCode } from "$lib/hooks/use-highlighted-code.svelte.js";
const lines = useHighlightedCode(
() => code,
() => "json"
);
</script>
<CodeBlock.Root>
<CodeBlock.Content>
{#each lines.current as line, index (index)}
<CodeBlock.Line code={line} />
{/each}
</CodeBlock.Content>
</CodeBlock.Root> Shiki uses its JavaScript regex engine, so there is no WASM to load.
Languages
Each language loads the first time it is used. Edit the list in lib/highlighter.ts. A language that is not in the list renders as plain text.
@import "tailwindcss";
:root { --radius: 0.625rem;}def greet(name: str) -> str: return f"Hello, {name}!"A language that is not in the list renders as plain text.The list ships with bash, css, diff, html, javascript, json, jsx, markdown, python, sql, svelte, 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.
$ pnpm test[32m✓[39m src/format.test.ts [2m(4 tests)[22m[32m✓[39m src/parse.test.ts [2m(7 tests)[22m[31m✗[39m src/stream.test.ts [2m(3 tests | 1 failed)[22m
[31mAssertionError: expected 'hello' to be 'hello world'[39m
Tests [31m1 failed[39m | [32m13 passed[39m (14)ANSI colors do not carry from one line to the next.
Server Rendering
highlightCode is async and returns plain data, so you can call it in a load function. Shiki then stays out of the client bundle.
import { highlightCode } from "$lib/highlighter.js";
const code = `export function add(a: number, b: number) {
return a + b;
}`;
export async function load() {
return {
lines: (await highlightCode(code, "ts")) ?? code.split("\n"),
};
} <script lang="ts">
import * as CodeBlock from "$lib/components/ui/code-block/index.js";
let { data } = $props();
</script>
<CodeBlock.Root>
<CodeBlock.Content lineNumbers>
{#each data.lines as line, index (index)}
<CodeBlock.Line code={line} />
{/each}
</CodeBlock.Content>
</CodeBlock.Root> Streaming
While the code streams, the hook tokenizes only the new lines, starting where the last line left off. Lines that did not change keep the same tokens, so Svelte skips them.
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-blockexport function Search() { const [query, setQuery] = React.useState("") const results = useSearch(query) const debounced = useDebounce(query, 300) const results = useSearch(debounced)
return <SearchResults results={results} />}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()}AI_GATEWAY_API_KEY=your-api-keyMarkdown
Render the message with svelte-streamdown and route fenced code to a CodeBlock with components.code. Inline code goes through the codespan snippet, so it stays inline.
The code component gets incomplete, which is true until the closing fence arrives. Use it to disable the copy button while the code is incomplete.
<script lang="ts">
import { useHighlightedCode } from "$lib/hooks/use-highlighted-code.svelte.js";
import * as CodeBlock from "$lib/components/ui/code-block/index.js";
let {
token,
incomplete,
}: { token: { text: string; lang?: string }; incomplete: boolean } =
$props();
const language = $derived(token.lang?.split(/s/)[0] ?? "");
const lines = useHighlightedCode(
() => token.text,
() => language
);
</script>
<CodeBlock.Root>
<CodeBlock.Header>
<CodeBlock.Title>{language || "text"}</CodeBlock.Title>
<CodeBlock.Actions>
<CodeBlock.CopyButton value={token.text} disabled={incomplete} />
</CodeBlock.Actions>
</CodeBlock.Header>
<CodeBlock.Content>
{#each lines.current as line, index (index)}
<CodeBlock.Line code={line} />
{/each}
</CodeBlock.Content>
</CodeBlock.Root> <Streamdown
{content}
controls={false}
components={{ code: MarkdownCodeBlock }}
/> Accessibility
CodeBlock.Contentis aprewith acodeelement and always setsdir="ltr", so code reads left to right on an RTL page.CodeBlock.Contenthastabindex={0}, so keyboard users can focus it and scroll it. Passtabindex={-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. CodeBlock.CopyButtonis labelled "Copy", and a polite live region announces "Copied" after a successful copy.- Give a wrap toggle
aria-pressedso its state is announced. - Give a Show More button
aria-expandedand pointaria-controlsat theidofCodeBlock.Content.
API Reference
CodeBlock.Root
The surface that holds the header, the content and the footer.
CodeBlock.Header
A row above the content for a title and actions.
CodeBlock.Title
A filename or a label, with an optional icon. It truncates.
CodeBlock.Actions
Holds buttons at the end of the header. As a direct child of CodeBlock.Root, it floats.
CodeBlock.CopyButton
A ghost icon button that copies value to the clipboard. It accepts the props of Button.
CodeBlock.Content
The pre that scrolls or wraps.
CodeBlock.Line
One line of code.
CodeBlock.Footer
A row below the content, such as for a Show More button.
useHighlightedCode
const lines = useHighlightedCode(
() => code,
() => language
); Returns an object whose current property has one entry per line, for the code prop of CodeBlock.Line. Each entry is the line's tokens once highlighting finishes. It is a plain string until then, and for a language that is not in the list.