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()}
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass, codeBlockActionsClass,
codeBlockContentClass, codeBlockCodeClass, codeBlockLines,
} from '#components/ui/code-block.ts';
import { DownloadIcon, FileCodeIcon, WrapTextIcon } from '#lib/ui/lucide.ts';
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()
}`;
export default function CodeBlockDemo() {
return html`
<div class="w-full max-w-lg">
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>
${FileCodeIcon()}
app/api/chat/route.ts
</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<button
type="button"
data-slot="button"
data-variant="ghost"
data-size="icon-xs"
aria-label="Wrap lines"
aria-pressed="false"
class=${cn(buttonClass({ variant: 'ghost', size: 'icon-xs' }), 'aria-pressed:text-foreground')}
>
${WrapTextIcon()}
</button>
<button
type="button"
data-slot="button"
data-variant="ghost"
data-size="icon-xs"
aria-label="Download"
class=${buttonClass({ variant: 'ghost', size: 'icon-xs' })}
>
${DownloadIcon()}
</button>
<ui-code-block-copy-button value=${code}></ui-code-block-copy-button>
</div>
</div>
<pre data-slot="code-block-content" data-numbered tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${codeBlockLines(code, { variants: { 6: 'highlighted', 7: 'highlighted', 8: 'highlighted', 9: 'highlighted', 10: 'highlighted' } })}</code></pre>
</div>
</div>
`;
}
View Code
Installation
Copy and paste the following code into your project.
/**
* Code block: a framed block of code with an optional header, title,
* actions, footer, line numbers and per-line highlights. Tier 1, with one
* Tier-2 part, the copy button.
*
* shadcn parity:
* CodeBlock (variant, size) → <div data-slot="code-block" data-variant data-size class=${codeBlockClass({ variant })}>
* (codeBlockVariants is the same helper under shadcn's name)
* CodeBlockHeader / Title / Actions / Footer
* → <div class=${codeBlockHeaderClass()} data-slot="code-block-header"> and so on
* CodeBlockContent (wrap, lineNumbers, startLine)
* → <pre data-slot="code-block-content" tabindex="0" dir="ltr" class=${codeBlockContentClass()}
* ?data-wrap ?data-numbered style="counter-reset: line N">
* <code data-slot="code-block-code" class=${codeBlockCodeClass()}>
* CodeBlockLine variant → codeBlockLines(text, { variants }) for numbered lines, or a
* <span data-slot="code-block-line" class=${codeBlockLineClass({ variant })}> of your own
* CodeBlockCopyButton value → <ui-code-block-copy-button value>, which copies its block's code
* when it has no value
*
* `codeBlockLines` splits text on newlines into the line spans numbering and
* highlights need, keeping an empty line as a newline so a copied selection
* keeps its blank lines. Pass `{ 3: 'added', 4: 'removed' }` as `variants`
* (one-based line numbers) to mark lines.
*
* A11y (required for accessible output): keep `tabindex="0"` on the `<pre>`,
* so a keyboard can reach and scroll a block wider than its frame, and
* `dir="ltr"`, since code reads left to right on any page. A title names the
* file or language. The copy button is named "Copy", becomes "Copied" for two
* seconds, and announces it through a polite live region. Added and removed
* lines are marked by colour and by a "+" / "−" gutter sign, which a screen
* reader skips, so say what changed in prose when it matters.
*
* @example
* ```html
* <div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
* <div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
* <div data-slot="code-block-title" class=${codeBlockTitleClass()}>app/page.ts</div>
* <div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
* <ui-code-block-copy-button></ui-code-block-copy-button>
* </div>
* </div>
* <pre data-slot="code-block-content" data-numbered tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code
* data-slot="code-block-code" class=${codeBlockCodeClass()}>${codeBlockLines(source, { variants: { 2: 'added' } })}</code></pre>
* </div>
* ```
*/
import { WebComponent, html, signal } from '@webjsdev/core';
import { cn } from '../lib/utils.ts';
import { buttonClass, type ButtonVariant, type ButtonSize } from './button.ts';
const CODE_BLOCK_VARIANTS = {
default: 'border border-input text-foreground shadow-xs dark:bg-input/30 has-[>[data-slot=code-block-content]:focus-visible]:border-ring',
destructive: 'border border-destructive/30 text-destructive dark:border-destructive/40',
} as const;
export type CodeBlockVariant = keyof typeof CODE_BLOCK_VARIANTS;
/** The frame's classes. */
export function codeBlockClass(opts: { variant?: CodeBlockVariant } & { className?: string } = {}): string {
return cn('rounded-md text-sm group-data-[size=sm]/code-block:text-xs has-[>[data-slot=code-block-content]:focus-visible]:ring-[3px] has-[>[data-slot=code-block-content]:focus-visible]:ring-ring/50 group/code-block relative flex w-full min-w-0 flex-col overflow-hidden', CODE_BLOCK_VARIANTS[opts.variant ?? 'default'], opts.className);
}
/** shadcn's name for {@link codeBlockClass}. Like cva, it merges a `className`. */
export function codeBlockVariants(opts: { variant?: CodeBlockVariant; className?: string } = {}): string {
return codeBlockClass(opts);
}
/** The header row. */
export function codeBlockHeaderClass(): string {
return 'gap-2 px-3 pt-3 text-muted-foreground group-data-[variant=destructive]/code-block:text-destructive group-data-[size=sm]/code-block:px-2.5 group-data-[size=sm]/code-block:pt-2.5 flex min-w-0 shrink-0 items-center *:has-[>[data-slot=code-block-title]]:min-w-0';
}
/** The title in the header. */
export function codeBlockTitleClass(): string {
return "font-sans text-sm font-medium text-foreground group-data-[variant=destructive]/code-block:text-destructive *:[svg]:me-1.5 [&_svg:not([class*='size-'])]:size-3.5 group-data-[size=sm]/code-block:text-xs min-w-0 truncate [&_svg]:pointer-events-none [&_svg]:inline-block [&_svg]:align-middle";
}
/** The actions (in the header, or floating over the code when a direct child of the frame). */
export function codeBlockActionsClass(): string {
return '-my-1 -me-1.5 gap-1 [[data-slot=code-block]>&]:m-0 [[data-slot=code-block]>&]:top-2 [[data-slot=code-block]>&]:end-2 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:top-1.5 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:end-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';
}
/** The scrolling `<pre>`. */
export function codeBlockContentClass(): string {
return 'px-3 py-3 leading-relaxed group-has-data-[slot=code-block-header]/code-block:pt-2 group-has-data-[slot=code-block-footer]/code-block:pb-2 group-data-[size=sm]/code-block:px-2.5 group-data-[size=sm]/code-block:py-2.5 min-h-0 min-w-0 scroll-fade-x scrollbar-thin overflow-auto text-start font-mono outline-none data-[wrap]:scroll-fade-y data-[wrap]:wrap-break-word data-[wrap]:whitespace-pre-wrap';
}
/** The `<code>` inside it. */
export function codeBlockCodeClass(): string {
return 'grid min-h-lh min-w-max content-start in-data-numbered:grid-cols-[auto_1fr] in-data-wrap:min-w-0';
}
const CODE_BLOCK_LINE_VARIANTS = {
default: '',
added: "bg-muted after:content-['+']",
removed: "bg-destructive/10 after:text-destructive after:content-['−']",
highlighted: 'bg-muted',
} as const;
export type CodeBlockLineVariant = keyof typeof CODE_BLOCK_LINE_VARIANTS;
/** One line's classes. */
export function codeBlockLineClass(opts: { variant?: CodeBlockLineVariant } & { className?: string } = {}): string {
return cn(
"-mx-3 px-3 in-data-numbered:gap-x-3 before:min-w-6 before:text-end before:text-muted-foreground after:start-1 after:text-muted-foreground group-data-[size=sm]/code-block:-mx-2.5 group-data-[size=sm]/code-block:px-2.5 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)_/_'']",
CODE_BLOCK_LINE_VARIANTS[opts.variant ?? 'default'],
opts.className,
);
}
/** shadcn's name for {@link codeBlockLineClass}. Like cva, it merges a `className`. */
export function codeBlockLineVariants(opts: { variant?: CodeBlockLineVariant; className?: string } = {}): string {
return codeBlockLineClass(opts);
}
/** The footer row. */
export function codeBlockFooterClass(): string {
return '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';
}
/**
* The line spans for `text`, one per line, for line numbers and highlights.
* `variants` maps a one-based line number to its variant.
*/
export function codeBlockLines(text: string, opts: { variants?: Record<number, CodeBlockLineVariant> } = {}) {
const lines = text.replace(/\n$/, '').split(/\n/);
return lines.map((line, i) => {
const variant = opts.variants?.[i + 1] ?? 'default';
// An empty line holds a newline, so copying a selection keeps blank lines.
// (Spelled as a char code: a string literal holding a newline reads, to the
// style bake's lexer, like a string that ran into code.)
return html`<span data-slot="code-block-line" data-variant=${variant} class=${codeBlockLineClass({ variant })}><span data-slot="code-block-line-content" class="min-w-0">${line === '' ? String.fromCharCode(10) : line}</span></span>`;
});
}
// --------------------------------------------------------------------------
// <ui-code-block-copy-button>
// --------------------------------------------------------------------------
export class UiCodeBlockCopyButton extends WebComponent({
value: String,
variant: String,
size: String,
}) {
readonly #copied = signal(false);
_timer = 0;
constructor() {
super();
this.value = '';
this.variant = 'ghost';
this.size = 'icon-xs';
}
disconnectedCallback(): void {
clearTimeout(this._timer);
super.disconnectedCallback?.();
}
/** What a click copies: the `value`, else the code in this block. */
text(): string {
if (this.value) return this.value;
const block = this.closest?.('[data-slot="code-block"]');
const code = block?.querySelector('[data-slot="code-block-code"]') ?? block?.querySelector('code');
return (code?.textContent ?? '').replace(/\n$/, '');
}
render() {
return html`<button
type="button"
data-slot="code-block-copy-button"
?data-copied=${this.#copied.get()}
aria-label=${this.#copied.get() ? 'Copied' : 'Copy'}
class=${cn(buttonClass({ variant: this.variant as ButtonVariant, size: this.size as ButtonSize }), '')}
@click=${this._onClick}
>${this.#copied.get()
? html`<svg xmlns="http://www.w3.org/2000/svg" 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"></path></svg>`
: html`<svg xmlns="http://www.w3.org/2000/svg" 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"></rect><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"></path></svg>`}</button><span aria-live="polite" class="sr-only">${this.#copied.get() ? 'Copied' : ''}</span>`;
}
_onClick = (): void => {
const write = navigator.clipboard?.writeText?.(this.text());
if (!write) return;
write.then(() => {
this.#copied.set(true);
clearTimeout(this._timer);
this._timer = window.setTimeout(() => { this.#copied.set(false); }, 2000);
this.dispatchEvent(new CustomEvent('ui-copy', { bubbles: true, detail: { text: this.text() } }));
}).catch(() => {});
};
}
UiCodeBlockCopyButton.register('ui-code-block-copy-button');
Update the import paths to match your project setup.
Usage
import {
codeBlockClass,
codeBlockHeaderClass,
codeBlockTitleClass,
codeBlockActionsClass,
codeBlockContentClass,
codeBlockCodeClass,
codeBlockLines,
codeBlockFooterClass,
} from '#components/ui/code-block.ts';
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>Terminal</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<ui-code-block-copy-button value=${output}></ui-code-block-copy-button>
</div>
</div>
<pre data-slot="code-block-content" tabindex="0" dir="ltr" class=${codeBlockContentClass()}><code
data-slot="code-block-code" class=${codeBlockCodeClass()}>${output}</code></pre>
</div>
Composition
code-block codeBlockClass()
├── code-block-header codeBlockHeaderClass()
│ ├── code-block-title codeBlockTitleClass()
│ └── code-block-actions codeBlockActionsClass()
│ └── <ui-code-block-copy-button>
├── code-block-actions (floating, when there is no header)
├── code-block-content codeBlockContentClass(), on a pre element
│ └── code-block-code codeBlockCodeClass(), on a code element
│ └── code-block-line codeBlockLines() or codeBlockLineClass()
└── code-block-footer codeBlockFooterClass()
The <code> takes a string or a list of line spans. Use lines, from codeBlockLines(), when you need line numbers or line variants.
Features
- It stays small. A string renders as one text node, and
codeBlockLines()splits text into line spans only when you need numbers or line variants. - 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 works with any highlighter. Lines are plain text, and the token spans of any highlighter fit inside a line. See Syntax Highlighting.
- 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
Put a string inside the <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
import { html } from '@webjsdev/core';
import {
codeBlockClass, codeBlockContentClass, codeBlockCodeClass,
} from '#components/ui/code-block.ts';
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 html`
<div class="w-full max-w-md">
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<pre data-slot="code-block-content" tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${output}</code></pre>
</div>
</div>
`;
}
View Code
Header
The header holds a title and the actions. <ui-code-block-copy-button> copies its value, or the code in its block when it has none.
$ 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
import { html } from '@webjsdev/core';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass, codeBlockActionsClass,
codeBlockContentClass, codeBlockCodeClass,
} from '#components/ui/code-block.ts';
import { TerminalIcon } from '#lib/ui/lucide.ts';
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 CodeBlockHeader() {
return html`
<div class="w-full max-w-md">
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>
${TerminalIcon()}
Terminal
</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<ui-code-block-copy-button value=${command}></ui-code-block-copy-button>
</div>
</div>
<pre data-slot="code-block-content" tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${output}</code></pre>
</div>
</div>
`;
}
View Code
A long title truncates. To link the title to a file, wrap it in an anchor.
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<a href="/files/route.ts">
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>app/api/chat/route.ts</div>
</a>
</div>
Actions
The actions hold any number of buttons. For a wrap toggle, keep the state in a component of your own and set data-wrap on the content to match.
$ 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)
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass, codeBlockActionsClass,
codeBlockContentClass, codeBlockCodeClass,
} from '#components/ui/code-block.ts';
import { DownloadIcon, TerminalIcon, WrapTextIcon } from '#lib/ui/lucide.ts';
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)`;
// The wrap toggle starts pressed, so the content carries data-wrap. A
// component that owns the toggle flips aria-pressed and data-wrap together.
export default function CodeBlockActions() {
return html`
<div class="w-full max-w-md">
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>
${TerminalIcon()}
Terminal
</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<button
type="button"
data-slot="button"
data-variant="ghost"
data-size="icon-xs"
aria-label="Wrap lines"
aria-pressed="true"
class=${cn(buttonClass({ variant: 'ghost', size: 'icon-xs' }), 'aria-pressed:text-foreground')}
>
${WrapTextIcon()}
</button>
<button
type="button"
data-slot="button"
data-variant="ghost"
data-size="icon-xs"
aria-label="Download"
class=${buttonClass({ variant: 'ghost', size: 'icon-xs' })}
>
${DownloadIcon()}
</button>
<ui-code-block-copy-button value=${output}></ui-code-block-copy-button>
</div>
</div>
<pre data-slot="code-block-content" data-wrap tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${output}</code></pre>
</div>
</div>
`;
}
View Code
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<button
type="button"
data-slot="button"
data-variant="ghost"
data-size="icon-xs"
aria-label="Wrap lines"
aria-pressed=${this.wrap}
class=${cn(buttonClass({ variant: 'ghost', size: 'icon-xs' }), 'aria-pressed:text-foreground')}
@click=${() => { this.wrap = !this.wrap; }}
>
${WrapTextIcon()}
</button>
<ui-code-block-copy-button value=${output}></ui-code-block-copy-button>
</div>
<pre data-slot="code-block-content" ?data-wrap=${this.wrap} tabindex="0" dir="ltr" class=${codeBlockContentClass()}><code
data-slot="code-block-code" class=${codeBlockCodeClass()}>${output}</code></pre>
Floating Actions
Without a header, put the actions directly inside the code block. 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
import { html } from '@webjsdev/core';
import {
codeBlockClass, codeBlockActionsClass, codeBlockContentClass, codeBlockCodeClass,
} from '#components/ui/code-block.ts';
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 html`
<div class="w-full max-w-md">
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<ui-code-block-copy-button value=${output}></ui-code-block-copy-button>
</div>
<pre data-slot="code-block-content" tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${output}</code></pre>
</div>
</div>
`;
}
View Code
Line Numbers
Add data-numbered to the content and render the text with codeBlockLines(), which splits it into lines. The numbers are not copied with a selection.
{ "name": "chat", "private": true, "scripts": { "dev": "next dev", "build": "next build" }}
import { html } from '@webjsdev/core';
import {
codeBlockClass, codeBlockContentClass, codeBlockCodeClass, codeBlockLines,
} from '#components/ui/code-block.ts';
const code = `{
"name": "chat",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build"
}
}`;
export default function CodeBlockLineNumbers() {
return html`
<div class="w-full max-w-md">
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<pre data-slot="code-block-content" data-numbered tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${codeBlockLines(code)}</code></pre>
</div>
</div>
`;
}
View Code
Start Line
Set counter-reset: line N on the content to number lines from N + 1, 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 { html } from '@webjsdev/core';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass,
codeBlockContentClass, codeBlockCodeClass, codeBlockLines,
} from '#components/ui/code-block.ts';
const code = ` if (!session) {
redirect("/login")
}
const projects = await db.project.findMany({
where: { ownerId: session.user.id },
orderBy: { updatedAt: "desc" },
})
return <ProjectList projects={projects} />
}`;
// The counter starts one below the first line: line 995 is counter-reset 994.
export default function CodeBlockStartLine() {
return html`
<div class="w-full max-w-md">
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>app/dashboard/page.tsx</div>
</div>
<pre data-slot="code-block-content" data-numbered tabindex="0" dir="ltr" style="counter-reset: line 994" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${codeBlockLines(code)}</code></pre>
</div>
</div>
`;
}
View Code
Wrap
Long lines scroll by default. Add data-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 { html } from '@webjsdev/core';
import {
codeBlockClass, codeBlockContentClass, codeBlockCodeClass,
} from '#components/ui/code-block.ts';
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 html`
<div class="flex w-full max-w-md flex-col gap-4">
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<pre data-slot="code-block-content" tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${output}</code></pre>
</div>
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<pre data-slot="code-block-content" data-wrap tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${output}</code></pre>
</div>
</div>
`;
}
View Code
Highlighted Lines
Pass variants to codeBlockLines(), mapping a line number (from 1) to 'highlighted' for the lines to call out.
export default { experimental: { reactCompiler: true, viewTransition: true, }, images: { remotePatterns: [{ hostname: "avatars.githubusercontent.com" }], },}
import { html } from '@webjsdev/core';
import {
codeBlockClass, codeBlockContentClass, codeBlockCodeClass, codeBlockLines,
} from '#components/ui/code-block.ts';
const code = `export default {
experimental: {
reactCompiler: true,
viewTransition: true,
},
images: {
remotePatterns: [{ hostname: "avatars.githubusercontent.com" }],
},
}`;
export default function CodeBlockHighlightedLines() {
return html`
<div class="w-full max-w-md">
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<pre data-slot="code-block-content" data-numbered tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${codeBlockLines(code, { variants: { 3: 'highlighted', 4: 'highlighted' } })}</code></pre>
</div>
</div>
`;
}
View Code
Diff
Map a line to 'added' or 'removed'. 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>}
import { html } from '@webjsdev/core';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass, codeBlockActionsClass,
codeBlockContentClass, codeBlockCodeClass, codeBlockLines, type CodeBlockLineVariant,
} from '#components/ui/code-block.ts';
const patch = ` export function Greeting({ name }: { name: string }) {
- return <p>Hello, {name}</p>
+ return <p className="text-sm text-muted-foreground">
+ Hello, {name}!
+ </p>
}`;
function getVariant(line: string): CodeBlockLineVariant {
if (line.startsWith('+')) {
return 'added';
}
if (line.startsWith('-')) {
return 'removed';
}
return 'default';
}
// The first character of each row is the diff marker. The line shows the
// rest, and the variant draws the marker.
const rows = patch.split('\n');
const variants = Object.fromEntries(rows.map((row, index) => [index + 1, getVariant(row)]));
const code = rows.map((row) => row.slice(1)).join('\n');
export default function CodeBlockDiff() {
return html`
<div class="w-full max-w-md">
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>components/greeting.tsx</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<ui-code-block-copy-button value=${patch}></ui-code-block-copy-button>
</div>
</div>
<pre data-slot="code-block-content" tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${codeBlockLines(code, { variants })}</code></pre>
</div>
</div>
`;
}
View Code
Height
Cap the height with a max-h-* class on the content. The content scrolls inside the block.
[01] GET /api/chat 200 in 12ms
[02] GET /api/chat 200 in 19ms
[03] GET /api/chat 200 in 26ms
[04] GET /api/chat 200 in 33ms
[05] GET /api/chat 200 in 40ms
[06] GET /api/chat 200 in 47ms
[07] GET /api/chat 200 in 14ms
[08] GET /api/chat 200 in 21ms
[09] GET /api/chat 200 in 28ms
[10] GET /api/chat 200 in 35ms
[11] GET /api/chat 200 in 42ms
[12] GET /api/chat 200 in 49ms
[13] GET /api/chat 200 in 16ms
[14] GET /api/chat 200 in 23ms
[15] GET /api/chat 200 in 30ms
[16] GET /api/chat 200 in 37ms
[17] GET /api/chat 200 in 44ms
[18] GET /api/chat 200 in 51ms
[19] GET /api/chat 200 in 18ms
[20] GET /api/chat 200 in 25ms
[21] GET /api/chat 200 in 32ms
[22] GET /api/chat 200 in 39ms
[23] GET /api/chat 200 in 46ms
[24] GET /api/chat 200 in 13ms
[25] GET /api/chat 200 in 20ms
[26] GET /api/chat 200 in 27ms
[27] GET /api/chat 200 in 34ms
[28] GET /api/chat 200 in 41ms
[29] GET /api/chat 200 in 48ms
[30] GET /api/chat 200 in 15ms
[31] GET /api/chat 200 in 22ms
[32] GET /api/chat 200 in 29ms
[33] GET /api/chat 200 in 36ms
[34] GET /api/chat 200 in 43ms
[35] GET /api/chat 200 in 50ms
[36] GET /api/chat 200 in 17ms
[37] GET /api/chat 200 in 24ms
[38] GET /api/chat 200 in 31ms
[39] GET /api/chat 200 in 38ms
[40] GET /api/chat 200 in 45ms
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass, codeBlockActionsClass,
codeBlockContentClass, codeBlockCodeClass,
} from '#components/ui/code-block.ts';
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 html`
<div class="w-full max-w-md">
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>Logs</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<ui-code-block-copy-button value=${logs}></ui-code-block-copy-button>
</div>
</div>
<pre data-slot="code-block-content" tabindex="0" dir="ltr" style="counter-reset: line 0" class=${cn(codeBlockContentClass(), 'max-h-48 scroll-fade-y')}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${logs}</code></pre>
</div>
</div>
`;
}
View Code
The content fades its edges with scroll-fade as it scrolls: left and right by default, top and bottom when it wraps. Add scroll-fade-y to a capped block that does not wrap.
Show More
The footer is a slot below the content. For Show More, cap the content while it is collapsed and put a native <details> in the footer, its <summary> styled as a ghost xs button. While it is open, group-has-[details[open]]/code-block variants lift the cap, so it works with no script.
"use client"
import * as React from "react"import { useChat } from "@ai-sdk/react"
import { Button } from "@/components/ui/button"import { Input } from "@/components/ui/input"
export function Chat() { const [input, setInput] = React.useState("") const { messages, sendMessage, status } = useChat()
return ( <div className="flex flex-col gap-4"> {messages.map((message) => ( <div key={message.id}> {message.parts.map((part, index) => part.type === "text" ? <p key={index}>{part.text}</p> : null )} </div> ))} <form onSubmit={(event) => { event.preventDefault() sendMessage({ text: input }) setInput("") }} > <Input value={input} onChange={(event) => setInput(event.target.value)} /> <Button disabled={status !== "ready"}>Send</Button> </form> </div> )}
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass, codeBlockActionsClass,
codeBlockContentClass, codeBlockCodeClass, codeBlockFooterClass, codeBlockLines,
} from '#components/ui/code-block.ts';
import { ChevronDownIcon } from '#lib/ui/lucide.ts';
const code = `"use client"
import * as React from "react"
import { useChat } from "@ai-sdk/react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
export function Chat() {
const [input, setInput] = React.useState("")
const { messages, sendMessage, status } = useChat()
return (
<div className="flex flex-col gap-4">
{messages.map((message) => (
<div key={message.id}>
{message.parts.map((part, index) =>
part.type === "text" ? <p key={index}>{part.text}</p> : null
)}
</div>
))}
<form
onSubmit={(event) => {
event.preventDefault()
sendMessage({ text: input })
setInput("")
}}
>
<Input value={input} onChange={(event) => setInput(event.target.value)} />
<Button disabled={status !== "ready"}>Send</Button>
</form>
</div>
)
}`;
// The toggle is a native <details> in the footer, so it works with no
// script and announces its own expanded state. While it is open, the
// group-has variants lift the cap on the content.
export default function CodeBlockShowMore() {
return html`
<div class="w-full max-w-md">
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>components/chat.tsx</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<ui-code-block-copy-button value=${code}></ui-code-block-copy-button>
</div>
</div>
<pre
id="code-block-show-more"
data-slot="code-block-content"
data-numbered
tabindex="0"
dir="ltr"
style="counter-reset: line 0"
class=${cn(codeBlockContentClass(), 'max-h-64 scroll-fade-y overflow-y-hidden group-has-[details[open]]/code-block:max-h-none group-has-[details[open]]/code-block:overflow-y-auto')}
><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${codeBlockLines(code)}</code></pre>
<div data-slot="code-block-footer" class=${cn(codeBlockFooterClass(), 'justify-center')}>
<details class="group/show-more">
<summary
aria-controls="code-block-show-more"
data-slot="button"
data-variant="ghost"
data-size="xs"
class=${cn(buttonClass({ variant: 'ghost', size: 'xs' }), 'list-none [&::-webkit-details-marker]:hidden')}
>
${ChevronDownIcon('transition-transform group-open/show-more:rotate-180')}
<span class="group-open/show-more:hidden">Show more</span>
<span class="hidden group-open/show-more:inline">Show less</span>
</summary>
</details>
</div>
</div>
</div>
`;
}
View Code
<pre
id="chat-source"
data-slot="code-block-content"
tabindex="0"
dir="ltr"
class=${cn(codeBlockContentClass(), 'max-h-64 scroll-fade-y overflow-y-hidden group-has-[details[open]]/code-block:max-h-none group-has-[details[open]]/code-block:overflow-y-auto')}
><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${code}</code></pre>
<div data-slot="code-block-footer" class=${cn(codeBlockFooterClass(), 'justify-center')}>
<details class="group/show-more">
<summary
aria-controls="chat-source"
class=${cn(buttonClass({ variant: 'ghost', size: 'xs' }), 'list-none [&::-webkit-details-marker]:hidden')}
>
<span class="group-open/show-more:hidden">Show more</span>
<span class="hidden group-open/show-more:inline">Show less</span>
</summary>
</details>
</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 * as React from "react"import { useChat } from "@ai-sdk/react"
import { Button } from "@/components/ui/button"import { Input } from "@/components/ui/input"
export function Chat() { const [input, setInput] = React.useState("") const { messages, sendMessage, status } = useChat()
return ( <div className="flex flex-col gap-4"> {messages.map((message) => ( <div key={message.id}> {message.parts.map((part, index) => part.type === "text" ? <p key={index}>{part.text}</p> : null )} </div> ))} <form onSubmit={(event) => { event.preventDefault() sendMessage({ text: input }) setInput("") }} > <Input value={input} onChange={(event) => setInput(event.target.value)} /> <Button disabled={status !== "ready"}>Send</Button> </form> </div> )}
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass, codeBlockActionsClass,
codeBlockContentClass, codeBlockCodeClass, codeBlockFooterClass, codeBlockLines,
} from '#components/ui/code-block.ts';
import { ChevronDownIcon } from '#lib/ui/lucide.ts';
const code = `"use client"
import * as React from "react"
import { useChat } from "@ai-sdk/react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
export function Chat() {
const [input, setInput] = React.useState("")
const { messages, sendMessage, status } = useChat()
return (
<div className="flex flex-col gap-4">
{messages.map((message) => (
<div key={message.id}>
{message.parts.map((part, index) =>
part.type === "text" ? <p key={index}>{part.text}</p> : null
)}
</div>
))}
<form
onSubmit={(event) => {
event.preventDefault()
sendMessage({ text: input })
setInput("")
}}
>
<Input value={input} onChange={(event) => setInput(event.target.value)} />
<Button disabled={status !== "ready"}>Send</Button>
</form>
</div>
)
}`;
// Open, the cap rises from max-h-64 to max-h-96 and the content scrolls
// inside it, so a long file never takes over the page.
export default function CodeBlockShowMoreScroll() {
return html`
<div class="w-full max-w-md">
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>components/chat.tsx</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<ui-code-block-copy-button value=${code}></ui-code-block-copy-button>
</div>
</div>
<pre
id="code-block-show-more-scroll"
data-slot="code-block-content"
data-numbered
tabindex="0"
dir="ltr"
style="counter-reset: line 0"
class=${cn(codeBlockContentClass(), 'max-h-64 scroll-fade-y overflow-y-hidden group-has-[details[open]]/code-block:max-h-96 group-has-[details[open]]/code-block:overflow-y-auto')}
><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${codeBlockLines(code)}</code></pre>
<div data-slot="code-block-footer" class=${cn(codeBlockFooterClass(), 'justify-center')}>
<details class="group/show-more">
<summary
aria-controls="code-block-show-more-scroll"
data-slot="button"
data-variant="ghost"
data-size="xs"
class=${cn(buttonClass({ variant: 'ghost', size: 'xs' }), 'list-none [&::-webkit-details-marker]:hidden')}
>
${ChevronDownIcon('transition-transform group-open/show-more:rotate-180')}
<span class="group-open/show-more:hidden">Show more</span>
<span class="hidden group-open/show-more:inline">Show less</span>
</summary>
</details>
</div>
</div>
</div>
`;
}
View Code
Size
Use data-size="sm" on the code block 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
import { html } from '@webjsdev/core';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass, codeBlockActionsClass,
codeBlockContentClass, codeBlockCodeClass,
} from '#components/ui/code-block.ts';
import { TerminalIcon } from '#lib/ui/lucide.ts';
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 html`
<div class="flex w-full max-w-md flex-col gap-4">
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>
${TerminalIcon()}
Terminal
</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<ui-code-block-copy-button value=${output}></ui-code-block-copy-button>
</div>
</div>
<pre data-slot="code-block-content" data-wrap tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${output}</code></pre>
</div>
<div data-slot="code-block" data-variant="default" data-size="sm" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>
${TerminalIcon()}
Terminal
</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<ui-code-block-copy-button value=${output}></ui-code-block-copy-button>
</div>
</div>
<pre data-slot="code-block-content" data-wrap tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${output}</code></pre>
</div>
</div>
`;
}
View Code
Destructive
Use codeBlockClass({ variant: 'destructive' }) with data-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 { html } from '@webjsdev/core';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass, codeBlockActionsClass,
codeBlockContentClass, codeBlockCodeClass,
} from '#components/ui/code-block.ts';
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 html`
<div class="w-full max-w-md">
<div data-slot="code-block" data-variant="destructive" data-size="default" class=${codeBlockClass({ variant: 'destructive' })}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>Error</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<ui-code-block-copy-button value=${error}></ui-code-block-copy-button>
</div>
</div>
<pre data-slot="code-block-content" data-wrap tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${error}</code></pre>
</div>
</div>
`;
}
View Code
Trace
Put a code block with data-size="sm" in a trace step's collapsible content for tool and terminal output. Add data-wrap and a max-h-64 class to the content so long output wraps and scrolls inside the trace. The block sets its own text color, so the trace content 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)
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import {
codeBlockClass, codeBlockContentClass, codeBlockCodeClass,
} from '#components/ui/code-block.ts';
import {
traceClass, traceLineClass, traceIconClass, traceTitleClass,
traceCollapsibleClass, traceCollapsibleTriggerClass, traceCollapsibleContentClass,
} from '#components/ui/trace.ts';
import { ChevronRightIcon, TerminalIcon } from '#lib/ui/lucide.ts';
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)`;
// TraceCollapsible is a native <details>, open by default here. The chevron
// after the line turns while it is open.
export default function CodeBlockTrace() {
return html`
<div class="w-full max-w-md">
<div data-slot="trace" class=${traceClass()}>
<details data-slot="trace-collapsible" open class=${cn(traceCollapsibleClass(), 'group/trace-collapsible')}>
<summary data-slot="trace-collapsible-trigger" class=${traceCollapsibleTriggerClass()}>
<span data-slot="trace-line" class=${traceLineClass()}>
<span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>${TerminalIcon()}</span>
<span data-slot="trace-title" class=${traceTitleClass()}>Ran node --version</span>
</span>
<span data-slot="trace-icon" aria-hidden="true" class=${cn(traceIconClass(), 'transition-transform group-open/trace-collapsible:rotate-90')}>${ChevronRightIcon()}</span>
</summary>
<div data-slot="trace-collapsible-content" class=${traceCollapsibleContentClass()}>
<div data-slot="code-block" data-variant="default" data-size="sm" class=${codeBlockClass()}>
<pre data-slot="code-block-content" data-wrap tabindex="0" dir="ltr" style="counter-reset: line 0" class=${cn(codeBlockContentClass(), 'max-h-64')}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${output}</code></pre>
</div>
</div>
</details>
<details data-slot="trace-collapsible" open class=${cn(traceCollapsibleClass(), 'group/trace-collapsible')}>
<summary data-slot="trace-collapsible-trigger" class=${traceCollapsibleTriggerClass()}>
<span data-slot="trace-line" data-status="error" class=${traceLineClass()}>
<span data-slot="trace-icon" aria-hidden="true" class=${traceIconClass()}>${TerminalIcon()}</span>
<span data-slot="trace-title" class=${traceTitleClass()}>Failed to run pnpm dev</span>
</span>
<span data-slot="trace-icon" aria-hidden="true" class=${cn(traceIconClass(), 'transition-transform group-open/trace-collapsible:rotate-90')}>${ChevronRightIcon()}</span>
</summary>
<div data-slot="trace-collapsible-content" class=${traceCollapsibleContentClass()}>
<div data-slot="code-block" data-variant="destructive" data-size="sm" class=${codeBlockClass({ variant: 'destructive' })}>
<pre data-slot="code-block-content" data-wrap tabindex="0" dir="ltr" style="counter-reset: line 0" class=${cn(codeBlockContentClass(), 'max-h-64')}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${error}</code></pre>
</div>
</div>
</details>
</div>
</div>
`;
}
View Code
Tabs
Show several files with Tabs, one code block in each <ui-tabs-content>.
import { streamText } from "ai"
export async function POST(request: Request) { const { messages } = await request.json() const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages })
return result.toUIMessageStreamResponse()}
"use client"
import { useChat } from "@ai-sdk/react"
export function Chat() { const { messages } = useChat()
return <MessageList messages={messages} />}
AI_GATEWAY_API_KEY=your-api-key
import { html } from '@webjsdev/core';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass, codeBlockActionsClass,
codeBlockContentClass, codeBlockCodeClass, codeBlockLines,
} from '#components/ui/code-block.ts';
const files = [
{
id: 'route',
title: 'app/api/chat/route.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',
code: `"use client"
import { useChat } from "@ai-sdk/react"
export function Chat() {
const { messages } = useChat()
return <MessageList messages={messages} />
}`,
},
{
id: 'env',
title: '.env.local',
code: 'AI_GATEWAY_API_KEY=your-api-key',
},
];
export default function CodeBlockTabs() {
return html`
<ui-tabs value="route" class="w-full max-w-md">
<ui-tabs-list>
${files.map((file) => html`
<ui-tabs-trigger value=${file.id}>${file.title.split('/').at(-1)}</ui-tabs-trigger>
`)}
</ui-tabs-list>
${files.map((file) => html`
<ui-tabs-content value=${file.id}>
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>${file.title}</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<ui-code-block-copy-button value=${file.code}></ui-code-block-copy-button>
</div>
</div>
<pre data-slot="code-block-content" data-numbered tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${codeBlockLines(file.code)}</code></pre>
</div>
</ui-tabs-content>
`)}
</ui-tabs>
`;
}
View Code
Message
Put a code block between paragraphs inside a Message.
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { bubbleClass, bubbleContentClass } from '#components/ui/bubble.ts';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass, codeBlockActionsClass,
codeBlockContentClass, codeBlockCodeClass, codeBlockLines,
} from '#components/ui/code-block.ts';
import { messageClass, messageContentClass } from '#components/ui/message.ts';
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() {
return html`
<div class="flex w-full max-w-md flex-col gap-4 text-sm">
<div data-slot="message" data-align="end" class=${messageClass()}>
<div data-slot="message-content" class=${messageContentClass()}>
<div data-slot="bubble" data-variant="muted" class=${bubbleClass({ variant: 'muted' })}>
<div data-slot="bubble-content" class=${bubbleContentClass()}>How do I stream a response?</div>
</div>
</div>
</div>
<div data-slot="message" data-align="start" class=${messageClass()}>
<div data-slot="message-content" class=${cn(messageContentClass(), 'gap-3')}>
<p>Create a route handler that returns the stream:</p>
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>app/api/chat/route.ts</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<ui-code-block-copy-button value=${code}></ui-code-block-copy-button>
</div>
</div>
<pre data-slot="code-block-content" tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${codeBlockLines(code)}</code></pre>
</div>
<p>The client reads it with useChat.</p>
</div>
</div>
</div>
`;
}
View Code
Typeset
A code block inside a typeset container keeps its own styles and gets the same space above as a paragraph.
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.
import { html } from '@webjsdev/core';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass, codeBlockActionsClass,
codeBlockContentClass, codeBlockCodeClass, codeBlockLines,
} from '#components/ui/code-block.ts';
import { FileCodeIcon } from '#lib/ui/lucide.ts';
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() {
return html`
<div class="typeset w-full max-w-md">
<h3>Stream a response</h3>
<p>
Create a route handler that calls <code>streamText</code> and returns
the stream to the client.
</p>
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>
${FileCodeIcon()}
app/api/chat/route.ts
</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<ui-code-block-copy-button value=${code}></ui-code-block-copy-button>
</div>
</div>
<pre data-slot="code-block-content" data-numbered tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${codeBlockLines(code)}</code></pre>
</div>
<p>
The <code>useChat</code> hook reads the stream on the client and renders
the answer while it is written.
</p>
</div>
`;
}
View Code
RTL
To enable RTL support, see the RTL configuration guide. Code always reads left to right. The header follows the page direction.
ثبّت الحزم، ثم شغّل خادم التطوير.
pnpm add ai @ai-sdk/react zodpnpm dev
import { html } from '@webjsdev/core';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass, codeBlockActionsClass,
codeBlockContentClass, codeBlockCodeClass, codeBlockLines,
} from '#components/ui/code-block.ts';
import { TerminalIcon } from '#lib/ui/lucide.ts';
const translations = {
en: {
dir: 'ltr',
values: {
description: 'Install the packages, then start the dev server.',
title: 'Terminal',
},
},
ar: {
dir: 'rtl',
values: {
description: 'ثبّت الحزم، ثم شغّل خادم التطوير.',
title: 'الطرفية',
},
},
he: {
dir: 'rtl',
values: {
description: 'התקן את החבילות, ואז הפעל את שרת הפיתוח.',
title: 'מסוף',
},
},
};
const code = `pnpm add ai @ai-sdk/react zod
pnpm dev`;
// The header follows dir="rtl". The content keeps dir="ltr", so the code
// still reads left to right.
export default function CodeBlockRtl() {
const lang = 'ar';
const { dir, values: t } = translations[lang];
return html`
<div class="flex w-full max-w-md flex-col gap-3 text-sm" dir=${dir} lang=${lang}>
<p>${t.description}</p>
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>
${TerminalIcon()}
${t.title}
</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<ui-code-block-copy-button value=${code}></ui-code-block-copy-button>
</div>
</div>
<pre data-slot="code-block-content" data-numbered tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${codeBlockLines(code)}</code></pre>
</div>
</div>
`;
}
View Code
Syntax Highlighting
codeBlockLines() renders plain text, so a block that only shows plain output stays small and no grammar reaches the browser. To highlight, run the highlighter of your choice and put its token spans inside each line, built with codeBlockLineClass().
{ "location": "San Francisco", "temperature": 18, "unit": "celsius", "conditions": ["fog", "wind"]}
import { html } from '@webjsdev/core';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass,
codeBlockContentClass, codeBlockCodeClass, codeBlockLines,
} from '#components/ui/code-block.ts';
const code = `{
"location": "San Francisco",
"temperature": 18,
"unit": "celsius",
"conditions": ["fog", "wind"]
}`;
// The kit ships no highlighter, so these lines are plain text. To colour
// them, put your highlighter's token spans inside each line span.
export default function CodeBlockHighlighting() {
return html`
<div class="w-full max-w-md">
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>getWeather output</div>
</div>
<pre data-slot="code-block-content" tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${codeBlockLines(code)}</code></pre>
</div>
</div>
`;
}
View Code
// tokens: one array of { text, className } per line, from your highlighter.
<pre data-slot="code-block-content" tabindex="0" dir="ltr" class=${codeBlockContentClass()}><code
data-slot="code-block-code" class=${codeBlockCodeClass()}>${tokens.map((line) => html`<span
data-slot="code-block-line" data-variant="default" class=${codeBlockLineClass()}><span
data-slot="code-block-line-content" class="min-w-0">${line.map((t) => html`<span class=${t.className}>${t.text}</span>`)}</span></span>`)}</code></pre>
The preview shows the plain lines the kit renders.
Languages
The kit loads no languages. Every block renders the text it is given, whatever its language, so the language list lives in the highlighter you bring.
@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 { html } from '@webjsdev/core';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass,
codeBlockContentClass, codeBlockCodeClass, codeBlockLines,
} from '#components/ui/code-block.ts';
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.',
},
];
export default function CodeBlockLanguages() {
return html`
<div class="flex w-full max-w-md flex-col gap-4">
${samples.map((sample) => html`
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>${sample.title}</div>
</div>
<pre data-slot="code-block-content" tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${codeBlockLines(sample.code)}</code></pre>
</div>
`)}
</div>
`;
}
View Code
Terminal Output
The kit does not read ANSI escape codes, so without a converter they show as text. The preview reads the few codes its output uses into colored spans inside each line, which is all a line needs.
$ 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)
import { html, type TemplateResult } from '@webjsdev/core';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass, codeBlockActionsClass,
codeBlockContentClass, codeBlockCodeClass, codeBlockLineClass,
} from '#components/ui/code-block.ts';
import { TerminalIcon } from '#lib/ui/lucide.ts';
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)`;
const ESCAPES = /\x1b\[([\d;]*)m/g;
const COLORS: Record<string, string> = {
31: 'text-red-600 dark:text-red-400',
32: 'text-green-600 dark:text-green-400',
};
// The kit does not parse ANSI. This reads the few SGR codes the output uses
// (a colour, its reset, dim and its reset) into spans inside one line. Like
// shadcn's, the colours do not carry from one line to the next.
function ansiLine(line: string) {
const parts: TemplateResult[] = [];
let color = '';
let dim = false;
let last = 0;
for (const match of line.matchAll(ESCAPES)) {
const text = line.slice(last, match.index);
if (text) parts.push(html`<span class=${[color, dim ? 'opacity-60' : ''].join(' ').trim() || null}>${text}</span>`);
for (const code of match[1].split(';')) {
if (code === '0' || code === '') { color = ''; dim = false; }
else if (code === '2') dim = true;
else if (code === '22') dim = false;
else if (code === '39') color = '';
else if (COLORS[code]) color = COLORS[code];
}
last = (match.index ?? 0) + match[0].length;
}
const rest = line.slice(last);
if (rest) parts.push(html`<span class=${[color, dim ? 'opacity-60' : ''].join(' ').trim() || null}>${rest}</span>`);
return html`<span data-slot="code-block-line" data-variant="default" class=${codeBlockLineClass()}><span data-slot="code-block-line-content" class="min-w-0">${parts.length ? parts : '\n'}</span></span>`;
}
export default function CodeBlockAnsi() {
return html`
<div class="w-full max-w-md">
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>
${TerminalIcon()}
Terminal
</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<ui-code-block-copy-button value=${output.replace(ESCAPES, '')}></ui-code-block-copy-button>
</div>
</div>
<pre data-slot="code-block-content" data-wrap tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${output.split('\n').map(ansiLine)}</code></pre>
</div>
</div>
`;
}
View Code
ANSI colors do not carry from one line to the next.
Server Rendering
Highlight in a 'use server' module and call it from the page, so the highlighter never reaches the browser and the page receives the finished tokens.
import { html } from '@webjsdev/core';
import { highlightCode } from '#modules/docs/queries/highlight-code.server.ts';
export default async function Page() {
// A 'use server' function that runs your highlighter on the server.
const tokens = await highlightCode(code, 'tsx');
return html`
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<pre data-slot="code-block-content" data-numbered tabindex="0" dir="ltr" class=${codeBlockContentClass()}><code
data-slot="code-block-code" class=${codeBlockCodeClass()}>${tokens.map(renderLine)}</code></pre>
</div>
`;
}
Streaming
A block renders the text it is given, so a component that holds the streaming text in a signal re-renders its lines as the text grows. The preview shows the settled result.
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 @webjsdev/ui add code-block
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} />}
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
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass, codeBlockActionsClass,
codeBlockContentClass, codeBlockCodeClass, codeBlockLines, type CodeBlockLineVariant,
} from '#components/ui/code-block.ts';
import { RotateCcwIcon } from '#lib/ui/lucide.ts';
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 @webjsdev/ui 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',
},
];
function StreamingBlock(block: (typeof blocks)[number]) {
const rows = block.code.split('\n');
// A diff row starts with +, - or a space. The marker is not part of the code.
const source = block.diff ? rows.map((row) => row.slice(1)).join('\n') : block.code;
const variants: Record<number, CodeBlockLineVariant> = {};
rows.forEach((row, index) => {
if (block.diff) {
variants[index + 1] = row.startsWith('+') ? 'added' : row.startsWith('-') ? 'removed' : 'default';
} else if (block.highlight?.includes(index)) {
variants[index + 1] = 'highlighted';
}
});
return html`
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
${block.title ? html`
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>${block.title}</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<ui-code-block-copy-button value=${source}></ui-code-block-copy-button>
</div>
</div>
` : ''}
<pre data-slot="code-block-content" ?data-numbered=${!!block.lineNumbers} tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${codeBlockLines(source, { variants })}</code></pre>
</div>
`;
}
// The settled state, with every block written out. A component streaming
// text in holds it in a signal and renders these same lines as it grows.
export default function CodeBlockStreaming() {
return html`
<div class="flex w-full max-w-md flex-col gap-4">
${blocks.map(StreamingBlock)}
<button type="button" data-slot="button" data-variant="outline" data-size="sm" class=${cn(buttonClass({ variant: 'outline', size: 'sm' }), 'self-start')}>
${RotateCcwIcon()}
Replay
</button>
</div>
`;
}
View Code
Markdown
The kit does not parse Markdown. Render the message with the Markdown renderer of your choice and route each fenced code block to a code block titled by its language. Inline code stays an inline <code>.
import { html } from '@webjsdev/core';
import { cn } from '#lib/utils/cn.ts';
import { bubbleClass, bubbleContentClass } from '#components/ui/bubble.ts';
import { buttonClass } from '#components/ui/button.ts';
import {
codeBlockClass, codeBlockHeaderClass, codeBlockTitleClass, codeBlockActionsClass,
codeBlockContentClass, codeBlockCodeClass, codeBlockLines,
} from '#components/ui/code-block.ts';
import { messageClass, messageContentClass } from '#components/ui/message.ts';
const question = 'How do I debounce a search input in React?';
const 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
}`;
const inlineCode = 'rounded-sm bg-muted px-1 py-0.5 font-mono text-[0.9em]';
// The settled answer. The kit does not parse Markdown: the paragraphs and the
// fenced code are written out here the way a Markdown renderer would emit
// them, with the fence rendered as a code block titled by its language.
function MarkdownCodeBlock(source: string, language: string) {
return html`
<div data-slot="code-block" data-variant="default" data-size="default" class=${codeBlockClass()}>
<div data-slot="code-block-header" class=${codeBlockHeaderClass()}>
<div data-slot="code-block-title" class=${codeBlockTitleClass()}>${language || 'text'}</div>
<div data-slot="code-block-actions" class=${codeBlockActionsClass()}>
<ui-code-block-copy-button value=${source}></ui-code-block-copy-button>
</div>
</div>
<pre data-slot="code-block-content" tabindex="0" dir="ltr" style="counter-reset: line 0" class=${codeBlockContentClass()}><code data-slot="code-block-code" class=${codeBlockCodeClass()}>${codeBlockLines(source)}</code></pre>
</div>
`;
}
export default function CodeBlockMarkdown() {
return html`
<div class="flex min-h-112 w-full max-w-md flex-col gap-4 py-6 text-sm">
<div data-slot="message" data-align="end" class=${messageClass()}>
<div data-slot="message-content" class=${messageContentClass()}>
<div data-slot="bubble" data-variant="muted" data-align="end" class=${bubbleClass({ variant: 'muted' })}>
<div data-slot="bubble-content" class=${bubbleContentClass()}>${question}</div>
</div>
</div>
</div>
<div data-slot="message" data-align="start" class=${messageClass()}>
<div data-slot="message-content" class=${messageContentClass()}>
<div class="space-y-4">
<p>
Wrap the value in a <code class=${inlineCode}>useDebounce</code> hook. It returns the latest value once it stops changing for <code class=${inlineCode}>delay</code> milliseconds.
</p>
${MarkdownCodeBlock(code, 'tsx')}
<p>Pass the debounced value to your fetch instead of the raw input.</p>
</div>
</div>
</div>
<button type="button" data-slot="button" data-variant="outline" data-size="sm" class=${cn(buttonClass({ variant: 'outline', size: 'sm' }), 'mt-auto self-start')}>
Replay
</button>
</div>
`;
}
View Code
While a fence is still streaming, leave the copy button out, and add it once the closing fence arrives.
Accessibility
- The content is a
<pre>with a<code>element. Keepdir="ltr"on it, so code reads left to right on an RTL page. - The content has
tabindex="0", so keyboard users can focus it and scroll it. Settabindex="-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. <ui-code-block-copy-button>is labelled "Copy", and a polite live region announces "Copied" after a successful copy.- Give a wrap toggle
aria-pressedso its state is announced. - A Show More
<details>announces its own expanded state. Pointaria-controlson its<summary>at theidof the content.
API Reference
codeBlockClass
The surface that holds the header, the content and the footer. Put it on a <div data-slot="code-block"> with data-variant and data-size to match. codeBlockVariants() is an alias of codeBlockClass() that also merges a className.
codeBlockHeaderClass
A row above the content for a title and actions, on a <div data-slot="code-block-header">. It takes no options.
codeBlockTitleClass
A filename or a label, with an optional icon, on a <div data-slot="code-block-title">. It truncates. It takes no options.
codeBlockActionsClass
Holds buttons at the end of the header, on a <div data-slot="code-block-actions">. As a direct child of the code block, it floats. It takes no options.
ui-code-block-copy-button
A ghost icon button that copies its value to the clipboard, or the code in its block when it has no value.
After a successful copy it fires ui-copy, which bubbles, with { detail: { text } }.
codeBlockContentClass
The <pre data-slot="code-block-content"> that scrolls or wraps. It holds a <code data-slot="code-block-code"> with codeBlockCodeClass(). Its behaviour is set with attributes.
codeBlockLines
codeBlockLines(text, { variants }) returns one line span per line of text, keeping an empty line as a newline. codeBlockLineClass({ variant }) styles a line span of your own. codeBlockLineVariants() is an alias of codeBlockLineClass() that also merges a className.
codeBlockFooterClass
A row below the content, such as for a Show More button, on a <div data-slot="code-block-footer">. It takes no options.
useHighlightedCode
See Syntax Highlighting for how token spans from a highlighter of your own go into the lines.