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()}// Inline SVG icons from Lucide (https://lucide.dev), ISC License, Copyright (c) Lucide Icons and Contributors.
import { createSignal, For } from "solid-js"
import { useHighlightedCode } from "~/hooks/use-highlighted-code"
import { Button } from "~/components/ui/button"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle
} from "~/components/ui/code-block"
const code = `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()
}`
function download(value: string, filename: string) {
const url = URL.createObjectURL(new Blob([value], { type: "text/plain" }))
const link = document.createElement("a")
link.href = url
link.download = filename
link.click()
URL.revokeObjectURL(url)
}
export default function CodeBlockDemo() {
const [wrap, setWrap] = createSignal(false)
const lines = useHighlightedCode(
() => code,
() => "ts"
)
return (
<div class="w-full max-w-lg">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z" />
<path d="M14 2v5a1 1 0 0 0 1 1h5" />
<path d="M10 12.5 8 15l2 2.5" />
<path d="m14 12.5 2 2.5-2 2.5" />
</svg>
app/api/chat/route.ts
</CodeBlockTitle>
<CodeBlockActions>
<Button
variant="ghost"
size="icon-xs"
aria-label="Wrap lines"
aria-pressed={wrap() ? "true" : "false"}
class="aria-pressed:text-foreground"
onClick={() => setWrap(!wrap())}
>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m16 16-3 3 3 3" />
<path d="M3 12h14.5a1 1 0 0 1 0 7H13" />
<path d="M3 19h6" />
<path d="M3 5h18" />
</svg>
</Button>
<Button
variant="ghost"
size="icon-xs"
aria-label="Download"
onClick={() => download(code, "route.ts")}
>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M12 15V3" />
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<path d="m7 10 5 5 5-5" />
</svg>
</Button>
<CodeBlockCopyButton value={code} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent wrap={wrap()} lineNumbers>
<For each={lines()}>
{(line, index) => (
<CodeBlockLine
variant={
index() >= 5 && index() <= 9 ? "highlighted" : "default"
}
>
{line}
</CodeBlockLine>
)}
</For>
</CodeBlockContent>
</CodeBlock>
</div>
)
}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 the following dependencies:
Install the required Solid UI dependencies:
Copy and paste the following code into your project.
// Inline SVG icons from Lucide (https://lucide.dev), ISC License, Copyright (c) Lucide Icons and Contributors.
import type { ComponentProps, JSX } from "@solidjs/web"
import { cva, type VariantProps } from "class-variance-authority"
import { createSignal, For, omit, onCleanup } from "solid-js"
import { cn } from "~/lib/utils"
import { Button, type ButtonProps } from "~/components/ui/button"
const codeBlockVariants = cva(
"rounded-lg text-sm has-[>[data-slot=code-block-content]:focus-visible]:ring-3 has-[>[data-slot=code-block-content]:focus-visible]:ring-ring/50 data-[size=sm]:text-xs group/code-block relative flex w-full min-w-0 flex-col overflow-hidden",
{
variants: {
variant: {
default: "border border-input text-foreground has-[>[data-slot=code-block-content]:focus-visible]:border-ring dark:bg-input/30",
destructive: "border border-destructive/30 text-destructive dark:border-destructive/40"
}
},
defaultVariants: {
variant: "default"
}
}
)
const codeBlockLineVariants = cva(
"-mx-3 px-3 group-data-[size=sm]/code-block:-mx-2.5 group-data-[size=sm]/code-block:px-2.5 before:min-w-6 before:text-end before:text-muted-foreground after:start-1 after:text-muted-foreground in-data-numbered:gap-x-3 relative block min-h-lh after:absolute after:top-0 after:select-none in-data-numbered:col-span-2 in-data-numbered:grid in-data-numbered:grid-cols-subgrid in-data-numbered:[counter-increment:line] in-data-numbered:before:content-[counter(line)] in-data-numbered:before:select-none in-data-numbered:supports-[content:counter(line)_/_'']:before:content-[counter(line)_/_'']",
{
variants: {
variant: {
default: "",
added: "bg-muted after:content-['+']",
removed: "bg-destructive/10 after:text-destructive after:content-['−']",
highlighted: "bg-muted"
}
},
defaultVariants: {
variant: "default"
}
}
)
export function CodeBlockHeader(props: ComponentProps<"div">) {
return (
<div
{...props}
data-slot="code-block-header"
class={cn(
"gap-2 px-3 pt-3 text-muted-foreground group-data-[size=sm]/code-block:px-2.5 group-data-[size=sm]/code-block:pt-2.5 group-data-[variant=destructive]/code-block:text-destructive flex min-w-0 shrink-0 items-center *:has-[>[data-slot=code-block-title]]:min-w-0",
props.class
)}
/>
)
}
export function CodeBlockTitle(props: ComponentProps<"div">) {
return (
<div
{...props}
data-slot="code-block-title"
class={cn(
"font-sans text-sm font-medium text-foreground group-data-[size=sm]/code-block:text-xs group-data-[variant=destructive]/code-block:text-destructive [&_svg:not([class*='size-'])]:size-3.5 *:[svg]:me-1.5 min-w-0 truncate [&_svg]:pointer-events-none [&_svg]:inline-block [&_svg]:align-middle",
props.class
)}
/>
)
}
export function CodeBlockActions(props: ComponentProps<"div">) {
return (
<div
{...props}
data-slot="code-block-actions"
class={cn(
"-my-1 -me-1.5 gap-1 [[data-slot=code-block]>&]:end-2 [[data-slot=code-block]>&]:top-2 [[data-slot=code-block]>&]:m-0 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:end-1.5 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:top-1.5 [[data-slot=code-block]>&]:*:[button]:bg-background [[data-slot=code-block]>&]:*:[button]:ring-1 [[data-slot=code-block]>&]:*:[button]:ring-foreground/10 ms-auto flex shrink-0 items-center [[data-slot=code-block]>&]:absolute [[data-slot=code-block]>&]:z-10 [[data-slot=code-block]>&]:opacity-0 [[data-slot=code-block]>&]:transition-opacity [[data-slot=code-block]>&]:group-focus-within/code-block:opacity-100 [[data-slot=code-block]>&]:group-hover/code-block:opacity-100 [[data-slot=code-block]>&]:pointer-coarse:opacity-100",
props.class
)}
/>
)
}
export function CodeBlockFooter(props: ComponentProps<"div">) {
return (
<div
{...props}
data-slot="code-block-footer"
class={cn(
"gap-2 px-3 pb-3 text-muted-foreground group-data-[size=sm]/code-block:px-2.5 group-data-[size=sm]/code-block:pb-2.5 flex min-w-0 shrink-0 items-center",
props.class
)}
/>
)
}
export function CodeBlock(
props: ComponentProps<"div"> &
VariantProps<typeof codeBlockVariants> & { size?: "default" | "sm" }
) {
const rest = omit(props, "class", "variant", "size")
return (
<div
{...rest}
data-slot="code-block"
data-variant={props.variant ?? "default"}
data-size={props.size ?? "default"}
class={cn(codeBlockVariants({ variant: props.variant }), props.class)}
/>
)
}
export function CodeBlockCopyButton(
props: Omit<ButtonProps, "onClick"> & { value: string; onCopy?: () => void }
) {
const rest = omit(props, "value", "onCopy", "children", "class")
const [copied, setCopied] = createSignal(false)
const [failed, setFailed] = createSignal(false)
let timer: ReturnType<typeof setTimeout> | undefined
onCleanup(() => clearTimeout(timer))
async function copy() {
try {
await navigator.clipboard.writeText(props.value)
setCopied(true)
setFailed(false)
props.onCopy?.()
clearTimeout(timer)
timer = setTimeout(() => setCopied(false), 2000)
} catch {
setFailed(true)
}
}
return (
<>
<Button
variant="ghost"
size="icon-xs"
{...rest}
data-slot="code-block-copy-button"
data-copied={copied() || undefined}
class={cn("", props.class)}
aria-label={
copied() ? "Copied" : failed() ? "Copy failed" : "Copy code"
}
onClick={copy}
>
{copied() ? (
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M20 6 9 17l-5-5" />
</svg>
) : (
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<rect width="14" height="14" x="8" y="8" rx="2" ry="2" />
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
</svg>
)}
</Button>
<span aria-live="polite" class="sr-only">
{copied() ? "Copied" : failed() ? "Copy failed" : ""}
</span>
</>
)
}
export function CodeBlockContent(
props: Omit<ComponentProps<"pre">, "style"> & {
wrap?: boolean
lineNumbers?: boolean
startLine?: number
style?: JSX.CSSProperties
}
) {
const rest = omit(
props,
"class",
"children",
"wrap",
"lineNumbers",
"startLine",
"style"
)
return (
<pre
{...rest}
data-slot="code-block-content"
data-wrap={props.wrap || undefined}
data-numbered={props.lineNumbers || undefined}
dir="ltr"
tabindex={0}
style={{
"counter-reset": "line " + ((props.startLine ?? 1) - 1),
...props.style
}}
class={cn(
"px-3 py-3 leading-relaxed group-has-data-[slot=code-block-footer]/code-block:pb-2 group-has-data-[slot=code-block-header]/code-block:pt-2 group-data-[size=sm]/code-block:px-2.5 group-data-[size=sm]/code-block:py-2.5 group-data-[size=sm]/code-block:group-has-data-[slot=code-block-header]/code-block:pt-1.5 min-h-0 min-w-0 scrollbar-thin overflow-auto scroll-fade-x text-start font-mono outline-none data-wrap:scroll-fade-y data-wrap:wrap-break-word data-wrap:whitespace-pre-wrap",
props.class
)}
>
<code
data-slot="code-block-code"
class="grid min-h-lh min-w-max content-start in-data-numbered:grid-cols-[auto_1fr] in-data-wrap:min-w-0"
>
{typeof props.children === "string" && props.lineNumbers ? (
<For each={props.children.replace(/\n$/, "").split("\n")}>
{(line) => <CodeBlockLine>{line}</CodeBlockLine>}
</For>
) : (
props.children
)}
</code>
</pre>
)
}
export function CodeBlockLine(
props: ComponentProps<"span"> & VariantProps<typeof codeBlockLineVariants>
) {
const rest = omit(props, "class", "children", "variant")
return (
<span
{...rest}
data-slot="code-block-line"
data-variant={props.variant ?? "default"}
class={cn(codeBlockLineVariants({ variant: props.variant }), props.class)}
>
<span data-slot="code-block-line-content" class="min-w-0">
{props.children === undefined ||
props.children === null ||
props.children === ""
? "\n"
: props.children}
</span>
</span>
)
}import { createMemo, type Accessor } from "solid-js"
import {
highlightCodeTokens,
renderHighlightedLines
} from "~/lib/highlighter"
export function useHighlightedCode(
code: Accessor<string>,
language: Accessor<string>
) {
const tokens = createMemo(() => highlightCodeTokens(code(), language()))
return () => renderHighlightedLines(tokens())
}import type { HighlighterCore, ThemedToken } from "shiki/core"
import { For } from "solid-js"
let highlighter: Promise<HighlighterCore> | undefined
async function loadHighlighter() {
const [
core,
engine,
light,
dark,
js,
jsx,
ts,
tsx,
css,
json,
python,
shell
] = await Promise.all([
import("shiki/core"),
import("shiki/engine/javascript"),
import("shiki/themes/github-light-default.mjs"),
import("shiki/themes/github-dark.mjs"),
import("shiki/langs/javascript.mjs"),
import("shiki/langs/jsx.mjs"),
import("shiki/langs/typescript.mjs"),
import("shiki/langs/tsx.mjs"),
import("shiki/langs/css.mjs"),
import("shiki/langs/json.mjs"),
import("shiki/langs/python.mjs"),
import("shiki/langs/shellscript.mjs")
])
return core.createHighlighterCore({
engine: engine.createJavaScriptRegexEngine(),
themes: [light.default, dark.default],
langs: [
js.default,
jsx.default,
ts.default,
tsx.default,
css.default,
json.default,
python.default,
shell.default
]
})
}
export async function highlightCodeTokens(code: string, language: string) {
highlighter ??= loadHighlighter()
const instance = await highlighter
const lang =
language === "ansi" || instance.getLoadedLanguages().includes(language)
? language
: "text"
return instance.codeToTokens(code, {
lang,
themes: { light: "github-light-default", dark: "github-dark" },
defaultColor: false,
cssVariablePrefix: "--token-"
}).tokens
}
export function renderHighlightedLines(lines: ThemedToken[][]) {
return lines.map((line) =>
line.length === 0 ? (
""
) : (
<For each={line}>
{(token) => (
<span
class="text-(--token-light) dark:text-(--token-dark)"
style={token.htmlStyle}
>
{token.content}
</span>
)}
</For>
)
)
}
export async function highlightCode(code: string, language = "text") {
highlighter ??= loadHighlighter()
const instance = await highlighter
const lang = instance.getLoadedLanguages().includes(language)
? language
: "text"
return instance.codeToHtml(code, {
lang,
themes: { light: "github-light-default", dark: "github-dark" },
transformers: [
{
pre(node) {
node.properties.class =
"shiki no-scrollbar min-w-0 overflow-auto overscroll-contain px-4 py-3.5 outline-none !bg-transparent"
},
code(node) {
node.properties["data-line-numbers"] = ""
},
line(node) {
node.properties["data-line"] = ""
}
}
]
})
}Update the import paths to match your project setup.
Usage
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockTitle
} from "~/components/ui/code-block"<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>Terminal</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value="pnpm dev" />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>pnpm dev</CodeBlockContent>
</CodeBlock>Compose header, title, actions, content, and footer inside CodeBlock. CodeBlockContent accepts plain text or explicit CodeBlockLine children. Set lineNumbers, startLine, or wrap; line variants are added, removed, and highlighted. CodeBlockCopyButton takes value and reports clipboard success or failure accessibly. The content accepts pre-highlighted JSX; it does not bundle a syntax highlighter.
Composition
CodeBlock
├── CodeBlockHeader
│ ├── CodeBlockTitle
│ └── CodeBlockActions
│ └── CodeBlockCopyButton
├── CodeBlockActions (floating, when there is no header)
├── CodeBlockContent
│ └── CodeBlockLine
└── CodeBlockFooterCodeBlockContent takes a string or a list of CodeBlockLine. Use lines when you need line variants or highlighted tokens.
Features
- It streams cheaply. A string child 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 the language grammars on first use and renders ANSI colors in terminal output. On the server,highlightCodekeeps Shiki out of the client bundle. - It fits where code shows up. Use it in a message, a Markdown fence, a Trace line, Tabs, a Dialog or a
typesetcontainer. - 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. 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 kBimport { CodeBlock, CodeBlockContent } from "~/components/ui/code-block"
const output = `$ 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`
export default function CodeBlockBasic() {
return (
<div class="w-full max-w-md">
<CodeBlock>
<CodeBlockContent>{output}</CodeBlockContent>
</CodeBlock>
</div>
)
}Header
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.0// Inline SVG icons from Lucide (https://lucide.dev), ISC License, Copyright (c) Lucide Icons and Contributors.
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockTitle
} from "~/components/ui/code-block"
const command = "pnpm add ai @ai-sdk/react zod"
const output = `$ ${command}
Packages: +14
Progress: resolved 412, reused 398, downloaded 14, added 14, done
Done in 2.8s using pnpm v10.18.0`
export default function CodeBlockHeaderExample() {
return (
<div class="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M12 19h8" />
<path d="m4 17 6-6-6-6" />
</svg>
Terminal
</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={command} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>{output}</CodeBlockContent>
</CodeBlock>
</div>
)
}A long title truncates. To link the title to a file, wrap CodeBlockTitle in an anchor.
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)// Inline SVG icons from Lucide (https://lucide.dev), ISC License, Copyright (c) Lucide Icons and Contributors.
import { createSignal } from "solid-js"
import { Button } from "~/components/ui/button"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockTitle
} from "~/components/ui/code-block"
const output = `$ 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)`
function download(value: string, filename: string) {
const url = URL.createObjectURL(new Blob([value], { type: "text/plain" }))
const link = document.createElement("a")
link.href = url
link.download = filename
link.click()
URL.revokeObjectURL(url)
}
export default function CodeBlockActionsExample() {
const [wrap, setWrap] = createSignal(true)
return (
<div class="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M12 19h8" />
<path d="m4 17 6-6-6-6" />
</svg>
Terminal
</CodeBlockTitle>
<CodeBlockActions>
<Button
variant="ghost"
size="icon-xs"
aria-label="Wrap lines"
aria-pressed={wrap() ? "true" : "false"}
class="aria-pressed:text-foreground"
onClick={() => setWrap((enabled) => !enabled)}
>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m16 16-3 3 3 3" />
<path d="M3 12h14.5a1 1 0 0 1 0 7H13" />
<path d="M3 19h6" />
<path d="M3 5h18" />
</svg>
</Button>
<Button
variant="ghost"
size="icon-xs"
aria-label="Download"
onClick={() => download(output, "lint.log")}
>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M12 15V3" />
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<path d="m7 10 5 5 5-5" />
</svg>
</Button>
<CodeBlockCopyButton value={output} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent wrap={wrap()}>{output}</CodeBlockContent>
</CodeBlock>
</div>
)
}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.0import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton
} from "~/components/ui/code-block"
const output = `$ 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`
export default function CodeBlockFloatingActions() {
return (
<div class="w-full max-w-md">
<CodeBlock>
<CodeBlockActions>
<CodeBlockCopyButton value={output} />
</CodeBlockActions>
<CodeBlockContent>{output}</CodeBlockContent>
</CodeBlock>
</div>
)
}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" }}import { CodeBlock, CodeBlockContent } from "~/components/ui/code-block"
const code = `{
"name": "chat",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build"
}
}`
export default function CodeBlockLineNumbers() {
return (
<div class="w-full max-w-md">
<CodeBlock>
<CodeBlockContent lineNumbers>{code}</CodeBlockContent>
</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.
if (!session) { redirect("/login") }
const projects = await db.project.findMany({ where: { ownerId: session.user.id }, orderBy: { updatedAt: "desc" }, })
return <ProjectList projects={projects} />}import { For } from "solid-js"
import { useHighlightedCode } from "~/hooks/use-highlighted-code"
import {
CodeBlock,
CodeBlockContent,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle
} from "~/components/ui/code-block"
const code = ` if (!session) {
redirect("/login")
}
const projects = await db.project.findMany({
where: { ownerId: session.user.id },
orderBy: { updatedAt: "desc" },
})
return <ProjectList projects={projects} />
}`
export default function CodeBlockStartLine() {
const lines = useHighlightedCode(
() => code,
() => "tsx"
)
return (
<div class="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>app/dashboard/page.tsx</CodeBlockTitle>
</CodeBlockHeader>
<CodeBlockContent lineNumbers startLine={995}>
<For each={lines()}>
{(line) => <CodeBlockLine>{line}</CodeBlockLine>}
</For>
</CodeBlockContent>
</CodeBlock>
</div>
)
}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.import { CodeBlock, CodeBlockContent } from "~/components/ui/code-block"
const 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.`
export default function CodeBlockWrap() {
return (
<div class="flex w-full max-w-md flex-col gap-4">
<CodeBlock>
<CodeBlockContent>{output}</CodeBlockContent>
</CodeBlock>
<CodeBlock>
<CodeBlockContent wrap>{output}</CodeBlockContent>
</CodeBlock>
</div>
)
}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" }], },}import { For } from "solid-js"
import {
CodeBlock,
CodeBlockContent,
CodeBlockLine
} from "~/components/ui/code-block"
const code = `export default {
experimental: {
reactCompiler: true,
viewTransition: true,
},
images: {
remotePatterns: [{ hostname: "avatars.githubusercontent.com" }],
},
}`
const highlighted = [2, 3]
export default function CodeBlockHighlightedLines() {
return (
<div class="w-full max-w-md">
<CodeBlock>
<CodeBlockContent lineNumbers>
<For each={code.split("\n")}>
{(line, index) => (
<CodeBlockLine
variant={
highlighted.includes(index()) ? "highlighted" : "default"
}
>
{line}
</CodeBlockLine>
)}
</For>
</CodeBlockContent>
</CodeBlock>
</div>
)
}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 class="text-sm text-muted-foreground"> Hello, {name}! </p>}import { For } from "solid-js"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle
} from "~/components/ui/code-block"
const patch = ` export function Greeting({ name }: { name: string }) {
- return <p>Hello, {name}</p>
+ return <p class="text-sm text-muted-foreground">
+ Hello, {name}!
+ </p>
}`
function getVariant(line: string) {
if (line.startsWith("+")) {
return "added"
}
if (line.startsWith("-")) {
return "removed"
}
return "default"
}
export default function CodeBlockDiff() {
return (
<div class="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>components/greeting.tsx</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={patch} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>
<For each={patch.split("\n")}>
{(line) => (
<CodeBlockLine variant={getVariant(line)}>
{line.slice(1)}
</CodeBlockLine>
)}
</For>
</CodeBlockContent>
</CodeBlock>
</div>
)
}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 45msimport {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockTitle
} from "~/components/ui/code-block"
const logs = Array.from(
{ length: 40 },
(_, index) =>
`[${String(index + 1).padStart(2, "0")}] GET /api/chat 200 in ${12 + ((index * 7) % 40)}ms`
).join("\n")
export default function CodeBlockHeight() {
return (
<div class="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>Logs</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={logs} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent class="max-h-48 scroll-fade-y">
{logs}
</CodeBlockContent>
</CodeBlock>
</div>
)
}CodeBlockContent fades the left and right edges by default and the top and bottom edges when it wraps. Add scroll-fade-y from the shared stylesheet 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"
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 class="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> )}// Inline SVG icons from Lucide (https://lucide.dev), ISC License, Copyright (c) Lucide Icons and Contributors.
import { createSignal, createUniqueId, For } from "solid-js"
import { useHighlightedCode } from "~/hooks/use-highlighted-code"
import { Button } from "~/components/ui/button"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockFooter,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle
} from "~/components/ui/code-block"
const code = `"use client"
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 class="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>
)
}`
export default function CodeBlockShowMore() {
const [expanded, setExpanded] = createSignal(false)
const lines = useHighlightedCode(
() => code,
() => "tsx"
)
const id = createUniqueId()
return (
<div class="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>components/chat.tsx</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={code} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent
id={id}
lineNumbers
class={
expanded() ? undefined : "max-h-64 overflow-y-hidden scroll-fade-y"
}
>
<For each={lines()}>
{(line) => <CodeBlockLine>{line}</CodeBlockLine>}
</For>
</CodeBlockContent>
<CodeBlockFooter class="justify-center">
<Button
variant="ghost"
size="xs"
aria-expanded={expanded() ? "true" : "false"}
aria-controls={id}
onClick={() => setExpanded(!expanded())}
>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
class="transition-transform in-aria-expanded:rotate-180"
>
<path d="m6 9 6 6 6-6" />
</svg>
{expanded() ? "Show less" : "Show more"}
</Button>
</CodeBlockFooter>
</CodeBlock>
</div>
)
}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 { 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 class="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> )}// Inline SVG icons from Lucide (https://lucide.dev), ISC License, Copyright (c) Lucide Icons and Contributors.
import { createSignal, createUniqueId, For } from "solid-js"
import { useHighlightedCode } from "~/hooks/use-highlighted-code"
import { Button } from "~/components/ui/button"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockFooter,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle
} from "~/components/ui/code-block"
const code = `"use client"
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 class="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>
)
}`
export default function CodeBlockShowMoreScroll() {
const [expanded, setExpanded] = createSignal(false)
const lines = useHighlightedCode(
() => code,
() => "tsx"
)
const id = createUniqueId()
return (
<div class="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>components/chat.tsx</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={code} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent
id={id}
lineNumbers
class={
expanded()
? "max-h-96 scroll-fade-y"
: "max-h-64 overflow-y-hidden scroll-fade-y"
}
>
<For each={lines()}>
{(line) => <CodeBlockLine>{line}</CodeBlockLine>}
</For>
</CodeBlockContent>
<CodeBlockFooter class="justify-center">
<Button
variant="ghost"
size="xs"
aria-expanded={expanded() ? "true" : "false"}
aria-controls={id}
onClick={() => setExpanded(!expanded())}
>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
class="transition-transform in-aria-expanded:rotate-180"
>
<path d="m6 9 6 6 6-6" />
</svg>
{expanded() ? "Show less" : "Show more"}
</Button>
</CodeBlockFooter>
</CodeBlock>
</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.0// Inline SVG icons from Lucide (https://lucide.dev), ISC License, Copyright (c) Lucide Icons and Contributors.
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockTitle
} from "~/components/ui/code-block"
const output = `$ 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`
export default function CodeBlockSize() {
return (
<div class="flex w-full max-w-md flex-col gap-4">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M12 19h8" />
<path d="m4 17 6-6-6-6" />
</svg>
Terminal
</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={output} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent wrap>{output}</CodeBlockContent>
</CodeBlock>
<CodeBlock size="sm">
<CodeBlockHeader>
<CodeBlockTitle>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M12 19h8" />
<path d="m4 17 6-6-6-6" />
</svg>
Terminal
</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={output} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent wrap>{output}</CodeBlockContent>
</CodeBlock>
</div>
)
}Destructive
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)import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockTitle
} from "~/components/ui/code-block"
const 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)`
export default function CodeBlockDestructive() {
return (
<div class="w-full max-w-md">
<CodeBlock variant="destructive">
<CodeBlockHeader>
<CodeBlockTitle>Error</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={error} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent wrap>{error}</CodeBlockContent>
</CodeBlock>
</div>
)
}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)// Inline SVG icons from Lucide (https://lucide.dev), ISC License, Copyright (c) Lucide Icons and Contributors.
import { CodeBlock, CodeBlockContent } from "~/components/ui/code-block"
import {
Trace,
TraceCollapsible,
TraceCollapsibleContent,
TraceCollapsibleTrigger,
TraceIcon,
TraceLine,
TraceTitle
} from "~/components/ui/trace"
const output = `$ node --version
v24.18.0`
const error = `$ pnpm dev
Error: listen EADDRINUSE: address already in use :::3000
at Server.setupListenHandle [as _listen2] (node:net:1908:16)`
export default function CodeBlockTrace() {
return (
<div class="w-full max-w-md">
<Trace>
<TraceCollapsible defaultOpen>
<TraceCollapsibleTrigger>
<TraceLine>
<TraceIcon>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M12 19h8" />
<path d="m4 17 6-6-6-6" />
</svg>
</TraceIcon>
<TraceTitle>Ran node --version</TraceTitle>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent>
<CodeBlock size="sm">
<CodeBlockContent wrap class="max-h-64">
{output}
</CodeBlockContent>
</CodeBlock>
</TraceCollapsibleContent>
</TraceCollapsible>
<TraceCollapsible defaultOpen>
<TraceCollapsibleTrigger>
<TraceLine status="error">
<TraceIcon>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M12 19h8" />
<path d="m4 17 6-6-6-6" />
</svg>
</TraceIcon>
<TraceTitle>Failed to run pnpm dev</TraceTitle>
</TraceLine>
</TraceCollapsibleTrigger>
<TraceCollapsibleContent>
<CodeBlock size="sm" variant="destructive">
<CodeBlockContent wrap class="max-h-64">
{error}
</CodeBlockContent>
</CodeBlock>
</TraceCollapsibleContent>
</TraceCollapsible>
</Trace>
</div>
)
}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()}import { For } from "solid-js"
import { useHighlightedCode } from "~/hooks/use-highlighted-code"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle
} from "~/components/ui/code-block"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "~/components/ui/tabs"
const files = [
{
id: "route",
title: "app/api/chat/route.ts",
language: "ts",
code: `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()
}`
},
{
id: "chat",
title: "components/chat.tsx",
language: "tsx",
code: `"use client"
import { useChat } from "@ai-sdk/react"
export function Chat() {
const { messages } = useChat()
return <MessageList messages={messages} />
}`
},
{
id: "env",
title: ".env.local",
language: "bash",
code: "AI_GATEWAY_API_KEY=your-api-key"
}
]
function FileCode(props: { code: string; language: string }) {
const lines = useHighlightedCode(
() => props.code,
() => props.language
)
return (
<CodeBlockContent lineNumbers>
<For each={lines()}>
{(line) => <CodeBlockLine>{line}</CodeBlockLine>}
</For>
</CodeBlockContent>
)
}
export default function CodeBlockTabs() {
return (
<Tabs defaultValue="route" class="w-full max-w-md">
<TabsList>
<For each={files}>
{(file) => (
<TabsTrigger value={file.id}>
{file.title.split("/").at(-1)}
</TabsTrigger>
)}
</For>
</TabsList>
<For each={files}>
{(file) => (
<TabsContent value={file.id}>
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>{file.title}</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={file.code} />
</CodeBlockActions>
</CodeBlockHeader>
<FileCode code={file.code} language={file.language} />
</CodeBlock>
</TabsContent>
)}
</For>
</Tabs>
)
}Message
Put a CodeBlock between paragraphs inside a Message.
import { For } from "solid-js"
import { useHighlightedCode } from "~/hooks/use-highlighted-code"
import { Bubble, BubbleContent } from "~/components/ui/bubble"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle
} from "~/components/ui/code-block"
import { Message, MessageContent } from "~/components/ui/message"
const code = `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()
}`
export default function CodeBlockChat() {
const lines = useHighlightedCode(
() => code,
() => "ts"
)
return (
<div class="flex w-full max-w-md flex-col gap-4 text-sm">
<Message align="end">
<MessageContent>
<Bubble variant="muted">
<BubbleContent>How do I stream a response?</BubbleContent>
</Bubble>
</MessageContent>
</Message>
<Message>
<MessageContent class="gap-3">
<p>Create a route handler that returns the stream:</p>
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>app/api/chat/route.ts</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={code} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>
<For each={lines()}>
{(line) => <CodeBlockLine>{line}</CodeBlockLine>}
</For>
</CodeBlockContent>
</CodeBlock>
<p>The client reads it with useChat.</p>
</MessageContent>
</Message>
</div>
)
}Typeset
A CodeBlock between paragraphs keeps its code styling and copy controls in a prose layout.
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.
// Inline SVG icons from Lucide (https://lucide.dev), ISC License, Copyright (c) Lucide Icons and Contributors.
import { For } from "solid-js"
import { useHighlightedCode } from "~/hooks/use-highlighted-code"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle
} from "~/components/ui/code-block"
const code = `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()
}`
export default function CodeBlockTypeset() {
const lines = useHighlightedCode(
() => code,
() => "ts"
)
return (
<div class="grid w-full max-w-md gap-3 text-start text-sm">
<h3 class="font-semibold">Stream a response</h3>
<p>
Create a route handler that calls <code>streamText</code> and returns
the stream to the client.
</p>
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z" />
<path d="M14 2v5a1 1 0 0 0 1 1h5" />
<path d="M10 12.5 8 15l2 2.5" />
<path d="m14 12.5 2 2.5-2 2.5" />
</svg>
app/api/chat/route.ts
</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={code} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent lineNumbers>
<For each={lines()}>
{(line) => <CodeBlockLine>{line}</CodeBlockLine>}
</For>
</CodeBlockContent>
</CodeBlock>
<p>
The <code>useChat</code> hook reads the stream on the client and renders
the answer while it is written.
</p>
</div>
)
}Syntax Highlighting
useHighlightedCode highlights with Shiki and returns a Solid JSX element for each CodeBlockLine.
{ "location": "San Francisco", "temperature": 18, "unit": "celsius", "conditions": ["fog", "wind"]}import { For } from "solid-js"
import { useHighlightedCode } from "~/hooks/use-highlighted-code"
import {
CodeBlock,
CodeBlockContent,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle
} from "~/components/ui/code-block"
const code = `{
"location": "San Francisco",
"temperature": 18,
"unit": "celsius",
"conditions": ["fog", "wind"]
}`
export default function CodeBlockHighlighting() {
const lines = useHighlightedCode(
() => code,
() => "json"
)
return (
<div class="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>getWeather output</CodeBlockTitle>
</CodeBlockHeader>
<CodeBlockContent>
<For each={lines()}>
{(line) => <CodeBlockLine>{line}</CodeBlockLine>}
</For>
</CodeBlockContent>
</CodeBlock>
</div>
)
}Shiki uses its JavaScript regex engine, so there is no WASM to load.
Languages
Configure the available grammars in lib/highlighter.tsx. Unrecognized languages render 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.import { For } from "solid-js"
import { useHighlightedCode } from "~/hooks/use-highlighted-code"
import {
CodeBlock,
CodeBlockContent,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle
} from "~/components/ui/code-block"
const samples = [
{
language: "css",
title: "app/globals.css",
code: `@import "tailwindcss";
:root {
--radius: 0.625rem;
}`
},
{
language: "python",
title: "main.py",
code: `def greet(name: str) -> str:
return f"Hello, {name}!"`
},
{
language: "text",
title: "notes.txt",
code: "A language that is not in the list renders as plain text."
}
]
function Sample(props: { code: string; language: string }) {
const lines = useHighlightedCode(
() => props.code,
() => props.language
)
return (
<CodeBlockContent>
<For each={lines()}>
{(line) => <CodeBlockLine>{line}</CodeBlockLine>}
</For>
</CodeBlockContent>
)
}
export default function CodeBlockLanguages() {
return (
<div class="flex w-full max-w-md flex-col gap-4">
<For each={samples}>
{(sample) => (
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>{sample.title}</CodeBlockTitle>
</CodeBlockHeader>
<Sample code={sample.code} language={sample.language} />
</CodeBlock>
)}
</For>
</div>
)
}The demo includes TypeScript, CSS, JSON, and Python.
Terminal Output
Pass "ansi" as the language to render the colors in terminal output. Without it, escape codes show as text.
$ 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)// Inline SVG icons from Lucide (https://lucide.dev), ISC License, Copyright (c) Lucide Icons and Contributors.
import { For } from "solid-js"
import { useHighlightedCode } from "~/hooks/use-highlighted-code"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle
} from "~/components/ui/code-block"
const output = `$ pnpm test
\x1b[32m✓\x1b[39m src/format.test.ts \x1b[2m(4 tests)\x1b[22m
\x1b[32m✓\x1b[39m src/parse.test.ts \x1b[2m(7 tests)\x1b[22m
\x1b[31m✗\x1b[39m src/stream.test.ts \x1b[2m(3 tests | 1 failed)\x1b[22m
\x1b[31mAssertionError: expected 'hello' to be 'hello world'\x1b[39m
Tests \x1b[31m1 failed\x1b[39m | \x1b[32m13 passed\x1b[39m (14)`
export default function CodeBlockAnsi() {
const lines = useHighlightedCode(
() => output,
() => "ansi"
)
return (
<div class="w-full max-w-md">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M12 19h8" />
<path d="m4 17 6-6-6-6" />
</svg>
Terminal
</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton
value={output.replaceAll(
new RegExp(String.fromCharCode(27) + "\\[[\\d;]*m", "g"),
""
)}
/>
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent wrap>
<For each={lines()}>
{(line) => <CodeBlockLine>{line}</CodeBlockLine>}
</For>
</CodeBlockContent>
</CodeBlock>
</div>
)
}ANSI colors do not carry from one line to the next.
Server Rendering
Call highlightCode from Astro frontmatter to render highlighted HTML at build time.
Streaming
Pass an accessor for the growing buffer to useHighlightedCode. Keep copy disabled until the block is complete.
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}npx solidui-cli@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-key// Inline SVG icons from Lucide (https://lucide.dev), ISC License, Copyright (c) Lucide Icons and Contributors.
import { createSignal, For, onCleanup, Show } from "solid-js"
import { useHighlightedCode } from "~/hooks/use-highlighted-code"
import { Button } from "~/components/ui/button"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle
} from "~/components/ui/code-block"
const blocks: {
title?: string
language: string
code: string
lineNumbers?: boolean
highlight?: number[]
diff?: boolean
}[] = [
{
title: "hooks/use-debounce.ts",
language: "ts",
lineNumbers: true,
code: `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
}`
},
{
language: "bash",
code: "npx solidui-cli@latest add code-block"
},
{
title: "components/search.tsx",
language: "tsx",
lineNumbers: true,
diff: true,
code: ` 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} />
}`
},
{
title: "app/api/chat/route.ts",
language: "ts",
lineNumbers: true,
highlight: [5, 6, 7, 8],
code: `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()
}`
},
{
title: ".env.local",
language: "bash",
code: "AI_GATEWAY_API_KEY=your-api-key"
}
]
// Where each block starts in the stream.
const offsets = blocks.map((_, index) =>
blocks.slice(0, index).reduce((total, block) => total + block.code.length, 0)
)
const total = blocks.reduce((sum, block) => sum + block.code.length, 0)
function StreamingBlock(props: {
block: (typeof blocks)[number]
code: string
}) {
const rows = () => props.code.split("\n")
const source = () =>
props.block.diff
? rows()
.map((row) => row.slice(1))
.join("\n")
: props.code
const lines = useHighlightedCode(source, () => props.block.language)
function variant(index: number) {
if (props.block.diff) {
const prefix = rows()[index]?.[0]
if (prefix === "+") return "added"
if (prefix === "-") return "removed"
}
return props.block.highlight?.includes(index) ? "highlighted" : "default"
}
return (
<CodeBlock>
<Show when={props.block.title}>
<CodeBlockHeader>
<CodeBlockTitle>{props.block.title}</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton
value={source()}
disabled={props.code.length < props.block.code.length}
/>
</CodeBlockActions>
</CodeBlockHeader>
</Show>
<CodeBlockContent lineNumbers={props.block.lineNumbers ?? false}>
<For each={lines()}>
{(line, index) => (
<CodeBlockLine variant={variant(index())}>{line}</CodeBlockLine>
)}
</For>
</CodeBlockContent>
</CodeBlock>
)
}
export default function CodeBlockStreaming() {
const [length, setLength] = createSignal(total)
let timer: ReturnType<typeof setInterval> | undefined
onCleanup(() => clearInterval(timer))
function replay() {
setLength(0)
let position = 0
timer = setInterval(() => {
position = Math.min(total, position + 6)
setLength(position)
if (position === total) clearInterval(timer)
}, 32)
}
return (
<div class="flex w-full max-w-md flex-col gap-4">
<For each={blocks}>
{(block, index) => {
const shown = () => length() - (offsets[index()] ?? 0)
return (
<Show when={shown() > 0}>
<StreamingBlock
block={block}
code={block.code.slice(0, shown())}
/>
</Show>
)
}}
</For>
<Button
variant="outline"
size="sm"
class="self-start"
disabled={length() < total}
onClick={replay}
>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
<path d="M3 3v5h5" />
</svg>
Replay
</Button>
</div>
)
}Markdown
Render inline Markdown code with <code> and fenced code with CodeBlock. This preview streams a sample response to show how the fenced block updates.
// Inline SVG icons from Lucide (https://lucide.dev), ISC License, Copyright (c) Lucide Icons and Contributors.
import { createSignal, For, onCleanup, Show } from "solid-js"
import { useHighlightedCode } from "~/hooks/use-highlighted-code"
import { Bubble, BubbleContent } from "~/components/ui/bubble"
import { Button } from "~/components/ui/button"
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle
} from "~/components/ui/code-block"
import { Message, MessageContent } from "~/components/ui/message"
const code = `import { createEffect, createSignal, onCleanup, type Accessor } from "solid-js"
export function useDebounce<T>(value: Accessor<T>, delay = 300) {
const [debounced, setDebounced] = createSignal(value())
createEffect(() => value(), (next) => {
const timeout = setTimeout(() => setDebounced(() => next), delay)
onCleanup(() => clearTimeout(timeout))
})
return debounced
}`
export default function CodeBlockMarkdown() {
const [position, setPosition] = createSignal(code.length)
const ready = () => position() === code.length
const lines = useHighlightedCode(
() => code.slice(0, position()),
() => "tsx"
)
let timer: ReturnType<typeof setInterval> | undefined
onCleanup(() => clearInterval(timer))
function replay() {
setPosition(0)
let offset = 0
timer = setInterval(() => {
offset = Math.min(code.length, offset + 5)
setPosition(offset)
if (offset === code.length) clearInterval(timer)
}, 30)
}
return (
<div class="flex min-h-112 w-full max-w-md flex-col gap-4 py-6 text-start text-sm">
<Message align="end">
<MessageContent>
<Bubble align="end" variant="muted">
<BubbleContent>
How do I debounce a search input in Solid?
</BubbleContent>
</Bubble>
</MessageContent>
</Message>
<Message>
<MessageContent>
<p>
Wrap the value in a <code>useDebounce</code> hook. It returns the
latest value once it stops changing for <code>delay</code>{" "}
milliseconds.
</p>
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>tsx</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={code} disabled={!ready()} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>
<For each={lines()}>
{(line) => <CodeBlockLine>{line}</CodeBlockLine>}
</For>
</CodeBlockContent>
</CodeBlock>
<Show when={ready()}>
<p>
Pass the debounced value to your fetch instead of the raw input.
</p>
</Show>
</MessageContent>
</Message>
<Show when={ready()}>
<Button
variant="outline"
size="sm"
class="mt-auto self-start"
onClick={replay}
>
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
<path d="M3 3v5h5" />
</svg>{" "}
Replay
</Button>
</Show>
</div>
)
}Accessibility
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.
API Reference
CodeBlock
The surface that holds the header, the content and the footer.
CodeBlockHeader
A row above the content for a title and actions.
CodeBlockTitle
A filename or a label, with an optional icon. It truncates.
CodeBlockActions
Holds buttons at the end of the header. As a direct child of CodeBlock, it floats.
CodeBlockCopyButton
A ghost icon button that copies value to the clipboard. It accepts the props of Button.
CodeBlockContent
The pre that scrolls or wraps.
CodeBlockLine
One line of code.
CodeBlockFooter
A row below the content, such as for a Show More button.
useHighlightedCode
Returns an accessor for the highlighted lines. Unrecognized languages render as plain text.