# Animated Code Block for UI SDK (/docs/components/code-block)

Lines cascade in from the left, a highlighted line's band sweeps across and follows the highlight when it moves, and copying pops a tick that draws itself.

<ComponentPreview slug="code-block" source="{&#x22;code&#x22;:&#x22;\&#x22;use client\&#x22;\n\nimport * as React from \&#x22;react\&#x22;\n\nimport {\n  CodeBlock,\n  CodeBlockActions,\n  CodeBlockContent,\n  CodeBlockCopyButton,\n  CodeBlockHeader,\n  CodeBlockTitle,\n} from \&#x22;@/components/keyframery/code-block\&#x22;\n\nconst code = `import { addMinutes, format, isBefore } from \&#x22;date-fns\&#x22;\n\n// Loaves leave the oven at 7:10 and 11:40.\nconst BAKES = [\&#x22;07:10\&#x22;, \&#x22;11:40\&#x22;] as const\n\nexport function pickupSlots(order: Order, now = new Date()) {\n  const ready = nextBake(BAKES, order.items, now)\n  const slots: Slot[] = []\n  for (let t = ready; isBefore(t, closing(now)); t = addMinutes(t, 20)) {\n    slots.push({ time: t, label: format(t, \&#x22;h:mm a\&#x22;) })\n  }\n  return slots.slice(0, 6)\n}\n`\n\nconst steps = [\n  { id: \&#x22;bakes\&#x22;, label: \&#x22;Bake times\&#x22;, lines: [3, 4] },\n  { id: \&#x22;slots\&#x22;, label: \&#x22;Every 20 min\&#x22;, lines: [7, 8, 9, 10, 11] },\n  { id: \&#x22;trim\&#x22;, label: \&#x22;First six\&#x22;, lines: [12] },\n] as const\n\nexport default function CodeBlockDemo({\n  lineNumbers = true,\n  wrap = false,\n  size = \&#x22;default\&#x22;,\n  themeFace = \&#x22;\&#x22;,\n  themeInk = \&#x22;\&#x22;,\n  themeMuted = \&#x22;\&#x22;,\n  themeRadius = 14,\n  themeFont = 12.5,\n  themeInsetX = 14,\n  themeInsetY = 12,\n}: {\n  lineNumbers?: boolean\n  wrap?: boolean\n  size?: \&#x22;default\&#x22; | \&#x22;sm\&#x22;\n  themeFace?: string\n  themeInk?: string\n  themeMuted?: string\n  themeRadius?: number\n  themeFont?: number\n  themeInsetX?: number\n  themeInsetY?: number\n}) {\n  const [step, setStep] = React.useState<(typeof steps)[number][\&#x22;id\&#x22;]>(\&#x22;slots\&#x22;)\n  const highlight = steps.find((s) => s.id === step)?.lines ?? []\n\n  /* Leave defaults unset so each part keeps its own theme and size fallback. */\n  const theme = {\n    ...(themeFace ? { \&#x22;--code-block-face\&#x22;: themeFace } : null),\n    ...(themeInk ? { \&#x22;--code-block-ink\&#x22;: themeInk } : null),\n    ...(themeMuted ? { \&#x22;--code-block-muted\&#x22;: themeMuted } : null),\n    ...(themeRadius !== 14 ? { \&#x22;--code-block-radius\&#x22;: `${themeRadius}px` } : null),\n    ...(themeFont !== 12.5 ? { \&#x22;--code-block-font\&#x22;: `${themeFont}px` } : null),\n    ...(themeInsetX !== 14 ? { \&#x22;--code-block-inset-x\&#x22;: `${themeInsetX}px` } : null),\n    ...(themeInsetY !== 12 ? { \&#x22;--code-block-inset-y\&#x22;: `${themeInsetY}px` } : null),\n  } as React.CSSProperties\n\n  return (\n    <div style={theme} className=\&#x22;@container w-full max-w-[600px]\&#x22;>\n      <div className=\&#x22;mb-3 flex items-center justify-between gap-3 @max-[30rem]:flex-col @max-[30rem]:items-start\&#x22;>\n        <div className=\&#x22;min-w-0\&#x22;>\n          <div className=\&#x22;text-[15px] font-semibold tracking-tight\&#x22;>Pickup times for pre-orders</div>\n          <p className=\&#x22;mt-1 text-[12px] text-muted-foreground\&#x22;>Rye &amp; Sons bakery, order app</p>\n        </div>\n        <div\n          role=\&#x22;group\&#x22;\n          aria-label=\&#x22;Walk through the code\&#x22;\n          className=\&#x22;flex shrink-0 gap-0.5 rounded-[11px] bg-muted p-0.5 shadow-[inset_0_1px_2px_rgb(0_0_0/0.07),inset_0_0_0_1px_rgb(0_0_0/0.035)] dark:shadow-[inset_0_1px_2px_rgb(0_0_0/0.5),inset_0_0_0_1px_rgb(255_255_255/0.04)]\&#x22;\n        >\n          {steps.map((s) => (\n            <button\n              key={s.id}\n              type=\&#x22;button\&#x22;\n              data-step={s.id}\n              aria-pressed={step === s.id}\n              onClick={() => setStep(s.id)}\n              className={[\n                \&#x22;h-7 rounded-[9px] px-2.5 text-[12px] leading-none font-medium whitespace-nowrap outline-none transition-[color,scale] duration-[calc(150ms*var(--kf-speed,1))] ease-house active:scale-[0.96] focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none\&#x22;,\n                step === s.id\n                  ? \&#x22;bg-background text-foreground shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_1px_rgb(0_0_0/0.05),0_3px_6px_-2px_rgb(0_0_0/0.1)] dark:bg-accent dark:shadow-[0_0_0_1px_rgb(255_255_255/0.07),inset_0_1px_0_rgb(255_255_255/0.08)]\&#x22;\n                  : \&#x22;text-muted-foreground hover:text-foreground\&#x22;,\n              ].join(\&#x22; \&#x22;)}\n            >\n              {s.label}\n            </button>\n          ))}\n        </div>\n      </div>\n\n      <CodeBlock code={code} language=\&#x22;ts\&#x22; lineNumbers={lineNumbers} wrap={wrap} highlight={[...highlight]} size={size}>\n        <CodeBlockHeader>\n          <CodeBlockTitle>\n            <svg viewBox=\&#x22;0 0 16 16\&#x22; fill=\&#x22;none\&#x22; stroke=\&#x22;currentColor\&#x22; strokeWidth=\&#x22;1.5\&#x22; strokeLinecap=\&#x22;round\&#x22; strokeLinejoin=\&#x22;round\&#x22; aria-hidden>\n              <path d=\&#x22;M9 2.75H5A1.25 1.25 0 0 0 3.75 4v8c0 .69.56 1.25 1.25 1.25h6c.69 0 1.25-.56 1.25-1.25V6L9 2.75Z\&#x22; />\n              <path d=\&#x22;M9 2.75V6h3.25\&#x22; />\n            </svg>\n            lib/pickup-slots.ts\n          </CodeBlockTitle>\n          <CodeBlockActions>\n            <span className=\&#x22;me-1 text-[11.5px] text-muted-foreground @max-[30rem]:hidden\&#x22;>TypeScript</span>\n            <CodeBlockCopyButton />\n          </CodeBlockActions>\n        </CodeBlockHeader>\n        <CodeBlockContent aria-label=\&#x22;pickup-slots.ts\&#x22; />\n      </CodeBlock>\n    </div>\n  )\n}&#x22;,&#x22;bindings&#x22;:{&#x22;lineNumbers&#x22;:[934,938],&#x22;wrap&#x22;:[949,954],&#x22;size&#x22;:[965,974],&#x22;themeFace&#x22;:[990,992],&#x22;themeInk&#x22;:[1007,1009],&#x22;themeMuted&#x22;:[1026,1028],&#x22;themeRadius&#x22;:[1046,1048],&#x22;themeFont&#x22;:[1064,1068],&#x22;themeInsetX&#x22;:[1086,1088],&#x22;themeInsetY&#x22;:[1106,1108]},&#x22;root&#x22;:[2149,4795],&#x22;importOffset&#x22;:211}" />

## Installation [#installation]

**CLI**

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

This adds `components/keyframery/code-block.tsx` and its primitive to your project, and installs UI SDK. The motion tokens are added to your global CSS the first time you install a component.

**Manual**

**Install the dependencies**

```bash
npm install @ui-sdk/core@0.1.0-beta.9 @ui-sdk/react@0.1.0-beta.9 clsx tailwind-merge
```

**Add the motion tokens**

Copy the [motion tokens](/docs/installation#what-the-cli-adds-to-your-css) into your global CSS, and this file into `lib/keyframery.tsx`. Every component shares them.

**lib/keyframery.tsx**

```tsx
"use client"

/* Speed for Keyframery components, as a prop.

   Every duration in the components is written as calc(Nms * var(--kf-speed, 1)). These helpers set
   that variable for you, so nobody has to know it exists:

     <Tabs speed="fast">                      one component
     <KeyframeryProvider speed="slow">        the whole app

   Parts that render in a portal (popups, menus, dialogs) are not inside the component in the page,
   so they pick the speed up through React context instead of the CSS cascade. */

import * as React from "react"

/** `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or any multiplier: `0.8` is 20% quicker. */
export type Speed = "fast" | "normal" | "slow" | number

export type SpeedProps = {
  /** How fast the component moves. `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or a multiplier like `0.8`. Popups follow it too. */
  speed?: Speed
}

export type MotionStyleName = "springy" | "calm" | "snappy" | "playful"

const presets = { fast: 0.6, normal: 1, slow: 1.4 } as const

export function speedValue(speed: Speed | undefined): number | undefined {
  if (speed === undefined) return undefined
  return typeof speed === "number" ? speed : presets[speed]
}

const SpeedContext = React.createContext<number | undefined>(undefined)

type SpeedStyle = React.CSSProperties & { "--kf-speed"?: number }

/* Wraps a component's parts. Without `speed` it adds nothing to the page. With it, a
   `display: contents` element carries the variable to the parts in place, and context carries it
   to the parts in a portal. */
export function Speed({ speed, children }: SpeedProps & { children?: React.ReactNode }) {
  const value = speedValue(speed)
  if (value === undefined) return children
  const style: SpeedStyle = { display: "contents", "--kf-speed": value }
  return (
    <SpeedContext value={value}>
      <span data-slot="speed" style={style}>
        {children}
      </span>
    </SpeedContext>
  )
}

/* For parts that render in a portal: adds the speed of the component they belong to. `style` can
   be an object or UI SDK's function of the part's state. */
export function useSpeedStyle<S>(style: S): S {
  return withSpeed(style, React.useContext(SpeedContext))
}

/* Adds a speed to a part's own `style`, for a part that takes `speed` and renders in a portal. */
export function withSpeed<S>(style: S, speed: Speed | undefined): S {
  const value = speedValue(speed)
  if (value === undefined) return style
  if (typeof style === "function")
    return ((state: unknown) => ({ "--kf-speed": value, ...(style as (s: unknown) => React.CSSProperties)(state) })) as S
  return { "--kf-speed": value, ...(style as React.CSSProperties | undefined) } as S
}

/* UI SDK parts take `children` as content or as a function of the part's state. A styled part
   that adds elements of its own (a chevron, a moving key) wraps either form with this, so the
   function form keeps working. */
export function mapChildren<State>(
  children: React.ReactNode | ((state: State) => React.ReactNode),
  wrap: (content: React.ReactNode) => React.ReactNode,
): React.ReactNode | ((state: State) => React.ReactNode) {
  return typeof children === "function" ? (state: State) => wrap(children(state)) : wrap(children)
}

/* Sets speed and motion style for the whole app, popups included. A component's own `speed` prop
   still wins inside that component. Server-rendered pages can put `data-motion` on <html> directly
   to avoid a change after hydration. */
export function KeyframeryProvider({
  speed,
  motion,
  children,
}: SpeedProps & {
  /** The motion style for the whole app: `"springy"` (the default), `"calm"`, `"snappy"` or `"playful"`. */
  motion?: MotionStyleName
  children?: React.ReactNode
}) {
  const value = speedValue(speed)
  React.useLayoutEffect(() => {
    const html = document.documentElement
    if (motion) html.setAttribute("data-motion", motion)
    if (value !== undefined) html.style.setProperty("--kf-speed", String(value))
    return () => {
      if (motion) html.removeAttribute("data-motion")
      if (value !== undefined) html.style.removeProperty("--kf-speed")
    }
  }, [motion, value])
  return children
}
```

**Copy the component**

**components/keyframery/code-block.tsx**

```tsx
"use client"

export * from "@/components/keyframery/primitives/code-block"

/* Theming variables (set on a part or ancestor; absent values preserve the theme):
   --code-block-face: Code sheet; default: bg-card.
   --code-block-ink: Code text; default: text-card-foreground.
   --code-block-muted: Comments and hints; default: text-muted-foreground.
   --code-block-radius: Sheet corners; default: rounded-[14px].
   --code-block-font: Code size; default: text-[12.5px].
   --code-block-inset-x: Line padding; default: px-3.5.
   --code-block-inset-y: Code padding; default: py-3.
*/

/* Styled code block: the animated primitive plus the Keyframery look. A quiet sheet with a filename
   row, the code on a slightly sunk ground, tokens coloured from the theme's own tokens (keywords in
   the ring colour, strings warm, comments muted), and a small key for copying. */

import * as React from "react"

import {
  CodeBlock as CodeBlockRoot,
  CodeBlockActions as CodeBlockActionsPrimitive,
  CodeBlockContent as CodeBlockContentPrimitive,
  CodeBlockCopyButton as CodeBlockCopyButtonPrimitive,
  CodeBlockFooter as CodeBlockFooterPrimitive,
  CodeBlockHeader as CodeBlockHeaderPrimitive,
  CodeBlockLine as CodeBlockLinePrimitive,
  CodeBlockTitle as CodeBlockTitlePrimitive,
} from "@/components/keyframery/primitives/code-block"
import { Speed, type SpeedProps } from "@/lib/keyframery"
import { cn } from "@/lib/utils"

/* UI SDK accepts a class name or a function of state; keep both working. */
function withClass<S>(base: string, className: string | ((state: S) => string | undefined) | undefined) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

/* Token colours, all from theme tokens. */
const tokens = cn(
  "[&_[data-token=keyword]]:text-ring",
  "[&_[data-token=tag]]:text-ring",
  "[&_[data-token=string]]:text-[color-mix(in_oklab,var(--destructive)_72%,var(--foreground))]",
  "[&_[data-token=number]]:text-[color-mix(in_oklab,var(--destructive)_55%,var(--ring))]",
  "[&_[data-token=comment]]:text-[color:var(--code-block-muted,var(--muted-foreground))] [&_[data-token=comment]]:italic",
  "[&_[data-token=function]]:text-foreground [&_[data-token=function]]:font-medium",
  "[&_[data-token=type]]:text-[color-mix(in_oklab,var(--ring)_55%,var(--foreground))]",
  "[&_[data-token=property]]:text-[color-mix(in_oklab,var(--ring)_40%,var(--foreground))]",
  "[&_[data-token=attribute]]:text-[color-mix(in_oklab,var(--ring)_55%,var(--foreground))]",
  "[&_[data-token=variable]]:text-[color-mix(in_oklab,var(--destructive)_55%,var(--ring))]",
  "[&_[data-token=punctuation]]:text-[color:var(--code-block-muted,var(--muted-foreground))]",
)

function CodeBlock({
  speed,
  className,
  variant = "default",
  size = "default",
  ...props
}: React.ComponentProps<typeof CodeBlockRoot> &
  SpeedProps & {
    /** `"destructive"` for an error or failed output. */
    variant?: "default" | "destructive"
    /** `"sm"` has tighter padding and 12px code, for tool output. */
    size?: "default" | "sm"
  }) {
  return (
    <Speed speed={speed}>
      <CodeBlockRoot
        data-variant={variant}
        data-size={size}
        className={withClass(
          cn(
            "flex w-full min-w-0 flex-col overflow-hidden rounded-[var(--code-block-radius,14px)] bg-[var(--code-block-face,var(--card))] text-[13px] text-[color:var(--code-block-ink,var(--card-foreground))]",
            "shadow-[0_0_0_1px_rgb(0_0_0/0.07),0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.12)]",
            "dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08),0_8px_24px_-12px_rgb(0_0_0/0.7)]",
            "has-[>[data-slot=code-block-content]:focus-visible]:ring-2 has-[>[data-slot=code-block-content]:focus-visible]:ring-ring",
            "data-[size=sm]:rounded-[12px] data-[size=sm]:text-[12px]",
            "data-[variant=destructive]:shadow-[0_0_0_1px_color-mix(in_oklab,var(--destructive)_35%,transparent)]",
            tokens,
          ),
          className,
        )}
        {...props}
      />
    </Speed>
  )
}

function CodeBlockHeader({ className, ...props }: React.ComponentProps<typeof CodeBlockHeaderPrimitive>) {
  return (
    <CodeBlockHeaderPrimitive
      className={withClass(
        cn(
          "flex h-10 min-w-0 shrink-0 items-center gap-2 border-b border-border/70 ps-3.5 pe-1.5 text-[color:var(--code-block-muted,var(--muted-foreground))]",
          "group-data-[size=sm]/code-block:h-8 group-data-[size=sm]/code-block:ps-3",
          "group-data-[variant=destructive]/code-block:text-destructive",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* A filename or a label, with an optional 14px icon before it. It truncates. */
function CodeBlockTitle({ className, ...props }: React.ComponentProps<typeof CodeBlockTitlePrimitive>) {
  return (
    <CodeBlockTitlePrimitive
      className={withClass(
        cn(
          "flex min-w-0 items-center gap-1.5 truncate text-[length:var(--code-block-font,12.5px)] leading-none font-medium text-foreground [&_svg]:size-3.5 [&_svg]:shrink-0 [&_svg]:text-[color:var(--code-block-muted,var(--muted-foreground))]",
          "group-data-[variant=destructive]/code-block:text-destructive",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* Buttons at the end of the header. As a direct child of CodeBlock it floats over the code's corner
   and shows on hover or focus. */
function CodeBlockActions({ className, ...props }: React.ComponentProps<typeof CodeBlockActionsPrimitive>) {
  return (
    <CodeBlockActionsPrimitive
      className={withClass(
        cn(
          "ms-auto flex shrink-0 items-center gap-1",
          "[[data-slot=code-block]>&]:absolute [[data-slot=code-block]>&]:end-2 [[data-slot=code-block]>&]:top-2 [[data-slot=code-block]>&]:z-10",
          "[[data-slot=code-block]>&]:opacity-0 [[data-slot=code-block]>&]:transition-opacity [[data-slot=code-block]>&]:duration-[calc(150ms*var(--kf-speed,1))]",
          "group-hover/code-block:[[data-slot=code-block]>&]:opacity-100 group-focus-within/code-block:[[data-slot=code-block]>&]:opacity-100 group-data-copied/code-block:[[data-slot=code-block]>&]:opacity-100",
          "pointer-coarse:[[data-slot=code-block]>&]:opacity-100 motion-reduce:transition-none",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* A small key. Copied, the tick takes the payoff green. */
function CodeBlockCopyButton({ className, ...props }: React.ComponentProps<typeof CodeBlockCopyButtonPrimitive>) {
  return (
    <CodeBlockCopyButtonPrimitive
      className={withClass(
        cn(
          "grid size-7 shrink-0 cursor-pointer place-items-center rounded-[8px] text-[color:var(--code-block-muted,var(--muted-foreground))] outline-none",
          "hover:bg-foreground/[0.06] hover:text-foreground",
          "[[data-slot=code-block]>[data-slot=code-block-actions]>&]:bg-background [[data-slot=code-block]>[data-slot=code-block-actions]>&]:shadow-[0_0_0_1px_rgb(0_0_0/0.08),0_1px_2px_rgb(0_0_0/0.06)]",
          "dark:[[data-slot=code-block]>[data-slot=code-block-actions]>&]:bg-accent dark:[[data-slot=code-block]>[data-slot=code-block-actions]>&]:shadow-[0_0_0_1px_rgb(255_255_255/0.08)]",
          "data-copied:text-[oklch(0.62_0.16_150)] data-copied:hover:text-[oklch(0.62_0.16_150)]",
          "focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* With no children it renders a styled line for every line of the code. */
function CodeBlockContent({ className, children, ...props }: React.ComponentProps<typeof CodeBlockContentPrimitive>) {
  return (
    <CodeBlockContentPrimitive
      className={withClass(
        cn(
          "min-h-0 min-w-0 overflow-auto py-[var(--code-block-inset-y,0.75rem)] font-mono text-[length:var(--code-block-font,12.5px)] leading-[1.7] outline-none [scrollbar-width:thin]",
          "bg-[color-mix(in_oklab,var(--muted)_45%,var(--card))] dark:bg-[color-mix(in_oklab,var(--muted)_35%,var(--card))]",
          "group-data-[size=sm]/code-block:py-2 group-data-[size=sm]/code-block:text-[11.5px]",
          "data-wrap:whitespace-pre-wrap data-wrap:break-words",
        ),
        className,
      )}
      {...props}
    >
      {children ??
        ((state) => (
          <code data-slot="code-block-code" className="block min-w-max in-data-wrap:min-w-0">
            {state.numbers.map((number) => (
              <CodeBlockLine key={number} value={number} />
            ))}
          </code>
        ))}
    </CodeBlockContentPrimitive>
  )
}

/* A line: gutter number, then the code. Highlighted lines get a band and a ring-coloured edge;
   added and removed lines a tint and a + or − in the gutter, so a diff doesn't rest on colour. */
function CodeBlockLine({ className, ...props }: React.ComponentProps<typeof CodeBlockLinePrimitive>) {
  return (
    <CodeBlockLinePrimitive
      className={withClass(
        cn(
          "grid grid-cols-[1fr] px-[var(--code-block-inset-x,0.875rem)] group-data-[size=sm]/code-block:px-3",
          "in-data-numbered:grid-cols-[2.25rem_1fr] in-data-numbered:ps-1",
          "*:data-[slot=code-block-line-number]:pe-3 *:data-[slot=code-block-line-number]:text-end *:data-[slot=code-block-line-number]:text-muted-foreground/60 *:data-[slot=code-block-line-number]:tabular-nums",
          "*:data-[slot=code-block-line-number]:transition-colors *:data-[slot=code-block-line-number]:duration-[calc(200ms*var(--kf-speed,1))]",
          "data-[variant=highlighted]:*:data-[slot=code-block-line-number]:text-foreground",
          "before:bg-[color-mix(in_oklab,var(--ring)_9%,transparent)] dark:before:bg-[color-mix(in_oklab,var(--ring)_14%,transparent)]",
          "before:shadow-[inset_2px_0_0_var(--ring)]",
          "data-[variant=added]:before:bg-[oklch(0.62_0.16_150/0.1)] data-[variant=added]:before:shadow-[inset_2px_0_0_oklch(0.62_0.16_150)]",
          "data-[variant=removed]:before:bg-[color-mix(in_oklab,var(--destructive)_9%,transparent)] data-[variant=removed]:before:shadow-[inset_2px_0_0_var(--destructive)]",
          "after:absolute after:start-1.5 after:top-0 after:text-[color:var(--code-block-muted,var(--muted-foreground))] after:select-none",
          "data-[variant=added]:after:content-['+'] data-[variant=removed]:after:text-destructive data-[variant=removed]:after:content-['−']",
          "in-data-wrap:*:data-[slot=code-block-line-content]:min-w-0",
        ),
        className,
      )}
      {...props}
    />
  )
}

function CodeBlockFooter({ className, ...props }: React.ComponentProps<typeof CodeBlockFooterPrimitive>) {
  return (
    <CodeBlockFooterPrimitive
      className={withClass("flex min-w-0 shrink-0 items-center gap-2 border-t border-border/70 px-[var(--code-block-inset-x,0.875rem)] py-2 text-[12px] text-[color:var(--code-block-muted,var(--muted-foreground))]", className)}
      {...props}
    />
  )
}

export {
  CodeBlock,
  CodeBlockActions,
  CodeBlockContent,
  CodeBlockCopyButton,
  CodeBlockFooter,
  CodeBlockHeader,
  CodeBlockLine,
  CodeBlockTitle,
}
export { tokenize, type CodeBlockLanguage, type CodeToken, type CodeTokenKind } from "@/components/keyframery/primitives/code-block"
```

**components/keyframery/primitives/code-block.tsx**

```tsx
"use client"

/* Animated code block, on UI SDK's core. UI SDK ships no code block, so the behaviour is defined in
   `@/components/core/code-block` with `definePrimitive` and rendered here. This file adds motion only.
   Colours, radii, shadows and spacing stay yours (style `data-token`, `data-variant` and `data-copied`).

   - Cascade: the lines arrive one after another from the left when the block mounts or the code changes.
   - Draw: a highlighted line's band sweeps in from the left; when the highlight moves, the old bands
     shrink back and the new ones sweep in, top to bottom.
   - Pop and Draw: on copy, the copy icon blurs away, the tick pops in and draws itself, and the button
     sinks under the press. */

import type { StateOf } from "@ui-sdk/core"
import { createParts, type PartProps, usePart } from "@ui-sdk/react/primitive"
import * as React from "react"

import { codeBlock } from "@/components/keyframery/core/code-block-core"
import { cn } from "@/lib/utils"

const parts = createParts(codeBlock, { root: "div", header: "div", title: "div", actions: "div", footer: "div" })

type ClassName<S> = string | ((state: S) => string | undefined) | undefined
/* UI SDK accepts a class name or a function of state; keep both working. */
function withClass<S>(base: string, className: ClassName<S>) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

const keyframes = [
  "@keyframes kf-code-line{from{opacity:0;translate:-10px 0;filter:blur(3px)}}",
  "@keyframes kf-code-tick{from{stroke-dashoffset:1}}",
].join("")

function CodeBlock({ className, ...props }: React.ComponentProps<typeof parts.Root>) {
  return (
    <>
      <style href="kf-code-block" precedence="default">
        {keyframes}
      </style>
      <parts.Root className={withClass("group/code-block relative", className)} {...props} />
    </>
  )
}

const CodeBlockHeader = parts.Header
const CodeBlockTitle = parts.Title
const CodeBlockActions = parts.Actions
const CodeBlockFooter = parts.Footer

function CopyIcon({ className }: { className?: string }) {
  return (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden className={className}>
      <rect x="5.25" y="5.25" width="8" height="8" rx="2" />
      <path d="M10.75 5.25V4.5a1.75 1.75 0 0 0-1.75-1.75H4.5A1.75 1.75 0 0 0 2.75 4.5V9c0 .97.78 1.75 1.75 1.75h.75" />
    </svg>
  )
}

/* The two icons share one cell. Copied: the copy icon shrinks into a blur, the tick pops in from 60%
   and its stroke draws. Back: the tick fades, the copy icon returns. */
const swapIn = "transition-[opacity,scale,filter] duration-[calc(420ms*var(--kf-speed,1))] ease-pop motion-reduce:transition-none!"
const swapOut = "transition-[opacity,scale,filter] duration-[calc(160ms*var(--kf-speed,1))] ease-house motion-reduce:transition-none!"

function CodeBlockCopyButton({
  className,
  children,
  ...props
}: PartProps<"button", StateOf<typeof codeBlock, "copy">>) {
  return usePart(
    codeBlock,
    "copy",
    {},
    {
      ...props,
      className: withClass(
        "relative transition-[scale] duration-[calc(260ms*var(--kf-speed,1))] ease-pop active:scale-[0.92] active:duration-[calc(90ms*var(--kf-speed,1))] motion-reduce:transition-none!",
        className,
      ),
      children:
        children ??
        ((state) => (
          <>
            <span className="grid place-items-center *:[grid-area:1/1]">
              <CopyIcon className={cn("size-4", state.copied ? cn(swapOut, "scale-50 opacity-0 blur-[3px]") : swapIn)} />
              <svg
                viewBox="0 0 16 16"
                fill="none"
                stroke="currentColor"
                strokeWidth="1.75"
                strokeLinecap="round"
                strokeLinejoin="round"
                aria-hidden
                className={cn("size-4", state.copied ? swapIn : cn(swapOut, "scale-[0.6] opacity-0"))}
              >
                {state.copied && (
                  <path
                    d="M3.5 8.5 6.5 11.5 12.5 4.75"
                    pathLength={1}
                    className="[stroke-dasharray:1] animate-[kf-code-tick_calc(300ms*var(--kf-speed,1))_var(--ease-house)_calc(80ms*var(--kf-speed,1))_backwards] motion-reduce:animate-none"
                  />
                )}
              </svg>
            </span>
          </>
        )),
    },
    "button",
  )
}

/* One line. With no children it renders its tokens, each a span with `data-token` set to its kind. */
function CodeBlockLine({
  value,
  className,
  children,
  ...props
}: { value: string } & Omit<PartProps<"span", StateOf<typeof codeBlock, "line">>, "value">) {
  return usePart(
    codeBlock,
    "line",
    { value },
    {
      ...props,
      className: withClass(
        cn(
          "relative block",
          /* Cascade: each line a beat after the one above it, the first 16 staggered. */
          "animate-[kf-code-line_calc(460ms*var(--kf-speed,1))_var(--ease-spring)_backwards]",
          "[animation-delay:calc(min(var(--code-line-index,0),16)*calc(22ms*var(--kf-speed,1))+calc(60ms*var(--kf-speed,1)))]",
          /* Draw: the band sweeps in from the left. Its surface follows the text colour; restyle it with before:. */
          "before:pointer-events-none before:absolute before:inset-0 before:-z-10 before:origin-left before:scale-x-0 before:content-['']",
          "before:bg-[color-mix(in_oklch,currentColor_7%,transparent)]",
          "before:transition-[scale] before:duration-[calc(180ms*var(--kf-speed,1))] before:ease-house",
          "data-[variant=highlighted]:before:scale-x-100 data-[variant=added]:before:scale-x-100 data-[variant=removed]:before:scale-x-100",
          "data-[variant=highlighted]:before:duration-[calc(560ms*var(--kf-speed,1))] data-[variant=highlighted]:before:ease-spring",
          "data-[variant=highlighted]:before:[transition-delay:calc(min(var(--code-line-index,0),16)*calc(18ms*var(--kf-speed,1)))]",
          "motion-reduce:animate-none! motion-reduce:before:transition-none!",
        ),
        className,
      ),
      children:
        children ??
        ((state) => (
          <>
            {state.lineNumbers && (
              <span data-slot="code-block-line-number" aria-hidden className="select-none">
                {state.number}
              </span>
            )}
            <span data-slot="code-block-line-content">
              {state.tokens.length === 0
                ? "\n"
                : state.tokens.map((token, index) => (
                    <span key={index} data-token={token.kind}>
                      {token.text}
                    </span>
                  ))}
            </span>
          </>
        )),
    },
    "span",
  )
}

/* The scrolling `pre`. With no children it renders a line part for every line of `code`. */
function CodeBlockContent({
  className,
  children,
  ...props
}: PartProps<"pre", StateOf<typeof codeBlock, "content">>) {
  return usePart(
    codeBlock,
    "content",
    {},
    {
      ...props,
      className: withClass("isolate", className),
      children:
        children ??
        ((state) => (
          <code data-slot="code-block-code" className="block min-w-max in-data-wrap:min-w-0">
            {state.numbers.map((number) => (
              <CodeBlockLine key={number} value={number} />
            ))}
          </code>
        )),
    },
    "pre",
  )
}

export {
  CodeBlock,
  CodeBlockActions,
  CodeBlockContent,
  CodeBlockCopyButton,
  CodeBlockFooter,
  CodeBlockHeader,
  CodeBlockLine,
  CodeBlockTitle,
}
export { tokenize, type CodeBlockLanguage, type CodeToken, type CodeTokenKind } from "@/components/keyframery/core/code-block-core"
```

**components/keyframery/core/code-block-core.ts**

```ts
/* A code block, as a UI SDK primitive. UI SDK ships none, so it is defined with its core: the same
   definition renders in React, Vue, Svelte, Solid and web components.

   It owns the code: splitting it into lines, a small tokenizer for a few languages (no highlighting
   package), which lines are highlighted, added or removed, line numbers, and the copy button
   (UI SDK's own copy-button example from "Define a Primitive", plus a screen reader announcement). */

import { announce, css, definePrimitive } from "@ui-sdk/core"

/** What a piece of a line is, for colouring it. */
type CodeTokenKind =
  | "keyword"
  | "string"
  | "number"
  | "comment"
  | "function"
  | "type"
  | "property"
  | "tag"
  | "attribute"
  | "punctuation"
  | "variable"

type CodeToken = { text: string; kind?: CodeTokenKind }

/** The languages the tokenizer knows. Anything else shows as plain text. */
type CodeBlockLanguage = "ts" | "tsx" | "js" | "jsx" | "json" | "css" | "html" | "bash" | "text"

type Rule = [RegExp, CodeTokenKind | ((match: string, rest: string) => CodeTokenKind | undefined) | undefined]

const jsKeywords =
  "import|export|from|as|default|const|let|var|function|return|if|else|for|while|of|in|new|class|extends|async|await|try|catch|finally|throw|type|interface|enum|typeof|instanceof|void|null|undefined|true|false|this|switch|case|break|continue|satisfies|keyof|readonly"

const js: Rule[] = [
  [/\/\*[\s\S]*?(?:\*\/|$)/y, "comment"],
  [/\/\/[^\n]*/y, "comment"],
  [/`(?:\\.|[^`\\])*`?/y, "string"],
  [/"(?:\\.|[^"\\\n])*"?|'(?:\\.|[^'\\\n])*'?/y, "string"],
  [/<\/?[A-Za-z][\w.]*/y, "tag"],
  [/\b\d[\d_]*(?:\.\d+)?(?:e[+-]?\d+)?n?\b/iy, "number"],
  [new RegExp(`\\b(?:${jsKeywords})\\b`, "y"), "keyword"],
  [/[A-Za-z_$][\w$]*/y, (word, rest) => {
    if (/^\s*\(/.test(rest)) return "function"
    if (/^\s*=(?!=)/.test(rest) && /^[a-z]/.test(word)) return undefined
    if (/^[A-Z]/.test(word)) return "type"
    return undefined
  }],
  [/\.(?=[A-Za-z_$])/y, "punctuation"],
  [/=>|[{}()[\];,.:?<>=+\-*/!&|%]/y, "punctuation"],
]

const rules: Record<Exclude<CodeBlockLanguage, "text">, Rule[]> = {
  ts: js,
  tsx: js,
  js,
  jsx: js,
  json: [
    [/"(?:\\.|[^"\\\n])*"(?=\s*:)/y, "property"],
    [/"(?:\\.|[^"\\\n])*"?/y, "string"],
    [/-?\b\d+(?:\.\d+)?(?:e[+-]?\d+)?\b/iy, "number"],
    [/\b(?:true|false|null)\b/y, "keyword"],
    [/[{}[\]:,]/y, "punctuation"],
  ],
  css: [
    [/\/\*[\s\S]*?(?:\*\/|$)/y, "comment"],
    [/@[\w-]+/y, "keyword"],
    [/--[\w-]+/y, "variable"],
    [/[\w-]+(?=\s*:(?!:))/y, "property"],
    [/"(?:\\.|[^"\\\n])*"?|'(?:\\.|[^'\\\n])*'?/y, "string"],
    [/#[0-9a-f]{3,8}\b/iy, "number"],
    [/-?\b\d*\.?\d+(?:px|rem|em|ms|s|%|deg|vh|vw|fr)?\b/y, "number"],
    [/[\w-]+(?=\()/y, "function"],
    [/[{}();:,>+~]/y, "punctuation"],
  ],
  html: [
    [/<!--[\s\S]*?(?:-->|$)/y, "comment"],
    [/<\/?[\w-]+/y, "tag"],
    [/[\w-:]+(?==)/y, "attribute"],
    [/"[^"\n]*"?|'[^'\n]*'?/y, "string"],
    [/\/?>/y, "tag"],
  ],
  bash: [
    [/#[^\n]*/y, "comment"],
    [/"(?:\\.|[^"\\\n])*"?|'[^'\n]*'?/y, "string"],
    [/\$\{?[\w]+\}?/y, "variable"],
    [/(?<=^|\n|&&\s*|\|\s*|;\s*)[\w./-]+/y, "function"],
    [/(?<=\s)--?[\w-]+/y, "attribute"],
    [/[|&;><]+/y, "punctuation"],
  ],
}

/* Splits code into lines of tokens. Multi-line comments and strings keep their kind on every line
   they cross. */
function tokenize(code: string, language: CodeBlockLanguage): CodeToken[][] {
  const source = code.replace(/\n$/, "")
  const list = language === "text" ? undefined : rules[language]
  const tokens: CodeToken[] = []
  if (!list) tokens.push({ text: source })
  else {
    let at = 0
    let plain = ""
    while (at < source.length) {
      let matched = false
      for (const [pattern, kind] of list) {
        pattern.lastIndex = at
        const found = pattern.exec(source)
        if (!found || found[0].length === 0) continue
        const text = found[0]
        if (plain) tokens.push({ text: plain }), (plain = "")
        tokens.push({ text, kind: typeof kind === "function" ? kind(text, source.slice(at + text.length)) : kind })
        at += text.length
        matched = true
        break
      }
      if (!matched) plain += source[at++]
    }
    if (plain) tokens.push({ text: plain })
  }
  const lines: CodeToken[][] = [[]]
  for (const token of tokens) {
    const parts = token.text.split("\n")
    parts.forEach((text, index) => {
      if (index > 0) lines.push([])
      if (text) lines[lines.length - 1].push({ text, kind: token.kind })
    })
  }
  return lines
}

/* Options arrive on every render: tokenize again only when the code or language changed, so the
   state keeps the same lines and nothing re-renders for nothing. */
let lastTokens: { code: string; language: CodeBlockLanguage; lines: CodeToken[][] } | undefined
function linesOf(code: string, language: CodeBlockLanguage) {
  if (lastTokens?.code !== code || lastTokens.language !== language) lastTokens = { code, language, lines: tokenize(code, language) }
  return lastTokens.lines
}

type CodeBlockOptions = {
  /** The code to show and to copy. A trailing newline is ignored. */
  code?: string
  /** Which tokenizer colours it: "ts", "tsx", "js", "jsx", "json", "css", "html", "bash" or "text". */
  language?: CodeBlockLanguage
  /** Numbers each line. */
  lineNumbers?: boolean
  /** The number of the first line. */
  startLine?: number
  /** Line numbers (counting from `startLine`) to mark as highlighted. */
  highlight?: number[]
  /** Line numbers to mark as added, for a diff. */
  added?: number[]
  /** Line numbers to mark as removed, for a diff. */
  removed?: number[]
  /** Wraps long lines instead of scrolling them. */
  wrap?: boolean
  /** Called after the copy button copied the code. */
  onCopy?: (code: string) => void
}

type CodeBlockState = {
  code: string
  language: CodeBlockLanguage
  lines: CodeToken[][]
  lineNumbers: boolean
  startLine: number
  highlight: number[]
  added: number[]
  removed: number[]
  wrap: boolean
  copied: boolean
}

type LineVariant = "default" | "highlighted" | "added" | "removed"

const fromOptions = (options: CodeBlockOptions) => {
  const code = options.code ?? ""
  const language = options.language ?? "text"
  return {
    code,
    language,
    lines: linesOf(code, language),
    lineNumbers: options.lineNumbers ?? false,
    startLine: options.startLine ?? 1,
    highlight: options.highlight ?? [],
    added: options.added ?? [],
    removed: options.removed ?? [],
    wrap: options.wrap ?? false,
  }
}

const variantOf = (state: CodeBlockState, number: number): LineVariant =>
  state.added.includes(number)
    ? "added"
    : state.removed.includes(number)
      ? "removed"
      : state.highlight.includes(number)
        ? "highlighted"
        : "default"

const codeBlock = definePrimitive({
  name: "code-block",
  options: {
    code: "string",
    language: "string",
    lineNumbers: "boolean",
    startLine: "number",
    highlight: "value",
    added: "value",
    removed: "value",
    wrap: "boolean",
    onCopy: "callback",
  },
  controlled: ["code", "language", "copied"],
  state: (options: CodeBlockOptions): CodeBlockState => ({ ...fromOptions(options), copied: false }),
  sync: (options) => fromOptions(options),
  api: (context) => {
    let timer: ReturnType<typeof setTimeout> | undefined
    context.onDestroy(() => clearTimeout(timer))

    /* New code clears an earlier "Copied". */
    let code = context.options().code
    context.onOptions((options) => {
      if (options.code === code) return
      code = options.code
      clearTimeout(timer)
      context.store.set({ copied: false })
    })

    const write = async (text: string) => {
      try {
        await navigator.clipboard.writeText(text)
      } catch {
        /* No clipboard permission (an insecure page, an embedded frame): the old way still works. */
        const area = document.createElement("textarea")
        area.value = text
        area.setAttribute("readonly", "")
        area.style.position = "fixed"
        area.style.opacity = "0"
        document.body.append(area)
        area.select()
        document.execCommand("copy")
        area.remove()
      }
    }

    return {
      /** Copies the code, shows "Copied" for two seconds and tells screen readers. */
      async copy() {
        const text = context.store.get().code
        await write(text)
        clearTimeout(timer)
        context.store.set({ copied: true })
        announce("Copied")
        context.options().onCopy?.(text)
        const el = context.element("copy")
        const speed = (el && parseFloat(getComputedStyle(el).getPropertyValue("--kf-speed"))) || 1
        timer = setTimeout(() => context.store.set({ copied: false }), 2000 * speed)
      },
      /** The numbers of the lines, as keys for the line parts. */
      numbers(state: CodeBlockState) {
        return state.lines.map((_, index) => String(state.startLine + index))
      },
    }
  },
  slots: (slot) => ({
    root: slot<{}, { copied: boolean; wrap: boolean; lineNumbers: boolean }>({
      state: (state) => ({ copied: state.copied, wrap: state.wrap, lineNumbers: state.lineNumbers }),
      attrs: (state) => ({
        "data-language": state.language,
        "data-wrap": state.wrap ? "" : undefined,
        "data-numbered": state.lineNumbers ? "" : undefined,
        "data-copied": state.copied ? "" : undefined,
      }),
    }),
    header: slot({}),
    title: slot({}),
    actions: slot({}),
    footer: slot({}),
    copy: slot<{}, { copied: boolean }>({
      role: "button",
      focus: "native",
      state: (state) => ({ copied: state.copied }),
      attrs: (state) => ({
        type: "button",
        "aria-label": state.copied ? "Copied" : "Copy code",
        "data-copied": state.copied ? "" : undefined,
      }),
      press: ({ api }) => void api.copy(),
    }),
    content: slot<{}, { numbers: string[]; wrap: boolean }>({
      state: (state, part) => ({ numbers: part.api.numbers(state), wrap: state.wrap }),
      attrs: (state) => ({
        tabindex: "0",
        dir: "ltr",
        "data-wrap": state.wrap ? "" : undefined,
        "data-numbered": state.lineNumbers ? "" : undefined,
      }),
    }),
    line: slot<{ value: string }, { tokens: CodeToken[]; number: number; variant: LineVariant; lineNumbers: boolean }>({
      props: { value: "string" },
      state: (state, part) => {
        const number = Number(part.key)
        return {
          tokens: state.lines[number - state.startLine] ?? [],
          number,
          variant: variantOf(state, number),
          lineNumbers: state.lineNumbers,
        }
      },
      attrs: (state, part) => {
        const number = Number(part.key)
        const variant = variantOf(state, number)
        return {
          "data-variant": variant,
          "data-highlighted": variant === "highlighted" ? "" : undefined,
          "data-line": part.key,
          /* Its place among the lines, for a stagger. */
          style: css({ "--code-line-index": number - state.startLine }),
        }
      },
    }),
  }),
  agent: { actions: ["copy"] },
})

export { codeBlock, tokenize, type CodeBlockLanguage, type CodeBlockOptions, type CodeToken, type CodeTokenKind }
```

**Check the import paths**

The files import from `@/components/keyframery/…` and `@/lib/…`. Change those if your project's aliases differ.

## Usage [#usage]

```tsx
import { CodeBlock, CodeBlockContent, CodeBlockCopyButton, CodeBlockHeader, CodeBlockTitle } from "@/components/keyframery/code-block"

export default function Usage() {
  return (
    <CodeBlock code={`npm install @ui-sdk/react @ui-sdk/core`} language="bash">
      <CodeBlockHeader>
        <CodeBlockTitle>Terminal</CodeBlockTitle>
        <CodeBlockCopyButton className="ms-auto" />
      </CodeBlockHeader>
      <CodeBlockContent />
    </CodeBlock>
  )
}
```

### Anatomy [#anatomy]

How the parts fit together:

```text
CodeBlock
├── CodeBlockHeader
│   ├── CodeBlockTitle
│   └── CodeBlockCopyButton
└── CodeBlockContent
```

## Examples [#examples]

### Line numbers and highlighted lines [#line-numbers-and-highlighted-lines]

`lineNumbers` numbers each line; `highlight` takes line numbers, and their bands sweep in from the left.

<ExamplePreview name="code-block/line-numbers">
  ```tsx
  import { CodeBlock, CodeBlockContent, CodeBlockCopyButton, CodeBlockHeader, CodeBlockTitle } from "@/components/keyframery/code-block"

  const code = `{
    "name": "corner-shop",
    "private": true,
    "scripts": {
      "dev": "vite",
      "build": "vite build"
    }
  }`

  export default function CodeBlockLineNumbers() {
    return (
      <CodeBlock code={code} language="json" lineNumbers highlight={[5, 6]} className="max-w-[420px]">
        <CodeBlockHeader>
          <CodeBlockTitle>package.json</CodeBlockTitle>
          <CodeBlockCopyButton className="ms-auto" />
        </CodeBlockHeader>
        <CodeBlockContent />
      </CodeBlock>
    )
  }
  ```
</ExamplePreview>

### A diff [#a-diff]

Mark lines with `added` and `removed`. Each gets a tint and a + or − in the gutter, so the change never rests on colour alone.

<ExamplePreview name="code-block/diff">
  ```tsx
  import { CodeBlock, CodeBlockContent, CodeBlockHeader, CodeBlockTitle } from "@/components/keyframery/code-block"

  const code = `.price {
    font-weight: 500;
    color: #6b6b6b;
    color: var(--muted-foreground);
    font-variant-numeric: tabular-nums;
  }`

  export default function CodeBlockDiff() {
    return (
      <CodeBlock code={code} language="css" removed={[3]} added={[4, 5]} className="max-w-[420px]">
        <CodeBlockHeader>
          <CodeBlockTitle>styles/cart.css</CodeBlockTitle>
        </CodeBlockHeader>
        <CodeBlockContent />
      </CodeBlock>
    )
  }
  ```
</ExamplePreview>

### Floating copy button [#floating-copy-button]

Put `CodeBlockActions` straight inside `CodeBlock` and the copy key floats over the corner, showing on hover or focus.

<ExamplePreview name="code-block/floating-copy">
  ```tsx
  import { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton } from "@/components/keyframery/code-block"

  export default function CodeBlockFloatingCopy() {
    return (
      <CodeBlock code={`git switch -c fix/receipt-totals`} language="bash" size="sm" className="max-w-[420px]">
        <CodeBlockActions>
          <CodeBlockCopyButton />
        </CodeBlockActions>
        <CodeBlockContent className="pe-12" />
      </CodeBlock>
    )
  }
  ```
</ExamplePreview>

## Motion [#motion]

| Move        | What you see                                                                                         |
| ----------- | ---------------------------------------------------------------------------------------------------- |
| **Cascade** | The lines arrive one after another from the left.                                                    |
| **Draw**    | A highlighted line's band sweeps in from the left; the old band shrinks back as the highlight moves. |
| **Pop**     | On copy, the copy icon blurs away and a tick pops in and draws itself.                               |
| **Press**   | The copy key sinks and springs back.                                                                 |

Timing and springiness follow the [motion style](/docs/motion-styles) you set. To change how fast this code block moves, pass `speed`:

```tsx
<CodeBlock speed="fast">
  …
</CodeBlock>
```

`"fast"` is 0.6×, `"slow"` 1.4×, and a number sets the multiplier. With reduced motion turned on, nothing moves: changes happen at once or with a short fade.

## Theming [#theming]

Set these CSS variables on the component or a parent. Leave them unset to follow the light and dark theme. The open Customize panel below the preview lets you try these settings.

| Variable               | What it changes    | Default               |
| ---------------------- | ------------------ | --------------------- |
| `--code-block-face`    | Code sheet         | bg-card               |
| `--code-block-ink`     | Code text          | text-card-foreground  |
| `--code-block-muted`   | Comments and hints | text-muted-foreground |
| `--code-block-radius`  | Sheet corners      | rounded-\[14px]       |
| `--code-block-font`    | Code size          | text-\[12.5px]        |
| `--code-block-inset-x` | Line padding       | px-3.5                |
| `--code-block-inset-y` | Code padding       | py-3                  |

## API reference [#api-reference]

Every part takes `className` and `children`, along with the props of the element it renders. The parts are rendered by UI SDK, so they also take `render`, to draw your own element, and a function of their state for `className` and `style`.

### CodeBlock [#codeblock]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;speed&#x22;,&#x22;type&#x22;:&#x22;\&#x22;fast\&#x22; | \&#x22;normal\&#x22; | \&#x22;slow\&#x22; | number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;How fast the component moves. `\&#x22;fast\&#x22;` (0.6×), `\&#x22;normal\&#x22;` (1×), `\&#x22;slow\&#x22;` (1.4×), or a multiplier like `0.8`. Popups follow it too.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;code&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The code to show and to copy. A trailing newline is ignored.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;onCopy&#x22;,&#x22;type&#x22;:&#x22;(code: string) => void&#x22;,&#x22;full&#x22;:&#x22;(code: string) => void&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Called with the code after the copy button copied it.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;wrap&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Wraps long lines instead of scrolling them.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;language&#x22;,&#x22;type&#x22;:&#x22;\&#x22;text\&#x22; | \&#x22;html\&#x22; | \&#x22;ts\&#x22; | \&#x22;tsx\&#x22; | \&#x22;js\&#x22; | \&#x22;jsx\&#x22; | \&#x22;json\&#x22; | \&#x22;css\&#x22; | \&#x22;bash\&#x22;&#x22;,&#x22;full&#x22;:&#x22;CodeBlockLanguage&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Which tokenizer colours it: \&#x22;ts\&#x22;, \&#x22;tsx\&#x22;, \&#x22;js\&#x22;, \&#x22;jsx\&#x22;, \&#x22;json\&#x22;, \&#x22;css\&#x22;, \&#x22;html\&#x22;, \&#x22;bash\&#x22; or \&#x22;text\&#x22;.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;lineNumbers&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Numbers each line.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;startLine&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The number of the first line.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;highlight&#x22;,&#x22;type&#x22;:&#x22;number[]&#x22;,&#x22;full&#x22;:&#x22;number[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Line numbers, counted from startLine, to highlight.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;added&#x22;,&#x22;type&#x22;:&#x22;number[]&#x22;,&#x22;full&#x22;:&#x22;number[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Line numbers to mark as added, for a diff.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;removed&#x22;,&#x22;type&#x22;:&#x22;number[]&#x22;,&#x22;full&#x22;:&#x22;number[]&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Line numbers to mark as removed, for a diff.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;variant&#x22;,&#x22;type&#x22;:&#x22;\&#x22;default\&#x22; | \&#x22;destructive\&#x22;&#x22;,&#x22;full&#x22;:&#x22;\&#x22;default\&#x22; | \&#x22;destructive\&#x22;&#x22;,&#x22;default&#x22;:&#x22;\&#x22;default\&#x22;&#x22;,&#x22;description&#x22;:&#x22;\&#x22;destructive\&#x22; for an error or failed output.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;size&#x22;,&#x22;type&#x22;:&#x22;\&#x22;default\&#x22; | \&#x22;sm\&#x22;&#x22;,&#x22;full&#x22;:&#x22;\&#x22;default\&#x22; | \&#x22;sm\&#x22;&#x22;,&#x22;default&#x22;:&#x22;\&#x22;default\&#x22;&#x22;,&#x22;description&#x22;:&#x22;\&#x22;sm\&#x22; has tighter padding and 12px code, for tool output.&#x22;,&#x22;required&#x22;:false}]" />

### CodeBlockLine [#codeblockline]

Renders a `<span>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;value&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The line's number, as a string.&#x22;,&#x22;required&#x22;:true}]" />

### Other parts [#other-parts]

These take the props of the element they render, and nothing else:

* `CodeBlockHeader`: a `<div>`
* `CodeBlockTitle`: a `<div>`
* `CodeBlockCopyButton`: a `<button>`
* `CodeBlockContent`: a `<pre>`
* `CodeBlockActions`: a `<div>`
* `CodeBlockFooter`: a `<div>`

## Keyboard [#keyboard]

| Key                       | What it does                                      |
| ------------------------- | ------------------------------------------------- |
| <kbd>Tab</kbd>            | Moves focus to the code, then to the copy button. |
| <kbd>← → ↑ ↓</kbd>        | Scroll the code while it has focus.               |
| <kbd>Enter or Space</kbd> | Copies the code from the copy button.             |

## Accessibility [#accessibility]

Roles, keyboard and focus are declared on the component's UI SDK primitive, and state is announced through the matching ARIA attributes. More in [Accessibility](/docs/accessibility).

## Built on UI SDK's core [#built-on-ui-sdks-core]

UI SDK doesn't ship a code block, so this one is defined with its core: one `definePrimitive` in `components/keyframery/core/code-block-core.ts`, with no React in it. UI SDK's adapters can render that same definition in Vue, Svelte, Solid and web components. To keep your own styling and take only the motion, import from `@/components/keyframery/primitives/code-block`.

## Questions

### How does the animated Code Block for UI SDK move?

Cascade: The lines arrive one after another from the left. Draw: A highlighted line's band sweeps in from the left; the old band shrinks back as the highlight moves. Pop: On copy, the copy icon blurs away and a tick pops in and draws itself. Press: The copy key sinks and springs back.

### Do I need Motion or Framer Motion for the animated Code Block?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### UI SDK has no code block. How is this one built on UI SDK?

Its behaviour is one definition written with UI SDK's core (`definePrimitive`), in `components/keyframery/core/code-block-core.ts`. Its parts are rendered by UI SDK's adapter, so they take `render`, state-based class names and `data-slot`, like every UI SDK component.

### What happens to the Code Block when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
