# Code block

Code the agent shows you in its answer, in a grey well: the file with its folders quiet, Copy, the syntax in six picked inks and a write-in replay. A well of JSON masks any key as it renders, and Copy copies the mask.

Tier: free. Type: component. Category: ai. Tags: agent, chat, keyboard, motion.

## Install

```bash
npx shadcn@latest add https://pixilui.com/r/code-block.json
```

One-time setup: add the registry to `components.json`:

```json
{
  "registries": {
    "@pixilui": "https://pixilui.com/r/{name}.json"
  }
}
```

Files: `components/pixilui/code-block.tsx`.

## Preview

Live preview: https://pixilui.com/components/code-block

Knobs:

- `block`: `code`, `JSON`
- `numbers`: `off`, `on`
- `fold`: `no fold`, `fold at 6`

Signature: Copy on a block with a key: the check draws, the masked key lights once and its dots ripple, and the clipboard holds the mask.

Styles: `lively` (default), `quiet`, set with `data-style` on <html>. The item reads the style through the foundation; it needs no prop. Standalone files: lively https://pixilui.com/r/standalone/code-block.tsx, quiet https://pixilui.com/r/standalone/code-block.quiet.tsx.

## Code

`components/pixilui/code-block.tsx`

```tsx
"use client";

/*
  Code block (B11, locked 3 Dec 2026, design/explorations/components/locked/code): the grey well every code part sits in, and the
  engine the code items share (tool call, diff, file edits, command). A port of the locked code.js, line for line where it
  decides anything; the look is foundation.css section 8 (.pixilui-code, --pixilui-code-*, --pixilui-syn-*).

  - CodeBlock: code the agent shows you in its answer, with its file (folders grey) or its language, Copy and the write-in
    replay (a ref's write(): the lines write in from their left edge a line after another under "Writing").
  - CodeBlockJson: a well of JSON, highlighted (a tool call's arguments or its result). A secret is masked as it renders: its
    prefix, eight dots and its last four, as one token whose tip says it copies masked. The real value never reaches the
    page, and Copy writes the same masked text (the behavior line).
  - A long block folds to a fade with "Show all N lines"; the height glides open and shut (the system's resize).
  - A body whose lines run wider than the well scrolls sideways; then it takes focus, so a keyboard can scroll it too.
  - Copy: the icon turns into its check, the tip says what was copied ("Copied, key masked"), the masked key lights once.

  The shared engine is exported for the other code items: masking, the JSON lines, the small TypeScript reading, the line
  painter with changed-word marks, the quiet blur swap for small text and the system's number roll.
*/

import { forwardRef, useCallback, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState, type ComponentPropsWithoutRef, type CSSProperties, type ReactNode, type Ref } from "react";
import { flushSync } from "react-dom";
import { IconCopyCheck } from "./icons/copy-check";
import { IconDisclosure } from "./icons/disclosure";
import { IconKey } from "./icons/key";
import { cn } from "./lib/utils";
import { prefersReducedMotion } from "./lib/motion/reduced-motion";
import { resize } from "./lib/motion/surface";
import { Button } from "./button";
import { Tooltip } from "./tooltip";

/* ------------------------------------------------------------------ tokens */

/** A token where the element is (a one-file build scopes the tokens to the item's root), as text. */
export function codeToken(el: Element | null, name: string): string {
  const at = el && el.isConnected ? el : typeof document !== "undefined" ? document.documentElement : null;
  return at ? getComputedStyle(at).getPropertyValue(name).trim() : "";
}
/** A duration token in ms ("200ms" or ".2s"); 0 when the token is missing. */
export function codeMs(el: Element | null, name: string): number {
  const v = codeToken(el, name);
  const n = parseFloat(v);
  if (!Number.isFinite(n)) return 0;
  return /\dm?s$/.test(v) && !/ms$/.test(v) ? n * 1000 : n;
}
/** A curve token; without the foundation the browser's plain ease, so nothing throws. */
export const codeCurve = (el: Element | null, name: string) => codeToken(el, name) || "ease";
const can = (el: Element | null | undefined): el is HTMLElement => !!el && typeof (el as HTMLElement).animate === "function";

/* ------------------------------------------------------------------ secrets */

/** The mask's dots: eight, for any key. */
export const codeBlockDots = "••••••••";
const KEY_PREFIX = /^((?:sk|rk|pk)_(?:live|test)_|ghp_|gho_|xox[abpr]-|Bearer\s)?([\s\S]*)$/;
/** A value that looks like a key (sk_live_…, ghp_…, xoxb-…, "Bearer …") is masked even when its key isn't named secret. */
export const codeBlockLooksSecret = /^(?:(?:sk|rk|pk)_(?:live|test)_|ghp_|gho_|xox[abpr]-|Bearer\s)/;
/** A key masked: its prefix, eight dots, its last four. */
export function maskValue(v: string): { prefix: string; last: string; text: string } {
  const m = KEY_PREFIX.exec(String(v))!;
  const prefix = m[1] || "";
  const last = m[2]!.slice(-4);
  return { prefix, last, text: `${prefix}${codeBlockDots}${last}` };
}
/** Secrets inside free text (code, a command's output): the prefix, eight dots, the last four. */
const SECRET_IN_TEXT = /\b((?:sk|rk|pk)_(?:live|test)_|whsec_|ghp_|gho_|xox[abpr]-)([A-Za-z0-9]{8,})\b/g;
/** Free text with every key in it masked (what Copy writes). */
export function maskText(t: string): string {
  return t.replace(SECRET_IN_TEXT, (_, pre: string, body: string) => `${pre}${codeBlockDots}${body.slice(-4)}`);
}
/** Whether free text holds a key. */
export function hasSecret(t: string): boolean {
  SECRET_IN_TEXT.lastIndex = 0;
  const yes = SECRET_IN_TEXT.test(t);
  SECRET_IN_TEXT.lastIndex = 0;
  return yes;
}

/** The words the code items say. Every visible word is here, so a buyer can translate them. */
export type CodeWords = {
  /** Copy's tip. */
  copy: string;
  /** Copy's tip once it has copied. */
  copied: string;
  /** Copy's tip once it has copied a block with a key in it. */
  copiedMasked: string;
  /** Show all of a folded block. */
  showAll: (lines: number) => string;
  /** Fold it again. */
  showFewer: string;
  /** A masked key's tip. */
  secretTip: (what: string) => string;
  /** A masked key's name for a screen reader. */
  secretLabel: (what: string, last: string) => string;
  /** What a masked key is when its key isn't named. */
  secret: string;
  /** A key found in free text. */
  secretKey: string;
  /** A webhook signing secret found in free text. */
  webhookSecret: string;
  /** A body that scrolls sideways, for a screen reader. */
  scrolls: (title: string) => string;
  /** A code block's replay. */
  writing: string;
  /** Copy's accessible name. */
  copyLabel: (what: string) => string;
};

export const codeWords: CodeWords = {
  copy: "Copy",
  copied: "Copied",
  copiedMasked: "Copied, key masked",
  showAll: (n) => `Show all ${n} lines`,
  showFewer: "Show fewer lines",
  secretTip: (what) => `${what}. Copies masked.`,
  secretLabel: (what, last) => `${what}, masked, ends in ${last}`,
  secret: "Secret",
  secretKey: "Secret key",
  webhookSecret: "Webhook signing secret",
  scrolls: (title) => `${title}, scrolls sideways`,
  writing: "Writing",
  copyLabel: (what) => `Copy ${what}`,
};

/** A masked key, as one token: the key mark, the prefix, the dots and the last four. */
export function CodeBlockSecret({ what, prefix, last, words = codeWords }: { what: string; prefix: string; last: string; words?: CodeWords }) {
  return (
    <Tooltip label={words.secretTip(what)}>
      <span className="pixilui-code-secret" tabIndex={0} role="img" data-pxi="" aria-label={words.secretLabel(what, last)}>
        <IconKey />
        <span className="pixilui-code-secret-v">
          {prefix}
          <span className="pixilui-code-dots" aria-hidden="true">
            {codeBlockDots}
          </span>
          <b>{last}</b>
        </span>
      </span>
    </Tooltip>
  );
}

/** Free text with its keys masked, each key a token; `paint` draws the text between them. */
export function maskNodes(t: string, paint: (s: string) => ReactNode, words: CodeWords = codeWords): ReactNode[] {
  const out: ReactNode[] = [];
  let at = 0;
  let m: RegExpExecArray | null;
  SECRET_IN_TEXT.lastIndex = 0;
  let k = 0;
  while ((m = SECRET_IN_TEXT.exec(t))) {
    const before = t.slice(at, m.index);
    if (before) out.push(<Frag key={k++}>{paint(before)}</Frag>);
    const what = m[1] === "whsec_" ? words.webhookSecret : words.secretKey;
    out.push(<CodeBlockSecret key={k++} what={what} prefix={m[1]!} last={m[2]!.slice(-4)} words={words} />);
    at = m.index + m[0].length;
  }
  const rest = t.slice(at);
  if (rest) out.push(<Frag key={k++}>{paint(rest)}</Frag>);
  return out;
}
const Frag = ({ children }: { children?: ReactNode }) => <>{children}</>;

/* ------------------------------------------------------------------ JSON lines */

/** One numbered line: its markup and its text (what Copy writes, masked). */
export type CodeLine = { node: ReactNode; text: string; secret?: boolean };
/** A JSON value. */
export type CodeJsonValue = string | number | boolean | null | CodeJsonValue[] | { [key: string]: CodeJsonValue };

/** JSON to numbered lines: syntax in the --syn inks, a secret as its masked token. */
export function jsonLines(value: CodeJsonValue, secrets: Record<string, string> = {}, words: CodeWords = codeWords): CodeLine[] {
  const out: CodeLine[] = [];
  const sp = (n: number) => "  ".repeat(n);
  const scalar = (v: CodeJsonValue, key: string | null): { node: ReactNode; text: string; secret?: boolean } => {
    if (typeof v === "string" && ((key !== null && key in secrets) || codeBlockLooksSecret.test(v))) {
      const m = maskValue(v);
      const what = (key !== null && secrets[key]) || words.secret;
      // the token stands for the whole value, so no quote marks around it (Copy still writes valid JSON)
      return { secret: true, text: JSON.stringify(m.text), node: <CodeBlockSecret what={what} prefix={m.prefix} last={m.last} words={words} /> };
    }
    if (typeof v === "string") return { text: JSON.stringify(v), node: <span className="pixilui-code-s">{JSON.stringify(v)}</span> };
    return { text: String(v), node: <span className="pixilui-code-v">{String(v)}</span> };
  };
  (function walk(v: CodeJsonValue, depth: number, key: string | null, last: boolean) {
    const pre = key !== null ? (
      <>
        <span className="pixilui-code-k">{JSON.stringify(key)}</span>
        <span className="pixilui-code-p">: </span>
      </>
    ) : null;
    const preT = key !== null ? `${JSON.stringify(key)}: ` : "";
    const comma = last ? "" : ",";
    if (v && typeof v === "object") {
      const arr = Array.isArray(v);
      const entries: [string | null, CodeJsonValue][] = arr ? v.map((x) => [null, x]) : Object.entries(v);
      const [o, c] = arr ? ["[", "]"] : ["{", "}"];
      if (!entries.length) {
        out.push({ node: <>{sp(depth)}{pre}<span className="pixilui-code-p">{`${o}${c}${comma}`}</span></>, text: sp(depth) + preT + o + c + comma });
        return;
      }
      out.push({ node: <>{sp(depth)}{pre}<span className="pixilui-code-p">{o}</span></>, text: sp(depth) + preT + o });
      entries.forEach(([k, x], i) => walk(x, depth + 1, arr ? null : k, i === entries.length - 1));
      out.push({ node: <>{sp(depth)}<span className="pixilui-code-p">{`${c}${comma}`}</span></>, text: sp(depth) + c + comma });
    } else {
      const s = scalar(v, key);
      out.push({ node: <>{sp(depth)}{pre}{s.node}<span className="pixilui-code-p">{comma}</span></>, text: sp(depth) + preT + s.text + comma, secret: s.secret });
    }
  })(value, 0, null, true);
  return out;
}

/* ------------------------------------------------------------------ syntax: a small TypeScript reading */

const KW = new Set("import from export const let var function return if else type interface new await async as of in for while true false null undefined".split(" "));
// a call is a name before "(", a key is a name before ":" (each its own group: an optional lookahead never counts in JS)
const TOK = /(\/\/.*$)|('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")|(\b\d[\d_.]*\b)|([A-Za-z_$][\w$]*(?=\s*\())|([A-Za-z_$][\w$]*(?=\s*:(?!:)))|([A-Za-z_$][\w$]*)|([{}()[\],.:;=<>+\-*/!?|&]+)|(\s+)|(.)/g;
/** A line read into tokens, each with its syntax class (or none). */
export function codeTokens(t: string): [string, string][] {
  const out: [string, string][] = [];
  let m: RegExpExecArray | null;
  TOK.lastIndex = 0;
  while ((m = TOK.exec(t)) && m[0]) {
    const name = m[4] || m[5] || m[6];
    const cls = m[1] ? "pixilui-code-c" : m[2] ? "pixilui-code-s" : m[3] ? "pixilui-code-v" : name ? (KW.has(name) ? "pixilui-code-kw" : m[4] ? "pixilui-code-f" : m[5] ? "pixilui-code-k" : "") : m[7] ? "pixilui-code-p" : "";
    out.push([m[0], cls]);
  }
  return out;
}
/** A line's markup, with the changed words (`mark`, a [start, end) range) wrapped once across however many tokens they cross. */
export function paintCode(t: string, mark?: [number, number] | null): ReactNode {
  const out: ReactNode[] = [];
  let at = 0;
  let k = 0;
  let marked: ReactNode[] | null = null;
  const seg = (s: string, cls: string) => (cls ? <span key={k++} className={cls}>{s}</span> : s);
  // plain text next to plain text is one run, as the lock writes it
  const push = (n: ReactNode) => {
    const list = marked ?? out;
    if (typeof n === "string" && typeof list[list.length - 1] === "string") list[list.length - 1] += n;
    else list.push(n);
  };
  for (const [s, cls] of codeTokens(t)) {
    let i = 0;
    while (i < s.length) {
      const pos = at + i;
      const inside = !!mark && pos >= mark[0] && pos < mark[1];
      if (inside && !marked) marked = [];
      if (!inside && marked) {
        out.push(<mark key={k++} className="pixilui-diff-w">{marked}</mark>);
        marked = null;
      }
      const stop = !mark ? s.length : inside ? Math.min(s.length, mark[1] - at) : pos < mark[0] ? Math.min(s.length, mark[0] - at) : s.length;
      push(seg(s.slice(i, stop), cls));
      i = stop;
    }
    at += s.length;
  }
  if (marked) out.push(<mark key={k++} className="pixilui-diff-w">{marked}</mark>);
  return out;
}

/* ------------------------------------------------------------------ the quiet blur swap and the number roll */

/**
 * One quiet blur swap for small text, as the lock's swap(): the old face goes out on a 2px blur (--pixilui-dur-exit,
 * --pixilui-ease-in), then the new one comes in 60ms later rising 2px as the blur melts (--pixilui-dur-move, --pixilui-ease-swap).
 * `face` names what it shows: a change of face swaps; the same face updates in place. Compared with where it is going, so a
 * quick second change is never lost. Reduced motion, or not on the page yet: at once.
 */
export const CodeBlockSwap = forwardRef<HTMLSpanElement, Omit<ComponentPropsWithoutRef<"span">, "children"> & { face: string; again?: number; children?: ReactNode }>(function CodeBlockSwap(
  { face, again = 0, children, ...rest },
  ref,
) {
  const el = useRef<HTMLSpanElement | null>(null);
  // `again` changing swaps the same face out and back in (the lock's header swaps once on its first decision, see Diff)
  const key = `${face}\u0000${again}`;
  const [shown, setShown] = useState<{ key: string; node: ReactNode }>({ key, node: children });
  const to = useRef(key);
  const latest = useRef(children);
  const anims = useRef<Animation[]>([]);
  useLayoutEffect(() => {
    latest.current = children;
  });
  // the same face: its content updates in place (a count, a button's state)
  if (shown.key === key && shown.node !== children) setShown({ key, node: children });
  useLayoutEffect(() => {
    const e = el.current;
    if (to.current === key) return;
    to.current = key;
    const land = () => flushSync(() => setShown({ key: to.current, node: latest.current }));
    if (!e || prefersReducedMotion() || !e.isConnected || !can(e)) return land();
    anims.current.forEach((a) => a.cancel());
    const out = e.animate([{ opacity: getComputedStyle(e).opacity, filter: "blur(0)" }, { opacity: 0, filter: `blur(${codeToken(e, "--pixilui-blur-in")})` }], {
      duration: codeMs(e, "--pixilui-dur-exit"),
      easing: codeCurve(e, "--pixilui-ease-in"),
      fill: "forwards",
    });
    anims.current = [out];
    out.finished.then(
      () => {
        land();
        out.cancel();
        anims.current = [
          e.animate([{ opacity: 0, transform: "translateY(2px)", filter: `blur(${codeToken(e, "--pixilui-blur-in")})` }, { opacity: 1, transform: "none", filter: "blur(0)" }], {
            duration: codeMs(e, "--pixilui-dur-move"),
            delay: 60, // check-registry-ignore: the lock's swap() writes this beat as a literal (code.js), not a token
            easing: codeCurve(e, "--pixilui-ease-swap"),
            fill: "backwards",
          }),
        ];
      },
      () => {},
    );
  }, [key]);
  return (
    <span
      ref={(n) => {
        el.current = n;
        if (typeof ref === "function") ref(n);
        else if (ref) ref.current = n;
      }}
      {...rest}
    >
      {shown.node}
    </span>
  );
});

/**
 * Rolling digits (the system's roll): the text changes in place, each digit rolls the way the value moved. A value that
 * never changed is plain text (`base` is what it was built with); changed at once (`roll` false: a build, a frozen state)
 * it is plain text with its value noted; once it has rolled, each character is its own box, as the system leaves it.
 * `replay` changing rolls it up again from nothing (an edit landing). Reduced motion: at once.
 */
export function useCodeRoll(value: string, { base = value, roll = true, replay = 0 }: { base?: string; roll?: boolean; replay?: number } = {}) {
  const el = useRef<HTMLElement | null>(null);
  const [face, setFace] = useState<{ v: string; set: boolean; chars: boolean; up: boolean; gen: number; replay: number }>(() => ({ v: value, set: value !== base, chars: false, up: true, gen: 0, replay }));
  if (face.v !== value || face.replay !== replay) {
    const reduce = prefersReducedMotion();
    const up = face.replay !== replay || parseFloat(value.replace(/[^\d.-]/g, "")) >= parseFloat(face.v.replace(/[^\d.-]/g, ""));
    // a replay rolls up from its first character and a 0 ("+0" to "+5"); from where it is already, it changes at once
    const from = face.replay !== replay ? `${value[0] ?? ""}0` : face.v;
    setFace({ v: value, set: true, chars: roll && !reduce && from !== value, up, gen: face.gen + 1, replay });
  }
  useLayoutEffect(() => {
    const e = el.current;
    if (!e || !face.chars || !face.gen) return;
    e.querySelectorAll<HTMLElement>(":scope > span").forEach((s) => {
      if (!/\d/.test(s.textContent ?? "") || !can(s)) return;
      s.animate([{ transform: `translateY(${face.up ? 60 : -60}%)`, opacity: 0, filter: "blur(2px)" }, { transform: "none", opacity: 1, filter: "none" }], {
        duration: codeMs(e, "--pixilui-dur-base"),
        easing: codeToken(e, "--pixilui-ease-out") || "ease",
        fill: "both",
      });
    });
  }, [face]);
  const content: ReactNode = face.chars ? [...face.v].map((ch, i) => <span key={`${face.gen}-${i}`} style={{ display: "inline-block" }}>{ch}</span>) : face.v;
  return { ref: el, content, dataV: face.set ? face.v : undefined };
}

/* ------------------------------------------------------------------ sideways */

/** A body that scrolls sideways takes Tab focus and says so (role region with its label); `fallback` is its tabIndex otherwise. Returns a callback ref and the body's props. */
export function useSideways(label: string, fallback?: number) {
  const [node, setNode] = useState<HTMLElement | null>(null);
  const [wide, setWide] = useState(false);
  useEffect(() => {
    if (!node || typeof ResizeObserver !== "function") return;
    const ro = new ResizeObserver(() => setWide(node.scrollWidth > node.clientWidth + 1));
    ro.observe(node);
    return () => ro.disconnect();
  }, [node]);
  const props = wide ? { tabIndex: 0, role: "region" as const, "aria-label": label } : fallback !== undefined ? { tabIndex: fallback } : {};
  return [setNode, props] as const;
}

/* ------------------------------------------------------------------ Copy */

/** Copy: writes the (masked) text, turns its icon into the check, says what was copied, lights the masked keys once. */
export function useCodeCopy(text: () => string, secret: boolean, words: CodeWords) {
  const [copied, setCopied] = useState(false);
  const [open, setOpen] = useState<boolean | undefined>(undefined);
  const [said, setSaid] = useState("");
  const done = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  useEffect(() => () => clearTimeout(done.current), []);
  const copy = useCallback(
    async (root: HTMLElement | null) => {
      try {
        await navigator.clipboard.writeText(text());
      } catch {
        /* no clipboard (a frozen page, an old browser): the feedback still shows */
      }
      flushSync(() => {
        setCopied(true);
        setSaid(secret ? words.copiedMasked : words.copied);
        setOpen(true);
      });
      // the key lights once: what you copied kept its mask
      root?.querySelectorAll<HTMLElement>(".pixilui-code-secret").forEach((k) => {
        k.removeAttribute("data-flash");
        void k.offsetWidth;
        k.setAttribute("data-flash", "");
      });
      clearTimeout(done.current);
      done.current = setTimeout(() => {
        setCopied(false);
        setSaid("");
        setOpen(false);
      }, 1600);
    },
    [text, secret, words],
  );
  return { copied, tip: copied ? said : words.copy, open, said, copy };
}

/** Copy, the locked sm Secondary 2 icon button with the copy-check icon and its tooltip. */
export function CodeBlockCopy({ label, tip, open, copied, onCopy, icon }: { label: string; tip: string; open?: boolean; copied: boolean; onCopy: () => void; icon?: ReactNode }) {
  return (
    <Tooltip label={tip} open={open}>
      <Button variant="secondary-2" size="sm" icon={icon ?? <IconCopyCheck />} aria-label={label} className="pixilui-code-copy" data-state={copied ? "copied" : undefined} onClick={onCopy} />
    </Tooltip>
  );
}

/* ------------------------------------------------------------------ the well */

/** Sets a callback or object ref. */
function assignRef<T>(ref: Ref<T> | undefined, value: T | null) {
  if (typeof ref === "function") ref(value);
  else if (ref) (ref as { current: T | null }).current = value;
}

type WellProps = {
  lines: { node: ReactNode; text: string; style?: CSSProperties; className?: string }[];
  head: ReactNode;
  title: string;
  copyLabel: string;
  text: string;
  secret: boolean;
  fold?: number;
  numbers: boolean;
  lang: string;
  words: CodeWords;
  copyIcon?: ReactNode;
  moreIcon?: ReactNode;
  className?: string;
  extraHead?: ReactNode;
  wellRef?: Ref<HTMLElement>;
  rest?: Omit<ComponentPropsWithoutRef<"figure">, "children">;
  lineClass?: string;
};

/** The well: the head (a label or a path, then Copy), the numbered mono lines, the fold and its Show all, Copy's status line. */
function Well({ lines, head, title, copyLabel, text, secret, fold, numbers, lang, words, copyIcon, moreIcon, className, wellRef, rest, lineClass }: WellProps) {
  const fig = useRef<HTMLElement | null>(null);
  const folds = !!fold && lines.length > fold;
  const [folded, setFolded] = useState(folds);
  const [bodyRef, bodyProps] = useSideways(words.scrolls(title));
  const textRef = useRef(text);
  useLayoutEffect(() => {
    textRef.current = text;
  });
  const { copied, tip, open, said, copy } = useCodeCopy(() => textRef.current, secret, words);
  const { style, ...other } = rest ?? {};
  return (
    <figure
      ref={(n) => {
        assignRef(fig, n);
        assignRef(wellRef, n);
      }}
      className={cn("pixilui-code", className)}
      data-lang={lang}
      data-secret={secret ? "" : undefined}
      data-numbers={numbers ? undefined : "off"}
      data-folded={folds && folded ? "" : undefined}
      style={folds ? ({ "--pixilui-code-fold": String(fold), ...style } as CSSProperties) : style}
      {...other}
    >
      <figcaption className="pixilui-code-head">
        {head}
        <CodeBlockCopy label={copyLabel} tip={tip} open={open} copied={copied} icon={copyIcon} onCopy={() => void copy(fig.current)} />
      </figcaption>
      <div ref={bodyRef} className="pixilui-code-body" {...bodyProps}>
        <pre className="pixilui-code-pre">
          <code>
            {lines.map((l, i) => (
              <span key={i} className={cn("pixilui-code-line", lineClass, l.className)} style={l.style}>
                {numbers ? (
                  <span className="pixilui-code-n" aria-hidden="true">
                    {i + 1}
                  </span>
                ) : null}
                <span className="pixilui-code-t">{l.node}</span>
              </span>
            ))}
          </code>
        </pre>
      </div>
      {folds ? (
        <div className="pixilui-code-more">
          <Button
            variant="secondary-2"
            size="sm"
            aria-expanded={!folded}
            data-code-more=""
            data-lines={lines.length}
            onClick={() => {
              const f = fig.current;
              const change = () => flushSync(() => setFolded((x) => !x));
              if (f) resize(f, change);
              else change();
            }}
          >
            <>
              <span>{folded ? words.showAll(lines.length) : words.showFewer}</span>
              {moreIcon ?? <IconDisclosure />}
            </>
          </Button>
        </div>
      ) : null}
      {/* Copy's confirmation, read out (the tip is only a description) */}
      <span className="sr-only" role="status">
        {said}
      </span>
    </figure>
  );
}

/* ------------------------------------------------------------------ CodeBlockJson */

export type CodeJsonProps = Omit<ComponentPropsWithoutRef<"figure">, "children" | "title"> & {
  /** The header's label ("Arguments", "Result"). */
  title?: string;
  /** Markup after the label (the result's status tag and time). */
  meta?: ReactNode;
  /** The value to show. */
  value: CodeJsonValue;
  /** Keys whose values are secrets, each with what it is ({ api_key: "Stripe secret key" }); values that look like keys are caught too. */
  secrets?: Record<string, string>;
  /** Show this many lines, then a fade and "Show all N lines". */
  fold?: number;
  /** Line numbers (default on). */
  numbers?: boolean;
  /** Every word it says. */
  words?: Partial<CodeWords>;
  /** Copy's icon (the locked copy-check). */
  copyIcon?: ReactNode;
  /** Show all's chevron (the locked disclosure). */
  moreIcon?: ReactNode;
};

/** A well of JSON, highlighted: a tool call's arguments or its result. A secret renders masked, and Copy copies the mask. */
export const CodeBlockJson = forwardRef<HTMLElement, CodeJsonProps>(function CodeBlockJson({ title = "Code", meta, value, secrets = {}, fold, numbers = true, words: w, copyIcon, moreIcon, className, ...rest }, ref) {
  const words = { ...codeWords, ...w };
  const lines = jsonLines(value, secrets, words);
  return (
    <Well
      wellRef={ref}
      lines={lines}
      title={title}
      lang="json"
      head={
        <>
          <span className="pixilui-code-title">{title}</span>
          {meta ? <span className="pixilui-code-meta">{meta}</span> : null}
        </>
      }
      copyLabel={words.copyLabel(title.toLowerCase())}
      text={lines.map((l) => l.text).join("\n")}
      secret={lines.some((l) => l.secret)}
      fold={fold}
      numbers={numbers}
      words={words}
      copyIcon={copyIcon}
      moreIcon={moreIcon}
      className={className}
      rest={rest}
    />
  );
});

/* ------------------------------------------------------------------ CodeBlock */

export type CodeBlockHandle = {
  /** The replay: the head says Writing while the lines write in from their left edge, a line after another. */
  write: () => void;
  /** The well. */
  element: HTMLElement | null;
};

export type CodeBlockProps = Omit<ComponentPropsWithoutRef<"figure">, "children"> & {
  /** The code. A key in it (sk_live_…, whsec_…, ghp_…) is masked as it renders, and Copy copies the mask. */
  code: string;
  /** The file ("app/api/refunds/route.ts"): the head shows it, folders grey, the file brighter. Without it, the language. */
  path?: string;
  /** The language, shown when there is no path (default TypeScript). */
  lang?: string;
  /** Show this many lines, then a fade and "Show all N lines". */
  fold?: number;
  /** Line numbers (default off). */
  numbers?: boolean;
  /** Every word it says. */
  words?: Partial<CodeWords>;
  /** Copy's icon (the locked copy-check). */
  copyIcon?: ReactNode;
  /** Show all's chevron (the locked disclosure). */
  moreIcon?: ReactNode;
};

/** Code the agent shows you in its answer: its file or language, Copy, and the write-in replay. */
export const CodeBlock = forwardRef<CodeBlockHandle, CodeBlockProps>(function CodeBlock({ code, path = "", lang = "TypeScript", fold, numbers = false, words: w, copyIcon, moreIcon, className, ...rest }, ref) {
  const words = { ...codeWords, ...w };
  const fig = useRef<HTMLElement | null>(null);
  const [say, setSay] = useState(false);
  const timer = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  useEffect(() => () => clearTimeout(timer.current), []);
  const src = code.replace(/\n$/, "").split("\n");
  const cut = path.lastIndexOf("/") + 1;
  useImperativeHandle(
    ref,
    () => ({
      get element() {
        return fig.current;
      },
      write() {
        const f = fig.current;
        if (!f) return;
        // replay: the header says Writing (the locked shimmer) while the lines write in, a stagger apart
        f.dataset.writing = "";
        flushSync(() => setSay(true));
        const gap = codeMs(f, "--pixilui-block-line-gap");
        f.querySelectorAll<HTMLElement>(".pixilui-block-line").forEach((l) => l.style.setProperty("--pixilui-block-delay", `${Number(l.style.getPropertyValue("--pixilui-i")) * gap}ms`));
        void f.offsetHeight;
        f.removeAttribute("data-writing");
        f.dataset.written = "";
        clearTimeout(timer.current);
        timer.current = setTimeout(() => {
          setSay(false);
          f.removeAttribute("data-written");
        }, gap * src.length + codeMs(f, "--pixilui-block-write"));
      },
    }),
    [src.length],
  );
  return (
    <Well
      wellRef={fig}
      lines={src.map((l, i) => {
        const node = maskNodes(l, (s) => paintCode(s), words);
        return { node: node.length ? node : " ", text: l, style: { "--pixilui-i": i } as CSSProperties };
      })}
      lineClass="pixilui-block-line"
      title={path || lang}
      lang={lang}
      head={
        <>
          {path ? (
            <span className="pixilui-block-path" title={path}>
              <span className="pixilui-block-dir">{path.slice(0, cut)}</span>
              <span className="pixilui-block-name">{path.slice(cut)}</span>
            </span>
          ) : (
            <span className="pixilui-code-title">{lang}</span>
          )}
          <span className="pixilui-block-say">{say ? <span className="pixilui-text-shimmer">{words.writing}</span> : null}</span>
        </>
      }
      copyLabel={words.copyLabel("code")}
      text={maskText(src.join("\n"))}
      secret={hasSecret(code)}
      fold={fold}
      numbers={numbers}
      words={words}
      copyIcon={copyIcon}
      moreIcon={moreIcon}
      className={cn("pixilui-block-snippet", className)}
      rest={rest}
    />
  );
});
```

## Usage

When to use:

- Code the agent wrote or quotes in a chat answer: a route, a config, a query.
- A tool's arguments or result as JSON (CodeJson), with keys masked.
- A long file: fold it at a few lines under Show all N lines.

When not to use:

- A change to a file the person should keep or undo: use Diff.
- A command and what it printed: use Command.
- A plain code sample on a docs page: a pre is enough.

```tsx
import { useRef } from "react";
import { Button } from "@/components/pixilui/button";
import { CodeBlock, CodeBlockJson, type CodeBlockHandle } from "@/components/pixilui/code-block";
import { codeBlockSample, codeJsonSample } from "@/components/pixilui/code-block.examples";

// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
  block: ["code", "JSON"],
  numbers: ["off", "on"],
  fold: ["no fold", "fold at 6"],
} as const;

/** The agent's answer around the block: chat message text, 15/24 (the answer tokens). */
const ANSWER = { fontSize: "var(--pixilui-text-answer)", lineHeight: "var(--pixilui-text-answer-leading)", letterSpacing: "var(--pixilui-text-answer-tracking)" };

/** Code the agent wrote in its answer, with Copy and the write-in replay; or a well of JSON with a masked key. */
export default function CodeBlockDemo({ block = "code", numbers = "off", fold = "no fold" }: KnobValues<typeof knobs>) {
  const ref = useRef<CodeBlockHandle>(null);
  const f = fold === "no fold" ? undefined : 6;
  return (
    <div className="grid w-full max-w-xl gap-3 rounded-panel bg-surface p-5 elevation-raised">
      <p className="m-0 text-foreground" style={ANSWER}>
        {block === "code" ? "Call it from the refunds route. Anything that needs a person goes to the review queue instead of failing." : "Stripe returned the refund, and the key in the call stayed masked."}
      </p>
      {block === "code" ? (
        <>
          <CodeBlock key={`${numbers}${fold}`} ref={ref} path="app/api/refunds/route.ts" code={codeBlockSample} numbers={numbers === "on"} fold={f} />
          <div>
            <Button variant="secondary-2" size="sm" onClick={() => ref.current?.write()}>
              Replay the writing
            </Button>
          </div>
        </>
      ) : (
        <CodeBlockJson key={`${numbers}${fold}`} title="Result" value={{ ...(codeJsonSample as object), api_key: "sk_live_51PqL8e2eZvKYlo2CrTq0b9mKzL9vT4242" }} secrets={{ api_key: "Stripe secret key" }} numbers={numbers === "on"} fold={f} />
      )}
    </div>
  );
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `lang` | `string` | `"TypeScript"` | The language, shown when there is no path (default TypeScript). |
| `code` (required) | `string` |  | The code. A key in it (sk_live_…, whsec_…, ghp_…) is masked as it renders, and Copy copies the mask. |
| `path` | `string` | `""` | The file ("app/api/refunds/route.ts"): the head shows it, folders grey, the file brighter. Without it, the language. |
| `fold` | `number` |  | Show this many lines, then a fade and "Show all N lines". |
| `numbers` | `boolean` | `false` | Line numbers (default off). |
| `words` | `Partial<CodeWords>` |  | Every word it says. |
| `copyIcon` | `ReactNode` |  | Copy's icon (the locked copy-check). |
| `moreIcon` | `ReactNode` |  | Show all's chevron (the locked disclosure). |

Also accepts every native `<figure>` attribute, and a ref to it.

## Keyboard

- `Tab`: Reaches Copy, each masked key (its tip says it copies masked), Show all, and the body when it scrolls sideways.
- `Enter` + `Space`: Copies, or folds and opens the block.

## Accessibility

- A masked key is role img named with what it is and its last four (Stripe secret key, masked, ends in 4242).
- Copy says what it copied in a status line (Copied, key masked); its tip is only a description.
- Line numbers are aria-hidden; a body wider than the well becomes a named region that takes focus, so a keyboard can scroll it.

## Motion

- Show all: the well's height glides open and shut (the system's resize, 280ms on the out curve).
- Copy: the icon turns into its check and the masked key lights once, its dots rippling (380ms).
- The replay: each line writes in from its left edge a line after another (45ms apart, 380ms each) under the Writing shimmer.
- Reduced motion: it folds, copies and writes at once.

## Responsive

- Fills its container. Long lines wrap under their own column with no sideways scroll; at 390 nothing spills.

## Performance

- Plain spans and CSS; one ResizeObserver per well notes when it scrolls sideways.

## Notes for AI

- <CodeBlock path="app/api/refunds/route.ts" code={code} /> in an answer; lang names it when there is no path; numbers and fold are optional.
- <CodeJson title="Arguments" value={args} secrets={{ api_key: "Stripe secret key" }} />: keys named in secrets are masked, and values that look like keys (sk_live_, ghp_, xoxb-, Bearer) always are.
- A ref's write() replays the agent writing it. Every word is in words (Copy, Copied, Show all, the key's tip).
- The well and its engine (masking, the syntax reading, the blur swap, the number roll) are shared by Tool call, Diff, File edits and Command.
- Per-style rule: quiet is compact (a 40 head, 10 and 12 pads) with its hairline ring.

## Related

- [Tool call](https://pixilui.com/components/tool-call/markdown): One tool call in the agent's answer: its row names the call (the tool's real logo, the function as a code tag, the time) and folds its Arguments and Result. A secret in the arguments renders masked, and Copy copies the mask.
- [Diff](https://pixilui.com/components/diff/markdown): An agent's edit to one file, waiting in its answer: the row reads Edited policy.ts +5 −2 with Undo and Keep, over the path and the line diff. Keep and Undo turn the diff into the file in place, and each change can be kept or undone on its own.
- [Command](https://pixilui.com/components/command/markdown): A command the agent ran: the row reads Ran pnpm test · 4.2 s and folds a well with the command, Copy and what it printed. Running, its output prints in, the clock ticks and Stop ends it; a failure reads red with its exit code.
- [File edits](https://pixilui.com/components/file-edits/markdown): An agent's edit across files as one row: Edited 3 files +22 −5 with Undo all and Keep all, over each file's diff hung from a hairline. Decide all at once or file by file and change by change; the row keeps count.
