# Rules

The design rules, as shipped in DESIGN.md.

Rax is a small design system for dense, data-heavy web apps: flat surfaces, strong text contrast, one accent colour you choose, light and dark modes. This file is the rule set. People and coding agents should read it before building UI with `@a31labs/rax`. It ships in the package at `node_modules/@a31labs/rax/DESIGN.md`.

## Setup

```sh
pnpm add @a31labs/rax react react-dom lucide-react
```

Peer dependencies: `react@^19`, `react-dom@^19`, `lucide-react@^1`.

Import the CSS once, at the top of your app's main stylesheet, in this order:

```css
@import "@a31labs/rax/styles.css";    /* first: fonts, tokens, base, every component, all inside @layer rax */
@import "tailwindcss";                /* only in apps that use Tailwind v4 */
@import "@a31labs/rax/tailwind.css";  /* optional: Tailwind theme mapped to Rax tokens */

:root { --rax-h: 258; --rax-c: 0.22; --rax-al: 0.55; --rax-al-dark: 0.66; }
```

Rax must come first. `styles.css` begins with `@layer theme, base, rax, components, utilities;`, and the first layer statement the browser sees fixes the order. With Rax first it sits below Tailwind's components and utilities, so your utility classes always win. If `tailwindcss` came first, `rax` would be appended as the last layer and override your utilities. Without Tailwind the layer still keeps your own CSS ahead of Rax whenever it is unlayered.

Import components from a subpath, one per component:

```tsx
import { Button } from "@a31labs/rax/button";
import { DataTable } from "@a31labs/rax/data-table";
```

The root export `@a31labs/rax` re-exports the primitives and `cx` (a class join helper), and never reaches `@tanstack/react-table`. Patterns (AppShell, SidebarShell, RailShell, PageHeader, Stat, KeyValueList, EmptyState, DataTable, FilterBar, Pagination, Card, BarList, Steps, Timeline, FileDrop, SelectionBar, SortableList) are subpath-only.

### Accent inputs

Rax ships the colour roles; the app sets the accent on `:root` with these inputs:

| Input | Meaning | Default |
|---|---|---|
| `--rax-h` | accent hue (oklch) | `258` |
| `--rax-c` | accent chroma | `0.22` |
| `--rax-al` | accent lightness, light mode | `0.55` |
| `--rax-al-dark` | accent lightness, dark mode | `0.66` |
| `--rax-accent-ink-l` | lightness of text on the accent, light mode (about 0.99 for dark accents, about 0.16 for light ones such as yellow) | `0.99` |
| `--rax-accent-ink-l-dark` | lightness of text on the accent, dark mode | `0.16` |

Pick values so text on the accent reaches 4.5:1 and the focus ring 3:1 in both modes. Presets verified by the contrast tests (inputs not listed keep their defaults):

| Preset | Inputs |
|---|---|
| blue (the defaults) | `--rax-h: 258; --rax-c: 0.22; --rax-al: 0.55; --rax-al-dark: 0.66` |
| teal | `--rax-h: 175; --rax-c: 0.13; --rax-al: 0.5; --rax-al-dark: 0.72` (`0.5`, not `0.55`: white on a lighter teal falls below 4.5:1) |
| yellow | `--rax-h: 88; --rax-c: 0.16; --rax-al: 0.8; --rax-al-dark: 0.82; --rax-accent-ink-l: 0.16` |
| graphite | `--rax-h: 260; --rax-c: 0; --rax-al: 0.25; --rax-al-dark: 0.9` |

### Second accent

One accent is the default and fits most apps. When a product needs a second brand colour, set any of `--rax-h2`, `--rax-c2`, `--rax-al2`, `--rax-al2-dark`, `--rax-accent-2-ink-l` and `--rax-accent-2-ink-l-dark`. They work like the accent inputs, and each one left unset falls back to its accent input, so without them `--rax-accent-2` is the accent. The presets above also pass as second accents.

The second accent gets the same roles: `--rax-accent-2`, `-ink`, `-soft` and `-line`. Components use it only where you ask for it: Badge, Progress and Timeline take `tone="accent-2"`, and chart series take `color: "accent-2"`. Buttons, focus rings, selection, checked controls and links stay on the first accent, so the second colour marks a category or a second series, never a second kind of action.

### Mode

Set `data-mode="light"` or `data-mode="dark"` on `<html>` (or on any element, to scope a region; scopes nest and every derived colour recomputes inside them). The class `.dark` is also supported for apps that already toggle it. Without either, Rax follows the system setting (`prefers-color-scheme`), so set `data-mode` explicitly when your app has its own theme switch. Each mode scope also sets `color-scheme`, so native scrollbars and form controls match. `prefers-contrast: more` raises `--rax-ink-2` and `--rax-edge` to `--rax-ink` in every mode and nested scope.

### Density

`data-density="default"` or `data-density="compact"` on any element. Compact shrinks controls and table rows. An explicit `data-density="default"` on a descendant overrides a compact ancestor. On coarse pointers (touch) the coarse sizes win over every density, so compact tables are larger on touch devices.

## Foundations

All custom properties are prefixed `--rax-`; all classes `rax-`. No colour or font family is written anywhere outside `tokens.css`. Do not write raw colours in app code either; use the roles.

### Typography

| Token | Value | Use |
|---|---|---|
| `--rax-font` | Inter Variable, system sans fallback | All UI text |
| `--rax-mono` | Red Hat Mono (400, 500), system mono fallback | Code, IDs, keys, shortcuts only |
| `--rax-fs` | 0.9375rem (15px) | Body, controls, labels, table cells |
| `--rax-fs-sm` | 0.875rem (14px) | Secondary text, table headers, hints, badges |
| `--rax-fs-h` | 1.125rem (18px) | Panel titles |
| `--rax-fs-title` | 1.5rem (24px) | Page titles, stat values |

- Nothing renders below 14px.
- Line height 1.5 for text, 1.25 for headings.
- Weights: 400 body and cell values; 500 labels; 600 buttons, table headers, primary cell text, badges, active tab and nav item; 700 page title, panel title, stat value, empty-state title.
- Numbers in tables and stats use tabular figures in the UI font. Mono is never used for figures.
- No tracked capitals and no mono labels.
- Fonts are self-hosted through `@fontsource-variable/inter` and `@fontsource/red-hat-mono` and imported by `styles.css`. No third-party font CDN.

### Size and spacing

| Token | Default | Compact | Coarse pointer |
|---|---|---|---|
| `--rax-h-ctl` (control height) | 40px | 30px | 44px |
| `--rax-h-ctl-sm` | 32px | 26px | 40px |
| `--rax-px-ctl` (control side padding) | 16px | 12px | 16px |
| `--rax-row-h` (table row) | 48px | 34px | 48px |
| `--rax-cell-px` (table cell side padding) | 16px | 12px | 16px |

- Panel: head padding 16px 20px, body 20px, footer 16px 20px with a 12px gap.
- Field: 8px between label, control and hint. Forms: 20px between fields, one column.
- Key-value lists: 12px row gap, 24px column gap. Page: 24px between sections.
- Spacing follows a 4px scale; control internals may use 2px steps.

### Shape

- Radius: controls 6px (`--rax-r-ctl`), panels and dialogs 10px (`--rax-r-panel`), badges 4px (`--rax-r-badge`), checkbox 3px (`--rax-r-check`); switch and avatar are fully round.
- Borders are 1px with three roles: `--rax-line` for dividers and panel borders (structure), `--rax-line-strong` for emphasis lines, the segmented control outline and the neutral badge outline, `--rax-edge` for the outline of anything you can click or type into (at least 3:1 against its background).
- Flat. No shadows on in-flow elements. Floating layers (dialog, popover, menu, tooltip, toast) use `--rax-shadow-float` only. `--rax-scrim` is the dialog backdrop.

### Colour roles

| Role | Light | Dark |
|---|---|---|
| `--rax-bg` | oklch(0.968 0.005 h) | oklch(0 0 0) |
| `--rax-surface` | oklch(1 0 0) | oklch(0.10 0.004 h) |
| `--rax-surface-2` | oklch(0.958 0.006 h) | oklch(0.155 0.006 h) |
| `--rax-surface-3` | oklch(0.925 0.008 h) | oklch(0.20 0.008 h) |
| `--rax-line` | oklch(0.885 0.008 h) | oklch(0.25 0.008 h) |
| `--rax-line-strong` | oklch(0.80 0.01 h) | oklch(0.34 0.01 h) |
| `--rax-edge` | oklch(0.60 0.014 h) | oklch(0.55 0.012 h) |
| `--rax-ink` | oklch(0.19 0.02 h) | oklch(0.97 0.004 h) |
| `--rax-ink-2` | oklch(0.40 0.016 h) | oklch(0.80 0.01 h) |
| `--rax-ink-3` | oklch(0.48 0.014 h) | oklch(0.68 0.01 h) |
| `--rax-focus` | oklch(0.46 max(c, 0.08) h) | oklch(0.82 max(c, 0.06) h) |

Also: `--rax-accent`, `--rax-accent-ink`, `--rax-accent-soft`, `--rax-accent-line`, `--rax-accent-text` (accent text on the surface, 4.5:1), `--rax-warn-on` (text on a solid warn fill), the same four for `--rax-accent-2`, and the status roles `--rax-ok`, `--rax-warn`, `--rax-danger`, each with `-soft` (fill) and `-ink` (text on the soft fill, 4.5:1). Status glyphs are lucide icons (CircleCheck, TriangleAlert, OctagonMinus, Info, Circle), drawn solid: the shape is filled and the mark is cut out of it; idle is an empty ring. They appear in badges, alerts, toasts, timelines and field errors.

Contrast rules:

- Body text 4.5:1 minimum.
- Secondary text that carries meaning uses `--rax-ink-2` (7:1). `--rax-ink-3` (4.5:1) is for placeholders, empty-cell dashes and disabled hints only.
- Control outlines (`--rax-edge`) and the focus ring 3:1 minimum.
- Few colours: one accent (a second only when the brand needs it), three statuses, tinted neutrals. Status colour is never decorative.

### Motion and feedback

- Colour and border transitions are 100ms. `transform` and `opacity` are the only animated geometry. Never `transition: all`.
- Loading indicators appear only after 100ms, so fast responses never flash a spinner.
- Nothing animates for decoration. Under `prefers-reduced-motion: reduce` nothing travels and spinners are static.
- Focus: `outline: 2px solid var(--rax-focus); outline-offset: 2px` on `:focus-visible`, shown instantly. Inside tabs, nav, list rows and table rows the offset is `-2px` (inset).

### Tailwind bridge

With `@a31labs/rax/tailwind.css` imported, layout code can use `bg-surface`, `text-ink-2`, `border-line`, `rounded-panel` and the other mapped names. The bridge maps tokens only; components keep their own classes.

## Components

Every component takes `className`, passes `ref` as a regular prop (React 19) and spreads remaining native props. There are no style props. Components with item configs (Tabs, SegmentedControl, Breadcrumbs, AppShell nav) accept an `attrs` object of `data-*` attributes per item, spread on that item's element. Decorative icons use `lucide-react` with `aria-hidden`.

### Primitives

#### Button, `@a31labs/rax/button`
Props: `variant` (`primary` | `secondary` default | `outline` | `ghost` | `danger`), `tone` (`accent` default | `ok` | `warn` | `danger`; colours primary and outline buttons), `size` (`default` | `sm`), `loading`, plus native button props (`type` defaults to `button`). Primary is accent fill; secondary is surface with an `edge` outline; ghost has no fill and ink-2 text; danger is danger-soft with a danger outline, solid on hover. Outline is transparent with a 1px edge in the tone and its label in the tone's text colour (`--rax-accent-text`, or the status ink), the soft fill on hover. `tone` adds colour to a decision row: Approve is `primary` + `ok` (ok-ink fill), Request changes `outline` + `warn` (or `primary` + `warn`: warn fill with `--rax-warn-on` text), Decline `outline` + `danger`. Labels always name the action; colour never carries it alone. Weight 600, active state moves 1px down, disabled at 50% opacity. `loading` shows a spinner after 100ms, keeps the width, ignores clicks and sets `aria-busy`. A button with `aria-disabled="true"` looks disabled and also ignores clicks (and form submit) while staying focusable. One primary per view region.

#### IconButton, `@a31labs/rax/icon-button`
Props: `label` (required: the aria-label and the native `title` tooltip), `icon`, plus Button props except `children`. Icons without words only for universally known actions (close, more, copy, delete with confirm); everything else gets icon plus text.

#### Spinner, `@a31labs/rax/spinner`
Prop `delay` (ms, default 100). Hidden until the delay passes; static under reduced motion.

#### Field, `@a31labs/rax/field`
Props: `label`, `hint`, `error`, `className`, `ref` (root element), one control as the child (Input, Textarea, Select, ...). Label on top (500), hint below in ink-2 at 14px. With `error` the control gets a danger outline and the hint is replaced by the error text in danger-ink, weight 500, with the danger glyph in front. The hook `useBlurValidation(value, validate)` returns `{ error, onBlur }`: no error until the first blur, then live while the user fixes it.

#### Input, `@a31labs/rax/input`
Native input props plus `mono`. Surface fill, `edge` outline, hover outline `ink-3`, focus ring. Placeholder only shows a format example and never replaces the label. Read-only: surface-2 fill. Disabled: 55% opacity.

#### Textarea, `@a31labs/rax/textarea`
Native textarea props, styled like Input.

#### Select, `@a31labs/rax/select`
Props: `value`, `onValueChange`, `items` (`{ value, label }`), `placeholder`, `disabled`, `readOnly`, `name`, `required`, `form`, `container`. `ref`, `id`, `onBlur`, `aria-*` and other native button props go to the trigger, so it works inside Field and with `useBlurValidation`; with `name` the value posts in a native form through a hidden input. Same shape as Input; the popup is a floating layer and opens above dialogs.

#### Checkbox, Radio, `@a31labs/rax/checkbox` and `@a31labs/rax/radio`
Props: `label` plus the Base UI root props; Radio comes with `RadioGroup`. 18px, `edge` outline, accent fill when checked, the label is part of the hit area.

#### Switch, `@a31labs/rax/switch`
Props: `label` plus Base UI switch props. For immediate on/off settings only; forms that submit use Checkbox.

#### Badge, `@a31labs/rax/badge`
Prop `tone`: `neutral` | `accent` | `accent-2` | `ok` | `warn` | `danger` | `idle`. 22px high, 14px, weight 600, radius 4px. Neutral has a `line-strong` outline. Status tones always show their glyph (filled circle with a check, triangle with an exclamation mark, octagon with a bar, empty ring) before the word. `accent` is for counts and "new"; `accent-2` marks a second category.

#### Kbd, `@a31labs/rax/kbd`
A `kbd` element in the mono font.

#### Avatar, `@a31labs/rax/avatar`
Prop `name` (initials, fully round).

#### Skeleton, `@a31labs/rax/skeleton`
Prop `width`. Placeholder bar; static under reduced motion.

#### Separator, `@a31labs/rax/separator`
A 1px `line` divider, horizontal or vertical.

#### Alert, `@a31labs/rax/alert`
Props: `tone` (`info` | `ok` | `warn` | `danger`), `title`, children, plus native div props. Status soft fill, glyph, text in ink. The role is `alert` for danger and `status` otherwise; pass `role` to override it.

#### Tabs, `@a31labs/rax/tabs`
Props: `value`, `onValueChange`, `items` (`{ value, label, attrs }`), children (`TabPanel value=...`). For switching views of content. Underline style: items `h-ctl` high, hover surface-2, selected item ink text, weight 600 and a 3px bar in `--rax-focus` on the 1px `line` baseline.

#### SegmentedControl, `@a31labs/rax/segmented-control`
Props: `value`, `onValueChange`, `items` (`{ value, label, ariaLabel, attrs }`), `label`. For switching a mode or filter (preview width, table state, list or grid). Joined buttons in one `line-strong` outline, selected item surface-3. Never used for navigation.

#### Breadcrumbs, `@a31labs/rax/breadcrumbs`
Prop `items` (`{ label, href, attrs }`; the last has no `href`). Separators are a slash.

#### Dialog, `@a31labs/rax/dialog`
Props: `open`, `onOpenChange`, `title`, `description`, children, `footer`, `modal` (default true), `container`; `className` and `ref` go to the dialog box. Only for irreversible or blocking decisions. Floating shadow, scrim, focus trapped, Escape closes. The dialog never grows taller than the viewport minus 32px; the body scrolls instead.

#### ConfirmDialog, `@a31labs/rax/confirm-dialog`
Props: `open`, `onOpenChange`, `title`, `description`, `confirmLabel`, `onConfirm` (may be async), `container`. Initial focus is on Cancel, the least destructive action. While `onConfirm` runs the danger button shows loading; a rejection keeps the dialog open and shows the error. Name the object, explain the consequence, label the danger button with the verb ("Delete service").

#### Popover, Menu, Tooltip, `@a31labs/rax/popover`, `@a31labs/rax/menu`, `@a31labs/rax/tooltip`
Popover: `trigger`, children, `side`, controlled or default open. Menu: `trigger`, `items` (`{ label, onSelect, danger, icon, description, current }`); with an icon or description an item becomes a richer row (a 32px icon tile, the label in 600 and the description in ink-2 under it), for app or area switchers, and `current` adds a check. Tooltip: `content`, one child. All three take `container`, and `className` and `ref` for the floating popup. Tooltips never hold information that is not available elsewhere.

#### Toast, `@a31labs/rax/toast`
Wrap the app in `ToastProvider`, call `useToast().show({ title, description, tone, action })`. The subpath also exports `Toast`, the presentational toast (`title`, `description`, `tone`, `action`, `onDismiss`, `className`), for static previews; the root export has only `ToastProvider` and `useToast`. Toasts stay until dismissed (close button always present) with an optional single action such as "Undo". The region is announced with `role="status"`. While a modal dialog is open, toasts remain clickable without closing it; keyboard users reach them after the dialog closes.

#### CopyField, `@a31labs/rax/copy-field`
Props: `value`, `label`, plus native div props. Read-only mono input with a Copy button that confirms inline. When the clipboard is blocked it selects the text and shows "Press Ctrl+C or ⌘C to copy".

#### SearchInput, `@a31labs/rax/search-input`
Props: `value`, `onValueChange`, `loading`, plus native input props. `className` goes to the wrapper; `ref`, `id` and `aria-*` go to the input, so it works inside Field. Looks like Input with a leading search icon in ink-3. The browser's own clear button is hidden. A ghost "Clear search" IconButton appears only when there is a value, and clicking it puts focus back in the input. Escape clears a non-empty value without closing a surrounding dialog; on an empty value Escape works as usual. `loading` replaces the icon with a Spinner after the usual 100ms delay. FilterBar uses it.

#### Combobox, `@a31labs/rax/combobox`
Props: `items` (`{ value, label, keywords }`), `value` and `onValueChange` (a string, or `string[]` with `multiple`), `placeholder`, `onQueryChange`, `onCreate`, `emptyText`, `disabled`, `name`, `container`. `ref`, `id` and `aria-*` go to the input, so it works inside Field; with `name` the value posts through a hidden input. Same shape as Input with a chevron trigger. In `multiple` mode the selection shows as surface-3 chips inside the box, each with a "Remove <label>" button. The popup is a floating layer that looks like Select's. Filtering matches label, value and keywords, ignoring case. With `onQueryChange` the app filters (async search) and the component does not. `onCreate` adds a final "Create “query”" option when no label matches exactly. Use Select for short fixed lists and Combobox once people need to search.

#### TagInput, `@a31labs/rax/tag-input`
Props: `value` (`string[]`), `onValueChange`, `max`, `validate`, `placeholder`, `suggestions` (native datalist), `mono`, plus native input props (they go to the text input, so it works inside Field). Looks like Input: `edge` outline, focus ring on the whole box, wraps onto more lines. Chips are surface-3 with a 24px "Remove <tag>" button. Enter or comma adds a tag, Backspace in an empty field removes the last one, and leaving the field adds the pending text. Tags are trimmed; blanks and duplicates (ignoring case) are rejected. A `validate` or `max` error shows inline in danger-ink with the danger glyph, sets `aria-invalid`, and keeps the text so the user can fix it.

#### ColorInput, `@a31labs/rax/color-input`
Props: `value` (`#rrggbb`), `onValueChange`, `allowEmpty`, plus native input props for the hex field (use `aria-label` or Field). A native colour swatch labelled "Pick colour" sits beside a mono hex Input, and the two stay in sync. Typing `#rgb` or `#rrggbb` emits lowercase `#rrggbb`; partial text waits, and invalid text reverts on blur. An empty value is allowed only with `allowEmpty`.

#### TileGroup, `@a31labs/rax/tile-group`
Props: `value`, `onValueChange`, `items` (`{ value, label, description, icon, disabled }`), `label` (group name), `columns` (the most columns; tiles never go below 180px), `name`. A radio group of cards for plan or style pickers, with roving focus and arrow keys. A tile is surface with an `edge` outline, radius 10px and 16px padding; hover outline ink-3. Checked tiles get a 2px accent outline, an accent-soft fill and a check glyph in the corner. The label is the radio's name and the description is its accessible description.

#### ChipGroup, `@a31labs/rax/chip-group`
Props: `value` (string array), `onValueChange`, `items` (`{ value, label, count }`), `label` (group name), `ordered`. Multi-select toggle chips for filters and interests: `h-ctl-sm` high, fully round, `line-strong` outline, 14px weight 500, the count in ink-2 tabular. Pressed chips get an accent-soft fill, an `accent-line` border and a check icon. The value array keeps click order; with `ordered` a pressed chip shows its position number instead of the check.

#### Accordion, `@a31labs/rax/accordion`
Props: `items` (`{ value, title, content, attrs }`), `value`, `defaultValue`, `onValueChange` (string arrays), `multiple` (default false), plus Base UI root props. A bordered surface container (line border, radius 10px) with rows divided by `line`. Each header is a full-width button (weight 600, hover surface-2, inset focus ring) with a chevron that rotates 180° when open (static under reduced motion). Panels open and close without animation, because height never animates.

#### Drawer, `@a31labs/rax/drawer`
Props: `open`, `onOpenChange`, `title`, `description`, children, `footer`, `side` (`left` | `right` default), `container`; `className` and `ref` go to the sheet. A full-height sheet from a screen edge, width min(400px, 100vw − 32px), floating shadow, `line` border on its inner edge. Head with title, description and a ghost close IconButton; the body scrolls; the footer is right-aligned. Scrim, focus trapped, Escape closes, a swipe toward the edge dismisses. Slides in via transform, opacity only under reduced motion; toasts stay clickable as with Dialog. For mobile navigation and side forms, not for blocking decisions (use Dialog).

#### ThemeToggle and useMode, `@a31labs/rax/theme-toggle`
`useMode()` returns `{ mode: "light" | "dark" | "system", resolved, setMode }`. It sets `data-mode` on `<html>` (removed for `system`), stores the choice in localStorage under `rax-mode`, and follows `prefers-color-scheme` for `resolved`. All callers share one module-level store, so no provider is needed; on the server it reports `system` and `light`. `ThemeToggle` is a ghost IconButton (moon or sun) that switches between light and dark from the resolved mode; its label names the action ("Switch to dark mode"). Put `modeScript` in an inline `<script>` in `<head>` to apply the stored mode before first paint.

#### Progress, `@a31labs/rax/progress`
Props: `value` (clamped to 0..`max`; `null` means indeterminate), `max` (default 100), `label`, `valueLabel` (replaces the default "NN%", e.g. "3 of 5" or "1.2 GB of 5 GB"), `tone` (`accent` default | `accent-2` | `ok` | `warn` | `danger`). Wraps Base UI Progress. Label above the bar on the left, value text on the right in ink-2 with tabular figures; `valueLabel` is also the `aria-valuetext`. Track 8px, surface-3, fully round, fill in the tone colour, grown through `transform: scaleX` and static under reduced motion. Indeterminate shows an opacity-pulsing bar and no value text.

#### Sparkline, `@a31labs/rax/sparkline`
Props: `data` (numbers), `width` (default 96), `height` (default 24), `label` (required; `role="img"` and `aria-label`, e.g. "Requests, last 7 days: rising from 12 to 40"), `area` (fills under the line with accent-soft). An inline SVG line with no axes, for Stat values and table cells. The stroke is `currentColor` and defaults to `--rax-accent`; set `color` to recolour it. Empty data, a single point and flat lines render as a centred line.

#### RelativeTime, `@a31labs/rax/relative-time`
Props: `date` (Date, ISO string or ms), `locale`, `now` (fixes the reference time, for tests). Renders `<time dateTime={ISO}>` with "5 minutes ago" or "in 2 days" (`Intl.RelativeTimeFormat`, `numeric: "auto"`) and the absolute date (dateStyle medium, timeStyle short) as `title`. The server and first render show the absolute date, so hydration matches; the relative text replaces it after mount. Dates under an hour away update every 30s.

#### CodeBlock, `@a31labs/rax/code-block`
Props: `code`, `title` (header bar, e.g. a filename or "JSON"), `language` (sets `data-language` only, no highlighting), `wrap` (pre-wrap). A `<pre><code>` in the mono font on surface-2 with a `line` border and radius 10px. It scrolls horizontally and is focusable so keyboard users can scroll it. Copy sits in the head, or top-right without a title, and shows "Copied" for 2s; when the clipboard is blocked it selects the code. The Copy click does not propagate, so it works inside clickable rows.

### Patterns

#### AppShell, `@a31labs/rax/app-shell`
Props: `brand`, `nav` (`{ label, href, current, attrs }`), `actions`, children, `renderLink` (plug in a router link). 56px bar on surface with a bottom `line`; nav items look like Tabs, with a 3px bar on the current page.

#### SidebarShell, `@a31labs/rax/sidebar-shell`
Props: `brand`, `subtitle` (the current area under the brand), `switcher` (beside the brand, e.g. a Menu that switches areas), `nav` (groups of `{ label, href, icon, current, badge, attrs, children }`, a group may have a `label`), `footer` (pinned to the bottom: the signed-in user, sign out), `actions` (right side of the mobile bar), children, `renderLink`, `collapsible` with `collapsed`, `defaultCollapsed`, `onCollapsedChange`, `brandMark` and `collapsedFooter`, `topbar` (a 56px bar across the page above the sidebar for context pickers, a page path and actions; `brand` is then optional) and `navStart` (above the groups, e.g. a link back to the parent level). A group with `collapsible` turns its label into a toggle (`aria-expanded`) with a chevron. A 260px sidebar on surface with a `line` edge, sticky at full height; the main area gets 32px 40px padding. Items are `h-ctl` high with a 20px icon, 12px gap, ink-2 text; hover surface-2. The current page has a surface-2 fill, weight 600, a 3px accent bar on the left edge and its icon in the accent. Items with `children` get a chevron toggle (`aria-expanded`) and open by themselves when one of their pages is current; sub-pages are indented and smaller. With `collapsible`, a "Collapse sidebar" row above the footer narrows the sidebar to 72px of icons: labels and badges stay in the accessible name and show as a title on hover, group labels become a divider, sub-pages hide, and `brandMark` and `collapsedFooter` replace the brand and footer. Below 1024px the sidebar becomes a 56px top bar with a menu button that opens the same navigation in a left Drawer; following a link closes it. Set `--rax-shell-top` when something sticky sits above the shell.

#### RailShell, `@a31labs/rax/rail-shell`
Props: `brand`, `context` (beside the brand, e.g. company and site pickers), `actions` (right side of the bar), `rail` (`{ label, href, icon, current, attrs }`), `railEnd` (pinned to the bottom of the rail), `subnav` (`{ title, items: { label, href, current } }`, a second column with the section's pages), children, `renderLink`. A 56px top bar across the page; below it an 88px rail of icons (20px) with their label under them at 14px, the current section on accent-soft with its icon in the accent. The subnav column is 220px with plain links, the current one on surface-2. Below 1024px the subnav becomes a scrolling row above the content; below 640px the rail becomes a tab bar fixed to the bottom. Set `--rax-shell-top` when something sticky sits above the shell.

#### PageHeader, `@a31labs/rax/page-header`
Props: `title`, `icon` (optional; a lucide icon 24px in the accent colour, 12px before the title), `breadcrumbs`, `actions`. Title 24px weight 700, actions aligned to the title baseline on the right.

#### Panel, `@a31labs/rax/panel`
Props: `title`, `description`, `actions`, `footer`, `flush`, `icon` (a lucide icon before the title) and `iconTone` (`accent` default | `accent-2` | `ok` | `warn` | `danger` | `neutral`). The icon is optional, plain, 20px, in the tone colour mixed with a little ink, on the title line 10px before the title; the description lines up under the title text. Surface fill, 1px `line` border, radius 10px, no shadow. Head and footer on surface-2; footer actions right-aligned, a destructive action left. Never a panel inside a panel.

#### Stat and StatGrid, `@a31labs/rax/stat`
`Stat` takes `label`, `value`, `hint` (a short note beside the value in ink-2) and `icon` with `iconTone` (`accent` default | `accent-2` | `ok` | `warn` | `danger` | `neutral`): a 36px tile in the tone's soft fill, top right, and the label turns into a 600 title. `StatGrid` lays cells in a panel divided by `line`; with `separate` each stat is its own card with a 16px gap. Label 14px ink-2, value 24px 700 tabular.

#### KeyValueList, `@a31labs/rax/key-value-list`
Prop `items` (`{ key, value, mono }`). Keys in ink-2, values in ink; `mono` for code values.

#### EmptyState, `@a31labs/rax/empty-state`
Props: `title`, `description`, `action`. Title 700, one sentence in ink-2, optional primary action.

#### FilterBar, `@a31labs/rax/filter-bar`
Props: `query`, `onQueryChange`, `placeholder`, children (selects, a SegmentedControl). One row above a table, wrapping on small screens.

#### Pagination, `@a31labs/rax/pagination`
Props: `page` (0-based, like DataTable's `manual.page`; the label shows "Page 1 of 3" for page 0), `pageCount`, `onPageChange` (called with the 0-based target page). Used by DataTable's footer; usable on its own.

#### DataTable, `@a31labs/rax/data-table`
The only component that depends on `@tanstack/react-table` (v9); it is reachable only through this subpath.

Props: `rows`, `columns`, `getRowId`, `label` (accessible name), `state` (`ready` | `loading` | `error`), `error`, `onRetry`, `empty` (`{ title, description, action }`), `selectable` with `selected` and `onSelectedChange` (a `Set` of row ids), `globalFilter` and `filterFn`, `pageSize` (default 25), `columnRules` (default off), `density` (unset by default, so the table inherits the surrounding density), `manual`, `resizable`, `reorderable`, `storageKey`, `rowHref`, `onRowNavigate`, `toolbar` (a row inside the panel above the table, on the surface, for FilterBar and view controls), plus Panel props (`title`, `description`, `actions`).

A column is `{ id, header, cell, sortValue, numeric, subtitle, firstSort, hideable, defaultHidden }`. A `sortValue` makes the column sortable; `firstSort: "desc"` makes the first click sort descending (dates, counts); empty values (`null` or `undefined`) sort last in both directions and render `–` in `--rax-ink-3`. `numeric` right-aligns with tabular figures. `subtitle` (first column only) renders on the same line in ink-2 at 14px.

- Client-side by default: sorting, filtering and paging happen in the browser. The default filter searches columns that have a `sortValue`.
- `manual` hands sorting, paging and totals to the app for server-loaded data: `{ sort, onSortChange, page (0-based), pageCount, onPageChange, total }`. Filtering is then owned by the app, for example through FilterBar.
- Header row surface-2, 14px, weight 600, ink-2. Rows `--rax-row-h`, divided by `line`, hover surface-2, selected rows accent-soft with a 3px accent edge on the left. Sortable headers are buttons with `aria-sort` and a direction caret.
- Selection: a header checkbox selects every row matching the filter across pages (current page only in manual mode). The footer counts selected rows including filtered-out ones ("3 selected, 2 hidden by filter"). In manual mode it counts every id in `selected`, including rows on other server pages. Row checkbox names come from the first column's `sortValue`, falling back to the row id.
- Built-in states: loading (skeleton rows), empty (EmptyState), error (Alert with retry).
- Columns menu: when any column is `hideable`, a columns icon button (named "Columns") at the end of the header row lists those columns as checkboxes, plus "Reset columns" once the layout differs from the defaults. `defaultHidden` columns start hidden. The first column can never be hidden. Hidden columns still take part in filtering and keep their sort.
- `resizable`: each header gets a resize handle on its right edge (a focusable separator; arrow keys change the width by 16px). Widths stay automatic until the first resize, then every shown column gets a fixed width (64 to 800px, cells truncate with an ellipsis) and a filler column takes the rest. Double-click a handle to go back to automatic widths.
- `reorderable`: the Columns menu (shown even without hideable columns) becomes a SortableList of every column but the first, each with a grip ("Reorder X") and, for hideable columns, its checkbox. Drag a grip, or use Arrow Up, Arrow Down, Home and End on it. The first column always stays first. Columns missing from a stored order (added later) go to the end.
- `storageKey` persists widths, visibility and order in localStorage under `rax-table:<storageKey>`, shared between tabs. The server render uses the defaults, so hydration matches; the stored layout applies right after mount. Blocked storage falls back to memory.
- `rowHref` makes whole rows links: the first cell holds a real link (keyboard and screen readers), a click anywhere else in the row follows it, and Ctrl, ⌘, Shift or the middle button open a new tab. Clicks on controls inside the row (checkboxes, buttons, links) and text selection never navigate. `onRowNavigate(href, row)` plugs in client-side routing; the default is `location.assign`. Do not put links in the first column's cell when using `rowHref`. Only http(s) and relative URLs are followed; anything else (`javascript:`, `data:`) leaves the row unlinked.
- Scrolls horizontally inside its panel on narrow screens; the page never scrolls sideways.

#### Card and CardGrid, `@a31labs/rax/card`
Props: `title`, `description`, `media` (16/9, object-fit cover), `meta` (a row of badges or text), `actions`, `href`, `renderLink` (plug in a router link). An item in a collection; Panel stays for sectioned app regions. Surface, 1px `line` border, radius 10px, no shadow. Title (an `h3`) clamps to 2 lines and the description to 3. With `href` the title link stretches over the whole card, `actions` stay clickable above it, the hover outline is ink-3 and the focus ring goes around the card. `CardGrid` is auto-fill minmax(260px, 1fr) with a 16px gap.

#### BarList, `@a31labs/rax/bar-list`
Props: `items` (`{ label, value, href, attrs }`), `format` (number to string, default `toLocaleString`), `showShare` (adds the share of the total), `limit` (shows the first N with a "Show all N" / "Show less" button with `aria-expanded`), `label` (accessible name). A `<ul>` of rows, each with an accent-soft bar behind it sized relative to the largest value, the label on the left truncated with an ellipsis, and the value right-aligned with tabular figures. Rows with `href` are links, underlined on hover with an inset focus ring. The no-dependency chart for "top N" breakdowns.

#### Steps, `@a31labs/rax/steps`
Props: `items` (`{ label, description, status: "done" | "current" | "todo" }`), `orientation` (`horizontal` default | `vertical`), plus native `ol` props. Markers are 24px circles: done is an accent fill with a check, current a 2px accent outline with its number, todo an `edge` outline with its number. Connectors are `line`, accent after a done step. The current step has `aria-current="step"` and weight 600; status is also spoken as hidden text ("completed", "current"). Horizontal stacks vertically below 481px.

#### Timeline, `@a31labs/rax/timeline`
Props: `items` (`{ id, title, time, description, icon, tone: "neutral" | "accent" | "accent-2" | "ok" | "warn" | "danger" }`), plus native `ol` props. A vertical list with a 1px `line` rail and a 24px marker column: a dot (line-strong, accent or accent-2), a status glyph for ok, warn and danger (the badge glyphs, so the shape carries the status), or a custom icon in a ringed circle. Title 500 with the time right-aligned in ink-2 at 14px, wrapping under the title when space runs out; description ink-2 at 14px.

#### FileDrop, `@a31labs/rax/file-drop`
Props: `onFiles(File[])`, `accept`, `multiple`, `maxSize` (bytes), `disabled`, `label`, `hint`, children (custom preview), plus native div props. A dashed `edge` border that turns to an accent border on accent-soft while a file is dragged over. A native button inside opens the hidden file picker on click, Enter or Space, and its focus ring shows on the whole zone. Dropped files are checked against `accept` too. Files that fail `accept` or `maxSize` are rejected with an inline error (`role="alert"`) naming each file. The input is reset after every pick, so the same file can be chosen again. No upload logic: the app uploads in `onFiles`.

#### SelectionBar, `@a31labs/rax/selection-bar`
Props: `count`, `onClear`, children (action buttons), `label` (noun, default "selected"), `sticky`. Bulk-action bar for selected list items: "N selected" (aria-live polite), the actions, and a ghost "Clear selection" button pushed right. Surface-2 fill, `line` border, radius 10px, wraps. Renders nothing when `count` is 0. `sticky` pins it to the bottom of the scroll container.

#### SortableList, `@a31labs/rax/sortable-list`
Props: `items`, `getId`, `renderItem`, `onReorder` (called with the new array), `label` (list name), `itemLabel` (used in announcements). Drag-to-reorder with no dependencies. Each row has a grip IconButton ("Reorder X"), and only a held grip makes the row draggable, so row text stays selectable. On the focused grip, Arrow Up and Arrow Down move the row by one and Home and End move it to the top or bottom; focus stays on the grip. Moves are announced in a hidden live region ("Moved X to position 3 of 5"). While dragging, the drop target shows a 2px accent line and the dragged row is dimmed.

### Charts

#### Chart, `@a31labs/rax/chart`
A thin layer over plain Recharts (`recharts` ^3, an optional peer dependency: install it only in apps that chart). Apps keep writing `AreaChart`, `Bar`, `XAxis` and so on; Rax sizes, colours and styles them. The root `@a31labs/rax` entry never imports Recharts.

- `ChartContainer`: props `config`, `label` (required; the root is `role="figure"` with `aria-label`), `height` (px, default 240), one Recharts chart as the child, plus native div props. Wraps the chart in a `ResponsiveContainer` at full width. Grid lines are `line`, axis lines and tick lines are hidden, tick labels are ink-3 at 14px with tabular figures, the hover cursor is `line-strong` (a surface-3 band on bars), the active dot has a surface ring, and the focused chart (Recharts' keyboard layer) shows the focus ring. Empty `data` keeps the height. On the server it renders the empty container at its height (the width is unknown there), and the chart draws after mount, so the layout does not jump. Give every chart a text alternative nearby too: a summary sentence or a table.
- `ChartConfig`: `Record<seriesKey, { label, color? }>`. `color` is `"accent" | "accent-2" | "ok" | "warn" | "danger" | "neutral"`, a slot number `1`–`6`, or any CSS colour. If exactly one series has no colour, it takes the accent, so single-series charts carry the app's brand. Otherwise series without a colour take slots 1, 2, 3, … in config order; a seventh uncoloured series gets `neutral` (`edge`), never a repeated slot. Each key becomes `--rax-series-<key>` on the container (characters outside `[a-zA-Z0-9_-]` turn into `-`), a separate namespace from the slot tokens. Use `chartVar(key)` for marks: `<Area dataKey="requests" fill={chartVar("requests")} />`. With a pale accent (under 3:1 on the surface, such as a light yellow), colour a single series with a slot: `color: 1`.
- `ChartTooltip` (Recharts `Tooltip` with `ChartTooltipContent`) and `ChartTooltipContent` (`formatter(value, key)`, `hideLabel`): a surface panel with a `line-strong` border, radius 6px and the float shadow; the label, then one row per series with a 10px colour key, the config label in ink-2 and the value right-aligned in tabular figures. Text is always ink, never the series colour. A series missing from the config shows its raw key with a neutral key. Missing values show "–"; range values (`[low, high]`) show "low–high".
- `ChartLegend` and `ChartLegendContent`: a centred, wrapping row of 10px keys and config labels in ink-2.
- `useChartConfig()` returns the config, for custom tooltip or legend content. Passing `content` to `ChartTooltip` or `ChartLegend` replaces the config-aware content entirely; that is intended for custom content, which can read the config through this hook.

Mark props Recharts only takes as props: 2px lines `strokeWidth={2}` (Recharts defaults to 1; Rax does not force it in CSS, so an explicit width always wins), rounded bar ends `radius={[4, 4, 0, 0]}` (horizontal bars `[0, 4, 4, 0]`), and a 2px surface gap between adjacent fills (stacked bars, pie and radial segments) `stroke="var(--rax-surface)" strokeWidth={2}`. No dual-axis charts: two measures on different scales are two charts.

What Rax's CSS sets on Recharts parts (all under `.rax-chart`): tick label `fill` and `font-size` (ink-3, small, tabular figures), grid line `stroke` (`line`), axis lines and tick lines hidden, tooltip cursor `stroke` (`line-strong`) and `fill` (surface-3 on bars and sectors), active-dot `stroke` (surface), and the focus outline on the chart surface. These are CSS rules, so a rule with higher specificity (for example `.my-chart .rax-chart .recharts-cartesian-axis-line { display: block }`) wins, and a chart that must look different can sit in a wrapper without `.rax-chart`.

Every built file starts with `"use client"`. In apps with server components, write charts in a client component: functions such as `chartVar` cannot be called from a server component, and Recharts itself needs the browser to measure and draw.

Config keys that differ only in characters outside `[a-zA-Z0-9_-]` map to the same variable (`a.b` and `a b` are both `a-b`); keep keys distinct.

Categorical palette, `--rax-chart-1` … `--rax-chart-6`: fixed hues, independent of the accent, in fixed order, never cycled. Lightness alternates so neighbours stay apart without colour vision.

| Slot | Light | Dark |
|---|---|---|
| 1 | oklch(0.50 0.21 260) | oklch(0.56 0.20 260) |
| 2 | oklch(0.60 0.22 0) | oklch(0.55 0.22 0) |
| 3 | oklch(0.50 0.14 150) | oklch(0.67 0.18 150) |
| 4 | oklch(0.62 0.20 300) | oklch(0.66 0.18 300) |
| 5 | oklch(0.66 0.18 55) | oklch(0.58 0.16 60) |
| 6 | oklch(0.60 0.13 215) | oklch(0.66 0.13 215) |

In both modes every slot clears 3:1 on the surface, adjacent slots are at least 21 apart (OKLab ΔE ×100) and at least 11 apart under simulated protanopia and deuteranopia. Apps can override `--rax-chart-1` … `--rax-chart-6` in their own mode scopes; keep the order rules and re-check contrast when they do. Tailwind gets them as `chart-1` … `chart-6`. Status colours are not categorical slots: use `ok`, `warn` and `danger` only when the series means that status. With more than six series, fold the rest into "Other".

### Date and time

#### DatePicker, DateRangePicker, TimeInput, DateTimePicker, `@a31labs/rax/date-picker`
Built on `react-day-picker` (^10, an optional peer dependency: install it only in apps that pick dates). The root `@a31labs/rax` entry never imports it.

Values are plain strings or instants, never ambiguous Dates:
- `DatePicker`: `value: string | null` as `YYYY-MM-DD`, a plain date with no time and no zone. It renders and emits the same day in every time zone.
- `DateRangePicker`: `value: { from: string; to: string } | null` of plain dates. Two months side by side (one below 640px, or set `months`), the first click starts a range and the second completes it (a second click before the first swaps them). `presets` (`{ label, range(today) }[]`, default `DEFAULT_PRESETS`: Today, Last 7 days, Last 30 days, This month, Last month) sit in a list beside the calendar, clamped to `min`/`max` (a preset entirely outside them is disabled); `[]` hides it. `name` posts `<name>_from` and `<name>_to`.
- `TimeInput`: `value: string | null` as `HH:mm` (24h), a native time field with Input's look; native input props go to the input.
- `DateTimePicker`: `value: Date | null`, an instant. Picked and shown as wall-clock time in `timeZone` (IANA name, default the viewer's), with the calendar and a time field in the popover. `name` posts the instant as an ISO string (UTC). A skipped time on a spring-forward day moves forward past the gap (02:30 becomes 03:30); a repeated time on a fall-back day takes the earlier instant, for 30-minute, 1-hour and 2-hour shifts alike.

Shared props: `min`, `max` (plain dates; days outside are disabled and navigation stops there; an invalid value, or `min` after `max`, is ignored), `disabled`, `readOnly` (does not open and does not block submit), `required` (blocks form submit when empty and hides clear), `name`, `form`, `placeholder`, `locale` (BCP 47, default the browser's; captions, weekdays, day labels and the trigger are formatted with `Intl.DateTimeFormat`), `weekStartsOn` (default from the locale), `clearable` (default true), `today` (a plain date, for demos and tests), `defaultOpen`, `container`, `labels` (`clear`, `popup`, `presets`, `time`, `nav`: the copy that is not a date; preset names come from `presets`, the empty text from `placeholder`), plus native button props for the trigger (`ref`, `id`, `aria-*`, `onBlur`), so it works inside Field. `className` goes to the wrapper. Invalid incoming values render as empty.

The trigger is a button with Input's height, edge, radius and focus ring, a calendar icon and the formatted value (`dateStyle: "medium"`, a range as `1–7 Mar 2026`); typing a date is not supported. The clear button sits inside the trigger's edge but outside the trigger button. The calendar opens in the floating layer above dialogs; Escape closes it first and focus returns to the trigger. Opened by the user, it moves focus to the selected day (or today); open from the first render (`defaultOpen`), it leaves focus where it is. Day cells are 40px (44px on coarse pointers); today is bold and underlined, the selected day is accent with accent-ink, a range middle is accent-soft, disabled days are ink-3 with no hover. The library's stylesheet is not used; its parts are renamed `rax-cal-*`. Month navigation ("Next month (April 2026)") and "Today" come from `Intl.RelativeTimeFormat` for the locale; selection is announced through `aria-selected`. On the server and during hydration the trigger shows the raw value (`2026-03-01`) and formats it after mount, because the default locale and zone differ between server and browser; pass `locale` (and `timeZone` for DateTimePicker) to format on the server too. `parsePlainDate` and `formatPlainDate` convert between `YYYY-MM-DD` and local-midnight Dates.

## Interaction rules

- Never colour alone: status pairs colour with a glyph and a word; errors pair with a glyph and text; selection pairs with a checkbox or an edge.
- Targets are at least 24px; default controls 40px; 44px on coarse pointers.
- Layout reflows down to 320px width without two-way scrolling.
- Decorative SVGs carry `aria-hidden`.
- Validate on blur, then live while the user fixes the value.
- Dialogs only for irreversible or blocking decisions; everything else is inline or a toast.
- One primary button per view region.

## Migrating an existing app

1. Install the package and import `@a31labs/rax/styles.css` (and optionally `tailwind.css`) as described in Setup.
2. Set your accent inputs on `:root` (hue, chroma, lightness, ink lightness) and check contrast.
3. Choose how modes are switched: set `data-mode` on `<html>`, or keep an existing `.dark` class, which Rax also honours.
4. Apps with shadcn-style variables (`--background`, `--primary`, `--border`, ...): delete the app's own variable blocks (the `:root { --background: ... }` and `.dark { ... }` rules), then add `@import "@a31labs/rax/compat/shadcn.css";` with the other imports at the top of the stylesheet (an `@import` cannot come after rules). It points those variable names at Rax roles, so existing components pick up the new look without edits.
5. Apps with hand-written components: skip the compat file and replace local components with Rax ones page by page, starting with Button, Field and Input, then tables and overlays. Remove the old CSS as each one goes.
6. Review each migrated page in light and dark.

## Versioning

Rax follows semver, managed with changesets.

- Patch: visual polish that keeps the API.
- Minor: new components, options or tokens.
- Major: renamed or removed tokens, classes or props.

Every component change is reviewed on its docs page in light and dark before release, and releases are published from CI through npm trusted publishing.

Page: https://rax.a31.at/foundations/rules
