Code Block
Code with syntax colors in SF Mono, a title, line numbers and a copy button.
@cupertinoui/code-blockRegistry JSON "use client"
import { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton, CodeBlockHeader, CodeBlockLine, CodeBlockTitle } from "@/components/ui/code-block"
import { useHighlightedCode } from "@/registry/macos/hooks/use-highlighted-code"
const code = `import SwiftUI
struct ContentView: View {
var body: some View {
Text("Hello, world!")
.padding()
}
}`
const tsx = `export function Greeting() {
return <Button variant="secondary">Hello, world!</Button>
}`
export default function CodeBlockDemo() {
const lines = useHighlightedCode(tsx, "tsx")
return (
<div className="flex w-full max-w-lg flex-col gap-4">
<CodeBlock>
<CodeBlockHeader>
<CodeBlockTitle>greeting.tsx</CodeBlockTitle>
<CodeBlockActions>
<CodeBlockCopyButton value={tsx} />
</CodeBlockActions>
</CodeBlockHeader>
<CodeBlockContent>
{lines.map((line, index) => (
<CodeBlockLine key={index}>{line}</CodeBlockLine>
))}
</CodeBlockContent>
</CodeBlock>
<CodeBlock size="sm">
<CodeBlockContent lineNumbers>{code}</CodeBlockContent>
</CodeBlock>
</div>
)
}Installation
pnpm dlx shadcn@latest add @cupertinoui/code-blockThe first install also adds the macOS theme. See Installation to set up the registry.
Usage
import { CodeBlock, CodeBlockContent, CodeBlockLine } from "@/components/ui/code-block"
import { useHighlightedCode } from "@/hooks/use-highlighted-code"
const lines = useHighlightedCode(code, "tsx")
<CodeBlock>
<CodeBlockContent>
{lines.map((line, i) => <CodeBlockLine key={i}>{line}</CodeBlockLine>)}
</CodeBlockContent>
</CodeBlock>useHighlightedCode colors code with Shiki in the browser, loading each language the first time it is used, and keeps up with code that streams in.
API Reference
Every part forwards the props of the underlying element. The props below are the ones CupertinoUI adds or changes.
CodeBlockContent
| Prop | Type | Description |
|---|---|---|
lineNumbers | booleanDefault: false | Numbers the lines. |
wrap | booleanDefault: false | Wraps long lines. |
className | string | Extra classes, merged with the component's own. |
CodeBlockLine
| Prop | Type | Description |
|---|---|---|
variant | "default" | "added" | "removed" | "highlighted"Default: "default" | Marks a line, e.g. in a diff. |
className | string | Extra classes, merged with the component's own. |
CodeBlockCopyButton
| Prop | Type | Description |
|---|---|---|
value | string | The text to copy. |
className | string | Extra classes, merged with the component's own. |