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

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

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.