- Accordion
- Attachment
- Avatar
- Badge
- Breadcrumb
- Button
- Button Group
- Card
- Checkbox
- Code Block
- Collapsible
- Dialog
- Dropdown Menu
- Empty
- Field
- Hover Card
- Input
- Input Group
- Input OTP
- Item
- Label
- Marker
- Message
- Number Flow
- Pagination
- Popover
- Progress
- Radio Group
- Select
- Slider
- Sonner
- Spinner
- Switch
- Tooltip
- Separator
- Sheet
- Tabs
- Textarea
- Toggle
- Toggle Group
- Trace
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()}"use client";
import type { VariantProps } from "class-variance-authority";
import { cva } from "class-variance-authority";
import {
CheckIcon,
CopyIcon,
FileCode2Icon,
FileJsonIcon,
FileTextIcon,
TerminalIcon,
} from "lucide-react";
import * as React from "react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
const codeBlockVariants = cva(
"group/code-block has-[>[data-slot=code-block-content]:focus-visible]:ring-ring/30 relative flex w-full min-w-0 flex-col overflow-hidden rounded-2xl text-sm has-[>[data-slot=code-block-content]:focus-visible]:ring-3 data-[size=sm]:rounded-xl data-[size=sm]:text-xs",
{
defaultVariants: {
variant: "default",
},
variants: {
variant: {
default:
"bg-muted text-foreground ring-foreground/5 dark:ring-foreground/10 ring-1",
destructive:
"bg-destructive/5 text-destructive ring-destructive/15 dark:bg-destructive/10 dark:ring-destructive/20 ring-1",
},
},
}
);
function CodeBlock({
className,
variant = "default",
size = "default",
...props
}: React.ComponentProps<"div"> &
VariantProps<typeof codeBlockVariants> & { size?: "default" | "sm" }) {
return (
<div
className={cn(codeBlockVariants({ variant }), className)}
data-size={size}
data-slot="code-block"
data-variant={variant}
{...props}
/>
);
}
function CodeBlockHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"text-muted-foreground group-data-[variant=destructive]/code-block:text-destructive flex min-w-0 shrink-0 items-center gap-2 px-4 pt-4 group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:pt-3 *:has-[>[data-slot=code-block-title]]:min-w-0",
className
)}
data-slot="code-block-header"
{...props}
/>
);
}
const iconMap: Record<string, typeof FileCode2Icon> = {
bash: TerminalIcon,
cjs: FileCode2Icon,
css: FileCode2Icon,
fish: TerminalIcon,
go: FileCode2Icon,
html: FileCode2Icon,
js: FileCode2Icon,
json: FileJsonIcon,
jsonc: FileJsonIcon,
jsx: FileCode2Icon,
less: FileCode2Icon,
md: FileTextIcon,
mdx: FileTextIcon,
mjs: FileCode2Icon,
php: FileCode2Icon,
py: FileCode2Icon,
rb: FileCode2Icon,
rs: FileCode2Icon,
sass: FileCode2Icon,
scss: FileCode2Icon,
sh: TerminalIcon,
toml: FileCode2Icon,
ts: FileCode2Icon,
tsx: FileCode2Icon,
yaml: FileCode2Icon,
yml: FileCode2Icon,
zsh: TerminalIcon,
};
function pickIcon(children: React.ReactNode): typeof FileCode2Icon | null {
if (typeof children !== "string") {
return null;
}
const trimmed = children.trim();
const last = trimmed.split(/\s+/u).pop() ?? "";
const dot = last.lastIndexOf(".");
if (dot < 0 || dot === last.length - 1) {
return FileCode2Icon;
}
const ext = last.slice(dot + 1).toLowerCase();
return iconMap[ext] ?? FileCode2Icon;
}
function CodeBlockTitle({
children,
className,
icon,
...props
}: React.ComponentProps<"div"> & { icon?: typeof FileCode2Icon | null }) {
const Icon = icon === undefined ? pickIcon(children) : icon;
return (
<div
className={cn(
"text-foreground group-data-[variant=destructive]/code-block:text-destructive inline-flex min-w-0 items-center gap-1.5 truncate font-sans text-sm font-medium group-data-[size=sm]/code-block:text-xs [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 group-data-[size=sm]/code-block:[&_svg:not([class*='size-'])]:size-3.5",
className
)}
data-slot="code-block-title"
{...props}
>
{Icon ? <Icon /> : null}
<span className="min-w-0 truncate">{children}</span>
</div>
);
}
function CodeBlockActions({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
className={cn(
"*:data-[slot=button]:hover:bg-foreground/5 dark:*:data-[slot=button]:hover:bg-foreground/10 [[data-slot=code-block]>&]:*:[button]:bg-background [[data-slot=code-block]>&]:*:[button]:ring-foreground/10 -my-1 ms-auto -me-1.5 flex shrink-0 items-center gap-1 [[data-slot=code-block]>&]:absolute [[data-slot=code-block]>&]:end-3 [[data-slot=code-block]>&]:top-3 [[data-slot=code-block]>&]:z-10 [[data-slot=code-block]>&]:m-0 [[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 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:end-2 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:top-2 [[data-slot=code-block]>&]:pointer-coarse:opacity-100 [[data-slot=code-block]>&]:*:[button]:ring-1",
className
)}
data-slot="code-block-actions"
{...props}
/>
);
}
function CodeBlockCopyButton({
value,
variant = "ghost",
size = "icon-xs",
className,
onClick,
...props
}: React.ComponentProps<typeof Button> & { value: string }) {
const [copied, setCopied] = React.useState(false);
React.useEffect(() => {
if (!copied) {
return;
}
const timeout = setTimeout(() => setCopied(false), 2000);
return () => clearTimeout(timeout);
}, [copied]);
return (
<>
<Button
aria-label={copied ? "Copied" : "Copy"}
className={cn(
"hover:bg-foreground/5 dark:hover:bg-foreground/10",
className
)}
data-copied={copied || undefined}
data-slot="code-block-copy-button"
onClick={(event: React.MouseEvent<HTMLButtonElement>) => {
onClick?.(event);
navigator.clipboard
.writeText(value)
.then(() => setCopied(true))
.catch(() => {});
}}
size={size}
variant={variant}
{...props}
>
{copied ? <CheckIcon /> : <CopyIcon />}
</Button>
<span aria-live="polite" className="sr-only">
{copied ? "Copied" : ""}
</span>
</>
);
}
function CodeBlockContent({
className,
children,
style,
wrap = false,
lineNumbers = false,
startLine = 1,
...props
}: React.ComponentProps<"pre"> & {
wrap?: boolean;
lineNumbers?: boolean;
startLine?: number;
}) {
return (
<pre
className={cn(
"scroll-fade-x data-wrap:scroll-fade-y min-h-0 min-w-0 scrollbar-thin overflow-auto px-4 py-4 text-start font-mono text-sm leading-relaxed outline-none 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-3 group-data-[size=sm]/code-block:py-3 group-data-[size=sm]/code-block:group-has-data-[slot=code-block-header]/code-block:pt-1.5 data-wrap:wrap-break-word data-wrap:whitespace-pre-wrap",
className
)}
data-numbered={lineNumbers || undefined}
data-slot="code-block-content"
data-wrap={wrap || undefined}
dir="ltr"
style={{ counterReset: `line ${startLine - 1}`, ...style }}
{...props}
>
<code
className="grid min-h-lh min-w-max content-start in-data-numbered:grid-cols-[auto_1fr] in-data-wrap:min-w-0"
data-slot="code-block-code"
>
{lineNumbers && typeof children === "string"
? children
.replace(/\n$/u, "")
.split("\n")
.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))
: children}
</code>
</pre>
);
}
const codeBlockLineVariants = cva(
"before:text-muted-foreground after:text-muted-foreground relative -mx-4 block min-h-lh px-4 group-data-[size=sm]/code-block:-mx-3 group-data-[size=sm]/code-block:px-3 before:min-w-6 before:text-end after:absolute after:start-1 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:gap-x-3 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)_/_'']",
{
defaultVariants: {
variant: "default",
},
variants: {
variant: {
added: "bg-foreground/5 after:content-['+']",
default: "",
highlighted: "bg-foreground/5",
removed: "bg-destructive/10 after:text-destructive after:content-['−']",
},
},
}
);
function CodeBlockLine({
className,
variant = "default",
children,
...props
}: React.ComponentProps<"span"> & VariantProps<typeof codeBlockLineVariants>) {
const empty =
children === undefined ||
children === null ||
children === "" ||
(Array.isArray(children) && children.length === 0);
return (
<span
className={cn(codeBlockLineVariants({ variant }), className)}
data-slot="code-block-line"
data-variant={variant}
{...props}
>
<span className="min-w-0" data-slot="code-block-line-content">
{empty ? "\n" : children}
</span>
</span>
);
}
function CodeBlockFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"text-muted-foreground flex min-w-0 shrink-0 items-center gap-2 px-4 pb-4 group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:pb-3",
className
)}
data-slot="code-block-footer"
{...props}
/>
);
}
export {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockFooter,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
};Code Block renders a monospaced code surface with optional header, copy button, line numbers, and per-line variants for diffs.
Installation
$ bunx --bun frakment add code-block$ npx frakment add code-block$ pnpm dlx frakment add code-block$ yarn dlx frakment add code-block
Install the following dependencies:
$ bun add class-variance-authority lucide-react$ npm install class-variance-authority lucide-react$ pnpm add class-variance-authority lucide-react$ yarn add class-variance-authority lucide-react
Install the required registry components first:
$ bunx --bun frakment add button$ npx frakment add button$ pnpm dlx frakment add button$ yarn dlx frakment add button
Copy and paste the following code into your project.
"use client";
import type { VariantProps } from "class-variance-authority";
import { cva } from "class-variance-authority";
import {
CheckIcon,
CopyIcon,
FileCode2Icon,
FileJsonIcon,
FileTextIcon,
TerminalIcon,
} from "lucide-react";
import * as React from "react";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
const codeBlockVariants = cva(
"group/code-block has-[>[data-slot=code-block-content]:focus-visible]:ring-ring/30 relative flex w-full min-w-0 flex-col overflow-hidden rounded-2xl text-sm has-[>[data-slot=code-block-content]:focus-visible]:ring-3 data-[size=sm]:rounded-xl data-[size=sm]:text-xs",
{
defaultVariants: {
variant: "default",
},
variants: {
variant: {
default:
"bg-muted text-foreground ring-foreground/5 dark:ring-foreground/10 ring-1",
destructive:
"bg-destructive/5 text-destructive ring-destructive/15 dark:bg-destructive/10 dark:ring-destructive/20 ring-1",
},
},
}
);
function CodeBlock({
className,
variant = "default",
size = "default",
...props
}: React.ComponentProps<"div"> &
VariantProps<typeof codeBlockVariants> & { size?: "default" | "sm" }) {
return (
<div
className={cn(codeBlockVariants({ variant }), className)}
data-size={size}
data-slot="code-block"
data-variant={variant}
{...props}
/>
);
}
function CodeBlockHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"text-muted-foreground group-data-[variant=destructive]/code-block:text-destructive flex min-w-0 shrink-0 items-center gap-2 px-4 pt-4 group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:pt-3 *:has-[>[data-slot=code-block-title]]:min-w-0",
className
)}
data-slot="code-block-header"
{...props}
/>
);
}
const iconMap: Record<string, typeof FileCode2Icon> = {
bash: TerminalIcon,
cjs: FileCode2Icon,
css: FileCode2Icon,
fish: TerminalIcon,
go: FileCode2Icon,
html: FileCode2Icon,
js: FileCode2Icon,
json: FileJsonIcon,
jsonc: FileJsonIcon,
jsx: FileCode2Icon,
less: FileCode2Icon,
md: FileTextIcon,
mdx: FileTextIcon,
mjs: FileCode2Icon,
php: FileCode2Icon,
py: FileCode2Icon,
rb: FileCode2Icon,
rs: FileCode2Icon,
sass: FileCode2Icon,
scss: FileCode2Icon,
sh: TerminalIcon,
toml: FileCode2Icon,
ts: FileCode2Icon,
tsx: FileCode2Icon,
yaml: FileCode2Icon,
yml: FileCode2Icon,
zsh: TerminalIcon,
};
function pickIcon(children: React.ReactNode): typeof FileCode2Icon | null {
if (typeof children !== "string") {
return null;
}
const trimmed = children.trim();
const last = trimmed.split(/\s+/u).pop() ?? "";
const dot = last.lastIndexOf(".");
if (dot < 0 || dot === last.length - 1) {
return FileCode2Icon;
}
const ext = last.slice(dot + 1).toLowerCase();
return iconMap[ext] ?? FileCode2Icon;
}
function CodeBlockTitle({
children,
className,
icon,
...props
}: React.ComponentProps<"div"> & { icon?: typeof FileCode2Icon | null }) {
const Icon = icon === undefined ? pickIcon(children) : icon;
return (
<div
className={cn(
"text-foreground group-data-[variant=destructive]/code-block:text-destructive inline-flex min-w-0 items-center gap-1.5 truncate font-sans text-sm font-medium group-data-[size=sm]/code-block:text-xs [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 group-data-[size=sm]/code-block:[&_svg:not([class*='size-'])]:size-3.5",
className
)}
data-slot="code-block-title"
{...props}
>
{Icon ? <Icon /> : null}
<span className="min-w-0 truncate">{children}</span>
</div>
);
}
function CodeBlockActions({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
className={cn(
"*:data-[slot=button]:hover:bg-foreground/5 dark:*:data-[slot=button]:hover:bg-foreground/10 [[data-slot=code-block]>&]:*:[button]:bg-background [[data-slot=code-block]>&]:*:[button]:ring-foreground/10 -my-1 ms-auto -me-1.5 flex shrink-0 items-center gap-1 [[data-slot=code-block]>&]:absolute [[data-slot=code-block]>&]:end-3 [[data-slot=code-block]>&]:top-3 [[data-slot=code-block]>&]:z-10 [[data-slot=code-block]>&]:m-0 [[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 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:end-2 group-data-[size=sm]/code-block:[[data-slot=code-block]>&]:top-2 [[data-slot=code-block]>&]:pointer-coarse:opacity-100 [[data-slot=code-block]>&]:*:[button]:ring-1",
className
)}
data-slot="code-block-actions"
{...props}
/>
);
}
function CodeBlockCopyButton({
value,
variant = "ghost",
size = "icon-xs",
className,
onClick,
...props
}: React.ComponentProps<typeof Button> & { value: string }) {
const [copied, setCopied] = React.useState(false);
React.useEffect(() => {
if (!copied) {
return;
}
const timeout = setTimeout(() => setCopied(false), 2000);
return () => clearTimeout(timeout);
}, [copied]);
return (
<>
<Button
aria-label={copied ? "Copied" : "Copy"}
className={cn(
"hover:bg-foreground/5 dark:hover:bg-foreground/10",
className
)}
data-copied={copied || undefined}
data-slot="code-block-copy-button"
onClick={(event: React.MouseEvent<HTMLButtonElement>) => {
onClick?.(event);
navigator.clipboard
.writeText(value)
.then(() => setCopied(true))
.catch(() => {});
}}
size={size}
variant={variant}
{...props}
>
{copied ? <CheckIcon /> : <CopyIcon />}
</Button>
<span aria-live="polite" className="sr-only">
{copied ? "Copied" : ""}
</span>
</>
);
}
function CodeBlockContent({
className,
children,
style,
wrap = false,
lineNumbers = false,
startLine = 1,
...props
}: React.ComponentProps<"pre"> & {
wrap?: boolean;
lineNumbers?: boolean;
startLine?: number;
}) {
return (
<pre
className={cn(
"scroll-fade-x data-wrap:scroll-fade-y min-h-0 min-w-0 scrollbar-thin overflow-auto px-4 py-4 text-start font-mono text-sm leading-relaxed outline-none 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-3 group-data-[size=sm]/code-block:py-3 group-data-[size=sm]/code-block:group-has-data-[slot=code-block-header]/code-block:pt-1.5 data-wrap:wrap-break-word data-wrap:whitespace-pre-wrap",
className
)}
data-numbered={lineNumbers || undefined}
data-slot="code-block-content"
data-wrap={wrap || undefined}
dir="ltr"
style={{ counterReset: `line ${startLine - 1}`, ...style }}
{...props}
>
<code
className="grid min-h-lh min-w-max content-start in-data-numbered:grid-cols-[auto_1fr] in-data-wrap:min-w-0"
data-slot="code-block-code"
>
{lineNumbers && typeof children === "string"
? children
.replace(/\n$/u, "")
.split("\n")
.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))
: children}
</code>
</pre>
);
}
const codeBlockLineVariants = cva(
"before:text-muted-foreground after:text-muted-foreground relative -mx-4 block min-h-lh px-4 group-data-[size=sm]/code-block:-mx-3 group-data-[size=sm]/code-block:px-3 before:min-w-6 before:text-end after:absolute after:start-1 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:gap-x-3 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)_/_'']",
{
defaultVariants: {
variant: "default",
},
variants: {
variant: {
added: "bg-foreground/5 after:content-['+']",
default: "",
highlighted: "bg-foreground/5",
removed: "bg-destructive/10 after:text-destructive after:content-['−']",
},
},
}
);
function CodeBlockLine({
className,
variant = "default",
children,
...props
}: React.ComponentProps<"span"> & VariantProps<typeof codeBlockLineVariants>) {
const empty =
children === undefined ||
children === null ||
children === "" ||
(Array.isArray(children) && children.length === 0);
return (
<span
className={cn(codeBlockLineVariants({ variant }), className)}
data-slot="code-block-line"
data-variant={variant}
{...props}
>
<span className="min-w-0" data-slot="code-block-line-content">
{empty ? "\n" : children}
</span>
</span>
);
}
function CodeBlockFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn(
"text-muted-foreground flex min-w-0 shrink-0 items-center gap-2 px-4 pb-4 group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:pb-3",
className
)}
data-slot="code-block-footer"
{...props}
/>
);
}
export {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockFooter,
CodeBlockHeader,
CodeBlockLine,
CodeBlockTitle,
};Update the import paths to match your project setup.
Usage
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";<CodeBlock>
<CodeBlockContent>npm install frakment</CodeBlockContent>
</CodeBlock>Basic
The simplest form — pass a string as children of CodeBlockContent.
npm install frakment"use client";
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
export function CodeBlockBasicDemo() {
return (
<div className="w-full max-w-lg">
<CodeBlock>
<CodeBlockContent>npm install frakment</CodeBlockContent>
</CodeBlock>
</div>
);
}Header
Wrap the top row in CodeBlockHeader. Use CodeBlockTitle for the filename and CodeBlockActions for buttons.
npx frakment add button"use client";
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockTitle,
} from "@/components/ui/code-block";
export function CodeBlockHeaderDemo() {
return (
<div className="w-full max-w-lg">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>Terminal</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value="npx frakment add button" />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>npx frakment add button</CodeBlockContent>
</CodeBlock>
</div>
);
}Actions
CodeBlockActions can hold multiple buttons — copy, download, wrap toggle. Each is a plain Button.
pnpm add frakment"use client";
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
CodeBlockHeader,
CodeBlockTitle,
} from "@/components/ui/code-block";
export function CodeBlockActionsDemo() {
return (
<div className="w-full max-w-lg">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>install.sh</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value="pnpm add frakment" />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>pnpm add frakment</CodeBlockContent>
</CodeBlock>
</div>
);
}Floating Actions
Place CodeBlockActions directly inside CodeBlock (no header) — the buttons float top-end and fade in on hover.
npm i frakment"use client";
import {
CodeBlock,
CodeBlockActions,
CodeBlockContent,
CodeBlockCopyButton,
} from "@/components/ui/code-block";
export function CodeBlockFloatingActionsDemo() {
return (
<div className="w-full max-w-lg">
<CodeBlock>
<CodeBlockActions>
<CodeBlockCopyButton value="npm i frakment" />
</CodeBlockActions>
<CodeBlockContent>npm i frakment</CodeBlockContent>
</CodeBlock>
</div>
);
}Line Numbers
Add lineNumbers to CodeBlockContent. Line numbers are not copied when the user selects the code.
import { Button } from "@/components/ui/button"
export default function Page() { return <Button>Click me</Button>}"use client";
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
export function CodeBlockLineNumbersDemo() {
return (
<div className="w-full max-w-lg">
<CodeBlock>
<CodeBlockContent
lineNumbers
>{`import { Button } from "@/components/ui/button"
export function Page() {
return <Button>Click me</Button>
}`}</CodeBlockContent>
</CodeBlock>
</div>
);
}Start Line
Set startLine to begin numbering from a different number — useful when showing a snippet from the middle of a file.
const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages, })
return result.toUIMessageStreamResponse()"use client";
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
export function CodeBlockStartLineDemo() {
return (
<div className="w-full max-w-lg">
<CodeBlock>
<CodeBlockContent
lineNumbers
startLine={20}
>{` const result = streamText({
model: "anthropic/claude-sonnet-4.5",
messages,
})
return result.toUIMessageStreamResponse()`}</CodeBlockContent>
</CodeBlock>
</div>
);
}Wrap
Add wrap to CodeBlockContent to break long lines instead of scroll. Compare both sides:
Error: Failed to resolve module from /app/page.tsxError: Failed to resolve module from /app/page.tsx"use client";
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
export function CodeBlockWrapDemo() {
return (
<div className="grid w-full max-w-2xl grid-cols-1 gap-4 p-4 sm:grid-cols-2">
<div className="flex flex-col gap-2">
<span className="text-muted-foreground text-xs font-medium">
default (scroll)
</span>
<CodeBlock>
<CodeBlockContent>
Error: Failed to resolve module from /app/page.tsx
</CodeBlockContent>
</CodeBlock>
</div>
<div className="flex flex-col gap-2">
<span className="text-muted-foreground text-xs font-medium">wrap</span>
<CodeBlock>
<CodeBlockContent wrap>
Error: Failed to resolve module from /app/page.tsx
</CodeBlockContent>
</CodeBlock>
</div>
</div>
);
}Highlighted Lines
Use CodeBlockLine with variant="highlighted" to draw attention to specific lines.
const config = { theme: 'system', primary: 'oklch(0.6 0.2 250)', radius: 0.5,}"use client";
import {
CodeBlock,
CodeBlockContent,
CodeBlockLine,
} from "@/components/ui/code-block";
export function CodeBlockHighlightedLinesDemo() {
return (
<div className="w-full max-w-lg">
<CodeBlock>
<CodeBlockContent>
<CodeBlockLine>{"const config = {"}</CodeBlockLine>
<CodeBlockLine>{" theme: 'system',"}</CodeBlockLine>
<CodeBlockLine variant="highlighted">
{" primary: 'oklch(0.6 0.2 250)',"}
</CodeBlockLine>
<CodeBlockLine>{" radius: 0.5,"}</CodeBlockLine>
<CodeBlockLine>{"}"}</CodeBlockLine>
</CodeBlockContent>
</CodeBlock>
</div>
);
}Diff
Use variant="added" and variant="removed". The + and − markers are added by CSS — no need to type them.
const config = { theme: 'light', theme: 'system',}"use client";
import {
CodeBlock,
CodeBlockContent,
CodeBlockLine,
} from "@/components/ui/code-block";
export function CodeBlockDiffDemo() {
return (
<div className="w-full max-w-lg">
<CodeBlock>
<CodeBlockContent>
<CodeBlockLine>{"const config = {"}</CodeBlockLine>
<CodeBlockLine variant="removed">{" theme: 'light',"}</CodeBlockLine>
<CodeBlockLine variant="added">{" theme: 'system',"}</CodeBlockLine>
<CodeBlockLine>{"}"}</CodeBlockLine>
</CodeBlockContent>
</CodeBlock>
</div>
);
}Height
Constrain height with a max-h-* class on CodeBlockContent. Content becomes scrollable — good for long build logs.
✓ Compiled successfully in 2.1s✓ Linting and checking validity of types✓ Collecting page data✓ Generating static pages (12/12)✓ Finalizing page optimization
Route (app) Size First Load JS┌ ○ / 1.2 kB 90.2 kB├ ○ /_not-found 875 B 88.9 kB├ ○ /docs 3.4 kB 92.4 kB└ ○ /docs/components 5.1 kB 94.1 kB
- First Load JS shared by all 88.1 kB ├ chunks/1a2b3c.js 45.2 kB ├ chunks/4d5e6f.js 32.9 kB └ chunks/7g8h9i.js 10.0 kB"use client";
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
export function CodeBlockHeightDemo() {
return (
<div className="w-full max-w-lg">
<CodeBlock>
<CodeBlockContent
className="max-h-40"
lineNumbers
>{`✓ Compiled successfully in 2.1s
✓ Linting and checking validity of types
✓ Collecting page data
✓ Generating static pages (12/12)
✓ Finalizing page optimization
Route (app) Size First Load JS
┌ ○ / 1.2 kB 90.2 kB
├ ○ /_not-found 875 B 88.9 kB
├ ○ /docs 3.4 kB 92.4 kB
└ ○ /docs/components 5.1 kB 94.1 kB
- First Load JS shared by all 88.1 kB
├ chunks/1a2b3c.js 45.2 kB
├ chunks/4d5e6f.js 32.9 kB
└ chunks/7g8h9i.js 10.0 kB`}</CodeBlockContent>
</CodeBlock>
</div>
);
}Size
Two sizes: default (14px, 16px padding) and sm (12px, 12px padding). sm fits inside compact slots.
npx frakment add buttonnpx frakment add button"use client";
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
export function CodeBlockSizeDemo() {
return (
<div className="flex w-full max-w-lg flex-col gap-4 p-4">
<div className="flex flex-col gap-2">
<span className="text-muted-foreground text-xs font-medium">
size="default"
</span>
<CodeBlock>
<CodeBlockContent>npx frakment add button</CodeBlockContent>
</CodeBlock>
</div>
<div className="flex flex-col gap-2">
<span className="text-muted-foreground text-xs font-medium">
size="sm"
</span>
<CodeBlock size="sm">
<CodeBlockContent>npx frakment add button</CodeBlockContent>
</CodeBlock>
</div>
</div>
);
}Destructive
Use variant="destructive" for error output. Background and text shift to destructive tone.
Error: Failed to resolve module '@/components/ui/code-block'"use client";
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
export function CodeBlockDestructiveDemo() {
return (
<div className="w-full max-w-lg">
<CodeBlock variant="destructive">
<CodeBlockContent>
{"Error: Failed to resolve module '@/components/ui/code-block'"}
</CodeBlockContent>
</CodeBlock>
</div>
);
}In Context
Documentation snippet
npx frakment add button"use client";
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
export function CodeBlockDocumentationDemo() {
return (
<CodeBlock className="mx-auto w-full max-w-md">
<CodeBlockContent wrap>{"npx frakment add button"}</CodeBlockContent>
</CodeBlock>
);
}API Reference
CodeBlock
| Prop | Type | Default | Description |
|---|---|---|---|
variant | defaultdestructive | default | Visual style of the container. |
size | defaultsm | default | Text size and padding scale. |
CodeBlockContent
| Prop | Type | Default | Description |
|---|---|---|---|
wrap | boolean | false | Wrap long lines instead of horizontal scroll. |
lineNumbers | boolean | false | Render line numbers. Requires string children. |
startLine | number | 1 | First line number when lineNumbers is enabled. |
CodeBlockLine
| Prop | Type | Default | Description |
|---|---|---|---|
variant | defaultaddedremovedhighlighted | default | Visual diff or highlight style for the line. |
Accessibility
- CodeBlockContent has
tabIndex={0}for keyboard scroll. - CodeBlockCopyButton has
aria-labeland aaria-liveregion announcing "Copied". - Use CodeBlockTitle as the accessible name of the block.
Composition
CodeBlock
├── CodeBlockHeader
│ ├── CodeBlockTitle
│ └── CodeBlockActions
├── CodeBlockContent
├── CodeBlockCopyButton
└── CodeBlockFooterBest Practices
- Set a max-height. Long files push the layout.
- Show the file name. Users need to know where the code goes.
- Copy action on hover, not always. Reduces visual noise.
- Do not highlight unknown languages. Fall back to plain text.