Code Block
Displays code, terminal output and diffs with an optional header, line numbers and a copy button.
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.
It doesn't highlight code itself. Lines take any markup, so a highlighter of your choice can color them.
Installation
Usage
<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
└── CodeBlockFooterCodeBlockContent takes a string (Code) or a list of CodeBlockLine. Use lines when you need line variants or highlighted tokens.
Features
- It streams cheaply. A string renders as one text node, and Blazor only patches the lines that changed 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 fits where code shows up. Use it in a message, a Trace line, Tabs, a Dialog or a block of prose.
- It scrolls by keyboard. The content is focusable, and floating actions show on focus as well as on hover.
Basic
Pass a string to CodeBlockContent as Code. 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
CodeBlockHeader holds a CodeBlockTitle and CodeBlockActions. CodeBlockCopyButton 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 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.
$ 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)<CodeBlockActions>
<Button Variant="ButtonVariant.Ghost" Size="ButtonSize.IconXs" aria-label="Wrap lines"
aria-pressed="@(_wrap ? "true" : "false")" @onclick="() => _wrap = !_wrap">
<Icon Data="LucideIcons.WrapText" />
</Button>
<CodeBlockCopyButton Value="@Output" />
</CodeBlockActions>
<CodeBlockContent Wrap="_wrap" Code="@Output" />
@code {
private bool _wrap;
}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.0Line Numbers
Add LineNumbers to CodeBlockContent. A string child 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 CodeBlockLine 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 CodeBlockLine. 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 CodeBlockContent. 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 45msCodeBlockContent 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.
"use client"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> )}
<CodeBlockContent id="chat-code" Code="@Code" Class="@(_expanded ? null : "max-h-64 overflow-y-hidden scroll-fade-y")" />
<CodeBlockFooter Class="justify-center">
<Button Variant="ButtonVariant.Ghost" Size="ButtonSize.Xs" aria-expanded="@(_expanded ? "true" : "false")"
aria-controls="chat-code" @onclick="() => _expanded = !_expanded">
@(_expanded ? "Show less" : "Show more")
</Button>
</CodeBlockFooter>
@code {
private bool _expanded;
}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"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 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)Tabs
Show several files with Tabs, one CodeBlock in each TabsContent.
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()}Message
Put a CodeBlock between paragraphs inside a Message.
Typeset
A CodeBlock sits in running text and keeps its own styles.
Stream a response
Create a route handler that calls streamText and returns the stream to the client.
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 useChat hook reads the stream on the client and renders the answer while it is written.
Syntax Highlighting
CodeBlock leaves highlighting to you: give each CodeBlockLine your highlighter's markup for that line. Without one, lines show as plain text, as below.
{ "location": "San Francisco", "temperature": 18, "unit": "celsius", "conditions": ["fog", "wind"]}<CodeBlock>
<CodeBlockContent>
@foreach (var line in highlightedLines)
{
<CodeBlockLine>@((MarkupString)line)</CodeBlockLine>
}
</CodeBlockContent>
</CodeBlock>Highlight on the server, so no highlighter has to load in the browser, and cache the result for code that doesn't change.
Terminal Output
For terminal output, turn ANSI escape codes into colored spans. This example handles the few its output uses.
$ 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)ANSI colors do not carry from one line to the next.
Streaming
As the code streams in, render the lines you have. Lines that did not change render the same markup, so Blazor leaves them alone.
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}dnx Blazix.Cli 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-keyAccessibility
CodeBlockContentis aprewith acodeelement and always setsdir="ltr", so code reads left to right on an RTL page.CodeBlockContenthastabindex="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. CodeBlockCopyButtonis 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 theidofCodeBlockContent.
RTL
To enable RTL support in Blazix, see the RTL configuration guide.
Translated with AI for the demo, so it may have mistakes.
هيّئ المشروع للكتابة من اليمين إلى اليسار، ثم أضف المكون.
dnx Blazix.Cli init --rtldnx Blazix.Cli add code-blockAPI Reference
CodeBlock
Other attributes are passed to the element it renders.
CodeBlockActions
Other attributes are passed to the element it renders.
CodeBlockContent
Other attributes are passed to the element it renders.
CodeBlockCopyButton
Other attributes are passed to the element it renders.
CodeBlockFooter
Other attributes are passed to the element it renders.
CodeBlockHeader
Other attributes are passed to the element it renders.
CodeBlockLine
Other attributes are passed to the element it renders.
CodeBlockTitle
Other attributes are passed to the element it renders.