# Code Block

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

```tsx
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](#syntax-highlighting).

## Installation

**Command**

```bash
npx shadcn@latest add @arene/code-block
```

Needs the [arene setup](https://www.arene.style/docs/installation) first. Also adds [Button](https://www.arene.style/docs/components/button) and [Select](https://www.arene.style/docs/components/select).

**Manual**

1. Install the packages it imports:

   ```bash
   npm install @base-ui/react @stylexjs/stylex clsx @phosphor-icons/react
   ```

2. Set up the token layer and the StyleX compiler, if you have not already. See
   [Installation](https://www.arene.style/docs/installation). The code block reads `markers.stylex.ts`
   and `states.ts` from that page, and needs `interop.css`, which fades the
   viewport's edges as it scrolls (`scroll-fade-x`, `scroll-fade-y`) and sizes the
   title icon. Highlighted code also needs `mdx.css`; see
   [Syntax highlighting](#syntax-highlighting).

3. Install [Button](https://www.arene.style/docs/components/button) and [Select](https://www.arene.style/docs/components/select).
   The copy and wrap buttons are buttons, and the package-manager tabs use a
   select.

4. Paste the tab-group helper and the component into your project. The
   helper keeps the package-manager choice in sync across the page.

   ```ts title="lib/tab-group.ts"
   "use client"

   import { useCallback, useEffect, useState } from "react"

   const groups = new Map<string, Set<(value: string) => void>>()

   const storageKey = (groupId: string) => `arene-tabs:${groupId}`

   export function useTabGroup(defaultValue: string, groupId?: string, persist = false) {
     const [value, setValue] = useState(defaultValue)

     useEffect(() => {
       if (!groupId) return

       if (persist) {
         try {
           const stored = localStorage.getItem(storageKey(groupId))
           if (stored) setValue(stored)
         } catch {}
       }

       let listeners = groups.get(groupId)
       if (!listeners) groups.set(groupId, (listeners = new Set()))
       listeners.add(setValue)

       return () => {
         listeners.delete(setValue)
         if (listeners.size === 0) groups.delete(groupId)
       }
     }, [groupId, persist])

     const onValueChange = useCallback(
       (next: string) => {
         setValue(next)
         if (!groupId) return

         if (persist) {
           try {
             localStorage.setItem(storageKey(groupId), next)
           } catch {}
         }

         for (const listener of groups.get(groupId) ?? []) {
           if (listener !== setValue) listener(next)
         }
       },
       [groupId, persist],
     )

     return [value, onValueChange] as const
   }
   ```

   ```tsx title="components/ui/code-block.tsx"
   "use client"

   import {
     Children,
     createContext,
     isValidElement,
     use,
     useCallback,
     useEffect,
     useRef,
     useState,
     type ComponentProps,
     type CSSProperties,
     type FocusEvent,
     type ReactNode,
     type RefObject,
   } from "react"
   import { useRender } from "@base-ui/react/use-render"
   import * as stylex from "@stylexjs/stylex"
   import type { StyleXStyles } from "@stylexjs/stylex"
   import { clsx } from "clsx"
   import { CheckIcon } from "@phosphor-icons/react/dist/csr/Check"
   import { CopyIcon } from "@phosphor-icons/react/dist/csr/Copy"
   import { TerminalIcon } from "@phosphor-icons/react/dist/csr/Terminal"
   import { TextAlignLeftIcon } from "@phosphor-icons/react/dist/csr/TextAlignLeft"

   import { Button } from "@/components/ui/button"
   import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
   import { useTabGroup } from "@/lib/tab-group"
   import { codeBlock as codeBlockMarker } from "@/theme/markers.stylex"
   import { states } from "@/theme/states"
   import {
     color,
     duration,
     font,
     layer,
     leading,
     radius,
     shadow,
     space,
     text,
   } from "@/theme/tokens.stylex"

   const codeCommand = "light-dark(oklch(0.49 0.19 295), oklch(0.73 0.13 300))"

   type ButtonProps = ComponentProps<typeof Button>

   type Overrides = { xstyle?: StyleXStyles }

   const InTabsContext = createContext(false)

   const CodeBlockFrameContext = createContext<"framed" | "flush">("framed")

   type CodeBlockFrame = "tray" | "panel" | "flush"

   type CodeBlockContextValue = {
     frame: CodeBlockFrame
     viewportRef: RefObject<HTMLElement | null>
     copyable: boolean
     numbered: boolean
     lineNumbersStart?: number | string
     keepBackground: boolean
     wrap: boolean
     setWrap: (wrap: boolean) => void
     overflows: boolean
   }

   const CodeBlockContext = createContext<CodeBlockContextValue | null>(null)

   const CodeBlockPrefixContext = createContext<ReactNode>(null)

   function useCodeBlock(part: string) {
     const context = use(CodeBlockContext)
     if (!context) throw new Error(`<${part}> must be rendered inside <CodeBlockRoot>`)
     return context
   }

   const styles = stylex.create({
     root: {
       position: "relative",
       fontSize: text.code,
       lineHeight: leading.code,
       "--code-pad-x": space.s4,
     },
     rootTray: {
       borderRadius: radius.xl,
       padding: space.s1,
       backgroundColor: color.tray,
     },

     header: {
       display: "flex",
       height: space.s9,
       alignItems: "center",
       gap: space.s2,
       paddingInline: space.s3,
       color: color.foreground,
     },
     caption: {
       minWidth: 0,
       flexGrow: 1,
       overflow: "hidden",
       textOverflow: "ellipsis",
       whiteSpace: "nowrap",
       fontFamily: font.mono,
       fontSize: text.xs,
       lineHeight: leading.xs,
       fontWeight: 500,
     },
     headerActions: { marginInlineEnd: `calc(-1 * ${space.s1_5})`, color: color.mutedForeground },
     actions: { display: "flex", alignItems: "center", gap: space.s0_5 },

     panel: { position: "relative", overflow: "clip", color: color.foreground },
     panelRaised: {
       borderRadius: radius.lg,
       backgroundColor: color.card,
       boxShadow: shadow.raised,
     },

     floatingAnchor: { position: "sticky", top: 0, zIndex: layer.overlay, height: 0 },

     floatingActions: {
       position: "absolute",
       top: space.s2,
       right: space.s2,
       zIndex: layer.overlay,
       padding: space.s0_5,
       borderRadius: radius.lg,
       backgroundColor: color.card,
       boxShadow: shadow.raised,
       color: color.mutedForeground,
       transitionProperty: "opacity",
       transitionDuration: duration.color,
       opacity: {
         default: 0,
         ":focus-within": 1,
         [stylex.when.ancestor(":hover", codeBlockMarker)]: 1,
         "@media (width < 48rem)": 1,
       },
     },

     inlineActions: {
       position: "absolute",
       insetBlock: 0,
       insetInlineEnd: 0,
       zIndex: layer.overlay,
       display: "flex",
       alignItems: "center",
       paddingInlineStart: space.s6,
       paddingInlineEnd: space.s2_5,
       backgroundImage: `linear-gradient(to right, transparent, ${color.card} ${space.s4})`,
       color: color.mutedForeground,
     },
     inlineActionsWrap: {
       alignItems: "flex-start",
       paddingBlockStart: space.s2,
       paddingInlineStart: space.s2,
       backgroundImage: "none",
     },

     viewport: {
       maxHeight: "40rem",
       overflow: "auto",
       paddingBlock: space.s3_5,
       outlineStyle: "none",
     },

     prefixed: {
       display: "flex",
       alignItems: "center",
       gap: space.s1,
       width: "max-content",
       minWidth: "100%",
       paddingInlineStart: "var(--code-pad-x)",
     },
     prefixedWrap: { alignItems: "flex-start", width: "100%" },
     prefixedBody: { display: "flex", flexGrow: 1, alignItems: "center" },
     prefixedBodyWrap: { display: "block", minWidth: 0 },
     prefixWord: { display: "flex", flexShrink: 0 },
     prefixWordWrap: { float: "inline-start" },
     prefixBadge: {
       display: "flex",
       flexShrink: 0,
       alignItems: "center",
       justifyContent: "center",
       width: space.s4,
       height: space.s4,
       borderRadius: radius.sm,
       backgroundColor: color.foreground,
       color: color.background,
     },
     prefixBadgeWrap: { marginBlockStart: `calc((1.625em - ${space.s4}) / 2)` },
     prefixGlyph: { width: "0.6875rem", height: "0.6875rem" },
     prefixTrigger: {
       height: "auto",
       gap: space.s1,
       paddingInlineStart: space.s1,
       paddingInlineEnd: space.s1,
       marginInlineEnd: `calc(-1 * ${space.s1})`,
       paddingBlock: space.s0_5,
       borderRadius: radius.md,
       borderColor: color.transparent,
       boxShadow: { default: "none", ":focus-visible": shadow.ring },
       backgroundColor: { default: color.transparent, ":hover": color.muted },
       fontFamily: font.mono,
       fontSize: "inherit",
       lineHeight: "inherit",
       color: codeCommand,
       userSelect: "text",
       "--arene-icon-size": space.s3,
     },
     prefixTriggerWrap: {
       paddingBlock: 0,
       marginBlock: "-1px",
       marginInlineEnd: 0,
       lineHeight: 1.625,
     },
     prefixItem: { fontFamily: font.mono, fontSize: text.code, lineHeight: leading.code },

     viewportFlush: { maxHeight: "none" },

     viewportCompact: { paddingBlock: space.s2 },

     viewportWrapReserve: {
       "--code-pad-end": `calc(2 * ${space.s6} + ${space.s0_5} + ${space.s2_5} + ${space.s2})`,
     },

     pre: {
       width: "max-content",
       minWidth: "100%",
       paddingInlineStart: "var(--code-pad-start, var(--code-pad-x))",
       paddingInlineEnd: "var(--code-pad-end, var(--code-pad-x))",
       fontFamily: font.mono,
       lineHeight: 1.625,
       tabSize: 2,
     },
     preWrap: { width: "100%", whiteSpace: "pre-wrap", overflowWrap: "anywhere" },

     icon: { flexShrink: 0, "--arene-icon-size": space.s3_5 },
     actionIcon: { color: { default: null, ":hover": color.foreground } },
     actionIconPressed: { color: color.foreground, backgroundColor: color.muted },

     copySwatch: {
       position: "relative",
       display: "flex",
       width: space.s3_5,
       height: space.s3_5,
       alignItems: "center",
       justifyContent: "center",
     },
     copyGlyph: {
       position: "absolute",
       transitionProperty: "transform, opacity",
       transitionDuration: {
         default: duration.move,
         "@media (prefers-reduced-motion: reduce)": "0s",
       },
     },
     copyGlyphHidden: { transform: "scale(0.5)", opacity: 0 },

     tabsRoot: {
       borderRadius: radius.xl,
       padding: space.s1,
       backgroundColor: color.tray,
     },
   })

   type CodeBlockRootProps = useRender.ComponentProps<"figure"> &
     Overrides & {
       allowCopy?: boolean | "true" | "false"
       keepBackground?: boolean
       wrap?: boolean
       defaultWrap?: boolean
       onWrapChange?: (wrap: boolean) => void
       "data-line-numbers"?: boolean | "true" | "false"
       "data-line-numbers-start"?: number | string
     }

   function CodeBlockRoot({
     render,
     ref,
     allowCopy = true,
     keepBackground = false,
     wrap: wrapProp,
     defaultWrap = false,
     onWrapChange,
     xstyle,
     style,
     className,
     children,
     "data-line-numbers": lineNumbers,
     "data-line-numbers-start": lineNumbersStart,
     ...props
   }: CodeBlockRootProps) {
     const viewportRef = useRef<HTMLElement>(null)
     const inTabs = use(InTabsContext)
     const frame: CodeBlockFrame = inTabs
       ? "panel"
       : use(CodeBlockFrameContext) === "flush"
         ? "flush"
         : "tray"
     const numbered = lineNumbers !== false && lineNumbers !== "false"
     const [uncontrolledWrap, setUncontrolledWrap] = useState(defaultWrap)
     const wrap = wrapProp ?? uncontrolledWrap
     const setWrap = (next: boolean) => {
       setUncontrolledWrap(next)
       onWrapChange?.(next)
     }
     const overflows = useOverflows(viewportRef)

     const sx = stylex.props(styles.root, frame === "tray" && styles.rootTray, codeBlockMarker, xstyle)

     const element = useRender({
       defaultTagName: "figure",
       render,
       ref,
       props: {
         dir: "ltr",
         "data-slot": "code-block",
         "data-frame": frame,
         "data-line-numbers": numbered,
         "data-line-numbers-start": lineNumbersStart,
         "data-wrap": wrap,
         ...sx,
         ...props,
         style: { ...sx.style, ...style },
         className: clsx("not-typeset", sx.className, className),
         children,
       },
     })

     return (
       <CodeBlockContext
         value={{
           frame,
           viewportRef,
           copyable: allowCopy !== false && allowCopy !== "false",
           numbered,
           lineNumbersStart,
           keepBackground,
           wrap,
           setWrap,
           overflows,
         }}
       >
         {element}
       </CodeBlockContext>
     )
   }

   function CodeBlockHeader({
     render,
     ref,
     xstyle,
     style,
     className,
     ...props
   }: useRender.ComponentProps<"div"> & Overrides) {
     const sx = stylex.props(styles.header, xstyle)
     return useRender({
       defaultTagName: "div",
       render,
       ref,
       props: {
         "data-slot": "code-block-header",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
   }

   type CodeBlockTitleProps = useRender.ComponentProps<"figcaption"> &
     Overrides & {
       icon?: ReactNode
     }

   function CodeBlockTitle({
     render,
     ref,
     icon,
     xstyle,
     style,
     className,
     ...props
   }: CodeBlockTitleProps) {
     const sx = stylex.props(styles.caption, xstyle)
     const caption = useRender({
       defaultTagName: "figcaption",
       render,
       ref,
       props: {
         "data-slot": "code-block-title",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })

     return (
       <>
         <CodeBlockIcon icon={icon} />
         {caption}
       </>
     )
   }

   type CodeBlockActionsProps = Omit<useRender.ComponentProps<"div">, "children"> &
     Overrides & {
       floating?: boolean
     }

   function CodeBlockActions({
     render,
     ref,
     floating = false,
     xstyle,
     style,
     className,
     ...props
   }: CodeBlockActionsProps) {
     const { frame, copyable, wrap, setWrap, overflows } = useCodeBlock("CodeBlockActions")
     const wrappable = wrap || overflows
     const anchored = floating && frame === "flush"
     const placement = !floating
       ? styles.headerActions
       : frame === "panel"
         ? [styles.inlineActions, wrap && styles.inlineActionsWrap]
         : styles.floatingActions

     const buttons = (
       <div {...stylex.props(styles.actions)}>
         {wrappable && <CodeBlockWrapButton wrap={wrap} onWrapChange={setWrap} />}
         {copyable && <CodeBlockCopyButton />}
       </div>
     )

     const sx = stylex.props(anchored ? styles.floatingAnchor : placement, xstyle)
     const element = useRender({
       defaultTagName: "div",
       render,
       ref,
       props: {
         "data-slot": "code-block-actions",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
         children: anchored ? <div {...stylex.props(placement)}>{buttons}</div> : buttons,
       },
     })

     return wrappable || copyable ? element : null
   }

   function CodeBlockPanel({
     render,
     ref,
     xstyle,
     style,
     className,
     onFocus,
     onBlur,
     ...props
   }: useRender.ComponentProps<"div"> & Overrides) {
     const { frame, viewportRef, keepBackground } = useCodeBlock("CodeBlockPanel")
     const [focused, setFocused] = useState(false)
     const sx = stylex.props(
       styles.panel,
       frame !== "flush" && styles.panelRaised,
       focused && states.fieldFocusedInset,
       xstyle,
     )
     return useRender({
       defaultTagName: "div",
       render,
       ref,
       props: {
         "data-slot": "code-block-panel",
         "data-keep-background": keepBackground,
         ...sx,
         ...props,
         onFocus: (event: FocusEvent<HTMLDivElement>) => {
           if (event.target === viewportRef.current) {
             setFocused(event.target.matches(":focus-visible"))
           }
           onFocus?.(event)
         },
         onBlur: (event: FocusEvent<HTMLDivElement>) => {
           if (event.target === viewportRef.current) setFocused(false)
           onBlur?.(event)
         },
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
   }

   type CodeBlockViewportProps = useRender.ComponentProps<"section"> &
     Overrides & {
       reserveActions?: boolean
     }

   function prefixedSelection(body: HTMLElement) {
     const word = body.firstElementChild
     const line = body.querySelector(".line")
     const selection = window.getSelection()
     if (!word || !line || !selection?.rangeCount) return null
     const range = selection.getRangeAt(0)
     if (!body.contains(range.startContainer) || !body.contains(range.endContainer)) return null
     return { word, line, selection, range }
   }

   function usePrefixedSelection(bodyRef: RefObject<HTMLDivElement | null>, prefixed: boolean) {
     useEffect(() => {
       const body = bodyRef.current
       if (!body) return

       const selectWord = (event: MouseEvent) => {
         if (event.detail < 2) return
         const found = prefixedSelection(body)
         if (!found) return
         const { word, line, selection, range } = found
         const lead = document.createRange()
         lead.setStart(line, 0)
         lead.setEnd(range.startContainer, range.startOffset)
         const skipped = lead.toString().trim()
         if (skipped !== "" && skipped !== line.firstElementChild?.textContent) return
         selection.setBaseAndExtent(word, 0, range.endContainer, range.endOffset)
       }

       const copyCommand = (event: ClipboardEvent) => {
         const found = prefixedSelection(body)
         if (!found || !event.clipboardData || !found.range.intersectsNode(found.word)) return
         const command = document.createRange()
         command.setStart(found.line, 0)
         command.setEnd(found.range.endContainer, found.range.endOffset)
         event.preventDefault()
         event.clipboardData.setData("text/plain", command.toString().trimEnd())
       }

       body.addEventListener("click", selectWord)
       body.addEventListener("copy", copyCommand)
       return () => {
         body.removeEventListener("click", selectWord)
         body.removeEventListener("copy", copyCommand)
       }
     }, [bodyRef, prefixed])
   }

   function CodeBlockViewport({
     render,
     ref,
     reserveActions = false,
     xstyle,
     style,
     className,
     children,
     ...props
   }: CodeBlockViewportProps) {
     const { frame, viewportRef, numbered, lineNumbersStart, wrap } = useCodeBlock("CodeBlockViewport")
     const prefix = use(CodeBlockPrefixContext)
     const prefixedBodyRef = useRef<HTMLDivElement>(null)
     usePrefixedSelection(prefixedBodyRef, prefix != null)
     const reserveWrapped = reserveActions && wrap && frame === "panel"
     const sx = stylex.props(
       styles.viewport,
       prefix != null && styles.viewportCompact,
       frame === "flush" && styles.viewportFlush,
       reserveWrapped && styles.viewportWrapReserve,
       xstyle,
     )
     const viewportStyle: CSSProperties & {
       "--code-pad-end": string | undefined
       "--code-pad-start": string | undefined
     } = {
       ...sx.style,
       "--code-pad-end": reserveActions && !reserveWrapped ? "2.75rem" : undefined,
       "--code-pad-start": prefix ? "0px" : undefined,
       counterSet: numbered ? `line ${Number(lineNumbersStart ?? 1) - 1}` : undefined,
       ...style,
     }

     return useRender({
       defaultTagName: "section",
       render,
       ref: [ref ?? null, viewportRef],
       props: {
         tabIndex: 0,
         "data-slot": "code-block-viewport",
         ...sx,
         ...props,
         className: clsx("mdx-scrollbar scroll-fade-x scroll-fade-y", sx.className, className),
         children: prefix ? (
           <div
             data-slot="code-block-prefixed"
             {...stylex.props(styles.prefixed, wrap && styles.prefixedWrap)}
           >
             <span aria-hidden {...stylex.props(styles.prefixBadge, wrap && styles.prefixBadgeWrap)}>
               <TerminalIcon aria-hidden="true" weight="bold" {...stylex.props(styles.prefixGlyph)} />
             </span>
             <div
               ref={prefixedBodyRef}
               {...stylex.props(styles.prefixedBody, wrap && styles.prefixedBodyWrap)}
             >
               <span {...stylex.props(styles.prefixWord, wrap && styles.prefixWordWrap)}>
                 {prefix}
               </span>
               {children}
             </div>
           </div>
         ) : (
           children
         ),
         style: viewportStyle,
       },
     })
   }

   type CodeBlockProps = Omit<CodeBlockRootProps, "title"> & {
     title?: ReactNode
     icon?: ReactNode
     viewportProps?: CodeBlockViewportProps
   }

   function CodeBlock({ title, icon, viewportProps, children, ...props }: CodeBlockProps) {
     return (
       <CodeBlockRoot {...props}>
         {title && (
           <CodeBlockHeader>
             <CodeBlockTitle icon={icon}>{title}</CodeBlockTitle>
             <CodeBlockActions />
           </CodeBlockHeader>
         )}
         <CodeBlockPanel>
           {!title && <CodeBlockActions floating />}
           <CodeBlockViewport
             aria-label={typeof title === "string" ? `Code: ${title}` : "Code block"}
             reserveActions={!title}
             {...viewportProps}
           >
             {children}
           </CodeBlockViewport>
         </CodeBlockPanel>
       </CodeBlockRoot>
     )
   }

   function Pre({
     render,
     ref,
     style,
     xstyle,
     className,
     ...props
   }: useRender.ComponentProps<"pre"> & Overrides) {
     const wrap = use(CodeBlockContext)?.wrap ?? false
     const sx = stylex.props(styles.pre, wrap && styles.preWrap, xstyle)
     return useRender({
       defaultTagName: "pre",
       render,
       ref,
       props: {
         "data-slot": "code-block-pre",
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })
   }

   function useOverflows(ref: RefObject<HTMLElement | null>) {
     const [overflows, setOverflows] = useState(false)

     useEffect(() => {
       const viewport = ref.current
       if (!viewport) return

       const check = () => setOverflows(viewport.scrollWidth > viewport.clientWidth + 1)
       const observer = new ResizeObserver(check)
       observer.observe(viewport)

       const pre = viewport.querySelector("pre")
       if (pre) observer.observe(pre)

       check()
       return () => observer.disconnect()
     }, [ref])

     return overflows
   }

   function CodeBlockWrapButton({
     wrap,
     onWrapChange,
   }: {
     wrap: boolean
     onWrapChange: (wrap: boolean) => void
   }) {
     return (
       <Button
         variant="ghost"
         size="icon-xs"
         onClick={() => onWrapChange(!wrap)}
         aria-pressed={wrap}
         aria-label={wrap ? "Disable soft wrap" : "Enable soft wrap"}
         xstyle={[styles.actionIcon, wrap && styles.actionIconPressed]}
       >
         <TextAlignLeftIcon aria-hidden="true" {...stylex.props(styles.icon)} />
       </Button>
     )
   }

   function CodeBlockIcon({ icon }: { icon?: ReactNode }) {
     if (!icon) return null

     const iconSx = stylex.props(styles.icon)

     if (typeof icon === "string") {
       return (
         <span
           aria-hidden
           {...iconSx}
           className={clsx("arene-icons", iconSx.className)}
           dangerouslySetInnerHTML={{ __html: icon }}
         />
       )
     }

     return (
       <span {...iconSx} className={clsx("arene-icons", iconSx.className)}>
         {icon}
       </span>
     )
   }

   function CodeBlockCopyButton({ xstyle, ...props }: ButtonProps) {
     const { viewportRef } = useCodeBlock("CodeBlockCopyButton")
     const [copied, setCopied] = useState(false)

     useEffect(() => {
       if (!copied) return
       const timeout = setTimeout(() => setCopied(false), 1600)
       return () => clearTimeout(timeout)
     }, [copied])

     const copy = useCallback(() => {
       const pre = viewportRef.current?.querySelector("pre")
       if (!pre) return

       const clone = pre.cloneNode(true)
       if (!(clone instanceof HTMLElement)) return
       for (const line of clone.querySelectorAll(".line.diff.remove")) {
         const newline = line.nextSibling
         if (newline?.nodeType === Node.TEXT_NODE && newline.textContent === "\n") newline.remove()
         line.remove()
       }

       void navigator.clipboard.writeText(clone.textContent ?? "").then(() => setCopied(true))
     }, [viewportRef])

     return (
       <Button
         variant="ghost"
         size="icon-xs"
         onClick={copy}
         aria-label={copied ? "Copied" : "Copy code"}
         xstyle={[styles.actionIcon, xstyle]}
         {...props}
       >
         <span {...stylex.props(styles.copySwatch)}>
           <CopyIcon
             aria-hidden="true"
             {...stylex.props(styles.copyGlyph, copied && styles.copyGlyphHidden)}
           />
           <CheckIcon
             aria-hidden="true"
             {...stylex.props(styles.copyGlyph, !copied && styles.copyGlyphHidden)}
           />
         </span>
       </Button>
     )
   }

   type CodeBlockTabOption = { value: string; prefix: string }

   type CodeBlockTabsContextValue = {
     value: string
     options: readonly CodeBlockTabOption[]
     onValueChange: (value: string) => void
   }

   const CodeBlockTabsContext = createContext<CodeBlockTabsContextValue | null>(null)

   function useCodeBlockTabs(part: string) {
     const context = use(CodeBlockTabsContext)
     if (!context) throw new Error(`<${part}> must be rendered inside <CodeBlockTabs>`)
     return context
   }

   function optionsFrom(children: ReactNode): CodeBlockTabOption[] {
     return Children.toArray(children).flatMap((child) =>
       isValidElement<CodeBlockTabProps>(child) && typeof child.props.value === "string"
         ? [{ value: child.props.value, prefix: child.props.prefix ?? child.props.value }]
         : [],
     )
   }

   type CodeBlockTabsProps = useRender.ComponentProps<"div"> &
     Overrides & {
       defaultValue: string
       groupId?: string
       persist?: boolean
     }

   function CodeBlockTabs({
     render,
     ref,
     defaultValue,
     groupId,
     persist = false,
     xstyle,
     style,
     className,
     children,
     ...props
   }: CodeBlockTabsProps) {
     const [value, onValueChange] = useTabGroup(defaultValue, groupId, persist)
     const sx = stylex.props(styles.tabsRoot, xstyle)

     const element = useRender({
       defaultTagName: "div",
       render,
       ref,
       props: {
         "data-slot": "code-block-tabs",
         ...sx,
         ...props,
         className: clsx("not-typeset", sx.className, className),
         style: { ...sx.style, ...style },
         children: <InTabsContext value={true}>{children}</InTabsContext>,
       },
     })

     return (
       <CodeBlockTabsContext value={{ value, options: optionsFrom(children), onValueChange }}>
         {element}
       </CodeBlockTabsContext>
     )
   }

   function CodeBlockTabsSelect({ "aria-label": label }: { "aria-label": string }) {
     const { value, options, onValueChange } = useCodeBlockTabs("CodeBlockTabsSelect")
     const { wrap } = useCodeBlock("CodeBlockTabsSelect")

     return (
       <Select
         value={value}
         items={options.map((option) => ({ value: option.value, label: option.prefix }))}
         onValueChange={(next: string | null) => {
           if (next != null) onValueChange(next)
         }}
       >
         <SelectTrigger
           size="sm"
           icon={null}
           aria-label={label}
           xstyle={[styles.prefixTrigger, wrap && styles.prefixTriggerWrap]}
         >
           <SelectValue />
         </SelectTrigger>
         <SelectContent>
           {options.map((option) => (
             <SelectItem key={option.value} value={option.value} xstyle={styles.prefixItem}>
               {option.prefix}
             </SelectItem>
           ))}
         </SelectContent>
       </Select>
     )
   }

   type CodeBlockTabProps = useRender.ComponentProps<"div"> &
     Overrides & {
       value: string
       prefix?: string
       selectLabel?: string
     }

   function CodeBlockTab({
     render,
     ref,
     value,
     prefix: _prefix,
     selectLabel = "Package manager",
     xstyle,
     style,
     className,
     ...props
   }: CodeBlockTabProps) {
     const { value: active } = useCodeBlockTabs("CodeBlockTab")
     const sx = stylex.props(xstyle)

     const element = useRender({
       defaultTagName: "div",
       render,
       ref,
       props: {
         "data-slot": "code-block-tab",
         "data-value": value,
         hidden: value !== active,
         ...sx,
         ...props,
         className: clsx(sx.className, className),
         style: { ...sx.style, ...style },
       },
     })

     return (
       <CodeBlockPrefixContext value={<CodeBlockTabsSelect aria-label={selectLabel} />}>
         {element}
       </CodeBlockPrefixContext>
     )
   }

   export {
     CodeBlock,
     CodeBlockActions,
     CodeBlockFrameContext,
     CodeBlockCopyButton,
     CodeBlockHeader,
     CodeBlockPanel,
     CodeBlockRoot,
     CodeBlockTitle,
     CodeBlockViewport,
     CodeBlockTab,
     CodeBlockTabs,
     Pre,
   }
   ```

5. Change the `@/` imports if your project uses different aliases.

## Usage

```tsx
import { CodeBlock, Pre } from "@/components/ui/code-block"
```

```tsx
<CodeBlock title="Terminal">
  <Pre>
    <code>{output}</code>
  </Pre>
</CodeBlock>
```

## Composition

```text
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.

```tsx
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](https://www.arene.style/docs/components/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.

```tsx
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.

```tsx
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`.

```tsx
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>
  )
}
```

```tsx
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.

```tsx
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`.

```tsx
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.

```tsx
"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:

```bash
npm install @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).

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

> **Note**
>
> 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](https://diffs.com/docs#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()`.

```tsx
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.

```css title="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:

| Prop            | Type                     | Default |
| --------------- | ------------------------ | ------- |
| `title`         | `ReactNode`              | —       |
| `icon`          | `ReactNode`              | —       |
| `viewportProps` | `CodeBlockViewportProps` | —       |

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.

| Prop                      | Type                      | Default |
| ------------------------- | ------------------------- | ------- |
| `wrap`                    | `boolean`                 | —       |
| `defaultWrap`             | `boolean`                 | `false` |
| `onWrapChange`            | `(wrap: boolean) => void` | —       |
| `allowCopy`               | `boolean`                 | `true`  |
| `keepBackground`          | `boolean`                 | `false` |
| `data-line-numbers`       | `boolean`                 | `true`  |
| `data-line-numbers-start` | `number \| string`        | `1`     |

### 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.

| Prop       | Type      | Default |
| ---------- | --------- | ------- |
| `floating` | `boolean` | `false` |

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

### CodeBlockCopyButton

A ghost `icon-xs` [Button](https://www.arene.style/docs/components/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.

| Prop             | Type      | Default |
| ---------------- | --------- | ------- |
| `reserveActions` | `boolean` | `false` |

`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

| Prop           | On              | Type      | Default             |
| -------------- | --------------- | --------- | ------------------- |
| `defaultValue` | `CodeBlockTabs` | `string`  | —                   |
| `groupId`      | `CodeBlockTabs` | `string`  | —                   |
| `persist`      | `CodeBlockTabs` | `boolean` | `false`             |
| `value`        | `CodeBlockTab`  | `string`  | —                   |
| `prefix`       | `CodeBlockTab`  | `string`  | `value`             |
| `selectLabel`  | `CodeBlockTab`  | `string`  | `"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

| Attribute                         | On             | Effect                                            |
| --------------------------------- | -------------- | ------------------------------------------------- |
| `data-slot="code-block"`          | the figure     | Where `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 panel      | `keepBackground` 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-frame`                      | the figure     | `tray`, `panel` inside tabs, or `flush`           |
| `data-wrap`                       | the figure     | `true` while wrapped                              |
| `data-line-numbers`               | the figure     | `mdx.css` numbers highlighted lines when `true`   |
| `data-keep-background`            | the panel      | `mdx.css` paints the theme background when `true` |

### CSS variables

| Variable           | On            | Effect                                                           |
| ------------------ | ------------- | ---------------------------------------------------------------- |
| `--code-pad-x`     | the figure    | Inline padding of the text, `1rem`                               |
| `--code-pad-start` | the viewport  | Start padding of the text. `--code-pad-x` when unset             |
| `--code-pad-end`   | the viewport  | End padding of the text. `--code-pad-x`, or room for the actions |
| `--code-gutter`    | `.highlights` | The width of the line-number gutter                              |
