# Code sample

A code figure with a label, a copy button and annotations. A quiet header row shows the language or the file name, and the copy button confirms on its own label. The code sits in a recessed area that scrolls sideways and does not wrap. The author can highlight a line or a word, dim all but the part under discussion, and mark the added and removed lines of a diff. These comment notations never go to the clipboard. Long files get a line limit that scrolls and does not clip, with an expand button when the limit applies. Shiki highlights the code with the text colours of the system, so each colour is a value that the generator already checked against the surface below it.

## Files

### code-sample.tsx

```tsx
/**
 * The code-sample BLOCK: a labelled, copyable, annotatable code figure. The first entry in
 * the blocks registry (`blocks/index.tsx`), and the one the docs themselves consume — every
 * MDX fence and every example's source renders through this file, so the block ships with a
 * real consumer rather than a demo.
 *
 * WHAT A BLOCK IS HERE (THESIS §6): copied source, not published code — and copy-paste is
 * only safe when the copied file makes no design decisions of its own. shadcn's copy-paste is centerless *by construction* because the decisions travel
 * in the copy; here every colour, distance and step resolves through the package, so the
 * center stays in the dependency and the copy carries only arrangement and behaviour.
 * Behaviour is allowed (the copy button's state, the expand control); invented values are not.
 *
 * THE FIVE JOBS: show (the element), name (the header's label or title), take (the copy
 * button), point (the author's annotations — line and word highlight, focus, diff, error
 * marks), and bound (`maxLines`, scroll-not-clip, expand as convenience).
 * Everything else the ecosystem ships is another component wearing this one's name (code
 * groups are Tabs; preview is the Example frame) or decoration (window chrome, icons).
 *
 * THE CHROME'S SHAPE: the NAME sits outside, a sibling row aligned to the code with the
 * pane's own inset token (`--surface-p-N`); the ACTIONS float over the pane — copy top-right,
 * expand bottom-centre — as
 * GLASS (`backdrop`, the theme's material: the docs Theme runs `material="3"`), at
 * Button's own medium default, because a floating control over content is exactly what the
 * material defends. No gradient — a scrollable well with a scrollbar already says "more".
 * SIZE PRICES EVERYTHING — pane, code step, label, copy and expand buttons all ride one
 * index — the ownership rule (§25, §30).
 *
 * WHAT THE COPY BUTTON HANDS OVER IS THE STRIPPED SOURCE — `plainText(lines)`, the code with
 * every `[!code …]` annotation removed, derived from the same tokens the paint renders, so
 * the clipboard and the pixels cannot disagree. Diff markers are real spans (a pseudo cannot
 * coexist with the line-number counter) but `aria-hidden` and `user-select: none`, so neither
 * assistive technology nor a drag-selection ever meets them.
 *
 * Async, and therefore server-only: tokenizing is build-time work, so a code fence costs the
 * reader nothing but the markup it produces. The client components are the copy button and,
 * only when the bound binds, the expand control.
 */
/* THE STYLESHEET IS IMPORTED BY THE FILE THAT EMITS ITS CLASSES. Import it anywhere else and
   deleting that file stops pulling `code.css` in — `.kd-line` stops being a block, every line
   of every fence runs together onto one line, and a type checker sees nothing wrong. The
   classes below are this file's, so the import is this file's; a law in `blocks.test.tsx`
   pairs the two. */
import "./code.css";

import * as React from "react";
import {
  Box,
  Code,
  CodeBlock,
  type Size,
  Surface,
  Toolbar,
  ToolbarGroup,
  ToolbarTitle,
} from "@kushagradhawan/kookie-ui-react";

import { CopyButton } from "./copy-button";
import { Expandable } from "./expandable";
import {
  isLang,
  leadingColumns,
  plainText,
  tokenize,
  type CodeLine,
  type Lang,
} from "./highlight";

/** What the header row calls each language. The grammar's id is a tool's name for it
    (`tsx`, `bash`); this is the reader's. */
const LANG_LABEL: Record<Lang, string> = {
  tsx: "TSX",
  ts: "TypeScript",
  jsx: "JSX",
  js: "JavaScript",
  css: "CSS",
  json: "JSON",
  bash: "Terminal",
  html: "HTML",
  mdx: "MDX",
};

/**
 * How many lines a well shows before it bounds itself.
 *
 * It is a DEFAULT rather than a per-call-site prop because the fault it fixes is the one
 * nobody remembers to fix: a fence or an example runs long, the page becomes a mile of
 * scrolling code, and the author who wrote it never sees the page it landed on. A bound is
 * not a property of any one route, so the number lives here and no call site states it.
 *
 * NOT SILENT: bounded means SCROLLABLE, and the expand control names what it is holding back
 * ("Show all N lines"), so nothing is hidden without saying how much.
 *
 * An unbounded well is `maxLines={Infinity}` — deliberately awkward, because wanting one is
 * rare and the reason should be visible at the call site.
 */
export const CODE_MAX_LINES = 24;

/**
 * How much a bound has to be holding back before it is worth a control.
 *
 * Binding at ONE line over puts a button on the page, a scroll region under it and a press
 * between the reader and one line of code. The chrome cost is fixed and the saving is not, so
 * below some overflow the bound spends more than it buys — and what it spends is not pixels,
 * it is a press.
 *
 * A SHARE OF THE BOUND, not a second stated number, and the share is what makes it right at
 * both ends. An absolute slack would override an explicit small bound: a call site asking for
 * `maxLines={2}` has said something deliberate, and hiding three lines there DOUBLES what is
 * on screen — worth pressing for — while hiding three against 24 is noise. One third: six at
 * the default, so 25 to 32 lines show whole and 33 bounds to 24.
 *
 * `Infinity` stays unbounded by arithmetic rather than by a branch: no count exceeds it.
 */
export const CODE_BOUND_SLACK = (maxLines: number) => Math.ceil(maxLines / 3);

export type CodeSampleProps = {
  code: string;
  lang: string;
  /** One index for the whole figure: the pane, the code step, the label and both buttons. */
  size?: Size;
  /** A file path, when the sample IS a file. Replaces the language label, because where the
      code lives is more use than what it is written in once you can see it. */
  title?: string;
  /** Suppress the header row. For the rare fence that is one word long, where a label and a
      copy button are more chrome than content. */
  bare?: boolean;
  /** Fence meta for Shiki's own directives — `{1,3-5}` highlights lines, `/word/` highlights
      a word. The chrome facts (`title`, `lineNumbers`, `maxLines`, `bare`) are real props;
      the MDX fence adapter parses them out of the meta string with `parseMeta`. */
  meta?: string;
  /** Number the lines. CSS counters — never markup, so never in a selection or the copy. */
  lineNumbers?: boolean;
  /** Bound the well to this many lines. Bounded means scrollable (see the element); an
      expand button appears only when the code actually exceeds the bound. Defaults to
      `CODE_MAX_LINES`; `Infinity` opts out. */
  maxLines?: number;
  /** The sample is already inside a pane, so the well draws none of its own — see the element.
      A well inside a ground is the same ground twice. */
  hosted?: boolean;
};

/** One rendered line: a block-level span carrying the author's flags as classes, so the
    theme (`code.css`) owns every colour and this file owns none. */
function Line({ line, marker }: { line: CodeLine; marker: boolean }) {
  const classes = ["kd-line"];
  if (line.highlight) classes.push("kd-line-highlight");
  if (line.add) classes.push("kd-line-add");
  if (line.remove) classes.push("kd-line-remove");
  if (line.focus) classes.push("kd-line-focus");
  if (line.level) classes.push(`kd-line-${line.level}`);

  /* THE LINE'S OWN INDENT, handed to the stylesheet as a column count.

     This is the one thing about a wrap that CSS cannot work out for itself: a continuation
     belongs under the line it continues, and where that line STARTS is inside its own text.
     A stylesheet can only hang from the pane's wall, which puts every continuation at column
     zero — reading as a shallower nesting level than the line it belongs to, which is worse
     than not hanging at all.

     Written only where there is one, so an unindented line grows no attribute and the
     stylesheet's own default answers for it. */
  const indent = leadingColumns(line);

  return (
    <span
      className={classes.join(" ")}
      {...(indent
        ? { style: { "--kd-indent": `${indent}ch` } as React.CSSProperties }
        : {})}
    >
      {marker ? (
        // A real span rather than a pseudo — the ::before slot belongs to the line-number
        // counter. Hidden from AT and from selection; the copy path never sees it because
        // copy text is derived from tokens, and this is not one.
        <span className="kd-line-marker" aria-hidden>
          {line.add ? "+" : line.remove ? "−" : ""}
        </span>
      ) : null}
      {line.tokens.map((token, index) => (
        <span
          key={index}
          className={token.word ? "kd-word" : undefined}
          style={{
            color: token.color,
            ...(token.italic ? { fontStyle: "italic" } : null),
          }}
        >
          {token.text}
        </span>
      ))}
    </span>
  );
}

/**
 * Tokenize, then render. The split exists because tokenizing is SERVER work and rendering is
 * not: a docs page with live controls rewrites one token's text when a control moves, and it
 * cannot call Shiki to do it — so the view below takes lines that are already
 * tokenized and is an ordinary synchronous component that a client component may render.
 *
 * One renderer, not two. The alternative is a second component painting `.kd-line` markup for
 * the live case, which is the shape this repo's own rule forbids: a mechanism with two
 * implementations owes a law that they agree, and the cheaper answer is to have one.
 */
export async function CodeSample({ code, lang, meta, ...view }: CodeSampleProps) {
  // An unlisted language would tokenize as plain text, which renders exactly like a fence
  // nobody got round to labelling — a silent downgrade. The docs law walks fences against
  // LANGS so this throw is a backstop rather than the enforcement, but a backstop that says
  // which fence and which language is worth the two lines.
  if (!isLang(lang)) {
    throw new Error(
      `Unknown code language "${lang}". Add it to LANGS in highlight.ts, or fix the fence.\n${code.slice(0, 80)}`,
    );
  }
  const { lines, focused, diff } = await tokenize(code, lang, meta);
  return <CodeSampleView lines={lines} focused={focused} diff={diff} lang={lang} {...view} />;
}

export type CodeSampleViewProps = Omit<CodeSampleProps, "code" | "meta"> & {
  /** Already tokenized. The one thing the view cannot do for itself. */
  lines: readonly CodeLine[];
  /** Some line said `[!code focus]`, so the rest stand down. */
  focused: boolean;
  /** Some line is an add or a remove, so every line gets a marker gutter. */
  diff: boolean;
};

export function CodeSampleView({
  lines,
  focused,
  diff,
  lang,
  size = "2",
  title,
  bare,
  lineNumbers,
  maxLines = CODE_MAX_LINES,
  hosted,
}: CodeSampleViewProps) {
  const copyText = plainText(lines);

  const paneClasses = [
    lineNumbers ? "kd-numbered" : null,
    focused ? "kd-focused" : null,
  ].filter(Boolean);
  const className = paneClasses.length ? paneClasses.join(" ") : undefined;

  const content = lines.map((line, index) => (
    <Line key={index} line={line} marker={diff} />
  ));

  // The bound binds only when the code exceeds it BY ENOUGH TO BE WORTH A PRESS — decided
  // here, from the line count the renderer already holds, never by measuring the DOM (v1's
  // defect class). Under the slack the well simply shows everything: the alternative, bounding
  // without the button, would hide lines while saying nothing, which is the one thing the
  // bound's own sentence forbids.
  const bounded = lines.length > maxLines + CODE_BOUND_SLACK(maxLines);

  // The copy button FLOATS top-right over the pane, as glass: a floating control over content
  // takes `backdrop`. It hangs from a positioned wrapper OUTSIDE the pane (inside, it breaks
  // the scroller's bleed — see the element), offset by the same inset token the pane pads with,
  // so it rests exactly one inset off the corner.
  /* The NAME FLOATS OVER THE PANE TOO, as the mirror of the copy button: same corner, same
     inset, opposite side, same material.

     A PATH IS COPIABLE AND A LANGUAGE IS NOT, so the two are not one component. `examples/
     dialog.tsx` is a thing you want in your clipboard — it is how you find the file — so it is
     the same `CopyButton` the code uses, with the path as both its label and its payload. A
     language name is a caption: there is nothing to copy and nothing to press, so it stays an
     inert `Chip`. They look different because they DO different things, which is this
     system's own rule rather than an inconsistency to tidy away.

     The chip keeps `backdrop` and the button takes it by construction, so both resolve the
     theme's material — and the atom family paints the same ring and rim the button does,
     which is what makes the two read as one kind of chrome. */
  /* A LANGUAGE IS LABELLED ONLY WHERE THE LABEL CHANGES WHAT YOU DO.

     Every fence on this site that is not a shell command is source you paste into a file, and
     `TSX` on a React library's docs is a label that is always true — it says nothing, on every
     fence. `Terminal` is the one that survives: it tells a reader the lines go
     in a shell rather than in their editor, which is the only thing here a reader could get
     wrong. CSS, JSON and HTML are unlabelled for the same reason as TSX — a stylesheet looks
     like a stylesheet, and knowing which file it belongs in is a question the prose around it
     answers, not a chip.

     Keyed on `bash` rather than on a list, so adding a language does not silently add a label:
     a new one has to argue its way in here. */
  const name = title ?? (lang === "bash" ? LANG_LABEL[lang] : null);

  /* ONE ROW, FLOATING OVER THE CODE.

     Moving it into FLOW is the wrong repair for the overlap it causes: a translucent control
     exists to be legible with content passing behind it, so a glass row with nothing behind it
     is decoration wearing a material's name. What is actually wrong is that the first line has
     nowhere to rest, and the answer to that is an inset, not flow — the platform pattern, where
     a scroll view holds a top contentInset and its content passes under a translucent toolbar.
     The band is a safe area, not an apology.

     IT SPANS THE PANE AND PADS ITSELF. The pane's inset is a READING measure — the distance
     a line of code needs from a wall — and chrome is not reading matter, so `inset-inline`
     reaches both walls and `p` puts a smaller number back.
     The buttons sit closer to the edge than the code does, which is what says they belong to
     the pane rather than to the text.

     A HOSTED SAMPLE IS THE OTHER CASE and does not disagree with it. Its own box IS the code
     column, so `inset-inline: 0` starts at the host's inset and any padding adds to it; the
     chrome REACHES the host's wall, which is the line below. Aligning both arrangements to the
     code is the wrong repair — one of them is already right.

     `z-index` is deliberately absent, and the row is rendered AFTER the scroller instead.
     Paint order alone does not settle it — `.kui-scroll-area` is positioned too, so the two
     settle on DOM order — and order is the whole fix: a z-index would be the number ladder
     §20 exists to avoid. */
  /* AND THE BAND IS ALWAYS RESERVED, name or no name.

     It was conditional: with a name at one wall and the copy button at the other the row covers
     the whole of line 1, so line 1 needed somewhere else to be — and with only the button, the
     argument ran, reserving a pane's width of clearance for a control in one corner puts a
     hand's width of nothing in the top-left.

     That argument is about the pixels the chrome COVERS, and a safe area is not about coverage.
     It is the band the pane says its chrome lives in, and a reader scanning a page of fences
     should not have to work out per fence whether the code begins under the buttons or beside
     them. The conditional bought a little of the top-left back and paid for it with two
     different code blocks on one page, which is the more expensive thing by a distance.

     So one rule: a fence that draws chrome reserves the band for it. `bare` still reserves
     nothing, because a bare fence draws no chrome at all — that is not the same fact wearing a
     condition, it is the absence of the row.

     `space-between` with ONE child pushes it to the START, so the empty wall has to be stated:
     the row means "name at one wall, action at the other", and with no name there is only the
     action, which takes the end.

A TOOLBAR, NOT A `Flex`. The row was stating the alignment, the split and the air itself —
     the three facts a Toolbar says once — and it earns the keyboard too whenever there is a
     name, because a path here is a `CopyButton` and not a label, so this row is usually TWO
     controls that were two separate tab stops.

     The justification conditional went with it, and that is the trade rather than a win: a
     toolbar is always `space-between`, so the empty wall is an empty child instead of a
     different value. It is honest in the same way the old spelling was — both say "there is
     nothing on that side" — and the toolbar cannot guess which side that is, because which
     controls sit where is what those controls mean. */
  const topbar = (
    <Toolbar size="3">
      <span />
      <CopyButton code={copyText} size="3" iconOnly />
    </Toolbar>
  );

  const named = name !== null;
  /* HOSTED AND BARE WHEN THE FIGURE DRAWS THE BOX. A well inside a ground is the same ground
     twice with a hairline between saying nothing, and the row over it would be a second copy
     button under the one the figure already floats. */
  const wellHosted = hosted || named;
  const wellBare = bare || named;

  const well = (
    <>
      {bounded ? (
        <Expandable
          size={size}
          maxLines={maxLines}
          lineCount={lines.length}
          topbar={wellBare ? undefined : topbar}
          {...(wellHosted ? { hosted: true } : {})}
          className={className}
        >
          {content}
        </Expandable>
      ) : (
        <CodeBlock
          size={size}
          {...(wellBare ? {} : { topbar })}
          {...(wellHosted ? { hosted: true } : {})}
          {...(className ? { className } : {})}
        >
          {content}
        </CodeBlock>
      )}
    </>
  );

  /* THE NAME IS A `Code`, IN FLOW, INSIDE THE PANE.

     A file's name is not a control and not a state: it is a literal, in the same face as the
     code under it, said once at the top of the thing it names. `Code` is the atom for exactly
     that — mono, sized off the line it sits in, no box of its own to disagree with the row's.

     WHAT IT IS NOT, and each was tried: a `Chip`, which is an atom priced for a sentence and
     lands at neither a chrome row's height nor its step; a `CopyButton`, which makes a name
     pressable; a TAB, which announces a list of places when there is one; and anything in the
     TOOLBAR, which is where controls live — the name is not one, and putting it there was what
     made it float over the first line it was naming.

     IT SITS IN THE PANE WITH THE CODE, which is what the figure already does one file over
     (`file-tabs.tsx`): the label names the code, so it belongs in the box the code is in. So a
     named sample takes the figure's arrangement — a Surface holding the label and a HOSTED
     well — rather than a caption stacked above a pane that draws itself. One pane either way.

     The copy button floats from the FIGURE, for the reason it does with several files: a hosted
     well has no pane of its own to float over, so the chrome hangs off the box that does. */
  if (name === null) return well;

  return (
    <Surface size={size} className="kd-figure">
      {/* THE NAME RIDES THE CHROME ROW. Under it, the label sat a chrome's height below the
          figure's top wall, with a band of nothing between the wall and the word naming the
          code. The row already reaches that wall and already holds a control at its end, so the
          label takes the start the row was leaving empty: one row, the name at one end and the
          copy at the other, and the code directly under the thing that names it. */}
      <Box className="kd-figure-chrome">
        <Toolbar size="3">
          {/* THE NAME IS THE BAND'S TITLE, IN THE CODE FACE. As plain code text in
              the row it missed the title's air beside the copy button and could push the button
              when it ran long. `ToolbarTitle` brings both; `render` keeps the atom, so the face
              and the step are unchanged. */}
          <ToolbarTitle render={<Code size={size} />}>{name}</ToolbarTitle>
          <ToolbarGroup backdrop>
            <CopyButton code={copyText} size="3" iconOnly />
          </ToolbarGroup>
        </Toolbar>
      </Box>
      {well}
    </Surface>
  );
}
```

### copy-button.tsx

```tsx
"use client";

/**
 * Copy-to-clipboard for a code sample. The one interactive part of a code block, and the
 * only reason any of this is a client component — everything else about a fence is decided
 * at build time.
 *
 * The confirmation is the BUTTON ITSELF saying so, not a toast: a toast is a floating layer
 * announcing something the thing you just pressed can say itself, and this system has no toast
 * anyway (§11 lists one; it has never shipped). It reverts on a timer, which is state.
 *
 * WHAT SAYS IT depends on what the button has. A labelled button changes its label; an
 * icon-only one changes its GLYPH to a check, and its accessible name with it, so a screen
 * reader hears the confirmation a sighted reader sees.
 *
 * A `ToolbarButton`, and that is a contract rather than a preference: every place this button
 * lives is a chrome row over a pane, and those rows are `Toolbar`s. A plain
 * Button cannot enrol in a toolbar's roving tab stop, so an unregistered control in one is a
 * stop the arrow keys never reach; and `ToolbarButton` throws outside a toolbar, which makes
 * the requirement loud rather than a comment nobody reads.
 */
import * as React from "react";
import { ToolbarButton, type Size } from "@kushagradhawan/kookie-ui-react";

import { CopyIcon } from "../app/icons";

export function CopyButton({
  code,
  label = "Copy",
  size = "1",
  icon,
  iconOnly,
}: {
  code: string;
  /** The accessible name, always. `iconOnly` decides whether it is also painted. */
  label?: string;
  /** The block's index, passed through — the chrome rides the same ladder as the pane. */
  size?: Size;
  /**
   * The resting glyph, for a button whose label already says what it copies. The code button
   * leaves it unset and gets a copy mark, because "Copy" is a verb with no object and the
   * glyph is what names the object. The NAME button passes a file mark instead: its label is
   * the object, so a copy mark there would say the same thing twice, and two identical marks
   * at either end of one pane would read as two of the same control.
   *
   * The CONFIRMATION is not overridable. Whatever the resting glyph, a press shows the check
   * — that is the button reporting what happened, and a component that let a call site
   * silence it would let a call site ship a copy that never says it copied.
   */
  icon?: React.ReactNode;
  /**
   * Paint the glyph alone. "Copy" beside a copy mark says one thing twice, and on a code
   * figure the button sits in a corner where a verb earns no room — every editor, terminal
   * and code host on the web has trained this glyph.
   *
   * The name does not go away, it stops being PAINTED: `aria-label` carries it, and Button's
   * own type refuses an icon-only control without one, so this cannot silently ship a button
   * a screen reader announces as "button".
   */
  iconOnly?: boolean;
}) {
  const [copied, setCopied] = React.useState(false);
  // Held in a ref so a second press restarts one timer rather than racing two, and so the
  // pending one is cleared on unmount — a page can navigate away mid-timeout.
  const timer = React.useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  React.useEffect(() => () => clearTimeout(timer.current), []);

  /* THE GLYPH IS THE RESTING ONE, ALWAYS. `done` is the button's own state, and it draws the
     confirmation: the button shows the system's tick in place of this glyph. The tick is the same
     drawing a checkbox's mark is. What stays here is the STATE and its timer, which is the
     rule §29 states one component over — a control that ran its own clock would decide, for
     every app, how long "just now" lasts.

     One glyph expression for both arms: an icon-only button puts it in `children` (there the
     glyph IS the content), a labelled one puts it in `leading` (there it adorns a label).
     The package's own comment states that split; this is the only place it has to be honoured. */
  const glyph = icon ?? <CopyIcon />;

  return (
    // Medium is the rung a `ToolbarButton` takes outside a group, so no emphasis is stated;
    // `backdrop` because this button FLOATS over the code — a floating control takes the
    // theme's material (glass).
    <ToolbarButton
      size={size}
      backdrop
      done={copied}
      {...(iconOnly
        ? { iconOnly: true as const, "aria-label": copied ? "Copied" : label }
        : { leading: glyph })}
      onClick={() => {
        // `?.` because clipboard access is absent on insecure origins — a docs site served
        // over plain HTTP on a LAN is the ordinary case, and there the press should do
        // nothing rather than throw an unhandled rejection into the console.
        void navigator.clipboard?.writeText(code).then(() => {
          setCopied(true);
          clearTimeout(timer.current);
          timer.current = setTimeout(() => setCopied(false), 2000);
        });
      }}
    >
      {iconOnly ? glyph : copied ? "Copied" : label}
    </ToolbarButton>
  );
}
```

### expandable.tsx

```tsx
"use client";

/**
 * The expand control for a bounded code block. Behaviour, so it lives in the block layer —
 * the element only knows how to BE bounded (`maxLines`, scrollable); whether to lift the
 * bound is a choice, and this is the one piece of state it takes.
 *
 * WHETHER THE BUTTON APPEARS IS DECIDED ON THE SERVER, not by measurement: the caller counts
 * its lines against the bound and only mounts this wrapper when the bound binds. Measuring
 * `scrollHeight` in an effect makes the toggle pop in after first paint; the whole class of
 * defect disappears when the deciding fact is the line count the renderer already holds.
 *
 * THE BUTTON FLOATS BOTTOM-CENTRE OVER THE PANE, AS GLASS: a floating control over content
 * takes `backdrop`, so the code passes behind it legibly, and no gradient — a scrollable well
 * with a scrollbar already says "more". It goes to the element as `footer` and hangs from the
 * WELL, beside the topbar, so both chrome rows float against the same box.
 *
 * `aria-expanded` and nothing more: the bounded well still scrolls, so no content is ever
 * hidden from anyone — the button changes how much is in view, not what exists. That is why
 * this is not a disclosure pattern and takes none of its wiring.
 */
import * as React from "react";
import { Button, CodeBlock, Flex, type Size } from "@kushagradhawan/kookie-ui-react";

export function Expandable({
  size,
  maxLines,
  lineCount,
  className,
  topbar,
  band,
  hosted,
  children,
}: {
  size: Size;
  maxLines: number;
  lineCount: number;
  className?: string | undefined;
  /** Passed straight through — the chrome belongs to the well, and this only bounds it. */
  topbar?: React.ReactNode;
  /** Passed straight through — whether that chrome spans is the block's answer, not the bound's. */
  band?: boolean;
  /** Passed straight through — whether the well draws its own pane is the host's answer. */
  hosted?: boolean;
  children: React.ReactNode;
}) {
  const [expanded, setExpanded] = React.useState(false);
  return (
    <CodeBlock
      size={size}
      {...(expanded ? {} : { maxLines })}
      {...(topbar ? { topbar } : {})}
      {...(band ? { band } : {})}
      {...(hosted ? { hosted } : {})}
      {...(className ? { className } : {})}
      footer={
        <Flex justify="center">
          <Button
            size={size}
            backdrop
            aria-expanded={expanded}
            onClick={() => setExpanded((value) => !value)}
          >
            {expanded ? "Show less" : `Show all ${lineCount} lines`}
          </Button>
        </Flex>
      }
    >
      {children}
    </CodeBlock>
  );
}
```

### highlight.ts

```ts
/**
 * Syntax highlighting, in the system's own colours, with the author's annotations.
 *
 * Shiki is the Base UI relationship one layer over: TextMate grammars are decades of
 * accumulated correctness nobody should rewrite, they are behaviour rather than appearance,
 * and they are invisible until someone paints them. So the grammars are theirs and every
 * colour is ours.
 *
 * The mechanism is Shiki's CSS-variables theme: instead of baking hexes, the tokenizer emits
 * `var(--code-token-*)` and the package's `CodeBlock` resolves those names against the ten
 * tones' SOLVED ink ladder (§15). That is the load-bearing part. A stock highlight theme is
 * a second colour system living inside the first — the one place on a site made of Kookie UI
 * where the pixels would not be Kookie UI's — and it would also be the only text on the page
 * held to no contrast target at all.
 *
 * THE PIPELINE IS `codeToHast`, NOT `codeToTokens`, and the reason is a fact about Shiki:
 * notation transformers only annotate the HAST — they never run in the token
 * pipeline. So the author's annotations (`// [!code highlight]`, `[!code ++]`, `[!code
 * focus]`, fence meta `{1,3}` and `/word/`) require walking the tree Shiki built. The walk
 * reduces it straight back to lines of tokens: nothing is trusted as markup, nothing is
 * `dangerouslySetInnerHTML`, and the renderer stays a map over plain data. The walk is LOUD
 * (the tokens.test.ts parser rule): a shape this file does not recognise throws rather than
 * degrading, because a silent one-char slice is how a negative assertion goes green.
 *
 * BOLD IS DROPPED, ITALIC IS KEPT, and the asymmetry is the type system's (§15: `bold` is
 * refused package-wide, and a value left reachable is one every call site can re-introduce).
 * Italic is not a weight and stays — it is the one signal separating a comment
 * from the code around it that does not spend a colour.
 */
import { createCssVariablesTheme, createHighlighter } from "shiki";
import {
  transformerMetaHighlight,
  transformerMetaWordHighlight,
  transformerNotationDiff,
  transformerNotationErrorLevel,
  transformerNotationFocus,
  transformerNotationHighlight,
  transformerNotationWordHighlight,
} from "@shikijs/transformers";

/**
 * The languages the docs actually contain. Listed rather than bundled: Shiki loads grammars
 * on demand, and a docs build that pulls every grammar it ships pays for languages this
 * system has no samples in. A law walks the code fences against this list, so an unlisted
 * language fails the build instead of silently rendering as plain text (which is Shiki's
 * fallback, and reads exactly like a fence nobody got round to labelling).
 */
export const LANGS = ["tsx", "ts", "jsx", "js", "css", "json", "bash", "html", "mdx"] as const;

export type Lang = (typeof LANGS)[number];

export const isLang = (value: string): value is Lang => (LANGS as readonly string[]).includes(value);

/** Named once. `createCssVariablesTheme` types its result's `name` as optional, so reading it
    back at the call site is a nullable string the highlighter will not accept — the constant
    is what makes registering the theme and selecting it the same fact. */
const THEME_NAME = "kookie";

const theme = createCssVariablesTheme({
  name: THEME_NAME,
  variablePrefix: "--code-",
  // No defaults. A `var()` with a fallback would paint SOMETHING when a name is unresolved,
  // which is how a token that code.css forgot ends up looking deliberate — the material
  // edge's `initial` argument (§10), one system over. Unresolved here means invalid at
  // computed-value time, so the token falls back to the block's own foreground and the miss
  // is visible rather than plausible.
  variableDefaults: {},
  fontStyle: true,
});

/**
 * One highlighter for the whole build. Shiki's setup cost is grammar parsing, which is
 * per-process rather than per-call, so a module-level promise is the difference between
 * paying it once and paying it per code fence on a site that is mostly code fences.
 */
let highlighterPromise: ReturnType<typeof createHighlighter> | undefined;

const getHighlighter = () => {
  highlighterPromise ??= createHighlighter({ themes: [theme], langs: [...LANGS] });
  return highlighterPromise;
};

/** One token as the renderer needs it: the text, the colour to paint it, whether it is the
    italic kind, and whether the author pointed at this word. Shiki's richer shapes stop here
    on purpose — everything past these four fields is a decision this file has already made. */
export type CodeToken = {
  text: string;
  color?: string | undefined;
  italic: boolean;
  /** `[!code word:x]` or fence meta `/x/` — the author highlighting a word. */
  word: boolean;
};

/** One line, with every way an author can point at it. The flags are booleans rather than a
    class string because the renderer owns the class names — this file owns the FACTS. */
export type CodeLine = {
  tokens: CodeToken[];
  /** `// [!code highlight]` or fence meta `{1,3-5}`. */
  highlight: boolean;
  /** `// [!code ++]` / `// [!code --]` — a diff's added and removed lines. */
  add: boolean;
  remove: boolean;
  /** `// [!code focus]` — this line is the point; the rest stand down. */
  focus: boolean;
  /** `// [!code error]` / `// [!code warning]` — the line a message is about. */
  level?: "error" | "warning" | undefined;
};

export type HighlightedCode = {
  lines: CodeLine[];
  /** Any line focused — the renderer keys the stand-down of the others on it. */
  focused: boolean;
  /** Any line added or removed — the renderer gives EVERY line a marker gutter, because a
      diff's context lines must stay aligned with its marked ones. */
  diff: boolean;
};

/** The code as the reader receives it: annotations stripped, exactly what the copy button
    hands over and what a selection drags. One derivation, so the paint and the clipboard
    cannot disagree about what the code says. */
/**
 * How many columns of whitespace a line begins with.
 *
 * A wrapped row has to continue at the line's OWN indentation, and CSS cannot read that: the
 * leading whitespace is part of the line's text, so the only thing a stylesheet can hang from
 * is the pane's wall. Every renderer that gets this right — an editor, a terminal, a diff view
 * — knows the number because it laid the text out itself. Here the tokenizer already holds it,
 * so it is derived once, at build time, beside `plainText` and for the same reason: a fact
 * about a line, read off the tokens rather than reconstructed from the markup they produce.
 *
 * Columns, not pixels. The well is monospaced, so a column IS a `ch`, and the number crosses
 * into CSS as one — the same argument `code.css` makes for stating its own distances in `ch`.
 * TABS ARE COUNTED AS ONE COLUMN and no source shipped here has any (a law walks for them),
 * because a tab's width is a rendering choice and honouring it would mean this file agreeing
 * with `tab-size` in two homes.
 */
export const leadingColumns = (line: CodeLine): number => {
  const text = line.tokens.map((token) => token.text).join("");
  return text.length - text.trimStart().length;
};

export const plainText = (lines: readonly CodeLine[]): string =>
  lines.map((line) => line.tokens.map((token) => token.text).join("")).join("\n");

/* ── The fence-meta vocabulary ─────────────────────────────────────────────────────────── */

/** What a fence's meta string can say, parsed by `parseMeta`. The chrome facts are ours;
    `{1,3-5}` and `/word/` stay in `rest` and ride Shiki's own meta transformers. */
export type FenceMeta = {
  title?: string | undefined;
  /**
   * `undefined` when the fence did not say, which is not the same as `false`. A consumer that
   * numbers every fence by default needs something to say NO with, and a two-state flag leaves
   * nothing — while a flag whose default flips makes every authored `lineNumbers` a no-op that
   * still reads as a decision. Three states: `lineNumbers` asks, `lineNumbers=false` refuses,
   * and silence is the consumer's own default.
   */
  lineNumbers?: boolean | undefined;
  maxLines?: number | undefined;
  bare: boolean;
  /** Whatever this file did not claim, handed to Shiki as the raw meta. */
  rest: string;
};

/**
 * Parse a fence's meta string — ```ts title="x.ts" lineNumbers=false maxLines=20 {1,3} — into
 * block's own props plus a remainder for Shiki. Closed vocabulary: an unrecognised WORD is
 * left in `rest` deliberately (Shiki's `{…}` and `/…/` live there), but the four claimed
 * directives are removed so they cannot also match as code words.
 */
export function parseMeta(meta: string | undefined): FenceMeta {
  let rest = meta ?? "";
  const take = (pattern: RegExp): string | undefined => {
    const match = pattern.exec(rest);
    if (!match) return undefined;
    rest = (rest.slice(0, match.index) + rest.slice(match.index + match[0].length)).trim();
    return match[1] ?? match[0];
  };
  const title = take(/title="([^"]*)"/);
  const maxLinesRaw = take(/(?:^|\s)maxLines=(\d+)(?=\s|$)/);
  /* `=true`/`=false` return the captured word; the bare form has no capture, so `take` gives
     back the whole match and anything that is not the literal "false" is an ask. */
  const lineNumbersRaw = take(/(?:^|\s)lineNumbers(?:=(true|false))?(?=\s|$)/);
  const lineNumbers = lineNumbersRaw === undefined ? undefined : lineNumbersRaw !== "false";
  const bare = take(/(?:^|\s)bare(?=\s|$)/) !== undefined;
  return {
    title,
    lineNumbers,
    maxLines: maxLinesRaw === undefined ? undefined : Number(maxLinesRaw),
    bare,
    rest: rest.trim(),
  };
}

/* ── The HAST walk ─────────────────────────────────────────────────────────────────────── */

/** The slice of HAST this file consumes, typed locally so the walk's assumptions are stated
    here rather than imported. Anything outside this shape throws in `tokenize`. */
type HastText = { type: "text"; value: string };
type HastElement = {
  type: "element";
  tagName: string;
  properties?: Record<string, unknown>;
  children: (HastElement | HastText | { type: string })[];
};

const isElement = (node: { type: string }): node is HastElement => node.type === "element";
const isText = (node: { type: string }): node is HastText => node.type === "text";

const classesOf = (node: HastElement): string[] => {
  const value = node.properties?.["class"] ?? node.properties?.["className"];
  if (value === undefined || value === null) return [];
  if (Array.isArray(value)) return value.map(String);
  return String(value).split(/\s+/);
};

/** All text under a node. Recursive because a transformer may nest a span; LOUD about any
    child kind that is neither element nor text, because swallowing one is how a token
    silently vanishes from the copy path. */
const textOf = (node: HastElement | HastText): string => {
  if (isText(node)) return node.value;
  return node.children
    .map((child) => {
      if (isText(child) || isElement(child)) return textOf(child);
      throw new Error(`highlight: unexpected ${child.type} node inside a token`);
    })
    .join("");
};

/** A token span's two styled facts, off its inline style string. The CSS-variables theme
    writes `color:var(--code-…)` and `font-style:italic`; bold (`font-weight`) is dropped
    here, which is the §15 refusal as a filter rather than a regex over emitted HTML. */
const styleOf = (node: HastElement): { color?: string; italic: boolean } => {
  const style = String(node.properties?.["style"] ?? "");
  const color = /(?:^|;)\s*color:([^;]+)/.exec(style)?.[1]?.trim();
  return { ...(color ? { color } : {}), italic: /font-style:\s*italic/.test(style) };
};

/**
 * Tokenize, returning LINES OF FLAGGED TOKENS rather than a string of HTML.
 *
 * `meta` is the fence's leftover meta string (after `parseMeta` took the chrome facts), so
 * `{1,3-5}` and `/word/` reach Shiki's own meta transformers unre-implemented.
 */
export async function tokenize(
  code: string,
  lang: Lang,
  meta?: string,
): Promise<HighlightedCode> {
  const highlighter = await getHighlighter();
  const root = highlighter.codeToHast(code.replace(/\n+$/, ""), {
    lang,
    theme: THEME_NAME,
    ...(meta ? { meta: { __raw: meta } } : {}),
    transformers: [
      transformerNotationDiff({ matchAlgorithm: "v3" }),
      transformerNotationHighlight({ matchAlgorithm: "v3" }),
      transformerNotationWordHighlight({ matchAlgorithm: "v3" }),
      transformerNotationFocus({ matchAlgorithm: "v3" }),
      transformerNotationErrorLevel({ matchAlgorithm: "v3" }),
      transformerMetaHighlight(),
      transformerMetaWordHighlight(),
    ],
  }) as unknown as { children: { type: string }[] };

  const pre = root.children.find(isElement);
  if (!pre || pre.tagName !== "pre") throw new Error("highlight: no <pre> in Shiki's output");
  const codeEl = pre.children.find(isElement);
  if (!codeEl || codeEl.tagName !== "code") throw new Error("highlight: no <code> in <pre>");

  const lines: CodeLine[] = [];
  for (const child of codeEl.children) {
    // The lines are span.line elements separated by "\n" text nodes; the renderer stacks
    // lines as blocks, so the separators are dropped here rather than re-derived there.
    if (isText(child)) {
      if (/^\n+$/.test(child.value)) continue;
      throw new Error(`highlight: stray text between lines: ${JSON.stringify(child.value)}`);
    }
    if (!isElement(child)) throw new Error(`highlight: unexpected ${child.type} between lines`);
    const classes = classesOf(child);
    if (!classes.includes("line")) throw new Error(`highlight: a non-line span between lines`);
    const tokens: CodeToken[] = [];
    for (const span of child.children) {
      if (isText(span)) {
        // Shiki keeps a diff/highlight line's trailing newline inside the line span.
        if (/^\n$/.test(span.value)) continue;
        throw new Error(`highlight: bare text inside a line: ${JSON.stringify(span.value)}`);
      }
      if (!isElement(span)) throw new Error(`highlight: unexpected ${span.type} in a line`);
      const { color, italic } = styleOf(span);
      tokens.push({
        text: textOf(span).replace(/\n$/, ""),
        color,
        italic,
        word: classesOf(span).includes("highlighted-word"),
      });
    }
    lines.push({
      tokens,
      highlight: classes.includes("highlighted") && !classes.includes("error") && !classes.includes("warning"),
      add: classes.includes("diff") && classes.includes("add"),
      remove: classes.includes("diff") && classes.includes("remove"),
      focus: classes.includes("focused"),
      level: classes.includes("error") ? "error" : classes.includes("warning") ? "warning" : undefined,
    });
  }

  return {
    lines,
    focused: lines.some((line) => line.focus),
    diff: lines.some((line) => line.add || line.remove),
  };
}
```

### code.css

```css
/* ── The author's annotations ──────────────────────────────────────────────────────────────
   The pane, the scroller, the mono family, the bound and the syntax token contract are
   `CodeBlock`'s; this file is the block's own half — the markup `code-sample.tsx` paints
   around the highlighter's tokens, and the five ways an author says "look here".

   The colours the tokens themselves resolve to are NOT here and must not come back: they are
   the package's, declared on the element, and Shiki is pointed at that prefix in
   `highlight.ts`. A copy of them in this file would be the same decision in two homes.

   Each line is a block-level span (the renderer emits no "\n" between them), because a line
   is the unit the author points at: a wash, a marker gutter and a number all belong to the
   LINE, and an inline run has no box to carry them.

   The wash reaches the well's edges through the surface-padding hook — the `m="bleed"`
   mechanism (§3) said in CSS: the negative margin undoes the pane's inset, the padding puts
   the text back, so an unwashed line renders byte-identically and a washed one paints edge to
   edge.

   NO `inline-size: max-content` HERE, and it must not come back: a max-content box is sized
   to its longest unbroken run, so it never wraps, and the element would overrule the
   `pre-wrap` the package states one file over. What it buys, stated honestly, is a wash
   covering the full SCROLLED width rather than stopping at the viewport. Wrapping removes
   almost every scroll, so the case is the rare one (a line with no space in it), and there
   the wash stops at the viewport's edge.

   A WRAP CONTINUES UNDER THE LINE'S OWN INDENT, and that is three distances rather than one.
   `text-indent` pulls the FIRST row back out of the padding, so row one starts exactly where
   it always did; every row after it begins at the padding, which is the sum of what row one
   spends before its glyphs — the number gutter, the line's own leading whitespace — plus the
   hang. All three are stated in `ch` for the reason `Code`'s own padding is stated in `em`:
   these are distances measured in characters, because the thing they indent is measured in
   characters.

   `--kd-indent` IS THE HALF CSS CANNOT WORK OUT, so the renderer writes it per line (see
   `code-sample.tsx`). Hanging from a fixed distance instead puts every continuation at column
   zero: it then reads as a SHALLOWER nesting level than the line it belongs to, which is a
   worse failure than not hanging at all — measured, a line indented seven columns began at
   x=525 and continued at 467, back at the code's own left wall.

   AND THE GUTTER IS NOT THE HANG. Spending one number on both makes the digits and the hang
   the same distance, which sounds economical and means a numbered fence has no hang left: the
   whole of it goes under the numbers, and every continuation lands flush at column zero — the
   defect the hang exists to prevent, on the only fences that carry numbers. They are two
   facts, so they are two numbers, and only one of them is conditional on anything.

   `min-block-size: 1lh` is what keeps an EMPTY line one line tall — a block span with no text
   has no line box of its own. */
.kd-line {
  /* How far a continuation hangs PAST the line's own indent. Two columns: enough to say "this
     is not a new statement" at a glance, and small enough that a wrapped row never travels far
     from the words it continues. A row's missing line number is the other half of the cue. */
  --kd-line-hang: 2ch;
  /* The line's own leading whitespace, written by the renderer on the lines that have any. */
  --kd-indent: 0ch;
  /* The number column, present only on a numbered fence — see the counter at the foot of this
     file, which is the one rule that sets it. */
  --kd-gutter: 0ch;
  /* WHERE A CONTINUATION BEGINS, and the one name the three declarations below share — a sum
     written three times is three chances to write it differently, and the box arithmetic only
     holds while the padding, the indent and the width bound agree to the pixel. */
  --kd-run: calc(var(--kd-gutter) + var(--kd-indent) + var(--kd-line-hang));
  display: block;
  /* THE HANG COMES OUT OF THE CONTENT WIDTH, or it is added to the BOX. This element is
     content-box, so `min-inline-size: 100%` sizes the content and the padding lands on top of
     it — measured, every well on the site kept 34px of sideways scroll after the wrap landed,
     which is the hang exactly. Subtracting it here keeps the border box at the pane's padding
     box, which is what makes a wash reach both edges. */
  min-inline-size: calc(100% - var(--kd-run));
  min-block-size: 1lh;
  margin-inline: calc(-1 * var(--kui-sf-p, 0px));
  padding-inline-end: var(--kui-sf-p, 0px);
  padding-inline-start: calc(var(--kui-sf-p, 0px) + var(--kd-run));
  text-indent: calc(-1 * var(--kd-run));
}

/* Five ways to say "look here", every colour a token. The washes are the families' own alpha
   steps so they composite against the well's local ground; a diff's added and removed lines
   are the status families — the same vocabulary the token colours speak (inserted, deleted,
   changed). */
.kd-line-highlight {
  background: var(--neutral-a3);
}
.kd-line-add {
  background: var(--success-a3);
}
.kd-line-remove {
  background: var(--destructive-a3);
}
.kd-line-error {
  background: var(--destructive-a3);
}
.kd-line-warning {
  background: var(--warning-a3);
}

/* Focus stands the OTHER lines down rather than raising the focused ones — the same shape as
   every stand-down in the system, and `--disabled-dim` is the one token that already means
   "present, not current". A hover restores the whole block, because a reader leaning in has
   asked to inspect. */
.kd-focused .kd-line:not(.kd-line-focus) {
  opacity: var(--disabled-dim);
}
.kd-focused:hover .kd-line {
  opacity: 1;
}

/* A pointed-at word. The pad-and-negative-margin pair keeps the glyph advance untouched, so
   the mono grid does not shift around the chip; `em` because the chip's breathing room is a
   property of the glyphs inside it (the atoms' rule, §15). */
.kd-word {
  background: var(--accent-a3);
  border-radius: 0.25em;
  padding-inline: 0.2em;
  margin-inline: -0.2em;
}

/* The diff gutter. A real span rather than a pseudo — ::before belongs to the line-number
   counter — hidden from AT by the renderer and from selection here, so the clipboard never
   grows a column of plus signs. Every line in a diff block carries one (context lines get an
   empty span) so marked and unmarked lines stay aligned. */
.kd-line-marker {
  display: inline-block;
  inline-size: 2ch;
  user-select: none;
}
.kd-line-add > .kd-line-marker {
  color: var(--success-ink);
}
.kd-line-remove > .kd-line-marker {
  color: var(--destructive-ink);
}

/* ── Line numbers ──────────────────────────────────────────────────────────────────────────
   CSS counters, never markup — the ecosystem's one unanimous answer — which is also what
   keeps a number out of every selection and every copy. Faint: a number is wayfinding, not
   content. */
.kd-numbered {
  counter-reset: kd-line;
}
/* Declared on the LINE rather than on the block, because `--kd-run` is substituted where it is
   declared (§6) — set on the ancestor, the line's own padding would resolve it to the 0ch
   default and reserve nothing for digits that are painted anyway. */
.kd-numbered .kd-line {
  --kd-gutter: 4ch;
}
.kd-numbered .kd-line::before {
  counter-increment: kd-line;
  content: counter(kd-line);
  display: inline-block;
  /* The digits and the space after them, which together are `--kd-gutter` — declared on the
     LINE, because that is the box whose padding has to reserve it, and read here so the two
     cannot disagree. The gutter is not the hang: see the head of this file. */
  inline-size: calc(var(--kd-gutter) - 1.5ch);
  margin-inline-end: 1.5ch;
  text-align: end;
  color: var(--color-text-faint);
}

/* THE FIGURE'S CHROME, and its two facts.
 *
 * THE INSET HAS ONE HOME HERE, and it must be the one the package's code well uses: a figure
 * holds a well, so two chrome rows are visible at once and a reader sees them against each
 * other. They disagreed once already — 12 against 24 — because each side picked a value nobody
 * could compare, and a law now holds these to the package's own choice.
 *
 * IT FLOATS, so the code starts at the pane's top edge and the row sits over the band the well
 * reserves for it. It was revealed on hover for one iteration — see the rule below for why that
 * went — and while it was, it had to be keyed on the FIGURE rather than on the well: the tab
 * bar's copy button sits outside the well, so a well-keyed rule could never reach it.
 */
.kd-figure {
  --kd-chrome-p: var(--layout-space-4);
  position: relative;
}

/* THE CHROME IS ALWAYS DRAWN, and it was revealed on hover for one iteration.

   Two things are wrong with revealing it, once you read a page rather than one figure: a
   control that appears when the pointer arrives cannot be seen from anywhere else on the page,
   so a reader has to suspect it before they can find it — and the band the well reserves is
   held whether or not anything is drawn in it, so hiding the one thing in that band buys
   nothing back.

   It stays legible over the code because it is GLASS, which is the arrangement §10 exists for:
   a floating control over content that passes behind it. */
/* The stage centres its subject far from the ground's walls, so the concentric corner (§6) has
   no corner to be concentric with. Cleared here, a Card or Surface on the stage wears its own. */
.kd-figure-stage {
  --kui-nest: initial;
}

.kd-figure-chrome {
  padding: var(--kd-chrome-p);
  /* In flow above the paper: reaches the ground's top and side walls,
     keeps its own padding as the gap to the card below. */
  margin-block-start: calc(-1 * var(--kui-sf-p));
  margin-inline: calc(-1 * var(--kui-sf-p));
}
```
