@rickycourtes/designrail 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,891 @@
1
- # Temporary Holding Version
1
+ # designrail
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The design foundation for any web project. Every project installs it and
4
+ builds on top of it, and one update to designrail reaches all of them.
5
+
6
+ designrail has two halves:
7
+
8
+ - **The foundation**: a set of token names (the contract), a default theme,
9
+ and a kit of parts (button, field, card, pill, dropdown, toast, sheet) that
10
+ every project imports. Each project brings only its theme (its own values for
11
+ those token names) and the parts no other project has. Each part has knobs
12
+ (custom properties) for restyling it without editing it, and sits in a CSS
13
+ cascade layer, so a project's own CSS always wins.
14
+ - **The tooling**: reads a codebase's CSS, SCSS, Less, HTML, JSX/TSX, Vue,
15
+ Svelte and Astro, then
16
+ - finds the colours, spacing and parts the code repeats
17
+ - turns them into a theme for the foundation
18
+ - rewrites hardcoded values to tokens
19
+ - keeps drift out with a git-aware check
20
+ - moves a project to a new foundation version with `upgrade`
21
+
22
+ It needs only Node 20 and has no dependencies. It scans a 300-file app in about
23
+ 100 ms, or about 10 ms from its cache.
24
+
25
+ - [Quick start](#quick-start)
26
+ - [Building on the foundation](#building-on-the-foundation)
27
+ - [Concepts](#concepts)
28
+ - [Commands](#commands)
29
+ - [The token contract](#the-token-contract)
30
+ - [The kit](#the-kit)
31
+ - [Design rules](#design-rules)
32
+ - [Configuration](#configuration)
33
+ - [What it reads](#what-it-reads)
34
+ - [CI and git hooks](#ci-and-git-hooks)
35
+ - [Coding agents](#coding-agents)
36
+ - [Library API](#library-api)
37
+ - [Performance](#performance)
38
+ - [Limits](#limits)
39
+ - [Developing designrail](#developing-designrail)
40
+
41
+ ## Quick start
42
+
43
+ ```bash
44
+ npm i -D @rickycourtes/designrail # the foundation and the tools
45
+ npx designrail init # config (records the foundation version) + DESIGN.md
46
+ npx designrail audit # health score and what to fix first
47
+ npx designrail extract # your theme, from the values already in use
48
+ npx designrail fix --write # hardcoded values → tokens
49
+ npx designrail check --install-hook # no new drift from here on
50
+ npx designrail specimens # a page with every token and part
51
+ ```
52
+
53
+ On a project that already has token files, skip `extract`. `fix` and `check`
54
+ use the tokens that are already there, plus the foundation's.
55
+
56
+ ### Installing
57
+
58
+ designrail is published publicly on npm as `@rickycourtes/designrail`, so it
59
+ installs like any other package: no `.npmrc` or token needed.
60
+
61
+ `npm i -D @rickycourtes/designrail` saves a `^0.2.0` range. While the version
62
+ is 0.x, a caret range takes patch releases (0.2.x) automatically through
63
+ `npm update`. A minor release (0.3.0) may rename things, so you move to it on
64
+ purpose and run `designrail upgrade`.
65
+
66
+ ## Building on the foundation
67
+
68
+ Load the foundation first, then your theme, then your own parts:
69
+
70
+ ```css
71
+ /* app.css */
72
+ @import '@rickycourtes/designrail/foundation.css'; /* default theme, base, every part (layered) */
73
+ @import './tokens/primitives.css'; /* your raw values */
74
+ @import './tokens/semantic.css'; /* the contract pointed at them: your look */
75
+ @import './ui/index.css'; /* your own parts and variants */
76
+ ```
77
+
78
+ ```js
79
+ import { dropdowns, toast } from '@rickycourtes/designrail/foundation.js';
80
+ dropdowns();
81
+ ```
82
+
83
+ How the layers work:
84
+
85
+ - **Layers**: the foundation lives in three cascade layers,
86
+ `designrail.tokens`, `designrail.base` and `designrail.parts`. Anything a
87
+ project writes outside a layer wins over them, whatever its specificity, so
88
+ `:root { --accent: … }` in your theme always beats the default.
89
+ - **Themes**: setting the core tokens (`--surface`, `--text`, `--accent`,
90
+ `--text-on-accent`, `--font-ui`) is enough to take over the look. Every other
91
+ colour (fills, borders, muted text, hover, raised and sunken surfaces) is
92
+ derived from those core tokens, so it follows any theme. Set any of them
93
+ yourself to go further.
94
+ - **Variants, not edits**: restyle a part through its knobs, on a class of
95
+ your own:
96
+
97
+ ```css
98
+ .btn.ink { --btn-bg: var(--text); --btn-fg: var(--surface); }
99
+ ```
100
+
101
+ Never `.btn { background: … }` where it is used: that freezes the part
102
+ against foundation updates. `check` reports it as `part-restyle`. Layout
103
+ where a part is used (margin, grid placement, width) is fine.
104
+ - **Ejecting**: when a project truly needs its own version of a part,
105
+ `designrail eject <part>` copies it in. That part then stops following the
106
+ foundation, and `upgrade` names it whenever the foundation's copy has moved
107
+ on.
108
+ - **Updating**: `npm outdated` shows when a project is behind. Bump with
109
+ `npm i -D @rickycourtes/designrail@^0.3.0` (Dependabot can open that PR in
110
+ each repo), then run `designrail upgrade`. It
111
+ lists what changed in each version between the one you were on and the one
112
+ installed (from `kit/changes.json`). With `--write` it rewrites renamed tokens
113
+ and classes across the project and records the new version in
114
+ `designrail.config.json`. Run `designrail check` after.
115
+
116
+ ## Concepts
117
+
118
+ **Primitives** are raw values, named for what they *are*: `--blue-500: #3b82f6`
119
+ or `--space-12: 12px`. Only token files read them. The exception is the
120
+ `--space-*`, `--radius-*` and `--font-size-*` steps, because a step on a scale
121
+ says all a gap needs.
122
+
123
+ **Semantic tokens** say what a value is *for*: `--surface: var(--white)` or
124
+ `--accent: var(--blue-500)`. Parts and pages read these. A theme (for example
125
+ dark mode) re-points the semantic layer and leaves every part alone.
126
+
127
+ **The contract** is the set of semantic names that `extract` produces and that
128
+ every kit part reads. A project that defines them can take any kit part as is.
129
+ See [The token contract](#the-token-contract).
130
+
131
+ **Parts** are reusable components: a button, a field, a card. The core rule is
132
+ *use the part we have; never draw it again*. `audit` finds the places a part was
133
+ drawn twice, and the foundation gives you one version to replace them with.
134
+
135
+ **The foundation** is the default theme plus the kit's parts, installed as a
136
+ package and layered underneath the project. **Knobs** are the custom properties
137
+ a part exposes (`--btn-bg`, `--card-pad`), so a project restyles it without
138
+ editing it.
139
+
140
+ **Drift** is anything that moves away from the system: a hardcoded colour, a
141
+ `var()` that resolves nowhere, a copy-pasted rule block. `check` reports it.
142
+ With git it reports only the drift a change *adds*.
143
+
144
+ ## Commands
145
+
146
+ ```
147
+ designrail <command> [dir] [flags]
148
+ ```
149
+
150
+ `dir` defaults to the current folder. For `trace` and `eject`, which take other
151
+ arguments, pass the folder with `-C dir`.
152
+
153
+ Every command takes these flags:
154
+
155
+ | Flag | Effect |
156
+ | --- | --- |
157
+ | `--json` | One line of JSON instead of text. |
158
+ | `--no-cache` | Reparse every file; read and write no cache. |
159
+ | `--all` | Every hit or item, not the first few. |
160
+ | `--help` | Usage. |
161
+
162
+ An unknown flag exits with code 2 and an error, rather than being guessed at.
163
+
164
+ ### `init [dir] [--agents] [--force]`
165
+
166
+ Writes `designrail.config.json` and `DESIGN.md`, the project's design rules
167
+ (see [Design rules](#design-rules)). If the project already has token files
168
+ (stylesheets that are mostly custom properties on `:root`), `init` finds them
169
+ and points `tokens` at them. `parts` is set to `src/ui` when there is a `src/`
170
+ folder, else `ui`. When the foundation is installed (or `package.json`
171
+ depends on `designrail`), `init` records its version as `foundation` and
172
+ prints the import lines.
173
+
174
+ - `--agents` adds a short "Design system (designrail)" section to `CLAUDE.md`
175
+ or `AGENTS.md` (whichever exists, else a new `CLAUDE.md`). See
176
+ [Coding agents](#coding-agents).
177
+ - `--force` rewrites files that already exist.
178
+
179
+ ### `audit [dir] [--html file] [--limit n]`
180
+
181
+ A 0–100 health score in five parts:
182
+
183
+ | Part | Points | Measures |
184
+ | --- | --- | --- |
185
+ | tokens | 40 | Design declarations (colour, spacing, radius, font size, family, shadow) that read a token instead of a literal. |
186
+ | colors | 15 | Distinct colours, and how many are near-identical (closer than `colorTolerance`). |
187
+ | scale | 15 | Spacing and radius values off the `grid`, per use. |
188
+ | duplication | 15 | Rules in identical groups, plus near-duplicate pairs. |
189
+ | reuse | 15 | Parts drawn as several class families, plus markup copied across files. |
190
+
191
+ Then the details:
192
+
193
+ - **Colours**: groups of near-identical colours (for example `#3b82f6`, `#3b83f6`
194
+ and `#3a82f7`), each of which could be one token.
195
+ - **Scales**: every spacing, radius and font-size value with its count, and
196
+ the spacing and radius values that sit off the grid, with file:line.
197
+ - **Families, weights, shadows, durations, z-index**: every distinct value.
198
+ - **Duplicate rule blocks**: selectors whose declarations are identical (`.card
199
+ ≡ .panel`), and pairs that share most of them (60%+), with what differs.
200
+ Near-identical colours count as equal here. Show/hide state rules
201
+ (`display`, `opacity`, `pointer-events`…) are left out.
202
+ - **Parts drawn more than one way**: class names grouped by role (button,
203
+ field, card, pill, dialog, toast, dropdown) and by family. For example,
204
+ `.btn`/`.btn-secondary` are one family while `.submit-button` and `.cta`
205
+ are others, so the report suggests one part with variants.
206
+ - **Repeated markup**: the same element structure (tags and classes) copied
207
+ in more than one place, and the same structure repeated with different
208
+ classes. Sibling repeats in a list are left out (render those from data).
209
+
210
+ `--html file` writes a self-contained report page to share. `--limit n` sets
211
+ how many items each section shows (default 6).
212
+
213
+ ### `scan [dir]`
214
+
215
+ What was read and how fast: file count by type, how many came from cache,
216
+ the token files found, how many design values read a token, and how many
217
+ literals sit outside token files.
218
+
219
+ ### `extract [dir] [--dry] [--force] [--out dir]`
220
+
221
+ Builds a token system from the values the project already uses. It writes
222
+ three files to the folder of the first `tokens` entry (`tokens/` by default):
223
+
224
+ - `primitives.css`
225
+ - **Colours**: near-identical ones merge (the most used one is kept), then
226
+ each is named by hue family and lightness step: `--gray-200`, `--blue-500`,
227
+ `--red-100`, `--white`, `--black-a20` for a colour with alpha. A pale tint
228
+ is named for its hue, never as a grey.
229
+ - **Spacing and radius**: values within `snap` px merge onto the grid
230
+ (`--space-12` merges 11px and 13px). An off-grid value used only once is
231
+ left as a value to snap, not made a step. `--radius-full` covers anything
232
+ at 500px and up.
233
+ - **Font sizes, families, weights, shadows, durations**: named for their
234
+ value (`--font-size-15`, `--font-inter`, `--weight-600`, `--shadow-1`,
235
+ `--duration-150`).
236
+ - Every token carries a comment with its use count and what it merged.
237
+ - `semantic.css`: the [contract](#the-token-contract), inferred from where
238
+ each value is used:
239
+ - `--surface` is the `body`/`html` background, else the most used neutral
240
+ background.
241
+ - `--text` is the `body` text colour, else the most used one that reads
242
+ on the page.
243
+ - `--text-on-accent` is what the project sets on accent backgrounds.
244
+ - `--accent` is the most used colour that is not grey, red or green;
245
+ `--danger`, `--success` and `--warning` are the most used red, green and
246
+ amber.
247
+ - `--radius-control` and `--radius-card` are the most used radius on
248
+ button/field and card/dialog rules.
249
+ - `--font-size-body` is the `body` size; `--font-display` is the family
250
+ the headings use.
251
+ - What the project never says is derived from the contract and marked
252
+ `/* derived */`.
253
+ - `tokens.json`: the same tokens as W3C Design Tokens (DTCG) JSON, for Figma
254
+ plugins and Style Dictionary. Semantic tokens are written as references
255
+ (`{primitive.blue-500}`).
256
+
257
+ If the project already has token files, `extract` stops and says so.
258
+ `--out dir` writes a fresh set elsewhere, and `--force` overwrites. `--dry`
259
+ prints the files instead of writing them.
260
+
261
+ Import `primitives.css`, then `semantic.css`, before your own styles. The
262
+ files are yours: edit names and values freely. `fix` and `check` read
263
+ whatever is there.
264
+
265
+ ### `fix [dir] [--write] [--snap] [--limit n]`
266
+
267
+ Rewrites hardcoded values as the tokens that hold them. It shows a diff
268
+ (`file`, line, `old → new`) unless you pass `--write`.
269
+
270
+ - **Colours** match within `colorTolerance`. When several tokens match, the
271
+ pick goes:
272
+ 1. an exact match before a near one
273
+ 2. a semantic token whose job matches the property (a `background` gets
274
+ `--surface`, a `color` gets `--text`, a `border` gets `--border`)
275
+ 3. a semantic token with no particular job (`--accent`)
276
+ 4. a primitive
277
+
278
+ A semantic token whose job is a different property is never used, so
279
+ `#1a1a1a` as a background never becomes `--text`.
280
+ - **Spacing, radius, font size**: an exact pixel match within the same scale
281
+ (rem converts at 16px; em is skipped). With `--snap`, anything within
282
+ `snap` px of a step also matches, and the diff marks it `snapped`. A
283
+ negative margin becomes `calc(var(--space-8) * -1)`.
284
+ - **Families, shadows, durations**: an exact match.
285
+ - **Where it writes**: CSS/SCSS/Less, `<style>` blocks, `style=""`
286
+ attributes, styled-components and `css`` ` templates, JSX style objects (a
287
+ number like `padding: 12` becomes `padding: 'var(--space-12)'`), and
288
+ Tailwind arbitrary values (`p-[12px]` becomes `p-[var(--space-12)]`).
289
+
290
+ At the end it lists, by kind, the values no token holds. Add those to your
291
+ token files, or regenerate with `extract --out`.
292
+
293
+ ### `check [dir] [--staged | --base REF] [--install-hook]`
294
+
295
+ The drift gate. It exits 1 if any rule set to `error` has a hit.
296
+
297
+ | Rule | Hit | Default |
298
+ | --- | --- | --- |
299
+ | `hardcoded` | A colour, spacing, radius, font size, family or shadow typed by hand outside token files. Shows the token that holds it, if one does. | error |
300
+ | `unresolved` | A `var(--x)` with `--x` defined nowhere and not set from JS. | error |
301
+ | `primitive-direct` | A primitive read outside token files when a semantic layer exists (except `allowPrimitives` and contract names). | warn |
302
+ | `duplicate-block` | A rule block identical to another one. | error |
303
+ | `unused` | A token nobody reads (contract names are exempt: they are the parts' API). | warn |
304
+ | `tracked-caps` | `text-transform: uppercase` with letter-spacing. | warn |
305
+ | `contract` | With the foundation installed: a core token (`--surface`, `--text`, `--accent`, `--text-on-accent`, `--font-ui`) the project never sets, so it shows the foundation's default. | warn |
306
+ | `part-restyle` | With the foundation installed: a rule that restyles a foundation part where it is used (`.card { background: … }`) instead of setting its knobs on a variant. Layout properties (margin, grid placement, width, position, display…) are allowed. Ejected parts are exempt. | warn |
307
+
308
+ With the foundation installed, its tokens count as defined (a project's
309
+ `var(--fill)` resolves), its parts' reads count as reads, and nothing inside
310
+ it is ever reported. `var(--x, fallback)` never counts as unresolved.
311
+
312
+ - **No flag**: every hit in the project.
313
+ - **`--staged`**: compares the git index with `HEAD` and reports only the hits
314
+ the staged change adds. This is what the pre-commit hook runs.
315
+ - **`--base REF`**: compares the working tree (untracked files included)
316
+ with `REF`. Use it in CI against the target branch.
317
+
318
+ Hits are counted per key, so one more use of a value that already drifted
319
+ still counts as new. Unchanged files are shared between both sides, so
320
+ diff mode costs little more than a plain check. `--install-hook` appends
321
+ `npx --no-install designrail check --staged || exit 1` to
322
+ `.git/hooks/pre-commit`.
323
+
324
+ ### `trace <selector | --token> [-C dir]`
325
+
326
+ - **`trace .btn.primary`**: every rule whose selector ends with that query
327
+ (`:hover` and other states included), and each `var()` followed down its
328
+ chain with file:line at each step:
329
+
330
+ ```
331
+ .btn.primary src/ui/button.css:86
332
+ --btn-bg: var(--accent)
333
+ --accent src/tokens/semantic.css:130 → --marigold-400 = #ffb23e src/tokens/primitives.css:39
334
+ ```
335
+
336
+ - **`trace --accent`**: what the token is built on (down to the literal), the
337
+ tokens built on it, and every place it is read, directly or through them.
338
+ Use it before changing a token, to see everything the change reaches.
339
+
340
+ ### `specimens [dir] [--out file]`
341
+
342
+ Writes one static page (default `.designrail/specimens.html`) showing:
343
+
344
+ - **Tokens**: semantic and primitive colours as swatches, spacing as bars,
345
+ radii, type sizes, families and shadows.
346
+ - **Parts**: every foundation part, rendered in the project's own tokens on top
347
+ of the foundation's (layered, as in the app). Parts are marked
348
+ *foundation*, *ejected* (the project's own copy) or, with no foundation
349
+ installed, *kit*.
350
+
351
+ A light/dark toggle appears when the token files define a dark theme. With
352
+ no token files of its own, the project is shown in the foundation's default
353
+ theme.
354
+
355
+ ### `upgrade [dir] [--write]`
356
+
357
+ Moves the project from the foundation version it is on (`foundation` in
358
+ `designrail.config.json`, written by `init`) to the one installed in
359
+ `node_modules/@rickycourtes/designrail`. It prints:
360
+
361
+ - each version in between, with its notes
362
+ - **Renamed** tokens and classes: chained across versions, so `--a → --b`
363
+ then `--b → --c` becomes `--a → --c`. `--write` rewrites them across the
364
+ project: `var()`s, selectors, and `class`/`className` values.
365
+ - **New** parts, tokens and classes.
366
+ - **Removed but still read**: tokens the foundation dropped that the project
367
+ still uses. Fix these by hand.
368
+ - **Ejected parts that no longer match** the foundation's copy, to diff by
369
+ hand.
370
+
371
+ `--write` also records the new version. Run `designrail check` afterwards.
372
+ Every foundation release adds an entry to `kit/changes.json`:
373
+
374
+ ```json
375
+ { "version": "0.3.0", "notes": "…", "renamed": { "--fill": "--fill-rest" },
376
+ "added": { "tokens": [], "parts": [], "classes": [] }, "removed": { "tokens": [], "parts": [] } }
377
+ ```
378
+
379
+ ### `eject <part…> [-C dir] [--force] [--dry]`
380
+
381
+ Copies a foundation part (from the installed version) into the project's
382
+ `parts` folder, for the project to own. The part is recorded under `ejected`
383
+ in the config. From then on it no longer follows foundation updates, and
384
+ `part-restyle` stops checking it. Import the copy after
385
+ `@rickycourtes/designrail/foundation.css`; it stays in the `designrail.parts` layer, so it
386
+ replaces the foundation's version and your own CSS still wins over it.
387
+
388
+ An existing file is kept unless you pass `--force`. `--dry` shows what would
389
+ happen without writing anything.
390
+
391
+ Without a foundation installed, `eject` works as a plain copy: every token
392
+ the part reads that the project lacks is added to its semantic token file.
393
+ Each one is derived from tokens the project already has where the contract
394
+ allows (`--fill` is a mix of `--text`), along with anything those derivations
395
+ need. (`add` was the old name for this command.)
396
+
397
+ ### `kit`
398
+
399
+ Lists the foundation's parts and what each is for.
400
+
401
+ ## The token contract
402
+
403
+ The semantic names `extract` writes and every kit part reads. A project that
404
+ defines them can adopt any part. The *Derived as* column is the default when
405
+ the project has no value of its own.
406
+
407
+ | Token | Group | For | Derived as |
408
+ | --- | --- | --- | --- |
409
+ | `--surface` | colour | The page and the plainest box. | from the project |
410
+ | `--surface-raised` | colour | A card, menu or sheet over the page. | `var(--surface)` |
411
+ | `--surface-sunken` | colour | A well: code, a tray, an inset field. | `color-mix(in oklab, var(--surface), var(--text) 4%)` |
412
+ | `--surface-scrim` | colour | Dims the page behind a dialog. | `color-mix(in srgb, #000 45%, transparent)` |
413
+ | `--fill` | colour | A control at rest: one shade off what it sits on. | `color-mix(in srgb, var(--text) 6%, transparent)` |
414
+ | `--fill-hover` | colour | The next shade, under the pointer. | `color-mix(in srgb, var(--text) 10%, transparent)` |
415
+ | `--fill-press` | colour | Pressed or selected. | `color-mix(in srgb, var(--text) 14%, transparent)` |
416
+ | `--text` | colour | Body text. | from the project |
417
+ | `--text-muted` | colour | Secondary text: hints, meta. | `color-mix(in oklab, var(--text) 70%, var(--surface))` |
418
+ | `--text-faint` | colour | Placeholders and disabled. | `color-mix(in oklab, var(--text) 45%, var(--surface))` |
419
+ | `--text-on-accent` | colour | Text on an accent fill. | from the project |
420
+ | `--border` | colour | A quiet rim or divider. | `color-mix(in oklab, var(--text) 13%, var(--surface))` |
421
+ | `--border-strong` | colour | A field rim, a rim that must read. | `color-mix(in oklab, var(--text) 25%, var(--surface))` |
422
+ | `--accent` | colour | The one accent: go, selected, primary. | from the project |
423
+ | `--accent-hover` | colour | The accent under the pointer. | `color-mix(in oklab, var(--accent), var(--text) 14%)` |
424
+ | `--danger` | colour | Something went wrong or will be lost. | `#dc2626` |
425
+ | `--success` | colour | Something worked. | `#16a34a` |
426
+ | `--warning` | colour | Careful. | `#d97706` |
427
+ | `--focus` | colour | The keyboard focus ring. | `var(--accent)` |
428
+ | `--font-ui` | type | Every label and paragraph. | `system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif` |
429
+ | `--font-display` | type | Headings. | `var(--font-ui)` |
430
+ | `--font-mono` | type | Code. | `ui-monospace, 'SF Mono', Menlo, Consolas, monospace` |
431
+ | `--font-size-small` | type | Hints, captions, pills. | `13px` |
432
+ | `--font-size-body` | type | Body and controls. | `15px` |
433
+ | `--font-size-title` | type | A card or sheet title. | `20px` |
434
+ | `--weight-strong` | type | Labels on buttons, titles. | `600` |
435
+ | `--radius-control` | shape | Buttons and fields. | `8px` |
436
+ | `--radius-card` | shape | Cards, menus, sheets. Inner radius = this − padding. | `12px` |
437
+ | `--radius-full` | shape | Pills and round buttons. | `999px` |
438
+ | `--control-h` | shape | Every control's height; 44px is a whole fingertip. | `44px` |
439
+ | `--shadow-raised` | shape | A card off the page. | `0 1px 2px rgb(0 0 0 / 0.08), 0 2px 8px rgb(0 0 0 / 0.06)` |
440
+ | `--shadow-overlay` | shape | A menu, toast or dialog over everything. | `0 8px 32px rgb(0 0 0 / 0.18)` |
441
+ | `--duration-fast` | motion | Hover and press. | `120ms` |
442
+ | `--duration-base` | motion | Open and close. | `220ms` |
443
+ | `--ease-out` | motion | Things arriving. | `cubic-bezier(0.2, 0, 0, 1)` |
444
+
445
+ Parts also read the spacing steps `--space-4`, `-6`, `-8`, `-12`, `-16` and
446
+ `-24` directly. `extract` always emits them.
447
+
448
+ `kit/tokens.css` is the foundation's default theme. It sets the core tokens
449
+ and derives everything else from them, exactly as in the table, except
450
+ `--surface-raised`, which steps lighter by how dark `--surface` is
451
+ (`oklch(from var(--surface) …)`): nothing on a white page, a visible step on a
452
+ dark one. Dark mode (`:root[data-theme='dark']`, or `prefers-color-scheme:
453
+ dark` unless `data-theme='light'`) changes only the core tokens and shadows,
454
+ so a project that sets its own core keeps its own look in both.
455
+
456
+ ## The kit
457
+
458
+ The foundation's parts: plain CSS, plus a little vanilla JS where behaviour
459
+ needs it, with no framework. Each part reads only the contract and the
460
+ spacing steps, so it takes on the project's look. All of them come in with
461
+ `@rickycourtes/designrail/foundation.css`; one at a time works too:
462
+
463
+ ```css
464
+ @layer designrail.tokens, designrail.base, designrail.parts;
465
+ @import '@rickycourtes/designrail/tokens.css';
466
+ @import '@rickycourtes/designrail/parts/base.css';
467
+ @import '@rickycourtes/designrail/parts/button.css';
468
+ ```
469
+
470
+ Each part's **knobs** are listed below. Set them on a variant class of your
471
+ own; the part reads them, so you never edit it.
472
+
473
+ ### base
474
+
475
+ The page (`body` background, text, font), heading resets, and layout helpers:
476
+
477
+ - `.stack`: a column with one gap (`--gap`, default `--space-12`)
478
+ - `.row`: a wrapping line (default `--space-8`)
479
+ - `.tight` / `.loose` change the gap; `.muted` and `.small` adjust text
480
+ - a keyboard-only focus ring (`:focus-visible`)
481
+ - motion stops under `prefers-reduced-motion`
482
+
483
+ Knob: `--gap` on `.stack` and `.row`.
484
+
485
+ ### button
486
+
487
+ ```html
488
+ <div class="actions">
489
+ <button class="btn quiet">Not now</button>
490
+ <button class="btn">Duplicate</button>
491
+ <button class="btn primary">Save changes</button>
492
+ </div>
493
+ <button class="icon-btn" aria-label="More">…</button>
494
+ ```
495
+
496
+ | Class | Use |
497
+ | --- | --- |
498
+ | `.btn` | Default: a fill one shade off its surface. |
499
+ | `.btn.primary` | The one accent action in a view. |
500
+ | `.btn.danger` | Loses something. |
501
+ | `.btn.quiet` | The third choice, beside a default or primary, never alone. |
502
+ | `.btn.small` | A denser row; it keeps a 44px hit area. |
503
+ | `.icon-btn` | A 1:1 circle, clear at rest. Needs `aria-label`. |
504
+ | `.actions` | A row of buttons, `--space-8` apart, end-aligned. |
505
+
506
+ | `.btn.outline` | A rim instead of a fill. |
507
+
508
+ The height is `--control-h`. The side padding is derived from the height so
509
+ it is twice the top padding (measured from the outer edge, rim included).
510
+
511
+ Knobs: `--btn-h`, `--btn-line`, `--btn-radius`, `--btn-bg`, `--btn-bg-hover`,
512
+ `--btn-bg-press`, `--btn-fg`, `--btn-fg-hover`, `--btn-rim`, `--btn-rim-w`,
513
+ `--btn-font-size`, `--btn-gap`; on `.icon-btn`: `--icon-btn-size`,
514
+ `--icon-btn-fg`, `--icon-btn-bg-hover`, `--icon-btn-bg-press`; `--icon-size` for
515
+ an svg inside either.
516
+
517
+ ```css
518
+ .btn.ink { --btn-bg: var(--text); --btn-bg-hover: color-mix(in oklab, var(--text), var(--surface) 20%); --btn-fg: var(--surface); }
519
+ ```
520
+
521
+ ### field
522
+
523
+ ```html
524
+ <label class="field">
525
+ <span class="label">Email</span>
526
+ <input class="input" type="email">
527
+ <span class="hint">We never share it.</span>
528
+ </label>
529
+ <label class="check"><input type="checkbox"><span>Email me</span></label>
530
+ ```
531
+
532
+ - `.input` styles `input`, `textarea` and `select` (`appearance: none` with
533
+ a drawn caret).
534
+ - `.field.invalid` turns the rim and hint `--danger`.
535
+ - Focus turns the rim to the accent; the ring is for the keyboard only.
536
+ - `.check` puts the tick at the top of a label, centred on its first line,
537
+ so a long label wraps under itself.
538
+
539
+ Knobs: `--input-h`, `--input-line`, `--input-rim-w`, `--input-radius`,
540
+ `--input-bg`, `--input-fg`, `--input-rim`, `--input-rim-hover`,
541
+ `--input-rim-focus`; `--field-gap` on `.field`; `--tick` on a `.check` input.
542
+
543
+ ### card
544
+
545
+ ```html
546
+ <div class="card">
547
+ <div class="card-head"><h3>Weekly digest</h3><p>Every Monday at 9:00</p></div>
548
+ <div class="inset">Inner boxes keep a concentric corner.</div>
549
+ <div class="actions"><button class="btn primary">Turn on</button></div>
550
+ </div>
551
+ ```
552
+
553
+ - `.card` is a padded raised surface that stacks its children with one gap.
554
+ - `.card.flat` swaps the shadow for a rim.
555
+ - `.inset` is a box inside a card. Its radius is the card's radius minus
556
+ its padding.
557
+ - The card is only as big as what it holds; it never stretches to fill a
558
+ column.
559
+
560
+ Knobs: `--card-pad`, `--card-gap`, `--card-radius`, `--card-bg`,
561
+ `--card-shadow`, `--card-rim`.
562
+
563
+ ### pill
564
+
565
+ ```html
566
+ <span class="pill accent"><span class="dot"></span>Live</span>
567
+ <span class="pill danger">Failed</span>
568
+ Comments <span class="count">12</span>
569
+ ```
570
+
571
+ - `.pill` takes `.accent`, `.danger`, `.success` or `.warning` to tint it by
572
+ what it says.
573
+ - `.dot` is a leading mark.
574
+ - `.count` is a number beside its label, with tabular figures.
575
+
576
+ Knobs: `--pill-tone` (the colour it says; the tinted variants mix their
577
+ background from it), `--pill-bg`, `--pill-fg`.
578
+
579
+ ### dropdown
580
+
581
+ ```html
582
+ <div class="dropdown">
583
+ <button class="btn" aria-haspopup="menu" aria-expanded="false">Sort</button>
584
+ <div class="menu" role="menu" hidden>
585
+ <button class="menu-item" role="menuitem">Newest</button>
586
+ <div class="menu-sep"></div>
587
+ <button class="menu-item" role="menuitem">Reset</button>
588
+ </div>
589
+ </div>
590
+ ```
591
+
592
+ ```js
593
+ import { dropdowns } from './ui/dropdown.js';
594
+ dropdowns(); // once; it delegates, so dropdowns added later work too
595
+ ```
596
+
597
+ - Click opens and closes the menu.
598
+ - Arrow keys, Home and End move between items; Escape closes the menu and
599
+ returns focus; Tab and an outside click close it.
600
+ - `.menu.end` aligns the menu to the right edge.
601
+ - `[aria-checked='true']` marks the current item.
602
+
603
+ Knobs: `--menu-pad`, `--menu-radius`, `--menu-bg`, `--menu-shadow`,
604
+ `--menu-min-w`, `--menu-item-h`.
605
+
606
+ ### toast
607
+
608
+ ```js
609
+ import { toast } from './ui/toast.js';
610
+ const dismiss = toast('Link copied', { action: { label: 'Undo', onClick: undo }, timeout: 4000 });
611
+ ```
612
+
613
+ - Toasts stack in one polite live region at the bottom of the page.
614
+ - Each has at most one action, and closes after `timeout` ms (`0` keeps it
615
+ open).
616
+ - The text is set with `textContent`, so a message is never parsed as HTML.
617
+
618
+ Knobs: `--toast-bg`, `--toast-fg`, `--toast-radius`, `--toast-max-w`.
619
+
620
+ ### sheet
621
+
622
+ ```html
623
+ <dialog class="sheet" id="rename">
624
+ <header class="sheet-head"><h2>Rename project</h2>
625
+ <button class="icon-btn sheet-close" aria-label="Close" onclick="this.closest('dialog').close()">×</button></header>
626
+ …
627
+ <footer class="actions"><button class="btn quiet">Cancel</button><button class="btn primary">Rename</button></footer>
628
+ </dialog>
629
+ ```
630
+
631
+ - Built on the native `<dialog>`: `el.showModal()` gives a focus trap,
632
+ Escape and an inert background.
633
+ - At most 420px wide; on screens under 520px it becomes a bottom sheet that
634
+ respects the safe area.
635
+
636
+ Knobs: `--sheet-pad`, `--sheet-gap`, `--sheet-width`, `--sheet-radius`,
637
+ `--sheet-bg`.
638
+
639
+ ## Design rules
640
+
641
+ `init` writes these to `DESIGN.md` for people and agents to follow. Each
642
+ bullet is tagged `{id · how it is checked}`:
643
+
644
+ - `check`: `designrail check` fails a change that breaks it.
645
+ - `audit`: `designrail audit` reports it.
646
+ - `eye`: a person or agent has to look.
647
+
648
+ The rules came out of Popup's design system.
649
+
650
+ **Tokens**
651
+ - Read semantic tokens, never a literal. `{tokens.no-hardcoded · check: hardcoded}`
652
+ - Primitives are for token files; the space, radius and font-size steps are
653
+ the exception. `{tokens.semantic-only · check: primitive-direct}`
654
+ - Every `var()` resolves. `{tokens.resolves · check: unresolved}`
655
+ - A token nobody reads goes. `{tokens.used · check: unused}`
656
+ - The theme sets the core tokens; the rest derive. `{tokens.core · check: contract}`
657
+ - One accent; other colours only say a state. `{tokens.one-accent · eye}`
658
+ - Spacing sits on the grid. `{tokens.grid · audit}`
659
+
660
+ **Parts**
661
+ - Use the part we have; never draw it again. A new look is a variant in the
662
+ part's own file. `{parts.reuse · audit}`
663
+ - Build on the foundation; restyle a part with its knobs on a variant, never
664
+ where it is used. `{parts.knobs · check: part-restyle}`
665
+ - No copy-pasted rule blocks. `{parts.no-duplicates · check: duplicate-block}`
666
+ - A button is a choice with a shape and a label naming its result; quiet is
667
+ the third choice. `{parts.buttons · eye}`
668
+ - An icon button is a 1:1 circle with an `aria-label`. `{parts.icon-button · eye}`
669
+
670
+ **Layout**
671
+ - Siblings get their gap from the container. `{layout.gap · eye}`
672
+ - Space is proximity: inside a group < between groups < padding. `{layout.proximity · eye}`
673
+ - A filled box pads every side, ends equal; a labelled control's side pad is
674
+ twice its top pad. `{layout.padding · eye}`
675
+ - Concentric corners: inner radius = outer radius − padding. `{layout.concentric · eye}`
676
+ - 44px touch targets. `{layout.targets · eye}`
677
+
678
+ **Type and motion**
679
+ - Sentence case, no tracked-out capitals. `{type.case · check: tracked-caps}`
680
+ - Focus glow for the keyboard only. `{motion.focus · eye}`
681
+ - Motion uses the duration and easing tokens and stops under reduced motion. `{motion.tokens · eye}`
682
+
683
+ Turn a checked rule off or down in the config's `rules`.
684
+
685
+ ## Configuration
686
+
687
+ `designrail.config.json` at the project root. `init` writes it, every key is
688
+ optional, and `schema.json` validates it.
689
+
690
+ ```json
691
+ {
692
+ "foundation": "0.2.0",
693
+ "ejected": [],
694
+ "include": ["."],
695
+ "exclude": ["dist", "build", "out", "coverage", "vendor", "**/*.min.*", "**/*.map"],
696
+ "tokens": ["tokens/primitives.css", "tokens/semantic.css"],
697
+ "parts": "ui",
698
+ "grid": 4,
699
+ "colorTolerance": 0.01,
700
+ "snap": 1,
701
+ "semanticOnly": true,
702
+ "allowPrimitives": ["--space-", "--radius-", "--font-size-"],
703
+ "runtimeTokens": [],
704
+ "rules": {
705
+ "hardcoded": "error",
706
+ "unresolved": "error",
707
+ "primitive-direct": "warn",
708
+ "duplicate-block": "error",
709
+ "unused": "warn",
710
+ "tracked-caps": "warn",
711
+ "contract": "warn",
712
+ "part-restyle": "warn"
713
+ },
714
+ "maxFileBytes": 1500000
715
+ }
716
+ ```
717
+
718
+ | Key | Meaning |
719
+ | --- | --- |
720
+ | `foundation` | The foundation version the project is on. `init` writes it; `upgrade --write` moves it. |
721
+ | `ejected` | Parts the project owns a copy of (`eject` writes it). |
722
+ | `include` | Folders to scan. |
723
+ | `exclude` | Globs left out. `.gitignore` entries, `.git`, `node_modules` and `.designrail` are always left out too. |
724
+ | `tokens` | The token files. Stylesheets that are mostly custom properties on `:root` (or `html`, `:host`, `[data-theme]`) count as token files even if unlisted. |
725
+ | `parts` | Where the project's own parts live, and where `eject` copies one. |
726
+ | `grid` | The spacing grid in px. |
727
+ | `colorTolerance` | ΔE (OKLab) below which two colours are the same colour. 0.01 merges `#3b82f6` and `#3b83f6` but keeps `#ffffff` and `#fafafa` apart. |
728
+ | `snap` | px within which `extract` merges lengths and `fix --snap` maps one to a step. |
729
+ | `semanticOnly` | Report primitives read outside token files. |
730
+ | `allowPrimitives` | Primitive prefixes allowed anywhere. |
731
+ | `runtimeTokens` | Custom properties set from JS, as names or prefixes, so they count as defined. Calls like `setProperty('--x', …)` are found on their own. |
732
+ | `rules` | `error`, `warn` or `off` per check rule. |
733
+ | `maxFileBytes` | Larger files are skipped. |
734
+
735
+ To exempt a single declaration, put `/* designrail-ignore */` (or
736
+ `/* measured */`) inside its value, for example
737
+ `margin-top: -3px /* measured */;`.
738
+
739
+ ## What it reads
740
+
741
+ | Source | Read as |
742
+ | --- | --- |
743
+ | `.css`, `.scss`, `.less`, `.pcss` | Rules, native/SCSS/Less nesting with `&`, `@media`/`@container`/`@supports`/`@layer`. `@keyframes` and `@font-face` contents are not counted as usage. |
744
+ | `.html`, `.vue`, `.svelte`, `.astro` | `<style>` blocks (`lang="scss"` too), `style=""` attributes, `<script>` contents, and the markup. |
745
+ | `.js`, `.jsx`, `.ts`, `.tsx`, `.mjs`, `.cjs` | `css`` `, `styled.x`` `, `styled(X)`` `, `createGlobalStyle`, `keyframes`; `style={{…}}`, `sx={{…}}`, `Object.assign(el.style, {…})` and `el.style.prop = '…'` (known CSS properties only, so config objects stay out); JSX markup; `var(--x)` reads and `setProperty('--x')` writes. |
746
+ | Class strings anywhere | Tailwind arbitrary values: `p-[13px]`, `bg-[#fafafa]`, `rounded-[10px]`, `text-[15px]`/`text-[#333]`, `shadow-[…]`, `z-[…]` and the rest. |
747
+
748
+ Values are recognised in every notation:
749
+
750
+ - **Colours**: hex (3, 4, 6 or 8 digits), `rgb()`/`rgba()`, `hsl()`/`hsla()`,
751
+ `oklch()`, `oklab()` and all 148 named colours.
752
+ - **Lengths**: px and rem.
753
+ - **Times**: ms and s.
754
+ - **Other**: `cubic-bezier()`, font stacks, weights, shadows and z-index.
755
+
756
+ `0` and hairlines (2px or less) in spacing and radius are measurements, not
757
+ scale steps, so they are ignored.
758
+
759
+ ## CI and git hooks
760
+
761
+ ```bash
762
+ npx designrail check --install-hook
763
+ ```
764
+
765
+ This adds `designrail check --staged` to `.git/hooks/pre-commit`.
766
+
767
+ In GitHub Actions:
768
+
769
+ ```yaml
770
+ - uses: actions/checkout@v4
771
+ with: { fetch-depth: 0 }
772
+ - run: npx designrail check --base origin/${{ github.base_ref }}
773
+ ```
774
+
775
+ Both fail only on what the change adds. The project's existing drift is the
776
+ baseline in git; there is no baseline file to maintain.
777
+
778
+ ## Coding agents
779
+
780
+ `designrail init --agents` adds this to `CLAUDE.md` or `AGENTS.md`:
781
+
782
+ > Before touching UI, read `DESIGN.md`. Build from the parts in `ui/` and the
783
+ > tokens in the token files, on top of the designrail foundation
784
+ > (`@rickycourtes/designrail/foundation.css`). Restyle a foundation part with its knobs on a
785
+ > variant, never by editing it; never type a colour, spacing, radius or font
786
+ > size by hand. Run `npx designrail check` before committing; `npx designrail
787
+ > trace <selector>` shows where a value comes from. A part the foundation
788
+ > lacks: write it in `ui/` from tokens; `npx designrail eject <part>` only to
789
+ > own a copy.
790
+
791
+ Every command's `--json` output is one line, small enough for an agent to
792
+ read whole.
793
+
794
+ ## Library API
795
+
796
+ ```js
797
+ import { loadProject, buildModel, audit, extract, planFix, hits } from 'designrail';
798
+
799
+ const model = buildModel(await loadProject('.', { cache: true }));
800
+ const report = audit(model); // { score, breakdown, colors, scales, blocks, parts, markup, … }
801
+ const tokens = extract(model); // { primitives, semantic, dark }
802
+ const plan = planFix(model, { snap: false }); // { edits: Map<file, [{ start, end, text, from, line }]>, missed }
803
+ const problems = hits(model); // [{ rule, level, file, line, msg, key }]
804
+ ```
805
+
806
+ The package also exports:
807
+
808
+ - `toCss`, `toDtcg`, `applyFix`
809
+ - `baselines` and `added` (the git diff mode)
810
+ - `traceSelector`, `traceToken`, `specimens`
811
+ - `findFoundation`, `planUpgrade`, `applyUpgrade`, `ejectParts`
812
+ - `PARTS`, `CONTRACT`
813
+ - the low-level readers `analyze`, `parseCss`, `parseColor` and `literals`
814
+
815
+ They give the same answers as the CLI.
816
+
817
+ ## Performance
818
+
819
+ - **Single-pass readers**: a forgiving CSS reader and tag scanner instead of
820
+ PostCSS or Babel, with value offsets kept so `fix` edits text in place.
821
+ - **Worker threads**: when more than 150 files need parsing, they are split
822
+ across up to 8 workers.
823
+ - **A cache in `.designrail/cache.json`**: keyed by each file's size and
824
+ mtime, so a rerun reads only what changed. The folder ignores itself in
825
+ git, and `--no-cache` skips the cache entirely.
826
+
827
+ On Popup (290 files), a cold scan takes 93 ms, a cached one 11 ms, and the
828
+ whole process about 0.05 s.
829
+
830
+ ## Limits
831
+
832
+ - **Detection is heuristic.** Role detection uses class names, so a button
833
+ called `.go` is not seen as a button. Semantic inference picks the most
834
+ used value for each job. Read `extract`'s comments and rename what it got
835
+ wrong; `fix` and `check` follow your names.
836
+ - **Indented `.sass`** syntax is not read.
837
+ - **Dynamic values are not read.** Values built at runtime (template strings
838
+ with interpolations, computed class names) are skipped.
839
+ - **A var() in a plain JS file never fails `unresolved` or
840
+ `primitive-direct`**, because it may be a string in a test or a tool. It
841
+ still counts as a read for `unused`.
842
+
843
+ ## Releasing
844
+
845
+ A release is a version tag. `.github/workflows/publish.yml` publishes it to
846
+ npm with provenance through npm trusted publishing, so there is no token or
847
+ secret. The package's trusted publisher on npmjs.com names this repo and
848
+ `publish.yml`.
849
+
850
+ 1. Add the version's entry to `kit/changes.json` (`renamed`, `added`,
851
+ `removed`, `notes`) and to `CHANGELOG.md`. `upgrade` reads the first; a
852
+ test fails if the current version has no entry.
853
+ 2. Bump `"version"` in `package.json`.
854
+ 3. Tag and push: `git tag -a vX.Y.Z -m vX.Y.Z && git push origin vX.Y.Z`.
855
+
856
+ The workflow checks that the tag matches `package.json` before it publishes. Patch releases (bug fixes, new knobs, new parts) are
857
+ safe for every project to take automatically. Anything that renames or
858
+ removes a token or class is a minor release in 0.x (a major release from
859
+ 1.0 on), and must carry its renames in `changes.json`.
860
+
861
+ ## Developing designrail
862
+
863
+ ```bash
864
+ npm test # mdtest: Markdown specs in test/*.md, checked by Claude
865
+ npx mdtest --list # list the Markdown tests (free, no Claude calls)
866
+ node bin/designrail.js audit fixtures/messy
867
+ ```
868
+
869
+ | Path | What |
870
+ | --- | --- |
871
+ | `bin/designrail.js` | Entry point. |
872
+ | `src/cli.js` | Commands and flag checking. |
873
+ | `src/project.js` | Config, file walk, cache, workers. |
874
+ | `src/sources.js`, `src/css.js`, `src/markup.js`, `src/values.js` | Readers: files → rules, declarations with offsets, literals, markup fingerprints. |
875
+ | `src/model.js` | Token files, definitions, uses, hardcoded occurrences. |
876
+ | `src/audit.js`, `src/extract.js`, `src/fix.js`, `src/check.js`, `src/trace.js`, `src/specimens.js`, `src/kit.js`, `src/upgrade.js`, `src/init.js` | One per command. |
877
+ | `src/contract.js` | The semantic contract. |
878
+ | `src/tokens.js` | Token index: each token resolved and classified. |
879
+ | `src/report.js` | Terminal and HTML output. |
880
+ | `kit/` | The foundation: `foundation.css`/`.js`, `tokens.css`, `parts/`, and `changes.json` (one entry per release, read by `upgrade`). |
881
+ | `rules/DESIGN.md` | The rules `init` installs. |
882
+ | `fixtures/messy` | A small project with planted problems, used by the tests. |
883
+
884
+ `fixtures/messy` plants:
885
+
886
+ - three blues that look the same
887
+ - `.card`, `.panel` and `.product-tile` with near-identical styles
888
+ - three button families
889
+ - card markup copied across pages
890
+ - off-grid spacing
891
+ - a Tailwind arbitrary value, a JSX style object and a styled-component