Code Block

Fenced code block with a title bar (title left, language tag + copy button right). The copy action shells out to `navigator.clipboard.writeText` and flips an inline "Copied!" affordance for 1.5s — the only piece of state this primitive owns. Everything…

blog & long-formclient320pxuiv1.3.0

Preview

Code Block — live renderprimitives-codeblock--default

Rendered from the story the storybook (a11y) CI gate runs axe against — the preview can't show something that hasn't been verified.

Install

Two equivalent paths — the URL works in any shadcn-CLI setup; the alias works once you've registered @interlace in your components.json.

Via shadcn URL
npx shadcn@latest add https://ds.interlace.tools/r/code-block.json
With the @interlace alias
npx shadcn@latest add @interlace/code-block

Behavior

What this component does — the keyboard path, the measured colour, the text equivalent and the states it can be in. Every figure below is read out of the test or the source that enforces it by scripts/build-behavior-map.mjs, so nothing here can outlive the gate that keeps it true.

Every semantic colour pair this component's own source uses, measured against the shipped hexes in all 4 theme × scheme combinations. The tightest is success on background at 7.28:1 (harbor · light), against a floor of 3:1.

Measured WCAG contrast ratios per token pair and theme
PairinterlacelightinterlacedarkharborlightharbordarkFloor
success on backgroundsuccess tint on the page surface7.68:110.30:17.28:19.86:13.0:1SC 1.4.11
destructive on backgrounddestructive tint on the page surface8.31:110.43:17.60:110.03:13.0:1SC 1.4.11
success on cardsuccess tint inside a card7.68:19.54:17.68:18.95:13.0:1SC 1.4.11
muted-foreground on backgroundsecondary copy9.41:111.32:17.82:19.52:14.5:1SC 1.4.3
destructive on carddestructive tint inside a card8.31:19.66:18.02:19.09:13.0:1SC 1.4.11
muted-foreground on cardsecondary copy in a card9.41:110.48:18.25:18.64:14.5:1SC 1.4.3
ring on backgroundfocus ring (SC 2.4.13)8.80:111.79:18.39:110.03:13.0:1SC 1.4.11
ring on cardfocus ring inside a card8.80:110.92:18.86:19.10:13.0:1SC 1.4.11
foreground on backgroundbody copy19.65:116.97:117.74:116.19:14.5:1SC 1.4.3

Text pairs are held to 4.5:1 (WCAG 2.2 SC 1.4.3); borders, rings and chart axes to 3:1 (SC 1.4.11 non-text). Bold is the worst cell in the row — the one a brand fork has to keep an eye on.

Where it renders, how narrow it survives, and whether its lines are inside the coverage gate — three answers a consumer needs before the paste, not after the bug.

Render boundary
'use client'

Hydrates. It brings JavaScript to any route that imports it — put the boundary here, not at the page.

Minimum viewport
MIN_VIEWPORT = 320

Declared, not assumed. Below 320 CSS px the preflight contract draws a dev-mode outline — how to switch it on.

Coverage gate
not in the gate

The 100% gate currently covers src/charts/**/*.{ts,tsx} and src/lib/**/*.{ts,tsx} and src/primitives/{button-variants,data-state-model,meter-scale,skeleton-variants}.ts and src/primitives/{alert,aspect-ratio,avatar,badge,box,breadcrumb,button,callout,card,checkbox,code-editor,container,data-state,focus-ring,grade-badge,grid,input,label,meter,pagination,published-date,reading-time,section,section-boundary,separator,skip-link,stack,stat-strip,tag,textarea,typography,visually-hidden}.tsx and src/patterns/lint-playground.tsx. This file is outside it — the glob widens in phase 7.2.

History

This component is at v1.3.0, first shipped in @interlace/ui 1.0.0. The version is stamped as a banner into the file the install writes, so the copy in your tree says which one you have — compare it with the number above before deciding whether to re-run the install.

Unreleased3 entries

  • Addedminor

    CodeBlock — Shiki notation contract: highlighted + diff lines Lines a highlighter marks highlighted, diff add, or diff remove (Shiki's transformerNotationHighlight / transformerNotationDiff, or anything emitting the same classes) are now styled by the block itself: token-backed washes that hold in both themes, edge-to-edge bleed through the pre's padding, and a + / - gutter marker so a diff is never color-alone. The copy button yields the post-diff code — .diff.remove lines are skipped — so nobody pastes the line they were told to delete; select-none nudges drag-selection the same way (a hint engines apply unevenly, not a clipboard barrier — the button is the guarantee).

  • Addedminor

    CodeBlock — onCopied seam + honest copy affordance onCopied?(text) fires after a SUCCESSFUL clipboard write with the exact copied text — the measurement seam a receipts-honest consumer needs. Past-tense name is a documented R17 deviation: native onCopy already reaches the figure via ...props and fires on selection-copy. Honesty fix riding along: with no clipboard API available the button used to flip "Copied!" without writing anything; it now stays quiet — no success is claimed that didn't happen.

  • Changedpatch

    CodeBlock — dead header conditional removed, docs match behavior Boolean(title) || Boolean(language) || true never evaluated its left side and the file docs still described a header that could be omitted. The header ALWAYS renders (the copy button needs a home); the code and both doc blocks now say exactly that. No runtime change.

Import

2 named exports — pull the parts you need.

Public API
import { CodeBlock, MIN_VIEWPORT } from '@/components/ui/code-block';

Anatomy

Extracted from the primitive's JSDoc header. The source is the only documentation that can't drift.

CodeBlock                          (figure — data-min-viewport=320)
    ├─ figcaption                    (header bar; always rendered)
    │   ├─ {title}                   (left)
    │   ├─ {language tag}            (right)
    │   └─ <button> "Copy" / "Copied!" (right; client-only)
    └─ <pre>
        └─ <code class="language-{lang}">{children}</code>

API reference

Parsed from the type declarations in the source — the same file the install writes into your tree, so this table can't drift from the component you get.

CodeBlockProps

Also accepts every <figure> attribute.

PropTypeDescription
titleReact.ReactNodeOptional header title — usually a filename like `eslint.config.mjs`.
languagestringOptional language tag — lowercases into `language-{lang}` on `<code>`.
childrenReact.ReactNodeThe fenced code source — a string, JSX, or pre-highlighted markup. Optional when `loading={true}` (the skeleton has no content to render).
loadingbooleanWhen true, render a `<Skeleton variant="code-block" />` (multi-line monospace silhouette) in place of the figure. Useful while a Shiki highlight or fetch resolves.
onCopied(text: string) => voidFired after a SUCCESSFUL clipboard write, with the exact text that was copied — the measurement seam for consumers (a copy affordance that can't be measured contradicts the receipts doctrine). Named `onCopied` (past tense), not `onCopy` (R17 — documented deviation): the native `onCopy` clipboard event already reaches the root `<figure>` via `...props` and fires on selection-copy too; this seam reports only the button's completed write.

Skeleton

Pass loading and the component renders a shape-matched <Skeleton /> in its own place — same box, so nothing reflows when the data lands. Below is the same story with loading={true}.

Code Block — loading stateprimitives-codeblock--loading
Usage
<CodeBlock loading={isPending} />

Accessibility

Every story for this component is rendered headlessly and checked with axe-core (wcag2aa, wcag22aa, best-practice, ACT) on every PR. That gate has no continue-on-error, so what ships has zero known violations.

What follows is what static analysis can see. Axe cannot press a key and never sees an overlay open, so the operable-without-a-mouse claim lives in Behavior instead, where the keyboard path is replayed step by step.

Focus + keyboard behaviour
Native element semantics — no interaction layer to get wrong.
Focus ring (WCAG 2.2 SC 2.4.13)
Inherited from the preflight focus contract shipped in @interlace/theme.
Reduced motion
No animation to gate.
ARIA in the source
  • aria-label
  • aria-live

Examples

4 more states from the same story file.

R-rule compliance

Every primitive in @interlace/ui models to the portable 26-rule floor enforced by the componentApi ESLint preset. The cells below pin exactly where each rule applies in this file.

RuleConceptWhere
R4Extends native el`React.ComponentProps<'figure'> & CodeBlockProps`
R6data-slot per partcode-block / code-block-header / code-block-title / code-block-language / code-block-copy / code-block-pre / code-block-code
R7className merged + ...rest`cn(BASE, className)` + `{...props}`
R8No isXxx; props are scalars`title?` / `language?` only — no boolean variants
R10Composition seam`title` / `language` slots accept ReactNode
R14Declares min viewport`data-min-viewport={String(MIN_VIEWPORT)}` + exported const
R18Tailwind onlyZero inline `style`; utility classes only
R19Tokens only`bg-card` / `border-border` / `rounded-md` / `p-md` / `text-code`
R20AA contrastforeground on card surface (semantic tokens, AA-clean)
R25Client componentOwns `useState` for the copy affordance
R26A11yCopy button has accessible label + aria-live region for state

Minimum viewport

This primitive declares MIN_VIEWPORT = 320 CSS px (DESIGN_PRINCIPLES #14). When mounted in a container narrower than this, the preflight contract draws a dev-mode outline so the regression is visible during local development.

Opt-in to the dev-mode warning
<body data-interlace-dev>...</body>

Add the data-interlace-dev attribute to the body in development builds only — preflight then outlines any primitive whose container is below its declared data-min-viewport.

Dependencies

Base UI primitive
Native / no Base UI dependency
Lucide icons
  • Check
  • Copy
NPM dependencies
  • lucide-react

Source

The full implementation — components/ui/code-block.tsx once installed.

304 lines · TypeScript
'use client';

import * as React from 'react';

// @interlace/code-block v1.3.0 — Interlace design system.
// Docs, props and live preview: https://ds.interlace.tools/c/code-block
// What changed since: https://ds.interlace.tools/c/code-block#history
// Generated banner — keep it, the upgrade diff reads this version.

/**
 * @interlace/ui — CodeBlock
 *
 * Fenced code block with a title bar (title left, language tag + copy button
 * right). The copy action shells out to `navigator.clipboard.writeText` and
 * flips an inline "Copied!" affordance for 1.5s — the only piece of state
 * this primitive owns. Everything else is structural: a `<figure>` wrapping
 * a `<pre><code class="language-{lang}">`, ready for any downstream syntax
 * highlighter (Shiki, Prism, hand-rolled — we don't care).
 *
 * The header ALWAYS renders — the copy button needs a home even when

…284 more lines…

Registry JSON

The raw registry record — what the shadcn CLI fetches.