---
title: Code Block for Astro
description: "Composable Astro code blocks with copy controls, line numbers, diff states, and syntax highlighting."
seo:
    title: Code Block for Astro | Shadcn & Tailwind CSS
related:
    - /components/tabs
    - /components/button
    - /components/scroll-area
sidebar:
    label: "Code Block"
---

```astro
---
import { Terminal } from "@lucide/astro"
import {
  CodeBlock,
  CodeBlockHeader,
  CodeBlockTitle,
  CodeBlockActions,
  CodeBlockCopyButton,
  CodeBlockContent,
} from "@/components/ui/code-block"
const output = "$ bun run build\n\n✓ Build complete.\n✓ 12 pages generated."
---

<CodeBlock class="w-full max-w-xl">
  <CodeBlockHeader>
    <CodeBlockTitle>
      <Terminal />
      Terminal
    </CodeBlockTitle>
    <CodeBlockActions>
      <CodeBlockCopyButton value={output} />
    </CodeBlockActions>
  </CodeBlockHeader>
  <CodeBlockContent code={output} />
</CodeBlock>
```

## Installation

### Command

```sh
bunx --bun shadcn@latest add @gnostic/code-block
```

### Manual

Complete the [Installation guide](/docs/installation) first. Then copy the component files below.

Install the component packages:

```sh
bun add shiki
```

#### src/components/ui/code-block/code-block-actions.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"

type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---

<div
  data-slot="code-block-actions"
  class={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}
>
  <slot />
</div>
```

#### src/components/ui/code-block/code-block-content.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import CodeBlockLine from "./code-block-line.astro"
import { highlightCode } from "./highlight-code.ts"
import type { CodeBlockContentProps } from "./types.ts"

type Props = HTMLAttributes<"pre"> & CodeBlockContentProps
const {
  class: className,
  code,
  language,
  wrap = false,
  lineNumbers = false,
  startLine = 1,
  style,
  tabindex = 0,
  dir: _dir,
  ...props
} = Astro.props
const content =
  code === undefined ? await Astro.slots.render("default") : undefined
const highlighted =
  code !== undefined && language
    ? await highlightCode(code, language)
    : undefined
// Rendered slots are already escaped by Astro. Do not decode them as source.
const slotLines =
  lineNumbers &&
  content !== undefined &&
  !content.includes('data-slot="code-block-line"')
    ? content.replace(/\r?\n$/, "").split(/\r?\n/)
    : undefined
const lines =
  code !== undefined && lineNumbers && !highlighted
    ? code.replace(/\r?\n$/, "").split(/\r?\n/)
    : undefined
const firstLine = Number.isFinite(startLine)
  ? Math.max(1, Math.trunc(startLine))
  : 1
---

<pre
  data-slot="code-block-content"
  data-wrap={wrap || undefined}
  data-numbered={lineNumbers || undefined}
  tabindex={tabindex}
  style={
    typeof style === "string"
      ? `counter-reset:line ${firstLine - 1};${style}`
      : { counterReset: `line ${firstLine - 1}`, ...style }
  }
  class={cn("min-h-0 min-w-0 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:wrap-break-word data-wrap:whitespace-pre-wrap m-0 bg-transparent text-inherit whitespace-pre [scrollbar-width:thin]", className)}
  {...props}
  dir="ltr"
><code data-slot="code-block-code" class="grid min-h-lh min-w-max content-start in-data-numbered:grid-cols-[auto_1fr] in-data-wrap:min-w-0 [font-family:inherit] text-inherit">{highlighted ? highlighted.map((line) => <CodeBlockLine><Fragment set:html={line} /></CodeBlockLine>) : lines ? lines.map((line) => <CodeBlockLine>{line}</CodeBlockLine>) : slotLines ? slotLines.map((line) => <CodeBlockLine><Fragment set:html={line} /></CodeBlockLine>) : code !== undefined ? code : <Fragment set:html={content} />}</code></pre>
```

#### src/components/ui/code-block/code-block-copy-button.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { Check, Copy } from "@lucide/astro"
import { cn } from "cn"
import Button from "../button/button.astro"
import type { CodeBlockCopyButtonProps } from "./types.ts"

type Props = Omit<HTMLAttributes<"button">, "value"> & CodeBlockCopyButtonProps
const {
  class: className,
  value,
  variant = "ghost",
  size = "icon-xs",
  "aria-label": label = "Copy",
  ...props
} = Astro.props
---

<div data-slot="copy-button" class="contents">
  <Button
    data-slot="code-block-copy-button"
    data-copy-control
    data-value={value}
    variant={variant}
    size={size}
    aria-label={label}
    class={cn("shrink-0 group/code-copy", className)}
    {...props}
  >
    <slot>
      <Copy aria-hidden="true" class="group-data-copied/code-copy:hidden" />
      <Check
        aria-hidden="true"
        class="hidden group-data-copied/code-copy:block"
      />
    </slot>
  </Button>
  <span
    aria-live="polite"
    aria-atomic="true"
    class="sr-only"
    data-slot="copy-button-status"
  ></span>
</div>

<script>
  import {
    create,
    type CopyToClipboardController,
  } from "../copy-button/copy-to-clipboard.ts"

  const controllers: CopyToClipboardController[] = []
  const initialize = () => controllers.push(...create())
  initialize()
  document.addEventListener("astro:page-load", initialize)
  document.addEventListener("astro:before-swap", () => {
    for (const controller of controllers) controller.destroy()
    controllers.length = 0
  })
</script>
```

#### src/components/ui/code-block/code-block-footer.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"

type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---

<div
  data-slot="code-block-footer"
  class={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}
>
  <slot />
</div>
```

#### src/components/ui/code-block/code-block-header.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"

type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---

<div
  data-slot="code-block-header"
  class={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}
>
  <slot />
</div>
```

#### src/components/ui/code-block/code-block-line.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import { codeBlockLineVariants } from "./code-block-variants.ts"
import type { CodeBlockLineProps } from "./types.ts"

type Props = HTMLAttributes<"span"> & CodeBlockLineProps
const { class: className, variant = "default", ...props } = Astro.props
const content = await Astro.slots.render("default")
---

<span
  data-slot="code-block-line"
  data-variant={variant}
  class={cn(codeBlockLineVariants({ variant }), className)}
  {...props}
>
  <span
    data-slot="code-block-line-content"
    class="min-w-0 [&_[style]]:text-(--shiki-light) dark:[&_[style]]:text-(--shiki-dark)"
    set:html={content || "\n"}
  />
</span>
```

#### src/components/ui/code-block/code-block-title.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"

type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---

<div
  data-slot="code-block-title"
  class={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}
>
  <slot />
</div>
```

#### src/components/ui/code-block/code-block-variants.ts

```ts
import { cva } from 'class-variance-authority'

export const codeBlockVariants = cva("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 group/code-block", {
    variants: {
        variant: {
            default: "border border-input bg-muted ring-1 ring-foreground/5 text-foreground has-[>[data-slot=code-block-content]:focus-visible]:border-ring dark:ring-foreground/10",
            destructive: "border border-destructive/30 text-destructive",
        },
    },
    defaultVariants: { variant: 'default' },
})

export 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-success/10 after:text-success after:content-['+']",
            removed: "bg-destructive/10 after:text-destructive after:content-['-']",
            highlighted: "bg-muted",
        },
    },
    defaultVariants: { variant: 'default' },
})
```

#### src/components/ui/code-block/code-block.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import { codeBlockVariants } from "./code-block-variants.ts"
import type { CodeBlockProps } from "./types.ts"

type Props = HTMLAttributes<"div"> & CodeBlockProps
const {
  class: className,
  variant = "default",
  size = "default",
  ...props
} = Astro.props
---

<div
  data-slot="code-block"
  data-variant={variant}
  data-size={size}
  class={cn(codeBlockVariants({ variant }), className)}
  {...props}
>
  <slot />
</div>
```

#### src/components/ui/code-block/highlight-code.ts

```ts
// Server-only Astro port of shadcn/ui's highlighter (MIT).
import { createHighlighterCore, type HighlighterCore } from 'shiki/core'
import { createJavaScriptRegexEngine } from 'shiki/engine/javascript'

const languages = {
    astro: () => import('shiki/langs/astro.mjs'),
    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',
}

let highlighter: Promise<HighlighterCore> | undefined

function getHighlighter() {
    highlighter ??= createHighlighterCore({
        themes: [
            import('shiki/themes/github-light.mjs'),
            import('shiki/themes/github-dark.mjs'),
        ],
        langs: [],
        engine: createJavaScriptRegexEngine({ forgiving: true }),
    })

    return highlighter
}

function getLanguage(language: string) {
    const name = language.toLowerCase()

    if (name === 'ansi') {
        return name
    }

    if (Object.hasOwn(languages, name)) {
        return name as keyof typeof languages
    }

    return Object.hasOwn(aliases, name) ? aliases[name]! : null
}

/** Escape source and token styles before insertion into an Astro HTML slot. */
function escapeHtml(value: string) {
    return value
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
}

/** Return safe HTML for each line. Unknown languages return escaped plain lines. */
export async function highlightCode(
    code: string,
    language: string,
): Promise<string[]> {
    const source = code.replace(/\r?\n$/, '')
    const lang = getLanguage(language)
    if (!lang) return source.split(/\r?\n/).map(escapeHtml)
    const shiki = await getHighlighter()
    if (lang !== 'ansi' && !shiki.getLoadedLanguages().includes(lang)) {
        await shiki.loadLanguage(languages[lang])
    }
    const tokenize = (text: string) =>
        shiki.codeToTokens(text, {
            lang,
            themes: { light: 'github-light', dark: 'github-dark' },
            defaultColor: false,
        }).tokens
    const tokens =
        lang === 'ansi'
            ? source.split(/\r?\n/).flatMap(tokenize)
            : tokenize(source)
    return tokens.map((line) =>
        line
            .map((token) => {
                const style = Object.entries(token.htmlStyle ?? {})
                    .map(([key, value]) => `${key}:${value}`)
                    .join(';')
                return `<span style="${escapeHtml(style)}">${escapeHtml(token.content)}</span>`
            })
            .join(''),
    )
}
```

#### src/components/ui/code-block/index.ts

```ts
export { default as CodeBlock } from './code-block.astro'
export { default as CodeBlockHeader } from './code-block-header.astro'
export { default as CodeBlockTitle } from './code-block-title.astro'
export { default as CodeBlockActions } from './code-block-actions.astro'
export { default as CodeBlockCopyButton } from './code-block-copy-button.astro'
export { default as CodeBlockContent } from './code-block-content.astro'
export { default as CodeBlockLine } from './code-block-line.astro'
export { default as CodeBlockFooter } from './code-block-footer.astro'

export type {
    CodeBlockProps,
    CodeBlockContentProps,
    CodeBlockLineProps,
    CodeBlockCopyButtonProps,
} from './types.ts'
```

#### src/components/ui/code-block/types.ts

```ts
import type { ButtonVariantProps } from '../button/button-variants.ts'

/** The surface around a code sample or terminal output. */
export interface CodeBlockProps {
    /** The tone of the block. @default 'default' */
    variant?: 'default' | 'destructive'
    /** The spacing and text size. @default 'default' */
    size?: 'default' | 'sm'
}

/** Code content. Use the default slot for composed CodeBlockLine parts. */
export interface CodeBlockContentProps {
    /** Plain source text. Takes precedence over the default slot. */
    code?: string
    /** Highlight `code` on the server with Shiki. Unknown languages stay plain. */
    language?: string
    /** Wrap long lines. @default false */
    wrap?: boolean
    /** Show line numbers outside the selectable text. @default false */
    lineNumbers?: boolean
    /** The first line number. @default 1 */
    startLine?: number
}

/** A single line with an optional diff or highlight state. */
export interface CodeBlockLineProps {
    /** The state of the line. @default 'default' */
    variant?: 'default' | 'added' | 'removed' | 'highlighted'
}

/** A Button that copies the supplied source text. */
export interface CodeBlockCopyButtonProps extends ButtonVariantProps {
    /** The exact text to copy, without line numbers or diff markers. */
    value: string
}
```

Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.


## Usage

```astro
---
import {
  CodeBlock,
  CodeBlockHeader,
  CodeBlockTitle,
  CodeBlockActions,
  CodeBlockCopyButton,
  CodeBlockContent,
} from "@/components/ui/code-block"

const output = "bun run build"
---

<CodeBlock>
  <CodeBlockHeader>
    <CodeBlockTitle>Terminal</CodeBlockTitle>
    <CodeBlockActions>
      <CodeBlockCopyButton value={output} />
    </CodeBlockActions>
  </CodeBlockHeader>
  <CodeBlockContent code={output} />
</CodeBlock>
```

## Composition

```text
CodeBlock
├── CodeBlockHeader
│   ├── CodeBlockTitle
│   └── CodeBlockActions
│       └── CodeBlockCopyButton
├── CodeBlockActions (floating, without a header)
├── CodeBlockContent
│   └── CodeBlockLine
└── CodeBlockFooter
```

Pass plain text through `code` or the default slot. Use `CodeBlockLine` parts
in the slot for individual line states. Header, title, actions, and footer
accept HTML attributes and default slots. Wrap the title in an anchor to link
to a file. Place each block in a `TabsContent` to show multiple files.

## Tabs

Show several files with one `CodeBlock` in each `TabsContent`. Each panel has its
own title, highlighted source, line numbers, and copy button. This ports the
[shadcn tabs example](https://ui.shadcn.com/docs/components/base/code-block#tabs)
to Astro. The React and API code shown in the panels is sample text.

```astro
---
import {
  CodeBlock,
  CodeBlockActions,
  CodeBlockContent,
  CodeBlockCopyButton,
  CodeBlockHeader,
  CodeBlockTitle,
} from "@/components/ui/code-block"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"

const files = [
  {
    id: "route",
    title: "app/api/chat/route.ts",
    language: "ts",
    code: `import { streamText } from "ai"

export async function POST(request: Request) {
  const { messages } = await request.json()
  const result = streamText({ model: "anthropic/claude-sonnet-4.5", messages })

  return result.toUIMessageStreamResponse()
}`,
  },
  {
    id: "chat",
    title: "components/chat.tsx",
    language: "tsx",
    code: `"use client"

import { useChat } from "@ai-sdk/react"

export function Chat() {
  const { messages } = useChat()

  return <MessageList messages={messages} />
}`,
  },
  {
    id: "env",
    title: ".env.local",
    language: "bash",
    code: "AI_GATEWAY_API_KEY=your-api-key",
  },
]
---

<Tabs defaultValue="route" class="w-full max-w-md">
  <TabsList aria-label="Code files">
    {files.map((file) => (
      <TabsTrigger value={file.id}>{file.title.split("/").at(-1)}</TabsTrigger>
    ))}
  </TabsList>
  {files.map((file) => (
    <TabsContent value={file.id} hidden={file.id !== "route"}>
      <CodeBlock>
        <CodeBlockHeader>
          <CodeBlockTitle>{file.title}</CodeBlockTitle>
          <CodeBlockActions>
            <CodeBlockCopyButton value={file.code} />
          </CodeBlockActions>
        </CodeBlockHeader>
        <CodeBlockContent
          code={file.code}
          language={file.language}
          lineNumbers
        />
      </CodeBlock>
    </TabsContent>
  ))}
</Tabs>
```

## Floating actions

Put actions directly inside the root to show them on hover or keyboard focus.
They stay visible on touch screens.

```astro
---
import {
  CodeBlock,
  CodeBlockActions,
  CodeBlockCopyButton,
  CodeBlockContent,
} from "@/components/ui/code-block"
const output = "bun add astro\nbun run dev"
---

<CodeBlock class="w-full max-w-xl">
  <CodeBlockActions>
    <CodeBlockCopyButton value={output} />
  </CodeBlockActions>
  <CodeBlockContent>{output}</CodeBlockContent>
</CodeBlock>
```

## Line numbers and syntax highlighting

Set `lineNumbers` and use `startLine` for a sample from the middle of a file.
The line number column grows to fit its content. Use `language` with `code`
for server-side syntax highlighting. Shiki does not enter the browser bundle.

```astro
---
import {
  CodeBlock,
  CodeBlockHeader,
  CodeBlockTitle,
  CodeBlockContent,
} from "@/components/ui/code-block"
const code =
  'const project = {\n  name: "Atlas",\n  private: true,\n}\n\nexport default project'
---

<CodeBlock class="w-full max-w-xl">
  <CodeBlockHeader>
    <CodeBlockTitle>project.ts</CodeBlockTitle>
  </CodeBlockHeader>
  <CodeBlockContent code={code} language="ts" lineNumbers startLine={24} />
</CodeBlock>
```

## Diff and highlighted lines

Use `added`, `removed`, or `highlighted` on each `CodeBlockLine`. Diff markers
use a symbol and a color. Line numbers and markers are not part of the copied
source. Empty lines retain their height and selectable newline.

For highlighted lines, import `highlightCode` from
`@/components/ui/code-block/highlight-code` in Astro frontmatter. It returns
an array of escaped HTML strings. Put each result in a `CodeBlockLine` with
`<Fragment set:html={line} />`.

```astro
---
import {
  CodeBlock,
  CodeBlockHeader,
  CodeBlockTitle,
  CodeBlockContent,
  CodeBlockLine,
} from "@/components/ui/code-block"
import { highlightCode } from "@/components/ui/code-block/highlight-code"
const code =
  "export const config = {\n  retries: 1,\n  retries: 3,\n  timeout: 5000,\n}"
const lines = await highlightCode(code, "ts")
---

<CodeBlock class="w-full max-w-xl">
  <CodeBlockHeader>
    <CodeBlockTitle>config.ts</CodeBlockTitle>
  </CodeBlockHeader>
  <CodeBlockContent lineNumbers>
    {lines.map((line, index) => (
      <CodeBlockLine
        variant={
          index === 1
            ? "removed"
            : index === 2
              ? "added"
              : index === 3
                ? "highlighted"
                : "default"
        }
      >
        <Fragment set:html={line} />
      </CodeBlockLine>
    ))}
  </CodeBlockContent>
</CodeBlock>
```

## Wrap, small size, and errors

Use `wrap` to wrap long lines, `size="sm"` for compact output, and
`variant="destructive"` for errors. A caller-owned button can change the
content's `data-wrap` attribute. Keep its `aria-pressed` state in sync.

```astro
---
import {
  CodeBlock,
  CodeBlockHeader,
  CodeBlockTitle,
  CodeBlockActions,
  CodeBlockCopyButton,
  CodeBlockContent,
} from "@/components/ui/code-block"
import { Button } from "@/components/ui/button"
const output =
  "Error: The request exceeds the configured size limit. Reduce the number of records, then send the request again."
---

<CodeBlock variant="destructive" size="sm" class="w-full max-w-xl">
  <CodeBlockHeader>
    <CodeBlockTitle>Error</CodeBlockTitle>
    <CodeBlockActions>
      <Button variant="ghost" size="xs" aria-pressed="true" data-code-wrap>
        Wrap lines
      </Button>
      <CodeBlockCopyButton value={output} />
    </CodeBlockActions>
  </CodeBlockHeader>
  <CodeBlockContent code={output} wrap />
</CodeBlock>
<script>
  document.addEventListener("click", (event) => {
    const button =
      event.target instanceof Element
        ? event.target.closest("[data-code-wrap]")
        : null
    if (!button) return
    const content = button
      .closest('[data-slot="code-block"]')
      ?.querySelector('[data-slot="code-block-content"]')
    const wrap = button.getAttribute("aria-pressed") !== "true"
    button.setAttribute("aria-pressed", String(wrap))
    content?.toggleAttribute("data-wrap", wrap)
  })
</script>
```

## Height and footer

Limit the content height with a `max-h-*` class. Use the footer for a Show More
button. Keep `aria-expanded` in sync and point `aria-controls` at the content.

```astro
---
import {
  CodeBlock,
  CodeBlockHeader,
  CodeBlockTitle,
  CodeBlockContent,
  CodeBlockFooter,
} from "@/components/ui/code-block"
import { Button } from "@/components/ui/button"
const id = `code-log-${crypto.randomUUID()}`
const output = Array.from(
  { length: 20 },
  (_, index) => `[${String(index + 1).padStart(2, "0")}] GET /api/projects 200`,
).join("\n")
---

<CodeBlock class="w-full max-w-xl">
  <CodeBlockHeader>
    <CodeBlockTitle>Request log</CodeBlockTitle>
  </CodeBlockHeader>
  <CodeBlockContent id={id} code={output} class="max-h-36" />
  <CodeBlockFooter class="justify-center">
    <Button
      variant="ghost"
      size="xs"
      aria-expanded="false"
      aria-controls={id}
      data-code-expand
    >
      Show more
    </Button>
  </CodeBlockFooter>
</CodeBlock>
<script>
  document.addEventListener("click", (event) => {
    const button =
      event.target instanceof Element
        ? event.target.closest("[data-code-expand]")
        : null
    if (!button) return
    const content = document.getElementById(
      button.getAttribute("aria-controls") ?? "",
    )
    const expanded = button.getAttribute("aria-expanded") !== "true"
    button.setAttribute("aria-expanded", String(expanded))
    button.textContent = expanded ? "Show less" : "Show more"
    content?.classList.toggle("max-h-36", !expanded)
    content?.classList.toggle("max-h-80", expanded)
  })
</script>
```

## Terminal colors

Use `language="ansi"` to show terminal colors. Each line starts with fresh
ANSI state, as in the shadcn component.

```astro
---
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block"
const output =
  "$ bun test\n\u001b[32m✓\u001b[39m parser.test.ts (4 tests)\n\u001b[31m✗\u001b[39m format.test.ts (1 failed)"
---

<CodeBlock class="w-full max-w-xl">
  <CodeBlockContent code={output} language="ansi" />
</CodeBlock>
```

## Inside Typeset

Typeset leaves elements with `data-slot` and their contents unchanged. A direct
child component gets the same space above it as a paragraph. Code Block needs
no `data-not-typeset` attribute. Plain `pre` and `code` elements keep their text
styles.

```astro
---
import {
  CodeBlock,
  CodeBlockHeader,
  CodeBlockTitle,
  CodeBlockActions,
  CodeBlockCopyButton,
  CodeBlockContent,
} from "@/components/ui/code-block"

const code = 'const message = "Hello, Astro"\nconsole.log(message)'
---

<div class="typeset w-full max-w-xl">
  <h3>Run the example</h3>
  <p>
    Save this code in <code>hello.ts</code>.
  </p>
  <CodeBlock>
    <CodeBlockHeader>
      <CodeBlockTitle>hello.ts</CodeBlockTitle>
      <CodeBlockActions>
        <CodeBlockCopyButton value={code} />
      </CodeBlockActions>
    </CodeBlockHeader>
    <CodeBlockContent code={code} language="ts" lineNumbers />
  </CodeBlock>
  <p>Then run the file in your terminal.</p>
  <pre><code>bun hello.ts</code></pre>
</div>
```

## Astro port notes

This component follows the [shadcn Code Block](https://ui.shadcn.com/docs/components/base/code-block)
composition. Coss does not supply this component. The shared Gnostic recipe
uses the same layout with semantic success and destructive colors. Shadcn presets
use their upstream Code Block recipes. Gnostic, Soft, and Glow use the shared
Gnostic recipe with their own color, font, and radius tokens.

Use Astro `class`, slots, and scripts. There are no React hooks or render props.
Rendering and highlighting run on the server. Incremental client highlighting
and Streamdown integration are not included. Native scrolling is used; the
upstream scroll-fade utilities are not included.

Supported languages are Astro, Bash, CSS, diff, HTML, JavaScript, JSON, JSX,
Markdown, Python, SQL, TSX, TypeScript, YAML, and ANSI. Common short names such
as `ts`, `js`, `sh`, and `yml` work. Unknown languages render as plain text.
One final newline is omitted when text is split into lines. The copy button
always copies its exact `value`, including final newlines.

## Accessibility

Code always reads left to right. The header follows the page direction.
Content has `tabindex="0"` so keyboard users can scroll it. Set
`tabindex={-1}` to remove this tab stop. Line numbers use CSS counters with
empty alternative text where the browser supports it.

The copy button uses the shared [Copy Button controller](/components/copy-button).
It has an accessible label and a polite status message. It reports
copy failure if the Clipboard API is unavailable or permission is denied.
Clipboard access requires a secure context, such as HTTPS or localhost.
Native button attributes, including `disabled`, pass through.

## API Reference

### CodeBlockProps

<AutoTypeTable
    path="../../packages/ui/src/components/ui/code-block/types.ts"
    name="CodeBlockProps"
/>

### CodeBlockContentProps

<AutoTypeTable
    path="../../packages/ui/src/components/ui/code-block/types.ts"
    name="CodeBlockContentProps"
/>

### CodeBlockLineProps

<AutoTypeTable
    path="../../packages/ui/src/components/ui/code-block/types.ts"
    name="CodeBlockLineProps"
/>

### CodeBlockCopyButtonProps

Accepts the shared Button `variant` and `size` props. Defaults are `ghost` and
`icon-xs`. Use the default slot to replace the copy and check icons.

<AutoTypeTable
    path="../../packages/ui/src/components/ui/code-block/types.ts"
    name="CodeBlockCopyButtonProps"
/>

Read the [installed source](/r/code-block.json) for the complete prop types.

## Theme and layout

Code Block uses the project preset for its frame and controls. Set a maximum content height for long examples, and choose wrapping or scrolling to suit the code. Keep copy controls reachable at narrow widths. Use [Tabs](/components/tabs) for related code samples and [Typeset](/docs/theming#text-and-headings) for the surrounding guide.
