Skip to content
GitHub11 stars

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()}
<div class="w-full max-w-lg">
    <CodeBlock>
        <CodeBlockHeader>

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

dnx Blazix.Cli add code-block

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
└── CodeBlockFooter

CodeBlockContent 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 kB
<div class="w-full max-w-md">
    <CodeBlock><CodeBlockContent Code="@Output" /></CodeBlock>
</div>

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
<div class="w-full max-w-md">
    <CodeBlock>
        <CodeBlockHeader>

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)
<div class="w-full max-w-md">
    <CodeBlock>
        <CodeBlockHeader>
<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.0
<div class="w-full max-w-md">
    <CodeBlock>
        <CodeBlockActions><CodeBlockCopyButton Value="@Output" /></CodeBlockActions>

Line 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"  }}
<div class="w-full max-w-md">
    <CodeBlock><CodeBlockContent LineNumbers="true" Code="@Code" /></CodeBlock>
</div>

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} />}
<div class="w-full max-w-md">
    <CodeBlock>
        <CodeBlockHeader>

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.
<div class="flex w-full max-w-md flex-col gap-4">
    <CodeBlock><CodeBlockContent Code="@Output" /></CodeBlock>
    <CodeBlock><CodeBlockContent Wrap="true" Code="@Output" /></CodeBlock>
</div>

@code {
    private const string Output = "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" }],  },}
<div class="w-full max-w-md">
    <CodeBlock>
        <CodeBlockContent LineNumbers="true">

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>}
<div class="w-full max-w-md">
    <CodeBlock>
        <CodeBlockHeader>

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
<div class="w-full max-w-md">
    <CodeBlock>
        <CodeBlockHeader>

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"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>  )}
<div class="w-full max-w-md">
    <CodeBlock>
        <CodeBlockHeader>
<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.

components/chat.tsx
"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>  )}
<div class="w-full max-w-md">
    <CodeBlock>
        <CodeBlockHeader>

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
<div class="flex w-full max-w-md flex-col gap-4">
    <CodeBlock>
        <CodeBlockHeader>

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)
<div class="w-full max-w-md">
    <CodeBlock Variant="CodeBlockVariant.Destructive">
        <CodeBlockHeader>

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)
<div class="w-full max-w-md">
    <Trace>
        <TraceCollapsible Open="true">

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()}
<Tabs Value="route" Class="w-full max-w-md">
    <TabsList>
        @foreach (var file in Files)

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.

<div class="flex w-full max-w-md flex-col gap-4 text-sm">
    <Message Align="MessageAlign.End">
        <MessageContent>

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.

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 useChat hook reads the stream on the client and renders the answer while it is written.

<div class="@("w-full max-w-md text-sm leading-relaxed [&_code]:rounded-md [&_code]:bg-muted [&_code]:px-1 [&_code]:py-0.5 [&_code]:font-mono [&>*+*]:mt-4")">
    <h3 class="text-base font-semibold">Stream a response</h3>
    <p>Create a route handler that calls <code>streamText</code> and returns the stream to the client.</p>

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.

getWeather output
{  "location": "San Francisco",  "temperature": 18,  "unit": "celsius",  "conditions": ["fog", "wind"]}
<div class="w-full max-w-md">
    <CodeBlock>
        <CodeBlockHeader>
<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.

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)
<div class="w-full max-w-md">
    <CodeBlock>
        <CodeBlockHeader>

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.

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}
dnx Blazix.Cli 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
@implements IDisposable

<div class="flex w-full max-w-md flex-col gap-4">

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.

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-block
@* The code itself stays left to right: CodeBlockContent sets dir="ltr" on its <pre>. *@
<div class="flex w-full max-w-md flex-col gap-3 text-sm">
    <p>@T.Description</p>

API Reference

CodeBlock

ParameterTypeDefault
Variant CodeBlockVariant CodeBlockVariant.Default
Size CodeBlockSize CodeBlockSize.Default
Class string? -
ChildContent RenderFragment? -

Other attributes are passed to the element it renders.

CodeBlockActions

ParameterTypeDefault
Class string? -
ChildContent RenderFragment? -

Other attributes are passed to the element it renders.

CodeBlockContent

ParameterTypeDefault
Code string? -
Wrap bool false
LineNumbers bool false
StartLine int 1
Style string? -
Class string? -
ChildContent RenderFragment? -

Other attributes are passed to the element it renders.

CodeBlockCopyButton

ParameterTypeDefault
Valuerequired string -
Variant ButtonVariant ButtonVariant.Ghost
Size ButtonSize ButtonSize.IconXs
Type ButtonType ButtonType.Button
OnClick EventCallback<MouseEventArgs> -
Class string? -

Other attributes are passed to the element it renders.

CodeBlockFooter

ParameterTypeDefault
Class string? -
ChildContent RenderFragment? -

Other attributes are passed to the element it renders.

CodeBlockHeader

ParameterTypeDefault
Class string? -
ChildContent RenderFragment? -

Other attributes are passed to the element it renders.

CodeBlockLine

ParameterTypeDefault
Variant CodeBlockLineVariant CodeBlockLineVariant.Default
Class string? -
ChildContent RenderFragment? -

Other attributes are passed to the element it renders.

CodeBlockTitle

ParameterTypeDefault
Class string? -
ChildContent RenderFragment? -

Other attributes are passed to the element it renders.