Code Block
An opinionated, server-highlighted code block. Ships Shiki coloured by the kit's own ramps (brand keywords, accent functions, success strings, warning constants), a copy button, optional line numbers, and dual-theme dark mode with zero client-side highlighting JavaScript. CodeBlockClient draws the same block inside a client component.
Installation
npx shadcn@latest add https://ui.mattdowney.com/r/code-block.jsonUsage
import { CodeBlock } from "@/components/ui/code-block"Examples
Default
A block of code with a copy button. Render it from a server file: it is an async component, and a client component cannot render it.
import { Button } from "@/components/ui/button"
export function Example() {
return <Button variant="subtle">Save changes</Button>
}Line numbers
Prefix each line with its number via showLineNumbers.
import { Button } from "@/components/ui/button"
export function Example() {
return <Button variant="subtle">Save changes</Button>
}Languages
Loaded up front: tsx, ts, jsx, js, bash, css, json, html, markdown, yaml. Any other language Shiki ships, like toml here, loads the first time a block asks for it. An unknown one renders as plain text.
npx shadcn@latest add https://ui.mattdowney.com/r/button.json{
"name": "ui.md",
"type": "registry:ui"
}[package]
name = "ui-md"
version = "1.0.0"In a client component
CodeBlockClient for code inside a client tree, such as markdown rendered in the browser. The box and copy button render at once and the colours follow; pass html from highlightCode to skip that step.
title: Design gaps
tags:
- kit
- registry
draft: falseAPI Reference
| Prop | Type | Default | Description |
|---|---|---|---|
| code*CodeBlock | string | None | The source to highlight. Leading and trailing whitespace is trimmed. |
| languageCodeBlock | string | "tsx" | Language grammar to highlight with: any language Shiki ships. The common ten load with the highlighter and the rest on first use, so they cost nothing until a block asks. An unknown language falls back to plain text. |
| htmlCodeBlockClient | string | None | HTML from highlightCode(code, language), an async server helper exported by code-block. With it the block arrives coloured and the browser loads no highlighter. Without it the code shows plain, then Shiki loads in the browser and colours it. The other props work as on CodeBlock. |
| showLineNumbersCodeBlock | boolean | false | Prefixes each line with its line number. |
| framedCodeBlock | boolean | true | Draws the block's own surface (edge, radius, fill). Turn it off to set the code inside a surface that already has one, such as a tab in a Card; the code keeps its inset and the copy button. |
| classNameCodeBlock | string | None | Merged onto the frame (the Card, or the plain wrapper when framed is off). |
| revealCopyButton | "hover" | "always" | "hover" | hover shows the button only while the pointer or focus is inside a group/code parent (always on touch). always keeps it shown, for a box with no such parent. |
| onCopyCopyButton | () => void | None | Called after the text reaches the clipboard, never on a failed write. For analytics or a toast. |
| code*CodeBlockstringThe source to highlight. Leading and trailing whitespace is trimmed. |
| languageCodeBlockstring = "tsx"Language grammar to highlight with: any language Shiki ships. The common ten load with the highlighter and the rest on first use, so they cost nothing until a block asks. An unknown language falls back to plain text. |
htmlCodeBlockClientstringHTML from highlightCode(code, language), an async server helper exported by code-block. With it the block arrives coloured and the browser loads no highlighter. Without it the code shows plain, then Shiki loads in the browser and colours it. The other props work as on CodeBlock. |
| showLineNumbersCodeBlockboolean = falsePrefixes each line with its line number. |
| framedCodeBlockboolean = trueDraws the block's own surface (edge, radius, fill). Turn it off to set the code inside a surface that already has one, such as a tab in a Card; the code keeps its inset and the copy button. |
classNameCodeBlockstringMerged onto the frame (the Card, or the plain wrapper when framed is off). |
revealCopyButton"hover" | "always" = "hover"hover shows the button only while the pointer or focus is inside a group/code parent (always on touch). always keeps it shown, for a box with no such parent. |
| onCopyCopyButton() => voidCalled after the text reaches the clipboard, never on a failed write. For analytics or a toast. |
import { bundledLanguages, createHighlighter, type BundledLanguage, type Highlighter } from "shiki"
import { CodeBlockFrame } from "@/registry/ui/code-block-client"
import { CODE_BLOCK_THEMES, CODE_BLOCK_THEME_REGISTRATIONS } from "@/registry/ui/code-block-themes"
// @use-when a syntax-highlighted code sample rendered from a Server Component.
// From a client component use CodeBlockClient, which highlights in the browser.
// UI.MD ships an opinionated highlighter: Shiki coloured by the kit's own ramps
// through `--code-*` variables, so one render serves both color schemes, and the
// highlighting runs on the server, so it adds no JavaScript to the page.
// Loaded with the highlighter, because most pages use them. Every other
// language Shiki ships loads the first time a block asks for it, so a `rust` or
// `toml` block works without adding weight to the pages that never use one. An
// unknown language falls back to plain text instead of throwing.
const LANGUAGES = [
"tsx",
"ts",
"jsx",
"js",
"bash",
"css",
"json",
"html",
"markdown",
"yaml",
]
// Module-level singleton so the grammar and theme load happens once per server
// process, not once per code block.
let highlighterPromise: Promise<Highlighter> | null = null
const languageLoads = new Map<string, Promise<boolean>>()
function getHighlighter() {
if (!highlighterPromise) {
highlighterPromise = createHighlighter({
themes: CODE_BLOCK_THEME_REGISTRATIONS,
langs: LANGUAGES,
})
}
return highlighterPromise
}
async function resolveLanguage(highlighter: Highlighter, language: string) {
if (highlighter.getLoadedLanguages().includes(language)) return language
let load = languageLoads.get(language)
if (!load) {
load = language in bundledLanguages
? highlighter.loadLanguage(language as BundledLanguage).then(() => true, () => false)
: Promise.resolve(false)
languageLoads.set(language, load)
}
return (await load) ? language : "text"
}
/**
* Highlight on the server and get the HTML `CodeBlockClient` takes as `html`,
* for a client tree that should arrive with its colours.
*/
export async function highlightCode(code: string, language = "tsx") {
const highlighter = await getHighlighter()
const lang = await resolveLanguage(highlighter, language)
return highlighter.codeToHtml(code.trim(), { lang, themes: CODE_BLOCK_THEMES })
}
export async function CodeBlock({
code,
language = "tsx",
showLineNumbers = false,
framed = true,
className,
}: {
code: string
language?: string
showLineNumbers?: boolean
/** Draw the block's own surface (edge, radius, fill). Turn it off to set the
* code inside a surface that already has one, such as a tab in a Card. The
* code keeps its inner inset and the copy button stays. */
framed?: boolean
className?: string
}) {
const trimmed = code.trim()
const html = await highlightCode(trimmed, language)
return (
<CodeBlockFrame
code={trimmed}
html={html}
showLineNumbers={showLineNumbers}
framed={framed}
className={className}
/>
)
}"use client"
import { useCallback, useEffect, useRef, useState } from "react"
import { IconCheck as Check, IconCopy as Copy } from "@tabler/icons-react"
import { cn } from "@/registry/lib/utils"
const ICON_LAYER =
"col-start-1 row-start-1 flex transition-[opacity,scale] duration-small ease-small motion-reduce:transition-[opacity]"
// @component CopyButton
// @use-when a copy affordance on a code sample. `CodeBlock` already
// includes one, so reach for this only when composing your own.
export function CopyButton({
text,
reveal = "hover",
variant = "card",
onCopy,
className,
}: {
text: string
/**
* `"hover"` hides the button until the pointer or focus enters the nearest
* `group/code` parent (always shown on touch). `"always"` keeps it shown,
* for a box with no such parent or one short enough that a hidden button
* reads as missing.
*/
reveal?: "hover" | "always"
/**
* `"card"` sits on a card fill so it covers the code it floats over.
* `"ghost"` is transparent until hover, with Button ghost's accent tint, for
* a header band or toolbar that is not code: a card fill there reads as a
* stray box.
*/
variant?: "card" | "ghost"
/** Called after the text has reached the clipboard, never on a failed write. */
onCopy?: () => void
className?: string
}) {
const [copied, setCopied] = useState(false)
const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
useEffect(() => {
return () => {
if (timerRef.current) clearTimeout(timerRef.current)
}
}, [])
const handleCopy = useCallback(async () => {
try {
await navigator.clipboard.writeText(text)
} catch {
return
}
onCopy?.()
setCopied(true)
if (timerRef.current) clearTimeout(timerRef.current)
timerRef.current = setTimeout(() => setCopied(false), 1500)
}, [text, onCopy])
return (
<button
type="button"
data-slot="copy-button"
onClick={handleCopy}
aria-label={copied ? "Copied" : "Copy to clipboard"}
className={cn(
// Revealed on hover/focus, always visible on touch where hover doesn't exist.
// The declared set, not the bare `transition` preset: the preset also
// covers transform and filter, which this button never changes, so
// full motion and reduced motion animate the same three properties
// and no separate motion-reduce narrowing is needed.
"inline-flex size-7 pointer-coarse:size-11 items-center justify-center rounded-action-sm text-subtle-foreground outline-none transition-[opacity,color,background-color] focus-visible:ring-[3px] focus-visible:ring-ring-focus",
variant === "card" && "bg-card hover:bg-muted hover:text-foreground",
variant === "ghost" &&
"bg-transparent hover:bg-accent-100 hover:text-accent-700 dark:hover:bg-accent-800 dark:hover:text-accent-200",
reveal === "hover" &&
"opacity-0 group-hover/code:opacity-100 group-focus-within/code:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100",
className
)}
>
{/* Both glyphs stay mounted and cross-fade with a small scale (on the
wrapper: the kit's icon rule owns the svg's own scale), so the swap
to the check never hard-cuts. Reduced motion keeps the fade. */}
<span className="grid place-items-center">
<span className={cn(ICON_LAYER, copied ? "scale-75 opacity-0 motion-reduce:scale-100" : "scale-100 opacity-100")}>
<Copy aria-hidden="true" className="size-3.5" />
</span>
<span className={cn(ICON_LAYER, copied ? "scale-100 opacity-100" : "scale-75 opacity-0 motion-reduce:scale-100")}>
<Check aria-hidden="true" className="size-3.5" />
</span>
</span>
</button>
)
}"use client"
import { useEffect, useState } from "react"
import type { Highlighter } from "shiki"
import { cn } from "@/registry/lib/utils"
import { ScrollFade } from "@/registry/ui/scroll-fade"
import { CopyButton } from "@/registry/ui/code-block-copy-button"
import { CODE_BLOCK_THEMES, CODE_BLOCK_THEME_REGISTRATIONS } from "@/registry/ui/code-block-themes"
type CodeBlockFrameProps = {
/** The trimmed source, for the copy button and the plain fallback. */
code: string
/** Shiki's output. Without it the code renders plain in the same box. */
html?: string | null
showLineNumbers?: boolean
framed?: boolean
className?: string
}
// The surface both code blocks draw in: the server `CodeBlock` hands it Shiki's
// HTML, `CodeBlockClient` hands it plain code first and the HTML once the
// browser has highlighted it.
export function CodeBlockFrame({
code,
html,
showLineNumbers = false,
framed = true,
className,
}: CodeBlockFrameProps) {
// Single-line snippets center the copy button vertically; multi-line pins it
// to the top-right so it never sits over a wrapped line.
const singleLine = !code.includes("\n")
const inner = cn(
// CodeBlock owns its inner <pre> completely, so a surrounding prose
// renderer (Prose, Tailwind Typography) can't paint a second surface on it:
// the frame is the only surface. Radius and shadow are reset too, or
// Prose's pre ring draws a container-in-container inside the frame.
"w-max min-w-full p-4 pe-12 text-sm [&_pre]:!bg-transparent [&_pre]:!p-0 [&_pre]:!rounded-none [&_pre]:!shadow-none [&_code]:!text-xs [&_code]:!leading-relaxed",
showLineNumbers &&
"[&_.line]:before:me-4 [&_.line]:before:inline-block [&_.line]:before:w-4 [&_.line]:before:text-end [&_.line]:before:text-subtle-foreground [&_.line]:before:content-[counter(line)] [&_.line]:before:[counter-increment:line] [&_pre]:[counter-reset:line]"
)
return (
// Framed, it is a WELL, not a card: Input's fill and a 1px border, no
// shadow. Code is read and copied, never clicked, and a raised card with a
// ring reads as something to press. Every docs and setup screen surveyed
// (PlanetScale, Neon, Featurebase, Google Analytics) sinks its code the
// same way. A grey fill alone would vanish on the light page background.
<div
data-slot="code-block"
className={cn(
"group/code relative",
framed && "flex flex-col overflow-clip rounded-lg border border-border bg-input-bg bg-clip-padding text-foreground",
className
)}
>
<CopyButton
text={code}
className={cn(
"absolute end-2 z-10",
singleLine ? "top-1/2 -translate-y-1/2" : "top-2"
)}
/>
{/* A long line scrolls sideways under a custom overlay scrollbar, and the
right skim fades it out before it reaches the copy button. The
content is `w-max min-w-full` so it is as wide as its longest line,
and `pr-12` lets the last characters scroll clear of the skim and the
button (size-7 at right-2 is 36px in; 48 leaves a 12px gap). */}
<ScrollFade orientation="horizontal" skimHeight={40}>
{html ? (
<div className={inner} dangerouslySetInnerHTML={{ __html: html }} />
) : (
// Shiki's markup shape (`pre > code > span.line`, a newline between
// lines), so line numbers and spacing match the highlighted form and
// nothing moves when the colours arrive.
<div className={inner}>
<pre className="text-foreground">
<code>
{code.split("\n").map((line, i) => (
<span key={i}>
{i > 0 && "\n"}
<span className="line">{line}</span>
</span>
))}
</code>
</pre>
</div>
)}
</ScrollFade>
</div>
)
}
// One highlighter per page, made on first use. The JavaScript regex engine
// keeps the WebAssembly one out of the browser, and each grammar is fetched
// only when a block in that language mounts.
let highlighterPromise: Promise<Highlighter> | null = null
const languageLoads = new Map<string, Promise<boolean>>()
async function highlightInBrowser(code: string, language: string) {
const shiki = await import("shiki")
if (!highlighterPromise) {
highlighterPromise = import("shiki/engine/javascript").then(({ createJavaScriptRegexEngine }) =>
shiki.createHighlighter({
themes: CODE_BLOCK_THEME_REGISTRATIONS,
langs: [],
engine: createJavaScriptRegexEngine(),
})
)
}
const highlighter = await highlighterPromise
let load = languageLoads.get(language)
if (!load) {
load = language in shiki.bundledLanguages
? highlighter
.loadLanguage(language as keyof typeof shiki.bundledLanguages)
.then(() => true, () => false)
: Promise.resolve(false)
languageLoads.set(language, load)
}
const lang = (await load) ? language : "text"
return highlighter.codeToHtml(code, { lang, themes: CODE_BLOCK_THEMES })
}
/**
* `CodeBlock` for a client tree. It draws the same box at once with the code
* plain, then highlights in the browser after mount. Pass `html` from
* `highlightCode` (a server helper in `code-block`) to skip the browser step
* and ship the colours with the page.
*/
// @use-when one syntax-highlighted code sample rendered from a client
// component, where the server `CodeBlock` cannot render. The text around it
// is still `Prose`; this is only the code block.
export function CodeBlockClient({
code,
language = "tsx",
html,
showLineNumbers = false,
framed = true,
className,
}: {
code: string
/** Any language Shiki ships. Its grammar loads on first use; an unknown one stays plain. */
language?: string
/** Already-highlighted HTML from `highlightCode`, so the browser does no work. */
html?: string
showLineNumbers?: boolean
/** Draw the block's own surface. Off sets the code inside a surface that already has one. */
framed?: boolean
className?: string
}) {
const trimmed = code.trim()
const [highlighted, setHighlighted] = useState<{ key: string; html: string } | null>(null)
const key = `${language}\n${trimmed}`
useEffect(() => {
if (html) return
let live = true
highlightInBrowser(trimmed, language).then(
(out) => live && setHighlighted({ key, html: out }),
() => {}
)
return () => {
live = false
}
}, [html, trimmed, language, key])
return (
<CodeBlockFrame
code={trimmed}
// Only the colours for this exact code: a stale result never paints over new text.
html={html ?? (highlighted?.key === key ? highlighted.html : null)}
showLineNumbers={showLineNumbers}
framed={framed}
className={className}
/>
)
}import type { ThemeRegistration } from "shiki"
const CODE_BLOCK_THEMES = { light: "ui-md-light", dark: "ui-md-dark" } as const
// One role per kind of word, each a `--code-*` token from the kit's ramps.
// Roles are reused across languages where the context keeps them apart (a JSON
// key and a CSS property are both a "property"), so a block never needs more
// than eight hues.
const v = (role: string) => `var(--code-${role})`
const tokenColors: ThemeRegistration["tokenColors"] = [
// Plain names, operators and punctuation recede.
{ scope: ["variable", "variable.other", "variable.parameter", "meta.definition.variable"], settings: { foreground: v("foreground") } },
{
scope: [
"punctuation",
"meta.brace",
"keyword.operator",
"punctuation.definition.tag",
"punctuation.separator",
"punctuation.terminator",
"punctuation.accessor",
],
settings: { foreground: v("token-punctuation") },
},
{ scope: ["comment", "punctuation.definition.comment", "string.comment", "markup.quote"], settings: { foreground: v("token-comment"), fontStyle: "italic" } },
// Keywords: control flow, declarations, modifiers, `this`, CSS at-rules, decorators.
{
scope: [
"keyword",
"keyword.control",
"keyword.other",
"keyword.operator.new",
"keyword.operator.expression",
"keyword.operator.logical.python",
"keyword.control.at-rule",
"storage",
"storage.type",
"storage.modifier",
"variable.language",
"punctuation.definition.template-expression",
"meta.decorator",
"entity.name.function.decorator",
"punctuation.definition.decorator",
],
settings: { foreground: v("token-keyword") },
},
// Functions, methods, types, classes, shell commands, CSS selectors.
{
scope: [
"entity.name.function",
"support.function",
"variable.function",
"meta.function-call.generic",
"entity.name.type",
"entity.name.class",
"entity.other.inherited-class",
"support.class",
"support.type",
"entity.name.namespace",
"entity.name.command",
"support.function.builtin.shell",
"entity.other.attribute-name.class.css",
"entity.other.attribute-name.id.css",
"entity.other.attribute-name.pseudo-class",
"entity.other.attribute-name.pseudo-element",
"meta.diff.range",
],
settings: { foreground: v("token-function") },
},
// Tags: HTML and JSX elements, React components, CSS element selectors.
{
scope: ["entity.name.tag", "support.class.component", "entity.name.tag.css"],
settings: { foreground: v("token-tag") },
},
// Properties: object and JSON keys, CSS properties and custom properties,
// HTML and JSX attributes, YAML keys.
{
scope: [
"meta.object-literal.key",
"support.type.property-name",
"support.type.vendored.property-name",
"support.type.custom-property",
"variable.css",
"variable.argument.css",
"meta.property-name",
"entity.other.attribute-name",
"entity.name.tag.yaml",
"entity.name.tag.toml",
"variable.other.key",
],
settings: { foreground: v("token-property") },
},
// Strings, template strings, regexes, inline code in Markdown.
{
scope: ["string", "string.quoted", "string.template", "string.regexp", "punctuation.definition.string", "markup.inline.raw", "markup.fenced_code"],
settings: { foreground: v("token-string") },
},
// Constants: numbers, booleans, null, ALL_CAPS constants, units, escapes,
// shell variables and flags.
{
scope: [
"constant",
"constant.numeric",
"constant.language",
"constant.character",
"constant.character.escape",
"constant.other",
"constant.other.option",
"support.constant",
"variable.other.constant",
"variable.other.enummember",
"keyword.other.unit",
"variable.other.normal.shell",
"punctuation.definition.variable.shell",
"constant.other.character-class.regexp",
"markup.list punctuation.definition.list",
],
settings: { foreground: v("token-constant") },
},
// Markdown.
{ scope: ["markup.heading", "entity.name.section", "punctuation.definition.heading"], settings: { foreground: v("token-keyword"), fontStyle: "bold" } },
{ scope: ["markup.bold"], settings: { fontStyle: "bold" } },
{ scope: ["markup.italic"], settings: { fontStyle: "italic" } },
{ scope: ["markup.underline.link", "string.other.link", "markup.link"], settings: { foreground: v("token-link"), fontStyle: "underline" } },
// Diffs and errors.
{ scope: ["markup.inserted", "punctuation.definition.inserted", "meta.diff.header.to-file"], settings: { foreground: v("token-inserted") } },
{ scope: ["markup.deleted", "punctuation.definition.deleted", "meta.diff.header.from-file"], settings: { foreground: v("token-deleted") } },
{ scope: ["invalid", "invalid.illegal", "invalid.deprecated"], settings: { foreground: v("token-deleted"), fontStyle: "underline" } },
]
const ansi = (name: string) => v(`ansi-${name}`)
const colors = {
"editor.foreground": v("foreground"),
"editor.background": v("background"),
"terminal.ansiBlack": ansi("black"),
"terminal.ansiRed": ansi("red"),
"terminal.ansiGreen": ansi("green"),
"terminal.ansiYellow": ansi("yellow"),
"terminal.ansiBlue": ansi("blue"),
"terminal.ansiMagenta": ansi("magenta"),
"terminal.ansiCyan": ansi("cyan"),
"terminal.ansiWhite": ansi("white"),
"terminal.ansiBrightBlack": ansi("bright-black"),
"terminal.ansiBrightRed": ansi("bright-red"),
"terminal.ansiBrightGreen": ansi("bright-green"),
"terminal.ansiBrightYellow": ansi("bright-yellow"),
"terminal.ansiBrightBlue": ansi("bright-blue"),
"terminal.ansiBrightMagenta": ansi("bright-magenta"),
"terminal.ansiBrightCyan": ansi("bright-cyan"),
"terminal.ansiBrightWhite": ansi("bright-white"),
}
function theme(name: string, type: "light" | "dark"): ThemeRegistration {
return { name, type, fg: v("foreground"), bg: v("background"), colors, tokenColors }
}
/** The two themes to load into a Shiki highlighter. Plain objects, so this
* file never pulls Shiki into a bundle by itself. */
const CODE_BLOCK_THEME_REGISTRATIONS: ThemeRegistration[] = [
theme(CODE_BLOCK_THEMES.light, "light"),
theme(CODE_BLOCK_THEMES.dark, "dark"),
]
// The theme pair both code blocks highlight with. Every colour is a `--code-*`
// token the base layer maps onto the kit's ramps, so a block matches the page
// and retunes with a project's accent and brand. Light and dark read the same
// variables and the values switch with the theme, so the `.shiki` rule the
// code-block item installs still finds `--shiki-dark`. No directive on purpose,
// so the server `CodeBlock` and the client `CodeBlockClient` read the same value.
export { CODE_BLOCK_THEMES, CODE_BLOCK_THEME_REGISTRATIONS }