Skip to content
Esc
↑↓navigate↵open⌘Jpreview
On this page

Code Block for Astro

Composable Astro code blocks with copy controls, line numbers, diff states, and syntax highlighting.

Terminal
$ bun run build

✓ Build complete.
✓ 12 pages generated.

Installation

bunx --bun shadcn@latest add @gnostic/code-block
npx shadcn@latest add @gnostic/code-block
pnpm dlx shadcn@latest add @gnostic/code-block

Component classes: Default Gnostic.

Complete the Installation guide first. Then copy the component files below.

Install component packages

bun add shiki

Copy the files

src/components/ui/code-block/code-block-actions.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
---
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
---
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
---
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
---
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
---
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
---
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
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
---
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
// 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
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
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
}

Usage

---
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

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 to Astro. The React and API code shown in the panels is sample text.

app/api/chat/route.ts
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()}

Floating actions

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

bun add astro
bun run dev

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.

project.ts
const project = {  name: "Atlas",  private: true,}
export default project

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} />.

config.ts
export const config = {  retries: 1,  retries: 3,  timeout: 5000,}

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.

Error
Error: The request exceeds the configured size limit. Reduce the number of records, then send the request again.

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.

Request log
[01] GET /api/projects 200
[02] GET /api/projects 200
[03] GET /api/projects 200
[04] GET /api/projects 200
[05] GET /api/projects 200
[06] GET /api/projects 200
[07] GET /api/projects 200
[08] GET /api/projects 200
[09] GET /api/projects 200
[10] GET /api/projects 200
[11] GET /api/projects 200
[12] GET /api/projects 200
[13] GET /api/projects 200
[14] GET /api/projects 200
[15] GET /api/projects 200
[16] GET /api/projects 200
[17] GET /api/projects 200
[18] GET /api/projects 200
[19] GET /api/projects 200
[20] GET /api/projects 200

Terminal colors

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

$ bun test✓ parser.test.ts (4 tests)✗ format.test.ts (1 failed)

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.

Run the example

Save this code in hello.ts.

hello.ts
const message = "Hello, Astro"console.log(message)

Then run the file in your terminal.

bun hello.ts

Astro port notes

This component follows the shadcn 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. 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

PropType
variant?'default' | 'destructive'

The tone of the block.

Type'default' | 'destructive'
Default'default'
size?'default' | 'sm'

The spacing and text size.

Type'default' | 'sm'
Default'default'

CodeBlockContentProps

PropType
code?string

Plain source text. Takes precedence over the default slot.

Typestring
language?string

Highlight `code` on the server with Shiki. Unknown languages stay plain.

Typestring
wrap?boolean

Wrap long lines.

Typeboolean
Defaultfalse
lineNumbers?boolean

Show line numbers outside the selectable text.

Typeboolean
Defaultfalse
startLine?number

The first line number.

Typenumber
Default1

CodeBlockLineProps

PropType
variant?'default' | 'added' | 'removed' | 'highlighted'

The state of the line.

Type'default' | 'added' | 'removed' | 'highlighted'
Default'default'

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.

PropType
valuestring

The exact text to copy, without line numbers or diff markers.

Typestring
variant?"outline" | "default" | "glass" | "surface" | "destructive-outline" | "destructive" | "ghost" | "link" | "secondary" | null | undefined
Type"outline" | "default" | "glass" | "surface" | "destructive-outline" | "destructive" | "ghost" | "link" | "secondary" | null | undefined
size?"icon" | "icon-xs" | "icon-sm" | "icon-lg" | "icon-xl" | "default" | "lg" | "sm" | "xl" | "xs" | null | undefined
Type"icon" | "icon-xs" | "icon-sm" | "icon-lg" | "icon-xl" | "default" | "lg" | "sm" | "xl" | "xs" | null | undefined

Read the installed source 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 for related code samples and Typeset for the surrounding guide.