Skip to content

Code Block

Shows code, terminal output, logs and diffs, with an optional title, line numbers, highlighting and a copy button.

lib/orders.ts
export async function approveOrder(id: string) {  const order = await getOrder(id)
  if (order.status !== "waiting") {    throw new Error("Order " + id + " is not waiting for approval")  }
  return updateOrder(id, { status: "approved" })}

Installation

pnpm dlx shadcn@latest add @silkware/code-block

The block draws plain text by itself. To highlight syntax, add the hook and the highlighter that it shares:

pnpm dlx shadcn@latest add @silkware/use-highlighted-code

To copy the component by hand, install its dependencies:

pnpm add class-variance-authority cn lucide-react shiki

The copy button uses the Button, so install it too:

pnpm dlx shadcn@latest add @silkware/button

Then copy the source into components/ui/code-block.tsx:

components/ui/code-block.tsx
"use client"
import * as React from "react"import { cva, type VariantProps } from "class-variance-authority"import { cn } from "cn"
import { Button } from "@/components/ui/button"import { CheckIcon, CopyIcon } from "lucide-react"
const codeBlockVariants = cva(  "group/code-block relative flex w-full min-w-0 flex-col overflow-hidden rounded-lg text-sm has-[>[data-slot=code-block-content]:focus-visible]:ring-3 has-[>[data-slot=code-block-content]:focus-visible]:ring-ring/50 data-[size=sm]:text-xs",  {    variants: {      variant: {        default:          "border border-input text-foreground has-[>[data-slot=code-block-content]:focus-visible]:border-ring dark:bg-input/30",        destructive:          "border border-destructive/30 text-destructive dark:border-destructive/40",      },    },    defaultVariants: {      variant: "default",    },  })
function CodeBlock({  className,  variant = "default",  size = "default",  ...props}: React.ComponentProps<"div"> &  VariantProps<typeof codeBlockVariants> & { size?: "default" | "sm" }) {  return (    <div      data-slot="code-block"      data-variant={variant}      data-size={size}      className={cn(codeBlockVariants({ variant }), className)}      {...props}    />  )}
function CodeBlockHeader({ className, ...props }: React.ComponentProps<"div">) {  return (    <div      data-slot="code-block-header"      className={cn(        "flex min-w-0 shrink-0 items-center gap-2 px-4 pt-4 text-muted-foreground group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:pt-3 group-data-[variant=destructive]/code-block:text-destructive *:has-[>[data-slot=code-block-title]]:min-w-0",        className      )}      {...props}    />  )}
function CodeBlockTitle({ className, ...props }: React.ComponentProps<"div">) {  return (    <div      data-slot="code-block-title"      className={cn(        "min-w-0 truncate font-sans text-sm font-medium text-foreground group-data-[size=sm]/code-block:text-xs group-data-[variant=destructive]/code-block:text-destructive [&_svg]:pointer-events-none [&_svg]:inline-block [&_svg]:align-middle [&_svg:not([class*='size-'])]:size-4 group-data-[size=sm]/code-block:[&_svg:not([class*='size-'])]:size-3.5 *:[svg]:me-1.5",        className      )}      {...props}    />  )}
function CodeBlockActions({  className,  ...props}: React.ComponentProps<"div">) {  return (    <div      data-slot="code-block-actions"      className={cn(        "-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]:bg-background [[data-slot=code-block]>&]:*:[button]:ring-1 [[data-slot=code-block]>&]:*:[button]:ring-foreground/10",        className      )}      {...props}    />  )}
function CodeBlockCopyButton({  value,  variant = "ghost",  size = "icon-xs",  className,  onPress,  ...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        data-slot="code-block-copy-button"        data-copied={copied || undefined}        variant={variant}        size={size}        aria-label={copied ? "Copied" : "Copy"}        className={cn(className)}        onPress={(event) => {          onPress?.(event)          navigator.clipboard            .writeText(value)            .then(() => setCopied(true))            .catch(() => {})        }}        {...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      data-slot="code-block-content"      data-wrap={wrap || undefined}      data-numbered={lineNumbers || undefined}      dir="ltr"      tabIndex={0}      style={{ counterReset: `line ${startLine - 1}`, ...style }}      className={cn(        "min-h-0 min-w-0 scroll-fade-x scrollbar-thin overflow-auto px-4 py-4 text-start font-mono 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:scroll-fade-y data-wrap:wrap-break-word data-wrap:whitespace-pre-wrap",        className      )}      {...props}    >      <code        data-slot="code-block-code"        className="grid min-h-lh min-w-max content-start in-data-numbered:grid-cols-[auto_1fr] in-data-wrap:min-w-0"      >        {lineNumbers && typeof children === "string"          ? children              .replace(/\n$/, "")              .split("\n")              .map((line, index) => (                <CodeBlockLine key={index}>{line}</CodeBlockLine>              ))          : children}      </code>    </pre>  )}
const codeBlockLineVariants = cva(  "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 before:text-muted-foreground after:absolute after:start-1 after:top-0 after:text-muted-foreground 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)_/_'']",  {    variants: {      variant: {        default: "",        added: "bg-muted after:content-['+']",        removed: "bg-destructive/10 after:text-destructive after:content-['−']",        highlighted: "bg-muted",      },    },    defaultVariants: {      variant: "default",    },  })
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      data-slot="code-block-line"      data-variant={variant}      className={cn(codeBlockLineVariants({ variant }), className)}      {...props}    >      <span data-slot="code-block-line-content" className="min-w-0">        {empty ? "\n" : children}      </span>    </span>  )}
function CodeBlockFooter({ className, ...props }: React.ComponentProps<"div">) {  return (    <div      data-slot="code-block-footer"      className={cn(        "flex min-w-0 shrink-0 items-center gap-2 px-4 pb-4 text-muted-foreground group-data-[size=sm]/code-block:px-3 group-data-[size=sm]/code-block:pb-3",        className      )}      {...props}    />  )}
export {  CodeBlock,  CodeBlockHeader,  CodeBlockTitle,  CodeBlockActions,  CodeBlockCopyButton,  CodeBlockContent,  CodeBlockLine,  CodeBlockFooter,}

For highlighting, copy the hook and the highlighter as well:

hooks/use-highlighted-code.ts
import * as React from "react"
import { loadHighlighter } from "@/lib/highlighter"
export function useHighlightedCode(value: string, language: string) {  const code = value.endsWith("\n") ? value.slice(0, -1) : value  const [loaded, setLoaded] = React.useState<{    language: string    highlighter: Awaited<ReturnType<typeof loadHighlighter>>  } | null>(null)  const highlighter = loaded?.language === language ? loaded.highlighter : null
  React.useEffect(() => {    let cancelled = false
    loadHighlighter(language)      .then((next) => {        if (!cancelled) {          setLoaded({ language, highlighter: next })        }      })      .catch(() => {})
    return () => {      cancelled = true    }  }, [language])
  const [done, setDone] = React.useState<{    highlighter: typeof highlighter    text: string    lines: React.ReactNode[]    state?: Parameters<NonNullable<typeof highlighter>["highlight"]>[1]  }>({ highlighter: null, text: "", lines: [] })
  let next = done
  if (next.highlighter !== highlighter || !code.startsWith(next.text)) {    next = { highlighter, text: "", lines: [] }  }
  const end = code.lastIndexOf("\n") + 1
  if (highlighter && end > next.text.length) {    const result = highlighter.highlight(      code.slice(next.text.length, end - 1),      next.state    )
    next = {      highlighter,      text: code.slice(0, end),      lines: [...next.lines, ...result.lines],      state: result.state,    }  }
  if (next !== done) {    setDone(next)  }
  const tail = code.slice(end)
  return React.useMemo(() => {    if (!highlighter) {      return code.split("\n")    }
    return [...next.lines, highlighter.highlight(tail, next.state).lines[0]]  }, [code, highlighter, next, tail])}
lib/highlighter.tsx
import * as React from "react"import {  createCssVariablesTheme,  createHighlighterCore,  type GrammarState,  type HighlighterCore,} from "shiki/core"import { createJavaScriptRegexEngine } from "shiki/engine/javascript"
const languages = {  bash: () => import("shiki/langs/shellscript.mjs"),  css: () => import("shiki/langs/css.mjs"),  diff: () => import("shiki/langs/diff.mjs"),  html: () => import("shiki/langs/html.mjs"),  javascript: () => import("shiki/langs/javascript.mjs"),  json: () => import("shiki/langs/json.mjs"),  jsx: () => import("shiki/langs/jsx.mjs"),  markdown: () => import("shiki/langs/markdown.mjs"),  python: () => import("shiki/langs/python.mjs"),  sql: () => import("shiki/langs/sql.mjs"),  tsx: () => import("shiki/langs/tsx.mjs"),  typescript: () => import("shiki/langs/typescript.mjs"),  yaml: () => import("shiki/langs/yaml.mjs"),}
const aliases: Record<string, keyof typeof languages> = {  js: "javascript",  md: "markdown",  py: "python",  sh: "bash",  shell: "bash",  shellscript: "bash",  ts: "typescript",  yml: "yaml",  zsh: "bash",}
const ansi = {  "ansi-black": "var(--syntax-foreground)",  "ansi-red": "var(--syntax-token-deleted)",  "ansi-green": "var(--syntax-token-inserted)",  "ansi-yellow": "var(--syntax-token-constant)",  "ansi-blue": "var(--syntax-token-keyword)",  "ansi-magenta": "var(--syntax-token-keyword)",  "ansi-cyan": "var(--syntax-token-keyword)",  "ansi-white": "var(--syntax-token-comment)",}
const theme = createCssVariablesTheme({  name: "silkware",  variablePrefix: "--syntax-",  fontStyle: false,  variableDefaults: {    ...ansi,    ...Object.fromEntries(      Object.entries(ansi).map(([name, value]) => [        name.replace("ansi-", "ansi-bright-"),        value,      ])    ),  },})
let highlighter: Promise<HighlighterCore> | undefined
function getHighlighter() {  highlighter ??= createHighlighterCore({    themes: [theme],    langs: [],    engine: createJavaScriptRegexEngine({ forgiving: true }),  })
  return highlighter}
function getLanguage(language: string) {  const name = language.toLowerCase()
  if (name === "ansi") {    return name  }
  if (name in languages) {    return name as keyof typeof languages  }
  return aliases[name] ?? null}
export async function loadHighlighter(language: string) {  const lang = getLanguage(language)
  if (!lang) {    return null  }
  const shiki = await getHighlighter()
  if (lang !== "ansi" && !shiki.getLoadedLanguages().includes(lang)) {    await shiki.loadLanguage(languages[lang])  }
  return {    highlight(code: string, state?: GrammarState) {      const tokenize = (text: string) =>        shiki.codeToTokens(text, {          lang,          theme: "silkware",          grammarState: state,        }).tokens
      const tokens =        lang === "ansi"          ? code.split("\n").flatMap((line) => tokenize(line))          : tokenize(code)
      return {        lines: tokens.map((line) =>          line.map((token, index) => (            <span              key={index}              style={{ color: token.color }}            >              {token.content}            </span>          ))        ),        state: shiki.getLastGrammarState(tokens),      }    },  }}
export async function highlightCode(code: string, language: string) {  const highlighter = await loadHighlighter(language)
  return highlighter ? highlighter.highlight(code).lines : null}

Usage

import {  CodeBlock,  CodeBlockActions,  CodeBlockContent,  CodeBlockCopyButton,  CodeBlockFooter,  CodeBlockHeader,  CodeBlockLine,  CodeBlockTitle,} from "@/components/ui/code-block"
<CodeBlock>  <CodeBlockHeader>    <CodeBlockTitle>Terminal</CodeBlockTitle>    <CodeBlockActions>      <CodeBlockCopyButton value={output} />    </CodeBlockActions>  </CodeBlockHeader>  <CodeBlockContent>{output}</CodeBlockContent></CodeBlock>

CodeBlockContent takes a string or a list of CodeBlockLine. Pass a string for plain output: it renders as one text node, which is cheap while output streams. Pass lines when you need highlighted tokens or a state on a line: highlighted, added or removed. The code always reads left to right, whatever the direction of the page. In a conversation a block sits inside a Message or a Trace; see Tool and Terminal for the patterns.

Examples

Basic

A string, with no header. Good for short output inside a message.

$ pnpm sync:orders
Reading orders from the Brevia ERP
Found 38 open orders in 3 sites
Done in 2.1s

CodeBlockHeader holds a CodeBlockTitle, with an optional icon, and CodeBlockActions. A long title truncates. CodeBlockCopyButton copies exactly the value you give it, which can differ from what is shown: here it copies the command without its output.

Terminal
$ pnpm sync:orders --site verona
Reading orders from the Brevia ERP
Found 14 open orders in Verona
Done in 0.9s

Actions

CodeBlockActions holds any buttons. For a wrap toggle, keep the state yourself, pass it to wrap and give the button aria-pressed.

Terminal
$ pnpm check:prices
rows/steel.csv
  14:3  error  Unit price is missing for item FN-2291
  22:3  error  Unit price is missing for item FN-2304

2 problems (2 errors, 0 warnings)

Floating actions

Without a header, put CodeBlockActions directly in the CodeBlock. The buttons float in the top corner, appear on hover and on focus, and always show on touch screens.

$ pnpm sync:orders
Found 38 open orders in 3 sites
Done in 2.1s

Line numbers

lineNumbers on CodeBlockContent numbers each line. A string child is split into lines for you. Numbers are not part of a selection.

{  "supplier": "Lamivo Metalli",  "item": "FN-2291",  "unitPrice": 18.4,  "currency": "EUR"}

Start line

startLine numbers the lines from a given line, for a snippet from the middle of a file. The gutter grows to fit the widest number. It works with lineNumbers.

lib/orders.ts
  if (order.status !== "waiting") {    return null  }
  const prices = await getPriceList(order.supplierId)  return applyPrices(order, prices)}

Syntax highlighting

useHighlightedCode(code, language) returns one node per line, for CodeBlockLine. It returns plain lines until the highlighter has loaded and for a language it does not know. The project highlighter loads Shiki with its JavaScript regex engine, so there is no WebAssembly to ship, and loads each language the first time it is used.

order-4417.json
{  "supplier": "Lamivo Metalli",  "site": "Verona",  "lines": [    { "item": "FN-2291", "quantity": 40 },    { "item": "FN-2304", "quantity": 12 }  ]}

The languages are bash, css, diff, html, javascript, json, jsx, markdown, python, sql, tsx, typescript and yaml, with the aliases js, md, py, sh, shell, shellscript, ts, yml and zsh, and ansi for terminal colour codes. Edit the list in lib/highlighter.tsx to change it. The themes are GitHub light and dark, and they follow the theme of the page.

Wrap

Long lines scroll by default. wrap wraps them, which suits error messages and logs that people read as sentences. Keep the default for code, where line breaks carry meaning.

Error: The supplier rejected order 4417 because the price list it was built from is out of date. The list was last updated on 2026-11-02 and the supplier expects the 2026-11-24 version. Update the price list and send the order again.
Error: The supplier rejected order 4417 because the price list it was built from is out of date. The list was last updated on 2026-11-02 and the supplier expects the 2026-11-24 version. Update the price list and send the order again.

Highlighted lines

Render each line as a CodeBlockLine and set variant="highlighted" on the ones to call out.

{  "site": "Verona",  "items": 1204,  "belowMinimum": 9,  "status": "needs-reorder"}

Diff

variant="added" and variant="removed" tint a line and add a + or a − marker in the gutter. The marker means the change does not rest on the tint. The markers are not copied, so strip the leading character of each patch line yourself, as the example does.

lib/pricing.ts
const price = item.unitPriceconst total = price * quantityconst discount = supplier.discount ?? 0const total = price * quantity * (1 - discount)return total

Height

Cap the height with a max-h-* class on CodeBlockContent. The content scrolls inside the block and fades at the edge. Add scroll-fade-y to a capped block that does not wrap.

Sync log
[01] Synced order 4400 in 12ms
[02] Synced order 4401 in 19ms
[03] Synced order 4402 in 26ms
[04] Synced order 4403 in 33ms
[05] Synced order 4404 in 40ms
[06] Synced order 4405 in 47ms
[07] Synced order 4406 in 14ms
[08] Synced order 4407 in 21ms
[09] Synced order 4408 in 28ms
[10] Synced order 4409 in 35ms
[11] Synced order 4410 in 42ms
[12] Synced order 4411 in 49ms
[13] Synced order 4412 in 16ms
[14] Synced order 4413 in 23ms
[15] Synced order 4414 in 30ms
[16] Synced order 4415 in 37ms
[17] Synced order 4416 in 44ms
[18] Synced order 4417 in 51ms
[19] Synced order 4418 in 18ms
[20] Synced order 4419 in 25ms
[21] Synced order 4420 in 32ms
[22] Synced order 4421 in 39ms
[23] Synced order 4422 in 46ms
[24] Synced order 4423 in 13ms
[25] Synced order 4424 in 20ms
[26] Synced order 4425 in 27ms
[27] Synced order 4426 in 34ms
[28] Synced order 4427 in 41ms
[29] Synced order 4428 in 48ms
[30] Synced order 4429 in 15ms
[31] Synced order 4430 in 22ms
[32] Synced order 4431 in 29ms
[33] Synced order 4432 in 36ms
[34] Synced order 4433 in 43ms
[35] Synced order 4434 in 50ms
[36] Synced order 4435 in 17ms
[37] Synced order 4436 in 24ms
[38] Synced order 4437 in 31ms
[39] Synced order 4438 in 38ms
[40] Synced order 4439 in 45ms

Show more

CodeBlockFooter is a row below the content. For a collapsed block, cap the height and put a small ghost button in the footer, with aria-expanded and aria-controls pointing at the id of the content.

lib/summary.ts
export function summarise(orders: Order[]) {  const waiting = orders.filter((order) => order.status === "waiting")  const late = orders.filter((order) => order.daysLate > 0)  const bySite = new Map<string, number>()
  for (const order of orders) {    bySite.set(order.site, (bySite.get(order.site) ?? 0) + 1)  }
  return {    waiting: waiting.length,    late: late.length,    bySite: Object.fromEntries(bySite),  }}

Size

size="sm" tightens the padding and sets the text to text-xs. Use it for tool output inside a Trace and for blocks in a narrow column.

Default
$ pnpm sync:orders
Found 38 open orders in 3 sites
Done in 2.1s
Small
$ pnpm sync:orders
Found 38 open orders in 3 sites
Done in 2.1s

Destructive

variant="destructive" draws a crimson border and text for errors and failed output. The title and the text still say that it failed.

Error
Error: Supplier rejected order 4417 (409 Conflict)
    at sendOrder (lib/orders.ts:142:11)
    at approveOrder (lib/orders.ts:118:9)

Streaming

While code arrives in pieces, pass the text so far to useHighlightedCode on every render. It highlights each complete line once and only the unfinished last line again, so the cost stays flat as the block grows. Give the content a min-h-* class so the block does not jump while the first lines arrive.

lib/totals.ts

Accessibility

KeyAction
TabMoves focus to the copy button and the other actions, which come first, then into the code.
Arrow keysScroll the focused code up, down, left or right.
Page UpPage DownScroll the focused code by a page.
HomeEndScroll the focused code to its start or its end.
EnterPresses the focused action button.
SpacePresses the focused action button, or scrolls the focused code by a page.

The component provides:

  • A pre with a code element, so the text is read as preformatted code.
  • dir="ltr" on the content, so code reads left to right on a right-to-left page.
  • tabIndex={0} on the content, so keyboard users can focus it and scroll it. Pass tabIndex={-1} to remove the stop when the block never overflows.
  • Floating actions that show when focus is anywhere inside the block, not only on hover.
  • Line numbers drawn with CSS counters, so they are not read out and not copied.
  • A + or − marker on diff lines, so a change does not depend on colour.
  • A copy button labelled "Copy", then "Copied", and a polite live region that announces "Copied" after a successful copy.

You provide:

  • A title or a nearby heading that says what the code is, such as the file name.
  • aria-pressed on a wrap toggle, and aria-expanded and aria-controls on a show more button.
  • A label on every icon button you add to the actions.
  • Text that explains an error. The destructive variant changes colour; say what failed in the title or nearby.
  • Highlighting that adds to the code, not replaces it. The colours of the highlighter are a cue, not the only way to tell tokens apart.

Guidelines

When to use

  • To show code, commands, configuration or API responses that people read or copy.
  • To show terminal output, logs and error traces from a tool an agent ran.
  • To show a diff of a change, such as a price list update or a patch.

When not to use

  • For a word or two of code inside a sentence. Use inline code in the text.
  • For a keyboard shortcut. Use Kbd.
  • For tabular output that people sort or filter. Use a Table.
  • For the structure of files in a project. Use the File Tree pattern.
  • For text an agent wrote in prose. Use a Bubble with the ghost variant.

Content

  • Show real code and real output, trimmed to what the reader needs. Do not pad with empty lines.
  • Title the block with the file name or the command: "lib/orders.ts", "Terminal".
  • Give CodeBlockCopyButton the text a person would paste, which is often only the command, not its output.
  • Name the language when the highlighter knows it. For anything else, show plain text rather than a wrong grammar.
  • Keep titles short, in sentence case for words and as written for file names.

Wrapping and diffs

Wrap messages, not code. A sentence in an error reads better wrapped, and a line of code reads better unwrapped. For a patch, use line variants and not typed + and - characters, which become part of the text and are copied.

Error: The supplier rejected order 4417 because the price list it was built from is out of date. Update the price list and send the order again.
Do

Wrap an error message so the whole sentence is visible.

Error: The supplier rejected order 4417 because the price list it was built from is out of date. Update the price list and send the order again.
Don’t

Don’t make people scroll sideways to read a sentence. The end of the message, the part that says what to do, is out of sight.

const rate = 0.1const rate = 0.15
Do

Mark changed lines with the added and removed variants. The marker and the tint are not copied with the code.

- const rate = 0.1
+ const rate = 0.15
Don’t

Don’t type plus and minus signs into the text. They are copied with the code and the block has no tint.

API reference

CodeBlock

Renders a <div> with the border, the radius and the text size. It holds the header, the content and the footer, and gives them their size through a data attribute. It accepts every prop of a div.

PropTypeDefaultDescription
variant?"default" | "destructive""default"The tone of the block. destructive uses the destructive colour for the border and the text.
size?"default" | "sm""default"sm tightens the padding and sets the text to text-xs, for tool output.
className?stringNoneClasses merged after the variant classes.

CodeBlockHeader

Renders a <div>, a row above the content for a title and actions.

PropTypeDefaultDescription
className?stringNoneClasses merged after the header classes.

CodeBlockTitle

Renders a <div> with the file name or the label, in the sans font. It truncates and can hold an icon before the text.

PropTypeDefaultDescription
className?stringNoneClasses merged after the title classes.

CodeBlockActions

Renders a <div> that holds buttons at the end of the header. As a direct child of CodeBlock it floats in the top corner and shows on hover and focus.

PropTypeDefaultDescription
className?stringNoneClasses merged after the actions classes.

CodeBlockCopyButton

Renders a ghost icon Button that copies value to the clipboard, then shows a check for two seconds. It accepts every React Aria Button prop. Its label changes from "Copy" to "Copied", and a visually hidden live region announces the copy.

PropTypeDefaultDescription
valuestringNoneThe text to copy.
variant?ButtonProps variant"ghost"The Button variant.
size?ButtonProps size"icon-xs"The Button size.
onPress?(event: PressEvent) => voidNoneCalled before the text is copied.

CodeBlockContent

Renders a <pre> with a <code> inside, in the monospace stack. It scrolls, or wraps with wrap. A string child is rendered as one text node, or split into numbered lines with lineNumbers.

PropTypeDefaultDescription
children?ReactNodeNoneA string, or a list of CodeBlockLine.
wrap?booleanfalseWraps long lines instead of scrolling them.
lineNumbers?booleanfalseNumbers each line. A string child is split into lines.
startLine?number1The number of the first line when lineNumbers is set.
tabIndex?number0Makes the content focusable so it can be scrolled by keyboard.
className?stringNoneClasses merged after the content classes, such as max-h-48.

CodeBlockLine

Renders a <span> for one line, with a wrapper for its text. Use it when you pass highlighted nodes or need a line state.

PropTypeDefaultDescription
variant?"default" | "added" | "removed" | "highlighted""default"The state of the line. added and removed add a plus or a minus marker.
children?ReactNodeNoneThe text or the highlighted nodes of the line.
className?stringNoneClasses merged after the line classes.

CodeBlockFooter

Renders a <div>, a row below the content, for a show more button or a note.

PropTypeDefaultDescription
className?stringNoneClasses merged after the footer classes.

useHighlightedCode

Imported from @/hooks/use-highlighted-code. It tokenizes with Shiki and returns one React node per line. Complete lines are highlighted once, so the hook is safe to call with text that grows.

PropTypeDefaultDescription
valuestringNoneThe code to highlight. One trailing newline is ignored.
languagestringNoneA language or alias from lib/highlighter.tsx, or ansi. An unknown language returns plain lines.