# Code View

Code on its own, with line numbers: a listing, a diff, or an editor.

The code itself, with no frame, to place anywhere: an editor pane, a diff view, the body of a Code Block. A gutter of line numbers as wide as the widest number, then the code in mono at a 20px line height with light syntax colouring (keywords, strings and numbers, function calls), or lines already highlighted elsewhere. A diff shows one gutter, a green / red accent bar, a row tint and word-level add / del highlights. A current line is tinted across the gutter and the code. Long lines wrap (wrap) or the code scrolls sideways under a gutter that stays. Its height is the code's, a fixed height, a cap past which it scrolls, or its container's (fill). Read-only it is plain markup, complete in the first frame and server-rendered, and every line is in the page. editable turns it into a code editor (CodeMirror 6): undo history, find and replace (a compact widget floating over the code), several cursors, folding by indentation. The editor is loaded only then (a dynamic import), so a read-only view never downloads it; its packages are installed with the component all the same. It looks exactly like the listing: same font, line height, gutter, colours, current-line tint and insets. An editable view keeps a 12px fold column after the gutter's hairline, in the listing shown while the editor loads as well, so nothing moves when the editor arrives; a read-only view has none, so turning editable on or off on a live view moves the code by that column.

Kind: component · Category: Display · Status: beta · Targets: React, Vue, Svelte

## Add

```bash
npx fndn add code-view
```

It writes the folder `code-view/` into the project's ui folder (`index.ts`, `code-view.tsx`, `CodeView.vue`, `CodeView.svelte`, `code-view.recipe.ts`), and what it is built from: [Button](/components/button.md), [Input Group](/components/input-group.md), [Toggle](/components/toggle.md), [Tooltip](/components/tooltip.md). First time: [Installation](/installation.md).

## Usage

```tsx
import { CodeView } from "@/components/ui/code-view";
```

```vue
import { CodeView } from "@/components/ui/code-view";
```

```svelte
import { CodeView } from "$lib/components/ui/code-view";
```

## Parts

In the DOM the root carries `data-slot="code-view"` and each part `data-slot="code-view-<part>"`; in the recipe the root is the `base` slot and each part a slot named after it in camelCase.

| Part | Element | data-slot | Flags | Notes |
| --- | --- | --- | --- | --- |
| `root` | `div` | `code-view` |  | The box: surface fill, no frame, no radius, no shadow; the font, 20px line and colour of the code; code reads left to right (direction: ltr) in every page. Carries --fndn-code-view-height (height) and --fndn-code-view-max-height (maxHeight); fill makes it as tall as its container. |
| `body` | `div` | `code-view-body` |  | The listing's scroller, 12px block inset. While the code overflows it is a focusable role=region named by label (code-view.logic.ts watchOverflow). Gone once the editor shows. |
| `rows` | `div` | `code-view-rows` |  | Grid: the gutter column (as wide as the widest number) + the code; rows are subgrids |
| `row` | `div` | `code-view-row` | repeats | One line. A diff row is tinted by its kind (ctx, add, del). The current line is tinted (hover) and carries aria-current="true". |
| `bar` | `span` | `code-view-bar` | optional | Diff only: the 3px accent bar of an added (green) or removed (red hatch) row, in the gutter |
| `num` | `span` | `code-view-num` |  | Line number: 2xs, ink-3 (ink on the current line), right-aligned on the gutter's hairline, not selectable. A diff shows the new number, or the old one on a removed row. |
| `code` | `code` | `code-view-code` |  | The line's text |
| `piece` | `span` | `code-view-piece` | optional | Diff only: an added or removed run of words, tinted |
| `tok` | `span` | `code-view-tok` | optional | A syntax colour (kw, str, fn) from the light tokenizer (code-view.logic.ts tokenize); the editor marks the same runs with the same classes |
| `icons` | `span` | `code-view-icons` | optional | Editable only, never shown: the Phosphor caret the editor copies into its fold markers |
| `editor` | `div` | `code-view-editor` | optional | Editable only: where the editor (a CodeMirror EditorView) is mounted. While it loads it lies over the listing, invisible, at the same size; then it takes the listing's scroll position and the listing goes. Everything inside is the editor's own markup, given the listing's look by code-view.editor.ts. |
| `search` | `div` | `code-view-search` | optional | Editable only, while find is open (Mod+F): the find widget, floating over the code at its top end corner (8px clear), so opening it never pushes or scrolls the code. The popup's surface, shadow and radius, 4px inset; at a narrow width it spans the view less 8px each side. It runs on CodeMirror's own search state, commands and keys. |
| `search-row` | `div` | `code-view-search-row` | optional, repeats | Row 1: the replace caret, the find field, the count, Previous, Next, Close. Row 2, while the caret is open: the replace field, Replace and Replace all. |
| `search-expand` | `button` | `code-view-search-expand` | optional | A Button (ghost, xs, square, muted) with a right caret that turns down while the replace row shows (aria-expanded), marked data-code-view="search-expand". The replace row is hidden each time find opens. |
| `search-field` | `input` | `code-view-search-field` | optional | An InputGroup (sm, mono) named Find, marked data-code-view="search-field" on its input, with three square Toggles (ghost, xs, muted) in its end: Aa match case, ab match whole word, .* regular expression, each named and tipped by its tooltip. It takes the focus, its text selected, when find opens and on Mod+F. |
| `search-count` | `span` | `code-view-search-count` | optional | "3 of 12" (the match the selection is on), "12 results" when it is on none, "No results", or nothing while the query is empty; xs, ink-2, tabular, as wide as "No results" so the row keeps still. A polite role=status, so the count is announced. |
| `replace-field` | `input` | `code-view-replace-field` | optional | An InputGroup (sm, mono) named Replace, marked data-code-view="replace-field", lined up under the find field; then Replace and Replace all, ghost xs Buttons. |

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `string` |  | Bindable (React: `defaultValue` and `onValueChange`; Vue: `v-model:value`; Svelte: `bind:value`). The code, lines separated by \n (an empty value is one empty line; a trailing \n ends in an empty last line, as in an editor). Editable, it is the editor's text: an edit reports it (valueChange); a value set from outside replaces the text and the caret keeps its place. |
| `highlighted` | `string[]` |  | Lines already highlighted elsewhere (shiki and the like), as trusted HTML, one string per line; shown instead of value's rows. Display only: editable shows value with the tokenizer's colours instead. |
| `diff` | `{ old: number\|null; cur: number\|null; type: ctx\|add\|del; pieces: { text: string; change?: 'add'\|'del' }[] }[]` |  | A unified diff, shown instead of value. A diff is never editable and has no current line. |
| `label` | `string` |  | The accessible name: of the scroll region while the listing overflows, of the editor's text box (a file name or path). |
| `editable` | `boolean` | `false` | A code editor on value (CodeMirror 6, loaded now): typing, undo / redo, find and replace, several cursors, folding by indentation. Tab indents; Escape then Tab leaves. Ignored with diff. |
| `currentLine` | `number` |  | Bindable (React: `defaultCurrentLine` and `onCurrentLineChange`; Vue: `v-model:currentLine`; Svelte: `bind:currentLine`). The current line, 1-based: its row is tinted (hover) across the gutter and the code, its number turns ink, and it is kept in view (the code scrolls just enough, at once; the page never scrolls). Editable, it is the caret's line, line 1 unless set: moving the caret reports it (currentLineChange), and a new value puts the caret at the start of that line. A diff has none. |
| `wrap` | `boolean` | `true` | Long lines wrap (as in documentation): a wrapped line keeps its number on its first row. false: a line never wraps; the code scrolls sideways and the gutter (with a diff's accent bar) stays at the inline start over an opaque fill, as an editor's does. |
| `height` | `number` |  | Fixed height in px: the box keeps its size whatever the code (loading, switching files). |
| `maxHeight` | `number` |  | Height in px past which the code scrolls. |
| `fill` | `boolean` | `false` | As tall as its container (give the container a height): the code scrolls inside. Layout only, nothing measured, so it follows every resize. |
| `labels` | `object` |  | The editor's words, for translation: { find, replace, toggleReplace, next, previous, close, matchCase, wholeWord, regexp, replaceOne, replaceAll, count, results, noResults, fold, unfold, folded }; in count and results, {current} and {total} stand for the numbers. |

Other attributes and `class` go to the root; `class` is merged through the recipe.

## Events

| Event | Payload |
| --- | --- |
| `valueChange` | (value: string) after every edit made in the editor (typing, paste, undo); never for a value set from outside |
| `currentLineChange` | (line: number) when the caret moves to another line in the editor |

## States

`overflowing`, `current-line`, `add`, `del`, `ctx`, `editable`, `focus`, `selection`

## Keyboard and accessibility

Role: region (the listing, while it scrolls); textbox, multi-line (editable).

Keyboard:

- Read-only: Tab reaches the code while it overflows; the arrow keys and Page Up / Page Down scroll it
- Editable: one tab stop. Typing edits; Tab and Shift+Tab indent and outdent the selected lines
- Editable: Escape, then Tab or Shift+Tab within two seconds, moves focus out of the editor; Ctrl+M (Shift+Alt+M on macOS) makes Tab move focus until pressed again
- Editable: Mod+Z undo, Mod+Shift+Z / Mod+Y redo; Mod+D adds the next occurrence as a cursor, Alt+click adds a cursor, Alt+drag a column of cursors; Ctrl+Shift+[ / ] (macOS Cmd+Alt+[ / ]) fold and unfold
- Find: Mod+F opens it with the focus in its field (again, takes the focus back to it); Enter next match, Shift+Enter previous, F3 / Mod+G and Shift+F3 / Mod+Shift+G too; Escape closes it and returns the focus to the code; Enter in the replace field replaces the current match. A match already in view never scrolls the code.

Notes:

- Read-only, the line numbers are user-select: none, so selecting and copying by hand skips them, and every line is in the page, so the browser's find reaches all of it.
- Editable, the text box is named by label and is aria-multiline; the gutter is aria-hidden; folding a range is announced. The focus shows as the caret and the current line, as in a field inside a composite surface: no ring.
- The code is direction: ltr: it reads left to right in right-to-left pages.
- The find widget's count is a polite status: it is announced as it changes. Every icon-only control is named, and its tooltip says its key.

## Motion

- None. The current line moves and is scrolled to at once: it follows the caret, a high-frequency action.
- The editor arriving: no motion and no shift; it takes the listing's scroll position.
- The caret blinks as an editor's does; not with reduced motion.
- Fold markers appear at once while the pointer is over the gutter; a folded line's marker always shows.
- Find widget: appears and goes at once (a keyboard action, used often). The replace caret turns down over duration.move with easing.out-strong, at once from the keyboard.

## Tokens

`color.accent`, `color.accent-ink`, `color.accent-tint`, `color.green`, `color.green-tint`, `color.hover`, `color.ink`, `color.ink-2`, `color.ink-3`, `color.inset`, `color.line`, `color.orange`, `color.orange-tint`, `color.red`, `color.red-tint`, `color.surface`, `font.mono`, `radius.card`, `radius.chip`, `shadow.raised`, `text.2xs`, `text.dense`

## Dependencies

- [Button](/components/button.md)
- [Input Group](/components/input-group.md)
- [Toggle](/components/toggle.md)
- [Tooltip](/components/tooltip.md)

## Examples

### Edit a config file

React · `edit-config.tsx`

```tsx
import { useState } from "react";
import { CodeView } from "@/components/ui/code-view";

const initial = [
  "export default {",
  "  project: \"web-app\",",
  "  regions: [\"fra1\", \"iad1\"],",
  "  buildCommand: \"pnpm build\",",
  "};",
].join("\n");

export default function EditConfig() {
  const [code, setCode] = useState(initial);
  return <CodeView editable label="northwind.config.ts" value={code} onValueChange={setCode} />;
}
```

Vue · `edit-config.vue`

```vue
<script setup lang="ts">
import { ref } from "vue";
import { CodeView } from "@/components/ui/code-view";

const code = ref([
  "export default {",
  "  project: \"web-app\",",
  "  regions: [\"fra1\", \"iad1\"],",
  "  buildCommand: \"pnpm build\",",
  "};",
].join("\n"));
</script>

<template>
  <CodeView v-model:value="code" editable label="northwind.config.ts" />
</template>
```

Svelte · `edit-config.svelte`

```svelte
<script lang="ts">
  import { CodeView } from "$lib/components/ui/code-view";

  let code = $state([
    "export default {",
    "  project: \"web-app\",",
    "  regions: [\"fra1\", \"iad1\"],",
    "  buildCommand: \"pnpm build\",",
    "};",
  ].join("\n"));
</script>

<CodeView bind:value={code} editable label="northwind.config.ts" />
```

### Point at the line that failed

React · `failed-build.tsx`

```tsx
import { CodeView } from "@/components/ui/code-view";

const log = [
  "$ pnpm build",
  "> web-app@2.14.0 build",
  "> vite build",
  "vite v6.2.0 building for production...",
  "transforming (412) src/routes/billing/invoices.tsx",
  "✓ 1,284 modules transformed.",
  "error during build:",
  "src/routes/billing/invoices.tsx (88:14): \"formatTotal\" is not exported by \"src/lib/money.ts\"",
  "  at getRollupError (node_modules/rollup/dist/es/shared/parseAst.js:397:41)",
  "ELIFECYCLE  Command failed with exit code 1.",
].join("\\n");

/* a build log with the line that failed marked; the log scrolls past 160px */
export default function FailedBuild() {
  return <CodeView label="Build log" value={log} currentLine={8} maxHeight={160} />;
}
```

Vue · `failed-build.vue`

```vue
<script setup lang="ts">
import { CodeView } from "@/components/ui/code-view";

const log = [
  "$ pnpm build",
  "> web-app@2.14.0 build",
  "> vite build",
  "vite v6.2.0 building for production...",
  "transforming (412) src/routes/billing/invoices.tsx",
  "✓ 1,284 modules transformed.",
  "error during build:",
  "src/routes/billing/invoices.tsx (88:14): \"formatTotal\" is not exported by \"src/lib/money.ts\"",
  "  at getRollupError (node_modules/rollup/dist/es/shared/parseAst.js:397:41)",
  "ELIFECYCLE  Command failed with exit code 1.",
].join("\\n");
</script>

<!-- a build log with the line that failed marked; the log scrolls past 160px -->
<template>
  <CodeView label="Build log" :value="log" :current-line="8" :max-height="160" />
</template>
```

Svelte · `failed-build.svelte`

```svelte
<script lang="ts">
  import { CodeView } from "$lib/components/ui/code-view";

  const log = [
    "$ pnpm build",
    "> web-app@2.14.0 build",
    "> vite build",
    "vite v6.2.0 building for production...",
    "transforming (412) src/routes/billing/invoices.tsx",
    "✓ 1,284 modules transformed.",
    "error during build:",
    "src/routes/billing/invoices.tsx (88:14): \"formatTotal\" is not exported by \"src/lib/money.ts\"",
    "  at getRollupError (node_modules/rollup/dist/es/shared/parseAst.js:397:41)",
    "ELIFECYCLE  Command failed with exit code 1.",
  ].join("\n");
</script>

<!-- a build log with the line that failed marked; the log scrolls past 160px -->
<CodeView label="Build log" value={log} currentLine={8} maxHeight={160} />
```

### The body of an editor pane

React · `editor-pane.tsx`

```tsx
import { useState } from "react";
import { File } from "@phosphor-icons/react";
import { CodeView } from "@/components/ui/code-view";
import { Tabs } from "@/components/ui/tabs";

const files = [
  {
    path: "src/middleware/rate-limit.ts",
    name: "rate-limit.ts",
    code: [
      "import { buckets } from \"./store\";",
      "",
      "const WINDOW_MS = 60_000;",
      "const LIMIT = 120;",
      "",
      "export function rateLimit(key: string, now = Date.now(), options: { limit?: number; windowMs?: number } = {}) {",
      "  const bucket = buckets.get(key) ?? { count: 0, windowStart: now };",
      "  if (now - bucket.windowStart >= (options.windowMs ?? WINDOW_MS)) {",
      "    bucket.count = 0;",
      "    bucket.windowStart = now;",
      "  }",
      "  bucket.count += 1;",
      "  buckets.set(key, bucket);",
      "  return bucket.count <= (options.limit ?? LIMIT);",
      "}",
    ].join("\n"),
  },
  { path: "package.json", name: "package.json", code: "{\n  \"name\": \"billing-api\",\n  \"version\": \"2.14.0\",\n  \"private\": true\n}" },
];

/* an editor pane: closable file tabs over an editable code view (lines never wrap, the gutter
 * stays while the code scrolls sideways) */
export default function EditorPane() {
  const [open, setOpen] = useState(files);
  const [active, setActive] = useState(files[0]!.path);
  const edit = (path: string, code: string) => setOpen((tabs) => tabs.map((file) => (file.path === path ? { ...file, code } : file)));
  return (
    <div className="h-64 w-full max-w-[560px] overflow-hidden rounded-card bg-canvas shadow-card">
      {open.length ? (
        <Tabs
          size="xs"
          closable
          fill
          aria-label="Open files"
          value={active}
          onValueChange={setActive}
          onClose={(path) => setOpen((tabs) => tabs.filter((file) => file.path !== path))}
          items={open.map((file) => ({
            value: file.path,
            label: file.name,
            icon: <File data-slot="icon" />,
            content: <CodeView editable fill wrap={false} label={file.path} value={file.code} onValueChange={(code) => edit(file.path, code)} />,
          }))}
        />
      ) : (
        <p className="p-4 text-sm text-ink-2">No open files</p>
      )}
    </div>
  );
}
```

Vue · `editor-pane.vue`

```vue
<script setup lang="ts">
import { computed, ref } from "vue";
import { PhFile } from "@phosphor-icons/vue";
import { CodeView } from "@/components/ui/code-view";
import { Tabs } from "@/components/ui/tabs";

const files = [
  {
    path: "src/middleware/rate-limit.ts",
    name: "rate-limit.ts",
    code: [
      "import { buckets } from \"./store\";",
      "",
      "const WINDOW_MS = 60_000;",
      "const LIMIT = 120;",
      "",
      "export function rateLimit(key: string, now = Date.now(), options: { limit?: number; windowMs?: number } = {}) {",
      "  const bucket = buckets.get(key) ?? { count: 0, windowStart: now };",
      "  if (now - bucket.windowStart >= (options.windowMs ?? WINDOW_MS)) {",
      "    bucket.count = 0;",
      "    bucket.windowStart = now;",
      "  }",
      "  bucket.count += 1;",
      "  buckets.set(key, bucket);",
      "  return bucket.count <= (options.limit ?? LIMIT);",
      "}",
    ].join("\n"),
  },
  { path: "package.json", name: "package.json", code: "{\n  \"name\": \"billing-api\",\n  \"version\": \"2.14.0\",\n  \"private\": true\n}" },
];

const open = ref(files);
const active = ref(files[0]!.path);
const items = computed(() => open.value.map((file) => ({ value: file.path, label: file.name, icon: PhFile })));
const fileOf = (path: string) => open.value.find((file) => file.path === path)!;
</script>

<!-- an editor pane: closable file tabs over an editable code view (lines never wrap, the gutter
     stays while the code scrolls sideways) -->
<template>
  <div class="h-64 w-full max-w-[560px] overflow-hidden rounded-card bg-canvas shadow-card">
    <Tabs
      v-if="open.length"
      v-model:value="active"
      size="xs"
      closable
      fill
      aria-label="Open files"
      :items="items"
      @close="(path) => (open = open.filter((file) => file.path !== path))"
    >
      <template #panel="{ item }">
        <CodeView v-model:value="fileOf(item.value).code" editable fill :wrap="false" :label="item.value" />
      </template>
    </Tabs>
    <p v-else class="p-4 text-sm text-ink-2">No open files</p>
  </div>
</template>
```

Svelte · `editor-pane.svelte`

```svelte
<script lang="ts">
  import File from "phosphor-svelte/lib/FileIcon";
  import { CodeView } from "$lib/components/ui/code-view";
  import { Tabs } from "$lib/components/ui/tabs";

  const files = [
    {
      path: "src/middleware/rate-limit.ts",
      name: "rate-limit.ts",
      code: [
        "import { buckets } from \"./store\";",
        "",
        "const WINDOW_MS = 60_000;",
        "const LIMIT = 120;",
        "",
        "export function rateLimit(key: string, now = Date.now(), options: { limit?: number; windowMs?: number } = {}) {",
        "  const bucket = buckets.get(key) ?? { count: 0, windowStart: now };",
        "  if (now - bucket.windowStart >= (options.windowMs ?? WINDOW_MS)) {",
        "    bucket.count = 0;",
        "    bucket.windowStart = now;",
        "  }",
        "  bucket.count += 1;",
        "  buckets.set(key, bucket);",
        "  return bucket.count <= (options.limit ?? LIMIT);",
        "}",
      ].join("\n"),
    },
    { path: "package.json", name: "package.json", code: "{\n  \"name\": \"billing-api\",\n  \"version\": \"2.14.0\",\n  \"private\": true\n}" },
  ];

  let open = $state(files);
  let active = $state(files[0]!.path);
  const items = $derived(open.map((file) => ({ value: file.path, label: file.name, icon: File })));
  const fileOf = (path: string) => open.find((file) => file.path === path)!;
</script>

<!-- an editor pane: closable file tabs over an editable code view (lines never wrap, the gutter
     stays while the code scrolls sideways) -->
<div class="h-64 w-full max-w-[560px] overflow-hidden rounded-card bg-canvas shadow-card">
  {#if open.length}
    <Tabs
      bind:value={active}
      size="xs"
      closable
      fill
      aria-label="Open files"
      {items}
      onclose={(path) => (open = open.filter((file) => file.path !== path))}
    >
      {#snippet panel({ item })}
        <CodeView value={fileOf(item.value).code} onvaluechange={(code) => (fileOf(item.value).code = code)} editable fill wrap={false} label={item.value} />
      {/snippet}
    </Tabs>
  {:else}
    <p class="p-4 text-sm text-ink-2">No open files</p>
  {/if}
</div>
```

## Recipe

`code-view.recipe.ts`:

```ts
import { tv, type VariantProps } from "../lib/tv";

/* code-view — code on its own, with line numbers: a listing, a diff, or an editor. No frame: the
 * host (a Code Block's card, an editor pane) draws it. Every colour is a token.
 *
 * The font, the 20px line and the colour sit on the root, so the read-only listing and the editor
 * (code-view.editor.ts, which makes CodeMirror inherit them) are drawn alike. The listing is a grid:
 * one gutter column as wide as the widest number, then the code; each row is a subgrid. Code reads
 * left to right, also in right-to-left pages. */

const MONO = "[direction:ltr] font-mono";

export const codeView = tv({
  slots: {
    /* the box: fixed height (height), a cap (maxHeight) or the code's; the code scrolls inside */
    base: [
      "relative flex min-w-0 flex-col bg-surface text-dense leading-5 text-ink-2",
      MONO,
      "h-[var(--fndn-code-view-height,auto)] max-h-[var(--fndn-code-view-max-height,none)]",
    ],
    /* the read-only scroller: 12px block inset; a focusable region while it overflows */
    body: [
      "min-h-0 flex-1 overflow-auto overscroll-x-contain py-3",
      "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-accent focus-visible:-outline-offset-2",
    ],
    rows: "grid grid-cols-[max-content_minmax(0,1fr)]",
    row: "relative col-[1/-1] grid grid-cols-subgrid",
    bar: "absolute inset-y-0 start-0 w-[3px]",
    /* line numbers: right-aligned on the gutter's hairline; not selectable, so a hand copy skips them */
    num: "col-[1] min-w-5 px-1 border-e border-e-line text-2xs tabular-nums text-end text-ink-3 select-none",
    code: "col-[2] min-w-0 ps-1 pe-3 [font:inherit]",
    /* word-level add / del highlight (the change variant) */
    piece: "rounded-[3px] px-0.5 -mx-px box-decoration-clone",
    /* light syntax colouring: keywords, strings and numbers, function calls (the tok variant);
     * the editor marks the same runs with the same classes */
    tok: "",
    /* where the editor is mounted; its own markup inside is themed by code-view.editor.ts */
    editor: "isolate flex min-h-0 flex-1 flex-col [&>.cm-editor]:min-h-0 [&>.cm-editor]:flex-1",
    /* the fold marker's icon, which the editor copies into its gutter */
    icons: "hidden",
    /* the find widget: floats over the code at its top end corner, so opening it moves nothing;
     * the popup's surface, shadow and radius, 4px inset. At a narrow width it spans the view less
     * 8px each side. Row 1: the replace caret, the find field (its options inside its end), the
     * count, Previous, Next, Close; row 2, while shown: the replace field and its two actions. */
    search: "absolute top-2 end-2 flex w-max max-w-[calc(100%-16px)] flex-col gap-1 rounded-card bg-surface p-1 font-sans text-ink shadow-raised",
    searchRow: "flex min-w-0 items-center gap-1",
    /* the caret turns down while the replace row shows, as a disclosure's does */
    searchExpand: "[&_[data-slot=icon]]:motion-transform-move [&_[data-slot=icon]]:kbd-instant [&[aria-expanded=true]_[data-slot=icon]]:rotate-90",
    /* the option toggles' faces are short mono glyphs (Aa, ab, .*), as editors show them */
    searchField: "w-56 min-w-0 flex-1 [&_[data-slot=input-group-end]_button]:font-mono [&_[data-slot=input-group-end]_button]:text-[11px]",
    /* "3 of 12": as wide as "No results", so the row keeps still while it counts */
    searchCount: "min-w-16 shrink-0 px-1 text-center text-xs whitespace-nowrap tabular-nums text-ink-2",
    replaceField: "w-56 min-w-0 flex-1 ms-7",
  },
  variants: {
    /* the diff's accent bar sits in the gutter: numbers keep clear of it */
    diff: { true: { num: "ps-[7px]" } },
    /* wrap: long lines wrap (as in documentation). Off: a line never wraps, the code scrolls
     * sideways, and the gutter (and a diff's accent bar) stays at the inline start over an opaque
     * fill, so code slides under it. Code reads left to right in every page, so the sticky start is
     * the left edge. */
    wrap: {
      true: { code: "wrap-anywhere whitespace-pre-wrap" },
      false: {
        rows: "w-max min-w-full grid-cols-[max-content_1fr]",
        /* every cell sits on the row's one line (the bar shares the gutter's cell) */
        code: "row-[1] whitespace-pre",
        num: "sticky start-0 z-[1] row-[1] bg-surface",
        /* the bar leaves its absolute place for the gutter's cell, so it sticks with the numbers */
        bar: "sticky start-0 inset-y-auto z-[2] col-[1] row-[1] self-stretch justify-self-start",
      },
    },
    /* editable: the editor's fold column (12px after the gutter's hairline) is kept free in the
     * listing shown while the editor loads, so nothing moves when it arrives */
    fold: { true: { code: "ps-4" } },
    /* the editor is mounted but not shown yet: it lies over the listing, laid out at the same size
     * (so it measures and takes the listing's scroll position), and invisible */
    ready: { false: { editor: "invisible absolute inset-0" } },
    /* as tall as its container: the code scrolls inside */
    fill: { true: { base: "h-full min-h-0" } },
    /* the current line: the row is tinted across the gutter and the code, its number turns ink */
    current: { true: { row: "bg-hover", num: "text-ink" } },
    /* a diff row's kind: tint, accent bar (striped for a removal) and number colour */
    type: {
      ctx: {},
      add: { row: "bg-green-tint", bar: "bg-green", num: "text-green" },
      del: {
        row: "bg-red-tint",
        bar: "bg-[repeating-linear-gradient(45deg,var(--fndn-red)_0,var(--fndn-red)_1.5px,transparent_1.5px,transparent_3px)]",
        num: "text-red",
      },
    },
    change: {
      add: { piece: "bg-[color-mix(in_srgb,var(--fndn-green)_18%,transparent)]" },
      del: { piece: "bg-[color-mix(in_srgb,var(--fndn-red)_18%,transparent)]" },
    },
    tok: {
      kw: { tok: "text-accent-ink" },
      str: { tok: "text-orange" },
      fn: { tok: "font-medium text-ink" },
    },
  },
  /* a sticky gutter number carries its row's tint over the opaque surface */
  compoundVariants: [
    { wrap: false, current: true, class: { num: "bg-hover" } },
    { wrap: false, type: "add", class: { num: "bg-[linear-gradient(var(--fndn-green-tint),var(--fndn-green-tint))]" } },
    { wrap: false, type: "del", class: { num: "bg-[linear-gradient(var(--fndn-red-tint),var(--fndn-red-tint))]" } },
  ],
  defaultVariants: { diff: false, wrap: true, fold: false, ready: true, fill: false, current: false },
});

export type CodeViewRecipeProps = VariantProps<typeof codeView>;
```
