Code Block

Displays code, terminal output and tool results in a raised panel, with a title, copy and wrap.

Terminal
$ npm run build
> vite build

vite v7.1.4 building for production...
✓ 412 modules transformed.
dist/index.html                  0.46 kB │ gzip:  0.30 kB
dist/assets/index-Bx3k9aQe.css   18.92 kB │ gzip:  4.61 kB
dist/assets/index-C7mR2fLp.js   214.37 kB │ gzip: 68.05 kB
✓ built in 2.14s
import * as stylex from "@stylexjs/stylex"
import { CodeBlock, Pre } from "@/components/ui/code-block"
import { TerminalIcon } from "@phosphor-icons/react/dist/csr/Terminal"
import { widths } from "@/theme/widths"

const output = `$ npm run build
> vite build

vite v7.1.4 building for production...
✓ 412 modules transformed.
dist/index.html                  0.46 kB │ gzip:  0.30 kB
dist/assets/index-Bx3k9aQe.css   18.92 kB │ gzip:  4.61 kB
dist/assets/index-C7mR2fLp.js   214.37 kB │ gzip: 68.05 kB
✓ built in 2.14s`

export default function CodeBlockDemo() {
  return (
    <div {...stylex.props(widths.lg)}>
      <CodeBlock title="Terminal" icon={<TerminalIcon />}>
        <Pre>
          <code>{output}</code>
        </Pre>
      </CodeBlock>
    </div>
  )
}

CodeBlock shows code and program output: source files, terminal sessions, tool calls and model output. It renders whatever you put in its <pre> as is, so plain text needs no highlighter. Syntax highlighting is an optional layer: see Syntax highlighting.

Installation

pnpm dlx shadcn@latest add @arene/code-block

Needs the arene setup first. Also adds Button and Select.

Usage

import { CodeBlock, Pre } from "@/components/ui/code-block"
<CodeBlock title="Terminal">
  <Pre>
    <code>{output}</code>
  </Pre>
</CodeBlock>

Composition

CodeBlock
├── CodeBlockHeader            (when there is a title)
│   ├── CodeBlockTitle
│   └── CodeBlockActions
└── CodeBlockPanel
    ├── CodeBlockActions       (floating, when there is no title)
    └── CodeBlockViewport
        └── Pre
            └── code

CodeBlock assembles these parts for you. Each one is exported, so you can build the same tree by hand with CodeBlockRoot at the top. A tray holds the title row and a raised panel, and the viewport inside the panel scrolls.

Plain code

Put a string in <code> inside Pre. Nothing parses or tokenizes it, so the block is cheap to re-render while output streams in. Without a title, the copy button floats over the top end of the panel and shows on hover or focus. It always shows on narrow screens.

{
  "id": "call_8f2c",
  "name": "search_docs",
  "arguments": { "query": "dark mode tokens", "limit": 3 },
  "status": "completed"
}
import * as stylex from "@stylexjs/stylex"
import { CodeBlock, Pre } from "@/components/ui/code-block"
import { widths } from "@/theme/widths"

const output = `{
  "id": "call_8f2c",
  "name": "search_docs",
  "arguments": { "query": "dark mode tokens", "limit": 3 },
  "status": "completed"
}`

export default function CodeBlockPlain() {
  return (
    <div {...stylex.props(widths.lg)}>
      <CodeBlock>
        <Pre>
          <code>{output}</code>
        </Pre>
      </CodeBlock>
    </div>
  )
}

The panel sets its own text color, so a block inside muted content, such as a Trace, still reads at full contrast.

Title

title adds a header row above the panel. It renders as the figure's <figcaption> and truncates when it is too long. icon puts an icon before it.

src/lib/format-bytes.ts
export function formatBytes(bytes: number) {
  const units = ["B", "kB", "MB", "GB"]
  const exponent = Math.min(Math.floor(Math.log10(bytes) / 3), units.length - 1)
  return `${(bytes / 1000 ** exponent).toFixed(1)} ${units[exponent]}`
}
Response
HTTP/1.1 204 No Content
import { CodeBlock, Pre } from "@/components/ui/code-block"
import { VStack } from "@/components/ui/stack"
import { FileTsIcon } from "@phosphor-icons/react/dist/csr/FileTs"
import { widths } from "@/theme/widths"

const source = `export function formatBytes(bytes: number) {
  const units = ["B", "kB", "MB", "GB"]
  const exponent = Math.min(Math.floor(Math.log10(bytes) / 3), units.length - 1)
  return \`\${(bytes / 1000 ** exponent).toFixed(1)} \${units[exponent]}\`
}`

export default function CodeBlockTitle() {
  return (
    <VStack gap={6} xstyle={widths.lg}>
      <CodeBlock title="src/lib/format-bytes.ts" icon={<FileTsIcon />}>
        <Pre>
          <code>{source}</code>
        </Pre>
      </CodeBlock>
      <CodeBlock title="Response">
        <Pre>
          <code>{"HTTP/1.1 204 No Content"}</code>
        </Pre>
      </CodeBlock>
    </VStack>
  )
}

Copy

The copy button copies the text of the <pre>. On highlighted code it leaves out lines marked as removed in a diff. Set allowCopy={false} to hide it.

Commit
9f3c2e1a7b4d8c06e5f2a1b9d3c7e4f8a2b6c0d1
Exit status
Process exited with code 0
import { CodeBlock, Pre } from "@/components/ui/code-block"
import { VStack } from "@/components/ui/stack"
import { widths } from "@/theme/widths"

export default function CodeBlockCopy() {
  return (
    <VStack gap={6} xstyle={widths.lg}>
      <CodeBlock title="Commit">
        <Pre>
          <code>{"9f3c2e1a7b4d8c06e5f2a1b9d3c7e4f8a2b6c0d1"}</code>
        </Pre>
      </CodeBlock>
      <CodeBlock title="Exit status" allowCopy={false}>
        <Pre>
          <code>{"Process exited with code 0"}</code>
        </Pre>
      </CodeBlock>
    </VStack>
  )
}

Long output

The viewport scrolls in both directions and is capped at 40rem. Pass a different cap through viewportProps.

server.log
[01] GET /api/chat 200 in 12ms (cache miss)
[02] GET /api/threads 200 in 19ms (cache hit)
[03] GET /api/files/upload 200 in 26ms (cache hit)
[04] GET /api/search?q=release+notes 200 in 33ms (cache miss)
[05] GET /api/chat 200 in 40ms (cache hit)
[06] GET /api/threads 200 in 47ms (cache hit)
[07] GET /api/files/upload 200 in 14ms (cache miss)
[08] GET /api/search?q=release+notes 200 in 21ms (cache hit)
[09] GET /api/chat 200 in 28ms (cache hit)
[10] GET /api/threads 200 in 35ms (cache miss)
[11] GET /api/files/upload 200 in 42ms (cache hit)
[12] GET /api/search?q=release+notes 200 in 49ms (cache hit)
[13] GET /api/chat 200 in 16ms (cache miss)
[14] GET /api/threads 200 in 23ms (cache hit)
[15] GET /api/files/upload 200 in 30ms (cache hit)
[16] GET /api/search?q=release+notes 200 in 37ms (cache miss)
[17] GET /api/chat 200 in 44ms (cache hit)
[18] GET /api/threads 200 in 51ms (cache hit)
[19] GET /api/files/upload 200 in 18ms (cache miss)
[20] GET /api/search?q=release+notes 200 in 25ms (cache hit)
[21] GET /api/chat 200 in 32ms (cache hit)
[22] GET /api/threads 200 in 39ms (cache miss)
[23] GET /api/files/upload 200 in 46ms (cache hit)
[24] GET /api/search?q=release+notes 200 in 13ms (cache hit)
[25] GET /api/chat 200 in 20ms (cache miss)
[26] GET /api/threads 200 in 27ms (cache hit)
[27] GET /api/files/upload 200 in 34ms (cache hit)
[28] GET /api/search?q=release+notes 200 in 41ms (cache miss)
[29] GET /api/chat 200 in 48ms (cache hit)
[30] GET /api/threads 200 in 15ms (cache hit)
[31] GET /api/files/upload 200 in 22ms (cache miss)
[32] GET /api/search?q=release+notes 200 in 29ms (cache hit)
[33] GET /api/chat 200 in 36ms (cache hit)
[34] GET /api/threads 200 in 43ms (cache miss)
[35] GET /api/files/upload 200 in 50ms (cache hit)
[36] GET /api/search?q=release+notes 200 in 17ms (cache hit)
[37] GET /api/chat 200 in 24ms (cache miss)
[38] GET /api/threads 200 in 31ms (cache hit)
[39] GET /api/files/upload 200 in 38ms (cache hit)
[40] GET /api/search?q=release+notes 200 in 45ms (cache miss)
import * as stylex from "@stylexjs/stylex"
import { CodeBlock, Pre } from "@/components/ui/code-block"
import { widths } from "@/theme/widths"

const styles = stylex.create({
  viewport: { maxHeight: "16rem" },
})

const routes = ["/api/chat", "/api/threads", "/api/files/upload", "/api/search?q=release+notes"]

const logs = Array.from({ length: 40 }, (_, index) => {
  const line = String(index + 1).padStart(2, "0")
  const route = routes[index % routes.length]
  return `[${line}] GET ${route} 200 in ${12 + ((index * 7) % 40)}ms (cache ${index % 3 === 0 ? "miss" : "hit"})`
}).join("\n")

export default function CodeBlockScroll() {
  return (
    <div {...stylex.props(widths.lg)}>
      <CodeBlock title="server.log" viewportProps={{ xstyle: styles.viewport }}>
        <Pre>
          <code>{logs}</code>
        </Pre>
      </CodeBlock>
    </div>
  )
}
const styles = stylex.create({
  viewport: { maxHeight: "16rem" },
})

<CodeBlock viewportProps={{ xstyle: styles.viewport }}>…</CodeBlock>

Wrapping

Long lines scroll by default. When a line overflows, a wrap button appears next to the copy button. Set defaultWrap to start wrapped, which suits error messages and terminal output.

Scrolls
Error: Request too large. The prompt is 212,431 tokens and the context window is 200,000 tokens. Remove some messages or summarize the conversation, then try again.
Wraps
Error: Request too large. The prompt is 212,431 tokens and the context window is 200,000 tokens. Remove some messages or summarize the conversation, then try again.
import { CodeBlock, Pre } from "@/components/ui/code-block"
import { VStack } from "@/components/ui/stack"
import { widths } from "@/theme/widths"

const error = `Error: Request too large. The prompt is 212,431 tokens and the context window is 200,000 tokens. Remove some messages or summarize the conversation, then try again.`

export default function CodeBlockWrap() {
  return (
    <VStack gap={6} xstyle={widths.lg}>
      <CodeBlock title="Scrolls">
        <Pre>
          <code>{error}</code>
        </Pre>
      </CodeBlock>
      <CodeBlock title="Wraps" defaultWrap>
        <Pre>
          <code>{error}</code>
        </Pre>
      </CodeBlock>
    </VStack>
  )
}

To control it, pass wrap and onWrapChange. The built-in wrap button calls onWrapChange.

const [wrap, setWrap] = useState(true)

<CodeBlock title="Terminal" wrap={wrap} onWrapChange={setWrap}>
  <Pre>
    <code>{output}</code>
  </Pre>
</CodeBlock>

Streaming

Append to the string as output arrives. The block re-renders one text node, and the wrap button appears once a line overflows.

Terminal
$ npm test
"use client"

import { useEffect, useState } from "react"
import { Button } from "@/components/ui/button"
import { CodeBlock, Pre } from "@/components/ui/code-block"
import { HStack, VStack } from "@/components/ui/stack"
import { ArrowClockwiseIcon } from "@phosphor-icons/react/dist/csr/ArrowClockwise"
import { TerminalIcon } from "@phosphor-icons/react/dist/csr/Terminal"
import { widths } from "@/theme/widths"

const lines = [
  "$ npm test",
  "> vitest run",
  "",
  " ✓ src/lib/format-bytes.test.ts (4 tests) 3ms",
  " ✓ src/lib/parse-sse.test.ts (7 tests) 6ms",
  " ✓ src/components/message.test.tsx (12 tests) 48ms",
  " ✓ src/routes/chat.test.tsx (9 tests) 112ms",
  "",
  " Test Files  4 passed (4)",
  "      Tests  32 passed (32)",
  "   Duration  1.42s",
]

export default function CodeBlockStreaming() {
  const [count, setCount] = useState(1)
  const done = count >= lines.length

  useEffect(() => {
    if (done) return
    const timeout = setTimeout(() => setCount(count + 1), 350)
    return () => clearTimeout(timeout)
  }, [count, done])

  return (
    <VStack gap={3} xstyle={widths.lg}>
      <CodeBlock title="Terminal" icon={<TerminalIcon />} defaultWrap>
        <Pre>
          <code>{lines.slice(0, count).join("\n")}</code>
        </Pre>
      </CodeBlock>
      <HStack justify="end">
        <Button variant="outline" size="sm" disabled={!done} onClick={() => setCount(1)}>
          <ArrowClockwiseIcon aria-hidden="true" />
          Replay
        </Button>
      </HStack>
    </VStack>
  )
}

Package-manager tabs

CodeBlockTabs shows one command for several package managers. A Select stands in for the command's first word, and the choice is shared by every CodeBlockTabs with the same groupId. Set persist to keep it across reloads. This page's own commands use it:

pnpm add @phosphor-icons/react

Each CodeBlockTab holds one highlighted CodeBlock. Its prefix is the word the select shows, when that differs from value (npx for npm, for example).

<CodeBlockTabs defaultValue="npm" groupId="package-manager" persist>
  <CodeBlockTab value="npm">{npmBlock}</CodeBlockTab>
  <CodeBlockTab value="pnpm">{pnpmBlock}</CodeBlockTab>
</CodeBlockTabs>

The tabs need highlighted markup. mdx.css hides the first token of the command's .line so the select can take its place, and plain text has no tokens to hide.

Syntax highlighting

CodeBlock doesn't tokenize code. It styles the markup that Pierre Highlights produces, through the rules in mdx.css. The CLI doesn't add mdx.css, so to highlight code:

  1. Install @pierre/highlights.
  2. Copy mdx.css below and import it after interop.css, outside any @layer.
  3. Give the CodeBlock the highlights class.
  4. Render each line as a <span className="line"> and join the lines with "\n", so the copy button keeps the line breaks.
  5. Render each token as a <span> with the token's htmlStyle as its inline style. With defaultColor: false, that style holds --hls-light and --hls-dark, and mdx.css picks one with light-dark().
import { Fragment, type CSSProperties } from "react"
import { codeToTokens, type Lang } from "@pierre/highlights"
import { githubDark, githubLight } from "@pierre/highlights/themes"
import { CodeBlock, Pre } from "@/components/ui/code-block"

const themes = { light: githubLight, dark: githubDark }

export function HighlightedCode({
  code,
  lang,
  title,
}: {
  code: string
  lang: Lang
  title?: string
}) {
  const { tokens } = codeToTokens(code, { lang, themes, defaultColor: false })

  return (
    <CodeBlock title={title} className="highlights">
      <Pre>
        <code>
          {tokens.map((line, index) => (
            <Fragment key={index}>
              {index > 0 && "\n"}
              <span className="line">
                {line.map((token, position) => (
                  <span key={position} style={token.htmlStyle as CSSProperties}>
                    {token.content}
                  </span>
                ))}
              </span>
            </Fragment>
          ))}
        </code>
      </Pre>
    </CodeBlock>
  )
}

codeToTokens is synchronous once the package is imported, and the import loads about 370 kB of WebAssembly. Tokenize on the server or at build time when you can, and send the client the rendered markup. Every block on this page is tokenized at build time.

With the highlights class, padding moves from the <pre> to each .line, so a highlighted line's background reaches both edges of the panel. Highlighted blocks also get these from mdx.css:

  • Line numbers, on by default for blocks of more than one line. Set data-line-numbers={false} on the block to turn them off, and data-line-numbers-start to start from another number.
  • .highlighted, .highlighted-word, .diff.add and .diff.remove on a line or token, which tint it.
  • keepBackground, which paints the theme's own background on the panel. It reads --hls-light-bg and --hls-dark-bg, which codeToTokens returns as a CSS string in bg. Set them on the block's style.

mdx.css also styles the viewport's thin scrollbar (mdx-scrollbar). Without it, plain code still renders and the browser draws its own scrollbar.

styles/mdx.css
:root {
  --code-highlight: light-dark(oklch(0.52 0.16 262), oklch(0.72 0.14 262));
  --code-add: light-dark(oklch(0.53 0.13 152), oklch(0.76 0.16 155));
  --code-remove: light-dark(oklch(0.56 0.21 25), oklch(0.71 0.19 25));
}

.highlights {
  --code-gutter: 1.75rem;
}

.highlights code span {
  color: light-dark(var(--hls-light), var(--hls-dark));
  font-style: var(--hls-light-font-style, normal);
  font-weight: var(--hls-light-font-weight, inherit);
}

.dark .highlights code span {
  font-style: var(--hls-dark-font-style, normal);
  font-weight: var(--hls-dark-font-weight, inherit);
}

@media (prefers-color-scheme: dark) {
  :root:not(.light) .highlights code span {
    font-style: var(--hls-dark-font-style, normal);
    font-weight: var(--hls-dark-font-weight, inherit);
  }
}

.highlights .line {
  position: relative;
  padding-inline: var(--code-pad-start, var(--code-pad-x)) var(--code-pad-end, var(--code-pad-x));
}

[data-slot="code-block-prefixed"] .line > span:first-child {
  display: none;
}

[data-slot="code-block-prefixed"] [data-slot="code-block-pre"] {
  min-width: 0;
}

[data-slot="code-block-pre"] > code {
  display: flex;
  flex-direction: column;
}

[data-slot="code-block-panel"][data-keep-background="true"] {
  background-color: light-dark(var(--hls-light-bg), var(--hls-dark-bg));
}

.highlights [data-slot="code-block-pre"] {
  padding-inline: 0;
}

.highlights[data-slot="code-block"][data-wrap="true"] [data-slot="code-block-prefixed"] code,
.highlights[data-slot="code-block"][data-wrap="true"] [data-slot="code-block-prefixed"] .line {
  display: block;
}

.highlights[data-slot="code-block"][data-wrap="true"]
  [data-slot="code-block-prefixed"]
  .line
  > span {
  white-space: pre;
}

.highlights[data-slot="code-block"][data-wrap="true"] [data-slot="code-block-prefixed"] .line {
  padding-inline-start: 0.25rem;
  text-indent: -0.25rem;
}

.highlights .line:empty {
  height: 1.6em;
  height: 1lh;
}

.highlights .highlighted {
  --code-marker: var(--code-highlight);
  background-color: color-mix(in oklab, var(--code-highlight) 9%, transparent);
  box-shadow: inset 2px 0 0 color-mix(in oklab, var(--code-highlight) 55%, transparent);
}

.highlights .highlighted-word {
  padding: 0.125em 0.2em;
  margin-inline: -0.2em;
  border-radius: 0.25rem;
  background-color: color-mix(in oklab, var(--code-highlight) 14%, transparent);
  box-shadow: 0 0 0 1px color-mix(in oklab, var(--code-highlight) 30%, transparent);
}

.highlights .diff::before {
  position: absolute;
  left: 0.375rem;
  font-weight: 500;
}

.highlights .diff.add {
  --code-marker: var(--code-add);
  background-color: color-mix(in oklab, var(--code-add) 12%, transparent);
}

.highlights .diff.add::before {
  content: "+";
  color: var(--code-add);
}

.highlights .diff.remove {
  --code-marker: var(--code-remove);
  background-color: color-mix(in oklab, var(--code-remove) 12%, transparent);
  opacity: 0.75;
}

.highlights .diff.remove::before {
  content: "-";
  color: var(--code-remove);
}

.highlights.has-focused .line:not(.focused) {
  filter: blur(2px);
  opacity: 0.55;
  transition:
    filter 200ms,
    opacity 200ms;
}

.highlights.has-focused:hover .line:not(.focused) {
  filter: blur(0);
  opacity: 1;
}

.highlights[data-line-numbers="true"] .line {
  counter-increment: line;
  padding-left: calc(var(--code-pad-x) + var(--code-gutter));
}

.highlights[data-line-numbers="true"] .line:only-child {
  padding-left: var(--code-pad-start, var(--code-pad-x));
}

.highlights[data-line-numbers="true"] .line:only-child::after {
  content: none;
}

.highlights[data-line-numbers="true"] .line::after {
  content: counter(line);
  position: absolute;
  inset-block: 0;
  left: 0;
  width: calc(var(--code-pad-x) + var(--code-gutter) - 0.75rem);
  text-align: right;
  color: color-mix(in oklab, var(--code-marker, var(--muted-foreground)) 60%, transparent);
  user-select: none;
}

[data-slot="alert-description"] > :first-child {
  margin-block-start: 0;
}

[data-slot="alert-description"] > :last-child {
  margin-block-end: 0;
}

.mdx-scrollbar {
  scrollbar-width: thin;
  scrollbar-color: color-mix(in oklab, var(--muted-foreground) 35%, transparent) transparent;
}

.mdx-scrollbar::-webkit-scrollbar {
  width: 0.625rem;
  height: 0.625rem;
}

.mdx-scrollbar::-webkit-scrollbar-track {
  background: transparent;
}

.mdx-scrollbar::-webkit-scrollbar-thumb {
  border: 3px solid transparent;
  border-radius: 9999px;
  background-clip: content-box;
  background-color: color-mix(in oklab, var(--muted-foreground) 30%, transparent);
}

.mdx-scrollbar::-webkit-scrollbar-thumb:hover {
  background-color: color-mix(in oklab, var(--muted-foreground) 55%, transparent);
}

.mdx-steps {
  counter-reset: mdx-step;
  margin-block: 1.75rem;
  margin-inline-start: 0.75rem;
  padding-inline-start: 2rem;
  border-inline-start: 1px solid var(--border);
}

.mdx-step {
  counter-increment: mdx-step;
  position: relative;
  padding-block-end: 1.75rem;
}

.mdx-step:last-child {
  padding-block-end: 0;
}

.mdx-step > :first-child {
  margin-block-start: 0;
}

.mdx-step::before {
  content: counter(mdx-step);
  position: absolute;
  top: 0;
  left: calc(-2rem - 0.75rem);
  display: flex;
  align-items: center;
  justify-content: center;
  width: 1.5rem;
  height: 1.5rem;
  border-radius: 9999px;
  border: 1px solid var(--border);
  background-color: var(--card);
  box-shadow: 0 0 0 4px var(--background);
  font-size: 0.75rem;
  font-variant-numeric: tabular-nums;
  font-weight: 500;
  line-height: 1;
  color: var(--foreground);
}

@keyframes mdx-folder-open {
  from {
    height: 0;
    opacity: 0;
  }
  to {
    height: var(--collapsible-panel-height);
    opacity: 1;
  }
}

@keyframes mdx-folder-close {
  from {
    height: var(--collapsible-panel-height);
    opacity: 1;
  }
  to {
    height: 0;
    opacity: 0;
  }
}

[data-slot="files-folder-panel"] {
  overflow: hidden;
}

[data-slot="files-folder-panel"][data-open] {
  animation: mdx-folder-open 180ms ease-out;
}

[data-slot="files-folder-panel"][data-closed] {
  animation: mdx-folder-close 180ms ease-out;
}

@media (prefers-reduced-motion: reduce) {
  [data-slot="files-folder-panel"][data-open],
  [data-slot="files-folder-panel"][data-closed] {
    animation-duration: 1ms;
  }

  .highlights.has-focused .line:not(.focused) {
    transition: none;
  }
}

[data-rmiz] {
  display: block;
  position: relative;
}

[data-rmiz-ghost] {
  pointer-events: none;
  position: absolute;
}

[data-rmiz-btn-zoom],
[data-rmiz-btn-unzoom] {
  display: none;
}

[data-rmiz-content="found"] img {
  cursor: zoom-in;
}

[data-rmiz-modal][open] {
  width: 100vw;
  width: 100dvw;
  height: 100vh;
  height: 100dvh;
  max-width: none;
  max-height: none;
  margin: 0;
  padding: 0;
  position: fixed;
  overflow: hidden;
  background-color: transparent;
}

[data-rmiz-modal]:focus-visible {
  outline: none;
}

[data-rmiz-modal]::backdrop {
  display: none;
}

[data-rmiz-modal-overlay] {
  position: absolute;
  inset: 0;
  transition: background-color 0.3s;
}

[data-rmiz-modal-overlay="visible"] {
  background-color: var(--background);
}

[data-rmiz-modal-overlay="hidden"] {
  background-color: transparent;
}

[data-rmiz-modal-content] {
  width: 100%;
  height: 100%;
  position: relative;
}

[data-rmiz-modal-img] {
  position: absolute;
  cursor: zoom-out;
  image-rendering: high-quality;
  transform-origin: 0 0;
  transition: transform 0.3s;
}

@media (prefers-reduced-motion: reduce) {
  [data-rmiz-modal-overlay],
  [data-rmiz-modal-img] {
    transition-duration: 0.01ms !important;
  }
}

API reference

Pass render to replace a part's element. Every part takes xstyle, className and style. style is real inline CSS, merged over the compiled styles.

CodeBlock

CodeBlockRoot with a header, a panel and a viewport already inside. It takes every CodeBlockRoot prop, plus:

PropTypeDefault
titleReactNode—
iconReactNode—
viewportPropsCodeBlockViewportProps—

A string title also labels the viewport (Code: <title>). Without one the viewport is labelled "Code block".

CodeBlockRoot

The <figure>. It holds the wrap state and reads its frame from the surrounding context.

PropTypeDefault
wrapboolean—
defaultWrapbooleanfalse
onWrapChange(wrap: boolean) => void—
allowCopybooleantrue
keepBackgroundbooleanfalse
data-line-numbersbooleantrue
data-line-numbers-startnumber | string1

CodeBlockHeader and CodeBlockTitle

The header is the row above the panel. CodeBlockTitle is the <figcaption> and takes icon.

CodeBlockActions

The built-in wrap and copy buttons. The wrap button shows only while a line overflows or the block is wrapped.

PropTypeDefault
floatingbooleanfalse

floating positions the buttons over the panel, for a block without a header.

CodeBlockCopyButton

A ghost icon-xs Button that copies the <pre>'s text. It takes every Button prop and must be inside a CodeBlockRoot.

CodeBlockPanel

The raised panel inside the tray. It sets the text color, and draws an inset focus ring while the viewport has keyboard focus.

CodeBlockViewport

The scrolling <section>. It is focusable, so the keyboard can scroll it.

PropTypeDefault
reserveActionsbooleanfalse

reserveActions keeps the text clear of floating actions. CodeBlock sets it when there is no title.

Pre

The <pre>. It pads plain code and wraps it when the block is wrapped. Put a <code> inside it.

CodeBlockTabs and CodeBlockTab

PropOnTypeDefault
defaultValueCodeBlockTabsstring—
groupIdCodeBlockTabsstring—
persistCodeBlockTabsbooleanfalse
valueCodeBlockTabstring—
prefixCodeBlockTabstringvalue
selectLabelCodeBlockTabstring"Package manager"

CodeBlockFrameContext

"framed" by default. A provider set to "flush" drops the tray and the panel's shadow and removes the viewport's height cap, for a block that sits inside another surface. The docs' preview cards use it for the source under each demo.

Data attributes

AttributeOnEffect
data-slot="code-block"the figureWhere mdx.css scopes the highlighter rules
data-slot="code-block-header"the header
data-slot="code-block-title"the figcaption
data-slot="code-block-actions"the actions
data-slot="code-block-panel"the panelkeepBackground paints here
data-slot="code-block-viewport"the viewport
data-slot="code-block-pre"the <pre>
data-slot="code-block-tabs"the tabs root
data-slot="code-block-tab"each tab
data-framethe figuretray, panel inside tabs, or flush
data-wrapthe figuretrue while wrapped
data-line-numbersthe figuremdx.css numbers highlighted lines when true
data-keep-backgroundthe panelmdx.css paints the theme background when true

CSS variables

VariableOnEffect
--code-pad-xthe figureInline padding of the text, 1rem
--code-pad-startthe viewportStart padding of the text. --code-pad-x when unset
--code-pad-endthe viewportEnd padding of the text. --code-pad-x, or room for the actions
--code-gutter.highlightsThe width of the line-number gutter