Skip to content

Isometric line figures that answer the pointer. For React and for anything with a DOM.

Specs and plans stay on the machine: docs/superpowers leaves the repo and is ignored

Lucas Marques415f4af7d722
diff --git a/.gitignore b/.gitignore
index d803734..7b9fbe7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,3 +16,6 @@ playwright-report/
# Copied in from the root by the package's prepack
packages/hairline/README.md
packages/hairline/LICENSE
+
+# Specs and plans from the superpowers skills: kept on the machine, not in the repo
+docs/superpowers/
diff --git a/docs/superpowers/plans/2026-10-01-hairline-create-skill.md b/docs/superpowers/plans/2026-10-01-hairline-create-skill.md
deleted file mode 100644
index d77fdce..0000000
--- a/docs/superpowers/plans/2026-10-01-hairline-create-skill.md
+++ /dev/null
@@ -1,1919 +0,0 @@
-# `hairline-create` Skill Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Ship `skills/hairline-create/`, a skill that turns `/hairline-create <idea>` into one new Hairline figure on a self-contained HTML page, drawn on the package's own engine and held to its ten rules.
-
-**Architecture:** The agent writes one file, the figure. A generated `kernel.js` (the package's `src/core`, bundled into one global `HL`) and a fixed `bench.html` are pasted around it by `build.mjs`; `validate.mjs` rejects a page whose kernel or bench changed or whose figure breaks a mechanical rule; `look.md` covers what text cannot check. Tests live in `packages/hairline/test` and run in the existing CI steps.
-
-**Tech Stack:** Node 22 built-ins only inside the skill folder; esbuild 0.28.2 for the kernel generator; Vitest and Playwright (Chrome) for the tests, as the package already uses.
-
-**Spec:** `docs/superpowers/specs/2026-10-01-hairline-create-skill-design.md`
-
-**Execution:** Subagent-driven. Implementers run on Opus (`model: "opus"`); the controller (Fable) reviews each task and runs Tasks 6 and 7 itself.
-
-## What this plan adds to the spec
-
-Five things the spec did not name. Task 5 writes them into the spec so the two agree.
-
-1. **`build.mjs`** joins the skill folder: `node build.mjs <figure.js>` writes the page. The agent never has to read or retype the kernel, and the tests assemble pages the same way an agent does.
-2. **Two more validator checks:** `hit` (input only through `HL.pointer`; nothing measured on screen: rule 01) and the bench must be unchanged, not only the kernel.
-3. **`setTimeout` is rejected outright**, not only in loops. A static check cannot tell a loop from a single call, and a delay belongs to a tween.
-4. **Two URL parameters on the bench**, for the look: `?w=240` narrows the page, `&at=x,y` holds the pointer at a viewBox point for tools that cannot hover.
-5. **Figures are pointer-only.** The bench's stage is an image (`role="img"`), so the Riffle example drops the package's keyboard handling.
-
-## Global Constraints
-
-- Nothing under `packages/hairline/src` is edited. No public API is added to the package.
-- Files in `skills/hairline-create/` import Node built-ins only. No `package.json` there, no dependencies.
-- The skill folder holds exactly: `SKILL.md`, `rules.md`, `concepts.md`, `look.md`, `kernel.js`, `bench.html`, `build.mjs`, `validate.mjs`, `examples/terrain.js`, `examples/riffle.js`.
-- `kernel.js` is generated. It is never edited by hand; `node scripts/kernel.mjs` writes it.
-- A figure is at most 200 lines. Both examples obey this.
-- Node 22 or later. esbuild pinned at `0.28.2` (the version `packages/hairline` already has).
-- Code, comments and copy are in English. Comments match the repository's density and voice: they say why, in plain sentences.
-- Commits: stage files by name only; end every message with `Co-Authored-By: Claude <[email protected]>`. Never commit `apps/site/.vitest/`, `apps/site/AGENTS.md`, `apps/site/CLAUDE.md`, `.vercel/`, `.superpowers/`, `.claude/`, `.env.local`.
-- Branch: `skill-create`. Do not merge; do not push to `main`.
-
-## Environment notes for implementers
-
-- The repository is `~/estudos/hairline`. The shell's working directory resets after every command, so start each one with `cd ~/estudos/hairline` (or a subfolder).
-- Prefix commands with `rtk`. When you need a command's raw output, use `rtk proxy <cmd>`.
-- Playwright reuses a server already on port 4310, and that server reads the skill's files once, at start. Before every browser run: `lsof -ti:4310 | xargs kill 2>/dev/null; true`.
-- Unit tests: `cd ~/estudos/hairline/packages/hairline && rtk proxy pnpm exec vitest run test/skill`.
-- Browser tests: `cd ~/estudos/hairline/packages/hairline && rtk proxy pnpm exec playwright test skill.spec.ts --reporter=line`.
-
-## Review Focus
-
-Failure modes the spec implies but does not name. Each has a test in the task that owns the code.
-
-1. **The skill folder is a symlink.** `npx skills add` links skills into the agent's folder. `node <link>/build.mjs` and `node <link>/validate.mjs` must still run, not exit silently. (Task 2 and Task 4: run both through a symlink.)
-2. **The page is opened from disk.** The output is a `file://` page with an inline module script; it must draw there, not only over HTTP. (Task 2: Playwright opens the built file by `file://` URL.)
-3. **The figure throws at mount.** The person must see what went wrong under the stage, not an empty plate. (Task 2: `/bench/throws`.)
-4. **The person's system is dark and they press the theme switch.** The switch must win in both directions. (Task 2: theme test under `colorScheme: "dark"`.)
-5. **The kernel or figure contains `$&`, `$1` or the page has CRLF line endings.** Assembly must paste text literally, and the validator must not call a CRLF copy of a good page changed. (Task 2: `$` test; Task 4: CRLF test.)
-
----
-
-### Task 1: The kernel generator and the kernel
-
-**Files:**
-- Create: `scripts/kernel.mjs`
-- Create (generated): `skills/hairline-create/kernel.js`
-- Create: `packages/hairline/test/skill/kernel.test.ts`
-- Modify: `package.json` (root): add the `kernel` script and the `esbuild` devDependency
-- Modify: `turbo.json`: the `test` task's inputs
-- Modify: `pnpm-lock.yaml` (by `pnpm install`)
-
-**Interfaces:**
-- Consumes: `packages/hairline/src/core/{iso,motion,stage,styles}.ts`, read-only.
-- Produces:
- - `node scripts/kernel.mjs` writes `skills/hairline-create/kernel.js`; `node scripts/kernel.mjs --check` exits 0 when the committed file is current, 1 with a message on stderr when it is not.
- - `kernel.js` layout: line 1 is `/* hairline kernel sha256:<64 hex> */`; then the index comment; then esbuild's output, which defines `var HL`; the last line is `/* /hairline kernel */`. The hash is the SHA-256 of everything after line 1, including the final newline.
- - `HL` has exactly these 44 keys: `clamp lerp rad r2 poly seg open Cam proj unproj fit rrect circ hull ringAt facing run prism rings extremes fillet ghost setReducedMotion reducedMotion spring stepS bezier EASE_LIFT tween tval tset tdone mk solid put flatDot place fade reflect register pointer disposer css inject`.
-
-- [ ] **Step 1: Add esbuild to the root, the `kernel` script, and the turbo inputs**
-
-In the root `package.json`, add to `scripts`:
-
-```json
-"kernel": "node scripts/kernel.mjs"
-```
-
-and to `devDependencies`:
-
-```json
-"esbuild": "0.28.2"
-```
-
-In `turbo.json`, replace the `test` task with:
-
-```json
-"test": {
- "dependsOn": ["^build"],
- "inputs": ["$TURBO_DEFAULT$", "$TURBO_ROOT$/skills/**", "$TURBO_ROOT$/scripts/kernel.mjs"]
-}
-```
-
-The skill's files sit outside every package, so without these inputs turbo would replay a cached test run after the skill changed.
-
-Run: `cd ~/estudos/hairline && rtk pnpm install`
-Expected: the lockfile gains a root `esbuild 0.28.2` entry and nothing else changes version.
-
-- [ ] **Step 2: Write the failing test**
-
-Create `packages/hairline/test/skill/kernel.test.ts`:
-
-```ts
-import { spawnSync } from "node:child_process";
-import { createHash } from "node:crypto";
-import { readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { expect, it } from "vitest";
-
-/** The skill's kernel: generated from src/core, committed, and held current here. */
-const ROOT = fileURLToPath(new URL("../../../../", import.meta.url));
-const text = () => readFileSync(ROOT + "skills/hairline-create/kernel.js", "utf8");
-
-it("the committed kernel is what src/core gives now", () => {
- const run = spawnSync("node", ["scripts/kernel.mjs", "--check"], { cwd: ROOT, encoding: "utf8" });
- expect(run.stderr).toBe("");
- expect(run.status).toBe(0);
-});
-
-it("its first line carries the hash of everything after it", () => {
- const src = text(), cut = src.indexOf("\n");
- const hash = /^\/\* hairline kernel sha256:([0-9a-f]{64}) \*\/$/.exec(src.slice(0, cut))?.[1];
- expect(hash).toBe(createHash("sha256").update(src.slice(cut + 1)).digest("hex"));
- expect(src.endsWith("/* /hairline kernel */\n")).toBe(true);
-});
-
-it("defines one global, HL, holding what its index lists and nothing else", () => {
- const src = text();
- const HL = new Function(`${src}\nreturn HL;`)() as Record<string, unknown>;
- const indexed = [...src.slice(0, src.indexOf("var HL")).matchAll(/^ \* {3}(\w+)/gm)].map((m) => m[1]);
- expect(indexed.slice().sort()).toEqual(Object.keys(HL).sort());
- expect(Object.keys(HL)).toHaveLength(44);
- expect(typeof HL.register).toBe("function");
- expect(typeof HL.EASE_LIFT).toBe("function");
-});
-
-it("can sit inside a script element, and is left readable", () => {
- const src = text();
- expect(src).not.toMatch(/<\/script/i);
- expect(src.split("\n").length).toBeGreaterThan(300);
-});
-```
-
-- [ ] **Step 3: Run it to see it fail**
-
-Run: `cd ~/estudos/hairline/packages/hairline && rtk proxy pnpm exec vitest run test/skill/kernel.test.ts`
-Expected: FAIL. The first test fails on a non-empty stderr (`Cannot find module … scripts/kernel.mjs`); the others fail with `ENOENT … kernel.js`.
-
-- [ ] **Step 4: Write the generator**
-
-Create `scripts/kernel.mjs`:
-
-```js
-/**
- * The skill's kernel: packages/hairline/src/core as one plain script that
- * defines a single global, HL. `node scripts/kernel.mjs` writes
- * skills/hairline-create/kernel.js; with `--check` it writes nothing and exits
- * 1 when the committed file is not what the source gives now.
- *
- * The output is not minified: an agent reads the index at its top, and a
- * person can read the rest. Its first line carries the hash of everything
- * after it, which is how the skill's validator knows a kernel was not edited.
- */
-import { build } from "esbuild";
-import { createHash } from "node:crypto";
-import { readFileSync, writeFileSync } from "node:fs";
-import { join } from "node:path";
-import { fileURLToPath } from "node:url";
-
-const ROOT = fileURLToPath(new URL("..", import.meta.url));
-const OUT = join(ROOT, "skills/hairline-create/kernel.js");
-const FILES = ["iso", "motion", "stage", "styles"];
-
-/* One name per line, three spaces in: test/skill/kernel.test.ts holds this list to HL's keys. */
-const INDEX = `/*
- * HL: everything a figure may call. Read this index; the code under it is the
- * package's src/core, unchanged, and a figure should not need to read it.
- *
- * Every figure is drawn in a 400 × 320 viewBox. World space is x/y on the
- * ground and z up. Plates are filled with the ground colour and painted back
- * to front, so a nearer one covers a farther one: append in that order.
- *
- * Camera
- * Cam(azDeg, k, S) a camera: azimuth in degrees, k = sin(elevation) (0.5 is the 2:1 view), S = scale
- * fit(C, points, cx, cy) centres the box of [x, y, z] points on (cx, cy); call it once, before proj
- * proj(C) returns P(x, y, z), which gives [sx, sy]
- * unproj(C, sx, sy, z) the world [x, y] under a screen point, on the plane at height z
- * facing(C) returns front(sample): whether a ring sample faces the camera
- * Rounded solids
- * rrect(u0, v0, u1, v1, r, n) a rounded rectangle, as a ring of samples {u, v, nu, nv}
- * circ(R, n) a circle, as a ring
- * rings(x0, y0, x1, y1, r, b) [ring, inner]: a rounded footprint and its crease ring, inset by b
- * prism(P, front, ring, inner, z0, z1) {sil, crease}: a solid standing from z0 to z1, as two path strings
- * ringAt(P, ring, z) the ring's points, projected at height z
- * run(ring, keep) the one cyclic run of samples that pass keep
- * hull(points) the convex hull of screen points
- * extremes(P, ring) [left, right, nearest] samples: where dashed drops fall from
- * fillet(points, radii, n) rounds every vertex of a closed polygon
- * ghost(P, front, ring, z0, depth) a reflection's path {d, y0, y1}; reflect() draws it for you
- * Paths and numbers
- * poly(points) a closed path string
- * open(points) an open polyline string
- * seg(a, b) one segment, as its own subpath
- * clamp(v, a, b)
- * lerp(a, b, t)
- * rad(deg)
- * r2(n) two decimals
- * The continuous clock: one spring per moving number
- * spring(x, opts) at rest on x; write .t to retarget; opts {k, c, m, eps}, default k 100, c 18, m 1
- * stepS(sp, dt) advances by dt seconds; returns whether it is still moving
- * The discrete clock: a 700ms tween on (.32, .72, 0, 1)
- * tween(v, dur) at rest on v
- * tset(tw, to, now, delay) retargets from where it is, after delay ms: the stagger
- * tval(tw, now) its value at now
- * tdone(tw, now) whether it has landed
- * bezier(x1, y1, x2, y2) a CSS cubic-bezier, as a function of progress
- * EASE_LIFT the lift curve itself
- * reducedMotion() true when the reader asked for less motion; springs and tweens already land at once
- * setReducedMotion(on) the loop's business, not a figure's
- * Drawing
- * mk(tag, attrs, parent) one svg element: the only way a figure makes a node
- * solid(parent) {g, sil, cr}: a group holding a silhouette path and a crease path
- * put(solid, paths) writes prism()'s paths into solid()'s elements
- * flatDot(parent, C, r, cls) a dot lying on the ground plane; cls is "dot", "dot m" or "dot off"
- * place(el, point) moves a dot or a circle to [sx, sy]
- * reflect(svg, parent, P, front, ring, z0, depth) a fading mirror under a solid
- * fade(svg, y0, y1, a0) a vertical fade, as a mask; returns the value for a mask attribute
- * Life
- * register(stage, tick) joins the one frame loop; tick(dt in seconds, now in ms) returns true to ask for another frame; gives {wake, unregister}
- * pointer(stage, handlers) {move(point), down(point), leave()}, points in viewBox units; returns its disposer
- * disposer() {add, on, dispose}: collects tear-down, so destroy is bag.dispose
- * The bench's business, not a figure's
- * css(lightDark)
- * inject(root)
- *
- * Classes, on path, polygon, ellipse and line. They are the whole palette; a
- * figure sets no colour, width or fill of its own.
- * (none) filled with the ground colour, medium stroke
- * sil the silhouette's stroke hi the bright stroke: the only highlight
- * lo the dim stroke nf no fill fo fill only, no stroke
- * dash a dashed guide
- * dot a bright dot dot m a medium dot dot off a dim dot
- */`;
-
-/** The kernel's text, from the source as it is now. */
-export async function kernel() {
- const result = await build({
- stdin: {
- contents: FILES.map((f) => `export * from "./${f}";`).join("\n"),
- resolveDir: join(ROOT, "packages/hairline/src/core"),
- sourcefile: "kernel.ts",
- loader: "ts",
- },
- // esbuild names each source file in a comment, relative to this: the same on every machine
- absWorkingDir: ROOT,
- bundle: true,
- format: "iife",
- globalName: "HL",
- target: "es2020",
- charset: "utf8",
- legalComments: "none",
- write: false,
- });
- const body = `${INDEX}\n${result.outputFiles[0].text.trimEnd()}\n/* /hairline kernel */\n`;
- return `/* hairline kernel sha256:${createHash("sha256").update(body).digest("hex")} */\n${body}`;
-}
-
-if (process.argv[1] === fileURLToPath(import.meta.url)) {
- const text = await kernel();
- if (process.argv.includes("--check")) {
- let have = "";
- try { have = readFileSync(OUT, "utf8"); } catch { /* not generated yet: stale */ }
- if (have !== text) {
- console.error("skills/hairline-create/kernel.js is stale: run `pnpm kernel` and commit the result.");
- process.exit(1);
- }
- console.log("kernel is current");
- } else {
- writeFileSync(OUT, text);
- console.log(`wrote skills/hairline-create/kernel.js: ${text.split("\n").length} lines, ${Buffer.byteLength(text)} bytes`);
- }
-}
-```
-
-- [ ] **Step 5: Generate the kernel**
-
-Run: `cd ~/estudos/hairline && mkdir -p skills/hairline-create && rtk proxy node scripts/kernel.mjs`
-Expected: `wrote skills/hairline-create/kernel.js: <N> lines, <B> bytes`, with N over 300. Write N and B into your report; the controller needs them for the trial.
-
-- [ ] **Step 6: Run the test to see it pass**
-
-Run: `cd ~/estudos/hairline/packages/hairline && rtk proxy pnpm exec vitest run test/skill/kernel.test.ts`
-Expected: PASS, 4 tests.
-
-If the index test fails with a difference between the two lists, the index in `scripts/kernel.mjs` is wrong, not the test: add or remove the named line, regenerate, run again.
-
-- [ ] **Step 7: Run the whole suite and the typecheck**
-
-Run: `cd ~/estudos/hairline && rtk proxy pnpm typecheck && rtk proxy pnpm test`
-Expected: both pass, with no new warnings.
-
-- [ ] **Step 8: Commit**
-
-```bash
-cd ~/estudos/hairline && rtk git add package.json pnpm-lock.yaml turbo.json scripts/kernel.mjs skills/hairline-create/kernel.js packages/hairline/test/skill/kernel.test.ts && rtk git commit -m "Skill: the kernel, src/core as one script with a single global, generated and held current by a test
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
----
-
-### Task 2: The bench, the build script and the Terrain example
-
-**Files:**
-- Create: `skills/hairline-create/bench.html`
-- Create: `skills/hairline-create/build.mjs`
-- Create: `skills/hairline-create/examples/terrain.js`
-- Create: `packages/hairline/test/skill/build.test.ts`
-- Create: `packages/hairline/test/browser/skill.spec.ts`
-- Modify: `packages/hairline/test/browser/serve.mjs` (routes for the bench)
-
-**Interfaces:**
-- Consumes: `skills/hairline-create/kernel.js` and the global `HL` (Task 1).
-- Produces:
- - **The figure format.** A figure file is the body of an inline module script. It takes what it needs from `HL`, defines `mount({ stage, svg, read }, value)` returning `{ set(value), destroy() }`, and ends with `hairline({ name, means, rules, range, mount });`. `name` is a lowercase string, `means` one sentence, `rules` an array of rule numbers 1–10, `range` three numbers (the figure's value at intensity 0, 0.5 and 1).
- - **`bench.html`** with two slots, `/*KERNEL*/` inside `<script id="hl-kernel">` and `/*FIGURE*/` inside `<script type="module" id="hl-figure">`. Element ids: `stage`, `name`, `read`, `intensity`, `value`, `theme`, `means`, `rules`, `error`. It defines `window.hairline(figure)` and, after mount, `window.hairline.figure` (the handle). URL parameters `w` (page width in px) and `at` (`x,y` in viewBox units: holds the pointer there).
- - **`build.mjs`**: `export function assemble(figure: string): string` (the page), `export function nameOf(figure: string): string | null`, and the CLI `node build.mjs <figure.js> [out.html]`, which writes the page (default `hairline-<name>.html` in the working directory), prints its absolute path and exits 0; with no argument it prints usage on stderr and exits 2.
- - **Server routes** on `http://localhost:4310`: `/bench/terrain`, `/bench/throws`.
-
-- [ ] **Step 1: Write the failing unit test for the build script**
-
-Create `packages/hairline/test/skill/build.test.ts`:
-
-```ts
-import { spawnSync } from "node:child_process";
-import { mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { fileURLToPath } from "node:url";
-import { expect, it } from "vitest";
-
-/** build.mjs puts a figure on the bench: the page is the bench, the kernel and the figure, and nothing else. */
-const SKILL = fileURLToPath(new URL("../../../../skills/hairline-create/", import.meta.url));
-const dir = mkdtempSync(join(tmpdir(), "hl-build-"));
-const terrain = readFileSync(SKILL + "examples/terrain.js", "utf8");
-const node = (args: string[], cwd = dir) => spawnSync("node", args, { cwd, encoding: "utf8" });
-
-it("writes the bench with the kernel and the figure in their slots", () => {
- const out = join(dir, "page.html");
- const run = node([SKILL + "build.mjs", SKILL + "examples/terrain.js", out]);
- expect(run.stderr).toBe("");
- expect(run.status).toBe(0);
- expect(run.stdout.trim()).toBe(out);
- const page = readFileSync(out, "utf8");
- expect(page).toContain(readFileSync(SKILL + "kernel.js", "utf8").trimEnd());
- expect(page).toContain(terrain.trim());
- expect(page).not.toContain("/*KERNEL*/");
- expect(page).not.toContain("/*FIGURE*/");
-});
-
-it("names the page after the figure when no path is given", () => {
- const run = node([SKILL + "build.mjs", SKILL + "examples/terrain.js"]);
- expect(run.status).toBe(0);
- expect(run.stdout.trim().endsWith("hairline-terrain.html")).toBe(true);
- expect(readFileSync(run.stdout.trim(), "utf8")).toContain("<title>");
-});
-
-it("pastes text literally, so a figure may hold $& and $1", () => {
- const src = join(dir, "dollar.js"), out = join(dir, "dollar.html");
- const figure = terrain.replace("hairline({", () => 'const odd = "$& and $1 and $$";\nhairline({');
- writeFileSync(src, figure);
- expect(node([SKILL + "build.mjs", src, out]).status).toBe(0);
- expect(readFileSync(out, "utf8")).toContain('const odd = "$& and $1 and $$";');
-});
-
-it("runs when the skill folder is reached through a symlink", () => {
- const link = join(dir, "linked");
- symlinkSync(SKILL, link);
- const out = join(dir, "linked.html");
- const run = node([join(link, "build.mjs"), join(link, "examples/terrain.js"), out]);
- expect(run.status).toBe(0);
- expect(run.stdout.trim()).toBe(out);
-});
-
-it("says how to call it when it is given nothing", () => {
- const run = node([SKILL + "build.mjs"]);
- expect(run.status).toBe(2);
- expect(run.stderr).toContain("usage: node build.mjs <figure.js> [out.html]");
-});
-```
-
-- [ ] **Step 2: Run it to see it fail**
-
-Run: `cd ~/estudos/hairline/packages/hairline && rtk proxy pnpm exec vitest run test/skill/build.test.ts`
-Expected: FAIL at collection with `ENOENT … examples/terrain.js`.
-
-- [ ] **Step 3: Write the Terrain example**
-
-Create `skills/hairline-create/examples/terrain.js`. It is `packages/hairline/src/figures/terrain.ts` with the types taken out, the imports replaced by one destructuring of `HL`, and the declaration at the end. The arithmetic and the order in which nodes are made must not change: a later step compares its drawing with the package's, character for character.
-
-```js
-/**
- * Terrain: a field of 81 pillars on a rounded plinth. The pointer is projected
- * back onto the ground, and each pillar takes its height from its distance to
- * it, on its own spring. At rest the field is a dune with two rises. A 3 × 3
- * dot mark rides the lid of the pillar under the pointer, or the peak at rest;
- * pillars above half height take the bright stroke. The slider is the radius,
- * in cells.
- *
- * The pattern: a continuous field. Springs, a falloff by distance, a hit test
- * on the ground plane (which never moves), and a rest that is a composition.
- */
-const {
- Cam, clamp, facing, fit, prism, proj, rings, unproj, spring, stepS,
- flatDot, mk, place, pointer, put, register, disposer, solid,
-} = HL;
-
-const N = 9, CELL = 14, FOOT = 11, HMAX = 58, EXT = N * CELL, PB = 5;
-
-/** The share of full height at u radii from the pointer: 1 → .31 at 42% → .09 at the edge and beyond. */
-const falloff = (u) =>
- u <= 0 ? 1 : u <= 0.417 ? 1 - (u / 0.417) * 0.6875 : u <= 1 ? 0.3125 - ((u - 0.417) / 0.583) * 0.2185 : 0.094;
-
-function mount({ stage, svg, read }, value) {
- const bag = disposer();
- const C = Cam(45, 0.5, 1.58);
- fit(C, [[-6, -6, -PB], [EXT + 6, EXT + 6, -PB], [EXT + 6, -6, -PB], [-6, EXT + 6, -PB], [0, 0, HMAX * 0.75]], 200, 166);
- const P = proj(C), front = facing(C);
- let R = value * CELL, over = null;
-
- const g = mk("g", {}, svg), cols = [];
- const [pr, pi] = rings(-6, -6, EXT + 6, EXT + 6, 9, 2.2);
- put(solid(g), prism(P, front, pr, pi, -PB, 0));
- // Diagonal by diagonal from the back corner, so appending is painting back to front.
- for (let s = 0; s <= 2 * (N - 1); s++) for (let i = 0; i < N; i++) {
- const j = s - i;
- if (j < 0 || j >= N) continue;
- const u = i / (N - 1), v = j / (N - 1);
- const h0 = 4 + 25 * Math.exp(-((u - 0.22) ** 2 + (v - 0.74) ** 2) / 0.07) + 12 * Math.exp(-((u - 0.8) ** 2 + (v - 0.26) ** 2) / 0.035);
- const x0 = i * CELL + (CELL - FOOT) / 2, y0 = j * CELL + (CELL - FOOT) / 2;
- const [ring, inner] = rings(x0, y0, x0 + FOOT, y0 + FOOT, 2.6, 0.9);
- cols.push({ i, j, h0, ring, inner, sp: spring(h0, { eps: 0.04 }), el: solid(g), drawn: NaN });
- }
-
- // The mark: a 3 × 3 of dots riding the lid of one pillar, moved in the paint
- // order to just after it, so the pillars in front still cover it.
- const mark = mk("g", {}, g), md = [];
- for (let k = 0; k < 9; k++) md.push(flatDot(mark, C, 0.55, k === 4 ? "dot" : "dot m"));
- const peak = cols.reduce((a, b) => (b.h0 > a.h0 ? b : a));
- const byCell = new Map();
- cols.forEach((c) => byCell.set(c.i + "," + c.j, c));
- let mc = null, want = peak;
-
- function drawMark() {
- if (want !== mc) { mc = want; mc.el.g.after(mark); }
- const cx = (mc.i + 0.5) * CELL, cy = (mc.j + 0.5) * CELL, h = Math.max(0.6, mc.sp.x);
- md.forEach((el, k) => place(el, P(cx + ((k % 3) - 1) * 2.5, cy + (Math.floor(k / 3) - 1) * 2.5, h)));
- }
- // A pillar whose spring hasn't moved keeps its paths: most of the 81 are still on most frames.
- function drawCol(c) {
- const h = Math.max(0.6, c.sp.x);
- if (h === c.drawn) return;
- c.drawn = h;
- put(c.el, prism(P, front, c.ring, c.inner, 0, h));
- c.el.sil.classList.toggle("hi", h > HMAX * 0.5);
- }
-
- const B = register(stage, (dt) => {
- let m = false;
- for (const c of cols) { if (stepS(c.sp, dt)) m = true; drawCol(c); }
- drawMark();
- return m;
- });
- bag.add(B.unregister);
-
- function retarget() {
- for (const c of cols) {
- if (!over) { c.sp.t = c.h0; continue; }
- const dx = (c.i + 0.5) * CELL - over[0], dy = (c.j + 0.5) * CELL - over[1];
- c.sp.t = HMAX * falloff(Math.hypot(dx, dy) / R);
- }
- if (over) {
- const i = clamp(Math.floor(over[0] / CELL), 0, N - 1), j = clamp(Math.floor(over[1] / CELL), 0, N - 1);
- want = byCell.get(i + "," + j);
- read.textContent = `cell ${i}·${j}`;
- } else { want = peak; read.textContent = "rest"; }
- B.wake();
- }
-
- bag.add(pointer(stage, {
- move: (p) => { over = unproj(C, p[0], p[1], 0); retarget(); },
- leave: () => { over = null; retarget(); },
- }));
- bag.add(() => svg.replaceChildren());
-
- return {
- set: (v) => { R = v * CELL; if (over) retarget(); },
- destroy: bag.dispose,
- };
-}
-
-hairline({
- name: "terrain",
- means: "A field of pillars rises under the pointer and falls off with distance.",
- rules: [1, 3, 5, 9],
- range: [1.5, 3, 5],
- mount,
-});
-```
-
-- [ ] **Step 4: Write the bench**
-
-Create `skills/hairline-create/bench.html`:
-
-```html
-<!doctype html>
-<html lang="en">
-<head>
-<meta charset="utf-8">
-<meta name="viewport" content="width=device-width, initial-scale=1">
-<title>Hairline figure</title>
-<style>
- :root { color-scheme: light; --ground: #ffffff; --ink: #232327; --muted: #6f6f78; --line: #e0e0e4; }
- @media (prefers-color-scheme: dark) {
- :root:not([data-theme="light"]) { color-scheme: dark; --ground: #08090a; --ink: #d0d6e0; --muted: #8a8c95; --line: #29292d; }
- }
- :root[data-theme="dark"] { color-scheme: dark; --ground: #08090a; --ink: #d0d6e0; --muted: #8a8c95; --line: #29292d; }
- :root[data-theme="light"] { color-scheme: light; }
- * { box-sizing: border-box; }
- body {
- margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px 16px;
- background: var(--ground); color: var(--ink);
- font: 13px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; -webkit-font-smoothing: antialiased;
- }
- main { width: 100%; max-width: 640px; }
- .plate { position: relative; border: 1px solid var(--line); border-radius: 14px; overflow: hidden; }
- .tag, .label, output, button { font: 11px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; letter-spacing: 0.02em; }
- .tag { position: absolute; top: 12px; z-index: 1; color: var(--muted); pointer-events: none; }
- #name { left: 14px; }
- #read { right: 14px; color: var(--ink); font-variant-numeric: tabular-nums; }
- .controls { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 12px; margin-top: 14px; }
- .label { color: var(--muted); }
- input[type="range"] {
- flex: 1 1 96px; min-width: 0; height: 32px; margin: 0; background: transparent; cursor: pointer;
- -webkit-appearance: none; appearance: none;
- }
- input[type="range"]::-webkit-slider-runnable-track { height: 1px; background: var(--muted); }
- input[type="range"]::-webkit-slider-thumb {
- -webkit-appearance: none; width: 13px; height: 13px; margin-top: -6px; border-radius: 50%;
- border: 1px solid var(--ink); background: var(--ground);
- }
- input[type="range"]::-moz-range-track { height: 1px; background: var(--muted); }
- input[type="range"]::-moz-range-thumb { width: 11px; height: 11px; border-radius: 50%; border: 1px solid var(--ink); background: var(--ground); }
- input[type="range"]:focus-visible, button:focus-visible { outline: 1.5px solid var(--ink); outline-offset: 2px; }
- output { min-width: 4ch; text-align: right; font-variant-numeric: tabular-nums; }
- button {
- height: 32px; padding: 0 12px; border: 1px solid var(--line); border-radius: 8px;
- background: transparent; color: var(--ink); cursor: pointer;
- }
- #means { margin: 14px 0 0; text-wrap: pretty; }
- #rules { margin: 6px 0 0; line-height: 1.6; }
- #error { margin: 12px 0 0; padding-left: 10px; border-left: 1px solid var(--ink); }
-</style>
-</head>
-<body>
-<main>
- <div class="plate">
- <span class="tag" id="name"></span>
- <span class="tag" id="read"></span>
- <div id="stage"></div>
- </div>
- <div class="controls">
- <label class="label" for="intensity">intensity</label>
- <input id="intensity" type="range" min="0" max="1" step="0.01" value="0.5">
- <output id="value" for="intensity"></output>
- <span class="label">theme</span>
- <button id="theme" type="button" aria-label="Switch between the light and the dark theme"></button>
- </div>
- <p id="means"></p>
- <p id="rules" class="label"></p>
- <p id="error" role="alert" hidden></p>
-</main>
-<script id="hl-kernel">/*KERNEL*/</script>
-<script id="hl-bench">
-/*
- * The bench: the page a figure is shown on. It makes the host and the svg the
- * way the package's mount does, hands them to the figure, and owns everything
- * around it: the read-out, the slider, the theme, the line under the stage.
- */
-(() => {
- const RULES = ["hit", "order", "reach", "accent", "rest", "honesty", "cost", "clock", "radius", "quiet"];
- const $ = (id) => document.getElementById(id);
- const root = document.documentElement, params = new URLSearchParams(location.search);
-
- /* the theme: the system's until the switch is pressed, then the switch's */
- const dark = () => (root.dataset.theme ? root.dataset.theme === "dark" : matchMedia("(prefers-color-scheme: dark)").matches);
- const label = () => { $("theme").textContent = dark() ? "dark" : "light"; };
- $("theme").addEventListener("click", () => { root.dataset.theme = dark() ? "light" : "dark"; label(); });
- label();
-
- /* ?w=240 narrows the page, for a look at the size of a thumbnail */
- const w = Number(params.get("w"));
- if (w > 0) document.querySelector("main").style.maxWidth = w + "px";
-
- /* a figure that fails says so under the stage, instead of leaving an empty plate */
- addEventListener("error", (e) => {
- $("error").hidden = false;
- $("error").textContent = String((e.error && e.error.message) || e.message);
- });
-
- let mounted = false;
- window.hairline = (figure) => {
- if (mounted) throw new Error("hairline: one figure per page.");
- mounted = true;
- const stage = $("stage"), slider = $("intensity");
-
- /* intensity to the figure's own number: two straight lines that meet at 0.5, as in the package */
- const [lo, mid, hi] = figure.range;
- const at = (i) => Math.round((i <= 0.5 ? lo + (i / 0.5) * (mid - lo) : mid + ((i - 0.5) / 0.5) * (hi - mid)) * 1000) / 1000;
-
- HL.inject(document);
- stage.setAttribute("data-hairline", figure.name);
- stage.setAttribute("role", "img");
- stage.setAttribute("aria-label", figure.means);
- const svg = HL.mk("svg", { viewBox: "0 0 400 320", "aria-hidden": "true" }, stage);
-
- let text = null;
- const read = {
- get textContent() { return text; },
- set textContent(value) { text = value == null ? "" : String(value); $("read").textContent = text; },
- };
-
- document.title = "Hairline · " + figure.name;
- $("name").textContent = figure.name;
- $("means").textContent = figure.means;
- $("rules").textContent = figure.rules.map((n) => String(n).padStart(2, "0") + " " + RULES[n - 1]).join(" · ");
- const show = () => { $("value").textContent = String(at(Number(slider.value))); };
- show();
-
- const handle = figure.mount({ stage, svg, read }, at(0.5));
- if (text === null) read.textContent = "rest";
- slider.addEventListener("input", () => { show(); handle.set(at(Number(slider.value))); });
- window.hairline.figure = handle;
-
- /* ?at=200,160 holds the pointer at a viewBox point, for a picture of the answer without a mouse */
- const p = (params.get("at") || "").split(",").map(Number);
- if (p.length === 2 && p.every(Number.isFinite)) {
- const r = stage.getBoundingClientRect();
- stage.dispatchEvent(new PointerEvent("pointermove", {
- pointerType: "mouse", pointerId: 1, bubbles: true,
- clientX: r.left + (p[0] / 400) * r.width, clientY: r.top + (p[1] / 320) * r.height,
- }));
- }
- };
-})();
-</script>
-<script type="module" id="hl-figure">/*FIGURE*/</script>
-</body>
-</html>
-```
-
-- [ ] **Step 5: Write the build script**
-
-Create `skills/hairline-create/build.mjs`:
-
-```js
-#!/usr/bin/env node
-/**
- * Puts a figure on the bench: `node build.mjs <figure.js> [out.html]` writes
- * one self-contained page, bench.html with kernel.js and the figure in its two
- * slots and nothing else changed, and prints where it is. Without a path the
- * page is hairline-<name>.html in the working directory.
- */
-import { readFileSync, realpathSync, writeFileSync } from "node:fs";
-import { resolve } from "node:path";
-import { fileURLToPath } from "node:url";
-
-const here = (p) => fileURLToPath(new URL(p, import.meta.url));
-
-/** The page for a figure's source. The replacements are functions so `$&` in the kernel or the figure is pasted as it is. */
-export function assemble(figure) {
- const kernel = readFileSync(here("./kernel.js"), "utf8").replace(/\r\n/g, "\n").trimEnd();
- return readFileSync(here("./bench.html"), "utf8").replace(/\r\n/g, "\n")
- .replace("/*KERNEL*/", () => `\n${kernel}\n`)
- .replace("/*FIGURE*/", () => `\n${figure.replace(/\r\n/g, "\n").trim()}\n`);
-}
-
-/** The figure's name, read from its declaration. */
-export const nameOf = (figure) => /\bname:\s*["'`]([a-z][a-z0-9-]*)["'`]/.exec(figure)?.[1] ?? null;
-
-/* The skill is often installed as a symlink, so the path Node was given is resolved before it is compared. */
-if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(here("./build.mjs"))) {
- const [src, out] = process.argv.slice(2);
- if (!src) {
- console.error("usage: node build.mjs <figure.js> [out.html]");
- process.exit(2);
- }
- const figure = readFileSync(src, "utf8");
- const file = resolve(out ?? `hairline-${nameOf(figure) ?? "figure"}.html`);
- writeFileSync(file, assemble(figure));
- console.log(file);
-}
-```
-
-- [ ] **Step 6: Run the unit test to see it pass**
-
-Run: `cd ~/estudos/hairline/packages/hairline && rtk proxy pnpm exec vitest run test/skill/build.test.ts`
-Expected: PASS, 5 tests.
-
-- [ ] **Step 7: Serve the bench to the browser tests**
-
-In `packages/hairline/test/browser/serve.mjs`, add the import under the existing ones:
-
-```js
-import { assemble } from "../../../../skills/hairline-create/build.mjs";
-```
-
-add, above `const routes`:
-
-```js
-/* The skill's bench (skills/hairline-create), with a figure on it: what its agent hands over. */
-const example = (name) => assemble(readFileSync(here(`../../../../skills/hairline-create/examples/${name}.js`), "utf8"));
-const THROWS = `hairline({ name: "throws", means: "A figure that fails at mount.", rules: [5], range: [0, 1, 2], mount() { throw new Error("no drawing today"); } });`;
-```
-
-and add to the `routes` object:
-
-```js
- "/bench/terrain": ["text/html", example("terrain")],
- "/bench/throws": ["text/html", assemble(THROWS)],
-```
-
-Update the file's opening comment to say it also serves the skill's bench.
-
-- [ ] **Step 8: Write the failing browser tests**
-
-Create `packages/hairline/test/browser/skill.spec.ts`:
-
-```ts
-import { expect, test, type Page } from "@playwright/test";
-import { execFileSync } from "node:child_process";
-import { mkdtempSync, readFileSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { fileURLToPath, pathToFileURL } from "node:url";
-import { play } from "../parity/driver.mjs";
-import { INTENSITY, SCRIPTS } from "../parity/scripts.mjs";
-
-/**
- * The skill's bench (skills/hairline-create) with its examples on it: the page
- * an agent hands over. It answers the pointer, its controls reach the figure,
- * and it draws what the package draws, so the extracted kernel is the engine.
- */
-const file = (p: string) => readFileSync(new URL(p, import.meta.url), "utf8");
-const SKILL = fileURLToPath(new URL("../../../../skills/hairline-create/", import.meta.url));
-const clock = file("../parity/clock.js") + "\nwindow.__freeze(1000);";
-
-type Step = Record<string, unknown>;
-type Checkpoint = { at: string; read: string; svg: string };
-/** Each example: a viewBox point that is on the figure, what the slider shows at its two ends, and how much of the package's script it can play. */
-const EXAMPLES = {
- terrain: { at: [200, 160], ends: ["1.5", "5"], steps: (SCRIPTS as Record<string, Step[]>).terrain },
-} as Record<string, { at: [number, number]; ends: [string, string]; steps: Step[] }>;
-
-const svg = (page: Page) => page.locator("#stage > svg").evaluate((el) => el.innerHTML);
-const read = (page: Page) => page.locator("#read").innerText();
-const setIntensity = (page: Page, value: number) => page.locator("#intensity").evaluate((el, value) => {
- (el as HTMLInputElement).value = String(value);
- el.dispatchEvent(new Event("input", { bubbles: true }));
-}, value);
-/** Everything the page complains about. */
-function watch(page: Page) {
- const problems: string[] = [];
- page.on("pageerror", (e) => problems.push(String(e)));
- page.on("console", (m) => { if (m.type() === "error" || m.type() === "warning") problems.push(m.text()); });
- return problems;
-}
-/* a figure sleeps until its IntersectionObserver reports it on screen, and that report comes on the browser's own time */
-const settle = (page: Page) => page.evaluate(() => new Promise((done) => window.__realTimeout(done, 500)));
-
-for (const [id, ex] of Object.entries(EXAMPLES)) {
- test(`${id} answers the pointer and comes back to rest, with nothing on the console`, async ({ page }) => {
- const problems = watch(page);
- await page.goto(`/bench/${id}`);
- const stage = page.locator("#stage");
- await expect(stage.locator("svg > *").first()).toBeAttached();
- await expect(page.locator("#read")).toHaveText("rest");
- await expect(page.locator("#name")).toHaveText(id);
- await expect(page.locator("#means")).not.toBeEmpty();
- await expect(page.locator("#rules")).toHaveText(/^\d\d [a-z]+( · \d\d [a-z]+)*$/);
- const box = (await stage.boundingBox())!;
- expect(box.width / box.height).toBeCloseTo(5 / 4, 2);
- const rest = await svg(page);
-
- await page.mouse.move(box.x + (ex.at[0] / 400) * box.width, box.y + (ex.at[1] / 320) * box.height, { steps: 4 });
- await expect(page.locator("#read")).not.toHaveText("rest");
- await expect.poll(() => svg(page)).not.toBe(rest);
-
- await page.mouse.move(2, 2);
- await expect(page.locator("#read")).toHaveText("rest");
- await expect.poll(() => svg(page), { timeout: 8000 }).toBe(rest);
- expect(problems).toEqual([]);
- });
-
- test(`${id}: the slider reaches the figure`, async ({ context, page }) => {
- await context.addInitScript(clock);
- const drawn = async (value: number) => {
- await page.goto(`/bench/${id}`);
- await page.locator("#stage svg > *").first().waitFor();
- await settle(page);
- const [cp] = await play(page, {
- stage: page.locator("#stage"),
- snap: async () => ({ svg: await svg(page), read: await read(page) }),
- set: () => setIntensity(page, value),
- }, [{ set: true }, { move: ex.at }, { adv: 12 }, { cp: "answering" }]) as Checkpoint[];
- return { svg: cp.svg, value: await page.locator("#value").innerText() };
- };
- const low = await drawn(0), high = await drawn(1);
- expect([low.value, high.value]).toEqual(ex.ends);
- expect(low.svg).not.toBe(high.svg);
- });
-
- test(`${id} on the bench draws what the package draws`, async ({ context, page }) => {
- const golden = (JSON.parse(file(`../parity/golden/${id}.json`)) as { checkpoints: Checkpoint[] }).checkpoints;
- /* the goldens hold Riffle's hidden hit bands and the names the site gives its cards; neither is drawn or said here */
- const strip = (s: string) => s.replace(/<g class="bands">.*?<\/g>/, "");
- const unname = (s: string) => s.replace(/ · .*$/, "");
- await context.addInitScript(clock);
- await page.goto(`/bench/${id}`);
- const stage = page.locator("#stage");
- await stage.locator("svg > *").first().waitFor();
- await settle(page);
-
- const got = await play(page, {
- stage,
- snap: async () => ({ svg: await svg(page), read: await read(page) }),
- set: () => setIntensity(page, (INTENSITY as Record<string, number>)[id]),
- }, ex.steps) as Checkpoint[];
-
- expect(got.length).toBeGreaterThanOrEqual(4);
- for (const [i, have] of got.entries()) {
- expect(have.at).toBe(golden[i].at);
- expect(have.read, `caption at "${have.at}"`).toBe(unname(golden[i].read));
- expect(strip(have.svg), `drawing at "${have.at}"`).toBe(strip(golden[i].svg));
- }
- });
-}
-
-test("the theme switch changes the palette, and wins over the system's theme both ways", async ({ page }) => {
- const stroke = () => page.locator("#stage path.sil").first().evaluate((el) => getComputedStyle(el).stroke);
- await page.goto("/bench/terrain");
- await expect.poll(stroke).toBe("rgb(164, 164, 172)");
- await expect(page.locator("#theme")).toHaveText("light");
- await page.locator("#theme").click();
- await expect.poll(stroke).toBe("rgb(91, 93, 100)");
- await expect(page.locator("body")).toHaveCSS("background-color", "rgb(8, 9, 10)");
- await expect(page.locator("#theme")).toHaveText("dark");
-
- await page.emulateMedia({ colorScheme: "dark" });
- await page.reload();
- await expect.poll(stroke).toBe("rgb(91, 93, 100)");
- await page.locator("#theme").click();
- await expect.poll(stroke).toBe("rgb(164, 164, 172)");
- await expect(page.locator("body")).toHaveCSS("background-color", "rgb(255, 255, 255)");
-});
-
-test("the page fits a 240px screen without scrolling sideways", async ({ page }) => {
- await page.setViewportSize({ width: 240, height: 700 });
- await page.goto("/bench/terrain");
- await expect(page.locator("#stage svg > *").first()).toBeAttached();
- const { scroll, client } = await page.evaluate(() => ({ scroll: document.documentElement.scrollWidth, client: document.documentElement.clientWidth }));
- expect(scroll).toBeLessThanOrEqual(client);
- expect((await page.locator("#stage").boundingBox())!.width).toBeGreaterThan(180);
-});
-
-test("destroy leaves the svg empty", async ({ page }) => {
- await page.goto("/bench/terrain");
- await expect(page.locator("#stage svg > *").first()).toBeAttached();
- await page.evaluate(() => (window as unknown as { hairline: { figure: { destroy(): void } } }).hairline.figure.destroy());
- expect(await page.locator("#stage > svg").evaluate((el) => el.childElementCount)).toBe(0);
-});
-
-test("a figure that throws says so under the stage", async ({ page }) => {
- await page.goto("/bench/throws");
- await expect(page.locator("#error")).toBeVisible();
- await expect(page.locator("#error")).toContainText("no drawing today");
-});
-
-test("the built file draws when opened from disk, narrowed and with the pointer held by its URL", async ({ page }) => {
- const problems = watch(page);
- const out = join(mkdtempSync(join(tmpdir(), "hl-page-")), "hairline-terrain.html");
- execFileSync("node", [SKILL + "build.mjs", SKILL + "examples/terrain.js", out]);
- await page.goto(pathToFileURL(out).href + "?w=240&at=200,160");
- await expect(page.locator("#stage svg > *").first()).toBeAttached();
- await expect(page.locator("#read")).toHaveText(/^cell \d·\d$/);
- expect((await page.locator("#stage").boundingBox())!.width).toBeLessThanOrEqual(240);
- await expect(page).toHaveTitle("Hairline · terrain");
- expect(problems).toEqual([]);
-});
-```
-
-- [ ] **Step 9: Run the browser tests**
-
-Run: `lsof -ti:4310 | xargs kill 2>/dev/null; cd ~/estudos/hairline/packages/hairline && rtk proxy pnpm exec playwright test skill.spec.ts --reporter=line`
-Expected: PASS, 8 tests.
-
-To see them fail first, as TDD asks, run them once before Step 7's routes exist (every `/bench/…` test fails on a 404) and say in your report that you did.
-
-If "draws what the package draws" fails, the example is wrong, not the test: diff `examples/terrain.js` against `packages/hairline/src/figures/terrain.ts`. Do not touch the kernel, the goldens or `src`.
-
-- [ ] **Step 10: Run every suite**
-
-Run: `lsof -ti:4310 | xargs kill 2>/dev/null; cd ~/estudos/hairline && rtk proxy pnpm typecheck && rtk proxy pnpm test && rtk proxy pnpm test:browser`
-Expected: all pass. The package's own browser tests (figures, parity, theme) still pass: `serve.mjs` only gained routes.
-
-- [ ] **Step 11: Commit**
-
-```bash
-cd ~/estudos/hairline && rtk git add skills/hairline-create/bench.html skills/hairline-create/build.mjs skills/hairline-create/examples/terrain.js packages/hairline/test/skill/build.test.ts packages/hairline/test/browser/skill.spec.ts packages/hairline/test/browser/serve.mjs && rtk git commit -m "Skill: the bench and its build script, with Terrain on it drawing what the package draws
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
----
-
-### Task 3: The Riffle example
-
-**Files:**
-- Create: `skills/hairline-create/examples/riffle.js`
-- Modify: `packages/hairline/test/browser/serve.mjs` (one route)
-- Modify: `packages/hairline/test/browser/skill.spec.ts` (one entry in `EXAMPLES`)
-
-**Interfaces:**
-- Consumes: the figure format, `assemble`, the `/bench/<name>` route pattern and the `EXAMPLES` table (Task 2).
-- Produces: `/bench/riffle`; `examples/riffle.js`, at most 200 lines, pointer-only.
-
-- [ ] **Step 1: Add Riffle to the browser tests**
-
-In `packages/hairline/test/browser/skill.spec.ts`, add to `EXAMPLES`, after the `terrain` entry:
-
-```ts
- /* Riffle on the bench has no keyboard, so its script stops where the package's reaches for it */
- riffle: {
- at: [150, 120], ends: ["0", "90"],
- steps: (SCRIPTS as Record<string, Step[]>).riffle.slice(0, (SCRIPTS as Record<string, Step[]>).riffle.findIndex((s) => "focus" in s)),
- },
-```
-
-In `packages/hairline/test/browser/serve.mjs`, add to `routes`:
-
-```js
- "/bench/riffle": ["text/html", example("riffle")],
-```
-
-- [ ] **Step 2: Run to see it fail**
-
-Run: `lsof -ti:4310 | xargs kill 2>/dev/null; cd ~/estudos/hairline/packages/hairline && rtk proxy pnpm exec playwright test skill.spec.ts --reporter=line`
-Expected: the server fails to start with `ENOENT … examples/riffle.js`, so no test runs.
-
-- [ ] **Step 3: Write the example**
-
-Create `skills/hairline-create/examples/riffle.js`. It is `packages/hairline/src/figures/riffle.ts` and `riffle-geometry.ts` in one file, without types and without the keyboard. The arithmetic, and the order and attribute order in which nodes are made, must not change.
-
-```js
-/**
- * Riffle: a rounded tray holding eight cards. The card under the pointer
- * stands up and lifts; the ones in front lean forward and the ones behind lean
- * back, staggered outwards from it on the 700ms lift curve. Each card's number
- * is punched on its tab in a 4 × 2 grid, and goes to the read-out when the
- * card is pulled. The slider is the stagger, in ms.
- *
- * The pattern: discrete items. Tweens, a stagger by distance, identity carried
- * by geometry, and a hit test on static bands along the resting top edges, so
- * a card moving out from under the pointer cannot flip the choice.
- */
-const {
- Cam, clamp, facing, fillet, fit, hull, open, poly, proj, rad, ringAt, rrect, run, seg,
- tdone, tset, tval, tween, disposer, mk, place, pointer, reflect, register,
-} = HL;
-
-const N = 8, W = 84, H = 54, G = 13, TW = 22, TH = 7, TABS = [6, 31, 56], TK = 1.4;
-const REST = -12, BACK = -24, FWD = 20, LIFT = 16;
-const X0 = -5, X1 = W + 5, Y0 = -9, Y1 = (N - 1) * G + 9, WH = 20, WR = 6, WT = 2.4;
-
-/** A run of points ordered left to right on screen. */
-const LR = (pts) => (pts[0][0] <= pts[pts.length - 1][0] ? pts : pts.slice().reverse());
-
-/** The tray, which never moves: `far` is painted before the cards, `near` after them; each entry is [d, class]. */
-function tray(P, front, outer, inner) {
- // far half: body, the rim's inner edge, and the floor seam along the far walls
- const far = [
- [poly(hull(ringAt(P, outer, 0).concat(ringAt(P, outer, WH)))), "sil"],
- [poly(ringAt(P, inner, WH)), "nf"],
- [open(ringAt(P, run(inner, (q) => !front(q)), 2.5)), "nf lo"],
- ];
- // near half: one opaque piece from the rim's inner edge down to the floor
- const iF = LR(ringAt(P, run(inner, front), WH)), oT = LR(ringAt(P, run(outer, front), WH)), oB = LR(ringAt(P, run(outer, front), 0));
- // a finger pull, set into the front
- const hx = (X0 + X1) / 2, onFront = (ring) => ring.map((q) => P(q.u, Y1, q.v));
- const near = [
- [poly([...iF, oT[oT.length - 1], ...oB.slice().reverse(), oT[0]]), "fo"],
- [open(oT), "nf lo"],
- [open(iF), "nf"],
- [open([oT[0], ...oB, oT[oT.length - 1]]), "nf sil"],
- [poly(onFront(rrect(hx - 11, 6.5, hx + 11, 12.5, 3, 5))), "nf"],
- [poly(onFront(rrect(hx - 9.4, 8, hx + 9.4, 11, 1.5, 5))), "nf lo"],
- ];
- return { far, near };
-}
-
-/** Card i, back to front: its number (8 at the back), which of three tab positions it takes, and its filleted outline, upright in its own plane. */
-function card(i) {
- const n = N - i, t0 = TABS[(N - 1 - i) % 3];
- const shape = fillet(
- [[0, 0], [W, 0], [W, H], [t0 + TW, H], [t0 + TW, H + TH], [t0, H + TH], [t0, H], [0, H]],
- [1, 1, 3.2, 1.8, 2.4, 2.4, 1.8, 3.2],
- );
- return { n, t0, shape };
-}
-
-/** Card i leaning th degrees (negative leans back) and lifted by `lift`: its paths, and where its eight punches sit. */
-function pose(P, i, t0, shape, th, lift) {
- const yb = i * G, s = Math.sin(rad(th)), c = Math.cos(rad(th));
- const w = (u, v) => P(u, yb + v * s, v * c + lift);
- const wb = (u, v) => P(u, yb + v * s - TK * c, v * c + TK * s + lift);
- const punch = [];
- for (let k = 0; k < 8; k++) punch.push(w(t0 + TW / 2 + ((k % 4) - 1.5) * 3.6, H + TH / 2 + (0.5 - Math.floor(k / 4)) * 2.8));
- return {
- back: poly(shape.map((p) => wb(p[0], p[1]))),
- face: poly(shape.map((p) => w(p[0], p[1]))),
- head: seg(w(6, H - 11), w(W - 6, H - 11)),
- rules: [H - 18, H - 25, H - 32, H - 39].map((v) => seg(w(6, v), w(W - 6, v))).join(""),
- punch,
- };
-}
-
-function mount({ stage, svg, read }, value) {
- const bag = disposer();
- let stag = value;
-
- // The camera is fitted to the tray with a card lifted, so nothing leaves the frame in any pose.
- const C = Cam(45, 0.5, 1.62);
- fit(C, [[X0, Y0, 0], [X1, Y1, -8], [X1, Y0, 0], [X0, Y1, 0], [X0, Y0, H + TH], [X1, Y0, H + TH + LIFT]], 200, 166);
- const P = proj(C), front = facing(C);
- const outer = rrect(X0, Y0, X1, Y1, WR, 6), inner = rrect(X0 + WT, Y0 + WT, X1 - WT, Y1 - WT, WR - WT, 6);
- const paths = tray(P, front, outer, inner);
-
- const g = mk("g", {}, svg);
- reflect(svg, g, P, front, outer, 0, 14);
- for (const [d, cls] of paths.far) mk("path", { d, class: cls }, g);
-
- const cards = [];
- for (let i = 0; i < N; i++) {
- const { n, t0, shape } = card(i);
- const grp = mk("g", {}, g);
- const back = mk("path", { class: "lo" }, grp), face = mk("path", { class: "sil" }, grp);
- const head = mk("path", { class: "nf" }, grp), rules = mk("path", { class: "nf lo" }, grp);
- // the card's number, punched in a 4 × 2 grid on its tab
- const punch = [];
- for (let k = 0; k < 8; k++) punch.push(mk("circle", { r: 1.05, class: "dot " + (k === n - 1 ? "m" : "off") }, grp));
- cards.push({ n, t0, shape, back, face, head, rules, punch, a: tween(REST), z: tween(0) });
- }
-
- for (const [d, cls] of paths.near) mk("path", { d, class: cls }, g);
-
- // hit bands: oblique strips along the RESTING top edges. They never move, and nothing draws them.
- const top = (i) => P(W / 2, i * G + H * Math.sin(rad(REST)), H * Math.cos(rad(REST)));
- const c0 = top(0), c1 = top(1), d = [c1[0] - c0[0], c1[1] - c0[1]];
- const px0 = P(0, 0, 0), px1 = P(1, 0, 0), ex = [px1[0] - px0[0], px1[1] - px0[1]];
- const HALF = W / 2 + 6, det = d[0] * ex[1] - d[1] * ex[0];
-
- /** The card whose band holds the point, in the band's own (s, r) coordinates; -1 outside. */
- function hit([x, y]) {
- const qx = x - c0[0], qy = y - c0[1];
- const s = (qx * ex[1] - qy * ex[0]) / det, r = (d[0] * qy - d[1] * qx) / det;
- if (Math.abs(r) > HALF || s < -0.5 || s > N + 1) return -1;
- return clamp(Math.round(s), 0, N - 1);
- }
-
- function draw(i, th, lift) {
- const cd = cards[i], q = pose(P, i, cd.t0, cd.shape, th, lift);
- cd.back.setAttribute("d", q.back);
- cd.face.setAttribute("d", q.face);
- cd.head.setAttribute("d", q.head);
- cd.rules.setAttribute("d", q.rules);
- cd.punch.forEach((el, k) => place(el, q.punch[k]));
- }
-
- const B = register(stage, (_dt, now) => {
- let moving = false;
- cards.forEach((cd, i) => { draw(i, tval(cd.a, now), tval(cd.z, now)); if (!tdone(cd.a, now) || !tdone(cd.z, now)) moving = true; });
- return moving;
- });
- bag.add(B.unregister);
-
- let act = -1;
- const caption = (a) => (a < 0 ? "rest" : String(N - a).padStart(2, "0"));
- /** Pulls card a (-1 puts them all back). The stagger spreads out from the card pulled, or the one let go. */
- function setActive(a) {
- if (a === act) return;
- const now = performance.now(), from = a >= 0 ? a : act;
- act = a;
- cards.forEach((cd, i) => {
- const delay = Math.abs(i - from) * stag;
- const th = a < 0 ? REST : i < a ? BACK : i > a ? FWD : 0;
- tset(cd.a, th, now, delay); tset(cd.z, a === i ? LIFT : 0, now, delay);
- cd.face.classList.toggle("hi", i === a); cd.head.classList.toggle("hi", i === a); cd.punch[cd.n - 1].classList.toggle("m", i !== a);
- });
- read.textContent = caption(a);
- B.wake();
- }
-
- bag.add(pointer(stage, { move: (p) => setActive(hit(p)), leave: () => setActive(-1) }));
- bag.add(() => svg.replaceChildren());
-
- return {
- set: (v) => { stag = v; },
- destroy: bag.dispose,
- };
-}
-
-hairline({
- name: "riffle",
- means: "Eight cards in a tray: the one under the pointer stands up, and its neighbours lean away in turn.",
- rules: [1, 2, 8, 10],
- range: [0, 40, 90],
- mount,
-});
-```
-
-- [ ] **Step 4: Check its length**
-
-Run: `cd ~/estudos/hairline && rtk proxy wc -l skills/hairline-create/examples/riffle.js`
-Expected: 200 or fewer. If it is over, shorten comments, never code.
-
-- [ ] **Step 5: Run the browser tests to see them pass**
-
-Run: `lsof -ti:4310 | xargs kill 2>/dev/null; cd ~/estudos/hairline/packages/hairline && rtk proxy pnpm exec playwright test skill.spec.ts --reporter=line`
-Expected: PASS, 11 tests (three per example, five on the bench itself).
-
-If "riffle on the bench draws what the package draws" fails on a caption, print `golden[i].read` and `have.read`; the package's own parity test (`parity.spec.ts`) shows how the site's captions are reduced. If it fails on the drawing, diff the example against the two source files.
-
-- [ ] **Step 6: Run every suite, then commit**
-
-Run: `lsof -ti:4310 | xargs kill 2>/dev/null; cd ~/estudos/hairline && rtk proxy pnpm typecheck && rtk proxy pnpm test && rtk proxy pnpm test:browser`
-Expected: all pass.
-
-```bash
-cd ~/estudos/hairline && rtk git add skills/hairline-create/examples/riffle.js packages/hairline/test/browser/serve.mjs packages/hairline/test/browser/skill.spec.ts && rtk git commit -m "Skill: Riffle as the second example, the discrete pattern beside Terrain's continuous one
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
----
-
-### Task 4: The validator
-
-**Files:**
-- Create: `skills/hairline-create/validate.mjs`
-- Create: `packages/hairline/test/skill/validate.test.ts`
-
-**Interfaces:**
-- Consumes: `assemble(figure)` from `./build.mjs`; `kernel.js`'s first-line hash; the figure format; the slot markup `<script type="module" id="hl-figure">\n…\n</script>` that `assemble` writes (Tasks 1 and 2).
-- Produces:
- - `export function validate(page: string): string[]`: the problems, each one line of the form `<id>: <what to fix>`, with `id` one of `kernel bench text paint outside clock hit readout handle declare length`.
- - CLI `node validate.mjs <page.html>`: exit 0 and `ok <file>: …` on stdout; exit 1 with the problems and `<n> to fix in <file>` on stderr; exit 2 on a missing argument or an unreadable file.
-
-- [ ] **Step 1: Write the failing test**
-
-Create `packages/hairline/test/skill/validate.test.ts`:
-
-```ts
-import { execFileSync, spawnSync } from "node:child_process";
-import { mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { fileURLToPath } from "node:url";
-import { describe, expect, it } from "vitest";
-
-/**
- * validate.mjs passes the two examples and fails a page broken in one way,
- * naming that way and no other. The broken pages are Terrain with one change.
- */
-const SKILL = fileURLToPath(new URL("../../../../skills/hairline-create/", import.meta.url));
-const dir = mkdtempSync(join(tmpdir(), "hl-validate-"));
-const terrain = readFileSync(SKILL + "examples/terrain.js", "utf8");
-let n = 0;
-
-/** Builds a figure's page, changes the page if asked, and validates it. */
-function check(figure: string, change?: (page: string) => string, script = SKILL + "validate.mjs") {
- const src = join(dir, `f${++n}.js`), out = join(dir, `f${n}.html`);
- writeFileSync(src, figure);
- execFileSync("node", [SKILL + "build.mjs", src, out]);
- if (change) writeFileSync(out, change(readFileSync(out, "utf8")));
- const run = spawnSync("node", [script, out], { encoding: "utf8" });
- return { status: run.status, out: run.stdout, err: run.stderr };
-}
-/** Terrain with a line of code just before its declaration. */
-const plus = (code: string) => terrain.replace("hairline({", () => `${code}\nhairline({`);
-
-describe("pages that pass", () => {
- for (const name of ["terrain", "riffle"]) {
- it(`the ${name} example`, () => {
- const figure = readFileSync(`${SKILL}examples/${name}.js`, "utf8");
- expect(figure.trim().split("\n").length).toBeLessThanOrEqual(200);
- const run = check(figure);
- expect(run.err).toBe("");
- expect(run.status).toBe(0);
- expect(run.out).toMatch(/^ok .*kernel and bench intact/);
- });
- }
-
- it("a page saved with CRLF line endings", () => {
- expect(check(terrain, (page) => page.replace(/\n/g, "\r\n")).status).toBe(0);
- });
-
- it("a range that falls, as Slow's does", () => {
- expect(check(terrain.replace("range: [1.5, 3, 5]", "range: [5, 3, 1.5]")).status).toBe(0);
- });
-
- it("through a symlink to the skill folder", () => {
- const link = join(dir, "linked");
- symlinkSync(SKILL, link);
- const run = check(terrain, undefined, join(link, "validate.mjs"));
- expect(run.status).toBe(0);
- expect(run.out).toMatch(/^ok /);
- });
-});
-
-const BROKEN: [id: string, why: string, figure: string, change?: (page: string) => string][] = [
- ["kernel", "the kernel was edited", terrain, (page) => page.replace("var HL = ", "var HL = /* mine */ ")],
- ["bench", "the bench was edited", terrain, (page) => page.replace("</main>", "<p>better</p></main>")],
- ["text", "a text element", plus('mk("text", {}, document.querySelector("svg"));')],
- ["text", "markup written as a string", plus('document.querySelector("svg").innerHTML = "";')],
- ["paint", "a fill of its own", plus('mk("path", { fill: "red" });')],
- ["paint", "a stroke width of its own", plus('mk("path", { "stroke-width": 2 });')],
- ["paint", "an inline style", plus('document.body.style.background = "#000";')],
- ["outside", "a fetch", plus('fetch("https://example.com/data.json");')],
- ["outside", "a node made by hand", plus('document.createElementNS("http://www.w3.org/2000/svg", "path");')],
- ["outside", "a script tag in a string", plus('const s = "</script>";')],
- ["clock", "its own frame", plus("requestAnimationFrame(() => {});")],
- ["clock", "its own timer", plus("setTimeout(() => {}, 100);")],
- ["clock", "no kernel loop", terrain.replace("register(stage,", "((s, t) => ({ wake() {}, unregister() {} }))(stage,")],
- ["hit", "a box measured on screen", plus("stage.getBoundingClientRect();")],
- ["hit", "its own listener", plus('stage.addEventListener("pointermove", () => {});')],
- ["hit", "no pointer", terrain.replace("bag.add(pointer(stage,", "bag.add(((s, h) => () => {})(stage,")],
- ["readout", "no read-out", terrain.replace(/read\.textContent = [^;]+;/g, "")],
- ["handle", "no destroy", terrain.replace("destroy: bag.dispose", "stop: bag.dispose")],
- ["declare", "no means", terrain.replace(/\n {2}means: .*\n/, "\n")],
- ["declare", "a range that turns back", terrain.replace("range: [1.5, 3, 5]", "range: [1.5, 5, 3]")],
- ["declare", "a rule that does not exist", terrain.replace("rules: [1, 3, 5, 9]", "rules: [1, 11]")],
- ["declare", "no declaration", terrain.replace(/hairline\(\{[\s\S]*$/, "")],
- ["length", "over 200 lines", plus(Array.from({ length: 200 }, (_, i) => `const pad${i} = ${i};`).join("\n"))],
-];
-
-describe("pages that fail, each for its own reason", () => {
- for (const [id, why, figure, change] of BROKEN) {
- it(`${id}: ${why}`, () => {
- const run = check(figure, change);
- expect(run.status).toBe(1);
- const ids = run.err.split("\n").map((line) => /^([a-z]+): /.exec(line)?.[1]).filter(Boolean);
- expect(ids.length).toBeGreaterThan(0);
- expect([...new Set(ids)]).toEqual([id]);
- expect(run.err).toMatch(/\d+ to fix in /);
- });
- }
-});
-
-it("says how to call it when it is given nothing, and when the file is not there", () => {
- const none = spawnSync("node", [SKILL + "validate.mjs"], { encoding: "utf8" });
- expect(none.status).toBe(2);
- expect(none.stderr).toContain("usage: node validate.mjs <page.html>");
- const gone = spawnSync("node", [SKILL + "validate.mjs", join(dir, "nope.html")], { encoding: "utf8" });
- expect(gone.status).toBe(2);
- expect(gone.stderr).toContain("cannot read");
-});
-```
-
-- [ ] **Step 2: Run it to see it fail**
-
-Run: `cd ~/estudos/hairline/packages/hairline && rtk proxy pnpm exec vitest run test/skill/validate.test.ts`
-Expected: FAIL. Every test fails because `validate.mjs` does not exist: `status` is 1 with Node's `Cannot find module` on stderr, so the passing cases fail on `err` and the broken ones on the ids.
-
-- [ ] **Step 3: Write the validator**
-
-Create `skills/hairline-create/validate.mjs`:
-
-```js
-#!/usr/bin/env node
-/**
- * Checks a page made by build.mjs: `node validate.mjs hairline-<name>.html`.
- * It prints what to fix and exits 1, or prints `ok` and exits 0. The checks
- * read the text of the file, so they catch what is mechanical; the look
- * (look.md) catches the rest. Each line it prints starts with the check's name:
- *
- * kernel the kernel in the page is this folder's kernel.js, untouched
- * bench nothing but the figure differs from bench.html
- * text no words inside the figure (rule 10)
- * paint no stroke width, colour, fill, filter or shadow of its own (rule 04)
- * outside nothing loaded or reached outside the file; every node from HL.mk
- * clock no timers or frames of its own; it joins HL.register (rule 07)
- * hit input only through HL.pointer; nothing measured on screen (rule 01)
- * readout it writes read.textContent
- * handle mount returns { set, destroy }
- * declare the file ends with hairline({ name, means, rules, range, mount })
- * length at most 200 lines
- */
-import { createHash } from "node:crypto";
-import { readFileSync, realpathSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { assemble } from "./build.mjs";
-
-const here = (p) => fileURLToPath(new URL(p, import.meta.url));
-const LIMIT = 200;
-const unix = (s) => s.replace(/\r\n/g, "\n");
-/** A figure's source without its comments, so its prose is never read as code. A `//` after a colon or inside a quote is kept: it is a URL. */
-const bare = (src) => src.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:\\"'`])\/\/.*$/gm, "$1");
-
-/** What a figure must not contain. */
-const BAD = [
- ["text", /<\s*(?:text|tspan|textPath|foreignObject)\b|["'`](?:text|tspan|textPath|foreignObject)["'`]|\b(?:innerHTML|outerHTML|insertAdjacentHTML|innerText)\b/,
- "rule 10. No words inside the figure, and no markup written as a string. Say it with geometry (a punch, a dot code, a bright edge); names go to read.textContent."],
- ["paint", /stroke-width|strokeWidth|stroke-dasharray|["'`](?:fill|stroke|filter|style|color|stop-color)["'`]|\b(?:fill|stroke|filter|style)\s*:|\.style\b|#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|oklch|oklab|color-mix)\(|drop-shadow|box-shadow|feDropShadow|feGaussianBlur|[Gg]radient/,
- "rule 04. The figure sets a stroke width, colour, fill, filter, gradient or shadow of its own. Use the kernel's classes and nothing else: sil, hi, lo, nf, fo, dash, dot, dot m, dot off."],
- ["outside", /\bfetch\s*\(|\bimport\b|XMLHttpRequest|WebSocket|EventSource|sendBeacon|https?:\/\/|\burl\(|<\/?script|<(?:link|img|iframe|style)\b|new\s+Image\b|createElement|\beval\s*\(|new\s+Function\b|localStorage|sessionStorage|\.cookie\b/,
- "the figure reaches outside the file or makes nodes by hand. One self-contained file: no fetch, import, URL, script tag or storage, and every node comes from HL.mk."],
- ["clock", /\bsetInterval\b|\bsetTimeout\b|\brequestAnimationFrame\b|\.animate\s*\(|<animate|IntersectionObserver|\bmatchMedia\b/,
- "rule 07. The figure runs a clock of its own. Move inside HL.register(stage, tick), with springs (stepS) or tweens (tset, tval); a delay is a tween's delay. The loop sleeps offscreen and honours reduced motion for you."],
- ["hit", /getBoundingClientRect|elementFromPoint|elementsFromPoint|:hover|(?:addEventListener|\.on)\s*\(\s*(?:\w+\s*,\s*)?["'`](?:mouse|pointer|touch|click)|\bon(?:mouse|pointer|touch|click)\w*\s*=/,
- "rule 01. The figure listens to the pointer itself or measures what is on screen. Take the pointer from HL.pointer(stage, { move, leave }) and test it against the rest or target pose, in world units."],
-];
-
-/** What a figure must contain. */
-const NEED = [
- ["clock", /\bregister\s*\(/, "rule 07. The figure never joins the kernel's loop. Draw inside HL.register(stage, tick), and give its unregister to destroy."],
- ["hit", /\bpointer\s*\(/, "the figure never listens to the pointer. Call HL.pointer(stage, { move, leave }) and answer it."],
- ["readout", /\bread\.textContent\s*=/, 'the figure never writes the read-out. Set read.textContent to what is under the pointer, and to "rest" when nothing is.'],
- ["handle", /\bset\s*[:(]/, "mount must return { set(value), destroy() }, and set is missing. It takes the slider's number."],
- ["handle", /\bdestroy\s*[:(]/, "mount must return { set(value), destroy() }, and destroy is missing. It undoes everything mount did: bag.dispose."],
-];
-
-/** The declaration at the end of the file, read as text. */
-function declared(code) {
- const say = (what) => `declare: the file must end with hairline({ name, means, rules, range, mount }). ${what}`;
- const m = /\bhairline\s*\(\s*\{([\s\S]*?)\}\s*\)\s*;?\s*$/.exec(code.trimEnd());
- if (!m) return [say("That call is missing, or is not the last statement.")];
- const d = m[1], wrong = [];
- const list = (key) => {
- const a = new RegExp(`\\b${key}:\\s*\\[([^\\]]*)\\]`).exec(d);
- return a ? a[1].split(",").map((s) => s.trim()).filter(Boolean).map(Number) : null;
- };
- if (!/\bname:\s*(["'`])[a-z][a-z0-9-]{1,30}\1/.test(d)) wrong.push("name (lowercase letters, digits and hyphens)");
- if (!/\bmeans:\s*(["'`])(?:(?!\1).){1,140}\1/.test(d)) wrong.push("means (one sentence, at most 140 characters)");
- const rules = list("rules"), range = list("range");
- if (!rules || !rules.length || rules.some((r) => !Number.isInteger(r) || r < 1 || r > 10)) wrong.push("rules (the numbers, 1 to 10, of the rules it leans on)");
- const oneWay = range && range.length === 3 && range.every(Number.isFinite) && range[0] !== range[2] && (range[1] - range[0]) * (range[2] - range[1]) >= 0;
- if (!oneWay) wrong.push("range (three numbers that move one way: the figure's value at intensity 0, 0.5 and 1)");
- if (!/\bmount\b/.test(d)) wrong.push("mount");
- return wrong.length ? [say(`Wrong or missing: ${wrong.join("; ")}.`)] : [];
-}
-
-/** Everything wrong with a page, one line each; empty when it passes. */
-export function validate(input) {
- const page = unix(input), out = [];
-
- const kernel = unix(readFileSync(here("./kernel.js"), "utf8")).trimEnd();
- const cut = kernel.indexOf("\n");
- const hash = /sha256:([0-9a-f]{64})/.exec(kernel.slice(0, cut))?.[1];
- if (hash !== createHash("sha256").update(kernel.slice(cut + 1) + "\n").digest("hex")) {
- out.push("kernel: kernel.js in the skill folder has been edited. Install the skill again; the kernel is never changed by hand.");
- }
-
- const fig = /<script type="module" id="hl-figure">\n([\s\S]*?)\n<\/script>/.exec(page);
- if (!fig) return [...out, "bench: the page has no figure slot. Make it with `node build.mjs <figure.js>`, not by hand."];
- if (!page.includes(kernel)) {
- out.push("kernel: the kernel in the page is not kernel.js. Build again with `node build.mjs`; never edit or retype the kernel.");
- } else if (page.trimEnd() !== assemble(fig[1]).trimEnd()) {
- out.push("bench: the page differs from bench.html outside the figure. Build again with `node build.mjs`; the bench is fixed, and a change belongs in the figure.");
- }
-
- const src = fig[1], code = bare(src);
- for (const [id, re, say] of BAD) if (re.test(code)) out.push(`${id}: ${say}`);
- for (const [id, re, say] of NEED) if (!re.test(code)) out.push(`${id}: ${say}`);
- out.push(...declared(code));
- const lines = src.split("\n").length;
- if (lines > LIMIT) out.push(`length: the figure is ${lines} lines and the limit is ${LIMIT}. A figure this long is usually two ideas: cut the concept down to one.`);
- return out;
-}
-
-/* The skill is often installed as a symlink, so the path Node was given is resolved before it is compared. */
-if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(here("./validate.mjs"))) {
- const file = process.argv[2];
- if (!file) {
- console.error("usage: node validate.mjs <page.html>");
- process.exit(2);
- }
- let page;
- try { page = readFileSync(file, "utf8"); } catch {
- console.error(`cannot read ${file}`);
- process.exit(2);
- }
- const problems = validate(page);
- if (problems.length) {
- for (const p of problems) console.error(p);
- console.error(`${problems.length} to fix in ${file}`);
- process.exit(1);
- }
- console.log(`ok ${file}: kernel and bench intact, and the figure passes the static checks. Now the look: look.md.`);
-}
-```
-
-- [ ] **Step 4: Run the test to see it pass**
-
-Run: `cd ~/estudos/hairline/packages/hairline && rtk proxy pnpm exec vitest run test/skill/validate.test.ts`
-Expected: PASS, 29 tests (5 passing pages, 23 broken ones, 1 usage).
-
-A broken case that reports a second id means one of the patterns is too wide or the mutation trips two checks. Fix the pattern if it would also misfire on honest code; otherwise change the mutation in the test and say so in your report. Do not loosen a pattern until the examples pass by accident.
-
-- [ ] **Step 5: Run every suite, then commit**
-
-Run: `cd ~/estudos/hairline && rtk proxy pnpm typecheck && rtk proxy pnpm test`
-Expected: all pass.
-
-```bash
-cd ~/estudos/hairline && rtk git add skills/hairline-create/validate.mjs packages/hairline/test/skill/validate.test.ts && rtk git commit -m "Skill: the validator, which rejects a changed kernel or bench and a figure that breaks a mechanical rule
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
----
-
-### Task 5: The skill's words
-
-**Files:**
-- Create: `skills/hairline-create/SKILL.md`
-- Create: `skills/hairline-create/rules.md`
-- Create: `skills/hairline-create/concepts.md`
-- Create: `skills/hairline-create/look.md`
-- Create: `packages/hairline/test/skill/shape.test.ts`
-- Modify: `CONTRIBUTING.md` (layout and commands)
-- Modify: `docs/superpowers/specs/2026-10-01-hairline-create-skill-design.md` (the five additions)
-
-**Interfaces:**
-- Consumes: the file names, the CLI of `build.mjs` and `validate.mjs`, the check names, the bench's `?w` and `?at` parameters, the rule names in the bench's `RULES` (Tasks 1–4).
-- Produces: the skill as an agent reads it. The four files below are written by the architect; transcribe them exactly. If something in them contradicts the code, stop and report it instead of rewording.
-
-- [ ] **Step 1: Write the failing test**
-
-Create `packages/hairline/test/skill/shape.test.ts`:
-
-```ts
-import { existsSync, readdirSync, readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { expect, it } from "vitest";
-
-/** The skill folder is what an agent installs: these hold its shape. */
-const SKILL = fileURLToPath(new URL("../../../../skills/hairline-create/", import.meta.url));
-const FILES = ["SKILL.md", "bench.html", "build.mjs", "concepts.md", "examples/riffle.js", "examples/terrain.js", "kernel.js", "look.md", "rules.md", "validate.mjs"];
-const text = (p: string) => readFileSync(SKILL + p, "utf8");
-
-it("holds exactly its ten files", () => {
- const found = (readdirSync(SKILL, { recursive: true, withFileTypes: true }) as import("node:fs").Dirent[])
- .filter((e) => e.isFile())
- .map((e) => (e.parentPath + "/" + e.name).slice(SKILL.length).replace(/^\//, ""));
- expect(found.sort()).toEqual(FILES);
-});
-
-it("SKILL.md opens with a name that is its folder's and a description that says when to use it", () => {
- const m = /^---\nname: (.+)\ndescription: (.+)\nargument-hint: (.+)\n---\n/.exec(text("SKILL.md"));
- expect(m).not.toBeNull();
- expect(m![1]).toBe("hairline-create");
- expect(m![2]).toMatch(/^Use when /);
- expect(m![2].length).toBeLessThanOrEqual(1024);
- expect(text("SKILL.md").split("\n").length).toBeLessThan(120);
-});
-
-it("SKILL.md points to every other file, and to none that is not there", () => {
- const skill = text("SKILL.md");
- for (const f of FILES.filter((f) => f !== "SKILL.md")) expect(skill, f).toContain(f);
- for (const [, f] of skill.matchAll(/`([\w./-]+\.(?:md|mjs|js|html))`/g)) expect(existsSync(SKILL + f), f).toBe(true);
-});
-
-it("rules.md has the ten rules, named as the bench names them", () => {
- const names = [...text("rules.md").matchAll(/^## (\d\d) · (\w+)/gm)].map((m) => `${m[1]} ${m[2]}`);
- const bench = /const RULES = (\[[^\]]+\]);/.exec(text("bench.html"))![1];
- expect(names).toEqual((JSON.parse(bench) as string[]).map((name, i) => `${String(i + 1).padStart(2, "0")} ${name}`));
-});
-
-it("look.md and SKILL.md name the validator's checks and the bench's parameters as they are", () => {
- expect(text("look.md")).toContain("?w=240");
- expect(text("look.md")).toContain("at=");
- for (const id of ["kernel", "bench", "text", "paint", "outside", "clock", "hit", "readout", "handle", "declare", "length"]) {
- expect(text("validate.mjs"), id).toMatch(new RegExp(`^ \\* {3}${id} `, "m"));
- }
-});
-```
-
-- [ ] **Step 2: Run it to see it fail**
-
-Run: `cd ~/estudos/hairline/packages/hairline && rtk proxy pnpm exec vitest run test/skill/shape.test.ts`
-Expected: FAIL. "holds exactly its ten files" lists six; the others fail with `ENOENT`.
-
-- [ ] **Step 3: Write `SKILL.md`**
-
-Create `skills/hairline-create/SKILL.md`:
-
-````markdown
----
-name: hairline-create
-description: Use when someone asks for a new Hairline figure, or runs /hairline-create with an idea. Draws one isometric line figure that answers the pointer, in the style and on the engine of @lucasmarkes/hairline, and hands it over as a single self-contained HTML file.
-argument-hint: "[idea]"
----
-
-# Hairline: create a figure
-
-You are making one figure in the Hairline style: an isometric line drawing, built from rounded solids in a single stroke, that answers the pointer. It ships as one HTML file with nothing to install. The six figures of `@lucasmarkes/hairline` are the bar; `examples/terrain.js` and `examples/riffle.js` are two of them, in the format you will write.
-
-You write one thing: the figure. The engine (`kernel.js`) and the page (`bench.html`) are fixed. Never edit them, never paste a changed copy of them, and never write again what the kernel already gives you.
-
-Every path below is in this skill's folder.
-
-## 1. Concept
-
-Read `concepts.md`. Then offer two or three concepts, one line each:
-
-> **Name.** The object. What the pointer does to it. What the read-out says.
-
-Wait for the person to pick. Skip this step only when they arrived with the object and the gesture already chosen. If there is nobody to ask, take the concept with the strongest rest pose and say which you took.
-
-One figure, one idea. A concept that needs a label to be understood is not a concept yet.
-
-## 2. Build
-
-1. Read `rules.md`. The ten rules are not advice: a figure that breaks one is not finished.
-2. Read the index at the top of `kernel.js`: the first comment, down to `var HL`. It lists everything you may call. Do not read the code under it.
-3. Read the example nearer your concept: `examples/terrain.js` for a continuous field, `examples/riffle.js` for discrete items.
-4. Write the figure as `<name>.js` in the person's working directory, in the shape of the examples: take what you need from `HL`, define `mount({ stage, svg, read }, value)` returning `{ set, destroy }`, and end the file with `hairline({ name, means, rules, range, mount })`.
- - `name`: lowercase, one word or hyphenated.
- - `means`: one sentence saying what the figure shows. It is the line under the stage.
- - `rules`: the numbers of the rules this figure leans on most.
- - `range`: the one number the slider drives, at intensity 0, 0.5 and 1. The middle one is the default, and the three move one way.
-5. Assemble it: `node build.mjs <name>.js` writes `hairline-<name>.html`. Without Node, copy `bench.html` and put the contents of `kernel.js` where `/*KERNEL*/` is and your figure where `/*FIGURE*/` is, by file operation, changing nothing else.
-
-## 3. Check
-
-1. `node validate.mjs hairline-<name>.html`. Fix every line it prints, build again, run it again. Without Node, read the list of checks at the top of `validate.mjs` and answer each one from your code.
-2. The look: follow `look.md`. Fix what fails, then go back to 1.
-
-Do not hand over a page the validator rejects. Do not say the look is done if you did not look.
-
-## 4. Hand over
-
-Publish `hairline-<name>.html` as an artifact if you can. If you cannot, leave the file where the person can open it and say where it is. Then say, one line each:
-
-- the metaphor: what the object is, and what the pointer does to it;
-- the rules it leans on;
-- anything you could not verify (no Node, no browser), plainly.
-
-## 5. Adjust
-
-When the person asks for a change, edit only `<name>.js`, then build, validate and look again. The tenth version is held to the same bar as the first.
-
-## What goes wrong
-
-| If you catch yourself | Do this instead |
-| --- | --- |
-| adding a label, a number or a letter to the drawing | say it with geometry (rule 10); names go to `read.textContent` |
-| reaching for a colour, a fill or a glow | move one stroke from `sil` to `hi` (rule 04) |
-| writing a timer, a `requestAnimationFrame` or a CSS animation | `register(stage, tick)`, with springs or tweens (rules 07 and 08) |
-| testing the pointer against what is drawn right now | test it against the rest or target pose (rule 01) |
-| drawing a box with twelve edges | `prism` of two rounded rings: a silhouette and one crease (rule 09) |
-| leaving rest flat, empty, or symmetric because that was easy | compose it: rest is the thumbnail (rule 05) |
-| editing the kernel or the bench to make something work | the figure is wrong; change the figure |
-| letting in a second idea | cut it: one figure, one idea |
-````
-
-- [ ] **Step 4: Write `rules.md`**
-
-Create `skills/hairline-create/rules.md`:
-
-````markdown
-# The ten rules
-
-They come from the study behind the package (lucasmarkes.com/lab/hairline). Each has what it says, how to keep it with the kernel, and what gets a figure rejected.
-
-## 01 · hit: hit areas don't move
-
-Test the pointer against the rest pose, or the target pose, never the pose on screen. Otherwise the geometry lifts out from under the pointer, the hover drops, the geometry falls back, and the hover returns: a flicker loop.
-
-- **Keep it:** `unproj(C, sx, sy, 0)` puts the pointer on the ground plane, which never moves; pick by world coordinates (Terrain). For items, test static bands along their resting edges (Riffle). When a choice depends on a moving value, read the spring's target (`.t`), not its position (`.x`).
-- **Rejected when:** the pointer held still on a moving edge makes the figure oscillate; picking reads a spring's current value; the figure measures the DOM (`getBoundingClientRect`, `elementFromPoint`, `:hover`) or adds its own pointer listeners.
-
-## 02 · order: stagger by distance
-
-`delay = |i − a| × step`. The motion spreads out from the pointer instead of running down a list.
-
-- **Keep it:** `tset(tween, target, now, Math.abs(i - a) * step)`, with a step of 30–60ms so it reads as one gesture.
-- **Rejected when:** items move in index order whatever was touched; all move at once when the concept is a spread; a step so long the last item starts after the first has landed and the gesture reads as a queue.
-
-## 03 · reach: clamp the reach
-
-The answer has a far end, and the figure is still composed there.
-
-- **Keep it:** a falloff that reaches a floor (Terrain's is 1 → .31 at 42% of the radius → .09 beyond); `clamp` every lift, gap and lean; fit the camera to the most extreme pose (`fit` with the lifted points), so nothing leaves the 400 × 320 frame at intensity 1.
-- **Rejected when:** at the slider's far end the figure comes apart, overlaps itself or leaves the frame; an unclamped value follows the pointer without limit.
-
-## 04 · accent: the stroke is the only highlight
-
-No fills, glows or shadows. The active edge goes from the silhouette's stroke to the bright one and nothing else changes colour, so the colour reads as information.
-
-- **Keep it:** `el.sil.classList.toggle("hi", active)`. Dots change between `dot`, `dot m` and `dot off`. That is the whole palette.
-- **Rejected when:** the figure sets any colour, fill, opacity trick, gradient, filter, shadow or stroke width of its own; more than one thing is bright without each meaning something; highlight is used as decoration.
-
-## 05 · rest: rest is designed, never flat
-
-Leaving returns the figure to a composition: a dune, a lean, a slight explode. The still frame is the thumbnail, so it has to hold up alone.
-
-- **Keep it:** give every part a rest value that is not zero and not uniform (Terrain's dune is two Gaussians; Riffle's cards lean back 12°). Put one bright mark at rest where the eye should start.
-- **Rejected when:** at rest the figure is a flat grid, an empty tray, a perfectly regular row; at rest nothing says what the figure is about; rest and "nothing rendered yet" look alike.
-
-## 06 · honesty: construction stays honest
-
-Plates are opaque, filled with the ground colour. Guides and dashed lines are painted behind the plates they belong to, so the drawing never shows a line it should not.
-
-- **Keep it:** append back to front (Terrain walks its grid diagonal by diagonal from the far corner); a shape that must hide what is behind it keeps its fill (no `nf`); guides use `dash` and are appended before their plate. When depth order changes, move the group (`a.after(b)`), do not redraw.
-- **Rejected when:** a far edge shows through a near solid; paint order is the order the code happened to make things in; a dashed guide crosses the face of the plate it belongs to.
-
-## 07 · cost: loops sleep offscreen
-
-Only ambient motion runs without input, and only while visible.
-
-- **Keep it:** all motion happens inside `register(stage, tick)`. Return `true` from `tick` only while something is still moving; call `wake()` after input. The loop stops when every figure has settled, sleeps offscreen, and lands springs and tweens at once under reduced motion.
-- **Rejected when:** the figure has a timer, a `requestAnimationFrame` or a CSS animation of its own; `tick` always returns `true` in a figure that is not ambient; a path is rewritten on frames where its value did not change (keep the last drawn value and skip).
-
-## 08 · clock: two clocks
-
-A discrete change (which item) gets a long ease-out: 700ms on `(.32, .72, 0, 1)`. A continuous input (where the pointer is) gets a spring, `k 100 · c 18 · m 1`, because its target moves every frame and a timed ease would always be chasing it.
-
-- **Keep it:** `tween` / `tset` / `tval` for which; `spring` / `stepS` for where. Use the defaults unless the figure has a reason you can state.
-- **Rejected when:** a tween follows the pointer's position; a spring animates a choice between items; durations or spring constants are invented; anything is linear.
-
-## 09 · radius: round every corner, then draw less
-
-A solid is the hull of two rounded rings, its top and its base. The vertical corners are never drawn. The top edge becomes one dim crease a unit or two inside the silhouette. Bright outside, dim inside: that hierarchy is most of the polish.
-
-- **Keep it:** `rings(x0, y0, x1, y1, r, b)` then `prism(P, front, ring, inner, z0, z1)` into `solid(parent)` with `put`. A thin plate gets a second line for its thickness, not a second solid. Round flat outlines with `fillet`.
-- **Rejected when:** a box shows twelve edges or any vertical corner line; a corner is sharp; inner lines are as bright as the silhouette; a solid has more than its silhouette, one crease, and at most a few marks the object would really have.
-
-## 10 · quiet: no words inside the figure
-
-Geometry carries identity: a punch on a card's tab, a dot code on a crate's lid, a bright edge instead of a label. Names go to the corner read-out, outside the drawing. Anything decorative has to be something the object would really have.
-
-- **Keep it:** `read.textContent = …` names what is under the pointer, in a few characters (`cell 4·2`, `08`), and says `rest` when nothing is. Number things with dots.
-- **Rejected when:** the svg holds text, letters or digits drawn as paths, icons, arrows or logos; the figure cannot be understood without its read-out; the read-out is a sentence.
-
-## The frame
-
-Not a rule of the study, but every figure shares it.
-
-- The viewBox is 400 × 320. Centre the figure near (200, 166) with `fit`.
-- The camera is `Cam(45, 0.5, S)`: the 2:1 view. Change `S` to fit; leave the angle alone unless the camera is the concept.
-- The silhouette must read at 240px wide. Past a hundred or so solids, or with parts under ten viewBox units, it will not.
-- `mount` keeps no state outside itself, and `destroy` leaves the svg empty and nothing running: collect tear-down in `disposer()` and return `bag.dispose`.
-- At most 200 lines. A longer figure is usually two ideas.
-````
-
-- [ ] **Step 5: Write `concepts.md`**
-
-Create `skills/hairline-create/concepts.md`:
-
-````markdown
-# From an idea to a concept
-
-A concept is three things: **an object**, **what the pointer does to it**, and **what the read-out says**. It fits on one line. If it does not, it is not ready to build.
-
-## Finding it
-
-1. **Find the object.** Something you could put on a desk: a tray, a belt, a platter, a stack, a board of pegs. Not a diagram. "A sales funnel" is not boxes and arrows; it might be a rack of sieves, each finer than the last.
-2. **Find the variable.** Every idea has one number or one choice that matters: how far, which one, how fast, how long. That is what the pointer gets.
-3. **Give the pointer that variable.** Where it is sets a position (continuous); what it is over sets a choice (discrete). The answer should be what a hand would expect from the object.
-4. **Design the rest.** What does the object look like when nobody touches it? It must already be a composition, and already say what the figure is about.
-5. **Choose the read-out's words.** A few characters naming what is under the pointer: `cell 4·2`, `08`, `sieve 3`. And `rest`.
-6. **Choose the slider's number.** One number that makes the answer weaker or stronger: a radius, a stagger, a gap, a rate. Its three values go in `range`.
-
-## Six answers already proven
-
-The package's six figures each answer the pointer a different way. A new figure usually borrows one.
-
-| Answer | In the package | The pointer | The clock | The slider |
-| --- | --- | --- | --- | --- |
-| **A field** | Terrain: pillars rise near the pointer | sets a position on the ground; height falls off with distance | a spring per part | the radius |
-| **One of many** | Riffle: the card under the pointer stands up | picks an item; its neighbours part, staggered outwards | tweens | the stagger |
-| **Scrub and pick** | Exploded: a window comes apart in layers | x scrubs the gap, y picks a layer, which gets the bright edge | a spring for the gap | the gap |
-| **Paint and decay** | Phosphor: a dot matrix you can draw on | excites what it passes; the marks fade; an idle loop returns | a decay per dot | the afterglow |
-| **Dilate time** | Slow: crates ride a belt through a gate | the world keeps moving, hovering slows it so it can be read | a spring on the rate | the rate |
-| **Push the camera** | Turntable: a platter you flick round | pushes; friction bleeds the spin; detents catch it | friction, then a spring | the coast |
-
-`examples/terrain.js` is the first and `examples/riffle.js` the second, in full.
-
-## A weak concept
-
-Drop it, or fix it before building, when:
-
-- **It is dead at rest.** Nothing to look at until touched.
-- **It needs words.** Without a label nobody would know what it is.
-- **It holds more than one idea.** Two gestures, two variables, two objects.
-- **The pointer has no reason.** The figure would be the same as a loop.
-- **It is a diagram.** Boxes, arrows and lines between them are not an object.
-- **It is an icon.** The literal symbol of the idea (a padlock for security) has nothing to answer with.
-- **It depends on colour.** The palette is one stroke in four weights.
-- **It will not read at 240px.** Too many parts, or parts too small.
-
-## An example
-
-For "a sales funnel":
-
-> **Sieves.** Five trays stacked on a rack, each with a finer grid of holes. The pointer's height picks a tray, which slides out and takes the bright edge; the ones above it lift clear. The read-out names the stage: `sieve 3`.
->
-> **Chute.** Beads ride a belt that narrows through four gates, fewer passing each. Hovering slows the belt; the gate nearest the pointer brightens as a bead passes. The read-out says how many reached it: `gate 2 · 31`.
->
-> **Basin.** A field of pegs sloping to one drain. The pointer raises a ridge that splits the slope, and the pegs behind it stand taller the nearer they are. The read-out names the cell: `cell 6·2`.
-
-Each has an object, a gesture and a read-out; each is one idea; each is something at rest.
-````
-
-- [ ] **Step 6: Write `look.md`**
-
-Create `skills/hairline-create/look.md`:
-
-````markdown
-# The look
-
-The validator reads text. This is what only eyes can check. Do it every time the figure changes.
-
-## Four pictures
-
-Open `hairline-<name>.html` in a browser and take four pictures. Two parameters in the address help:
-
-- `?w=240` narrows the page to 240px, the size of a thumbnail.
-- `&at=x,y` holds the pointer at a point of the figure's 400 × 320 viewBox, for tools that cannot hover. Choose a point that is on your figure.
-
-| Picture | Address |
-| --- | --- |
-| full size, at rest | `hairline-<name>.html` |
-| full size, answering | `hairline-<name>.html?at=200,160` |
-| 240px, at rest | `hairline-<name>.html?w=240` |
-| 240px, answering | `hairline-<name>.html?w=240&at=200,160` |
-
-Wait a second after loading before the answering pictures, so springs and tweens have landed.
-
-## What to see
-
-Answer each with yes or no. A no is fixed in the figure before anything is handed over.
-
-1. **The silhouette reads at 240px.** You can say what the object is from the small picture alone.
-2. **Rest is a composition** (rule 05). Not flat, not empty, not a regular grid; something is bright where the eye should start.
-3. **The answer falls off with distance, or spreads out from the pointer** (rules 02 and 03). It is not everything at once, and not one part alone.
-4. **Nothing flickers** (rule 01). Hold `at` on an edge that moves when touched and take two pictures a second apart: they are the same.
-5. **Bright outside, dim inside** (rule 09). Every solid is a silhouette and one crease; no vertical corner is drawn; no corner is sharp.
-6. **Nothing shows through** (rule 06). No far edge crosses a near solid; no guide crosses its own plate.
-7. **One highlight** (rule 04). What is bright is what the pointer chose, and it is a stroke.
-8. **The read-out names what is under the pointer**, in a few characters, and says `rest` at rest.
-9. **Nothing leaves the frame.** With the slider at each end and the pointer at the figure's edges, every part stays inside the plate.
-10. **Both themes.** Press the theme button: nothing vanishes and nothing is left the wrong colour.
-11. **No words** (rule 10). Nothing in the drawing is a letter, a digit, an arrow or an icon.
-12. **The page is clean.** No line under the stage reporting an error, and nothing on the console.
-
-If you are unsure whether the figure's weight is right, build an example the same way and put the two side by side: `node build.mjs examples/terrain.js`.
-
-## Without a browser
-
-Answer the same twelve from the code, each with the line that makes it true: the rest values for 2, the falloff or stagger for 3, the hit test for 4, the paint order for 6. Then say at hand-over, in these words, that the figure was **not looked at in a browser**. Do not skip the list and do not guess a yes.
-````
-
-- [ ] **Step 7: Run the shape test to see it pass**
-
-Run: `cd ~/estudos/hairline/packages/hairline && rtk proxy pnpm exec vitest run test/skill`
-Expected: PASS: `shape.test.ts` 5 tests, and `kernel`, `build` and `validate` still green.
-
-- [ ] **Step 8: Tell contributors about the skill**
-
-In `CONTRIBUTING.md`, in the `## Layout` block, add after the `apps/site` line:
-
-```
-skills/hairline-create the skill that draws a new figure: its kernel is generated from packages/hairline/src/core
-```
-
-In the `## Commands` table, add after the `pnpm dev` row:
-
-```markdown
-| `pnpm kernel` | Regenerates `skills/hairline-create/kernel.js` from `packages/hairline/src/core`. Run it after any change there; a test fails until you do. |
-```
-
-- [ ] **Step 9: Bring the spec up to date**
-
-In `docs/superpowers/specs/2026-10-01-hairline-create-skill-design.md`:
-
-1. In the table under "Files in `skills/hairline-create/`", add a row after `bench.html`:
-
-```markdown
-| `build.mjs` | Puts a figure on the bench: `node build.mjs <figure.js>` writes the page. No dependencies. |
-```
-
-2. Under "The validator", replace the bullet about the figure's own clock with:
-
-```markdown
-- the figure runs its own clock (`setInterval`, `setTimeout`, `requestAnimationFrame`) or never joins the kernel's loop: rule 07 and reduced motion;
-- the figure listens to the pointer itself, measures what is on screen, or never calls the kernel's `pointer`: rule 01;
-- anything in the page other than the figure differs from the bench;
-```
-
-3. Under "The look", add after the first paragraph:
-
-```markdown
-The bench takes two URL parameters for this: `?w=240` narrows the page, and `&at=x,y` holds the pointer at a viewBox point, for tools that cannot hover.
-```
-
-4. Under "The figure contract", add a last paragraph:
-
-```markdown
-Figures are pointer-only. The bench's stage is an image, not a focusable group, so the Riffle example leaves out the package's keyboard handling.
-```
-
-- [ ] **Step 10: Run every suite, then commit**
-
-Run: `lsof -ti:4310 | xargs kill 2>/dev/null; cd ~/estudos/hairline && rtk proxy pnpm build && rtk proxy pnpm typecheck && rtk proxy pnpm test && rtk proxy pnpm test:browser && rtk proxy pnpm run release --static`
-Expected: all pass. This is the CI job, in its order.
-
-```bash
-cd ~/estudos/hairline && rtk git add skills/hairline-create/SKILL.md skills/hairline-create/rules.md skills/hairline-create/concepts.md skills/hairline-create/look.md packages/hairline/test/skill/shape.test.ts CONTRIBUTING.md docs/superpowers/specs/2026-10-01-hairline-create-skill-design.md && rtk git commit -m "Skill: the flow, the ten rules with what rejects a figure, how to find a concept, and the look
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
----
-
-### Task 6: Pull request (controller)
-
-**Files:** none.
-
-**Interfaces:**
-- Consumes: the branch `skill-create` with Tasks 1–5 committed and the whole-branch review done.
-- Produces: an open pull request against `main` with CI green. It is not merged: the trial comes first, and the merge is Lucas's call.
-
-- [ ] **Step 1: Push and open the pull request**
-
-```bash
-cd ~/estudos/hairline && rtk git push -u origin skill-create
-```
-
-Open the pull request with `rtk gh pr create --base main --head skill-create`, titled `hairline-create: a skill that draws a new Hairline figure`, its body covering: what the skill is and how it is installed (`npx skills add lucasmarkes/hairline`, once the repository is public); the files; what CI now checks; the five additions to the spec; an empty **Trial** section for Task 7.
-
-- [ ] **Step 2: Watch CI**
-
-Run: `cd ~/estudos/hairline && rtk proxy gh pr checks --watch`
-Expected: `verify` passes. If it fails, read the log (`rtk proxy gh run view --log-failed`), fix on the branch with a test, push again.
-
----
-
-### Task 7: The trial (controller, with Lucas)
-
-No automatic test proves an agent turns a new idea into a good figure. This is the test.
-
-**Files:**
-- Modify, as the trial finds defects: `skills/hairline-create/rules.md`, `concepts.md`, `look.md`, `SKILL.md`, `validate.mjs` (each change to the validator with a failing case added to `BROKEN` first)
-- Scratch, never committed: `.superpowers/trial/<n>-<name>/`
-
-**Interfaces:**
-- Consumes: the finished skill folder.
-- Produces: five pages judged by Lucas, and a **Trial** section in the pull request: the ideas, the verdicts, every recurring defect and the line or check it became.
-
-- [ ] **Step 1: Run five clean sessions**
-
-Dispatch five fresh subagents, each knowing nothing of this conversation, three on `opus` and two on `sonnet` (a weaker agent is part of the test). Each gets this prompt, with its idea and folder filled in:
-
-```
-Read ~/estudos/hairline/skills/hairline-create/SKILL.md and follow it exactly, for this request:
-
-/hairline-create <idea>
-
-There is nobody to pick a concept: write your concepts down, then take one as SKILL.md says for that case. Work in ~/estudos/hairline/.superpowers/trial/<n>-<slug>/ (create it). Do not read anything else in the repository: you have only the skill folder, as someone who installed it would. Do not publish an artifact; leave the HTML file in your folder.
-
-Report: the concepts you offered and the one you took; the path of the HTML file; the validator's final output; your answers to the look, and whether you looked in a browser; which files of the skill you read, and whether you read the kernel's code below its index; anything in the skill that was unclear, missing or wrong.
-```
-
-The ideas, chosen to differ in kind:
-
-1. `a sales funnel` (a flow that narrows)
-2. `a rate limiter` (time and a threshold)
-3. `git branches merging` (structure; the pull towards a diagram)
-4. `a bookshelf` (plain discrete objects)
-5. `weather over a city` (ambient, continuous, not technical)
-
-- [ ] **Step 2: Check each page before showing it**
-
-For each: `node skills/hairline-create/validate.mjs <page>` exits 0, and the page opens with a clean console. A session that handed over a failing page is a finding in itself: write down which instruction it skipped.
-
-- [ ] **Step 3: Lucas judges**
-
-Give Lucas the five pages and, for each, the concept line. Ask for a verdict on each (would it sit beside Terrain: yes, nearly, no) and what is wrong with it. Wait for the answer.
-
-- [ ] **Step 4: Turn defects into the skill**
-
-A defect seen in two or more pages, or one Lucas calls out as a rule broken, becomes a change:
-
-- mechanical (it can be read off the text) → a check in `validate.mjs`, with its failing case added to `BROKEN` in `validate.test.ts` first, watched to fail, then made to pass;
-- a matter of taste → a "Rejected when" line in `rules.md`, a line in `concepts.md`'s weak list, or a question in `look.md`;
-- a misreading of the flow → `SKILL.md`.
-
-Also from the reports: if agents read the kernel's code despite the instruction, or the kernel's size hurt them, say so in the pull request with the numbers from Task 1, Step 5.
-
-Then run the idea that came out worst once more, in a clean session, to see the change hold.
-
-- [ ] **Step 5: Record and hand the merge to Lucas**
-
-Run the CI job locally (Task 5, Step 10), commit the changes by name, push, and write the **Trial** section of the pull request: the five ideas and verdicts, each defect and what it became, what is still not good enough. Then ask Lucas whether to merge. Do not merge without a yes.
diff --git a/docs/superpowers/plans/2026-10-01-hairline-docs.md b/docs/superpowers/plans/2026-10-01-hairline-docs.md
deleted file mode 100644
index 2c526ad..0000000
--- a/docs/superpowers/plans/2026-10-01-hairline-docs.md
+++ /dev/null
@@ -1,1323 +0,0 @@
-# Hairline Docs Page Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Replace the site's interim `/docs` with one page of real documentation: a sidebar of anchors, nine sections fed by the data in `lib/`, grayscale code blocks with line numbers, and the six figures live.
-
-**Architecture:** `app/docs/page.tsx` stays an async Server Component. It highlights every snippet at build with shiki, using a CSS-variables theme, and passes the HTML to three server section components in `app/docs/sections.tsx`. Two small client components do the interactive parts. `CodeBlock` copies code, and `Tabs` remembers the chosen tab. `Sidebar` marks the section in view with an IntersectionObserver. `SECTIONS` in `lib/docs.ts` is the one list that both the sidebar and the page map over.
-
-**Tech Stack:** Next 16.3.8 App Router, React 19.3, Tailwind 4.3.3 (`@theme` tokens in `app/globals.css`), shiki 4.5.0, vitest 5.0.3, Playwright 1.63.0 (Chrome).
-
-**Spec:** `docs/superpowers/specs/2026-10-01-hairline-docs-design.md`
-
-## Global Constraints
-
-- Repo `~/estudos/hairline`, branch `site-on-vercel`. The app is `apps/site`. Every path below is relative to `apps/site` unless it starts with `docs/`, and every command runs from `apps/site`.
-- Prefix every shell command with `rtk`.
-- No new dependency. The page stays a static Server Component, and no highlighter reaches the browser.
-- Black and white. Geist Sans everywhere, Geist Mono only inside `code` and `pre`, and Instrument Serif only in the home's `h1 em`.
-- Code, comments and copy are in English. Comments follow the house style: one plain sentence saying why, not what.
-- Every commit message ends with a blank line, then `Co-Authored-By: Claude <[email protected]>`.
-- Never stage `.vercel/`, `.superpowers/`, `.claude/`, `AGENTS.md`, `CLAUDE.md` or `.vitest/`. Stage files by name, never with `git add .` or `-A`.
-- Run `rtk pnpm build` before any Playwright run; Playwright serves the built site with `next start -p 4320`.
- - It reuses a server already on 4320, so first check that `lsof -ti:4320` prints nothing. If it prints a PID, kill it.
- - `pnpm build` needs `../../packages/hairline/dist/index.js`. If that is missing, run `rtk pnpm --filter @lucasmarkes/hairline build` first.
-- Exact copy for the page header and every section: see the spec's "Layout" and "Sections". It is repeated in the code below; the code is what you paste.
-
-## Review Focus
-
-1. **Opening `/docs#theme` directly.** The browser lands with the Theme heading clear of the sticky chrome, and Theme is marked in the sidebar on the first observer callback. Pinned in Task 4.
-2. **Storage that throws** (private mode, blocked). The quick start stays on React, every tab still switches, and the console stays clean. Pinned in Task 3.
-3. **A long code line, the intensity table or the tab bar at 320px.** Each scrolls or shrinks inside its own box, and the page never scrolls sideways. Pinned in Task 3.
-4. **No JavaScript.** The sidebar and strip are plain links that still move the hash, and the quick start shows React. Pinned in Task 4.
-5. **The end of the page, where Accessibility can never reach the band.** Scrolling to the bottom marks Accessibility. Pinned in Task 4.
-
----
-
-### Task 1: Grayscale highlighting
-
-**Files:**
-- Modify: `lib/highlight.ts`
-- Modify: `app/globals.css` (`:root`, and the `.t-*` rules at lines 120–124)
-- Test: `test/docs.test.ts`, `test/site.spec.ts`
-
-**Interfaces:**
-- Consumes: `REACT`, `VANILLA`, `CDN`, `CSS` from `lib/snippets.ts`, all existing.
-- Produces: `highlight(code: string, lang: string): Promise<string>`. The signature is unchanged. Its output now colors tokens only with `var(--code-…)`, and its `<pre>` has no `tabindex`. It also produces the `--code-*` custom properties on `:root`. Task 2 extends the `SAMPLES` array in `test/docs.test.ts`.
-
-- [ ] **Step 1: Write the failing vitest tests**
-
-In `test/docs.test.ts`, add `import { highlight } from "@/lib/highlight";` to the imports. Change the snippets import line to:
-
-```ts
-import { CDN, CSS, PASTE, REACT, VANILLA, install, snippet } from "@/lib/snippets";
-```
-
-Append at the end of the file:
-
-```ts
-/** Every snippet the docs highlight, with its language. */
-const SAMPLES: [code: string, lang: string][] = [[REACT, "tsx"], [VANILLA, "ts"], [CDN, "html"], [CSS, "css"]];
-
-describe("highlighting", () => {
- it("colours tokens with the --code- variables only, and leaves the block one tab stop", async () => {
- for (const [code, lang] of SAMPLES) {
- const html = await highlight(code, lang);
- expect(html).toContain("var(--code-");
- // the CSS sample holds #ffffff as text, so only colours set in a style count
- expect(html).not.toMatch(/(?:color|background-color):\s*#/i);
- expect(html).not.toContain("tabindex");
- }
- });
-
- it("writes only variables globals.css defines", async () => {
- const css = readFileSync(new URL("../app/globals.css", import.meta.url), "utf8");
- const used = new Set<string>();
- for (const [code, lang] of SAMPLES) for (const m of (await highlight(code, lang)).matchAll(/var\((--code-[a-z-]+)\)/g)) used.add(m[1]);
- expect(used.size).toBeGreaterThan(3);
- for (const name of used) expect(css).toContain(`${name}:`);
- });
-});
-```
-
-- [ ] **Step 2: Write the failing Playwright test**
-
-In `test/site.spec.ts`, add after the test "the docs prerender six empty boxes…":
-
-```ts
-test("the docs' code is in greys: every token's colour has equal red, green and blue", async ({ page }) => {
- await page.goto("/docs");
- const colours = await page.locator("main pre span").evaluateAll((spans) => spans.map((s) => getComputedStyle(s).color));
- expect(colours.length).toBeGreaterThan(20);
- const tinted = colours.filter((c) => {
- const [r, g, b] = c.match(/\d+(\.\d+)?/g)!.map(Number);
- return !(r === g && g === b);
- });
- expect(tinted).toEqual([]);
-});
-```
-
-- [ ] **Step 3: Run the tests to see them fail**
-
-Run: `rtk pnpm exec vitest run -t "highlighting"`
-Expected: FAIL. Both tests fail: shiki's `min-light` writes hex colours and `tabindex="0"`, and `globals.css` defines no `--code-` variable.
-
-Run: `lsof -ti:4320; rtk pnpm build && rtk pnpm exec playwright test -g "in greys"`
-Expected: FAIL. `tinted` lists `min-light`'s coloured tokens, for example `rgb(…)` values with unequal channels.
-
-- [ ] **Step 4: Highlight with the CSS-variables theme**
-
-Replace the whole of `lib/highlight.ts` with:
-
-```ts
-import { codeToHtml, createCssVariablesTheme } from "shiki";
-
-/** shiki writes var(--code-…) instead of colours; globals.css sets them, in greys. */
-const theme = createCssVariablesTheme({ name: "hairline", variablePrefix: "--code-" });
-
-const escape = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
-
-/** The block around the code is its tab stop, so shiki's own tabindex on the pre goes. */
-export async function highlight(code: string, lang: string): Promise<string> {
- const html = await codeToHtml(code.trimEnd(), { lang, theme });
- return html.replace(' tabindex="0"', "");
-}
-
-export function plain(code: string): string {
- return `<pre class="shiki"><code>${escape(code.trimEnd())}</code></pre>`;
-}
-```
-
-- [ ] **Step 5: Define the variables and move the inspector's snippet onto them**
-
-In `app/globals.css`, replace the `:root` block (lines 16–21) with:
-
-```css
-:root {
- --lift: 0 1px 2px #00000008, 0 10px 28px -16px #00000024;
- --lift-lg: 0 1px 2px #00000008, 0 2px 6px #00000008, 0 32px 64px -34px #00000038;
- --ease-out: cubic-bezier(0.23, 1, 0.32, 1);
- --ease-icon: cubic-bezier(0.2, 0, 0, 1);
- /* Code in greys, each at least 4.5:1 on the code frame's #fafafa. shiki writes these names. */
- --code-foreground: #0a0a0a;
- --code-background: transparent;
- --code-token-constant: #0a0a0a;
- --code-token-function: #404040;
- --code-token-parameter: #404040;
- --code-token-string: #525252;
- --code-token-string-expression: #525252;
- --code-token-keyword: #6b6b6b;
- --code-token-comment: #6b6b6b;
- --code-token-punctuation: #6b6b6b;
- --code-token-link: #6b6b6b;
-}
-```
-
-Then replace these lines:
-
-```css
-.t-kw { color: var(--color-muted); }
-.t-tag { font-weight: 500; }
-.t-attr { color: #525252; }
-```
-
-with:
-
-```css
-.t-kw { color: var(--code-token-keyword); }
-.t-str { color: var(--code-token-string); }
-.t-tag { color: var(--code-token-constant); font-weight: 500; }
-.t-attr { color: var(--code-token-function); }
-.t-val { color: var(--code-foreground); }
-```
-
-- [ ] **Step 6: Run the tests to see them pass**
-
-Run: `rtk pnpm exec vitest run`
-Expected: PASS, 18 tests in `test/docs.test.ts`: the 16 existing ones plus the 2 new ones.
-
-Run: `lsof -ti:4320; rtk pnpm build && rtk pnpm exec playwright test -g "in greys|prerender six"`
-Expected: PASS, 2 passed.
-
-- [ ] **Step 7: Commit**
-
-```bash
-rtk git add lib/highlight.ts app/globals.css test/docs.test.ts test/site.spec.ts
-rtk git commit -m "Docs: code is highlighted in greys through shiki's CSS-variables theme, and the inspector's snippet uses the same variables
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
----
-
-### Task 2: The docs' data
-
-**Files:**
-- Create: `lib/docs.ts`
-- Modify: `lib/snippets.ts`, `lib/figures.ts`, `lib/llms.ts`
-- Test: `test/docs.test.ts`
-
-**Interfaces:**
-- Consumes: `OPTIONS`, `THEME`, `INTENSITY`, `FIGURES` from `lib/figures.ts`. `SAMPLES` and `highlight` from Task 1, in the test file.
-- Produces, all used by Task 3:
- - `lib/docs.ts`:
- - `type Group = "Getting started" | "API" | "Reference"`
- - `type Section = { id: string; group: Group; title: string }`
- - `SECTIONS: Section[]`, nine entries in page order.
- - `lib/snippets.ts`:
- - `QUICKSTART: { label: string; lang: string; file: string; code: string }[]`, with React/`app/page.tsx`, Vanilla/`main.ts` and CDN/`index.html`.
- - `REACT_SIGNATURE: string` and `VANILLA_SIGNATURE: string`.
- - `PASTE` stays for now; the old page still imports it, and Task 3 deletes it.
- - `lib/figures.ts`: `measure(value: number, unit: string): string`, which returns `"40 ms"` or `"0.2× normal speed"`. `CARDS` stays for now; Task 3 deletes it.
-
-- [ ] **Step 1: Write the failing tests**
-
-In `test/docs.test.ts`:
-
-1. Change the imports to:
-
- ```ts
- import { SECTIONS } from "@/lib/docs";
- import { FIGURES, INTENSITY, OPTIONS, measure } from "@/lib/figures";
- import { CDN, CSS, QUICKSTART, REACT, REACT_SIGNATURE, VANILLA, VANILLA_SIGNATURE, install, snippet } from "@/lib/snippets";
- ```
-
- This drops `PASTE`.
-
-2. Replace the whole `describe("the quickstart", …)` block and the whole `describe("the Tiny card", …)` block with:
-
-```ts
-describe("the quick start", () => {
- it("pastes React, Vanilla and CDN, each under a file name, and none of them sets an option the package dropped", () => {
- expect(QUICKSTART.map((q) => [q.label, q.file])).toEqual([["React", "app/page.tsx"], ["Vanilla", "main.ts"], ["CDN", "index.html"]]);
- expect(QUICKSTART.map((q) => q.code)).toEqual([REACT, VANILLA, CDN]);
- for (const q of QUICKSTART) expect(q.code).not.toMatch(/stagger|radius|afterglow|coast|bands|labels|ranges|className/);
- });
-});
-
-describe("the theme's CSS", () => {
- it("sets all six theme properties", () => {
- for (const key of ["plate", "hi", "edge", "mid", "lo", "stroke"]) expect(CSS).toContain(`--hairline-${key}:`);
- });
-});
-
-describe("the signatures", () => {
- it("list the component's four options with their types, read from the options table", () => {
- expect(REACT_SIGNATURE).toBe(`<Terrain
- intensity?: number
- theme?: "auto" | "light" | "dark"
- label?: string
- onRead?: (text: string) => void
- {...divProps}
-/>
-`);
- });
-
- it("give the function's handle its two methods", () => {
- expect(VANILLA_SIGNATURE).toBe(`terrain(element: HTMLElement, options?: HairlineOptions): {
- update(options: HairlineOptions): void
- destroy(): void
-}
-`);
- });
-});
-
-describe("the Install note's size", () => {
- it("is the gzip size of the vanilla entry, to a tenth of a kB", () => {
- const bytes = gzipSync(readFileSync(new URL("../../../packages/hairline/dist/index.js", import.meta.url))).length;
- expect(tiny()).toBe(`${(bytes / 1000).toFixed(1)} kB`);
- expect(tiny()).toMatch(/^\d+\.\d kB$/);
- });
-});
-
-describe("the docs' sections", () => {
- it("are nine, in three groups in order, with unique ids that work as fragments", () => {
- expect(SECTIONS.map((s) => s.id)).toEqual(["install", "quick-start", "options", "react", "vanilla", "cdn", "figures", "theme", "accessibility"]);
- expect(new Set(SECTIONS.map((s) => s.id)).size).toBe(9);
- for (const s of SECTIONS) expect(s.id).toMatch(/^[a-z-]+$/);
- expect(SECTIONS.map((s) => s.group)).toEqual([
- "Getting started", "Getting started", "Getting started",
- "API", "API", "API",
- "Reference", "Reference", "Reference",
- ]);
- });
-
- it("share their headings with /llms.txt", () => {
- const text = llms("https://example.test");
- for (const title of ["Install", "Options", "Figures", "Theme", "Accessibility"]) {
- expect(SECTIONS.map((s) => s.title)).toContain(title);
- expect(text).toContain(`\n## ${title}\n`);
- }
- });
-});
-
-describe("the intensity table", () => {
- it("writes each number with its unit, as /llms.txt does", () => {
- expect(measure(40, "ms")).toBe("40 ms");
- expect(measure(0.2, "× normal speed")).toBe("0.2× normal speed");
- for (const doc of FIGURES) {
- const [lo, mid, hi] = INTENSITY[doc.id].map((n) => measure(n, doc.parameter.unit));
- expect(scale(doc.id, doc.parameter)).toBe(`${doc.parameter.name} ${lo} at 0, ${mid} at 0.5, ${hi} at 1`);
- }
- });
-});
-```
-
-3. Extend `SAMPLES` from Task 1 so the signatures go through the variables test too:
-
-```ts
-const SAMPLES: [code: string, lang: string][] = [[REACT, "tsx"], [VANILLA, "ts"], [CDN, "html"], [CSS, "css"], [REACT_SIGNATURE, "tsx"], [VANILLA_SIGNATURE, "ts"]];
-```
-
-- [ ] **Step 2: Run the tests to see them fail**
-
-Run: `rtk pnpm exec vitest run`
-Expected: FAIL. vitest cannot resolve `@/lib/docs`, and `QUICKSTART`, `REACT_SIGNATURE`, `VANILLA_SIGNATURE` and `measure` are not exported.
-
-- [ ] **Step 3: Create `lib/docs.ts`**
-
-```ts
-/**
- * The docs' sections, in page order. The sidebar and the page both map over
- * this list, so an anchor cannot exist on one side only.
- */
-
-export type Group = "Getting started" | "API" | "Reference";
-
-export type Section = { id: string; group: Group; title: string };
-
-export const SECTIONS: Section[] = [
- { id: "install", group: "Getting started", title: "Install" },
- { id: "quick-start", group: "Getting started", title: "Quick start" },
- { id: "options", group: "Getting started", title: "Options" },
- { id: "react", group: "API", title: "React" },
- { id: "vanilla", group: "API", title: "Vanilla" },
- { id: "cdn", group: "API", title: "CDN" },
- { id: "figures", group: "Reference", title: "Figures" },
- { id: "theme", group: "Reference", title: "Theme" },
- { id: "accessibility", group: "Reference", title: "Accessibility" },
-];
-```
-
-- [ ] **Step 4: Add `measure` to `lib/figures.ts` and use it in `scale`**
-
-In `lib/figures.ts`, add directly after the `INTENSITY` constant:
-
-```ts
-/** A number with its unit, as the docs' table and /llms.txt write it: "40 ms", "0.2× normal speed". */
-export function measure(value: number, unit: string): string {
- return `${value}${unit.startsWith("×") ? "" : " "}${unit}`;
-}
-```
-
-In `lib/llms.ts`:
-
-1. Change the first import to:
-
- ```ts
- import { FIGURES, INTENSITY, LINKS, OPTIONS, THEME, measure, type Row } from "./figures";
- ```
-
-2. Replace the body of `scale` with:
-
- ```ts
- export function scale(id: keyof typeof INTENSITY, parameter: { name: string; unit: string }): string {
- const [lo, mid, hi] = INTENSITY[id].map((n) => measure(n, parameter.unit));
- return `${parameter.name} ${lo} at 0, ${mid} at 0.5, ${hi} at 1`;
- }
- ```
-
-- [ ] **Step 5: Add the quick start and the signatures to `lib/snippets.ts`**
-
-1. Change the first line to:
-
- ```ts
- import { OPTIONS, THEME } from "./figures";
- ```
-
-2. Insert this block directly above the `/** The quickstart's second step. */` comment. Leave `PASTE` where it is; Task 3 removes it.
-
-```ts
-/** The quick start's tabs: the same figure three ways, each under the file it goes in. */
-export const QUICKSTART: { label: string; lang: string; file: string; code: string }[] = [
- { label: "React", lang: "tsx", file: "app/page.tsx", code: REACT },
- { label: "Vanilla", lang: "ts", file: "main.ts", code: VANILLA },
- { label: "CDN", lang: "html", file: "index.html", code: CDN },
-];
-
-/** The component's props, read from the options table so the two cannot drift. */
-export const REACT_SIGNATURE = `<Terrain
-${OPTIONS.map((o) => ` ${o.name}?: ${o.type}`).join("\n")}
- {...divProps}
-/>
-`;
-
-export const VANILLA_SIGNATURE = `terrain(element: HTMLElement, options?: HairlineOptions): {
- update(options: HairlineOptions): void
- destroy(): void
-}
-`;
-```
-
-- [ ] **Step 6: Run the tests to see them pass**
-
-Run: `rtk pnpm exec vitest run`
-Expected: PASS, 23 tests. Task 1 left 18. This task removes the 2 quickstart tests and the Tiny test, and adds 8.
-
-Run: `rtk pnpm typecheck`
-Expected: no errors. `PASTE` and `CARDS` still exist, so the old page still compiles.
-
-- [ ] **Step 7: Commit**
-
-```bash
-rtk git add lib/docs.ts lib/snippets.ts lib/figures.ts lib/llms.ts test/docs.test.ts
-rtk git commit -m "Docs: the sections, the quick start's three files, the two signatures and the intensity table's units come from lib, beside llms.txt
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
----
-
-### Task 3: Code blocks and the docs page, without the sidebar
-
-**Files:**
-- Create: `components/code-block.tsx`, `app/docs/sections.tsx`
-- Modify: `components/tabs.tsx`, `app/docs/page.tsx`, `app/page.tsx`, `app/globals.css`
-- Modify: `lib/snippets.ts` (delete `PASTE`) and `lib/figures.ts` (delete `CARDS`)
-- Test: `test/site.spec.ts`
-
-**Interfaces:**
-- Consumes:
- - `highlight` (Task 1).
- - `SECTIONS`, `QUICKSTART`, `REACT_SIGNATURE`, `VANILLA_SIGNATURE` and `measure` (Task 2).
- - `CopyIcon({ text, select, label })` from `components/copy.tsx` and `Install({ commands })` from `components/install.tsx`, both existing.
-- Produces, used by Task 4:
- - `CodeBlock({ title, html, plain? }: { title: string; html: string; plain?: boolean })`.
- - `type Tab = { label: string; file: string; html: string }`, and `Tabs({ tabs, label }: { tabs: Tab[]; label: string })`.
- - `GettingStarted`, `Api` and `Reference`, server components.
- - The DOM hooks:
- - `section#{id}[aria-labelledby={id}-title]` with `h2#{id}-title`.
- - `.docs`, the page grid that Task 4 puts the sidebar into.
- - `.docs-main`.
- - `[data-code]` on every code frame, `.code-title`, and `.code-body`.
- - The CSS variables `--topbar` (on `:root`) and `--doc-offset` (on `.docs`).
-
-- [ ] **Step 1: Write the failing Playwright tests**
-
-In `test/site.spec.ts`:
-
-1. Replace the whole test "Get started leads to the docs, whose quickstart pastes four ways and lists the four options" with:
-
-```ts
-test("Get started leads to the docs, whose quick start pastes three ways and copies the tab on show", async ({ page, context }) => {
- await context.grantPermissions(["clipboard-read", "clipboard-write"]);
- await page.goto("/");
- await page.getByRole("link", { name: "Get started" }).click();
- await expect(page).toHaveURL(/\/docs$/);
- const quick = page.locator("#quick-start");
- await expect(quick.getByRole("tab")).toHaveText(["React", "Vanilla", "CDN"]);
- await expect(quick.locator(".code-title")).toHaveText("app/page.tsx");
- await quick.getByRole("tab", { name: "CDN" }).click();
- await expect(quick.locator(".code-title")).toHaveText("index.html");
- await expect(quick.getByRole("tabpanel")).toContainText("https://esm.sh/@lucasmarkes/hairline");
- await quick.getByRole("button", { name: "Copy code" }).click();
- expect(await page.evaluate(() => navigator.clipboard.readText())).toMatch(/^<div id="figure"/);
- await expect(page.locator("#options [data-options] tbody tr td:first-child")).toHaveText(["intensity", "theme", "label", "onRead"]);
-});
-```
-
-2. Replace the whole test "one family outside the hero: …" with this version, which also checks `/docs`:
-
-```ts
-/** Every element that holds text of its own, outside code, the hero's serif word and the figures, with its family. */
-const families = (page: Page) =>
- page.evaluate(() =>
- [...document.querySelectorAll("body *")]
- // the install pill is code, prompt and all
- .filter((el) => !el.closest("h1 em, code, pre, .pill, [data-hairline]") && [...el.childNodes].some((n) => n.nodeType === 3 && n.textContent!.trim()))
- .map((el) => `${el.tagName} ${getComputedStyle(el).fontFamily}`),
- );
-
-test("one family outside the hero: the serif is the headline's one word, mono is code", async ({ page }) => {
- await page.goto("/");
- await expect(page.locator("h1 em")).toHaveCSS("font-family", /Instrument Serif/);
- const home = await families(page);
- expect(home.length).toBeGreaterThan(5);
- expect(home.filter((f) => !/geist/i.test(f) || /mono/i.test(f))).toEqual([]);
-
- await page.goto("/docs");
- const docs = await families(page);
- expect(docs.length).toBeGreaterThan(40);
- expect(docs.filter((f) => !/geist/i.test(f) || /mono/i.test(f))).toEqual([]);
- for (const id of IDS) await expect(page.locator(`[data-row="${id}"] h3`)).toHaveCSS("font-style", "normal");
-});
-```
-
-3. Append these tests at the end of the file:
-
-```ts
-test("a code block copies its code without the line numbers, and a signature has none", async ({ page, context }) => {
- await context.grantPermissions(["clipboard-read", "clipboard-write"]);
- await page.goto("/docs");
- const blocks = page.locator("#react [data-code]");
- await expect(blocks.locator(".code-title")).toHaveText(["Signature", "app/page.tsx"]);
- const usage = blocks.last();
- await usage.getByRole("button", { name: "Copy code" }).click();
- const text = await page.evaluate(() => navigator.clipboard.readText());
- expect(text.split("\n")[0]).toBe('import { Terrain } from "@lucasmarkes/hairline/react";');
- expect(text).not.toMatch(/^\s*\d/m);
- const number = (block: typeof usage) => block.locator(".line").first().evaluate((el) => getComputedStyle(el, "::before").content);
- expect(await number(usage)).not.toBe("none");
- expect(await number(blocks.first())).toBe("none");
-});
-
-test("the quick start remembers the tab a reader picked", async ({ page }) => {
- await page.goto("/docs");
- const quick = page.locator("#quick-start");
- await quick.getByRole("tab", { name: "Vanilla" }).click();
- await page.reload();
- await expect(quick.getByRole("tab", { name: "Vanilla" })).toHaveAttribute("aria-selected", "true");
- await expect(quick.locator(".code-title")).toHaveText("main.ts");
-});
-
-test("when storage throws, the quick start stays on React and still switches, with a clean console", async ({ page }) => {
- await page.addInitScript(() => {
- Object.defineProperty(window, "localStorage", { get() { throw new DOMException("blocked", "SecurityError"); } });
- });
- const noise = watch(page);
- await page.goto("/docs");
- const quick = page.locator("#quick-start");
- await expect(quick.getByRole("tab", { name: "React" })).toHaveAttribute("aria-selected", "true");
- await quick.getByRole("tab", { name: "CDN" }).click();
- await expect(quick.getByRole("tab", { name: "CDN" })).toHaveAttribute("aria-selected", "true");
- expect(noise).toEqual([]);
-});
-
-test("the docs fit a phone down to 320px: rows stack text first, and wide code and tables scroll in their own box", async ({ page }) => {
- for (const width of [390, 320]) {
- await page.setViewportSize({ width, height: 800 });
- await page.goto("/docs");
- expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(width);
- const row = page.locator('[data-row="terrain"]');
- const text = (await row.locator("h3").boundingBox())!;
- const tile = (await row.locator(".tile").boundingBox())!;
- expect(tile.y).toBeGreaterThan(text.y + text.height);
- }
-});
-
-test("the figures' link goes to the home's figure", async ({ page }) => {
- await page.goto("/docs");
- await page.getByRole("link", { name: "Try them on the home page →" }).click();
- await expect(page).toHaveURL(/\/#try$/);
- await expect(page.locator("#try [data-inspector]")).toBeInViewport();
-});
-```
-
-- [ ] **Step 2: Run them to see them fail**
-
-Run: `lsof -ti:4320; rtk pnpm build && rtk pnpm exec playwright test -g "quick start|one family|code block copies|storage throws|320px|home's figure"`
-Expected: FAIL, 7 failing tests: the 6 new or rewritten ones, plus "one family", which finds the `.props` cells in mono. Most time out because `#quick-start`, `#react` and the "Try them" link do not exist yet.
-
-- [ ] **Step 3: Create `components/code-block.tsx`**
-
-```tsx
-"use client";
-
-import { useRef } from "react";
-import { CopyIcon } from "./copy";
-
-/**
- * A code sample in its frame: a bar with its title and a copy icon, then the
- * code, which is the block's one tab stop so the keyboard can scroll it.
- * Line numbers are drawn in CSS, so they are never selected or copied;
- * `plain` leaves them off.
- */
-export function CodeBlock({ title, html, plain = false }: { title: string; html: string; plain?: boolean }) {
- const body = useRef<HTMLDivElement>(null);
- return (
- <div className="code" data-code>
- <div className="code-bar">
- <span className="code-title">{title}</span>
- <CopyIcon text={() => body.current?.textContent ?? ""} select={body} label="Copy code" />
- </div>
- <div ref={body} tabIndex={0} className="code-body" data-plain={plain || undefined} dangerouslySetInnerHTML={{ __html: html }} />
- </div>
- );
-}
-```
-
-- [ ] **Step 4: Rewrite `components/tabs.tsx`**
-
-```tsx
-"use client";
-
-import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react";
-import { CopyIcon } from "./copy";
-
-export type Tab = { label: string; file: string; html: string };
-
-/** Where the reader's tab is kept between visits. */
-const KEY = "hairline:docs-tab";
-
-/**
- * Code under tabs, in the same frame as CodeBlock: the tabs on the left, the
- * shown tab's file name and the copy icon on the right. The server renders
- * the first tab; the stored one is read after mount, and storage that throws
- * (private mode, blocked) leaves the first tab on.
- */
-export function Tabs({ tabs, label }: { tabs: Tab[]; label: string }) {
- const [at, setAt] = useState(0);
- const panel = useRef<HTMLDivElement>(null);
- const list = useRef<HTMLDivElement>(null);
- const id = useId();
-
- useEffect(() => {
- try {
- const stored = tabs.findIndex((tab) => tab.label === localStorage.getItem(KEY));
- if (stored > 0) setAt(stored);
- } catch {}
- }, [tabs]);
-
- const pick = (i: number) => {
- setAt(i);
- try {
- localStorage.setItem(KEY, tabs[i].label);
- } catch {}
- };
-
- const onKeyDown = (event: KeyboardEvent) => {
- const step = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0;
- if (!step) return;
- event.preventDefault();
- const next = (at + step + tabs.length) % tabs.length;
- pick(next);
- list.current?.querySelectorAll<HTMLButtonElement>("[role=tab]")[next]?.focus();
- };
-
- return (
- <div className="code" data-code>
- <div className="code-bar">
- <div ref={list} role="tablist" aria-label={label} onKeyDown={onKeyDown} className="code-tabs">
- {tabs.map((tab, i) => (
- <button key={tab.label} type="button" role="tab" id={`${id}-tab-${i}`} aria-selected={i === at} aria-controls={`${id}-panel`} tabIndex={i === at ? 0 : -1} onClick={() => pick(i)} className="code-tab">
- {tab.label}
- </button>
- ))}
- </div>
- <span className="code-title" title={tabs[at].file}>{tabs[at].file}</span>
- <CopyIcon text={() => panel.current?.textContent ?? ""} select={panel} label="Copy code" />
- </div>
- <div ref={panel} role="tabpanel" id={`${id}-panel`} aria-labelledby={`${id}-tab-${at}`} tabIndex={0} className="code-body" dangerouslySetInnerHTML={{ __html: tabs[at].html }} />
- </div>
- );
-}
-```
-
-- [ ] **Step 5: Create `app/docs/sections.tsx`**
-
-```tsx
-import type { ReactNode } from "react";
-import { Exploded, Phosphor, Riffle, Slow, Terrain, Turntable } from "@lucasmarkes/hairline/react";
-import { CodeBlock } from "@/components/code-block";
-import { Install } from "@/components/install";
-import { Tabs, type Tab } from "@/components/tabs";
-import { SECTIONS } from "@/lib/docs";
-import { FIGURES, INTENSITY, OPTIONS, THEME, measure } from "@/lib/figures";
-import { PACKAGE } from "@/lib/snippets";
-
-const SMALL = { riffle: Riffle, terrain: Terrain, exploded: Exploded, phosphor: Phosphor, slow: Slow, turntable: Turntable };
-
-/** A section takes its title from SECTIONS, the list the sidebar reads, so the two always agree. */
-function Section({ id, children }: { id: string; children: ReactNode }) {
- const { title } = SECTIONS.find((s) => s.id === id)!;
- return (
- <section id={id} aria-labelledby={`${id}-title`} className="doc-section">
- <h2 id={`${id}-title`} className="doc-h2">{title}</h2>
- {children}
- </section>
- );
-}
-
-const C = ({ children }: { children: ReactNode }) => <code className="doc-code">{children}</code>;
-
-export function GettingStarted({ commands, size, quickstart }: { commands: { label: string; code: string }[]; size: string; quickstart: Tab[] }) {
- return (
- <>
- <Section id="install">
- <p className="doc-p">Install the package, then import a figure wherever your interface runs.</p>
- <div className="max-w-[460px]"><Install commands={commands} /></div>
- <p className="doc-note">
- Click the command to switch package manager. ESM only, no dependencies, <span data-size>{size}</span> gzipped for all six; a bundle that imports one carries one.
- </p>
- </Section>
- <Section id="quick-start">
- <p className="doc-p">Paste a figure. It fills its parent&rsquo;s width at a 5:4 aspect ratio.</p>
- <Tabs tabs={quickstart} label="Quick start" />
- </Section>
- <Section id="options">
- <p className="doc-p">Every figure takes the same four options, all optional.</p>
- <div className="overflow-x-auto">
- <table className="props" data-options>
- <thead>
- <tr><th>Option</th><th>Type</th><th>Default</th><th>What it does</th></tr>
- </thead>
- <tbody>
- {OPTIONS.map((row) => (
- <tr key={row.name}>
- <td><code>{row.name}</code></td><td><code>{row.type}</code></td><td><code>{row.default}</code></td><td>{row.description}</td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- </Section>
- </>
- );
-}
-
-export function Api({ code }: { code: { reactSignature: string; react: string; vanillaSignature: string; vanilla: string; cdn: string } }) {
- return (
- <>
- <Section id="react">
- <CodeBlock title="Signature" html={code.reactSignature} plain />
- <p className="doc-p">
- Import any of the six from <C>{PACKAGE}/react</C>. Each renders a <C>&lt;div&gt;</C>, takes any <C>&lt;div&gt;</C> attribute and forwards its ref. The entry is a client module, so a Server Component renders it without writing <C>&quot;use client&quot;</C>.
- </p>
- <CodeBlock title="app/page.tsx" html={code.react} />
- </Section>
- <Section id="vanilla">
- <CodeBlock title="Signature" html={code.vanillaSignature} plain />
- <p className="doc-p">
- One function per figure, named in lower case: {FIGURES.map((f, i) => <span key={f.id}>{i ? ", " : ""}<C>{f.id}</C></span>)}. In <C>update</C>, a key set to <C>undefined</C> goes back to its default and a key left out stays as it is. <C>destroy</C> removes the drawing and its listeners.
- </p>
- <CodeBlock title="main.ts" html={code.vanilla} />
- </Section>
- <Section id="cdn">
- <p className="doc-p">Without a bundler, import from esm.sh in a module script.</p>
- <CodeBlock title="index.html" html={code.cdn} />
- </Section>
- </>
- );
-}
-
-export function Reference({ css }: { css: string }) {
- return (
- <>
- <Section id="figures">
- <p className="doc-p">Every figure takes <C>intensity</C>, from 0 to 1. Here is what it turns up.</p>
- <ul className="grid">
- {FIGURES.map((doc) => {
- const Small = SMALL[doc.id];
- return (
- <li key={doc.id} className="figure-row" data-row={doc.id}>
- <div>
- <h3 className="text-[20px] font-medium leading-none tracking-[-0.02em]">{doc.name}</h3>
- <p className="mt-3 text-[15px] leading-[1.5]">Higher intensity: {doc.stronger}</p>
- <p className="mt-1 max-w-[52ch] text-[14px] leading-[1.55] text-muted">{doc.summary}</p>
- </div>
- <div className="tile w-full max-w-[240px] justify-self-end"><Small /></div>
- </li>
- );
- })}
- </ul>
- <div className="table-scroll" tabIndex={0} role="region" aria-label="What intensity sets in each figure">
- <table className="intensity" data-intensity>
- <thead>
- <tr><th>Figure</th><th>Parameter</th><th>0</th><th>0.5</th><th>1</th></tr>
- </thead>
- <tbody>
- {FIGURES.map((doc) => (
- <tr key={doc.id}>
- <td>{doc.name}</td>
- <td><code>{doc.parameter.name}</code></td>
- {INTENSITY[doc.id].map((n, i) => <td key={i}><code>{measure(n, doc.parameter.unit)}</code></td>)}
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- <a className="doc-more" href="/#try">Try them on the home page →</a>
- </Section>
- <Section id="theme">
- <p className="doc-p">
- Six custom properties, set on the figure or on any ancestor. Without them a figure is light, or dark when an ancestor has class <C>dark</C> or <C>data-theme=&quot;dark&quot;</C>, or when the page&rsquo;s <C>color-scheme</C> is dark.
- </p>
- <div className="overflow-x-auto">
- <table className="props" data-tokens>
- <thead>
- <tr><th>Property</th><th>Light</th><th>Role</th></tr>
- </thead>
- <tbody>
- {THEME.map((t) => (
- <tr key={t.property}><td><code>{t.property}</code></td><td><code>{t.light}</code></td><td>{t.role}</td></tr>
- ))}
- </tbody>
- </table>
- </div>
- <CodeBlock title="globals.css" html={css} />
- </Section>
- <Section id="accessibility">
- <ul className="doc-list">
- <li>Each figure is an image with a description; <C>label</C> (or <C>aria-label</C> in React) replaces it.</li>
- <li>Riffle is a focusable group: the arrow keys walk its cards and a live region reads out the card&rsquo;s number.</li>
- <li>Under <C>prefers-reduced-motion</C>, Phosphor and Slow hold still, and every figure still answers the pointer.</li>
- </ul>
- </Section>
- </>
- );
-}
-```
-
-- [ ] **Step 6: Rewrite `app/docs/page.tsx`**
-
-```tsx
-import type { Metadata } from "next";
-import { Footer, Topbar } from "@/components/chrome";
-import { LINKS } from "@/lib/figures";
-import { highlight } from "@/lib/highlight";
-import { tiny } from "@/lib/size";
-import { CDN, CSS, QUICKSTART, REACT, REACT_SIGNATURE, VANILLA, VANILLA_SIGNATURE, install } from "@/lib/snippets";
-import { Api, GettingStarted, Reference } from "./sections";
-
-const SITE = process.env.NEXT_PUBLIC_SITE_URL!;
-
-export const metadata: Metadata = { title: "Docs · hairline", alternates: { canonical: "/docs" } };
-
-/**
- * The docs: one page of sections. A Server Component, so every snippet is
- * highlighted at build and each figure goes through server rendering and
- * hydration on every deploy, as on the home.
- */
-export default async function Docs() {
- const [quickstart, reactSignature, react, vanillaSignature, vanilla, cdn, css] = await Promise.all([
- Promise.all(QUICKSTART.map(async (q) => ({ label: q.label, file: q.file, html: await highlight(q.code, q.lang) }))),
- highlight(REACT_SIGNATURE, "tsx"),
- highlight(REACT, "tsx"),
- highlight(VANILLA_SIGNATURE, "ts"),
- highlight(VANILLA, "ts"),
- highlight(CDN, "html"),
- highlight(CSS, "css"),
- ]);
-
- return (
- <>
- <Topbar />
- <div className="docs">
- <main className="docs-main">
- <header className="max-w-[64ch]">
- <h1 className="text-[36px] font-medium leading-[1.05] tracking-[-0.035em] md:text-[44px]">Six figures, one set of options.</h1>
- <p className="mt-4 text-[16px] leading-[1.55] text-muted">
- Every figure takes the same four options and draws itself in SVG, with no dependencies. Install the package, paste a figure, and turn <code className="doc-code">intensity</code> up or down.
- </p>
- </header>
- <GettingStarted commands={install(SITE)} size={tiny()} quickstart={quickstart} />
- <Api code={{ reactSignature, react, vanillaSignature, vanilla, cdn }} />
- <Reference css={css} />
- <p className="doc-note">
- Anything missing? <a className="doc-more" href={`${LINKS.github}/issues`}>Open an issue on GitHub</a>.
- </p>
- </main>
- </div>
- <Footer />
- </>
- );
-}
-```
-
-- [ ] **Step 7: Give the home's figure its anchor**
-
-In `app/page.tsx`, replace:
-
-```tsx
- <section aria-label="Try it">
-```
-
-with:
-
-```tsx
- <section id="try" aria-label="Try it" className="scroll-mt-[calc(var(--topbar)+24px)]">
-```
-
-- [ ] **Step 8: Delete `PASTE` and `CARDS`**
-
-- In `lib/snippets.ts`, delete the `/** The quickstart's second step. */` comment and the whole `PASTE` constant under it.
-- In `lib/figures.ts`, delete the `/** The four cards under the figures. … */` comment and the whole `CARDS` constant under it.
-
-- [ ] **Step 9: The CSS for the docs**
-
-In `app/globals.css`:
-
-1. Add `--topbar: 54px;` as the first line inside `:root`.
-
-2. In `.topbar`, replace `padding: 12px clamp(18px, 5vw, 28px);` with:
-
- ```css
- height: var(--topbar); padding: 0 clamp(18px, 5vw, 28px);
- ```
-
-3. Replace the 8 lines from `.code { overflow: hidden; …` through `.code-panel code { font: inherit; }` with:
-
-```css
-/* Code: a frame, a bar with the title and a copy icon, the code. Line numbers are a counter in ::before, so they are never selected or copied. */
-.code { overflow: hidden; border-radius: 12px; background: #fafafa; box-shadow: inset 0 0 0 1px var(--color-stone); }
-.code-bar { display: flex; align-items: center; gap: 8px; min-height: 44px; padding: 4px 4px 4px 14px; border-bottom: 1px solid var(--color-stone); }
-.code-tabs { display: flex; flex: none; gap: 2px; margin-left: -8px; }
-.code-tab { border-radius: 7px; padding: 6px 10px; font-size: 13px; font-weight: 500; line-height: 1; color: var(--color-muted); transition: background-color 150ms ease, color 150ms ease; }
-.code-tab[aria-selected="true"] { background: #fff; color: var(--color-ink); box-shadow: 0 0 0 1px var(--color-stone); }
-.code-tab:hover { color: var(--color-ink); }
-.code-title { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; color: var(--color-muted); }
-.code-tabs + .code-title { text-align: right; }
-.code-body { overflow-x: auto; padding: 16px 18px; font: 400 13px/1.65 var(--font-mono); }
-.code-body pre { margin: 0; }
-.code-body code { font: inherit; counter-reset: line; }
-.code-body .line::before { counter-increment: line; content: counter(line); display: inline-block; width: 2ch; margin-right: 16px; text-align: right; color: var(--color-faint); }
-.code-body[data-plain] .line::before { content: none; }
-```
-
-4. Delete these four lines:
-
- ```css
- .card { … }
- .step { min-width: 0; }
- .step-title { … }
- .step-n { … }
- ```
-
- Also delete the empty line that separates them from `.props`.
-
-5. Replace the five `.props` lines with:
-
-```css
-.props, .intensity { width: 100%; border-collapse: collapse; font-size: 13px; }
-:is(.props, .intensity) th { padding: 8px 14px 8px 0; text-align: left; font-size: 13px; font-weight: 500; color: var(--color-muted); }
-:is(.props, .intensity) td { padding: 12px 14px 12px 0; vertical-align: top; border-top: 1px solid var(--color-line); line-height: 1.5; }
-.props td:nth-child(-n + 3) { white-space: nowrap; }
-.props td:nth-child(2), .props td:nth-child(3) { color: var(--color-muted); }
-.props[data-tokens] td:nth-child(3) { white-space: normal; color: var(--color-ink); }
-.intensity td { white-space: nowrap; }
-.intensity td:nth-child(n + 3) { color: var(--color-muted); font-variant-numeric: tabular-nums; }
-.table-scroll { overflow-x: auto; border-radius: 4px; }
-
-/* The docs: the header and nine sections in one column. Prose stops at 64ch; code and tables take the column. */
-.docs { --gutter: clamp(18px, 5vw, 28px); --doc-offset: calc(var(--topbar) + 24px); max-width: 1080px; margin: 0 auto; padding: 0 var(--gutter); }
-.docs-main { display: grid; gap: 64px; min-width: 0; padding: 48px 0 96px; }
-.docs-main > * { min-width: 0; }
-.doc-section { display: grid; gap: 16px; scroll-margin-top: var(--doc-offset); }
-.doc-section > * { min-width: 0; }
-.doc-h2 { font-size: 24px; font-weight: 500; line-height: 1.2; letter-spacing: -0.02em; }
-.doc-p, .doc-list { max-width: 64ch; font-size: 15px; line-height: 1.6; text-wrap: pretty; }
-.doc-list { display: grid; gap: 8px; padding-left: 1.2em; list-style: disc; }
-.doc-note { max-width: 64ch; font-size: 14px; line-height: 1.55; color: var(--color-muted); text-wrap: pretty; }
-.doc-code { font-size: 0.9em; color: var(--color-ink); }
-.doc-more { justify-self: start; font-size: 14px; color: var(--color-ink); text-decoration: underline; text-decoration-color: var(--color-faint); text-underline-offset: 4px; }
-.doc-more:hover { text-decoration-color: currentColor; }
-```
-
-6. Replace the focus rule:
-
- ```css
- :is(button, a, input, .code-panel):focus-visible { outline: 1.5px solid var(--color-ink); outline-offset: 2px; }
- ```
-
- with:
-
- ```css
- :is(button, a, input, .code-body, .table-scroll):focus-visible { outline: 1.5px solid var(--color-ink); outline-offset: 2px; }
- ```
-
-7. In `@media (max-width: 640px)`, replace:
-
- ```css
- .figure-row { grid-template-columns: minmax(0, 1fr) 120px; gap: 16px; }
- ```
-
- with:
-
- ```css
- /* a row stacks, text first, and the figure keeps its width */
- .figure-row { grid-template-columns: minmax(0, 1fr); gap: 16px; }
- .figure-row .tile { justify-self: start; }
- ```
-
- Then add this as the last line inside that media query:
-
- ```css
- .props[data-tokens] td:nth-child(3) { flex-basis: 100%; margin-top: 6px; }
- ```
-
-- [ ] **Step 10: Typecheck, then run the Playwright tests to see them pass**
-
-Run: `rtk pnpm typecheck`
-Expected: no errors. If a file still imports `PASTE` or `CARDS`, the error names it. Remove that import, since nothing should use either any more.
-
-Run: `lsof -ti:4320; rtk pnpm build && rtk pnpm exec playwright test`
-Expected: PASS, 20 tests. Task 1 left 15. "Get started…" and "one family…" were replaced in place, and the 5 new tests ("code block copies", "remembers the tab", "storage throws", "320px", "home's figure") make 20.
-
-Run: `rtk pnpm exec vitest run`
-Expected: PASS, 23 tests.
-
-- [ ] **Step 11: Commit**
-
-```bash
-rtk git add components/code-block.tsx components/tabs.tsx app/docs/sections.tsx app/docs/page.tsx app/page.tsx app/globals.css lib/snippets.ts lib/figures.ts test/site.spec.ts
-rtk git commit -m "Docs: one page of nine sections, code in a frame with line numbers and a remembered tab, the figures live with their intensity table
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
----
-
-### Task 4: The sidebar and the phone strip
-
-**Files:**
-- Create: `components/sidebar.tsx`
-- Modify: `app/docs/page.tsx`, `app/globals.css`
-- Test: `test/site.spec.ts`
-
-**Interfaces:**
-- Consumes:
- - `SECTIONS` and `Group` from `lib/docs.ts` (Task 2).
- - `.docs`, `--topbar`, `--doc-offset` and `section#{id}` from Task 3.
-- Produces:
- - `Sidebar()`, a client component with no props, rendered as the first child of `.docs`.
- - Two `<nav aria-label="Docs">` landmarks. `.doc-sidebar` is displayed from 1024px and `.doc-strip` below it, so exactly one is in the accessibility tree at a time.
- - `.doc-strip-scroll`, which carries `data-start` and `data-end` while there is more strip to scroll that way.
-
-- [ ] **Step 1: Write the failing Playwright tests**
-
-Append to `test/site.spec.ts`:
-
-```ts
-test("the sidebar's links land on their section under the top bar and mark it, and scrolling moves the mark", async ({ page }) => {
- await page.goto("/docs");
- const nav = page.getByRole("navigation", { name: "Docs" });
- await expect(nav.getByRole("link")).toHaveText(["Install", "Quick start", "Options", "React", "Vanilla", "CDN", "Figures", "Theme", "Accessibility"]);
- await expect(nav.getByRole("link", { name: "Install" })).toHaveAttribute("aria-current", "location");
-
- await nav.getByRole("link", { name: "Theme" }).click();
- await expect(page).toHaveURL(/\/docs#theme$/);
- await expect(nav.getByRole("link", { name: "Theme" })).toHaveAttribute("aria-current", "location");
- await expect(nav.locator("[aria-current]")).toHaveCount(1);
- await expect.poll(() => page.locator("#theme-title").evaluate((el) => el.getBoundingClientRect().top)).toBeGreaterThanOrEqual(54);
-
- await page.evaluate(() => document.getElementById("figures")!.scrollIntoView());
- await expect(nav.getByRole("link", { name: "Figures" })).toHaveAttribute("aria-current", "location");
-
- // Accessibility is too short to reach the band; the end of the page marks it
- await page.evaluate(() => window.scrollTo(0, document.documentElement.scrollHeight));
- await expect(nav.getByRole("link", { name: "Accessibility" })).toHaveAttribute("aria-current", "location");
-});
-
-test("opening /docs#theme lands on Theme, clear of the top bar, with Theme marked", async ({ page }) => {
- await page.goto("/docs#theme");
- const nav = page.getByRole("navigation", { name: "Docs" });
- await expect(nav.getByRole("link", { name: "Theme" })).toHaveAttribute("aria-current", "location");
- const top = await page.locator("#theme-title").evaluate((el) => el.getBoundingClientRect().top);
- expect(top).toBeGreaterThanOrEqual(54);
- expect(top).toBeLessThan(200);
-});
-
-test("on a phone the sidebar is one strip under the top bar, and it follows the reader", async ({ page }) => {
- await page.setViewportSize({ width: 390, height: 800 });
- await page.goto("/docs");
- const strip = page.locator(".doc-strip");
- const scroller = strip.locator(".doc-strip-scroll");
- await expect(strip).toBeVisible();
- await expect(page.locator(".doc-sidebar")).toBeHidden();
- expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390);
- await expect(scroller).toHaveAttribute("data-end", "");
- await expect(scroller).not.toHaveAttribute("data-start");
-
- const inside = async (name: string) => {
- const s = (await scroller.boundingBox())!;
- const b = (await strip.getByRole("link", { name }).boundingBox())!;
- return b.x >= s.x - 1 && b.x + b.width <= s.x + s.width + 1;
- };
- // the page moves, not the strip: the strip has to bring Accessibility in by itself
- await page.evaluate(() => window.scrollTo(0, document.documentElement.scrollHeight));
- await expect(strip.getByRole("link", { name: "Accessibility" })).toHaveAttribute("aria-current", "location");
- await expect.poll(() => inside("Accessibility")).toBe(true);
- await expect(scroller).toHaveAttribute("data-start", "");
-
- await strip.getByRole("link", { name: "Install" }).click();
- await expect(page).toHaveURL(/#install$/);
- await expect(strip.getByRole("link", { name: "Install" })).toHaveAttribute("aria-current", "location");
- await expect.poll(() => inside("Install")).toBe(true);
- // the heading clears the top bar and the strip
- await expect.poll(async () => {
- const s = (await strip.boundingBox())!;
- const t = (await page.locator("#install-title").boundingBox())!;
- return t.y >= s.y + s.height;
- }).toBe(true);
- expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390);
-});
-
-test.describe("without JavaScript", () => {
- test.use({ javaScriptEnabled: false });
-
- test("the sidebar is plain links that still move the page, and the quick start shows React", async ({ page }) => {
- await page.goto("/docs");
- const nav = page.getByRole("navigation", { name: "Docs" });
- await expect(nav.getByRole("link", { name: "Theme" })).toHaveAttribute("href", "#theme");
- await nav.getByRole("link", { name: "Theme" }).click();
- await expect(page).toHaveURL(/\/docs#theme$/);
- const quick = page.locator("#quick-start");
- await expect(quick.getByRole("tab", { name: "React" })).toHaveAttribute("aria-selected", "true");
- await expect(quick.locator(".code-title")).toHaveText("app/page.tsx");
- });
-});
-```
-
-- [ ] **Step 2: Run them to see them fail**
-
-Run: `lsof -ti:4320; rtk pnpm build && rtk pnpm exec playwright test -g "sidebar|#theme|strip|without JavaScript"`
-Expected: FAIL, 4 tests. There is no navigation named "Docs" and no `.doc-strip`, so each one times out on its first locator.
-
-- [ ] **Step 3: Create `components/sidebar.tsx`**
-
-```tsx
-"use client";
-
-import { useEffect, useRef, useState } from "react";
-import { SECTIONS, type Group } from "@/lib/docs";
-
-const GROUPS = [...new Set(SECTIONS.map((s) => s.group))] as Group[];
-const LAST = SECTIONS[SECTIONS.length - 1].id;
-
-/**
- * The docs' anchors: grouped in a column beside the page from 1024px, one
- * sideways strip under the top bar below it. Both are plain links, so they
- * work without JavaScript; the script only marks the section in view, which
- * is the first one, in page order, inside a band from under the sticky
- * chrome to 30% down the viewport.
- */
-export function Sidebar() {
- const [active, setActive] = useState(SECTIONS[0].id);
- const [edges, setEdges] = useState({ start: false, end: false });
- const strip = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- const sections = SECTIONS.map((s) => document.getElementById(s.id)).filter((el): el is HTMLElement => el !== null);
- if (!sections.length) return;
- // the band starts where a section lands after a click: its scroll-margin-top, under the top bar and on a phone the strip
- const offset = parseFloat(getComputedStyle(sections[0]).scrollMarginTop) || 0;
- const inBand = new Set<string>();
- const pick = () => {
- const end = window.innerHeight + window.scrollY >= document.documentElement.scrollHeight - 2;
- // the last section is too short to reach the band, so the end of the page marks it
- if (end) return setActive(LAST);
- const first = SECTIONS.find((s) => inBand.has(s.id));
- if (first) setActive(first.id);
- };
- const observer = new IntersectionObserver(
- (entries) => {
- for (const entry of entries) {
- if (entry.isIntersecting) inBand.add(entry.target.id);
- else inBand.delete(entry.target.id);
- }
- pick();
- },
- { rootMargin: `-${offset}px 0px -70% 0px` },
- );
- for (const el of sections) observer.observe(el);
- window.addEventListener("scroll", pick, { passive: true });
- return () => {
- observer.disconnect();
- window.removeEventListener("scroll", pick);
- };
- }, []);
-
- useEffect(() => {
- const el = strip.current;
- if (!el) return;
- const measure = () => setEdges({ start: el.scrollLeft > 1, end: el.scrollLeft + el.clientWidth < el.scrollWidth - 1 });
- measure();
- el.addEventListener("scroll", measure, { passive: true });
- const resize = new ResizeObserver(measure);
- resize.observe(el);
- return () => {
- el.removeEventListener("scroll", measure);
- resize.disconnect();
- };
- }, []);
-
- // Brings the marked item into the strip by scrolling the strip alone. scrollIntoView would also scroll the
- // page, and would cut short the smooth scroll a click on the strip has just started.
- useEffect(() => {
- const el = strip.current;
- const item = el?.querySelector<HTMLElement>(`a[href="#${active}"]`);
- if (!el || !item || !el.clientWidth) return;
- const pad = 24;
- if (item.offsetLeft - pad < el.scrollLeft) el.scrollTo({ left: item.offsetLeft - pad });
- else if (item.offsetLeft + item.offsetWidth + pad > el.scrollLeft + el.clientWidth) el.scrollTo({ left: item.offsetLeft + item.offsetWidth + pad - el.clientWidth });
- }, [active]);
-
- const link = (id: string, title: string) => (
- <li key={id}>
- <a href={`#${id}`} className="doc-link" aria-current={id === active ? "location" : undefined}>{title}</a>
- </li>
- );
-
- return (
- <>
- <nav aria-label="Docs" className="doc-sidebar">
- {GROUPS.map((group) => (
- <div key={group} className="doc-group">
- <p className="doc-group-label">{group}</p>
- <ul>{SECTIONS.filter((s) => s.group === group).map((s) => link(s.id, s.title))}</ul>
- </div>
- ))}
- </nav>
- <nav aria-label="Docs" className="doc-strip">
- <div ref={strip} className="doc-strip-scroll" data-start={edges.start || undefined} data-end={edges.end || undefined}>
- <ul>{SECTIONS.map((s) => link(s.id, s.title))}</ul>
- </div>
- </nav>
- </>
- );
-}
-```
-
-Spec deviation: the spec names `scrollIntoView({ block: "nearest", inline: "nearest" })` for the strip. That call scrolls every scrolling ancestor, the page included, and in Chrome it cancels the page's smooth scroll that a click has just started. Scrolling the strip itself, with the same "nearest" rule, keeps the behaviour the spec asks for without that side effect.
-
-- [ ] **Step 4: Put the sidebar on the page**
-
-In `app/docs/page.tsx`:
-
-1. Add the import:
-
- ```tsx
- import { Sidebar } from "@/components/sidebar";
- ```
-
-2. Replace:
-
- ```tsx
- <div className="docs">
- <main className="docs-main">
- ```
-
- with:
-
- ```tsx
- <div className="docs">
- <Sidebar />
- <main className="docs-main">
- ```
-
-- [ ] **Step 5: The CSS for the sidebar, the strip and smooth scrolling**
-
-In `app/globals.css`:
-
-1. Replace `html { color-scheme: light; scroll-behavior: smooth; }` with:
-
- ```css
- html { color-scheme: light; }
- @media (prefers-reduced-motion: no-preference) { html { scroll-behavior: smooth; } }
- ```
-
- Then delete `html { scroll-behavior: auto; }` from the `@media (prefers-reduced-motion: reduce)` block.
-
-2. In the `.docs` rule from Task 3, change `--doc-offset: calc(var(--topbar) + 24px);` to `--doc-offset: calc(var(--topbar) + 60px);`. On a phone that is the top bar, the 44px strip and 16px of air.
-
-3. Add after the `.doc-more:hover` rule:
-
-```css
-/* The sidebar: the same links twice, grouped in a column from 1024px, one sideways strip under the top bar below it. */
-.doc-link { display: flex; align-items: center; height: 32px; padding: 0 10px; border-radius: 8px; font-size: 14px; color: var(--color-muted); white-space: nowrap; transition: background-color 150ms ease, color 150ms ease; }
-.doc-link:hover { color: var(--color-ink); }
-.doc-link[aria-current] { color: var(--color-ink); background: var(--color-stone); }
-.doc-sidebar { display: none; }
-.doc-group-label { margin-bottom: 4px; padding: 0 10px; font-size: 12px; font-weight: 500; color: var(--color-muted); }
-.doc-strip { position: sticky; top: var(--topbar); z-index: 9; margin: 0 calc(-1 * var(--gutter)); background: color-mix(in srgb, var(--color-canvas) 82%, transparent); backdrop-filter: blur(12px); }
-.doc-strip-scroll { overflow-x: auto; padding: 6px var(--gutter); scrollbar-width: none; }
-.doc-strip-scroll::-webkit-scrollbar { display: none; }
-.doc-strip-scroll ul { display: flex; gap: 2px; width: max-content; }
-.doc-strip-scroll[data-start] { mask-image: linear-gradient(to right, transparent, #000 24px); }
-.doc-strip-scroll[data-end] { mask-image: linear-gradient(to right, #000 calc(100% - 24px), transparent); }
-.doc-strip-scroll[data-start][data-end] { mask-image: linear-gradient(to right, transparent, #000 24px, #000 calc(100% - 24px), transparent); }
-@media (min-width: 1024px) {
- .docs { --doc-offset: calc(var(--topbar) + 24px); display: grid; grid-template-columns: 220px minmax(0, 1fr); column-gap: 56px; padding-top: 64px; }
- .docs-main { padding-top: 0; }
- .doc-strip { display: none; }
- .doc-sidebar { display: grid; gap: 24px; align-self: start; position: sticky; top: calc(var(--topbar) + 24px); }
-}
-```
-
-- [ ] **Step 6: Run the tests to see them pass**
-
-Run: `rtk pnpm typecheck`
-Expected: no errors.
-
-Run: `lsof -ti:4320; rtk pnpm build && rtk pnpm exec playwright test`
-Expected: PASS, 24 tests: Task 3's 20 plus the 4 new ones.
-
-Run: `rtk pnpm exec vitest run`
-Expected: PASS, 23 tests.
-
-- [ ] **Step 7: Look at it**
-
-With the server from the last run stopped, run `rtk pnpm exec next start -p 4320` in the background. Then take screenshots with Playwright's `page.screenshot` at three sizes:
-- 1200×900 for `/docs`, the top of the page.
-- 1200×900 for `/docs#figures`.
-- 390×800 for `/docs`, after scrolling to Quick start.
-
-Save them in `/Users/lucasmarques/.claude/jobs/bf2ea971/tmp`, read each one, and check:
-- the sidebar sits beside the h1 and stays under the top bar while scrolling;
-- the strip shows its right fade;
-- code blocks show line numbers in a faint grey, and the signatures show none;
-- the figure rows stack on the phone.
-
-Then stop the server. Any defect goes back through a failing test first.
-
-- [ ] **Step 8: Commit and push**
-
-```bash
-rtk git add components/sidebar.tsx app/docs/page.tsx app/globals.css test/site.spec.ts
-rtk git commit -m "Docs: a sidebar of anchors marks the section in view, and on a phone it is one strip under the top bar that follows the reader
-
-Co-Authored-By: Claude <[email protected]>"
-rtk git push origin site-on-vercel
-```
-
-Expected: the push updates PR #1's branch. Vercel builds a preview from it.
diff --git a/docs/superpowers/plans/2026-10-01-hairline-dx-redesign.md b/docs/superpowers/plans/2026-10-01-hairline-dx-redesign.md
deleted file mode 100644
index a29df12..0000000
--- a/docs/superpowers/plans/2026-10-01-hairline-dx-redesign.md
+++ /dev/null
@@ -1,3072 +0,0 @@
-# Hairline: one prop, and a site that leads with the install — Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Replace the six per-figure options with one `intensity` option, take the names and hit bands out of Riffle, and rebuild the site in cuelume's structure: install first, a live inspector, then a two-step quickstart.
-
-**Architecture:** One internal module, `packages/hairline/src/intensity.ts`, turns `intensity` (0…1) into each figure's own parameter through a table of three points per figure. Every figure takes one options type, `HairlineOptions`, in both entries. The site keeps a copy of the table that a unit test holds equal to the package's, and builds one page from small client components (install pill, inspector, copy button) around statically rendered copy.
-
-**Tech Stack:** pnpm 10.20 workspace with Turborepo 2, TypeScript 5.9 strict, Node 22. Package: tsup (ESM), Vitest 5 with jsdom, Playwright 1.63 on installed Chrome (`channel: "chrome"`). Site: Next.js 16 (App Router, Turbopack, static prerender), React 19, Tailwind 4, Geist, Geist Mono and Instrument Serif through `next/font/google`, Shiki at build.
-
-**Spec:** `docs/superpowers/specs/2026-10-01-hairline-dx-redesign-design.md`, an amendment to `docs/superpowers/specs/2026-10-01-hairline-package-design.md`. Where the amendment speaks to a topic it replaces the base spec; everything else in the base spec stands. This plan sits between Task 14 Step 6 and Task 14 Step 7 of `docs/superpowers/plans/2026-10-01-hairline-package.md`, which resumes after its last task.
-
-## Global Constraints
-
-- All work is on the branch `site-on-vercel` of `~/estudos/hairline` (PR #1). Every command runs from the repository root unless a step says otherwise.
-- Nothing is pushed before Task 7. The site does not typecheck or build from Task 2 until Task 6 (it imports `ranges` and the old option names); that is expected, and only the package's gates must be green in Tasks 1 to 4.
-- The figures look exactly as they do today at the default. The parity goldens in `packages/hairline/test/parity/golden/` are never captured again: do not run `pnpm --filter @lucasmarkes/hairline capture`.
-- The `intensity` map, verbatim from the spec: two straight lines that meet at 0.5, rounded to three decimal places.
-
- | Figure | Parameter (internal) | 0 | 0.5 | 1 |
- | --- | --- | --- | --- | --- |
- | Riffle | stagger (ms) | 0 | 40 | 90 |
- | Terrain | radius (cells) | 1.5 | 3 | 5 |
- | Exploded | gap (viewBox units) | 12 | 28 | 40 |
- | Phosphor | afterglow (ms) | 150 | 520 | 1500 |
- | Slow | rate (× normal speed) | 0.6 | 0.2 | 0.05 |
- | Turntable | coast (ms) | 200 | 650 | 1500 |
-
-- Values `intensity` accepts: a finite number is clamped to 0…1; a numeric string is read as a number; anything else (`undefined`, `NaN`, `Infinity`, `""`, an object) is 0.5. `update({ intensity: undefined })` goes back to 0.5, and a key left out of `update` keeps its value.
-- The public API is exactly: from `@lucasmarkes/hairline`, the six functions and the types `HairlineOptions` and `Figure`; from `@lucasmarkes/hairline/react`, the six components and the type `HairlineProps`. `src/intensity.ts` is exported from neither.
-- Riffle's caption and live region carry the card's number only (`"03"`, `"rest"`). Selection does not change.
-- The site's copy is in English. No tile carries "Fig. N". The inspector's snippet shows only the props that differ from the default.
-- The size budgets in `packages/hairline/package.json` do not change: 12.8 kB (vanilla, all six), 5.4 kB (one figure), 13.2 kB (React).
-- Every commit message ends with a blank line and `Co-Authored-By: Claude <[email protected]>`.
-- Never commit `.vercel/`, `.superpowers/` or anything under `.claude/`.
-
-## Review Focus
-
-1. A caller without types passes `intensity` as a string from an attribute (`"0.8"`), out of range (`-3`, `7`), or as junk (`NaN`, `null`, `{}`): every figure mounts, updates and draws, with no `NaN` in the markup, and `"1"` draws as `1` does. Pinned in Task 1 (`intensity.test.ts`: "reads a numeric string…", "clamps to 0…1") and Task 2 (`mount.test.ts`: "mounts, updates and draws with %o as the intensity", and the `text` host in "reaches %s's engine…").
-2. A React prop that is removed (`<Terrain intensity={1} />` re-rendered as `<Terrain />`) goes back to 0.5, not to the last value. Pinned in Task 2 (`react.test.tsx`: "puts intensity back to 0.5 when the prop is removed").
-3. The inspector's snippet at the default: a slider value that only reads as 0.5 (`0.1 + 0.4`, `0.5000001`) is left out, and `0`, which is falsy, is still shown. Pinned in Task 5 (`docs.test.ts`: "leaves out an intensity that reads as 0.5…", "shows an intensity of 0…").
-4. Copy without clipboard permission (an iframe, an insecure origin, a denied prompt): the button selects the text so the reader can copy it by hand, and nothing is thrown. Pinned in Task 6 (`site.spec.ts`: "without a clipboard, copy selects the text instead and throws nothing").
-5. A phone, 390 px wide, with the longest install command (shadcn's) and the inspector's controls: no horizontal scroll, and every control on screen. Pinned in Task 6 (`site.spec.ts`: "the page fits a phone, with the longest install command and every control").
-
----
-
-### Task 1: The intensity map
-
-**Files:**
-- Create: `packages/hairline/src/intensity.ts`
-- Create: `packages/hairline/test/intensity.test.ts`
-- Modify: `packages/hairline/test/parity/scripts.mjs` (add `INTENSITY` after `OPTION`)
-
-**Interfaces:**
-- Consumes: nothing new. `test/parity/scripts.mjs` already exports `FIGURES`, `OPTION` (each figure's option name and the value its parity script sets) and `SCRIPTS`.
-- Produces, all internal to the package (neither entry exports them):
- - `type FigureId = "riffle" | "terrain" | "exploded" | "phosphor" | "slow" | "turntable"`
- - `const TABLE: Record<FigureId, readonly [number, number, number]>`, each figure's parameter at intensity 0, 0.5 and 1.
- - `const DEFAULT = 0.5`
- - `function intensity(value: unknown): number`, an intensity from anything, in 0…1.
- - `function parameter(figure: FigureId, value: unknown): number`, the figure's own number, rounded to three decimals.
- - From `test/parity/scripts.mjs`: `INTENSITY: Record<string, number>`, the intensity whose mapped value is `OPTION[id][1]`. Task 2's parity test sets it.
-
-- [ ] **Step 1: Write the failing test**
-
-The test pins the three points of every row, the direction of every row (Slow's falls), the parity intensities against the goldens' raw values, and the accepted values from the spec.
-
-`packages/hairline/test/intensity.test.ts`
-```ts
-import { describe, expect, it } from "vitest";
-import { DEFAULT, TABLE, intensity, parameter, type FigureId } from "../src/intensity";
-import { INTENSITY, OPTION } from "./parity/scripts.mjs";
-
-const IDS = Object.keys(TABLE) as FigureId[];
-
-describe("intensity", () => {
- it("keeps a number inside 0…1", () => {
- expect(intensity(0.8)).toBe(0.8);
- });
- it("clamps to 0…1", () => {
- expect(intensity(-3)).toBe(0);
- expect(intensity(7)).toBe(1);
- });
- it("reads a numeric string, as an attribute or a form field would give it", () => {
- expect(intensity("0.8")).toBe(0.8);
- expect(intensity(" 7 ")).toBe(1);
- });
- it.each([undefined, null, NaN, Infinity, -Infinity, "", " ", "fast", {}, [], true])("falls back to 0.5 for %o", (v) => {
- expect(intensity(v)).toBe(DEFAULT);
- expect(DEFAULT).toBe(0.5);
- });
-});
-
-describe("parameter", () => {
- it.each(IDS)("gives %s its table's three values at 0, 0.5 and 1", (id) => {
- expect([0, 0.5, 1].map((i) => parameter(id, i))).toEqual(TABLE[id]);
- });
-
- it.each(IDS)("moves %s one way only as intensity rises", (id) => {
- const values = Array.from({ length: 21 }, (_, k) => parameter(id, k / 20));
- const falls = id === "slow";
- for (let k = 1; k < values.length; k++) {
- if (falls) expect(values[k]).toBeLessThan(values[k - 1]);
- else expect(values[k]).toBeGreaterThan(values[k - 1]);
- }
- });
-
- it("rounds to three decimals", () => {
- expect(parameter("riffle", 0.7)).toBe(60);
- expect(parameter("riffle", 0.333)).toBe(26.64);
- });
-
- it("reads the intensity the way intensity() does", () => {
- expect(parameter("terrain", "0.75")).toBe(4);
- expect(parameter("terrain", 9)).toBe(5);
- expect(parameter("terrain", "fast")).toBe(3);
- });
-
- /* the parity goldens were captured with raw values; these intensities must land on them exactly */
- it.each(IDS)("lands %s on the golden's value at its parity intensity", (id) => {
- const raw = OPTION[id][1];
- expect(parameter(id, INTENSITY[id])).toBe(raw);
- });
-});
-```
-
-Add `INTENSITY` to the parity scripts, after `OPTION`, so the test above can import it:
-
-`packages/hairline/test/parity/scripts.mjs (diff)`
-```diff
---- a/packages/hairline/test/parity/scripts.mjs
-+++ b/packages/hairline/test/parity/scripts.mjs
-@@ -11,6 +11,12 @@ export const OPTION = {
- phosphor: ["afterglow", 900], slow: ["rate", 0.4], turntable: ["coast", 1000],
- };
-
-+/** The intensity the package is set to at `set`: each maps exactly onto the value in OPTION (test/intensity.test.ts holds them together). */
-+export const INTENSITY = {
-+ riffle: 0.7, terrain: 0.75, exploded: 5 / 6,
-+ phosphor: 0.5 + 190 / 980, slow: 0.25, turntable: 0.5 + 175 / 850,
-+};
-+
- export const SCRIPTS = {
- riffle: [
- { adv: 30 }, { cp: "rest" },
-```
-
-- [ ] **Step 2: Run the test to see it fail**
-
-Run: `pnpm --filter @lucasmarkes/hairline exec vitest run test/intensity.test.ts`
-Expected: FAIL, `Error: Cannot find module '../src/intensity'`, and no tests run.
-
-- [ ] **Step 3: Write the module**
-
-`packages/hairline/src/intensity.ts`
-```ts
-/**
- * One option, `intensity`, for every figure. Each figure turns it into the
- * one number its engine takes: two straight lines that meet at 0.5, where the
- * number is the figure's default, with the figure's limits at 0 and 1.
- *
- * Internal: neither entry exports this. The site keeps a copy of TABLE for its
- * copy and its tests hold the two together.
- */
-
-export type FigureId = "riffle" | "terrain" | "exploded" | "phosphor" | "slow" | "turntable";
-
-/** Each figure's number at intensity 0, 0.5 and 1. Slow's falls: a slower clock is a stronger answer. */
-export const TABLE: Record<FigureId, readonly [number, number, number]> = {
- riffle: [0, 40, 90], // stagger, ms
- terrain: [1.5, 3, 5], // radius, cells
- exploded: [12, 28, 40], // gap, viewBox units
- phosphor: [150, 520, 1500], // afterglow, ms
- slow: [0.6, 0.2, 0.05], // rate, × normal speed
- turntable: [200, 650, 1500], // coast, ms
-};
-
-export const DEFAULT = 0.5;
-
-/** An intensity from anything: numeric strings are read, what is not a finite number is the default, the rest is clamped to 0…1. */
-export function intensity(value: unknown): number {
- const n = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
- if (typeof n !== "number" || !Number.isFinite(n)) return DEFAULT;
- return Math.min(1, Math.max(0, n));
-}
-
-/** The figure's own number for an intensity, rounded to three decimals so 0.7 gives Riffle 60 and not 59.99999999999999. */
-export function parameter(figure: FigureId, value: unknown): number {
- const [lo, mid, hi] = TABLE[figure];
- const i = intensity(value);
- const v = i <= 0.5 ? lo + (i / 0.5) * (mid - lo) : mid + ((i - 0.5) / 0.5) * (hi - mid);
- return Math.round(v * 1000) / 1000;
-}
-```
-
-- [ ] **Step 4: Run the test to see it pass, then the package's gates**
-
-Run: `pnpm --filter @lucasmarkes/hairline exec vitest run test/intensity.test.ts`
-Expected: PASS, 34 tests.
-
-Run: `pnpm --filter @lucasmarkes/hairline test && pnpm --filter @lucasmarkes/hairline typecheck`
-Expected: every test file passes, and `tsc --noEmit` prints nothing. Nothing imports the module yet, so nothing else changes.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add packages/hairline/src/intensity.ts packages/hairline/test/intensity.test.ts packages/hairline/test/parity/scripts.mjs
-git commit -m "Intensity: one number from 0 to 1, mapped onto each figure's own parameter
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-### Task 2: One options type for both entries
-
-**Files:**
-- Modify: `packages/hairline/src/mount.ts` (the options type and the `update` merge)
-- Modify: `packages/hairline/src/index.ts` (the six functions take `HairlineOptions` and map `intensity`)
-- Modify: `packages/hairline/src/react.tsx` (one props type, `HairlineProps`)
-- Delete: `packages/hairline/src/ranges.ts`, `packages/hairline/test/ranges.test.ts`
-- Test: `packages/hairline/test/mount.test.ts`, `packages/hairline/test/react.test.tsx`, `packages/hairline/test/ssr.test.tsx`, `packages/hairline/test/types.test-d.tsx`
-- Test: `packages/hairline/test/browser/parity.spec.ts`, `packages/hairline/test/browser/figures.spec.ts`
-
-**Interfaces:**
-- Consumes from Task 1: `parameter(figure, value)` and `FigureId` from `src/intensity.ts`; `INTENSITY` from `test/parity/scripts.mjs`.
-- Produces, the whole public API from here on:
- - `src/mount.ts`:
- ```ts
- export type HairlineOptions = { intensity?: number; theme?: "auto" | "light" | "dark"; label?: string; onRead?: (text: string) => void };
- export type Figure = { update(options: HairlineOptions): void; destroy(): void };
- export function create(spec: Spec, el: HTMLElement, options?: HairlineOptions): Figure;
- ```
- In `update`, a key whose value is `undefined` is deleted from the stored options (it goes back to its default); a key that is absent is kept.
- - `src/index.ts`: `riffle`, `terrain`, `exploded`, `phosphor`, `slow`, `turntable`, each `(el: HTMLElement, options?: HairlineOptions) => Figure`, and `export type { Figure, HairlineOptions }`. Nothing else: `ranges`, `Range`, `BaseOptions`, `Theme` and the six `*Options` types are gone.
- - `src/react.tsx`: `export type HairlineProps = HairlineOptions & Omit<ComponentPropsWithoutRef<"div">, "children" | keyof HairlineOptions>`, and the six components, each taking `HairlineProps` with `ref` reaching the `<div>`. `FigureProps`, `FigureComponent` and the six `*Props` types are gone.
- - Riffle is mounted with no names, so its caption and live region read the card's number only. Task 3 removes the names from the engine itself.
-
-The parity goldens still hold Riffle's hit bands and the site's card names. The parity test now removes both from both sides before comparing, the way it would normalise ids, and sets `intensity` at `set` instead of the old option. The goldens are not captured again.
-
-- [ ] **Step 1: Write the failing tests**
-
-Replace `packages/hairline/test/mount.test.ts`. The new `intensity` block mounts six hosts side by side on one clock (default, 0.5, 0, 1, the string `"1"`, and 1 reset through `update({ intensity: undefined })`) and plays the same input into all of them, which pins that the prop reaches every engine at mount and through `update`. "mounts, updates and draws with %o as the intensity" is Review Focus 1. The caption block's "reads a pulled card out by its number alone…" replaces the old names test.
-
-`packages/hairline/test/mount.test.ts`
-```ts
-// @vitest-environment jsdom
-import { describe, expect, it, vi } from "vitest";
-import { frames, host, observers, pending } from "./dom";
-import { exploded, phosphor, riffle, slow, terrain, turntable } from "../src/index";
-
-const ALL = { riffle, terrain, exploded, phosphor, slow, turntable };
-const key = (el: Element, k: string) => el.dispatchEvent(new KeyboardEvent("keydown", { key: k, bubbles: true, cancelable: true }));
-
-describe("mount", () => {
- it.each(Object.entries(ALL))("%s draws into the element and takes it all back", (id, mount) => {
- const el = host();
- el.className = "mine";
- const f = mount(el);
- expect(el.getAttribute("data-hairline")).toBe(id);
- expect(el.querySelectorAll(":scope > svg")).toHaveLength(1);
- expect(el.querySelector("svg")!.getAttribute("viewBox")).toBe("0 0 400 320");
- expect(el.querySelector("svg")!.childElementCount).toBeGreaterThan(0);
- expect(el.getAttribute("aria-label")).toBeTruthy();
- f.destroy();
- expect(el.outerHTML).toBe('<div class="mine"></div>');
- });
-
- it("makes Riffle a focusable group with a live region, and the others images", () => {
- const a = host(), b = host();
- riffle(a); terrain(b);
- expect(a.getAttribute("role")).toBe("group");
- expect(a.getAttribute("tabindex")).toBe("0");
- expect(a.querySelector("[data-hairline-live]")!.getAttribute("aria-live")).toBe("polite");
- expect(b.getAttribute("role")).toBe("img");
- expect(b.hasAttribute("tabindex")).toBe(false);
- expect(b.querySelector("[data-hairline-live]")).toBeNull();
- });
-
- it("leaves the host's own attributes alone, at mount and at destroy", () => {
- const el = host();
- el.setAttribute("role", "figure");
- el.setAttribute("tabindex", "-1");
- el.setAttribute("aria-label", "My cards");
- const f = riffle(el, { label: "ignored" });
- expect(el.getAttribute("role")).toBe("figure");
- expect(el.getAttribute("tabindex")).toBe("-1");
- expect(el.getAttribute("aria-label")).toBe("My cards");
- f.destroy();
- expect(el.getAttribute("role")).toBe("figure");
- expect(el.getAttribute("tabindex")).toBe("-1");
- expect(el.getAttribute("aria-label")).toBe("My cards");
- });
-
- it("does not name an element that aria-labelledby already names", () => {
- const el = host();
- el.setAttribute("aria-labelledby", "caption");
- const f = terrain(el);
- expect(el.hasAttribute("aria-label")).toBe(false);
- f.destroy();
- expect(el.getAttribute("aria-labelledby")).toBe("caption");
- });
-
- it("drops its own name when the element gains aria-labelledby", () => {
- const el = host();
- const f = terrain(el);
- el.setAttribute("aria-labelledby", "caption");
- f.update({});
- expect(el.hasAttribute("aria-label")).toBe(false);
- });
-
- it("throws a TypeError for something that is not an element", () => {
- expect(() => riffle(null as unknown as HTMLElement)).toThrow(TypeError);
- expect(() => riffle("#cards" as unknown as HTMLElement)).toThrow(/takes an element/);
- });
-
- it("replaces a figure already on the element", () => {
- const el = host();
- riffle(el);
- terrain(el);
- expect(el.querySelectorAll(":scope > svg")).toHaveLength(1);
- expect(el.getAttribute("data-hairline")).toBe("terrain");
- expect(el.getAttribute("role")).toBe("img");
- expect(el.hasAttribute("tabindex")).toBe(false);
- expect(el.querySelector("[data-hairline-live]")).toBeNull();
- });
-
- it("puts the stylesheet in the document once, however many figures mount", () => {
- riffle(host()); terrain(host()); slow(host());
- const sheets = document.adoptedStyleSheets?.length ?? 0;
- expect(sheets + document.querySelectorAll("style[data-hairline-style]").length).toBe(1);
- });
-});
-
-describe("options", () => {
- it("sets and clears the theme attribute", () => {
- const el = host();
- const f = terrain(el, { theme: "dark" });
- expect(el.getAttribute("data-hairline-theme")).toBe("dark");
- f.update({ theme: "light" });
- expect(el.getAttribute("data-hairline-theme")).toBe("light");
- f.update({ theme: "auto" });
- expect(el.hasAttribute("data-hairline-theme")).toBe(false);
- f.update({ theme: "dark" });
- f.update({ theme: undefined });
- expect(el.hasAttribute("data-hairline-theme")).toBe(false);
- });
-
- it("updates the label, and goes back to the default when it is removed", () => {
- const el = host();
- const f = terrain(el);
- const standard = el.getAttribute("aria-label");
- f.update({ label: "Dunes" });
- expect(el.getAttribute("aria-label")).toBe("Dunes");
- f.update({ label: undefined });
- expect(el.getAttribute("aria-label")).toBe(standard);
- });
-
- // Review Focus 1: a caller without types passes what it has
- it.each(["0.8", -3, 7, NaN, null, "fast", {}, Infinity])("mounts, updates and draws with %o as the intensity", (v) => {
- const el = host();
- const bad = v as unknown as number;
- for (const mount of Object.values(ALL)) {
- const f = mount(el, { intensity: bad });
- el.dispatchEvent(new MouseEvent("pointermove", { clientX: 200, clientY: 160, bubbles: true }));
- f.update({ intensity: bad });
- frames(3);
- expect(el.querySelector("svg")!.innerHTML).not.toMatch(/NaN|Infinity|undefined/);
- f.destroy();
- }
- });
-});
-
-describe("intensity", () => {
- /* the same input for every host: a point, or a number of frames */
- const PLAY: Record<keyof typeof ALL, Array<[number, number] | number>> = {
- riffle: [[150, 120], 12],
- terrain: [[200, 160], 20],
- exploded: [[100, 80], 30],
- phosphor: [[240, 140], 2, [260, 145], 2, [280, 150], 15],
- slow: [[200, 160], 60],
- turntable: [[50, 176], 1, [120, 176], 1, [200, 176], 1, [280, 176], 1, [350, 176], 40],
- };
- const svg = (el: Element) => el.querySelector("svg")!.innerHTML.replace(/hl-fd\d+/g, "hl-fd");
-
- /* the hosts run side by side on one clock, so the default and an explicit 0.5 must draw alike: that is the control */
- it.each(Object.keys(ALL) as Array<keyof typeof ALL>)("reaches %s's engine, at mount and through update", (id) => {
- const mount = ALL[id];
- const els = Array.from({ length: 6 }, host);
- const [base, half, none, full, text, reset] = els;
- mount(base);
- mount(half, { intensity: 0.5 });
- mount(none, { intensity: 0 });
- mount(full, { intensity: 1 });
- mount(text, { intensity: "1" as unknown as number });
- mount(reset, { intensity: 1 }).update({ intensity: undefined });
- for (const step of PLAY[id]) {
- if (typeof step === "number") frames(step);
- else for (const el of els) el.dispatchEvent(new MouseEvent("pointermove", { clientX: step[0], clientY: step[1], bubbles: true }));
- }
- expect(svg(half)).toBe(svg(base));
- expect(svg(reset)).toBe(svg(base));
- expect(svg(none)).not.toBe(svg(base));
- expect(svg(full)).not.toBe(svg(base));
- expect(svg(text)).toBe(svg(full));
- });
-
- it("keeps the intensity when update leaves it out", () => {
- const els = [host(), host()];
- terrain(els[0], { intensity: 1 }).update({ theme: "dark" });
- terrain(els[1], { intensity: 1 });
- for (const el of els) el.dispatchEvent(new MouseEvent("pointermove", { clientX: 200, clientY: 160, bubbles: true }));
- frames(20);
- expect(svg(els[0])).toBe(svg(els[1]));
- });
-});
-
-describe("the caption", () => {
- it("calls onRead once at mount with the rest caption", () => {
- for (const [id, rest] of [["riffle", "rest"], ["terrain", "rest"], ["slow", "rate 1.00×"]] as const) {
- const onRead = vi.fn();
- ALL[id](host(), { onRead });
- expect(onRead.mock.calls).toEqual([[rest]]);
- }
- });
-
- it("does not repeat a caption that has not changed", () => {
- const onRead = vi.fn();
- slow(host(), { onRead });
- frames(30);
- expect(onRead.mock.calls).toEqual([["rate 1.00×"]]);
- });
-
- it("reads a pulled card out by its number alone, in the caption and the live region", () => {
- const el = host(), onRead = vi.fn();
- /* the old option, from a caller without types: ignored */
- const f = riffle(el, { onRead, labels: ["Radial menu", "Drum"] } as never);
- key(el, "ArrowLeft");
- expect(onRead).toHaveBeenLastCalledWith("01");
- expect(el.querySelector("[data-hairline-live]")!.textContent).toBe("01");
- f.update({ labels: ["Radial menu"] } as never);
- key(el, "ArrowRight");
- expect(onRead).toHaveBeenLastCalledWith("02");
- for (let i = 0; i < 7; i++) key(el, "ArrowRight");
- expect(onRead).toHaveBeenLastCalledWith("08");
- expect(el.querySelector("[data-hairline-live]")!.textContent).toBe("08");
- key(el, "Escape");
- expect(onRead).toHaveBeenLastCalledWith("rest");
- });
-
- // Review Focus 2: every figure on the page shares one frame loop
- it("reports an onRead that throws and keeps every figure running", () => {
- const reported = vi.fn();
- vi.stubGlobal("reportError", reported);
- const boom = new Error("consumer bug");
- const other = vi.fn();
- const a = host(), b = host();
- expect(() => slow(a, { onRead: () => { throw boom; } })).not.toThrow();
- slow(b, { onRead: other });
- a.dispatchEvent(new MouseEvent("pointermove", { clientX: 200, clientY: 160 }));
- b.dispatchEvent(new MouseEvent("pointermove", { clientX: 200, clientY: 160 }));
- expect(() => frames(120)).not.toThrow();
- expect(reported.mock.calls.length).toBeGreaterThan(1);
- expect(reported).toHaveBeenCalledWith(boom);
- expect(other.mock.calls.length).toBeGreaterThan(1);
- expect(other.mock.calls[other.mock.calls.length - 1][0]).toMatch(/^rate 0\.20×/);
- });
-});
-
-describe("teardown", () => {
- it("destroys twice without complaint", () => {
- const f = riffle(host());
- f.destroy();
- expect(() => f.destroy()).not.toThrow();
- });
-
- // Review Focus 3: a handle kept after its figure is gone
- it("ignores update on a destroyed figure", () => {
- const el = host();
- const f = terrain(el);
- f.destroy();
- f.update({ theme: "dark", label: "late", intensity: 1 });
- expect(el.outerHTML).toBe("<div></div>");
- });
-
- it("ignores a stale handle once another figure has taken the element", () => {
- const el = host();
- const old = riffle(el);
- terrain(el);
- old.update({ theme: "dark", label: "late" });
- old.destroy();
- expect(el.getAttribute("data-hairline")).toBe("terrain");
- expect(el.hasAttribute("data-hairline-theme")).toBe(false);
- expect(el.getAttribute("aria-label")).not.toBe("late");
- expect(el.querySelectorAll(":scope > svg")).toHaveLength(1);
- expect(el.querySelector("svg")!.childElementCount).toBeGreaterThan(0);
- });
-
- it("leaves no frame and no observer behind the last figure", () => {
- const a = slow(host()), b = phosphor(host());
- frames(2);
- expect(pending()).toBe(1);
- expect(observers.size).toBe(1);
- a.destroy();
- frames(2);
- expect(pending()).toBe(1);
- b.destroy();
- expect(pending()).toBe(0);
- expect(observers.size).toBe(0);
- });
-
- it("stops listening to the element", () => {
- const el = host(), onRead = vi.fn();
- riffle(el, { onRead }).destroy();
- onRead.mockClear();
- key(el, "ArrowLeft");
- expect(onRead).not.toHaveBeenCalled();
- });
-});
-```
-
-Replace `packages/hairline/test/react.test.tsx`. "puts intensity back to 0.5 when the prop is removed" is Review Focus 2.
-
-`packages/hairline/test/react.test.tsx`
-```tsx
-// @vitest-environment jsdom
-import { StrictMode, createRef } from "react";
-import { cleanup, render } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { frames, observers, pending } from "./dom";
-import { Exploded, Phosphor, Riffle, Slow, Terrain, Turntable } from "../src/react";
-
-afterEach(cleanup);
-
-const key = (el: Element, k: string) => el.dispatchEvent(new KeyboardEvent("keydown", { key: k, bubbles: true, cancelable: true }));
-/** The rendered div, sized as dom.ts's host() is, so a client point is a viewBox point. */
-const sized = (el: Element) => {
- el.getBoundingClientRect = () => ({ left: 0, top: 0, width: 400, height: 320, right: 400, bottom: 320, x: 0, y: 0, toJSON() {} });
- return el;
-};
-const svg = (el: Element) => el.querySelector("svg")!.innerHTML.replace(/hl-fd\d+/g, "hl-fd");
-
-describe("components", () => {
- it("renders each figure into one div", () => {
- const { container } = render(<><Riffle /><Terrain /><Exploded /><Phosphor /><Slow /><Turntable /></>);
- const ids = [...container.children].map((el) => el.getAttribute("data-hairline"));
- expect(ids).toEqual(["riffle", "terrain", "exploded", "phosphor", "slow", "turntable"]);
- for (const el of container.children) expect(el.querySelectorAll(":scope > svg")).toHaveLength(1);
- });
-
- it("passes div attributes through, forwards the ref, and keeps the options off the DOM", () => {
- const ref = createRef<HTMLDivElement>();
- const { container } = render(<Riffle ref={ref} id="cards" className="w-80" data-x="1" style={{ width: 320 }} intensity={0.8} theme="dark" label="Cards" onRead={() => {}} />);
- const el = container.firstElementChild as HTMLDivElement;
- expect(ref.current).toBe(el);
- expect(el.id).toBe("cards");
- expect(el.className).toBe("w-80");
- expect(el.getAttribute("data-x")).toBe("1");
- expect(el.style.width).toBe("320px");
- expect(el.style.aspectRatio).toBe("5 / 4");
- for (const name of ["intensity", "theme", "label", "onread"]) expect(el.hasAttribute(name)).toBe(false);
- expect(el.getAttribute("data-hairline-theme")).toBe("dark");
- expect(el.getAttribute("aria-label")).toBe("Cards");
- });
-
- it("lets the style prop override the aspect ratio", () => {
- const { container } = render(<Terrain style={{ aspectRatio: "1 / 1" }} />);
- expect((container.firstElementChild as HTMLElement).style.aspectRatio).toBe("1 / 1");
- });
-
- it("uses the label prop, and aria-label when the caller sets that instead", () => {
- const { container, rerender } = render(<Terrain label="Dunes" />);
- const el = container.firstElementChild!;
- expect(el.getAttribute("aria-label")).toBe("Dunes");
- rerender(<Terrain aria-label="Hills" />);
- expect(el.getAttribute("aria-label")).toBe("Hills");
- });
-
- it("updates the running figure when a prop changes, without remounting", () => {
- const { container, rerender } = render(<Riffle theme="dark" />);
- const el = container.firstElementChild!, drawing = el.querySelector("svg");
- rerender(<Riffle theme="light" />);
- expect(el.getAttribute("data-hairline-theme")).toBe("light");
- rerender(<Riffle />);
- expect(el.hasAttribute("data-hairline-theme")).toBe(false);
- expect(el.querySelector("svg")).toBe(drawing);
- });
-
- // Review Focus 2: a prop that is removed goes back to its default
- it("puts intensity back to 0.5 when the prop is removed", () => {
- const { container, rerender } = render(<><Terrain intensity={1} /><Terrain /><Terrain intensity={1} /></>);
- const [gone, standard, strong] = [...container.children].map(sized);
- rerender(<><Terrain /><Terrain /><Terrain intensity={1} /></>);
- for (const el of [gone, standard, strong]) el.dispatchEvent(new MouseEvent("pointermove", { clientX: 200, clientY: 160, bubbles: true }));
- frames(20);
- expect(svg(gone)).toBe(svg(standard));
- expect(svg(gone)).not.toBe(svg(strong));
- });
-
- // Review Focus 4: a function written inline is new on every render
- it("does not remount, and does not loop, on an inline onRead", () => {
- const seen: string[] = [];
- let renders = 0;
- function App({ n }: { n: number }) {
- renders++;
- return <Riffle data-n={n} onRead={(t) => seen.push(`${n}:${t}`)} />;
- }
- const { container, rerender } = render(<App n={1} />);
- const el = container.firstElementChild!, drawing = el.querySelector("svg");
- rerender(<App n={2} />);
- rerender(<App n={3} />);
- expect(renders).toBe(3);
- expect(el.querySelector("svg")).toBe(drawing);
- key(el, "ArrowLeft");
- // one call at mount, and the latest function is the one called afterwards
- expect(seen).toEqual(["1:rest", "3:01"]);
- });
-
- it("calls a state setter from onRead without looping", () => {
- const onRead = vi.fn();
- const { container } = render(<Slow onRead={onRead} />);
- expect(onRead.mock.calls).toEqual([["rate 1.00×"]]);
- expect(container.firstElementChild!.querySelectorAll("svg")).toHaveLength(1);
- });
-
- it("survives StrictMode's double mount with one drawing", () => {
- const onRead = vi.fn();
- const { container } = render(<StrictMode><Riffle onRead={onRead} /></StrictMode>);
- const el = container.firstElementChild!;
- expect(el.querySelectorAll(":scope > svg")).toHaveLength(1);
- expect(el.querySelectorAll("[data-hairline-live]")).toHaveLength(1);
- expect(observers.size).toBe(1);
- key(el, "ArrowLeft");
- expect(onRead).toHaveBeenLastCalledWith("01");
- });
-
- it("cleans up on unmount", () => {
- const { container, unmount } = render(<><Slow /><Phosphor /></>);
- expect(container.querySelectorAll("svg")).toHaveLength(2);
- unmount();
- expect(pending()).toBe(0);
- expect(observers.size).toBe(0);
- });
-
- it("names the components for the dev tools", () => {
- expect([Riffle, Terrain, Exploded, Phosphor, Slow, Turntable].map((c) => c.displayName))
- .toEqual(["Riffle", "Terrain", "Exploded", "Phosphor", "Slow", "Turntable"]);
- });
-});
-```
-
-Change the one server-rendering case in `packages/hairline/test/ssr.test.tsx` so it passes the new options, which must stay off the DOM:
-
-`packages/hairline/test/ssr.test.tsx (diff)`
-```diff
---- a/packages/hairline/test/ssr.test.tsx
-+++ b/packages/hairline/test/ssr.test.tsx
-@@ -13,7 +13,7 @@ describe("on the server", () => {
-
- it("renders a component as an empty box of the right shape", async () => {
- const { Riffle } = await import("../src/react");
-- const html = renderToString(createElement(Riffle, { className: "w-80", stagger: 60, labels: ["a"], onRead() {} }));
-+ const html = renderToString(createElement(Riffle, { className: "w-80", intensity: 0.8, theme: "dark", label: "Cards", onRead() {} }));
- expect(html).toBe('<div class="w-80" style="aspect-ratio:5 / 4"></div>');
- });
-
-```
-
-Replace `packages/hairline/test/types.test-d.tsx`. It checks that the new options compile on every function and component, that every dropped option is a compile error on every one of them, and what each entry exports:
-
-`packages/hairline/test/types.test-d.tsx`
-```tsx
-/**
- * Type tests. Nothing here runs: `pnpm typecheck` compiles this file, and an
- * `@ts-expect-error` line fails the build if the line below it stops being
- * an error. Vitest does not pick it up (it is not a `.test.` file).
- */
-import { createRef } from "react";
-import { exploded, phosphor, riffle, slow, terrain, turntable, type Figure, type HairlineOptions } from "../src/index";
-import * as vanilla from "../src/index";
-import * as components from "../src/react";
-import { Exploded, Phosphor, Riffle, Slow, Terrain, Turntable, type HairlineProps } from "../src/react";
-
-declare const el: HTMLElement;
-type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;
-const yes = <T extends true>() => {};
-
-/* every figure takes the same options */
-riffle(el, { intensity: 0.8, theme: "dark", label: "Cards", onRead: (t: string) => t });
-riffle(el);
-for (const mount of [riffle, terrain, exploded, phosphor, slow, turntable]) {
- yes<Equal<typeof mount, (el: HTMLElement, options?: HairlineOptions) => Figure>>();
- // @ts-expect-error the old per-figure options are gone
- mount(el, { stagger: 60 });
- // @ts-expect-error the old per-figure options are gone
- mount(el, { radius: 3 });
- // @ts-expect-error Riffle's bands are gone
- mount(el, { bands: true });
- // @ts-expect-error Riffle's names are gone
- mount(el, { labels: [] });
-}
-// @ts-expect-error a number, not a string
-slow(el, { intensity: "0.8" });
-// @ts-expect-error not a theme
-exploded(el, { theme: "sepia" });
-// @ts-expect-error the element is required
-riffle();
-yes<Equal<keyof HairlineOptions, "intensity" | "theme" | "label" | "onRead">>();
-
-/* the handle */
-const f = riffle(el);
-yes<Equal<typeof f, Figure>>();
-f.update({ intensity: undefined, theme: "light" });
-f.destroy();
-// @ts-expect-error update takes the same options
-f.update({ stagger: 60 });
-// @ts-expect-error update takes the same options
-f.update({ bands: true });
-
-/* the entries export the functions, the components and three types, and nothing of the old API */
-yes<Equal<keyof typeof vanilla, "riffle" | "terrain" | "exploded" | "phosphor" | "slow" | "turntable">>();
-yes<Equal<keyof typeof components, "Riffle" | "Terrain" | "Exploded" | "Phosphor" | "Slow" | "Turntable">>();
-// @ts-expect-error ranges is gone
-void vanilla.ranges;
-// @ts-expect-error the per-figure option types are gone
-type Old = import("../src/index").RiffleOptions;
-// @ts-expect-error the per-figure props types are gone
-type OldProps = import("../src/react").RiffleProps;
-
-/* components: the options, plus what a div takes */
-const ref = createRef<HTMLDivElement>();
-<Riffle ref={ref} intensity={0.8} theme="dark" className="w-80" id="cards" onClick={() => {}} onRead={(text) => text.length} />;
-<Terrain style={{ width: 320 }} aria-label="Dunes" data-x="1" />;
-<Riffle />;
-for (const C of [Riffle, Terrain, Exploded, Phosphor, Slow, Turntable]) {
- // @ts-expect-error the old per-figure options are gone
- <C stagger={60} />;
- // @ts-expect-error the old per-figure options are gone
- <C radius={3} />;
- // @ts-expect-error Riffle's bands are gone
- <C bands />;
- // @ts-expect-error Riffle's names are gone
- <C labels={[]} />;
-}
-// @ts-expect-error a number, not a string
-<Terrain intensity="0.8" />;
-// @ts-expect-error a figure has no children
-<Riffle>text</Riffle>;
-// @ts-expect-error the ref is to a div
-<Riffle ref={createRef<HTMLSpanElement>()} />;
-const props: HairlineProps = { intensity: 0.8, className: "w-80" };
-void props;
-```
-
-Delete the test of the module that goes away:
-
-```bash
-git rm packages/hairline/test/ranges.test.ts
-```
-
-- [ ] **Step 2: Run the tests to see them fail**
-
-Run: `pnpm --filter @lucasmarkes/hairline test`
-Expected: FAIL, `Tests 10 failed | 82 passed (92)`:
-- `mount.test.ts`: the six "reaches %s's engine, at mount and through update" (`expected '<g>…' not to be '<g>…'`: the old figures ignore `intensity`), and "reads a pulled card out by its number alone…" (`expected last "vi.fn()" call to have been called with [ '01' ]`).
-- `react.test.tsx`: "passes div attributes through, forwards the ref, and keeps the options off the DOM" and "puts intensity back to 0.5 when the prop is removed".
-- `ssr.test.tsx`: "renders a component as an empty box of the right shape" (`intensity` reaches the DOM as an attribute).
-
-Run: `pnpm --filter @lucasmarkes/hairline typecheck`
-Expected: FAIL, with `error TS2353: Object literal may only specify known properties, and 'intensity' does not exist in type …` in `mount.test.ts`, `error TS2322` for `intensity` on the components in `react.test.tsx`, and errors in `ssr.test.tsx` and `types.test-d.tsx`.
-
-- [ ] **Step 3: Write the options type and the merge**
-
-Replace `packages/hairline/src/mount.ts`:
-
-`packages/hairline/src/mount.ts`
-```ts
-import { inject } from "./core/styles";
-import type { FigureMount, Readout } from "./core/stage";
-import { parameter, type FigureId } from "./intensity";
-
-/**
- * Hairline — the public wrapper around an engine. An engine draws into an svg
- * it is handed and writes its caption to a read-out; this file makes both,
- * dresses the host element, and gives back the two calls a consumer needs.
- *
- * It only ever removes what it added: the svg, the live region, and the
- * attributes the host did not already have.
- */
-
-/** What every figure takes. */
-export type HairlineOptions = {
- /** How strongly the figure answers the pointer, from 0 (subtle) to 1 (strong). Default 0.5. */
- intensity?: number;
- /** `"auto"` follows the page: an ancestor with class `dark` or `data-theme="dark"`, then the page's `color-scheme`. Default `"auto"`. */
- theme?: "auto" | "light" | "dark";
- /** The accessible name. Each figure has a default description in English. */
- label?: string;
- /** The figure's caption, each time it changes. Called once at mount with the rest caption. */
- onRead?: (text: string) => void;
-};
-
-export type Figure = {
- /** Changes options on the running figure. A key set to `undefined` goes back to its default; a key left out stays as it was. */
- update(options: HairlineOptions): void;
- /** Stops the figure and removes what it added to the element. Safe to call twice. */
- destroy(): void;
-};
-
-/** What a figure is: its engine, and what it says about itself. */
-export type Spec = {
- id: FigureId;
- /** The default accessible name. */
- label: string;
- /** The caption at rest, for an engine that writes none until it is touched. */
- rest: string;
- engine: FigureMount;
- /** Operable from the keyboard: a focusable group with a live region, not an image. */
- focusable?: boolean;
-};
-
-const NS = "http://www.w3.org/2000/svg";
-const mounted = new WeakMap<Element, () => void>();
-
-/** An error from a consumer's callback, reported as uncaught without unwinding the frame loop every figure shares. */
-const report = (err: unknown) => {
- if (typeof reportError === "function") reportError(err);
- else setTimeout(() => { throw err; });
-};
-
-export function create(spec: Spec, el: HTMLElement, options?: HairlineOptions): Figure {
- if (typeof document === "undefined") {
- throw new Error(`hairline: ${spec.id}() needs a DOM. Call it in the browser, once the element exists: in an effect, in onMount, or in a script after the element.`);
- }
- if (!el || el.nodeType !== 1) {
- throw new TypeError(`hairline: ${spec.id}() takes an element as its first argument, and got ${el === null ? "null" : typeof el}.`);
- }
- mounted.get(el)?.();
-
- const opts: HairlineOptions = { ...options };
- const doc = el.ownerDocument;
- const root = el.getRootNode();
- inject(root.nodeType === 9 || "host" in root ? (root as Document | ShadowRoot) : doc);
-
- /* attributes: the host's own are left alone, ours are remembered */
- const owned = new Set<string>();
- const attr = (name: string, value: string | null) => {
- if (!owned.has(name) && el.hasAttribute(name)) return;
- if (value === null) { el.removeAttribute(name); owned.delete(name); }
- else { el.setAttribute(name, value); owned.add(name); }
- };
- const dress = () => {
- attr("data-hairline-theme", opts.theme === "light" || opts.theme === "dark" ? opts.theme : null);
- attr("aria-label", el.hasAttribute("aria-labelledby") ? null : typeof opts.label === "string" ? opts.label : spec.label);
- };
- attr("data-hairline", spec.id);
- attr("role", spec.focusable ? "group" : "img");
- if (spec.focusable) attr("tabindex", "0");
- dress();
-
- const svg = doc.createElementNS(NS, "svg");
- svg.setAttribute("viewBox", "0 0 400 320");
- svg.setAttribute("aria-hidden", "true");
- el.appendChild(svg);
- let live: HTMLElement | null = null;
- if (spec.focusable) {
- live = doc.createElement("span");
- live.setAttribute("data-hairline-live", "");
- live.setAttribute("aria-live", "polite");
- el.appendChild(live);
- }
-
- /* the read-out: engines write it every frame, so only a change goes any further */
- let text: string | null = null;
- const read: Readout = {
- get textContent() { return text; },
- set textContent(value) {
- const next = value ?? "";
- if (next === text) return;
- text = next;
- if (live) live.textContent = next;
- const fn = opts.onRead;
- if (typeof fn === "function") try { fn(next); } catch (err) { report(err); }
- },
- };
-
- let value = parameter(spec.id, opts.intensity);
- const engine = spec.engine({ stage: el, svg, read }, value);
- if (text === null) read.textContent = spec.rest;
-
- let dead = false;
- const destroy = () => {
- if (dead) return;
- dead = true;
- if (mounted.get(el) === destroy) mounted.delete(el);
- engine.destroy();
- svg.remove();
- live?.remove();
- for (const name of owned) el.removeAttribute(name);
- owned.clear();
- };
- mounted.set(el, destroy);
-
- return {
- update(next) {
- if (dead || !next) return;
- /* a caller without types may send keys that are not options; they are kept and never read */
- const own = opts as Record<string, unknown>, given = next as Record<string, unknown>;
- for (const k in given) {
- if (given[k] === undefined) delete own[k];
- else own[k] = given[k];
- }
- const v = parameter(spec.id, opts.intensity);
- if (v !== value) { value = v; engine.set(v); }
- dress();
- },
- destroy,
- };
-}
-```
-
-- [ ] **Step 4: Write the six functions**
-
-Replace `packages/hairline/src/index.ts`. Each function maps `intensity` through `parameter` into the one number its engine takes, and mounts Riffle with no names:
-
-`packages/hairline/src/index.ts`
-```ts
-import { create, type Figure, type HairlineOptions } from "./mount";
-import { mount as explodedEngine } from "./figures/exploded";
-import { mount as phosphorEngine } from "./figures/phosphor";
-import { mount as riffleEngine } from "./figures/riffle";
-import { mount as slowEngine } from "./figures/slow";
-import { mount as terrainEngine } from "./figures/terrain";
-import { mount as turntableEngine } from "./figures/turntable";
-
-/**
- * @lucasmarkes/hairline — six isometric line figures that answer the pointer.
- *
- * One function per figure. Each takes an element and the same options, draws
- * into the element, and returns `{ update, destroy }`. Each function names
- * its engine itself, so a bundle that imports one figure carries one.
- */
-
-export type { Figure, HairlineOptions } from "./mount";
-
-/** A tray of eight cards. The card under the pointer stands up; the arrow keys walk the cards. `intensity` spreads the ripple further from the pulled card. */
-export function riffle(el: HTMLElement, options?: HairlineOptions): Figure {
- return create({
- id: "riffle",
- label: "A tray of eight cards. Hover or use the arrow keys to pull a card.",
- rest: "rest",
- engine: riffleEngine,
- focusable: true,
- }, el, options);
-}
-
-/** Eighty-one pillars on a plinth that rise around the pointer. `intensity` widens the area that rises. */
-export function terrain(el: HTMLElement, options?: HairlineOptions): Figure {
- return create({
- id: "terrain",
- label: "Eighty-one pillars on a plinth that rise around the pointer and rest as a dune with two rises.",
- rest: "rest",
- engine: terrainEngine,
- }, el, options);
-}
-
-/** An app window in four layers. Moving across opens the gap; moving down picks a layer. `intensity` opens the layers further. */
-export function exploded(el: HTMLElement, options?: HairlineOptions): Figure {
- return create({
- id: "exploded",
- label: "An app window taken apart into four layers. Moving across opens the gap; moving down picks a layer.",
- rest: "",
- engine: explodedEngine,
- }, el, options);
-}
-
-/** A seven by seven dot matrix that plays a loop, and fades like phosphor where the pointer paints it. `intensity` makes the trail linger longer. */
-export function phosphor(el: HTMLElement, options?: HairlineOptions): Figure {
- return create({
- id: "phosphor",
- label: "A seven by seven dot matrix on a floating tile that plays a loop, and fades like phosphor where you paint it.",
- rest: "loop",
- engine: phosphorEngine,
- }, el, options);
-}
-
-/** Crates riding a belt through a gate. Hovering slows the clock without stopping it. `intensity` slows it more. */
-export function slow(el: HTMLElement, options?: HairlineOptions): Figure {
- return create({
- id: "slow",
- label: "Crates riding a belt through a gate. Hovering slows the clock without stopping it.",
- rest: "rate 1.00×",
- engine: slowEngine,
- }, el, options);
-}
-
-/** Blocks on a turntable. A flick across it spins it; it settles on the nearest quarter turn. `intensity` makes the spin coast longer. */
-export function turntable(el: HTMLElement, options?: HairlineOptions): Figure {
- return create({
- id: "turntable",
- label: "Blocks on a turntable. Flick across it to spin it; it settles on the nearest quarter turn.",
- rest: "az 045° · el 30°",
- engine: turntableEngine,
- }, el, options);
-}
-```
-
-Delete the ranges module, which nothing imports now:
-
-```bash
-git rm packages/hairline/src/ranges.ts
-```
-
-- [ ] **Step 5: Write the React entry**
-
-Replace `packages/hairline/src/react.tsx`:
-
-`packages/hairline/src/react.tsx`
-```tsx
-import {
- forwardRef, useCallback, useEffect, useLayoutEffect, useRef,
- type ComponentPropsWithoutRef, type ForwardRefExoticComponent, type RefAttributes,
-} from "react";
-import { exploded, phosphor, riffle, slow, terrain, turntable, type Figure, type HairlineOptions } from "./index";
-
-/**
- * @lucasmarkes/hairline/react — the six figures as components.
- *
- * A component renders one empty `<div>` and mounts the figure on it in a
- * layout effect, so on the server the box is there and the drawing is not.
- * It mounts once: a changed option reaches the running figure as `update`,
- * and `onRead` is called through a ref, so an inline function never remounts.
- */
-
-/** The figure's options, plus every `<div>` attribute except `children`. */
-export type HairlineProps = HairlineOptions & Omit<ComponentPropsWithoutRef<"div">, "children" | keyof HairlineOptions>;
-type HairlineComponent = ForwardRefExoticComponent<HairlineProps & RefAttributes<HTMLDivElement>>;
-
-const useIsoLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
-
-function make(name: string, mount: (el: HTMLElement, options?: HairlineOptions) => Figure): HairlineComponent {
- const Component = forwardRef<HTMLDivElement, HairlineProps>(function Hairline(props, ref) {
- const { intensity, theme, label, onRead, style, ...attrs } = props;
- /* aria-label stays on the div and is the figure's label too, so the two never disagree about the name */
- const named = label ?? props["aria-label"];
-
- const el = useRef<HTMLDivElement | null>(null);
- const figure = useRef<Figure | null>(null);
- const read = useRef(onRead);
- const set = useCallback((node: HTMLDivElement | null) => {
- el.current = node;
- if (typeof ref === "function") ref(node);
- else if (ref) ref.current = node;
- }, [ref]);
-
- useIsoLayoutEffect(() => { read.current = onRead; });
-
- useIsoLayoutEffect(() => {
- const f = mount(el.current!, { intensity, theme, label: named, onRead: (text) => read.current?.(text) });
- figure.current = f;
- return () => { f.destroy(); figure.current = null; };
- // mounts once; options reach the figure through the effect below
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- /* every key is sent, so a prop that was removed goes back to its default */
- useIsoLayoutEffect(() => { figure.current?.update({ intensity, theme, label: named }); }, [intensity, theme, named]);
-
- return <div {...attrs} ref={set} style={{ aspectRatio: "5 / 4", ...style }} />;
- });
- Component.displayName = name;
- return Component;
-}
-
-/** A tray of eight cards. The card under the pointer stands up; the arrow keys walk the cards. `intensity` spreads the ripple further from the pulled card. */
-export const Riffle = make("Riffle", riffle);
-/** Eighty-one pillars on a plinth that rise around the pointer. `intensity` widens the area that rises. */
-export const Terrain = make("Terrain", terrain);
-/** An app window in four layers. Moving across opens the gap; moving down picks a layer. `intensity` opens the layers further. */
-export const Exploded = make("Exploded", exploded);
-/** A seven by seven dot matrix that plays a loop, and fades like phosphor where the pointer paints it. `intensity` makes the trail linger longer. */
-export const Phosphor = make("Phosphor", phosphor);
-/** Crates riding a belt through a gate. Hovering slows the clock without stopping it. `intensity` slows it more. */
-export const Slow = make("Slow", slow);
-/** Blocks on a turntable. A flick across it spins it; it settles on the nearest quarter turn. `intensity` makes the spin coast longer. */
-export const Turntable = make("Turntable", turntable);
-```
-
-- [ ] **Step 6: Run the tests to see them pass**
-
-Run: `pnpm --filter @lucasmarkes/hairline test && pnpm --filter @lucasmarkes/hairline typecheck`
-Expected: PASS, `Tests 92 passed (92)`, and `tsc --noEmit` prints nothing.
-
-- [ ] **Step 7: Bring the browser tests to the new API**
-
-Replace `packages/hairline/test/browser/parity.spec.ts`. It strips Riffle's `<g class="bands">` group and the card names from both sides, and sets `INTENSITY[id]` at `set`:
-
-`packages/hairline/test/browser/parity.spec.ts`
-```ts
-import { expect, test } from "@playwright/test";
-import { readFileSync } from "node:fs";
-import { play } from "../parity/driver.mjs";
-import { FIGURES, INTENSITY, SCRIPTS } from "../parity/scripts.mjs";
-
-/**
- * The package draws what the site draws. Each golden is the site's svg at
- * every checkpoint of a pointer script (test/parity/capture.mjs); the same
- * script is played here against the package, on the same virtual clock.
- */
-const file = (p: string) => readFileSync(new URL(p, import.meta.url), "utf8");
-const clock = file("../parity/clock.js") + "\nwindow.__freeze(1000);";
-
-/*
- * The goldens hold two things the package no longer draws or says: Riffle's
- * hidden hit bands, and the names the site gives its cards. Both come out of
- * both sides before the comparison, the way ids would; everything else must
- * match character for character.
- */
-const strip = (svg: string) => svg.replace(/<g class="bands">.*?<\/g>/, "");
-const unname = (id: string, read: string) => (id === "riffle" ? read.replace(/ · .*$/, "") : read);
-
-type Checkpoint = { at: string; read: string; svg: string };
-
-for (const id of FIGURES as string[]) {
- test(`${id} draws what the site draws`, async ({ context, page }) => {
- const golden = JSON.parse(file(`../parity/golden/${id}.json`)) as { checkpoints: Checkpoint[] };
- const intensity = (INTENSITY as Record<string, number>)[id];
- await context.addInitScript(clock);
- await page.goto("/");
- await page.evaluate((id) => { window.__hl.mount(id as "riffle"); }, id);
- const stage = page.locator("#host");
- await stage.locator("svg > *").first().waitFor();
- /* a figure sleeps until its IntersectionObserver reports it on screen, and that report comes on the browser's own time */
- await page.evaluate(() => new Promise((done) => window.__realTimeout(done, 500)));
-
- const got: Checkpoint[] = await play(page, {
- stage,
- snap: () => page.evaluate(() => ({ svg: document.querySelector("#host > svg")!.innerHTML, read: window.__hl.read() })),
- set: () => page.evaluate((intensity) => window.__hl.figure!.update({ intensity }), intensity),
- }, (SCRIPTS as Record<string, object[]>)[id]);
-
- expect(got.map((c) => c.at)).toEqual(golden.checkpoints.map((c) => c.at));
- for (const [i, want] of golden.checkpoints.entries()) {
- expect(got[i].read, `caption at "${want.at}"`).toBe(unname(id, want.read));
- expect(strip(got[i].svg), `drawing at "${want.at}"`).toBe(strip(want.svg));
- }
- });
-}
-```
-
-In `packages/hairline/test/browser/figures.spec.ts`, Riffle's keyboard test mounts with no names and reads numbers only:
-
-`packages/hairline/test/browser/figures.spec.ts (diff)`
-```diff
---- a/packages/hairline/test/browser/figures.spec.ts
-+++ b/packages/hairline/test/browser/figures.spec.ts
-@@ -41,14 +41,14 @@ test("every figure mounts, answers the pointer and leaves, with nothing on the c
- });
-
- test("Riffle walks its cards from the keyboard and says each one in the live region", async ({ page }) => {
-- await mount(page, "riffle", { labels: ["Radial menu", "Drum"] });
-+ await mount(page, "riffle");
- const host = page.locator("#host"), live = host.locator("[data-hairline-live]");
- await page.keyboard.press("Tab");
- await expect(host).toBeFocused();
- await page.keyboard.press("ArrowLeft");
-- await expect(live).toHaveText("01 · Radial menu");
-+ await expect(live).toHaveText("01");
- await page.keyboard.press("ArrowRight");
-- await expect(live).toHaveText("02 · Drum");
-+ await expect(live).toHaveText("02");
- await page.keyboard.press("ArrowRight");
- await expect(live).toHaveText("03");
- await page.keyboard.press("Escape");
-```
-
-Run: `pnpm --filter @lucasmarkes/hairline build && pnpm --filter @lucasmarkes/hairline test:browser`
-Expected: PASS, `19 passed`. All six parity tests pass against the untouched goldens: at the default and at each `INTENSITY`, the package draws what the site drew.
-
-If a parity test fails on a drawing, do not capture the goldens again. The map in Task 1 or the wiring in Step 4 is wrong: the default must draw exactly what it drew before.
-
-- [ ] **Step 8: Commit**
-
-```bash
-git add packages/hairline/src packages/hairline/test
-git commit -m "API: every figure takes HairlineOptions, with one intensity in place of six options
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-### Task 3: Riffle without names or drawn bands
-
-**Files:**
-- Modify: `packages/hairline/src/figures/riffle.ts` (drop `RiffleHandle`, the names and the band paths)
-- Modify: `packages/hairline/src/core/styles.ts` (drop the `.bands` rules)
-- Test: `packages/hairline/test/mount.test.ts` (one new test in the `mount` block)
-
-**Interfaces:**
-- Consumes from Task 2: `index.ts` mounts Riffle through `create` with no names, and nothing calls `bands()` or `labels()` any more.
-- Produces: Riffle's engine `mount(els, value): FigureHandle`, the same handle type as the other five. The band geometry that decides which card is pulled (`hit`) is unchanged; only its drawing goes.
-
-- [ ] **Step 1: Write the failing test**
-
-Add this test to the `mount` block of `packages/hairline/test/mount.test.ts`, after "replaces a figure already on the element":
-
-`packages/hairline/test/mount.test.ts (diff)`
-```diff
---- a/packages/hairline/test/mount.test.ts
-+++ b/packages/hairline/test/mount.test.ts
-@@ -2,6 +2,7 @@
- import { describe, expect, it, vi } from "vitest";
- import { frames, host, observers, pending } from "./dom";
- import { exploded, phosphor, riffle, slow, terrain, turntable } from "../src/index";
-+import { css } from "../src/core/styles";
-
- const ALL = { riffle, terrain, exploded, phosphor, slow, turntable };
- const key = (el: Element, k: string) => el.dispatchEvent(new KeyboardEvent("keydown", { key: k, bubbles: true, cancelable: true }));
-@@ -79,6 +80,13 @@ describe("mount", () => {
- expect(el.querySelector("[data-hairline-live]")).toBeNull();
- });
-
-+ it("draws no hit bands on Riffle, and the stylesheet has no rules for them", () => {
-+ const el = host();
-+ riffle(el);
-+ expect(el.querySelector(".bands")).toBeNull();
-+ expect(css(true) + css(false)).not.toMatch(/bands/);
-+ });
-+
- it("puts the stylesheet in the document once, however many figures mount", () => {
- riffle(host()); terrain(host()); slow(host());
- const sheets = document.adoptedStyleSheets?.length ?? 0;
-```
-
-- [ ] **Step 2: Run it to see it fail**
-
-Run: `pnpm --filter @lucasmarkes/hairline exec vitest run test/mount.test.ts -t "draws no hit bands"`
-Expected: FAIL, `AssertionError: expected SVGGElement{ …(1) } to be null`.
-
-- [ ] **Step 3: Take the names and the bands out of the engine**
-
-In `packages/hairline/src/figures/riffle.ts`:
-
-`packages/hairline/src/figures/riffle.ts (diff)`
-```diff
---- a/packages/hairline/src/figures/riffle.ts
-+++ b/packages/hairline/src/figures/riffle.ts
-@@ -1,4 +1,4 @@
--import { clamp, poly, rad, type Vec2 } from "../core/iso";
-+import { clamp, rad, type Vec2 } from "../core/iso";
- import { tdone, tset, tval, tween, type Tween } from "../core/motion";
- import { BACK, FWD, G, H, LIFT, N, REST, W, card, pose, scene, tray } from "./riffle-geometry";
- import { disposer, mk, place, pointer, reflect, register, type FigureEls, type FigureHandle } from "../core/stage";
-@@ -10,21 +10,14 @@ import { disposer, mk, place, pointer, reflect, register, type FigureEls, type F
- *
- * Selection never reads the posed cards: it comes from static oblique bands
- * along the resting top edges, so a card moving out from under the pointer
-- * can't flip the choice back and forth. `bands(true)` shows them. The stage
-- * is a focusable group; the arrow keys walk the cards and the read-out names
-- * the one pulled: its number, and its name when `labels` gave it one.
-+ * can't flip the choice back and forth. The bands are geometry only; nothing
-+ * draws them. The stage is a focusable group; the arrow keys walk the cards
-+ * and the read-out names the one pulled by its number.
- *
- * The drawing itself — camera, tray, a card in any pose — is pure and lives in
- * riffle-geometry.ts; this file is the DOM, the tweens and the input.
- */
-
--export type RiffleHandle = FigureHandle & {
-- /** Shows or hides the hit bands. */
-- bands(on: boolean): void;
-- /** Names for the cards, card 01 first. A card without a name is read out by its number alone. */
-- labels(list: readonly string[]): void;
--};
--
- type Card = {
- n: number; t0: number; shape: Vec2[];
- back: SVGPathElement; face: SVGPathElement; head: SVGPathElement; rules: SVGPathElement;
-@@ -33,10 +26,9 @@ type Card = {
- a: Tween; z: Tween;
- };
-
--export const mount = ({ stage, svg, read }: FigureEls, value: number): RiffleHandle => {
-+export const mount = ({ stage, svg, read }: FigureEls, value: number): FigureHandle => {
- const bag = disposer();
- let stag = value;
-- let names: readonly string[] = [];
-
- const { P, front, outer, inner } = scene();
- const paths = tray(P, front, outer, inner);
-@@ -64,9 +56,6 @@ export const mount = ({ stage, svg, read }: FigureEls, value: number): RiffleHan
- const c0 = top(0), c1 = top(1), d = [c1[0] - c0[0], c1[1] - c0[1]];
- const px0 = P(0, 0, 0), px1 = P(1, 0, 0), ex = [px1[0] - px0[0], px1[1] - px0[1]];
- const HALF = W / 2 + 6, det = d[0] * ex[1] - d[1] * ex[0];
-- const bandG = mk("g", { class: "bands" }, g), bands: SVGPathElement[] = [];
-- const at = (s: number, r: number): Vec2 => [c0[0] + s * d[0] + r * ex[0], c0[1] + s * d[1] + r * ex[1]];
-- for (let i = 0; i < N; i++) bands.push(mk("path", { d: poly([at(i - 0.5, -HALF), at(i - 0.5, HALF), at(i + 0.5, HALF), at(i + 0.5, -HALF)]) }, bandG));
-
- /** The card whose band holds the point, in the band's own (s, r) coordinates; -1 outside. */
- function hit([x, y]: Vec2) {
-@@ -93,11 +82,7 @@ export const mount = ({ stage, svg, read }: FigureEls, value: number): RiffleHan
- bag.add(B.unregister);
-
- let act = -1;
-- const caption = (a: number) => {
-- if (a < 0) return "rest";
-- const n = N - a, name = names[n - 1];
-- return String(n).padStart(2, "0") + (name ? ` · ${name}` : "");
-- };
-+ const caption = (a: number) => (a < 0 ? "rest" : String(N - a).padStart(2, "0"));
- /** Pulls card a (-1 puts them all back). The stagger spreads out from the card pulled, or the one let go. */
- function setActive(a: number) {
- if (a === act) return;
-@@ -109,7 +94,6 @@ export const mount = ({ stage, svg, read }: FigureEls, value: number): RiffleHan
- tset(cd.a, th, now, delay); tset(cd.z, a === i ? LIFT : 0, now, delay);
- cd.face.classList.toggle("hi", i === a); cd.head.classList.toggle("hi", i === a); cd.punch[cd.n - 1].classList.toggle("m", i !== a);
- });
-- bands.forEach((b, i) => b.classList.toggle("on", i === a));
- read.textContent = caption(a);
- B.wake();
- }
-@@ -126,8 +110,6 @@ export const mount = ({ stage, svg, read }: FigureEls, value: number): RiffleHan
-
- return {
- set: (v) => { stag = v; },
-- bands: (on) => { bandG.classList.toggle("show", on); },
-- labels: (list) => { names = list; if (act >= 0) read.textContent = caption(act); },
- destroy: bag.dispose,
- };
- };
-```
-
-In `packages/hairline/src/core/styles.ts`, remove the two rules for the bands:
-
-`packages/hairline/src/core/styles.ts (diff)`
-```diff
---- a/packages/hairline/src/core/styles.ts
-+++ b/packages/hairline/src/core/styles.ts
-@@ -47,10 +47,6 @@ export function css(lightDark: boolean): string {
- `${SVG} :where(.dot.m){fill:var(--hl-edge)}`,
- `${SVG} :where(.dot.off){fill:var(--hl-lo)}`,
- `${SVG} :where(.ghost path){fill:none;stroke:var(--hl-mid)}`,
-- `${SVG} :where(.bands){opacity:0;transition:opacity 240ms ${EASE};pointer-events:none}`,
-- `${SVG} :where(.bands.show){opacity:1}`,
-- `${SVG} :where(.bands path){fill:none;stroke:var(--hl-mid);stroke-dasharray:2 3}`,
-- `${SVG} :where(.bands path.on){stroke:var(--hl-hi);stroke-dasharray:none}`,
- ].join("");
- }
-
-```
-
-- [ ] **Step 4: Run the tests and the package's gates**
-
-Run: `pnpm --filter @lucasmarkes/hairline test && pnpm --filter @lucasmarkes/hairline typecheck`
-Expected: PASS, `Tests 93 passed (93)`, and `tsc --noEmit` prints nothing.
-
-Run: `pnpm --filter @lucasmarkes/hairline build && pnpm --filter @lucasmarkes/hairline test:browser`
-Expected: PASS, `19 passed`. Riffle's parity test still passes: the bands came out of both sides of the comparison in Task 2, and now the package simply has none to remove.
-
-Run: `pnpm --filter @lucasmarkes/hairline size && pnpm --filter @lucasmarkes/hairline lint:package`
-Expected: `All good!` from size-limit, with every size under its budget (about 11.3 kB of 12.8, 4.8 of 5.4, and 11.6 of 13.2). publint prints no problem, and attw shows 🟢 for `node16 (from ESM)` and `bundler` on both entries.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add packages/hairline/src/figures/riffle.ts packages/hairline/src/core/styles.ts packages/hairline/test/mount.test.ts
-git commit -m "Riffle: no card names and no drawn hit bands; a card is read out by its number
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-### Task 4: The fixtures, the README and CONTRIBUTING speak `intensity`
-
-**Files:**
-- Modify: `fixtures/next-app/app/page.tsx`, `fixtures/next-app/app/registry/page.tsx`, `fixtures/next-app/app/vanilla.tsx`, `fixtures/vite-vanilla/src/main.ts`
-- Modify: `README.md`, `CONTRIBUTING.md`
-
-**Interfaces:**
-- Consumes from Task 2: the public API (`HairlineOptions`, the six functions and components). The registry item's source (`registry/src/hairline.tsx`, built by `registry/build.mjs` into the site's `/r/hairline.json`) wraps the components and takes its props from them through `ComponentProps<typeof …>`, so it follows the new props without a change.
-- Produces: the real-consumer layer (base spec, layer 6) on the new API, and the README that npm shows.
-
-This task's test is the existing consumer check, which packs the package, installs the tarball into copies of both fixtures, builds them with their own toolchains and opens them in Chrome. The fixtures still pass the old options, so it fails first.
-
-- [ ] **Step 1: Run the consumer check to see it fail**
-
-Run: `pnpm --filter @lucasmarkes/hairline build && node scripts/consumers.mjs`
-Expected: FAIL, exit code 1, ending `2 consumer checks failed.` Both fixtures print `✗ build (the fixture's own typecheck and bundler)`:
-- next-app: `error TS2322` for `labels` on `<Riffle>` and `rate` on `<Slow>` in `app/page.tsx`, and `error TS2353 … 'afterglow' does not exist in type 'HairlineOptions'` in `app/vanilla.tsx`.
-- vite-vanilla: `error TS2305: Module '"@lucasmarkes/hairline"' has no exported member 'ranges'` (and `'RiffleOptions'`), `error TS2315: Type 'Figure' is not generic`, and `TS2353` for `stagger` and `radius`.
-
-It needs the network: npm installs next, react and vite.
-
-- [ ] **Step 2: Move the fixtures to `intensity`**
-
-`fixtures/next-app/app/page.tsx (diff)`
-```diff
---- a/fixtures/next-app/app/page.tsx
-+++ b/fixtures/next-app/app/page.tsx
-@@ -9,8 +9,8 @@ import { Vanilla } from "./vanilla";
- export default function Page() {
- return (
- <main style={{ display: "grid", gap: 24, width: 400, margin: "40px auto" }}>
-- <Riffle id="riffle" labels={["Radial menu", "Drum"]} />
-- <Slow id="slow" rate={0.4} theme="dark" />
-+ <Riffle id="riffle" intensity={0.8} />
-+ <Slow id="slow" intensity={0.25} theme="dark" />
- <Vanilla />
- </main>
- );
-```
-
-`fixtures/next-app/app/registry/page.tsx (diff)`
-```diff
---- a/fixtures/next-app/app/registry/page.tsx
-+++ b/fixtures/next-app/app/registry/page.tsx
-@@ -1,5 +1,5 @@
- import type { CSSProperties } from "react";
--import { Terrain } from "@/components/ui/hairline";
-+import { Riffle, Terrain } from "@/components/ui/hairline";
-
- /** shadcn's tokens, as a dark theme would define them. */
- const tokens = { "--background": "#101014", "--foreground": "#fafafa", "--muted-foreground": "#a1a1aa", "--border": "#27272a" } as CSSProperties;
-@@ -13,6 +13,7 @@ export default function Page() {
- return (
- <main style={{ width: 400, margin: "40px auto", background: "var(--background)", ...tokens }}>
- <Terrain id="themed" />
-+ <Riffle intensity={0.8} />
- </main>
- );
- }
-```
-
-`fixtures/next-app/app/vanilla.tsx (diff)`
-```diff
---- a/fixtures/next-app/app/vanilla.tsx
-+++ b/fixtures/next-app/app/vanilla.tsx
-@@ -6,7 +6,7 @@ import { phosphor } from "@lucasmarkes/hairline";
- export function Vanilla() {
- const ref = useRef<HTMLDivElement>(null);
- useEffect(() => {
-- const figure = phosphor(ref.current!, { afterglow: 900 });
-+ const figure = phosphor(ref.current!, { intensity: 0.8 });
- return () => figure.destroy();
- }, []);
- return <div id="phosphor" ref={ref} />;
-```
-
-`fixtures/vite-vanilla/src/main.ts (diff)`
-```diff
---- a/fixtures/vite-vanilla/src/main.ts
-+++ b/fixtures/vite-vanilla/src/main.ts
-@@ -1,18 +1,17 @@
--import { exploded, phosphor, ranges, riffle, slow, terrain, turntable, type Figure, type RiffleOptions } from "@lucasmarkes/hairline";
-+import { exploded, phosphor, riffle, slow, terrain, turntable, type Figure } from "@lucasmarkes/hairline";
-
- /** No framework: six elements, six calls. */
- const el = (id: string) => document.getElementById(id)!;
- const read = el("read");
-
--const cards: Figure<RiffleOptions> = riffle(el("riffle"), {
-- stagger: ranges.riffle.stagger.max,
-- labels: ["Radial menu", "Drum"],
-+const cards: Figure = riffle(el("riffle"), {
-+ intensity: 1,
- onRead: (text) => { read.textContent = text; },
- });
--terrain(el("terrain"), { radius: 4 });
-+terrain(el("terrain"), { intensity: 0.75 });
- exploded(el("exploded"));
- phosphor(el("phosphor"), { theme: "dark" });
- slow(el("slow"));
- turntable(el("turntable"));
-
--cards.update({ bands: true });
-+cards.update({ intensity: 0.8 });
-```
-
-- [ ] **Step 3: Run the consumer check to see it pass**
-
-Run: `node scripts/consumers.mjs`
-Expected: PASS. Every line under `▸ tarball`, `▸ fixtures/next-app` and `▸ fixtures/vite-vanilla` is a `✓`, and it ends `Both consumers install, build and draw.`
-
-- [ ] **Step 4: Rewrite the README**
-
-The README leads with the install, shows `<Terrain />` with no props, and documents the four options in one table. The ranges table, Riffle's `bands` and `labels`, and every per-figure option are gone.
-
-`README.md`
-````markdown
-# hairline
-
-Six isometric line figures that answer the pointer. For React and for anything with a DOM.
-
-[![npm](https://img.shields.io/npm/v/@lucasmarkes/hairline)](https://www.npmjs.com/package/@lucasmarkes/hairline)
-[![CI](https://github.com/lucasmarkes/hairline/actions/workflows/ci.yml/badge.svg)](https://github.com/lucasmarkes/hairline/actions/workflows/ci.yml)
-[![license](https://img.shields.io/npm/l/@lucasmarkes/hairline)](./LICENSE)
-
-![The six figures: a tray of cards, a field of pillars, a window in layers, a dot matrix, a conveyor belt and a turntable](https://raw.githubusercontent.com/lucasmarkes/hairline/main/assets/hero.gif)
-
-Live, with a slider for `intensity`: **[hairline.lucasmarkes.com](https://hairline.lucasmarkes.com)**
-
-## Install
-
-```sh
-npm i @lucasmarkes/hairline
-```
-
-No dependencies. ESM only. React 18 or later is an optional peer, needed only by `@lucasmarkes/hairline/react`.
-
-With shadcn, which adds the package and a wrapper that reads your theme's tokens:
-
-```sh
-npx shadcn@latest add https://hairline.lucasmarkes.com/r/hairline.json
-```
-
-## Use
-
-### React
-
-```tsx
-import { Terrain } from "@lucasmarkes/hairline/react";
-
-export function Hero() {
- return <Terrain />;
-}
-```
-
-The figure fills its parent's width at a 5:4 aspect ratio. The entry is a client module, so a Server Component can render it with no `"use client"` of its own. Every component takes the options below and every `<div>` attribute, and forwards its ref to the `<div>`.
-
-### Anything else
-
-```ts
-import { terrain } from "@lucasmarkes/hairline";
-
-const figure = terrain(document.getElementById("figure")!);
-
-figure.update({ intensity: 0.8 });
-figure.destroy();
-```
-
-A figure draws into the element you give it, at the element's width and a 5:4 aspect ratio. `update` changes options on the running figure; `destroy` removes what the figure added. That is the shape of a Svelte action, so `use:terrain={{ intensity }}` works as it is.
-
-## The figures
-
-| Function | Component | What it is | A stronger `intensity` |
-| --- | --- | --- | --- |
-| `riffle` | `Riffle` | A tray of eight cards. The card under the pointer stands up; the arrow keys walk the cards. | The ripple spreads further from the pulled card. |
-| `terrain` | `Terrain` | Eighty-one pillars on a plinth that rise around the pointer. | A wider area rises. |
-| `exploded` | `Exploded` | An app window in four layers. Moving across opens the gap; moving down picks a layer. | The layers open further. |
-| `phosphor` | `Phosphor` | A dot matrix that plays a loop, and fades like phosphor where the pointer paints it. | The trail lingers longer. |
-| `slow` | `Slow` | Crates riding a belt through a gate. Hovering slows the clock without stopping it. | Time slows down more. |
-| `turntable` | `Turntable` | Blocks on a turntable. A flick spins it; it settles on the nearest quarter turn. | The spin coasts longer. |
-
-## Options
-
-Every figure takes the same four, all optional:
-
-| Option | Type | Default | |
-| --- | --- | --- | --- |
-| `intensity` | `number` | `0.5` | How strongly the figure answers the pointer, from 0 (subtle) to 1 (strong). A number outside 0…1 is clamped; anything that is not a number is 0.5. |
-| `theme` | `"auto" \| "light" \| "dark"` | `"auto"` | `"auto"` follows the page: an ancestor with class `dark` or `data-theme="dark"`, then the page's `color-scheme`. |
-| `label` | `string` | a description in English | The accessible name. In React, `aria-label` does the same. |
-| `onRead` | `(text: string) => void` | | The figure's caption, each time it changes: `"03"`, `"gap 28.0"`, `"rate 0.20×"`. |
-
-In `update`, a key set to `undefined` goes back to its default, and a key left out stays as it is.
-
-## Theme
-
-Six custom properties, set on the figure or on anything above it:
-
-```css
-.figures {
- --hairline-plate: #101014; /* the fill of every plate: the colour the figure sits on */
- --hairline-hi: #fafafa; /* what is lit */
- --hairline-edge: #a1a1aa; /* silhouettes */
- --hairline-mid: #52525b; /* every other stroke */
- --hairline-lo: #27272a; /* what recedes */
- --hairline-stroke: 0.9; /* stroke width, in CSS pixels at any size */
-}
-```
-
-`--hairline-plate` is the one to get right. Plates are filled, not transparent, because a plate hides what is drawn behind it; on a background that is neither white nor `#08090a`, set it to that background.
-
-The figure's styles have no specificity, so any rule of yours wins without `!important`.
-
-## Notes
-
-- **Accessibility.** A figure is an image with a description you can replace with `label`. Riffle is the exception: it is a focusable group, the arrow keys walk its cards, and a live region reads the card out.
-- **Reduced motion.** With `prefers-reduced-motion`, the figures that play on their own (Phosphor and Slow) hold still, and every figure still answers the pointer.
-- **Performance.** Every figure on a page shares one `requestAnimationFrame` loop. A figure off screen, or at rest, does no work, and the loop stops when nothing is moving.
-- **Server rendering.** On the server a component is an empty box with a 5:4 aspect ratio, so nothing shifts when it draws. The functions need a DOM: call them in an effect, in `onMount`, or in a script after the element.
-- **Shadow DOM.** A figure mounted inside a shadow root styles itself there.
-
-## More
-
-- [hairline.lucasmarkes.com](https://hairline.lucasmarkes.com): every figure live, an inspector that writes the snippet for you, and a CDN example.
-- [The essay](https://lucasmarkes.com/lab/hairline): how the figures are drawn, and why with lines.
-- [CHANGELOG.md](https://github.com/lucasmarkes/hairline/blob/main/CHANGELOG.md) and [CONTRIBUTING.md](https://github.com/lucasmarkes/hairline/blob/main/CONTRIBUTING.md).
-
-The style is a study of the illustrations on [Linear](https://linear.app)'s home page.
-
-## License
-
-MIT © Lucas Marques
-````
-
-- [ ] **Step 5: Update CONTRIBUTING**
-
-The parity paragraph says what the comparison strips and where the intensities come from, and "Adding an option" becomes "Tuning `intensity`":
-
-`CONTRIBUTING.md`
-````markdown
-# Contributing
-
-## Setup
-
-Node 22 or later, pnpm 10 (`corepack enable` picks the right one), and Google Chrome for the browser tests.
-
-```sh
-pnpm install
-pnpm build
-```
-
-## Layout
-
-```
-packages/hairline the package: src/core (maths, stage, styles), src/figures (six engines),
- src/mount.ts (the public lifecycle), src/index.ts and src/react.tsx (the two entries)
-apps/site hairline.lucasmarkes.com (Next.js)
-registry the shadcn item: its source, and the scripts that build and validate it
-fixtures two apps that install the packed tarball: Next.js and Vite
-scripts the release gate and what it calls
-```
-
-## Commands
-
-| | |
-| --- | --- |
-| `pnpm build` | Builds the package, then the site. |
-| `pnpm typecheck` | TypeScript, including the type tests in `packages/hairline/test/types.test-d.tsx`. |
-| `pnpm test` | Unit and component tests (Vitest, jsdom). |
-| `pnpm test:browser` | Browser tests in Chrome (Playwright): the figures, the theme, parity, the site. |
-| `pnpm dev` | The site on `localhost:3000`, with the package rebuilding on change. |
-| `pnpm release --static` | The release gate without the steps that need the network. CI runs this. |
-| `pnpm release` | The whole gate. It never publishes. |
-| `node scripts/consumers.mjs` | Packs the package and installs it in both fixtures. |
-
-## The engines, and why their comments mention "the study"
-
-The six engines in `packages/hairline/src/figures`, and `src/core/iso.ts`, `motion.ts` and `stage.ts`, were ported from the essay at [lucasmarkes.com/lab/hairline](https://lucasmarkes.com/lab/hairline), where they are figures 9.1 to 9.6. Their comments still say "the study" and "Fig 9.n": that is the essay.
-
-The port is held to the essay by the parity tests. `packages/hairline/test/parity/golden` holds the SVG each figure drew on the essay's page, under a frozen clock, at four moments of a scripted pointer path; `test/browser/parity.spec.ts` replays the same script against the package, on the same frozen clock, and expects the same SVG and the same caption, character for character. Two things come out of both sides first, because the package no longer has them: Riffle's hidden hit bands, and the names the essay gives Riffle's cards. Where the script changes the option, the package is set to the `intensity` in `test/parity/scripts.mjs` that maps exactly onto the essay's value.
-
-So a change to an engine that moves a line fails parity, and that is the point. If the change is meant, say so in the pull request and update the golden file for that figure by hand. The goldens are not regenerated from the package: `pnpm -C packages/hairline capture <commit> [url]` records them from the essay's site at that commit, and exists for the day the essay changes.
-
-## Tuning `intensity`
-
-Every figure takes one tuning option, `intensity`, from 0 to 1. Each figure turns it into its own number through the table in `packages/hairline/src/intensity.ts`: three values per figure, at 0, 0.5 and 1, joined by two straight lines. The value at 0.5 is the figure's default, so the default drawing never changes.
-
-To change how strongly a figure answers:
-
-1. Change its row in `src/intensity.ts`. `test/intensity.test.ts` checks the row still moves one way only, and that each parity intensity still lands on its golden value.
-2. Change the same row in `apps/site/lib/figures.ts`, which keeps a copy for the site's copy. `apps/site/test/docs.test.ts` fails until the two agree.
-
-There are no per-figure options, by design. A new option is a new key in `HairlineOptions` (`src/mount.ts`), for every figure at once.
-
-## Pull requests
-
-- One change per pull request, with a test that fails without it.
-- `pnpm typecheck && pnpm test && pnpm test:browser` pass.
-- A change a user can see gets a line in `CHANGELOG.md`, under the next version.
-
-## Releasing
-
-Maintainers only.
-
-1. Bump `version` in `packages/hairline/package.json` and add a `## <version> - <date>` section to `CHANGELOG.md`.
-2. `pnpm release` passes.
-3. Commit, then `git tag v<version> && git push origin main v<version>`.
-
-The tag starts `.github/workflows/publish.yml`, which waits for approval in the `release` environment, publishes to npm with provenance, and creates the GitHub Release from the changelog section. A version with a hyphen (`0.2.0-rc.0`) is published under the `next` dist-tag.
-````
-
-Run: `grep -nwE "stagger|radius|afterglow|coast|bands|labels|ranges|w-80" README.md`
-Expected: no output, exit code 1. (`-w` matches whole words, so "coasts" in Turntable's row does not count; `gap` and `rate` appear in the `onRead` captions, which is correct.)
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add fixtures README.md CONTRIBUTING.md
-git commit -m "Docs and fixtures: one intensity option, and the README leads with the install
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-### Task 5: The site's copy, snippets and llms.txt speak `intensity`
-
-**Files:**
-- Create: `apps/site/lib/size.ts` (the Tiny card's number)
-- Modify: `apps/site/lib/figures.ts` (the figures, the intensity mirror, the options table, the theme table, the cards, the links)
-- Modify: `apps/site/lib/snippets.ts` (the install commands, the inspector's snippet, the four quickstart tabs)
-- Modify: `apps/site/lib/highlight.ts` (no live span any more)
-- Modify: `apps/site/lib/llms.ts` (`/llms.txt` with one option and each figure's scale)
-- Test: `apps/site/test/docs.test.ts`
-
-**Interfaces:**
-- Consumes from Task 1: `TABLE` from `packages/hairline/src/intensity.ts` (the test only, through a relative path, since the package does not export it). From Task 2: the public API and the type `HairlineOptions`.
-- Produces, for Task 6's page and components:
- - `apps/site/lib/figures.ts`: `type FigureId`, `type FigureDoc = { id: FigureId; name: string; summary: string; stronger: string; parameter: { name: string; unit: string } }`, `FIGURES: FigureDoc[]` (in the package's order), `INTENSITY: Record<FigureId, readonly [number, number, number]>` (a copy of `TABLE`), `type Row = { name; type; default; description }`, `OPTIONS: Row[]` (intensity, theme, label, onRead), `THEME`, `CARDS: { title; body }[]` and `LINKS`.
- - `apps/site/lib/size.ts`: `tiny(): string`, for example `"16.3 kB"`.
- - `apps/site/lib/snippets.ts`: `PACKAGE`, `install(base: string): { label: string; code: string }[]` (npm, pnpm, yarn, bun, shadcn), `type Theme = "auto" | "light" | "dark"`, `snippet(name: string, state: { intensity: number; theme: Theme }): string`, `REACT`, `VANILLA`, `CDN`, `CSS`, and `PASTE: { label; lang; code }[]` (React, Vanilla, CDN, CSS).
- - `apps/site/lib/highlight.ts`: `highlight(code: string, lang: string): Promise<string>` and `plain(code: string): string`. `LIVE` and the third argument of `highlight` are gone.
- - `apps/site/lib/llms.ts`: `scale(id, parameter): string` and `llms(base: string): string`.
-
-The old `figures.ts` exported `CARDS`, `span`, `shown`, `rows`, `SHARED` and `NOTES`, which the page and the components still import. They go here, so the site's typecheck and build stay red until Task 6 replaces the page. Only `docs.test.ts` has to pass at the end of this task.
-
-- [ ] **Step 1: Write the failing test**
-
-Replace `apps/site/test/docs.test.ts`. It holds the site's copy of the intensity table equal to the package's, ties the options table to the keys of `HairlineOptions` at compile time, pins the inspector's snippet, and checks that no page or file mentions an option the package dropped. "leaves out an intensity that reads as 0.5…" and "shows an intensity of 0…" are Review Focus 3.
-
-`apps/site/test/docs.test.ts`
-````ts
-import { gzipSync } from "node:zlib";
-import { readFileSync } from "node:fs";
-import { describe, expect, it } from "vitest";
-import * as components from "@lucasmarkes/hairline/react";
-import * as figures from "@lucasmarkes/hairline";
-import type { HairlineOptions } from "@lucasmarkes/hairline";
-import { TABLE } from "../../../packages/hairline/src/intensity";
-import { FIGURES, INTENSITY, OPTIONS } from "@/lib/figures";
-import { llms, scale } from "@/lib/llms";
-import { tiny } from "@/lib/size";
-import { PASTE, install, snippet } from "@/lib/snippets";
-
-/** The docs describe the package, and these check that nothing was written by hand around it. */
-
-/* a key added to or taken from HairlineOptions fails the typecheck here, before the table can drift */
-const KEYS = { intensity: true, theme: true, label: true, onRead: true } satisfies Record<keyof HairlineOptions, true>;
-
-describe("the figures", () => {
- it("are the package's six, each with a function and a component", () => {
- expect(FIGURES.map((f) => f.id).sort()).toEqual(Object.keys(figures).sort());
- for (const doc of FIGURES) expect(components).toHaveProperty(doc.name);
- });
-
- it("copy the package's intensity table exactly", () => {
- expect(INTENSITY).toEqual(TABLE);
- });
-});
-
-describe("the options table", () => {
- it("has the four keys of HairlineOptions, in that order", () => {
- expect(OPTIONS.map((r) => r.name)).toEqual(Object.keys(KEYS));
- });
-
- it("gives intensity's default as 0.5", () => {
- expect(OPTIONS[0]).toMatchObject({ name: "intensity", type: "number", default: "0.5" });
- });
-});
-
-describe("the inspector's snippet", () => {
- it("is the bare component at the defaults", () => {
- expect(snippet("Terrain", { intensity: 0.5, theme: "auto" })).toContain("<Terrain />");
- });
-
- it("leaves out an intensity that reads as 0.5 at the slider's precision", () => {
- expect(snippet("Terrain", { intensity: 0.1 + 0.4, theme: "auto" })).toContain("<Terrain />");
- expect(snippet("Terrain", { intensity: 0.5000001, theme: "auto" })).toContain("<Terrain />");
- });
-
- it("shows an intensity of 0, which is not the default", () => {
- expect(snippet("Riffle", { intensity: 0, theme: "auto" })).toContain("<Riffle intensity={0} />");
- });
-
- it("shows what differs, intensity first, at two decimals", () => {
- expect(snippet("Slow", { intensity: 0.1 + 0.2, theme: "dark" })).toContain('<Slow intensity={0.3} theme="dark" />');
- expect(snippet("Slow", { intensity: 0.55, theme: "light" })).toContain('<Slow intensity={0.55} theme="light" />');
- expect(snippet("Slow", { intensity: 1, theme: "auto" })).toContain("<Slow intensity={1} />");
- });
-
- it("imports what it renders", () => {
- expect(snippet("Exploded", { intensity: 0.5, theme: "auto" })).toMatch(/^import \{ Exploded \} from "@lucasmarkes\/hairline\/react";/);
- });
-});
-
-describe("the install commands", () => {
- it("put npm first and install from the address the site is built for", () => {
- const commands = install("https://example.test");
- expect(commands.map((c) => c.label)).toEqual(["npm", "pnpm", "yarn", "bun", "shadcn"]);
- expect(commands[0].code).toBe("npm i @lucasmarkes/hairline");
- expect(commands[4].code).toBe("npx shadcn@latest add https://example.test/r/hairline.json");
- });
-});
-
-describe("the quickstart", () => {
- it("pastes React, Vanilla, CDN and CSS, and none of them sets an option the package dropped", () => {
- expect(PASTE.map((p) => p.label)).toEqual(["React", "Vanilla", "CDN", "CSS"]);
- for (const p of PASTE) expect(p.code).not.toMatch(/stagger|radius|afterglow|coast|bands|labels|ranges|className/);
- });
-
- it("sets all six theme properties in the CSS tab", () => {
- const css = PASTE[3].code;
- for (const key of ["plate", "hi", "edge", "mid", "lo", "stroke"]) expect(css).toContain(`--hairline-${key}:`);
- });
-});
-
-describe("the Tiny card", () => {
- it("is the gzip size of the vanilla entry, to a tenth of a kB", () => {
- const bytes = gzipSync(readFileSync(new URL("../../../packages/hairline/dist/index.js", import.meta.url))).length;
- expect(tiny()).toBe(`${(bytes / 1000).toFixed(1)} kB`);
- expect(tiny()).toMatch(/^\d+\.\d kB$/);
- });
-});
-
-describe("/llms.txt", () => {
- const text = llms("https://example.test");
-
- it.each(FIGURES)("names $name with its row of the intensity table", (doc) => {
- expect(text).toContain(`### ${doc.name}`);
- expect(text).toContain(doc.stronger);
- expect(text).toContain(scale(doc.id, doc.parameter));
- for (const n of INTENSITY[doc.id]) expect(scale(doc.id, doc.parameter)).toContain(String(n));
- });
-
- it("documents the four options, every theme property and the registry item", () => {
- for (const row of OPTIONS) expect(text).toContain(`- \`${row.name}\``);
- for (const key of ["plate", "hi", "edge", "mid", "lo", "stroke"]) expect(text).toContain(`--hairline-${key}`);
- expect(text).toContain("https://example.test/r/hairline.json");
- });
-
- it("mentions no option the package dropped", () => {
- expect(text).not.toMatch(/stagger=|radius=|\bbands\b|\blabels\b|\branges\b/);
- });
-
- it("has no hole in it", () => {
- // outside the code blocks, where `undefined` is a word TypeScript uses
- const prose = text.replace(/```[\s\S]*?```/g, "").replace(/`undefined`/g, "");
- expect(prose).not.toMatch(/undefined|NaN|\[object/);
- });
-});
-````
-
-- [ ] **Step 2: Run it to see it fail**
-
-Run: `pnpm --filter @lucasmarkes/hairline build && pnpm --filter @hairline/site test`
-Expected: FAIL. `test/docs.test.ts` fails to load with `TypeError: Cannot convert undefined or null to object` (the old `figures.ts` has no `INTENSITY`), and no test runs.
-
-- [ ] **Step 3: Write the site's library**
-
-Replace `apps/site/lib/figures.ts`. `INTENSITY` is a copy of the package's table, because the package does not export it; the test above keeps the two equal.
-
-`apps/site/lib/figures.ts`
-```ts
-/**
- * The page's copy about each figure, and the options every figure takes.
- *
- * INTENSITY copies the table in packages/hairline/src/intensity.ts, which the
- * package keeps internal. test/docs.test.ts holds the two equal, so /llms.txt
- * cannot describe a map the figures do not use.
- */
-
-export type FigureId = "riffle" | "terrain" | "exploded" | "phosphor" | "slow" | "turntable";
-
-export type FigureDoc = {
- id: FigureId;
- /** The React component, and the figure's name on the page. */
- name: string;
- summary: string;
- /** What a higher intensity does to this figure, as one sentence. */
- stronger: string;
- /** The number intensity sets inside the figure, for /llms.txt. */
- parameter: { name: string; unit: string };
-};
-
-export const FIGURES: FigureDoc[] = [
- {
- id: "riffle",
- name: "Riffle",
- summary: "A tray of eight cards. The card under the pointer stands up and its neighbours lean after it. The arrow keys walk the cards.",
- stronger: "The ripple spreads further from the pulled card.",
- parameter: { name: "stagger", unit: "ms" },
- },
- {
- id: "terrain",
- name: "Terrain",
- summary: "Eighty-one pillars on a plinth. They rise around the pointer and settle back into a dune with two rises.",
- stronger: "A wider area rises.",
- parameter: { name: "radius", unit: "cells" },
- },
- {
- id: "exploded",
- name: "Exploded",
- summary: "An app window taken apart into four layers. Moving across opens the gap; moving down picks a layer.",
- stronger: "The layers open further.",
- parameter: { name: "gap", unit: "viewBox units" },
- },
- {
- id: "phosphor",
- name: "Phosphor",
- summary: "A seven by seven dot matrix playing a loop. Where the pointer paints, the dots fade like phosphor.",
- stronger: "The trail lingers longer.",
- parameter: { name: "afterglow", unit: "ms" },
- },
- {
- id: "slow",
- name: "Slow",
- summary: "Crates riding a belt through a gate. Hovering slows the clock without stopping it.",
- stronger: "Time slows down more.",
- parameter: { name: "rate", unit: "× normal speed" },
- },
- {
- id: "turntable",
- name: "Turntable",
- summary: "Blocks on a turntable. A flick across it spins it, and it settles on the nearest quarter turn.",
- stronger: "The spin coasts longer.",
- parameter: { name: "coast", unit: "ms" },
- },
-];
-
-/** Each figure's number at intensity 0, 0.5 and 1: a copy of the package's table. */
-export const INTENSITY: Record<FigureId, readonly [number, number, number]> = {
- riffle: [0, 40, 90],
- terrain: [1.5, 3, 5],
- exploded: [12, 28, 40],
- phosphor: [150, 520, 1500],
- slow: [0.6, 0.2, 0.05],
- turntable: [200, 650, 1500],
-};
-
-export type Row = { name: string; type: string; default: string; description: string };
-
-/** The options every figure takes: the whole API, in the quickstart's table. */
-export const OPTIONS: Row[] = [
- { name: "intensity", type: "number", default: "0.5", description: "How strongly the figure answers the pointer, from 0 (subtle) to 1 (strong). Outside 0…1 is clamped; anything that is not a number is 0.5." },
- { name: "theme", type: "\"auto\" | \"light\" | \"dark\"", default: "\"auto\"", description: "\"auto\" follows the page: an ancestor with class dark or data-theme=\"dark\", then the page's color-scheme." },
- { name: "label", type: "string", default: "a description", description: "The accessible name. In React, aria-label does the same." },
- { name: "onRead", type: "(text: string) => void", default: "", description: "The figure's caption, each time it changes. Called once at mount with the rest caption." },
-];
-
-/** The public theme: six custom properties, set on the figure or on anything above it. */
-export const THEME: { property: string; light: string; role: string }[] = [
- { property: "--hairline-plate", light: "#ffffff", role: "The fill of every plate. It hides what is drawn behind, so it must be the colour the figure sits on." },
- { property: "--hairline-hi", light: "#232327", role: "The stroke of what is lit: the card pulled, the layer picked, a dot that is on." },
- { property: "--hairline-edge", light: "#a4a4ac", role: "Silhouettes, and dots at half strength." },
- { property: "--hairline-mid", light: "#c3c3c9", role: "Every other stroke." },
- { property: "--hairline-lo", light: "#e0e0e4", role: "What recedes: guides, and dots that are off." },
- { property: "--hairline-stroke", light: "0.9", role: "The stroke width, in CSS pixels at any size." },
-];
-
-/** The four cards under the figures. Tiny's body is the measured size; see lib/size.ts. */
-export const CARDS: { title: string; body: string }[] = [
- { title: "Tiny", body: "gzipped, all six figures. A bundle that imports one carries one." },
- { title: "No dependencies", body: "SVG and one shared animation frame. React is optional." },
- { title: "Accessible", body: "Keyboard on Riffle, a description for screen readers, and stillness under reduced motion." },
- { title: "Themeable", body: "Six CSS variables, on the figure or anything above it. Light and dark built in." },
-];
-
-export const LINKS = {
- github: "https://github.com/lucasmarkes/hairline",
- npm: "https://www.npmjs.com/package/@lucasmarkes/hairline",
- essay: "https://lucasmarkes.com/lab/hairline",
- linear: "https://linear.app",
-} as const;
-```
-
-Create `apps/site/lib/size.ts`:
-
-```ts
-import { readFileSync } from "node:fs";
-import { join } from "node:path";
-import { gzipSync } from "node:zlib";
-
-/**
- * The vanilla entry's gzip size with all six figures, as the Tiny card says
- * it: "16.3 kB". Measured at build from the package's own dist, which turbo
- * builds before the site. Next runs the build from apps/site.
- */
-export function tiny(): string {
- const file = readFileSync(join(process.cwd(), "../../packages/hairline/dist/index.js"));
- return `${(gzipSync(file).length / 1000).toFixed(1)} kB`;
-}
-```
-
-Replace `apps/site/lib/snippets.ts`. `snippet` writes only the props that differ from the default, and reads the slider at two decimals, so `0.1 + 0.4` counts as the default and `0` does not:
-
-`apps/site/lib/snippets.ts`
-```ts
-import { THEME } from "./figures";
-
-/**
- * Every piece of code the page shows, as plain text. The page highlights it;
- * /llms.txt prints it as it is.
- */
-
-export const PACKAGE = "@lucasmarkes/hairline";
-
-/** npm first: it is the command a stranger already knows. */
-export function install(base: string): { label: string; code: string }[] {
- return [
- { label: "npm", code: `npm i ${PACKAGE}` },
- { label: "pnpm", code: `pnpm add ${PACKAGE}` },
- { label: "yarn", code: `yarn add ${PACKAGE}` },
- { label: "bun", code: `bun add ${PACKAGE}` },
- { label: "shadcn", code: `npx shadcn@latest add ${base}/r/hairline.json` },
- ];
-}
-
-export type Theme = "auto" | "light" | "dark";
-
-/**
- * The inspector's snippet: the component with only the props that differ
- * from the default. The intensity is read to two decimals, the slider's
- * precision, so 0.5 and a float a hair away from it both leave it out.
- */
-export function snippet(name: string, state: { intensity: number; theme: Theme }): string {
- const intensity = Math.round(state.intensity * 100) / 100;
- const props = [
- intensity !== 0.5 ? ` intensity={${intensity}}` : "",
- state.theme !== "auto" ? ` theme="${state.theme}"` : "",
- ].join("");
- return `import { ${name} } from "${PACKAGE}/react";\n\n<${name}${props} />\n`;
-}
-
-export const REACT = `import { Terrain } from "${PACKAGE}/react";
-
-export default function Page() {
- return <Terrain />;
-}
-`;
-
-export const VANILLA = `import { terrain } from "${PACKAGE}";
-
-const figure = terrain(document.getElementById("figure")!);
-
-figure.update({ intensity: 0.8 });
-figure.destroy();
-`;
-
-export const CDN = `<div id="figure" style="width: 400px"></div>
-
-<script type="module">
- import { terrain } from "https://esm.sh/${PACKAGE}";
-
- terrain(document.getElementById("figure"));
-</script>
-`;
-
-export const CSS = `/* On a figure or anything above it. Without them a figure is light,
- or dark when the page says so. --hairline-plate must be the colour
- the figure sits on: it hides what is drawn behind each plate. */
-.figures {
-${THEME.map((t) => ` ${t.property}: ${t.light};`).join("\n")}
-}
-`;
-
-/** The quickstart's second step. */
-export const PASTE: { label: string; lang: string; code: string }[] = [
- { label: "React", lang: "tsx", code: REACT },
- { label: "Vanilla", lang: "ts", code: VANILLA },
- { label: "CDN", lang: "html", code: CDN },
- { label: "CSS", lang: "css", code: CSS },
-];
-```
-
-Replace `apps/site/lib/highlight.ts`. The inspector's snippet is plain text now, so nothing needs a live span:
-
-`apps/site/lib/highlight.ts`
-```ts
-import { codeToHtml } from "shiki";
-
-/** Highlighting happens here, at build, so no highlighter reaches the browser. */
-
-const escape = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
-
-export async function highlight(code: string, lang: string): Promise<string> {
- return codeToHtml(code.trimEnd(), { lang, theme: "min-light" });
-}
-
-/** Plain text in the same wrapper the highlighter writes. */
-export function plain(code: string): string {
- return `<pre class="shiki"><code>${escape(code.trimEnd())}</code></pre>`;
-}
-```
-
-Replace `apps/site/lib/llms.ts`:
-
-`apps/site/lib/llms.ts`
-````ts
-import { FIGURES, INTENSITY, LINKS, OPTIONS, THEME, type Row } from "./figures";
-import { CDN, PACKAGE, REACT, VANILLA, install } from "./snippets";
-
-/** The page as plain text, for a model to read: the same data, the same copy. */
-
-const table = (list: Row[]) => list.map((r) => `- \`${r.name}\` (${r.type}${r.default ? `, default ${r.default}` : ""}): ${r.description}`).join("\n");
-const fence = (lang: string, code: string) => "```" + lang + "\n" + code.trimEnd() + "\n```";
-
-/** "stagger 0 ms at 0, 40 ms at 0.5, 90 ms at 1" */
-export function scale(id: keyof typeof INTENSITY, parameter: { name: string; unit: string }): string {
- const unit = parameter.unit.startsWith("×") ? parameter.unit : ` ${parameter.unit}`;
- const [lo, mid, hi] = INTENSITY[id];
- return `${parameter.name} ${lo}${unit} at 0, ${mid}${unit} at 0.5, ${hi}${unit} at 1`;
-}
-
-export function llms(base: string): string {
- const out: string[] = [
- "# hairline",
- "",
- `> ${PACKAGE}: six isometric line figures that answer the pointer. SVG, no dependencies, ESM only. A function per figure, and a React component per figure. Every figure takes the same four options.`,
- "",
- "## Install",
- "",
- fence("sh", install(base).map((i) => i.code).join("\n")),
- "",
- "## Use",
- "",
- `React: \`import { ${FIGURES.map((f) => f.name).join(", ")} } from "${PACKAGE}/react"\`. Each component renders a \`<div>\`, takes the options below and any \`<div>\` attribute, and forwards its ref. The entry is a client module: render it from a Server Component without writing "use client".`,
- "",
- fence("tsx", REACT),
- "",
- `Vanilla: \`import { ${FIGURES.map((f) => f.id).join(", ")} } from "${PACKAGE}"\`. Each function takes an element and the options, draws into the element, and returns \`{ update(options), destroy() }\`. In \`update\`, a key set to \`undefined\` goes back to its default and a key left out stays as it is.`,
- "",
- fence("ts", VANILLA),
- "",
- "Without a bundler:",
- "",
- fence("html", CDN),
- "",
- "A figure fills its element's width at a 5:4 aspect ratio.",
- "",
- "## Options",
- "",
- table(OPTIONS),
- "",
- "## Figures",
- "",
- "What a higher `intensity` does to each figure, and the number it sets inside the figure (two straight lines through these three points):",
- ];
- for (const doc of FIGURES) {
- out.push("", `### ${doc.name}`, "", doc.summary, "", `Higher intensity: ${doc.stronger} (${scale(doc.id, doc.parameter)}.)`);
- }
- out.push(
- "", "## Theme", "",
- "Six CSS custom properties, set on the figure or on any ancestor. Without them a figure is light, or dark when an ancestor has class `dark` or `data-theme=\"dark\"`, or when the page's `color-scheme` is dark.",
- "", THEME.map((t) => `- \`${t.property}\` (light: ${t.light}): ${t.role}`).join("\n"),
- "", "## Accessibility", "",
- "A figure is an image with a description you can replace with `label`. Riffle is a focusable group: the arrow keys walk its cards and a live region reads out the card's number. Under prefers-reduced-motion, Phosphor and Slow hold still, and every figure still answers the pointer.",
- "", "## Links", "",
- `- Site: ${base}`, `- Source: ${LINKS.github}`, `- npm: ${LINKS.npm}`, `- The essay the figures come from: ${LINKS.essay}`, `- shadcn registry item: ${base}/r/hairline.json`, "",
- );
- return out.join("\n");
-}
-````
-
-- [ ] **Step 4: Run the test to see it pass**
-
-Run: `pnpm --filter @hairline/site test`
-Expected: PASS, `Tests 22 passed (22)` in `test/docs.test.ts`.
-
-Do not run the site's typecheck or build yet: they still fail on `app/page.tsx` and the components, which Task 6 replaces.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add apps/site/lib apps/site/test/docs.test.ts
-git commit -m "Site: the copy, the snippets and llms.txt speak one intensity option
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-### Task 6: The page: install first, the inspector, the quickstart
-
-**Files:**
-- Create: `apps/site/components/copy.tsx` (`useCopy` and `CopyButton`, with the select-the-text fallback)
-- Create: `apps/site/components/install.tsx` (the install pill: `$`, the manager, the command, copy)
-- Create: `apps/site/components/inspector.tsx` (one figure, its chips, the intensity slider, the theme switch and the live snippet)
-- Modify: `apps/site/components/tabs.tsx` (copy through `CopyButton`)
-- Delete: `apps/site/components/tile.tsx`, `apps/site/components/figure-demo.tsx`, `apps/site/components/theme-editor.tsx`
-- Modify: `apps/site/app/page.tsx`, `apps/site/app/layout.tsx` (Instrument Serif, and the Open Graph alt), `apps/site/app/globals.css`, `apps/site/app/og/page.tsx`
-- Test: `apps/site/test/site.spec.ts`
-
-**Interfaces:**
-- Consumes from Task 5: `FIGURES`, `OPTIONS`, `CARDS`, `LINKS` and `FigureId` from `@/lib/figures`; `tiny` from `@/lib/size`; `install`, `snippet`, `PASTE`, `PACKAGE` and `Theme` from `@/lib/snippets`; `highlight` and `plain` from `@/lib/highlight`. From Task 2: the six components and `HairlineOptions`.
-- Produces:
- - `apps/site/components/copy.tsx`: `useCopy(): [copied: boolean, copy: (text: string, fallback?: Element | null) => void]` and `CopyButton({ text: string | (() => string); select?: RefObject<Element | null>; label?: string; className?: string })`. When the clipboard is missing or refuses, `copy` selects `fallback`'s text and throws nothing.
- - `apps/site/components/install.tsx`: `Install({ commands: { label: string; code: string }[] })`, marked `data-install={label}`.
- - `apps/site/components/inspector.tsx`: `Inspector()`, marked `data-inspector`, Terrain first. The stage is `data-figure={id}`, the read-out `data-read`, the snippet `data-snippet`.
- - The page at `/`, top to bottom: the top bar (version, GitHub, `llms.txt`), the hero (headline, one sentence, the install pill, "Get started" and "GitHub"), the inspector, "One prop, six figures" (one row per figure, with no "Fig. N"), four cards (Tiny, No dependencies, Accessible, Themeable), "Two steps" (install, then paste in four tabs, then the options table with four rows), and the footer. Seven figures mount in all: six in the rows and one in the inspector.
- - `/og`: the headline and one Terrain, which Task 7 photographs.
-
-- [ ] **Step 1: Write the failing test**
-
-Replace `apps/site/test/site.spec.ts`. It runs against the built site in Chrome. "without a clipboard, copy selects the text instead and throws nothing" is Review Focus 4, and "the page fits a phone, with the longest install command and every control" is Review Focus 5. The shadcn command carries `http://localhost:3000`, because off Vercel the build's base URL is `localhost:3000` (`resolveBase()` in `scripts/base-url.mjs`) even though the tests serve on 4320.
-
-`apps/site/test/site.spec.ts`
-```ts
-import { expect, test, type Page } from "@playwright/test";
-
-const IDS = ["riffle", "terrain", "exploded", "phosphor", "slow", "turntable"];
-const MANAGERS = [
- ["npm", "npm i @lucasmarkes/hairline"],
- ["pnpm", "pnpm add @lucasmarkes/hairline"],
- ["yarn", "yarn add @lucasmarkes/hairline"],
- ["bun", "bun add @lucasmarkes/hairline"],
- // the build's base URL, which is localhost:3000 off Vercel
- ["shadcn", "npx shadcn@latest add http://localhost:3000/r/hairline.json"],
-] as const;
-
-function watch(page: Page): string[] {
- const noise: string[] = [];
- page.on("console", (m) => {
- // Vercel Analytics' script exists only on Vercel
- if (m.location().url.includes("/_vercel/")) return;
- if (m.type() === "error" || m.type() === "warning") noise.push(`${m.type()}: ${m.text()}`);
- });
- page.on("pageerror", (e) => noise.push(`pageerror: ${e}`));
- return noise;
-}
-
-/** The figure's drawing, without the ids that differ between mounts. */
-const drawing = (page: Page) => page.locator("[data-inspector] [data-hairline] > svg").evaluate((svg) => svg.innerHTML.replace(/hl-fd\d+/g, ""));
-
-test("the page prerenders empty boxes, then draws seven figures with a clean console", async ({ page, request }) => {
- const html = await (await request.get("/")).text();
- // every figure's box is empty on the server (the GitHub icon is the only svg)
- expect(html.match(/<div style="aspect-ratio:5 \/ 4"><\/div>/g)).toHaveLength(7);
- expect(html).not.toMatch(/aspect-ratio:5 \/ 4"[^>]*><svg/);
- expect(html).not.toMatch(/Fig\. \d/);
-
- const noise = watch(page);
- await page.goto("/");
- // the inspector's, and one per row
- await expect(page.locator("[data-hairline] > svg")).toHaveCount(7);
- for (const id of IDS) await expect(page.locator(`[data-row="${id}"] [data-hairline] > svg > *`).first()).toBeAttached();
- await expect(page.locator("[data-install]").first()).toHaveText(/npm i @lucasmarkes\/hairline/);
- await expect(page.locator("[data-size]")).toHaveText(/^\d+\.\d kB$/);
- await expect(page.locator("[data-version]")).toHaveText(/^v\d+\.\d+\.\d+/);
- expect(noise).toEqual([]);
-});
-
-test("the inspector's chips pick the figure, and the snippet follows", async ({ page }) => {
- await page.goto("/");
- const inspector = page.locator("[data-inspector]");
- await expect(inspector.locator("[data-snippet] .code-panel")).toContainText("<Terrain />");
- await inspector.getByRole("button", { name: "Riffle" }).click();
- await expect(inspector.locator("[data-figure]")).toHaveAttribute("data-figure", "riffle");
- await expect(inspector.locator("[data-hairline]")).toHaveCount(1);
- await expect(inspector.locator("[data-read]")).toHaveText("rest");
- await expect(inspector.locator("[data-snippet] .code-panel")).toContainText('import { Riffle } from "@lucasmarkes/hairline/react";');
- await expect(inspector.locator("[data-snippet] .code-panel")).toContainText("<Riffle />");
-});
-
-test("the inspector's slider reaches the figure, and the snippet shows it", async ({ page }) => {
- await page.goto("/");
- const inspector = page.locator("[data-inspector]");
- const slider = inspector.getByRole("slider", { name: "intensity" });
- const stage = inspector.locator("[data-hairline]");
- const box = (await stage.boundingBox())!;
- const hover = async () => {
- await page.mouse.move(box.x + 4, box.y + 4);
- await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2, { steps: 4 });
- await page.waitForTimeout(1200);
- };
-
- await slider.fill("0");
- await expect(inspector.locator("output")).toHaveText("0.00");
- await expect(inspector.locator("[data-snippet] .code-panel")).toContainText("<Terrain intensity={0} />");
- await hover();
- const subtle = await drawing(page);
-
- await slider.fill("1");
- await expect(inspector.locator("[data-snippet] .code-panel")).toContainText("<Terrain intensity={1} />");
- await hover();
- expect(await drawing(page)).not.toBe(subtle);
-
- await slider.fill("0.5");
- await expect(inspector.locator("[data-snippet] .code-panel")).toContainText("<Terrain />");
-});
-
-test("the inspector's theme switch repaints the figure", async ({ page }) => {
- await page.goto("/");
- const inspector = page.locator("[data-inspector]");
- await inspector.getByRole("button", { name: "Dark" }).click();
- await expect(inspector.locator("[data-snippet] .code-panel")).toContainText('<Terrain theme="dark" />');
- const plate = () => inspector.locator("[data-hairline] svg path").first().evaluate((el) => getComputedStyle(el).fill);
- await expect.poll(plate).toBe("rgb(8, 9, 10)");
- await inspector.getByRole("button", { name: "Auto" }).click();
- await expect.poll(plate).toBe("rgb(255, 255, 255)");
-});
-
-test("the install pill copies every manager's command", async ({ page, context }) => {
- await context.grantPermissions(["clipboard-read", "clipboard-write"]);
- await page.goto("/");
- const pill = page.locator("[data-install]").first();
- for (const [label, code] of MANAGERS) {
- await expect(pill).toHaveAttribute("data-install", label);
- await expect(pill.locator("code")).toHaveText(code);
- await pill.getByRole("button", { name: "Copy" }).click();
- await expect(pill.getByRole("button", { name: "Copied" })).toBeVisible();
- expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(code);
- await pill.getByRole("button", { name: new RegExp(`^${label}: switch to`) }).click();
- }
- await expect(pill).toHaveAttribute("data-install", "npm");
-});
-
-test("without a clipboard, copy selects the text instead and throws nothing", async ({ page }) => {
- await page.addInitScript(() => {
- Object.defineProperty(navigator, "clipboard", { value: { writeText: () => Promise.reject(new DOMException("denied", "NotAllowedError")) } });
- });
- const noise = watch(page);
- await page.goto("/");
- const pill = page.locator("[data-install]").first();
- await pill.getByRole("button", { name: "Copy" }).click();
- await expect(pill.getByRole("button", { name: "Copy" })).toBeVisible();
- expect(await page.evaluate(() => window.getSelection()?.toString())).toBe("npm i @lucasmarkes/hairline");
-
- const snippet = page.locator("[data-snippet]");
- await snippet.getByRole("button", { name: "Copy" }).click();
- expect(await page.evaluate(() => window.getSelection()?.toString())).toContain("<Terrain />");
- expect(noise).toEqual([]);
-});
-
-test("the quickstart pastes four ways and lists the four options", async ({ page, context }) => {
- await context.grantPermissions(["clipboard-read", "clipboard-write"]);
- await page.goto("/");
- await page.getByRole("link", { name: "Get started" }).click();
- await expect(page).toHaveURL(/#quickstart$/);
- const quick = page.locator("section[aria-labelledby=quickstart]");
- await expect(quick.getByRole("tab")).toHaveText(["React", "Vanilla", "CDN", "CSS"]);
- await quick.getByRole("tab", { name: "CSS" }).click();
- await expect(quick.locator(".code-panel")).toContainText("--hairline-plate: #ffffff;");
- await quick.locator(".code").getByRole("button", { name: "Copy" }).click();
- expect(await page.evaluate(() => navigator.clipboard.readText())).toContain("--hairline-stroke: 0.9;");
- await expect(quick.locator("[data-options] tbody tr td:first-child")).toHaveText(["intensity", "theme", "label", "onRead"]);
-});
-
-test("llms.txt and the registry item are served", async ({ request }) => {
- const llms = await request.get("/llms.txt");
- expect(llms.headers()["content-type"]).toContain("text/plain");
- expect(await llms.text()).toContain("# hairline");
-
- const item = await (await request.get("/r/hairline.json")).json();
- expect(item.name).toBe("hairline");
- expect(item.dependencies).toEqual(["@lucasmarkes/hairline"]);
- expect(item.files[0].path).toBe("components/ui/hairline.tsx");
- expect(item.files[0].content).toContain('"use client"');
-});
-
-test("the page fits a phone, with the longest install command and every control", async ({ page }) => {
- await page.setViewportSize({ width: 390, height: 800 });
- await page.goto("/");
- const width = () => page.evaluate(() => document.documentElement.scrollWidth);
- expect(await width()).toBeLessThanOrEqual(390);
-
- const pill = page.locator("[data-install]").first();
- for (let i = 0; i < 4; i++) await pill.getByRole("button", { name: /: switch to/ }).click();
- await expect(pill).toHaveAttribute("data-install", "shadcn");
- expect(await width()).toBeLessThanOrEqual(390);
-
- const inspector = page.locator("[data-inspector]");
- for (const name of ["Turntable", "Dark"]) {
- const control = inspector.getByRole("button", { name });
- await control.click();
- const box = (await control.boundingBox())!;
- expect(box.x).toBeGreaterThanOrEqual(0);
- expect(box.x + box.width).toBeLessThanOrEqual(390);
- }
- await inspector.getByRole("slider", { name: "intensity" }).fill("0.85");
- await expect(inspector.locator("[data-snippet] .code-panel")).toContainText('<Turntable intensity={0.85} theme="dark" />');
- expect(await width()).toBeLessThanOrEqual(390);
-});
-```
-
-- [ ] **Step 2: Run the site's typecheck to see it fail**
-
-The browser test needs a build, and the build cannot run yet, so the typecheck is this task's red.
-
-Run: `pnpm --filter @hairline/site typecheck`
-Expected: FAIL. Among the errors, all in files this task replaces or deletes:
-- `app/page.tsx`: `error TS2305: Module '"@/lib/figures"' has no exported member 'NOTES'` (and `'SHARED'`), `error TS2724: '"@/lib/figures"' has no exported member named 'rows'`, `error TS2305: Module '"@/lib/highlight"' has no exported member 'LIVE'`, `error TS2339: Property 'range' does not exist on type 'FigureDoc'`, and `error TS2322` for `labels` on `<Riffle>`.
-- `components/figure-demo.tsx`: no exported member `shown` from `@/lib/figures`, and none named `Range` from `@lucasmarkes/hairline`.
-- `components/theme-editor.tsx`: no exported member `themeCss` from `@/lib/snippets`.
-
-`test/site.spec.ts` has no error.
-
-- [ ] **Step 3: Write the copy button and the install pill**
-
-Create `apps/site/components/copy.tsx`. `copy` writes to the clipboard, and when that fails or does not exist it selects the text so the reader can copy it by hand:
-
-`apps/site/components/copy.tsx`
-```tsx
-"use client";
-
-import { useCallback, useEffect, useState, type RefObject } from "react";
-
-/**
- * Copies text, and says so for a moment. Without clipboard permission, or on
- * a page served without a secure context where there is no clipboard at all,
- * it selects the text instead, so the keyboard can copy it.
- */
-export function useCopy(): [copied: boolean, copy: (text: string, fallback?: Element | null) => void] {
- const [copied, setCopied] = useState(false);
-
- useEffect(() => {
- if (!copied) return;
- const timer = setTimeout(() => setCopied(false), 1600);
- return () => clearTimeout(timer);
- }, [copied]);
-
- const copy = useCallback(async (text: string, fallback?: Element | null) => {
- try {
- await navigator.clipboard.writeText(text);
- setCopied(true);
- } catch {
- if (!fallback) return;
- const range = document.createRange();
- range.selectNodeContents(fallback);
- const selection = window.getSelection();
- selection?.removeAllRanges();
- selection?.addRange(range);
- }
- }, []);
-
- return [copied, copy];
-}
-
-/**
- * A button that copies `text`, or selects what `select` points at when it
- * cannot. `text` can be a function, read at the click, for text the button
- * does not own.
- */
-export function CopyButton({ text, select, label = "Copy", className = "copy" }: { text: string | (() => string); select?: RefObject<Element | null>; label?: string; className?: string }) {
- const [copied, copy] = useCopy();
- return (
- <button type="button" className={className} onClick={() => copy(typeof text === "function" ? text() : text, select?.current)} aria-live="polite">
- {copied ? "Copied" : label}
- </button>
- );
-}
-```
-
-Create `apps/site/components/install.tsx`. The manager's name is the button that moves to the next manager; shadcn's shows `npx`:
-
-`apps/site/components/install.tsx`
-```tsx
-"use client";
-
-import { useRef, useState } from "react";
-import { CopyButton } from "./copy";
-
-/**
- * The install command in a pill. The command's first word is a button that
- * moves to the next package manager; the copy button copies the whole line.
- */
-export function Install({ commands }: { commands: { label: string; code: string }[] }) {
- const [at, setAt] = useState(0);
- const line = useRef<HTMLElement>(null);
- const { label, code } = commands[at];
- const head = code.slice(0, code.indexOf(" "));
- const next = commands[(at + 1) % commands.length].label;
-
- return (
- <div className="pill" data-install={label}>
- <span aria-hidden="true" className="select-none text-faint">$</span>
- <code ref={line} className="pill-line">
- <button type="button" className="pill-manager" onClick={() => setAt((at + 1) % commands.length)} aria-label={`${label}: switch to ${next}`} title={`Switch to ${next}`}>
- {head}
- </button>
- {code.slice(head.length)}
- </code>
- <CopyButton text={code} select={line} />
- </div>
- );
-}
-```
-
-Change `apps/site/components/tabs.tsx` to copy through `CopyButton`:
-
-`apps/site/components/tabs.tsx (diff)`
-```diff
---- a/apps/site/components/tabs.tsx
-+++ b/apps/site/components/tabs.tsx
-@@ -1,41 +1,17 @@
- "use client";
-
--import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react";
-+import { useId, useRef, useState, type KeyboardEvent } from "react";
-+import { CopyButton } from "./copy";
-
- export type Tab = { label: string; html: string };
-
--/**
-- * Code behind tabs, with a copy button. The HTML is highlighted at build; when
-- * `live` is given, every span marked data-live shows it, so a snippet follows
-- * a slider without a highlighter in the browser.
-- */
--export function Tabs({ tabs, label, live }: { tabs: Tab[]; label: string; live?: string }) {
-+/** Code behind tabs, with a copy button. The HTML is highlighted at build. */
-+export function Tabs({ tabs, label }: { tabs: Tab[]; label: string }) {
- const [at, setAt] = useState(0);
-- const [copied, setCopied] = useState(false);
- const panel = useRef<HTMLDivElement>(null);
- const list = useRef<HTMLDivElement>(null);
- const id = useId();
-
-- useEffect(() => {
-- if (live === undefined) return;
-- panel.current?.querySelectorAll("[data-live]").forEach((node) => { node.textContent = live; });
-- }, [live, at]);
--
-- useEffect(() => {
-- if (!copied) return;
-- const timer = setTimeout(() => setCopied(false), 1600);
-- return () => clearTimeout(timer);
-- }, [copied]);
--
-- const copy = async () => {
-- try {
-- await navigator.clipboard.writeText(panel.current?.textContent ?? "");
-- setCopied(true);
-- } catch {
-- // no clipboard permission: the text is still selectable
-- }
-- };
--
- const onKeyDown = (event: KeyboardEvent) => {
- const step = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0;
- if (!step) return;
-@@ -55,11 +31,11 @@ export function Tabs({ tabs, label, live }: { tabs: Tab[]; label: string; live?:
- </button>
- ))}
- </div>
-- <button type="button" onClick={copy} className="code-copy" aria-live="polite">
-- {copied ? "Copied" : "Copy"}
-- </button>
-+ {/* read at the click, so it is always the tab on screen */}
-+ <CopyButton text={() => panel.current?.textContent ?? ""} select={panel} />
- </div>
- <div ref={panel} role="tabpanel" id={`${id}-panel`} aria-labelledby={`${id}-tab-${at}`} tabIndex={0} className="code-panel" dangerouslySetInnerHTML={{ __html: tabs[at].html }} />
- </div>
- );
- }
-+
-```
-
-- [ ] **Step 4: Write the inspector**
-
-Create `apps/site/components/inspector.tsx`. It mounts one figure at a time, Terrain first; the chips pick the figure, the slider sets `intensity` from 0 to 1 in steps of 0.05, the switch sets `theme`, and the snippet below is `snippet(name, { intensity, theme })` as plain text:
-
-`apps/site/components/inspector.tsx`
-```tsx
-"use client";
-
-import { useId, useRef, useState } from "react";
-import { Exploded, Phosphor, Riffle, Slow, Terrain, Turntable } from "@lucasmarkes/hairline/react";
-import { FIGURES, type FigureId } from "@/lib/figures";
-import { snippet, type Theme } from "@/lib/snippets";
-import { CopyButton } from "./copy";
-
-const COMPONENTS = { riffle: Riffle, terrain: Terrain, exploded: Exploded, phosphor: Phosphor, slow: Slow, turntable: Turntable };
-const THEMES: { value: Theme; label: string }[] = [
- { value: "auto", label: "Auto" },
- { value: "light", label: "Light" },
- { value: "dark", label: "Dark" },
-];
-
-/**
- * One large figure and its three controls: which figure, how intense, which
- * theme. The snippet under them is the code for what is on screen.
- */
-export function Inspector() {
- const [id, setId] = useState<FigureId>("terrain");
- const [intensity, setIntensity] = useState(0.5);
- const [theme, setTheme] = useState<Theme>("auto");
- const [read, setRead] = useState("");
- const slider = useId();
- const code = useRef<HTMLPreElement>(null);
- const doc = FIGURES.find((f) => f.id === id)!;
- const Figure = COMPONENTS[id];
- const text = snippet(doc.name, { intensity, theme });
-
- return (
- <div className="panel grid gap-px md:grid-cols-[3fr_2fr] [&>*]:min-w-0" data-inspector>
- <div className="stage" data-figure={id} data-dark={theme === "dark" || undefined}>
- <Figure key={id} intensity={intensity} theme={theme} onRead={setRead} />
- <span className="cap" data-read aria-hidden="true">{read}</span>
- </div>
- <div className="grid content-start gap-7 bg-white p-6">
- <fieldset>
- <legend className="label">Figure</legend>
- <div className="flex flex-wrap gap-1.5">
- {FIGURES.map((f) => (
- <button key={f.id} type="button" className="chip" aria-pressed={f.id === id} onClick={() => { setId(f.id); setRead(""); }}>
- {f.name}
- </button>
- ))}
- </div>
- </fieldset>
- <div>
- <div className="flex items-baseline justify-between">
- <label htmlFor={slider} className="label">intensity</label>
- <output htmlFor={slider} className="font-mono text-[12px] tabular-nums text-muted">{intensity.toFixed(2)}</output>
- </div>
- <input id={slider} type="range" className="slider" min={0} max={1} step={0.05} value={intensity} onChange={(event) => setIntensity(Number(event.target.value))} />
- <p className="mt-2 text-[13px] leading-[1.5] text-muted">{doc.stronger}</p>
- </div>
- <fieldset>
- <legend className="label">theme</legend>
- <div className="segmented">
- {THEMES.map((t) => (
- <button key={t.value} type="button" aria-pressed={t.value === theme} onClick={() => setTheme(t.value)}>
- {t.label}
- </button>
- ))}
- </div>
- </fieldset>
- </div>
- <div className="code md:col-span-2" data-snippet>
- <div className="code-bar">
- <span className="code-tab" aria-selected="true">React</span>
- <CopyButton text={text} select={code} />
- </div>
- <pre ref={code} className="code-panel">{text}</pre>
- </div>
- </div>
- );
-}
-```
-
-- [ ] **Step 5: Remove the old components**
-
-```bash
-git rm apps/site/components/tile.tsx apps/site/components/figure-demo.tsx apps/site/components/theme-editor.tsx
-```
-
-- [ ] **Step 6: Write the page, the layout, the styles and the OG page**
-
-Replace `apps/site/app/page.tsx`:
-
-`apps/site/app/page.tsx`
-```tsx
-import pkg from "@lucasmarkes/hairline/package.json";
-import { Exploded, Phosphor, Riffle, Slow, Terrain, Turntable } from "@lucasmarkes/hairline/react";
-import { CopyButton } from "@/components/copy";
-import { Inspector } from "@/components/inspector";
-import { Install } from "@/components/install";
-import { Tabs } from "@/components/tabs";
-import { CARDS, FIGURES, LINKS, OPTIONS } from "@/lib/figures";
-import { highlight } from "@/lib/highlight";
-import { tiny } from "@/lib/size";
-import { PASTE, install } from "@/lib/snippets";
-
-const SITE = process.env.NEXT_PUBLIC_SITE_URL!;
-const SMALL = { riffle: Riffle, terrain: Terrain, exploded: Exploded, phosphor: Phosphor, slow: Slow, turntable: Turntable };
-
-function GitHub() {
- return (
- <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" fill="currentColor">
- <path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z" />
- </svg>
- );
-}
-
-function Heading({ id, title, children }: { id: string; title: React.ReactNode; children?: React.ReactNode }) {
- return (
- <header className="mb-10 max-w-[56ch]">
- <h2 id={id} className="scroll-mt-20 text-[30px] font-medium leading-[1.1] tracking-[-0.03em] md:text-[36px]">{title}</h2>
- {children ? <p className="mt-3 text-[16px] leading-[1.55] text-muted">{children}</p> : null}
- </header>
- );
-}
-
-/**
- * The whole site. A Server Component: every figure on it is the package's
- * React component rendered from here, so every deploy runs them through
- * server rendering and hydration.
- */
-export default async function Page() {
- const commands = install(SITE);
- const paste = await Promise.all(PASTE.map(async (p) => ({ label: p.label, html: await highlight(p.code, p.lang) })));
- const size = tiny();
-
- return (
- <>
- <header className="topbar">
- <a href="#top" className="text-[15px] font-medium tracking-[-0.02em]">hairline</a>
- <nav className="flex items-center gap-1">
- <span className="px-2 font-mono text-[12px] text-muted" data-version>v{pkg.version}</span>
- <a className="icon-link" href={LINKS.github} aria-label="GitHub"><GitHub /></a>
- <CopyButton text={`${SITE}/llms.txt`} label="llms.txt" className="btn btn-quiet" />
- </nav>
- </header>
-
- <main id="top" className="mx-auto grid max-w-[1080px] gap-32 px-[clamp(18px,5vw,28px)] pb-24 pt-16 md:pt-24 [&>*]:min-w-0">
- <section aria-labelledby="hairline" className="grid grid-cols-[minmax(0,1fr)] justify-items-center text-center">
- <h1 id="hairline" className="max-w-[16ch] text-[44px] font-medium leading-[1.02] tracking-[-0.045em] md:text-[64px]">
- Line drawings that <em className="font-serif text-[1.08em] font-normal tracking-[-0.02em]">answer</em> the pointer.
- </h1>
- <p className="mt-5 max-w-[44ch] text-[18px] leading-[1.5] text-muted">
- Six isometric figures for the web. SVG, no dependencies, React or plain DOM.
- </p>
- <div className="mt-9 w-full max-w-[460px]"><Install commands={commands} /></div>
- <div className="mt-5 flex gap-2">
- <a className="btn btn-primary" href="#quickstart">Get started</a>
- <a className="btn" href={LINKS.github}><GitHub /> GitHub</a>
- </div>
- </section>
-
- <section aria-label="Try it">
- <Inspector />
- </section>
-
- <section aria-labelledby="figures">
- <Heading id="figures" title="One prop, six figures">
- Every figure takes <code className="font-mono text-[14px] text-ink">intensity</code>, from 0 to 1. Here is what it turns up.
- </Heading>
- <ul className="grid">
- {FIGURES.map((doc) => {
- const Small = SMALL[doc.id];
- return (
- <li key={doc.id} className="figure-row" data-row={doc.id}>
- <div>
- <h3 className="font-serif text-[30px] leading-none">{doc.name}</h3>
- <p className="mt-3 text-[16px] leading-[1.5]">{doc.stronger}</p>
- <p className="mt-1 max-w-[52ch] text-[14px] leading-[1.55] text-muted">{doc.summary}</p>
- </div>
- <div className="tile w-full max-w-[240px] justify-self-end"><Small /></div>
- </li>
- );
- })}
- </ul>
- </section>
-
- <section aria-label="Why" className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
- {CARDS.map((card) => (
- <div key={card.title} className="card" data-card={card.title}>
- <h3 className="text-[15px] font-medium">{card.title}</h3>
- {card.title === "Tiny" ? <p className="mt-3 font-serif text-[34px] leading-none" data-size>{size}</p> : null}
- <p className="mt-2 text-[14px] leading-[1.5] text-muted">{card.body}</p>
- </div>
- ))}
- </section>
-
- <section aria-labelledby="quickstart">
- <Heading id="quickstart" title={<>Two <em className="font-serif font-normal">steps</em></>} />
- <ol className="grid gap-12">
- <li className="step">
- <h3 className="step-title"><span className="step-n">1</span>Install</h3>
- <div className="max-w-[460px]"><Install commands={commands} /></div>
- </li>
- <li className="step">
- <h3 className="step-title"><span className="step-n">2</span>Paste</h3>
- <p className="mb-4 max-w-[60ch] text-[14px] leading-[1.55] text-muted">
- A figure fills its parent&rsquo;s width at a 5:4 aspect ratio. The React entry is a client module, so a Server Component can render it as it is.
- </p>
- <Tabs tabs={paste} label="Paste" />
- </li>
- </ol>
- <div className="mt-14 overflow-x-auto">
- <table className="props" data-options>
- <thead>
- <tr><th>Option</th><th>Type</th><th>Default</th><th>What it does</th></tr>
- </thead>
- <tbody>
- {OPTIONS.map((row) => (
- <tr key={row.name}><td>{row.name}</td><td>{row.type}</td><td>{row.default}</td><td>{row.description}</td></tr>
- ))}
- </tbody>
- </table>
- </div>
- </section>
-
- <footer className="flex flex-wrap items-baseline gap-x-6 gap-y-3 border-t border-line pt-8 text-[13px] text-muted">
- <p>
- MIT licensed. Built by Lucas Marques. After <a className="text-ink" href={LINKS.linear}>Linear</a>&rsquo;s figures.
- </p>
- <nav className="flex gap-5 md:ml-auto">
- <a className="text-ink" href={LINKS.npm}>npm</a>
- <a className="text-ink" href={LINKS.github}>GitHub</a>
- <a className="text-ink" href="/llms.txt">llms.txt</a>
- <a className="text-ink" href={LINKS.essay}>The essay</a>
- </nav>
- </footer>
- </main>
- </>
- );
-}
-```
-
-In `apps/site/app/layout.tsx`, load Instrument Serif for the headline's one italic word, and describe the new card in the Open Graph alt:
-
-`apps/site/app/layout.tsx (diff)`
-```diff
---- a/apps/site/app/layout.tsx
-+++ b/apps/site/app/layout.tsx
-@@ -2,9 +2,13 @@ import type { Metadata } from "next";
- import type { ReactNode } from "react";
- import { GeistMono } from "geist/font/mono";
- import { GeistSans } from "geist/font/sans";
-+import { Instrument_Serif } from "next/font/google";
- import { Analytics } from "@vercel/analytics/next";
- import "./globals.css";
-
-+/** The headline's one serif word, and the figure names. */
-+const serif = Instrument_Serif({ weight: "400", style: ["normal", "italic"], subsets: ["latin"], variable: "--font-instrument-serif" });
-+
- const SITE = process.env.NEXT_PUBLIC_SITE_URL!;
- const DESCRIPTION = "Six isometric line figures that answer the pointer. SVG, no dependencies, for React and for everything else.";
-
-@@ -13,14 +17,14 @@ export const metadata: Metadata = {
- title: "hairline",
- description: DESCRIPTION,
- alternates: { canonical: "/" },
-- openGraph: { title: "hairline", description: DESCRIPTION, url: "/", siteName: "hairline", type: "website", images: [{ url: "/og.png", width: 1200, height: 630, alt: "The six hairline figures on a board." }] },
-+ openGraph: { title: "hairline", description: DESCRIPTION, url: "/", siteName: "hairline", type: "website", images: [{ url: "/og.png", width: 1200, height: 630, alt: "Line drawings that answer the pointer: the Terrain figure, its pillars rising." }] },
- twitter: { card: "summary_large_image", title: "hairline", description: DESCRIPTION, images: ["/og.png"], creator: "@lucasmarkes" },
- icons: { icon: "/icon.svg" },
- };
-
- export default function RootLayout({ children }: { children: ReactNode }) {
- return (
-- <html lang="en" className={`${GeistSans.variable} ${GeistMono.variable}`}>
-+ <html lang="en" className={`${GeistSans.variable} ${GeistMono.variable} ${serif.variable}`}>
- <body className="font-sans antialiased">
- {children}
- <Analytics />
-```
-
-Replace `apps/site/app/globals.css`. The hero's grid column and every step are `minmax(0, 1fr)` and `min-width: 0`, so the shadcn command scrolls inside its pill instead of widening a phone's page, and under 640 px the options table stacks one option per block:
-
-`apps/site/app/globals.css`
-```css
-@import "tailwindcss";
-
-/* After cuelume: a light canvas, white panels with a soft lift, one serif accent, mono for code. */
-@theme {
- --font-sans: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
- --font-mono: var(--font-geist-mono), ui-monospace, "SF Mono", Menlo, monospace;
- --font-serif: var(--font-instrument-serif), Georgia, serif;
- --color-canvas: #fbfaf9;
- --color-stone: #f2f0ed;
- --color-ink: #121212;
- --color-muted: #7e7e7d;
- --color-faint: #a9a7a3;
- --color-line: rgba(18, 18, 18, 0.07);
-}
-
-:root {
- --lift: 0 1px 2px #12121208, 0 10px 28px -16px #12121224;
- --lift-lg: 0 1px 2px #12121208, 0 2px 6px #12121208, 0 32px 64px -34px #12121238;
-}
-
-html { color-scheme: light; scroll-behavior: smooth; }
-body { min-height: 100vh; color: var(--color-ink); background: var(--color-canvas); }
-em { font-style: italic; }
-
-.topbar {
- position: sticky; top: 0; z-index: 10;
- display: flex; align-items: center; justify-content: space-between;
- padding: 12px clamp(18px, 5vw, 28px);
- background: color-mix(in srgb, var(--color-canvas) 82%, transparent);
- backdrop-filter: blur(12px);
-}
-
-.btn {
- display: inline-flex; align-items: center; gap: 8px; height: 36px; padding: 0 14px;
- border-radius: 9px; font-size: 14px; font-weight: 500;
- background: #fff; box-shadow: inset 0 0 0 1px var(--color-stone), var(--lift);
-}
-.btn-primary { background: var(--color-ink); color: #fff; box-shadow: var(--lift); }
-.btn-quiet { height: 30px; padding: 0 10px; font: 500 12px/1 var(--font-mono); color: var(--color-muted); }
-.btn-quiet:hover, .icon-link:hover { color: var(--color-ink); }
-.icon-link { display: inline-grid; place-items: center; width: 30px; height: 30px; border-radius: 8px; color: var(--color-muted); }
-
-.pill {
- display: flex; align-items: center; gap: 10px; height: 48px; padding: 0 6px 0 16px;
- border-radius: 12px; background: #fff; box-shadow: inset 0 0 0 1px var(--color-stone), var(--lift);
- font: 400 14px/1 var(--font-mono); text-align: left;
-}
-.pill-line { flex: 1; min-width: 0; overflow-x: auto; white-space: nowrap; scrollbar-width: none; }
-.pill-line::-webkit-scrollbar { display: none; }
-.pill-manager { border-radius: 5px; padding: 3px 4px; margin: -3px -4px; color: var(--color-ink); text-decoration: underline dotted var(--color-faint); text-underline-offset: 4px; cursor: pointer; }
-.pill-manager:hover { background: var(--color-stone); }
-
-.copy { flex: none; border-radius: 7px; padding: 7px 10px; font: 500 12px/1 var(--font-mono); color: var(--color-muted); }
-.copy:hover { color: var(--color-ink); background: var(--color-stone); }
-
-.panel { overflow: hidden; border-radius: 16px; background: var(--color-stone); box-shadow: inset 0 0 0 1px var(--color-stone), var(--lift-lg); }
-.stage { position: relative; display: grid; place-items: center; padding: clamp(12px, 4vw, 40px); background: #fff; }
-.stage > [data-hairline] { width: 100%; max-width: 520px; }
-.stage[data-dark] { background: #08090a; }
-.cap { position: absolute; left: 18px; bottom: 14px; font: 500 11px/1 var(--font-mono); letter-spacing: 0.02em; color: var(--hairline-edge, #a4a4ac); font-variant-numeric: tabular-nums; pointer-events: none; }
-.stage[data-dark] .cap { color: #5b5d64; }
-
-.label { display: block; margin-bottom: 10px; font: 500 11px/1 var(--font-mono); letter-spacing: 0.04em; text-transform: uppercase; color: var(--color-muted); }
-.chip { border-radius: 8px; padding: 7px 11px; font-size: 13px; color: var(--color-muted); box-shadow: inset 0 0 0 1px var(--color-stone); }
-.chip:hover { color: var(--color-ink); }
-.chip[aria-pressed="true"] { background: var(--color-ink); color: #fff; box-shadow: none; }
-.segmented { display: inline-flex; padding: 2px; border-radius: 9px; background: var(--color-stone); }
-.segmented button { border-radius: 7px; padding: 6px 12px; font-size: 13px; color: var(--color-muted); }
-.segmented button[aria-pressed="true"] { background: #fff; color: var(--color-ink); box-shadow: var(--lift); }
-
-.slider { width: 100%; height: 18px; appearance: none; background: transparent; cursor: pointer; }
-.slider::-webkit-slider-runnable-track { height: 2px; border-radius: 1px; background: rgba(18, 18, 18, 0.16); }
-.slider::-webkit-slider-thumb { appearance: none; width: 16px; height: 16px; margin-top: -7px; border-radius: 50%; background: #fff; box-shadow: 0 0 0 1px rgba(18, 18, 18, 0.2), var(--lift); }
-.slider::-moz-range-track { height: 2px; border-radius: 1px; background: rgba(18, 18, 18, 0.16); }
-.slider::-moz-range-thumb { width: 16px; height: 16px; border: 0; border-radius: 50%; background: #fff; box-shadow: 0 0 0 1px rgba(18, 18, 18, 0.2); }
-
-.code { overflow: hidden; border-radius: 12px; background: #fff; box-shadow: inset 0 0 0 1px var(--color-stone); }
-.panel .code { border-radius: 0; box-shadow: none; }
-.code-bar { display: flex; align-items: center; justify-content: space-between; padding: 6px 6px 6px 8px; border-bottom: 1px solid var(--color-line); }
-.code-tab { border-radius: 7px; padding: 6px 10px; font: 500 12px/1 var(--font-mono); color: var(--color-muted); }
-.code-tab[aria-selected="true"] { background: var(--color-stone); color: var(--color-ink); }
-.code-tab:hover { color: var(--color-ink); }
-.code-panel { margin: 0; overflow-x: auto; padding: 16px 18px; font: 400 13px/1.65 var(--font-mono); }
-.code-panel pre { margin: 0; background: transparent !important; }
-.code-panel code { font: inherit; }
-
-.tile { overflow: hidden; border-radius: 14px; background: #fff; box-shadow: inset 0 0 0 1px var(--color-stone), var(--lift); }
-.figure-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(120px, 240px); align-items: center; gap: 24px; padding: 28px 0; border-top: 1px solid var(--color-line); }
-.figure-row:last-child { border-bottom: 1px solid var(--color-line); }
-.card { border-radius: 14px; padding: 20px; background: #fff; box-shadow: inset 0 0 0 1px var(--color-stone); }
-
-.step { min-width: 0; }
-.step-title { display: flex; align-items: center; gap: 12px; margin-bottom: 16px; font-size: 17px; font-weight: 500; }
-.step-n { display: inline-grid; place-items: center; width: 24px; height: 24px; border-radius: 50%; background: var(--color-ink); color: #fff; font: 500 12px/1 var(--font-mono); }
-
-.props { width: 100%; border-collapse: collapse; font-size: 13px; }
-.props th { padding: 8px 14px 8px 0; text-align: left; font: 500 11px/1 var(--font-mono); letter-spacing: 0.04em; text-transform: uppercase; color: var(--color-muted); }
-.props td { padding: 12px 14px 12px 0; vertical-align: top; border-top: 1px solid var(--color-line); line-height: 1.5; }
-.props td:nth-child(-n + 3) { font-family: var(--font-mono); white-space: nowrap; }
-.props td:nth-child(2), .props td:nth-child(3) { color: var(--color-muted); }
-
-:is(button, a, input, .code-panel):focus-visible { outline: 1.5px solid var(--color-ink); outline-offset: 2px; }
-
-@media (max-width: 640px) {
- .figure-row { grid-template-columns: minmax(0, 1fr) 120px; gap: 16px; }
- /* one option per block: name, type and default on a line, the description under them */
- .props thead { display: none; }
- .props tr { display: flex; flex-wrap: wrap; column-gap: 12px; padding: 14px 0; border-top: 1px solid var(--color-line); }
- .props td { padding: 0; border: 0; }
- .props td:nth-child(4) { flex-basis: 100%; margin-top: 6px; }
-}
-@media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } }
-```
-
-Replace `apps/site/app/og/page.tsx`, which imported the deleted `Tile`, with the headline and one Terrain:
-
-`apps/site/app/og/page.tsx`
-```tsx
-import type { Metadata } from "next";
-import { Terrain } from "@lucasmarkes/hairline/react";
-
-/** The Open Graph card, as a page: scripts/og.mjs photographs it at 1200 × 630 into public/og.png. */
-export const metadata: Metadata = { robots: { index: false } };
-
-export default function Og() {
- return (
- <main className="flex h-[630px] w-[1200px] items-center gap-16 overflow-hidden px-20">
- <div className="w-[470px] shrink-0">
- <h1 className="text-[64px] font-medium leading-[1.02] tracking-[-0.045em]">
- Line drawings that <em className="font-serif text-[1.08em] font-normal tracking-[-0.02em]">answer</em> the pointer.
- </h1>
- <p className="mt-8 font-mono text-[18px] text-muted">npm i @lucasmarkes/hairline</p>
- </div>
- <div className="tile flex-1 p-6"><Terrain /></div>
- </main>
- );
-}
-```
-
-- [ ] **Step 7: Run the site's gates to see them pass**
-
-Run: `pnpm --filter @hairline/site typecheck && pnpm --filter @hairline/site test`
-Expected: PASS. `tsc --noEmit` prints nothing, and `Tests 22 passed (22)`.
-
-Run: `pnpm build && pnpm --filter @hairline/site test:browser`
-Expected: the build ends with `/`, `/og` and `/llms.txt` prerendered as static (○), then `9 passed`.
-
-Run: `pnpm typecheck && pnpm test`
-Expected: every turbo task succeeds, with `Tests 93 passed (93)` for the package and `Tests 22 passed (22)` for the site.
-
-Open `http://localhost:3000` after `pnpm --filter @hairline/site start` and look once at 1200 px and at 390 px (devtools): the install pill is the first thing under the headline, no tile says "Fig.", and Riffle's cards carry no names.
-
-- [ ] **Step 8: Commit**
-
-```bash
-git add apps/site/app apps/site/components apps/site/test/site.spec.ts
-git commit -m "Site: install first, a live inspector, and the figures without numbers
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-### Task 7: The Open Graph card, and the preview
-
-**Files:**
-- Modify: `scripts/og.mjs` (wait for one figure, not six)
-- Modify: `apps/site/public/og.png` (photographed again)
-
-**Interfaces:**
-- Consumes from Task 6: the `/og` page (the headline and one Terrain) and the Open Graph alt in `app/layout.tsx`.
-- Produces: the pushed branch `site-on-vercel`, its Vercel preview, and the address Lucas reviews. After their approval the base plan resumes at Task 14 Step 7.
-
-The card's script waited for six figures to draw, and the card has one now.
-
-- [ ] **Step 1: Wait for the one figure**
-
-`scripts/og.mjs (diff)`
-```diff
---- a/scripts/og.mjs
-+++ b/scripts/og.mjs
-@@ -24,8 +24,8 @@ try {
- await browser.close();
- process.exit(1);
- }
--await page.waitForFunction(() => document.querySelectorAll("[data-hairline] > svg > *").length >= 6 && document.fonts.status === "loaded");
--// Phosphor and Slow play on their own: give them a moment to be mid-loop.
-+await page.waitForFunction(() => document.querySelectorAll("[data-hairline] > svg > *").length >= 1 && document.fonts.status === "loaded");
-+// let the figure finish its first frames
- await page.waitForTimeout(1200);
- const out = join(SITE, "public/og.png");
- await page.screenshot({ path: out, clip: { x: 0, y: 0, width: 1200, height: 630 } });
-```
-
-- [ ] **Step 2: Photograph the card**
-
-Run, in one terminal: `pnpm build && pnpm --filter @hairline/site start`
-Run, in another: `node scripts/og.mjs`
-Expected: `wrote …/apps/site/public/og.png`, exit code 0. Stop the server afterwards.
-
-Open `apps/site/public/og.png`: 2400 × 1260 (1200 × 630 at twice the density), the headline "Line drawings that *answer* the pointer." with "answer" in Instrument Serif italic, `npm i @lucasmarkes/hairline` under it, and Terrain's grid on the right. No "Fig." and no six tiles.
-
-- [ ] **Step 3: Run every gate once more**
-
-Run: `pnpm typecheck && pnpm test && pnpm build && pnpm test:browser`
-Expected: every turbo task succeeds: `Tests 93 passed (93)` and `Tests 22 passed (22)`, then `19 passed` for the package and `9 passed` for the site.
-
-Run: `node scripts/consumers.mjs`
-Expected: `Both consumers install, build and draw.`
-
-- [ ] **Step 4: Commit**
-
-```bash
-git add scripts/og.mjs apps/site/public/og.png
-git commit -m "OG card: the headline and one figure, photographed again
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-- [ ] **Step 5: Push and watch the checks**
-
-```bash
-git push origin site-on-vercel
-gh pr checks 1 --watch
-```
-
-Expected: every check on PR #1 passes, the Vercel preview among them.
-
-- [ ] **Step 6: Check the preview**
-
-Run: `vercel ls hairline --scope lucasmarkes-team-projects | head -5`
-Expected: the newest row is a Preview deployment in state `● Ready`. Its URL is `PREVIEW` below.
-
-Previews are protected, so read them through the CLI, which bypasses the protection:
-
-Run: `vercel curl /llms.txt --deployment PREVIEW | head -3`
-Expected: `# hairline`, a blank line, then the summary ending `Every figure takes the same four options.`
-
-Run: `vercel curl /r/hairline.json --deployment PREVIEW | grep -o '"docs":"[^"]*"'`
-Expected: `"docs":"Docs: https://` followed by the preview's own host. A host of `localhost:3000` means the build did not see `VERCEL_URL` (see `scripts/base-url.mjs`).
-
-Run: `vercel curl / --deployment PREVIEW | grep -o '<meta property="og:image"[^>]*>'`
-Expected: one tag whose `content` is the preview's own `https://` address ending `/og.png`.
-
-- [ ] **Step 7: Ask Lucas to review the preview**
-
-Send Lucas `PREVIEW` and ask them to look at it on a laptop and on a phone: the install pill first, the inspector (chips, slider, theme, snippet), the six figures with no "Fig. N", Riffle with no names, and the options table. Their changes go back through the task that owns the code. When they approve, the base plan resumes at Task 14 Step 7, where Lucas merges PR #1 themselves. When it reaches Task 15, the 0.1.0 changelog entry describes this API: one `intensity` option for all six figures, no per-figure options, and no `ranges` export.
diff --git a/docs/superpowers/plans/2026-10-01-hairline-package.md b/docs/superpowers/plans/2026-10-01-hairline-package.md
deleted file mode 100644
index e8e4530..0000000
--- a/docs/superpowers/plans/2026-10-01-hairline-package.md
+++ /dev/null
@@ -1,6187 +0,0 @@
-# hairline Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** Ship the six Hairline figures as `@lucasmarkes/[email protected]` on npm (vanilla and React entries, with provenance), with a site at `hairline.lucasmarkes.com` that shows and documents every figure.
-
-**Architecture:** The website's figure engines are copied into `packages/hairline/src` as they are, with one small patch, and a thin public layer wraps them: `mount.ts` creates and destroys a figure on any element, `index.ts` has one function per figure, and `react.tsx` has one component per figure. Parity tests replay fixed pointer scripts on the package under a virtual clock. Each must produce the SVG that the website produces, character for character, against goldens captured from the website before any engine moves. A Next.js site in `apps/site` consumes the package through its public entries. It also serves a shadcn registry item and `/llms.txt`.
-
-**Tech Stack:**
-- Repository: pnpm 10 workspaces, Turborepo 2, TypeScript 5.9 (strict), Node 22.
-- Package: tsup 8 (ESM only, es2020); Vitest 5 on node and jsdom; Playwright 1.63 on the installed Chrome; esbuild for the test harness.
-- Package gates: publint, `@arethetypeswrong/cli`, size-limit.
-- Site: Next.js 16 App Router, React 19, Tailwind 4, Geist, Shiki 4 (at build time only), Vercel Analytics.
-- Publishing: GitHub Actions with npm provenance; Vercel.
-
-**Spec:** `docs/superpowers/specs/2026-10-01-hairline-package-design.md`. Read it before Task 1. Where this plan and the spec disagree, the plan says so under "Deviations from the spec".
-
-## Global Constraints
-
-**Package**
-- The name is `@lucasmarkes/hairline`. It is one package with two entries: `.` (vanilla) and `./react`.
-- v1 covers six figures: Riffle, Terrain, Exploded, Phosphor, Slow, Turntable. The maths and the frame loop stay private.
-- A figure draws only the drawing: no frame, no corner text, no slider.
-- Build: ESM only, `target: es2020`, declarations, source maps, `"sideEffects": false`.
-- Dependencies: none. `react >=18` is an optional peer dependency.
-- Licence: MIT. TypeScript strict. English in code, docs and site.
-
-**Options**
-
-| Figure | Option | Range | Default |
-| --- | --- | --- | --- |
-| Riffle | `stagger` | 0–90 ms | 40 |
-| Riffle | `bands` | boolean | `false` |
-| Riffle | `labels` | up to 8 strings | none |
-| Terrain | `radius` | 1.5–5 cells | 3 |
-| Exploded | `gap` | 12–40 | 28 |
-| Phosphor | `afterglow` | 150–1500 ms | 520 |
-| Slow | `rate` | 0.05–0.6 | 0.2 |
-| Turntable | `coast` | 200–1500 ms | 650 |
-
-A number outside its range is clamped.
-
-**Theme**
-- Six custom properties: `--hairline-plate`, `--hairline-hi`, `--hairline-edge`, `--hairline-mid`, `--hairline-lo`, `--hairline-stroke`.
-
- | | plate | hi | edge | mid | lo | stroke |
- | --- | --- | --- | --- | --- | --- | --- |
- | Light | `#ffffff` | `#232327` | `#a4a4ac` | `#c3c3c9` | `#e0e0e4` | `0.9` |
- | Dark | `#08090a` | `#d0d6e0` | `#5b5d64` | `#3e3e44` | `#29292d` | `0.9` |
-
-- The palette is chosen in this order, first match wins:
- 1. The `theme` option.
- 2. An ancestor with class `dark` or `data-theme="dark"`.
- 3. The page's `color-scheme`, through `light-dark()`.
- 4. Light.
-- Every selector is wrapped in `:where()`. Styles are injected through `adoptedStyleSheets`, with a `<style>` element as the fallback.
-
-**Public API (semver)**
-- The exports of both entries, the six custom properties, and the `data-hairline` and `data-hairline-theme` attributes.
-
-**Sources and naming**
-- Port from the website's `main` at `edfebe9`. `lucasmarkes.com/lab/hairline` is not changed.
-- Repository: `lucasmarkes/hairline`. Site: `hairline.lucasmarkes.com`. Vercel project: `hairline`, in the same team as motes (`lucasmarkes-team-projects`), with root directory `apps/site`.
-
-**Process**
-- **confirm** marks a step that is public or hard to undo. Stop and wait for Lucas before running it. Lucas creates the npm token themselves.
-- Every commit message ends with `Co-Authored-By: Claude <[email protected]>`.
-
-**Repository and tools**
-- The repository is `~/estudos/hairline`. It already holds the spec (`cf059dc`) on `main`. Tasks commit on `main`: the repository is new and private until Task 16.
-- Tools: Node 22, pnpm 10.20.0 through Corepack (`corepack enable`), Google Chrome installed (Playwright uses `channel: "chrome"`), `gh` and `vercel` logged in, and `ffmpeg` (used in Task 9 only).
-
-## Review Focus
-
-These are the inputs most likely to break a figure for someone using it. The spec implies them but does not test them. Each line names the test that pins it and the task that owns that test.
-
-1. **The host element already has `role`, `aria-label`, `tabindex` or `aria-labelledby`.** The mount never overwrites them, never names an element that `aria-labelledby` names, drops its own name when `aria-labelledby` appears later, and restores nothing it did not set. Task 6, `mount.test.ts`, the tests "leaves the host's own attributes alone, at mount and at destroy", "does not name an element that aria-labelledby already names" and "drops its own name when the element gains aria-labelledby".
-2. **The consumer's `onRead` throws.** The error is reported as uncaught, and every figure on the page keeps running, because they share one frame loop. Task 6, `mount.test.ts`, "reports an onRead that throws and keeps every figure running".
-3. **A handle is used after its figure is gone.** This covers `update` after `destroy`, `destroy` twice, and an old handle after a second figure took the element. Each is a no-op that never touches the new figure. Task 6, `mount.test.ts`, the "teardown" block.
-4. **React props that are new on every render.** An inline `onRead`, an inline `labels` array, or a state setter called from `onRead` must cause no remount and no render loop. Task 8, `react.test.tsx`, "does not remount, and does not loop, on an inline onRead and inline labels" and "calls a state setter from onRead without looping".
-5. **A figure mounted inside a shadow root, or on an element not yet in the document.** The stylesheet lands in the shadow root and nowhere else. A detached element is drawn and styled once it is attached. Task 7, `figures.spec.ts`, "a figure in a shadow root is styled there, and only there" and "a figure mounted on a detached element is drawn and styled once attached".
-
-## Phases and tasks
-
-| Spec phase | Tasks | Exit criterion, and where it is met |
-| --- | --- | --- |
-| 0 Repository, tooling, CI | 1, 2 | Build, typecheck and test pass on an empty package, locally (Task 1) and in CI (Task 2). |
-| 1 Goldens, port | 3, 4 | Parity for six figures: Task 7. |
-| 2 Public API | 5–8 | Layers 2–5: Tasks 4–8. |
-| 3 Gates, consumer fixtures | 9–11 | `release --static` (Task 9) and layer 6 locally (Task 11). |
-| 4 Site, Vercel | 12–14 | Lucas reviews a Vercel preview (Task 14). |
-| 5 Registry, llms.txt, docs | 1, 9, 10–12, 15 | The registry JSON validates (Task 10), and the item builds in `fixtures/next-app` (Task 11). |
-| 6 Launch | 15, 16 | The launch checklist is complete (Task 16). |
-
-### Deviations from the spec
-
-- **Parity is checked in Task 7, not right after the port (Task 4).** The parity test mounts each figure through the public `mount` layer (Tasks 5–6) and serves the package through the browser harness (Task 7). Writing a throwaway harness only to check parity two tasks early would test code that is then deleted. Task 4 is gated by the geometry tests and the typecheck instead.
-- **The capture script lives at `packages/hairline/test/parity/capture.mjs`,** next to the clock, the driver and the scripts it shares with the parity test. The spec puts it at `scripts/capture-golden.mjs`. Run it with `pnpm -C packages/hairline capture <commit>`.
-- **Some phase 5 items move earlier.** The registry item (Task 10) comes before the site, because the site's build and the Next.js fixture both use it. LICENSE is written in Task 1, and README and CONTRIBUTING in Task 9 (the release gate checks the README).
-- **Files the spec does not name:**
- - `scripts/consumers.mjs` (layer 6, and called by the release gate).
- - `.github/workflows/consumers.yml` (layer 6 on pull requests that touch what ships).
- - `scripts/changelog.mjs` (the GitHub Release notes).
- - `registry/validate.mjs` (the shadcn schema check).
-
-### Trade-offs, recorded here so a reviewer does not reopen them
-
-- **The React `<div>` carries `aspect-ratio: 5 / 4` inline.** A `style` prop overrides it; a class cannot. The README says so.
-- **`react.d.ts` inlines the option types** instead of importing them from the core entry. tsup's declaration build does this, and `attw` accepts it.
-- **The theme editor's presets on the site copy the package's palettes by hand.** The palettes are not public API.
-- **The site is light only.** It shows dark figures inside the theme editor.
-
-## File map
-
-```
-package.json, pnpm-workspace.yaml, turbo.json, tsconfig.base.json, .npmrc, .gitignore T1
-LICENSE, README.md (stub T1, real T9), CONTRIBUTING.md T9, CHANGELOG.md T15, assets/hero.gif T9
-.github/workflows/ci.yml T1, extended in T7 and T9
-.github/workflows/consumers.yml T11
-.github/workflows/publish.yml T15
-packages/hairline/
- package.json, tsconfig.json, tsup.config.ts, vitest.config.ts T1 (test script T4, tsup final T8)
- src/core/iso.ts, motion.ts T4: the engines' maths and springs (copied)
- src/core/stage.ts T4: svg helpers, frame loop, pointer (copied + patch)
- src/figures/*.ts T4: six engines, two geometry modules (copied, riffle patched)
- src/ranges.ts T5: option bounds and the clamp
- src/core/styles.ts T6: the stylesheet and its injection
- src/mount.ts T6: create/update/destroy around any engine
- src/index.ts T6: entry ".": six functions and the option types
- src/react.tsx T8: entry "./react": six components
- test/parity/ T3: clock.js, driver.mjs, scripts.mjs, capture.mjs, golden/*.json
- test/geometry.test.ts T4 test/ranges.test.ts T5
- test/dom.ts, test/mount.test.ts T6 test/react.test.tsx, ssr.test.tsx, types.test-d.tsx T8
- test/browser/ T7: serve.mjs, harness.html, entry.ts, parity/figures/theme specs
- playwright.config.ts T7
-scripts/release.mjs T9 scripts/base-url.mjs T10 scripts/consumers.mjs T11 scripts/og.mjs T13 scripts/changelog.mjs T15
-registry/src/hairline.tsx, registry/build.mjs, registry/validate.mjs T10
-fixtures/next-app/, fixtures/vite-vanilla/ T11
-apps/site/ T12 (the page), T13 (/og and public/og.png), T14 (Vercel)
-```
-
----
-
-### Task 1: Scaffold the monorepo and an empty package
-
-**Files:**
-- Create: `.gitignore`, `.npmrc`, `pnpm-workspace.yaml`, `tsconfig.base.json`, `turbo.json`, `package.json`, `LICENSE`, `README.md` (stub), `.github/workflows/ci.yml`
-- Create: `packages/hairline/package.json`, `packages/hairline/tsconfig.json`, `packages/hairline/tsup.config.ts`, `packages/hairline/vitest.config.ts`, `packages/hairline/src/index.ts`
-
-**Interfaces:**
-- Consumes: nothing.
-- Produces:
- - Root scripts: `pnpm build`, `pnpm typecheck`, `pnpm test`, `pnpm test:browser`, `pnpm release` (the script arrives in Task 9).
- - Package scripts: `build`, `typecheck`, `test`, `test:browser`, `capture`, `prepack`, `size`.
- - All of the package's devDependencies are installed now, so no later task changes the lockfile until Task 10 (ajv) and Task 12 (the site).
-
-This task has no behaviour to test first. Its test is that the three commands below pass on an empty package. That is the spec's phase 0 exit criterion.
-
-- [ ] **Step 1: Write the root files**
-
-`.gitignore`
-```text
-node_modules/
-dist/
-.turbo/
-.next/
-.vercel
-*.tsbuildinfo
-.DS_Store
-.env*
-coverage/
-test-results/
-playwright-report/
-
-# Agent scratch
-.claude/
-
-# Copied in from the root by the package's prepack
-packages/hairline/README.md
-packages/hairline/LICENSE
-```
-
-`.npmrc`
-```text
-strict-peer-dependencies=false
-auto-install-peers=true
-```
-
-`pnpm-workspace.yaml`
-```yaml
-packages:
- - 'packages/*'
- - 'apps/*'
-
-# esbuild ships a platform binary via postinstall; tsup needs it.
-onlyBuiltDependencies:
- - esbuild
-```
-
-`tsconfig.base.json`
-```json
-{
- "$schema": "https://json.schemastore.org/tsconfig",
- "compilerOptions": {
- "target": "ES2020",
- "lib": ["ES2020", "DOM", "DOM.Iterable"],
- "module": "ESNext",
- "moduleResolution": "bundler",
- "strict": true,
- "esModuleInterop": true,
- "forceConsistentCasingInFileNames": true,
- "resolveJsonModule": true,
- "isolatedModules": true,
- "skipLibCheck": true,
- "declaration": true,
- "sourceMap": true
- }
-}
-```
-
-`turbo.json`
-```json
-{
- "$schema": "https://turbo.build/schema.json",
- "ui": "stream",
- "agentGuidance": false,
- "tasks": {
- "build": {
- "dependsOn": ["^build"],
- "outputs": ["dist/**"]
- },
- "typecheck": {
- "dependsOn": ["^build"]
- },
- "test": {
- "dependsOn": ["^build"]
- },
- "test:browser": {
- "dependsOn": ["build"],
- "cache": false
- },
- "dev": {
- "dependsOn": ["^build"],
- "cache": false,
- "persistent": true
- },
- "clean": {
- "cache": false
- }
- }
-}
-```
-
-`ajv` joins the root devDependencies in Task 10.
-
-`package.json`
-```json
-{
- "name": "hairline-monorepo",
- "version": "0.0.0",
- "private": true,
- "description": "Six isometric line figures that answer the pointer",
- "packageManager": "[email protected]",
- "engines": {
- "node": ">=22"
- },
- "scripts": {
- "build": "turbo run build",
- "dev": "turbo run dev",
- "typecheck": "turbo run typecheck",
- "test": "turbo run test",
- "test:browser": "turbo run test:browser",
- "clean": "turbo run clean",
- "release": "node scripts/release.mjs"
- },
- "devDependencies": {
- "turbo": "^2.10.5",
- "typescript": "5.9.3"
- },
- "repository": {
- "type": "git",
- "url": "git+https://github.com/lucasmarkes/hairline.git"
- },
- "bugs": {
- "url": "https://github.com/lucasmarkes/hairline/issues"
- },
- "homepage": "https://hairline.lucasmarkes.com"
-}
-```
-
-`LICENSE`
-```text
-MIT License
-
-Copyright (c) 2026 Lucas Marques
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-```
-
-The real README replaces this one in Task 9:
-
-`README.md`
-```markdown
-# hairline
-
-Six isometric line figures that answer the pointer. For React and for anything with a DOM.
-```
-
-- [ ] **Step 2: Write the package's files**
-
-The test script carries `--passWithNoTests` until the first test exists (Task 4). Everything else in this manifest is final until the version bump in Task 15. The `size-limit` budgets are the first green build's sizes plus 10%, as the spec asks; Task 9 checks them.
-
-`packages/hairline/package.json`
-```json
-{
- "name": "@lucasmarkes/hairline",
- "version": "0.0.0",
- "description": "Six isometric line figures that answer the pointer. For React and for anything with a DOM.",
- "license": "MIT",
- "type": "module",
- "sideEffects": false,
- "keywords": [
- "svg",
- "isometric",
- "illustration",
- "interactive",
- "pointer",
- "animation",
- "react"
- ],
- "files": [
- "dist"
- ],
- "types": "./dist/index.d.ts",
- "exports": {
- ".": {
- "types": "./dist/index.d.ts",
- "default": "./dist/index.js"
- },
- "./react": {
- "types": "./dist/react.d.ts",
- "default": "./dist/react.js"
- },
- "./package.json": "./package.json"
- },
- "scripts": {
- "build": "rm -rf dist && tsup",
- "dev": "tsup --watch",
- "typecheck": "tsc --noEmit",
- "test": "vitest run --passWithNoTests",
- "clean": "rm -rf dist .turbo",
- "test:browser": "playwright test",
- "capture": "node test/parity/capture.mjs",
- "prepack": "cp ../../README.md ../../LICENSE .",
- "lint:package": "publint --strict && attw --pack . --profile esm-only",
- "size": "size-limit"
- },
- "publishConfig": {
- "access": "public"
- },
- "repository": {
- "type": "git",
- "url": "git+https://github.com/lucasmarkes/hairline.git",
- "directory": "packages/hairline"
- },
- "bugs": {
- "url": "https://github.com/lucasmarkes/hairline/issues"
- },
- "homepage": "https://hairline.lucasmarkes.com",
- "devDependencies": {
- "@arethetypeswrong/cli": "0.18.5",
- "@playwright/test": "1.63.0",
- "@size-limit/preset-small-lib": "14.1.0",
- "@testing-library/react": "^16.3.3",
- "@types/node": "^22.20.4",
- "@types/react": "^19.3.0",
- "@types/react-dom": "^19.3.0",
- "esbuild": "0.28.2",
- "jsdom": "^30.1.1",
- "publint": "0.3.24",
- "react": "^19.3.0",
- "react-dom": "^19.3.0",
- "size-limit": "14.1.0",
- "tsup": "^8.5.1",
- "typescript": "5.9.3",
- "vitest": "^5.0.3"
- },
- "peerDependencies": {
- "react": ">=18"
- },
- "peerDependenciesMeta": {
- "react": {
- "optional": true
- }
- },
- "size-limit": [
- {
- "name": "vanilla, all six figures",
- "path": "dist/index.js",
- "limit": "12.8 kB"
- },
- {
- "name": "vanilla, one figure",
- "path": "dist/index.js",
- "import": "{ terrain }",
- "limit": "5.4 kB"
- },
- {
- "name": "react, all six components",
- "path": "dist/react.js",
- "limit": "13.2 kB",
- "ignore": [
- "react",
- "react/jsx-runtime"
- ]
- }
- ]
-}
-```
-
-`packages/hairline/tsconfig.json`
-```json
-{
- "extends": "../../tsconfig.base.json",
- "compilerOptions": {
- "noEmit": true,
- "jsx": "react-jsx",
- "allowJs": true,
- "checkJs": false
- },
- "include": [
- "src",
- "test",
- "*.ts"
- ]
-}
-```
-
-`packages/hairline/vitest.config.ts`
-```ts
-import { defineConfig } from "vitest/config";
-
-export default defineConfig({
- test: {
- environment: "node",
- include: ["test/**/*.test.{ts,tsx}"],
- },
-});
-```
-
-One entry for now. Task 8 adds the React entry.
-
-`packages/hairline/tsup.config.ts`
-```ts
-import { defineConfig } from "tsup";
-
-export default defineConfig([{ format: ["esm"], target: "es2020", dts: true, sourcemap: true, entry: ["src/index.ts"] }]);
-```
-
-`packages/hairline/src/index.ts`
-```ts
-export {};
-```
-
-- [ ] **Step 3: Write CI**
-
-This is CI without the browser tests (added in Task 7) and the static release gate (added in Task 9):
-
-`.github/workflows/ci.yml`
-```yaml
-name: CI
-
-on:
- push:
- branches: [main]
- pull_request:
-
-# A newer push to the same branch or PR cancels the run in flight.
-concurrency:
- group: ci-${{ github.ref }}
- cancel-in-progress: true
-
-permissions:
- contents: read
-
-jobs:
- verify:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v7
-
- # Corepack activates the pnpm pinned in package.json's packageManager.
- - name: Enable Corepack
- run: corepack enable
-
- - uses: actions/setup-node@v7
- with:
- node-version: 22
- cache: pnpm
-
- - name: Install
- run: pnpm install --frozen-lockfile
-
- - name: Build
- run: pnpm build
-
- - name: Typecheck
- run: pnpm typecheck
-
- - name: Unit and component tests
- run: pnpm test
-
-```
-
-- [ ] **Step 4: Install, and run the phase 0 gate**
-
-Run:
-```bash
-cd ~/estudos/hairline
-corepack enable
-pnpm install
-pnpm build && pnpm typecheck && pnpm test
-```
-Expected:
-- `pnpm install` writes `pnpm-lock.yaml` and builds esbuild's binary, the only dependency allowed to run a build script.
-- `pnpm build` writes `packages/hairline/dist/index.js` and `index.d.ts`.
-- `pnpm typecheck` passes.
-- `pnpm test` prints "No test files found, exiting with code 0".
-
-All three exit 0.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add .gitignore .npmrc pnpm-workspace.yaml tsconfig.base.json turbo.json package.json pnpm-lock.yaml LICENSE README.md .github packages
-git commit -m "Scaffold: pnpm and Turborepo workspace with an empty @lucasmarkes/hairline
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-### Task 2: Create the private GitHub repository and get CI green
-
-**Files:** none.
-
-**Interfaces:**
-- Consumes: the commit from Task 1.
-- Produces: a private repository, `lucasmarkes/hairline`, with `origin` set up. CI runs on every push to `main` and on every pull request. Task 14 (Vercel) and Task 15 (`publish.yml`) rely on it.
-
-- [ ] **Step 1: Check the GitHub account**
-
-Run: `gh auth status`
-Expected: logged in to github.com as `lucasmarkes`. If not, stop and ask Lucas to run `! gh auth login`.
-
-- [ ] **Step 2: Create the repository (confirm)**
-
-**confirm:** this creates a repository on GitHub. It is private, but it is still an outside action. Ask Lucas before running it.
-
-```bash
-cd ~/estudos/hairline
-gh repo create lucasmarkes/hairline --private --source . --remote origin --push \
- --description "Six isometric line figures that answer the pointer. For React and for anything with a DOM."
-```
-Expected: the repository is created, `origin` is added, and `main` is pushed with both commits (the spec and Task 1).
-
-- [ ] **Step 3: Watch the first CI run**
-
-Run: `gh run watch --exit-status "$(gh run list --workflow CI --limit 1 --json databaseId --jq '.[0].databaseId')"`
-Expected: the `verify` job passes Install, Build, Typecheck and "Unit and component tests". This is the spec's phase 0 exit criterion, in CI.
-
-If Install fails with `ERR_PNPM_OUTDATED_LOCKFILE`, the lockfile was not committed. Commit it and push.
-
-No commit: nothing in the working tree changes.
-
-### Task 3: Capture the goldens from the website, before any engine moves
-
-**Files:**
-- Create: `packages/hairline/test/parity/clock.js`, `driver.mjs`, `scripts.mjs`, `capture.mjs`
-- Create (generated, committed): `packages/hairline/test/parity/golden/{riffle,terrain,exploded,phosphor,slow,turntable}.json`
-
-**Interfaces:**
-- Consumes: the package's devDependencies (`@playwright/test`) from Task 1. It also needs the website repository at `~/estudos/lucasmarkes.com/website`, which holds commit `edfebe9`.
-- Produces, for the parity test in Task 7:
- - `clock.js`: defines `window.__freeze(at?)`, `window.__advance(ms)` and `window.__realTimeout`. The virtual clock, added as an init script.
- - `driver.mjs`:
- - `FRAME` (`1000 / 60`).
- - `normalise(svg: string): string`: numbers mask and gradient ids by first appearance.
- - `play(page, target: { stage: Locator; snap(): Promise<{ svg: string; read: string }>; set(): Promise<void> }, steps): Promise<Array<{ at: string; read: string; svg: string }>>`.
- - `scripts.mjs`:
- - `FIGURES`: the six ids, in page order.
- - `OPTION`: `Record<id, [optionName, scriptValue]>`.
- - `SCRIPTS`: `Record<id, Step[]>`, where a step is one of `{adv}`, `{move:[x,y]}`, `{out}`, `{focus}`, `{key}`, `{set}` or `{cp}`.
- - `golden/<id>.json`: `{ source: { site, commit }, viewport, option, checkpoints: [{ at, read, svg }] }`.
-
-The goldens are the test. Every later change to an engine must reproduce them. They are taken from a production build of the website at `edfebe9`, exported to a temporary directory so that nothing in the website's working copy changes. `capture.mjs` captures each figure twice and fails if the two captures differ. That makes the run a determinism test of the clock and the scripts.
-
-- [ ] **Step 1: Write the virtual clock, the driver and the scripts**
-
-`packages/hairline/test/parity/clock.js`
-```js
-/**
- * A virtual clock for tests. Add it to a page with context.addInitScript,
- * before any of the page's own scripts.
- *
- * Live until window.__freeze(at): nothing changes in behaviour. From the
- * freeze on, performance.now() reads `at` and time moves only when
- * window.__advance(ms) is called: due timers fire in order, the rAF queue is
- * flushed with the new timestamp, and every animation in the document, CSS
- * transitions included, is paused and seeked to where the virtual clock says
- * it is. Same calls, same drawing.
- */
-(() => {
- const realNow = performance.now.bind(performance);
- const realDateNow = Date.now;
- const realRAF = window.requestAnimationFrame.bind(window);
- const realCAF = window.cancelAnimationFrame.bind(window);
- const realST = window.setTimeout.bind(window);
- const realCT = window.clearTimeout.bind(window);
- const realSI = window.setInterval.bind(window);
- const realCI = window.clearInterval.bind(window);
-
- let frozen = false;
- let now = 0;
- let dateOffset = 0;
- let seq = 1e9; // virtual ids never collide with the browser's
- let rafs = new Map();
- const timers = new Map();
- const started = new WeakMap();
- const rethrow = (e) => queueMicrotask(() => { throw e; });
-
- performance.now = () => (frozen ? now : realNow());
- Date.now = () => (frozen ? Math.round(now + dateOffset) : realDateNow());
-
- window.requestAnimationFrame = (cb) => {
- if (!frozen) return realRAF(cb);
- const id = ++seq; rafs.set(id, cb); return id;
- };
- window.cancelAnimationFrame = (id) => { if (!rafs.delete(id)) realCAF(id); };
- window.setTimeout = (cb, ms = 0, ...args) => {
- if (!frozen) return realST(cb, ms, ...args);
- const id = ++seq; timers.set(id, { at: now + Math.max(0, ms), cb, args, every: 0 }); return id;
- };
- window.clearTimeout = (id) => { if (!timers.delete(id)) realCT(id); };
- window.setInterval = (cb, ms = 0, ...args) => {
- if (!frozen) return realSI(cb, ms, ...args);
- const every = Math.max(1, ms);
- const id = ++seq; timers.set(id, { at: now + every, cb, args, every }); return id;
- };
- window.clearInterval = (id) => { if (!timers.delete(id)) realCI(id); };
-
- function runTimers(until) {
- for (;;) {
- let next = null, nextId = 0;
- for (const [id, t] of timers) if (t.at <= until && (!next || t.at < next.at)) { next = t; nextId = id; }
- if (!next) return;
- now = next.at;
- if (next.every) next.at += next.every; else timers.delete(nextId);
- try { if (typeof next.cb === "function") next.cb(...next.args); } catch (e) { rethrow(e); }
- }
- }
-
- /* At the freeze, an animation keeps the time it has already played: an
- entrance that finished on the wall clock stays finished (fill keeps it
- listed). After it, one first seen starts now, whatever the wall clock ran
- it for in between: an input between two advances starts transitions live */
- function seekAnimations(keepPlayed) {
- for (const a of document.getAnimations()) {
- if (!started.has(a)) { started.set(a, now - (keepPlayed ? Number(a.currentTime) || 0 : 0)); a.pause(); }
- const t = now - started.get(a);
- const end = a.effect ? a.effect.getComputedTiming().endTime : 0;
- if (Number.isFinite(end) && t >= end) { a.finish(); continue; }
- a.currentTime = t;
- }
- }
-
- window.__realTimeout = realST;
- window.__now = () => (frozen ? now : realNow());
- window.__freeze = (at) => {
- if (frozen) return;
- now = at ?? realNow();
- dateOffset = realDateNow() - now;
- frozen = true;
- seekAnimations(true);
- };
- window.__advance = (ms) => {
- if (!frozen) throw new Error("__advance before __freeze");
- const target = now + Math.max(0, ms);
- runTimers(target);
- now = target;
- const due = rafs; rafs = new Map();
- for (const cb of due.values()) { try { cb(now); } catch (e) { rethrow(e); } }
- seekAnimations(false);
- return now;
- };
-})();
-```
-
-`packages/hairline/test/parity/driver.mjs`
-```js
-/**
- * Plays a script against a figure, whoever is hosting it. `target` is the
- * host's side of it:
- * stage the element the pointer acts on (a Playwright Locator)
- * snap() the svg's markup and the caption, read from the page
- * set() changes the figure's option to the script's value
- * Time only moves here, through window.__advance (clock.js).
- *
- * The pointer is dispatched, not a real mouse: a real one reports whole
- * pixels, so the same viewBox point would land differently on stages of
- * different widths. A dispatched event carries the exact point.
- */
-export const FRAME = 1000 / 60;
-
-/** Mask and gradient ids count up per page; number them by first appearance instead. */
-export function normalise(svg) {
- const seen = new Map();
- return svg.replace(/hl-fd\d+/g, (id) => {
- if (!seen.has(id)) seen.set(id, `fd${seen.size + 1}`);
- return seen.get(id);
- });
-}
-
-const fire = (stage, type, pt) => stage.evaluate((el, [type, pt]) => {
- const r = el.getBoundingClientRect();
- el.dispatchEvent(new PointerEvent(type, {
- pointerType: "mouse", pointerId: 1, bubbles: type !== "pointerleave",
- clientX: pt ? r.left + (pt[0] / 400) * r.width : r.left - 40,
- clientY: pt ? r.top + (pt[1] / 320) * r.height : r.top - 40,
- }));
-}, [type, pt]);
-
-export async function play(page, target, steps) {
- const out = [];
- for (const s of steps) {
- if (s.adv) await page.evaluate(([n, f]) => { for (let i = 0; i < n; i++) window.__advance(f); }, [s.adv, FRAME]);
- else if (s.move) await fire(target.stage, "pointermove", s.move);
- else if (s.out) await fire(target.stage, "pointerleave", null);
- else if (s.focus) await target.stage.focus();
- else if (s.key) await page.keyboard.press(s.key);
- else if (s.set) await target.set();
- else if (s.cp) { const { svg, read } = await target.snap(); out.push({ at: s.cp, read, svg: normalise(svg) }); }
- else throw new Error(`unknown step ${JSON.stringify(s)}`);
- }
- return out;
-}
-```
-
-`packages/hairline/test/parity/scripts.mjs`
-```js
-/**
- * The pointer script each figure is put through, on the site (to capture the
- * goldens) and on the package (to compare). Points are in the figure's own
- * viewBox (400 × 320). `adv` is a count of 60 Hz frames on the virtual clock.
- */
-export const FIGURES = ["riffle", "terrain", "exploded", "phosphor", "slow", "turntable"];
-
-/** The option each figure has, and the value the script changes it to. */
-export const OPTION = {
- riffle: ["stagger", 60], terrain: ["radius", 4], exploded: ["gap", 36],
- phosphor: ["afterglow", 900], slow: ["rate", 0.4], turntable: ["coast", 1000],
-};
-
-export const SCRIPTS = {
- riffle: [
- { adv: 30 }, { cp: "rest" },
- { move: [150, 120] }, { adv: 60 }, { cp: "pulled" },
- { set: true }, { move: [200, 100] }, { adv: 20 }, { cp: "stagger in flight" },
- { out: true }, { adv: 150 }, { cp: "left" },
- { focus: true }, { key: "ArrowLeft" }, { adv: 60 }, { cp: "arrow" },
- { key: "ArrowRight" }, { adv: 60 }, { cp: "arrow back" },
- { key: "Escape" }, { adv: 120 }, { cp: "escape" },
- ],
- terrain: [
- { adv: 30 }, { cp: "rest" },
- { move: [200, 160] }, { adv: 40 }, { cp: "raised" },
- { set: true }, { adv: 30 }, { cp: "wider" },
- { move: [150, 200] }, { adv: 10 }, { cp: "moving" },
- { out: true }, { adv: 150 }, { cp: "left" },
- ],
- exploded: [
- { adv: 30 }, { cp: "rest" },
- { move: [100, 80] }, { adv: 40 }, { cp: "opening" },
- { move: [180, 60] }, { adv: 40 }, { cp: "pick high" },
- { move: [180, 120] }, { adv: 40 }, { cp: "pick middle" },
- { move: [180, 190] }, { adv: 40 }, { cp: "pick low" },
- { set: true }, { adv: 40 }, { cp: "wider" },
- { out: true }, { adv: 150 }, { cp: "left" },
- ],
- phosphor: [
- { adv: 30 }, { cp: "loop" },
- { move: [240, 140] }, { adv: 2 }, { move: [260, 145] }, { adv: 2 }, { move: [280, 150] }, { adv: 20 }, { cp: "painted" },
- { set: true }, { out: true }, { adv: 30 }, { cp: "afterglow" },
- { adv: 240 }, { cp: "loop again" },
- ],
- slow: [
- { adv: 30 }, { cp: "rest" },
- { move: [200, 160] }, { adv: 60 }, { cp: "slowed" },
- { set: true }, { adv: 60 }, { cp: "less slow" },
- { out: true }, { adv: 150 }, { cp: "left" },
- ],
- turntable: [
- { adv: 30 }, { cp: "rest" },
- { move: [50, 176] }, { adv: 1 }, { move: [120, 176] }, { adv: 1 }, { move: [200, 176] }, { adv: 1 },
- { move: [280, 176] }, { adv: 1 }, { move: [350, 176] }, { adv: 6 }, { cp: "spinning" },
- { set: true }, { out: true }, { adv: 60 }, { cp: "coasting" },
- { adv: 360 }, { cp: "seated" },
- ],
-};
-```
-
-- [ ] **Step 2: Write the capture script**
-
-`packages/hairline/test/parity/capture.mjs`
-```js
-/**
- * Captures the goldens: what the six figures draw on lucasmarkes.com/lab/hairline,
- * checkpoint by checkpoint, under the scripts in scripts.mjs. The package's
- * parity test (test/browser/parity.spec.ts) must draw the same.
- *
- * node test/parity/capture.mjs <commit> [url]
- *
- * <commit> is the website commit being served, recorded in each golden.
- * [url] is where a production build of it is running (default http://localhost:3124).
- * Every figure is captured twice, and a difference between the two is an error.
- */
-import { chromium } from "@playwright/test";
-import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
-import { play } from "./driver.mjs";
-import { FIGURES, OPTION, SCRIPTS } from "./scripts.mjs";
-
-const [commit, base = "http://localhost:3124"] = process.argv.slice(2);
-if (!commit) { console.error("usage: node test/parity/capture.mjs <commit> [url]"); process.exit(1); }
-
-const here = (p) => new URL(p, import.meta.url);
-const clock = readFileSync(here("./clock.js"), "utf8") + "\nwindow.__freeze(1000);";
-const VIEWPORT = { width: 1200, height: 900 };
-
-async function capture(browser, id) {
- const context = await browser.newContext({ viewport: VIEWPORT, deviceScaleFactor: 1, colorScheme: "light", reducedMotion: "no-preference" });
- await context.addInitScript(clock);
- const page = await context.newPage();
- await page.goto(`${base}/lab/hairline`);
- if (await page.locator("nextjs-portal").count()) throw new Error("This is the dev server. Capture against a production build (pnpm build && pnpm start).");
- const figure = page.locator("figure.hairline").nth(FIGURES.indexOf(id)), stage = figure.locator(".hl-stage");
- await stage.locator("svg.fg > *").first().waitFor();
- await stage.evaluate((el) => {
- const r = el.getBoundingClientRect();
- window.scrollTo({ top: window.scrollY + r.top + r.height / 2 - innerHeight / 2, behavior: "instant" });
- });
- await page.evaluate(() => new Promise((done) => window.__realTimeout(done, 500)));
- const input = figure.locator("input[type=range]"), value = OPTION[id][1];
- const checkpoints = await play(page, {
- stage,
- snap: () => stage.evaluate((el) => ({ svg: el.querySelector("svg").innerHTML, read: el.querySelector(".hl-read").textContent })),
- /* the slider is React's: set it the way a user's drag would, then give React real time to render */
- set: async () => {
- await input.evaluate((el, v) => {
- Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set.call(el, String(v));
- el.dispatchEvent(new Event("input", { bubbles: true }));
- }, value);
- await page.waitForFunction(([el, v]) => Number(el.value) === v, [await input.elementHandle(), value]);
- await page.evaluate(() => new Promise((done) => window.__realTimeout(done, 150)));
- },
- }, SCRIPTS[id]);
- await context.close();
- return checkpoints;
-}
-
-const browser = await chromium.launch({ channel: "chrome", headless: true });
-mkdirSync(here("./golden/"), { recursive: true });
-let failed = false;
-for (const id of FIGURES) {
- const first = await capture(browser, id), second = await capture(browser, id);
- if (JSON.stringify(first) !== JSON.stringify(second)) { console.error(`✗ ${id}: two captures differ; the golden would not be reproducible`); failed = true; continue; }
- const golden = { source: { site: "lucasmarkes.com/lab/hairline", commit }, viewport: VIEWPORT, option: OPTION[id], checkpoints: first };
- writeFileSync(here(`./golden/${id}.json`), JSON.stringify(golden, null, 1) + "\n");
- console.log(`✓ ${id}: ${first.map((c) => `${c.at} "${c.read}"`).join(" · ")}`);
-}
-await browser.close();
-process.exit(failed ? 1 : 0);
-```
-
-- [ ] **Step 3: Run it with nothing to capture, and see it fail**
-
-Run: `pnpm -C packages/hairline capture edfebe9`
-Expected: FAIL. `page.goto` throws `net::ERR_CONNECTION_REFUSED at http://localhost:3124/lab/hairline`, because the website is not running yet.
-
-- [ ] **Step 4: Export the website at `edfebe9`, build it and serve it on port 3124**
-
-```bash
-rm -rf /tmp/hairline-website && mkdir /tmp/hairline-website
-git -C ~/estudos/lucasmarkes.com/website archive edfebe9 | tar -x -C /tmp/hairline-website
-cd /tmp/hairline-website
-pnpm install --frozen-lockfile
-pnpm build
-pnpm start -p 3124
-```
-Leave `pnpm start` running in a second terminal, or in the background. Expected: `curl -s -o /dev/null -w '%{http_code}' http://localhost:3124/lab/hairline` prints `200`.
-
-- [ ] **Step 5: Capture**
-
-Run: `pnpm -C ~/estudos/hairline/packages/hairline capture edfebe9`
-
-Expected: six lines and exit 0:
-```
-✓ riffle: rest "…" · pulled "…" · …
-✓ terrain: rest "…" · raised "…" · …
-✓ exploded: …
-✓ phosphor: …
-✓ slow: …
-✓ turntable: …
-```
-
-A `✗ <id>: two captures differ` line means the capture is not reproducible. Do not commit. Stop and report which figure failed.
-
-- [ ] **Step 6: Check what was written**
-
-Run:
-```bash
-cd ~/estudos/hairline/packages/hairline
-node -e '
-const { FIGURES, SCRIPTS } = await import("./test/parity/scripts.mjs");
-const fs = await import("node:fs");
-for (const id of FIGURES) {
- const g = JSON.parse(fs.readFileSync(`test/parity/golden/${id}.json`, "utf8"));
- const want = SCRIPTS[id].filter((s) => s.cp).length;
- if (g.source.commit !== "edfebe9" || g.checkpoints.length !== want || g.checkpoints.some((c) => !c.svg.includes("<path"))) throw new Error(id);
- console.log(id, g.checkpoints.length, "checkpoints");
-}' --input-type=module
-```
-Expected: each of the six figures is printed with its checkpoint count, and nothing throws.
-
-- [ ] **Step 7: Stop the website and commit**
-
-Stop `pnpm start`. Then run `rm -rf /tmp/hairline-website`.
-
-```bash
-cd ~/estudos/hairline
-git add packages/hairline/test/parity
-git commit -m "Parity: goldens of the six figures, captured from lucasmarkes.com at edfebe9
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-### Task 4: Port the engines
-
-**Files:**
-- Create (copied from the website at `edfebe9`): `packages/hairline/src/core/iso.ts`, `src/core/motion.ts`, `src/core/stage.ts`, and in `src/figures/`: `riffle.ts`, `terrain.ts`, `exploded.ts`, `phosphor.ts`, `slow.ts`, `turntable.ts`, `riffle-geometry.ts`, `turntable-geometry.ts`
-- Modify (by patch): `src/core/stage.ts`, `src/figures/riffle-geometry.ts`, `src/figures/riffle.ts`
-- Modify: `packages/hairline/package.json` (the test script)
-- Test: `packages/hairline/test/geometry.test.ts`
-
-**Interfaces:**
-- Consumes: nothing from earlier tasks. The goldens from Task 3 judge this task's output in Task 7.
-- Produces, used by Tasks 5–8:
- - From `src/core/stage.ts`:
- - `type Readout = { textContent: string | null }`. An engine writes its caption here and touches nothing else on it.
- - `type FigureEls = { stage: HTMLElement; svg: SVGSVGElement; read: Readout }`
- - `type FigureHandle = { set(value: number): void; destroy(): void }`
- - `type FigureMount = (els: FigureEls, value: number) => FigureHandle`
- - `register(stage: Element, tick: Tick): Loop`, `pointer(stage: HTMLElement, on: PointerHandlers): () => void` and `disposer(): Disposer`. These are the engines' plumbing; nothing above the engines calls them.
- - Each `src/figures/<id>.ts` exports `mount`:
- - Terrain, Exploded, Phosphor, Slow and Turntable export `mount: FigureMount`.
- - Riffle exports `mount(els: FigureEls, value: number): RiffleHandle`, where `type RiffleHandle = FigureHandle & { bands(on: boolean): void; labels(list: readonly string[]): void }`.
- - Engines are imported only by `src/index.ts` (Task 6). Each takes its one number already clamped.
-
-The engines move as they are. Only three things change:
-- The website's `@/` imports become relative.
-- Riffle loses its "hit bands" button. The figure draws only the drawing; `bands` and `labels` become methods instead.
-- `stage.ts` accepts any `{ textContent }` as the caption sink, so the public layer can catch each caption without an element.
-
-Everything else is copied, so the comments that mention "the study" and "Fig 9.n" stay. CONTRIBUTING (Task 9) explains them.
-
-- [ ] **Step 1: Write the failing test**
-
-These are the website's five geometry tests (`tests/hairline-geometry.spec.ts`), ported to Vitest.
-
-`packages/hairline/test/geometry.test.ts`
-```ts
-import { expect, test } from "vitest";
-import { Cam, fit, proj, rad, unproj } from "../src/core/iso";
-import { BLK, DETENT, HOME, detent, paintOrder } from "../src/figures/turntable-geometry";
-
-/**
- * The parts of Hairline that can be checked without a browser. The painter's
- * order is the one that can go wrong somewhere in a full turn and look right
- * everywhere else, so it is swept all the way round at the three elevations
- * the turntable reaches (20° to 40°, resting at 30°).
- */
-const close = (a: number, b: number, eps = 1e-6) => expect(Math.abs(a - b)).toBeLessThan(eps);
-
-test("turntable order is a full permutation with no forced pick, all the way round", () => {
- for (const el of [20, 30, 40]) {
- const k = Math.sin(rad(el));
- for (let az = 0; az <= 360; az += 0.5) {
- const { order, forced } = paintOrder(BLK, Math.sin(rad(az)), Math.cos(rad(az)), k);
- expect(forced, `cycle at az ${az} el ${el}`).toBe(0);
- expect(order.slice().sort((a, b) => a - b)).toEqual(BLK.map((_, i) => i));
- }
- }
-});
-
-test("a stacked column paints bottom first", () => {
- // blocks 0 and 1 are column 0, and 5 and 6 are column 4; lower first at every angle
- for (let az = 0; az < 360; az += 7.5) {
- const o = paintOrder(BLK, Math.sin(rad(az)), Math.cos(rad(az)), 0.5).order;
- expect(o.indexOf(0)).toBeLessThan(o.indexOf(1));
- expect(o.indexOf(5)).toBeLessThan(o.indexOf(6));
- }
-});
-
-test("detent seats on the nearest quarter turn from HOME", () => {
- expect(HOME).toBe(45);
- expect(DETENT).toBe(90);
- expect(detent(45)).toBe(45);
- expect(detent(89)).toBe(45);
- expect(detent(91)).toBe(135);
- expect(detent(200)).toBe(225);
- expect(detent(-44)).toBe(-45);
- expect(detent(400)).toBe(405);
- for (let a = -720; a <= 720; a += 3.7) {
- const d = detent(a);
- expect(Math.abs(d - a)).toBeLessThanOrEqual(45);
- expect((((d - HOME) % 90) + 90) % 90).toBe(0);
- }
-});
-
-test("unproj inverts proj on the plane it is given", () => {
- for (const [az, k, S] of [[45, 0.5, 1.62], [0, 0.34, 2], [123, 0.64, 1.3], [-80, 0.5, 1.85]]) {
- const C = Cam(az, k, S);
- fit(C, [[0, 0, 0], [100, 80, 0], [0, 0, 40]], 200, 160);
- const P = proj(C);
- for (const [x, y, z] of [[0, 0, 0], [12.5, -40, 0], [80, 33, 17], [-20, 60, -9]]) {
- const [sx, sy] = P(x, y, z);
- const [ux, uy] = unproj(C, sx, sy, z);
- close(ux, x); close(uy, y);
- }
- }
-});
-
-test("fit centres the box it is given", () => {
- const C = Cam(45, 0.5, 1.58);
- const pts: [number, number, number][] = [[-6, -6, -5], [132, 132, -5], [132, -6, -5], [-6, 132, -5], [0, 0, 43.5]];
- fit(C, pts, 200, 166);
- const P = proj(C), xs = pts.map((p) => P(...p)[0]), ys = pts.map((p) => P(...p)[1]);
- close((Math.min(...xs) + Math.max(...xs)) / 2, 200);
- close((Math.min(...ys) + Math.max(...ys)) / 2, 166);
-});
-```
-
-- [ ] **Step 2: Run it and see it fail**
-
-Run: `pnpm -C packages/hairline exec vitest run test/geometry.test.ts`
-Expected: FAIL with `Error: Cannot find module '../src/core/iso' imported from …/test/geometry.test.ts`.
-
-- [ ] **Step 3: Copy the engines from the website at `edfebe9`, and make the imports relative**
-
-```bash
-cd ~/estudos/hairline/packages/hairline
-W=/tmp/hairline-port && rm -rf $W && mkdir $W
-git -C ~/estudos/lucasmarkes.com/website archive edfebe9 lib/hairline components/hairline | tar -x -C $W
-mkdir -p src/core src/figures
-cp $W/lib/hairline/iso.ts $W/lib/hairline/motion.ts $W/components/hairline/stage.ts src/core/
-cp $W/lib/hairline/riffle-geometry.ts $W/lib/hairline/turntable-geometry.ts $W/components/hairline/figures/*.ts src/figures/
-sed -i '' -e 's#"@/lib/hairline/iso"#"./iso"#' -e 's#"@/lib/hairline/motion"#"./motion"#' src/core/stage.ts
-sed -i '' -e 's#"@/lib/hairline/iso"#"../core/iso"#' -e 's#"@/lib/hairline/motion"#"../core/motion"#' \
- -e 's#"@/components/hairline/stage"#"../core/stage"#' -e 's#"@/lib/hairline/riffle-geometry"#"./riffle-geometry"#' \
- -e 's#"@/lib/hairline/turntable-geometry"#"./turntable-geometry"#' src/figures/*.ts
-rm -rf $W
-ls src/core src/figures
-```
-Expected: `src/core` holds `iso.ts`, `motion.ts` and `stage.ts`. `src/figures` holds the six engines plus `riffle-geometry.ts` and `turntable-geometry.ts`. `grep -rn '"@/' src` prints nothing. (`sed -i ''` is the macOS form. On Linux, write `sed -i`.)
-
-- [ ] **Step 4: Apply the port patch**
-
-Save this as `port.patch` at the repository root:
-
-`port.patch`
-```diff
-diff --git a/packages/hairline/src/core/stage.ts b/packages/hairline/src/core/stage.ts
---- a/packages/hairline/src/core/stage.ts
-+++ b/packages/hairline/src/core/stage.ts
-@@ -7,24 +7,24 @@
- /**
- * Hairline — the DOM side every figure shares: making svg nodes, the helpers
- * that write a solid or a dot into them, one frame loop for all six figures,
-- * the pointer, and the only reduced-motion query. From the study's shared
-- * section (design/lab-hairline/cartilha-v2.html).
-+ * the pointer, and the only reduced-motion query.
- *
-- * New here: everything comes apart. The study lives for one page load; the
-- * site navigates away and back, and React's StrictMode mounts twice. So
-- * `register` hands back an unregister, `pointer` a disposer, and `disposer()`
-- * collects them so a figure's `destroy` is one call. Once the last figure is
-- * unregistered no frame, observer or media listener is left behind, and the
-- * next `register` starts them again.
-+ * Everything comes apart. A page navigates away and back, and React's
-+ * StrictMode mounts twice. So `register` hands back an unregister, `pointer`
-+ * a disposer, and `disposer()` collects them so a figure's `destroy` is one
-+ * call. Once the last figure is unregistered no frame, observer or media
-+ * listener is left behind, and the next `register` starts them again.
- *
- * Nothing here touches `window` at import: the module is evaluated during
-- * the server render too, so the loop, the observer and the media query are
-+ * a server render too, so the loop, the observer and the media query are
- * created by the first `register`.
- */
-
- /* ---------- the contract ---------- */
-
--export type FigureEls = { stage: HTMLElement; svg: SVGSVGElement; read: HTMLElement };
-+/** Where an engine writes its caption. Only `textContent` is ever touched, so it need not be an element. */
-+export type Readout = { textContent: string | null };
-+export type FigureEls = { stage: HTMLElement; svg: SVGSVGElement; read: Readout };
- export type FigureHandle = { set(value: number): void; destroy(): void };
- export type FigureMount = (els: FigureEls, value: number) => FigureHandle;
-
-@@ -40,9 +40,6 @@
- if (parent) parent.appendChild(e);
- return e;
- }
--
--/** querySelector, typed. For elements the markup provides beside the three in FigureEls (Riffle's button). */
--export const $ = <E extends Element = HTMLElement>(sel: string, root: ParentNode = document) => root.querySelector<E>(sel);
-
- /** A solid's two paths in one group: the silhouette (`.sil`) and its crease (`.nf.lo`). */
- export type Solid = { g: SVGGElement; sil: SVGPathElement; cr: SVGPathElement };
-diff --git a/packages/hairline/src/figures/riffle-geometry.ts b/packages/hairline/src/figures/riffle-geometry.ts
---- a/packages/hairline/src/figures/riffle-geometry.ts
-+++ b/packages/hairline/src/figures/riffle-geometry.ts
-@@ -5,13 +5,10 @@
-
- /**
- * Riffle's drawing, with no DOM: the camera, the tray and a card in any pose,
-- * as path strings. The engine (components/hairline/figures/riffle.ts) writes
-- * these into its svg on every frame; the still on /lab
-- * (components/hairline-still.tsx) renders them once, at rest, on the server.
-- * One source, so the card on the index is the figure's own first frame.
-+ * as path strings. The engine (riffle.ts) writes these into its svg on every
-+ * frame.
- */
-
--export const NAMES = ["Radial menu", "Drum", "Dock", "Condense", "Settle", "Upload", "Badge", "Spark"];
- export const N = 8, W = 84, H = 54, G = 13, TW = 22, TH = 7, TABS = [6, 31, 56], TK = 1.4;
- export const REST = -12, BACK = -24, FWD = 20, LIFT = 16;
- export const X0 = -5, X1 = W + 5, Y0 = -9, Y1 = (N - 1) * G + 9, WH = 20, WR = 6, WT = 2.4;
-diff --git a/packages/hairline/src/figures/riffle.ts b/packages/hairline/src/figures/riffle.ts
---- a/packages/hairline/src/figures/riffle.ts
-+++ b/packages/hairline/src/figures/riffle.ts
-@@ -1,27 +1,30 @@
- import { clamp, poly, rad, type Vec2 } from "../core/iso";
- import { tdone, tset, tval, tween, type Tween } from "../core/motion";
--import { BACK, FWD, G, H, LIFT, N, NAMES, REST, W, card, pose, scene, tray } from "./riffle-geometry";
--import { $, disposer, mk, place, pointer, reflect, register, type FigureMount } from "../core/stage";
-+import { BACK, FWD, G, H, LIFT, N, REST, W, card, pose, scene, tray } from "./riffle-geometry";
-+import { disposer, mk, place, pointer, reflect, register, type FigureEls, type FigureHandle } from "../core/stage";
-
- /**
-- * Riffle (Fig 9.1) — a rounded tray holding the lab's eight experiments as
-- * cards. The card under the pointer stands up and lifts; the ones in front
-+ * Riffle (Fig 9.1) — a rounded tray holding eight cards. The card under the pointer stands up and lifts; the ones in front
- * lean forward and the ones behind lean back, staggered outwards from it on
- * the 700ms lift curve. A discrete figure, so every card runs on tweens.
- *
- * Selection never reads the posed cards: it comes from static oblique bands
- * along the resting top edges, so a card moving out from under the pointer
-- * can't flip the choice back and forth. "hit bands" shows them. The stage is
-- * a focusable group; the arrow keys walk the cards and the read-out, which is
-- * aria-live, names the one pulled.
-+ * can't flip the choice back and forth. `bands(true)` shows them. The stage
-+ * is a focusable group; the arrow keys walk the cards and the read-out names
-+ * the one pulled: its number, and its name when `labels` gave it one.
- *
- * The drawing itself — camera, tray, a card in any pose — is pure and lives in
-- * lib/hairline/riffle-geometry.ts, which the still on /lab renders too; this
-- * file is the DOM, the tweens and the input.
-- *
-- * From the study's `#riffle` (design/lab-hairline/cartilha-v2.html).
-+ * riffle-geometry.ts; this file is the DOM, the tweens and the input.
- */
-
-+export type RiffleHandle = FigureHandle & {
-+ /** Shows or hides the hit bands. */
-+ bands(on: boolean): void;
-+ /** Names for the cards, card 01 first. A card without a name is read out by its number alone. */
-+ labels(list: readonly string[]): void;
-+};
-+
- type Card = {
- n: number; t0: number; shape: Vec2[];
- back: SVGPathElement; face: SVGPathElement; head: SVGPathElement; rules: SVGPathElement;
-@@ -30,10 +33,10 @@
- a: Tween; z: Tween;
- };
-
--export const mount: FigureMount = ({ stage, svg, read }, value) => {
-+export const mount = ({ stage, svg, read }: FigureEls, value: number): RiffleHandle => {
- const bag = disposer();
-- const btn = $<HTMLButtonElement>(".hl-act", stage);
- let stag = value;
-+ let names: readonly string[] = [];
-
- const { P, front, outer, inner } = scene();
- const paths = tray(P, front, outer, inner);
-@@ -90,6 +93,11 @@
- bag.add(B.unregister);
-
- let act = -1;
-+ const caption = (a: number) => {
-+ if (a < 0) return "rest";
-+ const n = N - a, name = names[n - 1];
-+ return String(n).padStart(2, "0") + (name ? ` · ${name}` : "");
-+ };
- /** Pulls card a (-1 puts them all back). The stagger spreads out from the card pulled, or the one let go. */
- function setActive(a: number) {
- if (a === act) return;
-@@ -102,7 +110,7 @@
- cd.face.classList.toggle("hi", i === a); cd.head.classList.toggle("hi", i === a); cd.punch[cd.n - 1].classList.toggle("m", i !== a);
- });
- bands.forEach((b, i) => b.classList.toggle("on", i === a));
-- read.textContent = a >= 0 ? `${String(N - a).padStart(2, "0")} · ${NAMES[N - 1 - a]}` : "rest";
-+ read.textContent = caption(a);
- B.wake();
- }
-
-@@ -110,21 +118,16 @@
- bag.on(stage, "keydown", (e) => {
- if (e.key === "ArrowLeft" || e.key === "ArrowDown") { setActive(act < 0 ? N - 1 : Math.min(N - 1, act + 1)); e.preventDefault(); }
- else if (e.key === "ArrowRight" || e.key === "ArrowUp") { setActive(act < 0 ? N - 1 : Math.max(0, act - 1)); e.preventDefault(); }
-- // Escape puts a pulled card back and claims the key; at rest it passes on to
-- // the page's own Escape (components/escape-up.tsx), which leaves for /lab.
-+ // Escape puts a pulled card back and claims the key; at rest it passes on to the page.
- else if (e.key === "Escape" && act >= 0) { setActive(-1); e.preventDefault(); }
- });
- bag.on(stage, "blur", () => setActive(-1));
-- if (btn) {
-- bag.on(btn, "click", () => {
-- const on = btn.getAttribute("aria-pressed") !== "true";
-- btn.setAttribute("aria-pressed", String(on));
-- bandG.classList.toggle("show", on);
-- });
-- // the button outlives the engine (it is React's), so a remount starts with the bands hidden
-- bag.add(() => btn.setAttribute("aria-pressed", "false"));
-- }
- bag.add(() => svg.replaceChildren());
-
-- return { set: (v) => { stag = v; }, destroy: bag.dispose };
-+ return {
-+ set: (v) => { stag = v; },
-+ bands: (on) => { bandG.classList.toggle("show", on); },
-+ labels: (list) => { names = list; if (act >= 0) read.textContent = caption(act); },
-+ destroy: bag.dispose,
-+ };
- };
-```
-
-Run:
-```bash
-cd ~/estudos/hairline
-git apply --check port.patch && git apply port.patch && rm port.patch
-```
-Expected: no output. `git apply --check` fails loudly if a copied file differs from `edfebe9`. In that case, redo Step 3.
-
-- [ ] **Step 5: Turn on the test script for real**
-
-In `packages/hairline/package.json`, change
-`"test": "vitest run --passWithNoTests",`
-to
-`"test": "vitest run",`
-
-- [ ] **Step 6: Run the tests, the typecheck and the build**
-
-Run: `pnpm test && pnpm typecheck && pnpm build`
-Expected: `geometry.test.ts` reports 5 passed, the strict typecheck passes on every copied file, and the build passes. `src/index.ts` is still empty, so `dist` holds no engine yet.
-
-- [ ] **Step 7: Commit**
-
-```bash
-git add packages/hairline/src packages/hairline/test/geometry.test.ts packages/hairline/package.json
-git commit -m "Port: the six engines from lucasmarkes.com at edfebe9, with Riffle's button made methods
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-### Task 5: Option ranges and the clamp
-
-**Files:**
-- Create: `packages/hairline/src/ranges.ts`
-- Test: `packages/hairline/test/ranges.test.ts`
-
-**Interfaces:**
-- Consumes: nothing.
-- Produces, used by `mount.ts` and `index.ts` (Task 6), the site (Task 12) and the README (Task 9):
- - `type Range = { readonly min: number; readonly max: number; readonly step: number; readonly default: number; readonly unit: string }`
- - `const ranges`, typed `as const` with this shape: `{ riffle: { stagger }, terrain: { radius }, exploded: { gap }, phosphor: { afterglow }, slow: { rate }, turntable: { coast } }`. Each value is a `Range`. The values are those in Global Constraints.
- - `number(value: unknown, range: Range): number`. A finite number is clamped and a numeric string is read; anything else becomes the default.
-
-- [ ] **Step 1: Write the failing test**
-
-`packages/hairline/test/ranges.test.ts`
-```ts
-import { describe, expect, it } from "vitest";
-import { number, ranges } from "../src/ranges";
-
-const r = ranges.riffle.stagger; // 0 to 90, default 40
-
-describe("number", () => {
- it("keeps a number inside the range", () => {
- expect(number(60, r)).toBe(60);
- });
- it("clamps to the range", () => {
- expect(number(-5, r)).toBe(0);
- expect(number(500, r)).toBe(90);
- });
- it("reads a numeric string, as an attribute or a form field would give it", () => {
- expect(number("60", r)).toBe(60);
- expect(number(" 500 ", r)).toBe(90);
- });
- it.each([undefined, null, NaN, Infinity, -Infinity, "", " ", "fast", {}, [], true])("falls back to the default for %o", (v) => {
- expect(number(v, r)).toBe(40);
- });
-});
-
-describe("ranges", () => {
- it("has a default inside every range and a positive step", () => {
- for (const figure of Object.values(ranges)) {
- for (const range of Object.values(figure) as Array<(typeof ranges)["riffle"]["stagger"]>) {
- expect(range.min).toBeLessThan(range.max);
- expect(range.default).toBeGreaterThanOrEqual(range.min);
- expect(range.default).toBeLessThanOrEqual(range.max);
- expect(range.step).toBeGreaterThan(0);
- }
- }
- });
-});
-```
-
-- [ ] **Step 2: Run it and see it fail**
-
-Run: `pnpm -C packages/hairline exec vitest run test/ranges.test.ts`
-Expected: FAIL with `Error: Cannot find module '../src/ranges' imported from …/test/ranges.test.ts`.
-
-- [ ] **Step 3: Write the implementation**
-
-`packages/hairline/src/ranges.ts`
-```ts
-/** One numeric option: its bounds, the step a slider should move in, its default and its unit. */
-export type Range = {
- readonly min: number;
- readonly max: number;
- readonly step: number;
- readonly default: number;
- readonly unit: string;
-};
-
-/**
- * Every numeric option of every figure. A figure clamps what it is given to
- * `min`…`max` and falls back to `default`; `step` and `unit` are for whoever
- * builds a slider or a table from this.
- */
-export const ranges = {
- riffle: { stagger: { min: 0, max: 90, step: 5, default: 40, unit: "ms" } },
- terrain: { radius: { min: 1.5, max: 5, step: 0.25, default: 3, unit: "cells" } },
- exploded: { gap: { min: 12, max: 40, step: 1, default: 28, unit: "u" } },
- phosphor: { afterglow: { min: 150, max: 1500, step: 10, default: 520, unit: "ms" } },
- slow: { rate: { min: 0.05, max: 0.6, step: 0.05, default: 0.2, unit: "×" } },
- turntable: { coast: { min: 200, max: 1500, step: 50, default: 650, unit: "ms" } },
-} as const satisfies Record<string, Record<string, Range>>;
-
-/** A number from anything: numeric strings are read, what is not a finite number becomes the default, the rest is clamped. */
-export function number(value: unknown, range: Range): number {
- const n = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
- if (typeof n !== "number" || !Number.isFinite(n)) return range.default;
- return Math.min(range.max, Math.max(range.min, n));
-}
-```
-
-- [ ] **Step 4: Run it and see it pass**
-
-Run: `pnpm -C packages/hairline exec vitest run test/ranges.test.ts && pnpm typecheck`
-Expected: 15 tests pass (four `it`s, and an `it.each` that expands to eleven), and the typecheck passes.
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add packages/hairline/src/ranges.ts packages/hairline/test/ranges.test.ts
-git commit -m "API: option ranges, and a clamp that falls back to the default
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-### Task 6: The vanilla entry: styles, the mount and six functions
-
-**Files:**
-- Create: `packages/hairline/src/core/styles.ts`, `packages/hairline/src/mount.ts`
-- Modify (replace the empty file): `packages/hairline/src/index.ts`
-- Test: `packages/hairline/test/dom.ts` (a test helper), `packages/hairline/test/mount.test.ts`
-
-**Interfaces:**
-- Consumes:
- - From Task 4: `FigureEls`, `FigureHandle`, `Readout`, the six engines' `mount`, and `RiffleHandle.bands` / `.labels`.
- - From Task 5: `ranges`, `Range`, `number`.
-- Produces:
- - `src/core/styles.ts`:
- - `css(lightDark: boolean): string`: the stylesheet.
- - `inject(root: Document | ShadowRoot): void`: once per root, through `adoptedStyleSheets`, or a `<style>` element when constructable sheets are missing.
- - `src/mount.ts`:
- - `type Theme = "auto" | "light" | "dark"`
- - `type BaseOptions = { theme?: Theme; label?: string; onRead?: (text: string) => void }`
- - `type Figure<O> = { update(options: Partial<O>): void; destroy(): void }`
- - `type Spec<O, H> = { id; label; rest; key; range; engine; focusable?; apply? }`
- - `create(spec, el: HTMLElement, options?: O): Figure<O>`
- - `src/index.ts` (entry `.`):
- - Functions: `riffle`, `terrain`, `exploded`, `phosphor`, `slow`, `turntable`, each `(el: HTMLElement, options?: XOptions) => Figure<XOptions>`.
- - Option types: `RiffleOptions`, `TerrainOptions`, `ExplodedOptions`, `PhosphorOptions`, `SlowOptions`, `TurntableOptions`.
- - Re-exports: `ranges`, `Range`, `BaseOptions`, `Figure`, `Theme`.
- - `test/dom.ts`, used again in Task 8:
- - Installs, as a side effect, a fake `IntersectionObserver`, `matchMedia` and a manual `requestAnimationFrame`.
- - Exports `observers: Set<FakeObserver>`, `frames(n?)`, `pending()` and `host(): HTMLDivElement`.
-
-This task holds Review Focus items 1, 2 and 3. Their tests are in `mount.test.ts`:
-- Item 1: "leaves the host's own attributes alone, at mount and at destroy", "does not name an element that aria-labelledby already names", and "drops its own name when the element gains aria-labelledby".
-- Item 2: "reports an onRead that throws and keeps every figure running".
-- Item 3: the "teardown" block.
-
-- [ ] **Step 1: Write the DOM stubs the tests run on**
-
-jsdom has no `IntersectionObserver` or `matchMedia`, and its `requestAnimationFrame` runs on a real timer. These stubs make frames run only when a test asks for them.
-
-`packages/hairline/test/dom.ts`
-```ts
-import { afterEach, beforeEach, vi } from "vitest";
-import { terrain } from "../src/index";
-
-/**
- * What jsdom lacks and the figures need: an IntersectionObserver, matchMedia,
- * and frames that run when the test says so. Import it for the side effect;
- * it installs before each test and puts everything back after.
- */
-
-type Frame = (now: number) => void;
-let queue = new Map<number, Frame>();
-let id = 0;
-let now = 1000;
-
-/** The observers alive right now: one while any figure is mounted, none after the last is destroyed. */
-export const observers = new Set<FakeObserver>();
-
-class FakeObserver {
- targets = new Set<Element>();
- constructor(private cb: IntersectionObserverCallback) { observers.add(this); }
- observe(el: Element) {
- this.targets.add(el);
- this.cb([{ target: el, isIntersecting: true } as IntersectionObserverEntry], this as unknown as IntersectionObserver);
- }
- unobserve(el: Element) { this.targets.delete(el); }
- disconnect() { this.targets.clear(); observers.delete(this); }
-}
-
-/** Runs n frames of 1/60 s. A frame that nobody asked for still moves the clock. */
-export function frames(n = 1) {
- for (let i = 0; i < n; i++) {
- now += 1000 / 60;
- const run = [...queue.values()];
- queue = new Map();
- for (const fn of run) fn(now);
- }
-}
-
-/** How many frames are waiting. Zero means the loop is asleep. */
-export const pending = () => queue.size;
-
-beforeEach(() => {
- queue = new Map(); id = 0; now = 1000;
- vi.stubGlobal("IntersectionObserver", FakeObserver);
- vi.stubGlobal("matchMedia", (query: string) => ({ matches: false, media: query, addEventListener() {}, removeEventListener() {} }));
- vi.stubGlobal("requestAnimationFrame", (fn: Frame) => { queue.set(++id, fn); return id; });
- vi.stubGlobal("cancelAnimationFrame", (n: number) => { queue.delete(n); });
- vi.spyOn(performance, "now").mockImplementation(() => now);
-});
-
-afterEach(() => {
- // the loop is module state: empty it, or the next test starts with this one's figures still in it.
- // Mounting on an element destroys the figure it had.
- for (const el of hosts) terrain(el).destroy();
- hosts = [];
- document.body.replaceChildren();
- vi.unstubAllGlobals();
- vi.restoreAllMocks();
-});
-
-let hosts: HTMLElement[] = [];
-
-/** A host in the document, 400 × 320 at the origin, so a client point is a viewBox point. */
-export function host(): HTMLDivElement {
- const el = document.createElement("div");
- el.getBoundingClientRect = () => ({ left: 0, top: 0, width: 400, height: 320, right: 400, bottom: 320, x: 0, y: 0, toJSON() {} });
- document.body.appendChild(el);
- hosts.push(el);
- return el;
-}
-```
-
-- [ ] **Step 2: Write the failing test**
-
-These are lifecycle layer 3 from the spec. They are the contract of "What a mount does to the element", one test per sentence, plus the three Review Focus items.
-
-`packages/hairline/test/mount.test.ts`
-```ts
-// @vitest-environment jsdom
-import { describe, expect, it, vi } from "vitest";
-import { frames, host, observers, pending } from "./dom";
-import { exploded, phosphor, riffle, slow, terrain, turntable } from "../src/index";
-
-const ALL = { riffle, terrain, exploded, phosphor, slow, turntable };
-const key = (el: Element, k: string) => el.dispatchEvent(new KeyboardEvent("keydown", { key: k, bubbles: true, cancelable: true }));
-
-describe("mount", () => {
- it.each(Object.entries(ALL))("%s draws into the element and takes it all back", (id, mount) => {
- const el = host();
- el.className = "mine";
- const f = mount(el);
- expect(el.getAttribute("data-hairline")).toBe(id);
- expect(el.querySelectorAll(":scope > svg")).toHaveLength(1);
- expect(el.querySelector("svg")!.getAttribute("viewBox")).toBe("0 0 400 320");
- expect(el.querySelector("svg")!.childElementCount).toBeGreaterThan(0);
- expect(el.getAttribute("aria-label")).toBeTruthy();
- f.destroy();
- expect(el.outerHTML).toBe('<div class="mine"></div>');
- });
-
- it("makes Riffle a focusable group with a live region, and the others images", () => {
- const a = host(), b = host();
- riffle(a); terrain(b);
- expect(a.getAttribute("role")).toBe("group");
- expect(a.getAttribute("tabindex")).toBe("0");
- expect(a.querySelector("[data-hairline-live]")!.getAttribute("aria-live")).toBe("polite");
- expect(b.getAttribute("role")).toBe("img");
- expect(b.hasAttribute("tabindex")).toBe(false);
- expect(b.querySelector("[data-hairline-live]")).toBeNull();
- });
-
- it("leaves the host's own attributes alone, at mount and at destroy", () => {
- const el = host();
- el.setAttribute("role", "figure");
- el.setAttribute("tabindex", "-1");
- el.setAttribute("aria-label", "My cards");
- const f = riffle(el, { label: "ignored" });
- expect(el.getAttribute("role")).toBe("figure");
- expect(el.getAttribute("tabindex")).toBe("-1");
- expect(el.getAttribute("aria-label")).toBe("My cards");
- f.destroy();
- expect(el.getAttribute("role")).toBe("figure");
- expect(el.getAttribute("tabindex")).toBe("-1");
- expect(el.getAttribute("aria-label")).toBe("My cards");
- });
-
- it("does not name an element that aria-labelledby already names", () => {
- const el = host();
- el.setAttribute("aria-labelledby", "caption");
- const f = terrain(el);
- expect(el.hasAttribute("aria-label")).toBe(false);
- f.destroy();
- expect(el.getAttribute("aria-labelledby")).toBe("caption");
- });
-
- it("drops its own name when the element gains aria-labelledby", () => {
- const el = host();
- const f = terrain(el);
- el.setAttribute("aria-labelledby", "caption");
- f.update({});
- expect(el.hasAttribute("aria-label")).toBe(false);
- });
-
- it("throws a TypeError for something that is not an element", () => {
- expect(() => riffle(null as unknown as HTMLElement)).toThrow(TypeError);
- expect(() => riffle("#cards" as unknown as HTMLElement)).toThrow(/takes an element/);
- });
-
- it("replaces a figure already on the element", () => {
- const el = host();
- riffle(el);
- terrain(el);
- expect(el.querySelectorAll(":scope > svg")).toHaveLength(1);
- expect(el.getAttribute("data-hairline")).toBe("terrain");
- expect(el.getAttribute("role")).toBe("img");
- expect(el.hasAttribute("tabindex")).toBe(false);
- expect(el.querySelector("[data-hairline-live]")).toBeNull();
- });
-
- it("puts the stylesheet in the document once, however many figures mount", () => {
- riffle(host()); terrain(host()); slow(host());
- const sheets = document.adoptedStyleSheets?.length ?? 0;
- expect(sheets + document.querySelectorAll("style[data-hairline-style]").length).toBe(1);
- });
-});
-
-describe("options", () => {
- it("sets and clears the theme attribute", () => {
- const el = host();
- const f = terrain(el, { theme: "dark" });
- expect(el.getAttribute("data-hairline-theme")).toBe("dark");
- f.update({ theme: "light" });
- expect(el.getAttribute("data-hairline-theme")).toBe("light");
- f.update({ theme: "auto" });
- expect(el.hasAttribute("data-hairline-theme")).toBe(false);
- f.update({ theme: "dark" });
- f.update({ theme: undefined });
- expect(el.hasAttribute("data-hairline-theme")).toBe(false);
- });
-
- it("updates the label, and goes back to the default when it is removed", () => {
- const el = host();
- const f = terrain(el);
- const standard = el.getAttribute("aria-label");
- f.update({ label: "Dunes" });
- expect(el.getAttribute("aria-label")).toBe("Dunes");
- f.update({ label: undefined });
- expect(el.getAttribute("aria-label")).toBe(standard);
- });
-
- // Review Focus 1: a caller without types passes what it has
- it.each(["60", NaN, null, "fast", {}, Infinity])("mounts and updates with %o as the number", (v) => {
- const el = host();
- const bad = v as unknown as number;
- for (const mount of Object.values(ALL)) {
- const f = (mount as (el: HTMLElement, o?: Record<string, unknown>) => { update(o: Record<string, unknown>): void; destroy(): void })(
- el, { stagger: bad, radius: bad, gap: bad, afterglow: bad, rate: bad, coast: bad });
- f.update({ stagger: bad, radius: bad, gap: bad, afterglow: bad, rate: bad, coast: bad });
- frames(3);
- expect(el.querySelector("svg")!.innerHTML).not.toMatch(/NaN|Infinity|undefined/);
- f.destroy();
- }
- });
-
- it("shows Riffle's bands only for true", () => {
- const el = host();
- const f = riffle(el, { bands: true });
- const bands = el.querySelector(".bands")!;
- expect(bands.classList.contains("show")).toBe(true);
- f.update({ bands: "yes" as unknown as boolean });
- expect(bands.classList.contains("show")).toBe(false);
- f.update({ bands: true });
- f.update({ bands: undefined });
- expect(bands.classList.contains("show")).toBe(false);
- });
-});
-
-describe("the caption", () => {
- it("calls onRead once at mount with the rest caption", () => {
- for (const [id, rest] of [["riffle", "rest"], ["terrain", "rest"], ["slow", "rate 1.00×"]] as const) {
- const onRead = vi.fn();
- ALL[id](host(), { onRead });
- expect(onRead.mock.calls).toEqual([[rest]]);
- }
- });
-
- it("does not repeat a caption that has not changed", () => {
- const onRead = vi.fn();
- slow(host(), { onRead });
- frames(30);
- expect(onRead.mock.calls).toEqual([["rate 1.00×"]]);
- });
-
- it("reads a pulled card out by number, and by name when it has one", () => {
- const el = host(), onRead = vi.fn();
- const f = riffle(el, { onRead });
- key(el, "ArrowLeft");
- expect(onRead).toHaveBeenLastCalledWith("01");
- expect(el.querySelector("[data-hairline-live]")!.textContent).toBe("01");
- f.update({ labels: ["Radial menu", "Drum"] });
- expect(onRead).toHaveBeenLastCalledWith("01 · Radial menu");
- key(el, "ArrowRight");
- expect(onRead).toHaveBeenLastCalledWith("02 · Drum");
- key(el, "ArrowRight");
- expect(onRead).toHaveBeenLastCalledWith("03"); // fewer than eight names: the rest go by number
- key(el, "Escape");
- expect(onRead).toHaveBeenLastCalledWith("rest");
- });
-
- it("takes the first eight labels and reads anything that is not a string as no name", () => {
- const el = host(), onRead = vi.fn();
- riffle(el, { onRead, labels: [7, "b", "c", "d", "e", "f", "g", "h", "ninth"] as unknown as string[] });
- key(el, "ArrowLeft");
- expect(onRead).toHaveBeenLastCalledWith("01");
- for (let i = 0; i < 7; i++) key(el, "ArrowRight");
- expect(onRead).toHaveBeenLastCalledWith("08 · h");
- key(el, "ArrowRight");
- expect(onRead).toHaveBeenLastCalledWith("08 · h");
- });
-
- // Review Focus 2: every figure on the page shares one frame loop
- it("reports an onRead that throws and keeps every figure running", () => {
- const reported = vi.fn();
- vi.stubGlobal("reportError", reported);
- const boom = new Error("consumer bug");
- const other = vi.fn();
- const a = host(), b = host();
- expect(() => slow(a, { onRead: () => { throw boom; } })).not.toThrow();
- slow(b, { onRead: other });
- a.dispatchEvent(new MouseEvent("pointermove", { clientX: 200, clientY: 160 }));
- b.dispatchEvent(new MouseEvent("pointermove", { clientX: 200, clientY: 160 }));
- expect(() => frames(120)).not.toThrow();
- expect(reported.mock.calls.length).toBeGreaterThan(1);
- expect(reported).toHaveBeenCalledWith(boom);
- expect(other.mock.calls.length).toBeGreaterThan(1);
- expect(other.mock.calls[other.mock.calls.length - 1][0]).toMatch(/^rate 0\.20×/);
- });
-});
-
-describe("teardown", () => {
- it("destroys twice without complaint", () => {
- const f = riffle(host());
- f.destroy();
- expect(() => f.destroy()).not.toThrow();
- });
-
- // Review Focus 3: a handle kept after its figure is gone
- it("ignores update on a destroyed figure", () => {
- const el = host();
- const f = terrain(el);
- f.destroy();
- f.update({ theme: "dark", label: "late", radius: 5 });
- expect(el.outerHTML).toBe("<div></div>");
- });
-
- it("ignores a stale handle once another figure has taken the element", () => {
- const el = host();
- const old = riffle(el);
- terrain(el);
- old.update({ theme: "dark", label: "late" });
- old.destroy();
- expect(el.getAttribute("data-hairline")).toBe("terrain");
- expect(el.hasAttribute("data-hairline-theme")).toBe(false);
- expect(el.getAttribute("aria-label")).not.toBe("late");
- expect(el.querySelectorAll(":scope > svg")).toHaveLength(1);
- expect(el.querySelector("svg")!.childElementCount).toBeGreaterThan(0);
- });
-
- it("leaves no frame and no observer behind the last figure", () => {
- const a = slow(host()), b = phosphor(host());
- frames(2);
- expect(pending()).toBe(1);
- expect(observers.size).toBe(1);
- a.destroy();
- frames(2);
- expect(pending()).toBe(1);
- b.destroy();
- expect(pending()).toBe(0);
- expect(observers.size).toBe(0);
- });
-
- it("stops listening to the element", () => {
- const el = host(), onRead = vi.fn();
- riffle(el, { onRead }).destroy();
- onRead.mockClear();
- key(el, "ArrowLeft");
- expect(onRead).not.toHaveBeenCalled();
- });
-});
-```
-
-- [ ] **Step 3: Run it and see it fail**
-
-Run: `pnpm -C packages/hairline exec vitest run test/mount.test.ts`
-Expected: FAIL, `Tests 32 failed (32)`. `src/index.ts` exports nothing, so each test fails with a `TypeError` such as `riffle is not a function` or `terrain is not a function`.
-
-- [ ] **Step 4: Write the stylesheet**
-
-The palette values and their order are the spec's theme table. `:where()` keeps every rule at zero specificity.
-
-`packages/hairline/src/core/styles.ts`
-```ts
-/**
- * Hairline — the stylesheet, as a string, and the one function that puts it
- * in a document or a shadow root.
- *
- * Every selector is inside `:where()`, so each rule has zero specificity: a
- * rule of the page's always wins, and between these rules only their order
- * decides. The order below is therefore part of the design. The six
- * `--hairline-*` properties are the public theme; `--hl-*` are private and
- * read them with the palette as the fallback.
- */
-
-const LIGHT = { plate: "#ffffff", hi: "#232327", edge: "#a4a4ac", mid: "#c3c3c9", lo: "#e0e0e4" };
-const DARK = { plate: "#08090a", hi: "#d0d6e0", edge: "#5b5d64", mid: "#3e3e44", lo: "#29292d" };
-const KEYS = ["plate", "hi", "edge", "mid", "lo"] as const;
-type Palette = Record<(typeof KEYS)[number], string>;
-
-const vars = (p: Palette) => KEYS.map((k) => `--hl-${k}:var(--hairline-${k},${p[k]});`).join("");
-const EASE = "cubic-bezier(0.5,0,0.1,1)";
-const SVG = ":where([data-hairline]>svg)";
-
-/** The stylesheet. `lightDark` adds the rule that follows the page's `color-scheme`, for browsers that have `light-dark()`. */
-export function css(lightDark: boolean): string {
- const both = Object.fromEntries(KEYS.map((k) => [k, `light-dark(${LIGHT[k]},${DARK[k]})`])) as Palette;
- return [
- // the box, and the palette: light unless something below says otherwise
- `:where([data-hairline]){display:block;position:relative;aspect-ratio:5/4;touch-action:pan-y;user-select:none;-webkit-user-select:none;--hl-sw:var(--hairline-stroke,0.9);${vars(LIGHT)}}`,
- // the page's color-scheme
- lightDark ? `:where([data-hairline]){${vars(both)}}` : "",
- // an ancestor that says dark
- `:where(.dark,[data-theme="dark"]) :where([data-hairline]){${vars(DARK)}}`,
- // the figure's own theme option
- `:where([data-hairline][data-hairline-theme="light"]){${vars(LIGHT)}}`,
- `:where([data-hairline][data-hairline-theme="dark"]){${vars(DARK)}}`,
- `:where([data-hairline]:focus-visible){outline:1.5px solid var(--hl-hi);outline-offset:2px}`,
- `${SVG}{position:absolute;inset:0;width:100%;height:100%;display:block}`,
- // Riffle's live region: read, not seen
- `:where([data-hairline]>[data-hairline-live]){position:absolute;width:1px;height:1px;margin:-1px;padding:0;border:0;overflow:hidden;clip-path:inset(50%);white-space:nowrap}`,
- // the drawing: plates are filled with the plate colour and painted back to front
- `${SVG} :where(path,polygon,ellipse,line){fill:var(--hl-plate);stroke:var(--hl-mid);stroke-width:var(--hl-sw);vector-effect:non-scaling-stroke;stroke-linejoin:round;stroke-linecap:round;transition:stroke 260ms ${EASE}}`,
- `${SVG} :where(.nf){fill:none}`,
- `${SVG} :where(.fo){stroke:none}`,
- `${SVG} :where(.sil){stroke:var(--hl-edge)}`,
- `${SVG} :where(.hi){stroke:var(--hl-hi)}`,
- `${SVG} :where(.lo){stroke:var(--hl-lo)}`,
- `${SVG} :where(.dash){stroke-dasharray:1 3}`,
- `${SVG} :where(.dot){stroke:none;fill:var(--hl-hi);transition:fill 260ms ${EASE}}`,
- `${SVG} :where(.dot.m){fill:var(--hl-edge)}`,
- `${SVG} :where(.dot.off){fill:var(--hl-lo)}`,
- `${SVG} :where(.ghost path){fill:none;stroke:var(--hl-mid)}`,
- `${SVG} :where(.bands){opacity:0;transition:opacity 240ms ${EASE};pointer-events:none}`,
- `${SVG} :where(.bands.show){opacity:1}`,
- `${SVG} :where(.bands path){fill:none;stroke:var(--hl-mid);stroke-dasharray:2 3}`,
- `${SVG} :where(.bands path.on){stroke:var(--hl-hi);stroke-dasharray:none}`,
- ].join("");
-}
-
-const done = new WeakSet<Document | ShadowRoot>();
-
-/** Puts the stylesheet in a document or a shadow root, once: adopted where that exists, a `<style>` element where it doesn't. */
-export function inject(root: Document | ShadowRoot): void {
- if (done.has(root)) return;
- done.add(root);
- const doc = root.nodeType === 9 ? (root as Document) : (root as ShadowRoot).ownerDocument;
- const win = doc.defaultView;
- const text = css(!!win?.CSS?.supports?.("color", "light-dark(#000,#fff)"));
- if (win && "adoptedStyleSheets" in root) {
- try {
- const sheet = new win.CSSStyleSheet();
- sheet.replaceSync(text);
- root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
- return;
- } catch {
- // no constructable stylesheets here: fall through to an element
- }
- }
- const style = doc.createElement("style");
- style.setAttribute("data-hairline-style", "");
- style.textContent = text;
- (root.nodeType === 9 ? doc.head ?? doc.documentElement : root).appendChild(style);
-}
-```
-
-- [ ] **Step 5: Write the mount**
-
-`create` turns an engine and a `Spec` into a `Figure`:
-- It replaces any figure already on the element.
-- It injects the stylesheet into the element's root.
-- It sets only the attributes the element does not already have.
-- It catches each caption through a `Readout` and passes it to `onRead` when it changes, reporting a throwing `onRead` without stopping the loop.
-- It applies option updates, and on `destroy` takes back exactly what it added.
-
-`packages/hairline/src/mount.ts`
-```ts
-import { inject } from "./core/styles";
-import type { FigureEls, FigureHandle, Readout } from "./core/stage";
-import { number, type Range } from "./ranges";
-
-/**
- * Hairline — the public wrapper around an engine. An engine draws into an svg
- * it is handed and writes its caption to a read-out; this file makes both,
- * dresses the host element, and gives back the two calls a consumer needs.
- *
- * It only ever removes what it added: the svg, the live region, and the
- * attributes the host did not already have.
- */
-
-export type Theme = "auto" | "light" | "dark";
-
-export type BaseOptions = {
- /** `"auto"` follows the page: an ancestor with class `dark` or `data-theme="dark"`, then the page's `color-scheme`. Default `"auto"`. */
- theme?: Theme;
- /** The accessible name. Each figure has a default description in English. */
- label?: string;
- /** The figure's caption, each time it changes. Called once at mount with the rest caption. */
- onRead?: (text: string) => void;
-};
-
-export type Figure<O> = {
- /** Changes options on the running figure. A key set to `undefined` goes back to its default. */
- update(options: Partial<O>): void;
- /** Stops the figure and removes what it added to the element. Safe to call twice. */
- destroy(): void;
-};
-
-/** What a figure is: its engine, the one number it takes, and what it says about itself. */
-export type Spec<O extends BaseOptions, H extends FigureHandle> = {
- id: string;
- /** The default accessible name. */
- label: string;
- /** The caption at rest, for an engine that writes none until it is touched. */
- rest: string;
- /** The numeric option, and its range. */
- key: keyof O & string;
- range: Range;
- engine: (els: FigureEls, value: number) => H;
- /** Operable from the keyboard: a focusable group with a live region, not an image. */
- focusable?: boolean;
- /** Options beyond the number. Runs at mount and after every update; must be safe to repeat. */
- apply?: (engine: H, options: O) => void;
-};
-
-const NS = "http://www.w3.org/2000/svg";
-const mounted = new WeakMap<Element, () => void>();
-
-/** An error from a consumer's callback, reported as uncaught without unwinding the frame loop every figure shares. */
-const report = (err: unknown) => {
- if (typeof reportError === "function") reportError(err);
- else setTimeout(() => { throw err; });
-};
-
-export function create<O extends BaseOptions, H extends FigureHandle>(spec: Spec<O, H>, el: HTMLElement, options?: O): Figure<O> {
- if (typeof document === "undefined") {
- throw new Error(`hairline: ${spec.id}() needs a DOM. Call it in the browser, once the element exists: in an effect, in onMount, or in a script after the element.`);
- }
- if (!el || el.nodeType !== 1) {
- throw new TypeError(`hairline: ${spec.id}() takes an element as its first argument, and got ${el === null ? "null" : typeof el}.`);
- }
- mounted.get(el)?.();
-
- const opts = { ...options } as O;
- const doc = el.ownerDocument;
- const root = el.getRootNode();
- inject(root.nodeType === 9 || "host" in root ? (root as Document | ShadowRoot) : doc);
-
- /* attributes: the host's own are left alone, ours are remembered */
- const owned = new Set<string>();
- const attr = (name: string, value: string | null) => {
- if (!owned.has(name) && el.hasAttribute(name)) return;
- if (value === null) { el.removeAttribute(name); owned.delete(name); }
- else { el.setAttribute(name, value); owned.add(name); }
- };
- const dress = () => {
- attr("data-hairline-theme", opts.theme === "light" || opts.theme === "dark" ? opts.theme : null);
- attr("aria-label", el.hasAttribute("aria-labelledby") ? null : typeof opts.label === "string" ? opts.label : spec.label);
- };
- attr("data-hairline", spec.id);
- attr("role", spec.focusable ? "group" : "img");
- if (spec.focusable) attr("tabindex", "0");
- dress();
-
- const svg = doc.createElementNS(NS, "svg");
- svg.setAttribute("viewBox", "0 0 400 320");
- svg.setAttribute("aria-hidden", "true");
- el.appendChild(svg);
- let live: HTMLElement | null = null;
- if (spec.focusable) {
- live = doc.createElement("span");
- live.setAttribute("data-hairline-live", "");
- live.setAttribute("aria-live", "polite");
- el.appendChild(live);
- }
-
- /* the read-out: engines write it every frame, so only a change goes any further */
- let text: string | null = null;
- const read: Readout = {
- get textContent() { return text; },
- set textContent(value) {
- const next = value ?? "";
- if (next === text) return;
- text = next;
- if (live) live.textContent = next;
- const fn = opts.onRead;
- if (typeof fn === "function") try { fn(next); } catch (err) { report(err); }
- },
- };
-
- let value = number(opts[spec.key], spec.range);
- const engine = spec.engine({ stage: el, svg, read }, value);
- spec.apply?.(engine, opts);
- if (text === null) read.textContent = spec.rest;
-
- let dead = false;
- const destroy = () => {
- if (dead) return;
- dead = true;
- if (mounted.get(el) === destroy) mounted.delete(el);
- engine.destroy();
- svg.remove();
- live?.remove();
- for (const name of owned) el.removeAttribute(name);
- owned.clear();
- };
- mounted.set(el, destroy);
-
- return {
- update(next) {
- if (dead || !next) return;
- for (const k in next) {
- if (next[k] === undefined) delete opts[k];
- else opts[k] = next[k] as O[typeof k];
- }
- const v = number(opts[spec.key], spec.range);
- if (v !== value) { value = v; engine.set(v); }
- dress();
- spec.apply?.(engine, opts);
- },
- destroy,
- };
-}
-```
-
-- [ ] **Step 6: Write the entry**
-
-Each function names its own engine, so importing one figure bundles one engine. The JSDoc on every option gives its unit, range and default, as the spec asks.
-
-`packages/hairline/src/index.ts`
-```ts
-import { create, type BaseOptions, type Figure } from "./mount";
-import { ranges } from "./ranges";
-import { mount as explodedEngine } from "./figures/exploded";
-import { mount as phosphorEngine } from "./figures/phosphor";
-import { mount as riffleEngine } from "./figures/riffle";
-import { mount as slowEngine } from "./figures/slow";
-import { mount as terrainEngine } from "./figures/terrain";
-import { mount as turntableEngine } from "./figures/turntable";
-
-/**
- * @lucasmarkes/hairline — six isometric line figures that answer the pointer.
- *
- * One function per figure. Each takes an element and its own options, draws
- * into the element, and returns `{ update, destroy }`. Each function names
- * its engine itself, so a bundle that imports one figure carries one.
- */
-
-export { ranges, type Range } from "./ranges";
-export type { BaseOptions, Figure, Theme } from "./mount";
-
-export type RiffleOptions = BaseOptions & {
- /** The delay between one card and the next as they lean, in ms. 0 to 90. Default 40. */
- stagger?: number;
- /** Shows the bands the pointer is tested against. Default `false`. */
- bands?: boolean;
- /** Names for the eight cards, card 01 first. A named card is read out as `"03 · Dock"`, an unnamed one as `"03"`. */
- labels?: readonly string[];
-};
-
-export type TerrainOptions = BaseOptions & {
- /** How far the rise reaches around the pointer, in cells. 1.5 to 5. Default 3. */
- radius?: number;
-};
-
-export type ExplodedOptions = BaseOptions & {
- /** The space between two layers when fully open, in viewBox units (the drawing is 400 × 320). 12 to 40. Default 28. */
- gap?: number;
-};
-
-export type PhosphorOptions = BaseOptions & {
- /** How long a painted dot takes to fade, in ms. 150 to 1500. Default 520. */
- afterglow?: number;
-};
-
-export type SlowOptions = BaseOptions & {
- /** The clock's speed while the pointer is over the figure, as a multiple of normal. 0.05 to 0.6. Default 0.2. */
- rate?: number;
-};
-
-export type TurntableOptions = BaseOptions & {
- /** How long a flick keeps the table turning, in ms. 200 to 1500. Default 650. */
- coast?: number;
-};
-
-/** A tray of eight cards. The card under the pointer stands up; the arrow keys walk the cards. */
-export function riffle(el: HTMLElement, options?: RiffleOptions): Figure<RiffleOptions> {
- return create({
- id: "riffle",
- label: "A tray of eight cards. Hover or use the arrow keys to pull a card.",
- rest: "rest",
- key: "stagger",
- range: ranges.riffle.stagger,
- engine: riffleEngine,
- focusable: true,
- apply(engine, o) {
- engine.bands(o.bands === true);
- engine.labels(Array.isArray(o.labels) ? o.labels.slice(0, 8).map((s) => (typeof s === "string" ? s : "")) : []);
- },
- }, el, options);
-}
-
-/** Eighty-one pillars on a plinth that rise around the pointer. */
-export function terrain(el: HTMLElement, options?: TerrainOptions): Figure<TerrainOptions> {
- return create({
- id: "terrain",
- label: "Eighty-one pillars on a plinth that rise around the pointer and rest as a dune with two rises.",
- rest: "rest",
- key: "radius",
- range: ranges.terrain.radius,
- engine: terrainEngine,
- }, el, options);
-}
-
-/** An app window in four layers. Moving across opens the gap; moving down picks a layer. */
-export function exploded(el: HTMLElement, options?: ExplodedOptions): Figure<ExplodedOptions> {
- return create({
- id: "exploded",
- label: "An app window taken apart into four layers. Moving across opens the gap; moving down picks a layer.",
- rest: "",
- key: "gap",
- range: ranges.exploded.gap,
- engine: explodedEngine,
- }, el, options);
-}
-
-/** A seven by seven dot matrix that plays a loop, and fades like phosphor where the pointer paints it. */
-export function phosphor(el: HTMLElement, options?: PhosphorOptions): Figure<PhosphorOptions> {
- return create({
- id: "phosphor",
- label: "A seven by seven dot matrix on a floating tile that plays a loop, and fades like phosphor where you paint it.",
- rest: "loop",
- key: "afterglow",
- range: ranges.phosphor.afterglow,
- engine: phosphorEngine,
- }, el, options);
-}
-
-/** Crates riding a belt through a gate. Hovering slows the clock without stopping it. */
-export function slow(el: HTMLElement, options?: SlowOptions): Figure<SlowOptions> {
- return create({
- id: "slow",
- label: "Crates riding a belt through a gate. Hovering slows the clock without stopping it.",
- rest: "rate 1.00×",
- key: "rate",
- range: ranges.slow.rate,
- engine: slowEngine,
- }, el, options);
-}
-
-/** Blocks on a turntable. A flick across it spins it; it settles on the nearest quarter turn. */
-export function turntable(el: HTMLElement, options?: TurntableOptions): Figure<TurntableOptions> {
- return create({
- id: "turntable",
- label: "Blocks on a turntable. Flick across it to spin it; it settles on the nearest quarter turn.",
- rest: "az 045° · el 30°",
- key: "coast",
- range: ranges.turntable.coast,
- engine: turntableEngine,
- }, el, options);
-}
-```
-
-- [ ] **Step 7: Run the tests and see them pass**
-
-Run: `pnpm test && pnpm typecheck && pnpm build`
-Expected:
-- `geometry`, `ranges` and `mount` all pass.
-- The typecheck passes.
-- `dist/index.js` now exports the six functions and `ranges`.
-
-- [ ] **Step 8: Commit**
-
-```bash
-git add packages/hairline/src packages/hairline/test/dom.ts packages/hairline/test/mount.test.ts
-git commit -m "API: the vanilla entry, six functions over one mount, with styles injected per root
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-### Task 7: Browser tests: parity with the website, behaviour and theme
-
-**Files:**
-- Create: `packages/hairline/playwright.config.ts`
-- Create: `packages/hairline/test/browser/serve.mjs`, `harness.html`, `entry.ts`
-- Test: `packages/hairline/test/browser/parity.spec.ts`, `figures.spec.ts`, `theme.spec.ts`
-- Modify: `.github/workflows/ci.yml` (add the browser step)
-
-**Interfaces:**
-- Consumes:
- - From Task 3: `clock.js`, `play`, `normalise` (inside `play`), `FIGURES`, `OPTION`, `SCRIPTS` and the goldens.
- - From Task 6: the entry `src/index.ts`.
-- Produces:
- - `window.__hl` on the harness page (`http://localhost:4310`):
- - `hairline`: the whole entry.
- - `mount(id, options?, el?)`: records captions.
- - `read()`: the last caption.
- - `reads`: every caption.
- - `figure`: the current handle.
- - `pnpm test:browser` runs these specs. The site adds its own browser specs in Task 12.
-
-This task meets the spec's phase 1 exit criterion: parity for all six figures. Each figure is mounted through the public API and driven by the same script, on the same frozen clock, that captured the goldens. Its SVG must match the website's at every checkpoint, character for character, after `normalise` renumbers the mask and gradient ids. It also holds Review Focus item 5: the last two tests in `figures.spec.ts`.
-
-These tests check code that already exists (Tasks 4–6), so they should pass the first time. A failure here is a bug in the port or the mount: fix the code, never the golden. Step 5 breaks an engine on purpose, to prove that parity can fail.
-
-- [ ] **Step 1: Write the harness**
-
-esbuild bundles the package's source, not `dist`, so the browser tests need no build.
-
-`packages/hairline/playwright.config.ts`
-```ts
-import { defineConfig } from "@playwright/test";
-
-/** Browser tests run in the installed Chrome, against the harness page (test/browser/serve.mjs). */
-export default defineConfig({
- testDir: "test/browser",
- testMatch: "*.spec.ts",
- fullyParallel: true,
- forbidOnly: !!process.env.CI,
- reporter: process.env.CI ? "github" : "list",
- use: {
- baseURL: "http://localhost:4310",
- channel: "chrome",
- viewport: { width: 1200, height: 900 },
- deviceScaleFactor: 1,
- colorScheme: "light",
- },
- webServer: { command: "node test/browser/serve.mjs", url: "http://localhost:4310", reuseExistingServer: !process.env.CI },
-});
-```
-
-`packages/hairline/test/browser/serve.mjs`
-```js
-/**
- * The browser tests' server: the harness page and the package source, bundled
- * by esbuild at start. Playwright starts it (playwright.config.ts).
- */
-import { build } from "esbuild";
-import { readFileSync } from "node:fs";
-import { createServer } from "node:http";
-import { fileURLToPath } from "node:url";
-
-const PORT = 4310;
-const here = (p) => fileURLToPath(new URL(p, import.meta.url));
-
-const bundle = await build({ entryPoints: [here("./entry.ts")], bundle: true, format: "esm", target: "es2020", write: false });
-const routes = {
- "/": ["text/html", readFileSync(here("./harness.html"))],
- "/entry.js": ["text/javascript", bundle.outputFiles[0].contents],
-};
-
-createServer((req, res) => {
- const hit = routes[new URL(req.url, "http://x").pathname];
- if (!hit) { res.writeHead(404).end(); return; }
- res.writeHead(200, { "content-type": `${hit[0]}; charset=utf-8`, "cache-control": "no-store" }).end(hit[1]);
-}).listen(PORT, () => console.log(`harness on http://localhost:${PORT}`));
-```
-
-`packages/hairline/test/browser/harness.html`
-```html
-<!doctype html>
-<html lang="en">
-<head>
-<meta charset="utf-8">
-<title>hairline — test harness</title>
-<link rel="icon" href="data:,">
-<style>
- body { margin: 0; padding: 40px; }
- #host { width: 640px; }
-</style>
-</head>
-<body>
- <div id="host"></div>
- <script type="module" src="/entry.js"></script>
-</body>
-</html>
-```
-
-`packages/hairline/test/browser/entry.ts`
-```ts
-import * as hairline from "../../src/index";
-
-/**
- * The harness page's script: the package, on `window`, with one figure at a
- * time on #host. Tests drive it through page.evaluate.
- */
-type Id = "riffle" | "terrain" | "exploded" | "phosphor" | "slow" | "turntable";
-type Loose = Record<string, unknown>;
-type Mount = (el: HTMLElement, options?: Loose) => { update(o: Loose): void; destroy(): void };
-
-const api = {
- hairline,
- /** Every caption the current figure has written, in order. */
- reads: [] as string[],
- figure: null as ReturnType<Mount> | null,
- /** Mounts a figure on `el` (default #host), recording its captions. */
- mount(id: Id, options: Loose = {}, el: HTMLElement = document.getElementById("host")!) {
- api.reads = [];
- api.figure = (hairline[id] as unknown as Mount)(el, { ...options, onRead: (text: string) => api.reads.push(text) });
- return api.figure;
- },
- read: () => api.reads[api.reads.length - 1] ?? null,
-};
-
-declare global {
- interface Window {
- __hl: typeof api;
- /** test/parity/clock.js, when a test adds it */
- __realTimeout: typeof setTimeout;
- __advance(ms: number): number;
- }
-}
-window.__hl = api;
-```
-
-- [ ] **Step 2: Write the parity test**
-
-`packages/hairline/test/browser/parity.spec.ts`
-```ts
-import { expect, test } from "@playwright/test";
-import { readFileSync } from "node:fs";
-import { play } from "../parity/driver.mjs";
-import { FIGURES, OPTION, SCRIPTS } from "../parity/scripts.mjs";
-
-/**
- * The package draws what the site draws. Each golden is the site's svg at
- * every checkpoint of a pointer script (test/parity/capture.mjs); the same
- * script is played here against the package, on the same virtual clock.
- */
-const file = (p: string) => readFileSync(new URL(p, import.meta.url), "utf8");
-const clock = file("../parity/clock.js") + "\nwindow.__freeze(1000);";
-
-/* The site names its eight cards; the package takes names as an option. */
-const NAMES = ["Radial menu", "Drum", "Dock", "Condense", "Settle", "Upload", "Badge", "Spark"];
-
-type Checkpoint = { at: string; read: string; svg: string };
-
-for (const id of FIGURES as string[]) {
- test(`${id} draws what the site draws`, async ({ context, page }) => {
- const golden = JSON.parse(file(`../parity/golden/${id}.json`)) as { checkpoints: Checkpoint[] };
- const [key, value] = (OPTION as unknown as Record<string, [string, number]>)[id];
- await context.addInitScript(clock);
- await page.goto("/");
- await page.evaluate(([id, labels]) => { window.__hl.mount(id as "riffle", id === "riffle" ? { labels } : {}); }, [id, NAMES] as const);
- const stage = page.locator("#host");
- await stage.locator("svg > *").first().waitFor();
- /* a figure sleeps until its IntersectionObserver reports it on screen, and that report comes on the browser's own time */
- await page.evaluate(() => new Promise((done) => window.__realTimeout(done, 500)));
-
- const got: Checkpoint[] = await play(page, {
- stage,
- snap: () => page.evaluate(() => ({ svg: document.querySelector("#host > svg")!.innerHTML, read: window.__hl.read() })),
- set: () => page.evaluate(([key, value]) => window.__hl.figure!.update({ [key]: value }), [key, value] as const),
- }, (SCRIPTS as Record<string, object[]>)[id]);
-
- expect(got.map((c) => c.at)).toEqual(golden.checkpoints.map((c) => c.at));
- for (const [i, want] of golden.checkpoints.entries()) {
- expect(got[i].read, `caption at "${want.at}"`).toBe(want.read);
- expect(got[i].svg, `drawing at "${want.at}"`).toBe(want.svg);
- }
- });
-}
-```
-
-- [ ] **Step 3: Write the behaviour and theme tests**
-
-`figures.spec.ts` covers the spec's layer 4:
-- Every figure answers the pointer with a clean console.
-- Riffle answers the arrow keys and announces the card.
-- Turntable seats on a quarter turn after a flick.
-- Reduced motion.
-- Review Focus item 5.
-
-`packages/hairline/test/browser/figures.spec.ts`
-```ts
-import { expect, test, type Page } from "@playwright/test";
-
-/** The figures in a real browser: input, focus, reduced motion, shadow roots, a clean console. */
-
-const IDS = ["riffle", "terrain", "exploded", "phosphor", "slow", "turntable"] as const;
-type Id = (typeof IDS)[number];
-
-const mount = (page: Page, id: Id, options: Record<string, unknown> = {}) =>
- page.evaluate(([id, options]) => { window.__hl.mount(id, options); }, [id, options] as const);
-const read = (page: Page) => page.evaluate(() => window.__hl.read());
-/** A pointer event at a point of the 400 × 320 viewBox; no point is a leave. */
-const fire = (page: Page, type: string, pt?: [number, number]) => page.locator("#host").evaluate((el, [type, pt]) => {
- const r = el.getBoundingClientRect();
- el.dispatchEvent(new PointerEvent(type, {
- pointerType: "mouse", pointerId: 1, bubbles: type !== "pointerleave",
- clientX: pt ? r.left + (pt[0] / 400) * r.width : r.left - 40,
- clientY: pt ? r.top + (pt[1] / 320) * r.height : r.top - 40,
- }));
-}, [type, pt] as const);
-
-test.beforeEach(async ({ page }) => { await page.goto("/"); });
-
-test("every figure mounts, answers the pointer and leaves, with nothing on the console", async ({ page }) => {
- const problems: string[] = [];
- page.on("pageerror", (e) => problems.push(String(e)));
- page.on("console", (m) => { if (m.type() === "error" || m.type() === "warning") problems.push(m.text()); });
- for (const id of IDS) {
- await mount(page, id);
- const host = page.locator("#host");
- await expect(host.locator("svg > *").first()).toBeAttached();
- const box = (await host.boundingBox())!;
- expect(box.width / box.height).toBeCloseTo(5 / 4, 2);
- await host.hover({ position: { x: box.width * 0.45, y: box.height * 0.5 } });
- await page.mouse.move(box.x + box.width * 0.6, box.y + box.height * 0.45, { steps: 6 });
- await page.waitForTimeout(150);
- await page.mouse.move(2, 2);
- await page.evaluate(() => window.__hl.figure!.destroy());
- expect(await host.evaluate((el) => el.outerHTML)).toBe('<div id="host"></div>');
- }
- expect(problems).toEqual([]);
-});
-
-test("Riffle walks its cards from the keyboard and says each one in the live region", async ({ page }) => {
- await mount(page, "riffle", { labels: ["Radial menu", "Drum"] });
- const host = page.locator("#host"), live = host.locator("[data-hairline-live]");
- await page.keyboard.press("Tab");
- await expect(host).toBeFocused();
- await page.keyboard.press("ArrowLeft");
- await expect(live).toHaveText("01 · Radial menu");
- await page.keyboard.press("ArrowRight");
- await expect(live).toHaveText("02 · Drum");
- await page.keyboard.press("ArrowRight");
- await expect(live).toHaveText("03");
- await page.keyboard.press("Escape");
- await expect(live).toHaveText("rest");
- await page.keyboard.press("ArrowLeft");
- await host.blur();
- await expect(live).toHaveText("rest");
- /* read, not seen */
- const box = (await live.boundingBox())!;
- expect(box.width).toBeLessThanOrEqual(1);
- expect(box.height).toBeLessThanOrEqual(1);
-});
-
-test("Turntable settles on a quarter turn after a flick", async ({ page }) => {
- await mount(page, "turntable");
- expect(await read(page)).toBe("az 045° · el 30°");
- for (const x of [50, 120, 200, 280, 350]) { await fire(page, "pointermove", [x, 176]); await page.waitForTimeout(16); }
- await fire(page, "pointerleave");
- await expect.poll(() => read(page), { timeout: 8000 }).toMatch(/^az (045|135|225|315)° · el 30°$/);
- const settled = await read(page);
- await page.waitForTimeout(400);
- expect(await read(page)).toBe(settled);
- expect(await page.evaluate(() => window.__hl.reads.length)).toBeGreaterThan(3);
-});
-
-test("under reduced motion the loops hold still", async ({ browser }) => {
- const context = await browser.newContext({ reducedMotion: "reduce" });
- const page = await context.newPage();
- await page.goto("/");
- for (const id of ["phosphor", "slow"] as const) {
- await mount(page, id);
- await page.waitForTimeout(700);
- const a = await page.locator("#host > svg").innerHTML();
- await page.waitForTimeout(500);
- expect(await page.locator("#host > svg").innerHTML(), id).toBe(a);
- }
- await context.close();
-});
-
-test("a figure in a shadow root is styled there, and only there", async ({ page }) => {
- const fill = await page.evaluate(() => {
- const outer = document.createElement("div");
- document.body.append(outer);
- const root = outer.attachShadow({ mode: "open" });
- const el = document.createElement("div");
- el.style.width = "400px";
- root.append(el);
- window.__hl.mount("terrain", { theme: "dark" }, el);
- return {
- fill: getComputedStyle(el.querySelector("svg .sil")!).fill,
- position: getComputedStyle(el).position,
- inShadow: root.adoptedStyleSheets.length,
- inDocument: document.adoptedStyleSheets.length + document.querySelectorAll("style[data-hairline-style]").length,
- };
- });
- expect(fill).toEqual({ fill: "rgb(8, 9, 10)", position: "relative", inShadow: 1, inDocument: 0 });
-});
-
-// Review Focus 5: frameworks build a node first and attach it afterwards
-test("a figure mounted on a detached element is drawn and styled once attached", async ({ page }) => {
- const result = await page.evaluate(async () => {
- const el = document.createElement("div");
- el.style.width = "400px";
- window.__hl.mount("slow", {}, el);
- const before = el.querySelector("svg")!.childElementCount;
- document.body.append(el);
- await new Promise((done) => setTimeout(done, 300));
- const first = el.querySelector("svg")!.innerHTML;
- await new Promise((done) => setTimeout(done, 300));
- return {
- before: before > 0,
- box: [el.offsetWidth, el.offsetHeight],
- fill: getComputedStyle(el.querySelector("svg .sil")!).fill,
- running: el.querySelector("svg")!.innerHTML !== first,
- };
- });
- expect(result).toEqual({ before: true, box: [400, 320], fill: "rgb(255, 255, 255)", running: true });
-});
-```
-
-`theme.spec.ts` covers the four palette rules, in order, plus the two fallbacks the spec's risk table names: no `adoptedStyleSheets`, and no `light-dark()`.
-
-`packages/hairline/test/browser/theme.spec.ts`
-```ts
-import { expect, test, type Page } from "@playwright/test";
-
-/**
- * The palette rules, in the order the stylesheet applies them: the `theme`
- * option, an ancestor that says dark, the page's color-scheme, light. Read
- * off a real computed style: the plate colour a silhouette is filled with.
- */
-const LIGHT = "rgb(255, 255, 255)", DARK = "rgb(8, 9, 10)";
-
-const plate = (page: Page) => page.evaluate(() => getComputedStyle(document.querySelector("#host svg .sil")!).fill);
-const mount = (page: Page, options: Record<string, unknown> = {}) =>
- page.evaluate((options) => { window.__hl.mount("terrain", options); }, options);
-
-test.beforeEach(async ({ page }) => { await page.goto("/"); });
-
-test("light when nothing says otherwise", async ({ page }) => {
- await mount(page);
- expect(await plate(page)).toBe(LIGHT);
-});
-
-test("follows the page's color-scheme", async ({ page }) => {
- await mount(page);
- await page.evaluate(() => { document.documentElement.style.colorScheme = "dark"; });
- expect(await plate(page)).toBe(DARK);
- await page.evaluate(() => { document.documentElement.style.colorScheme = "light dark"; });
- expect(await plate(page)).toBe(LIGHT);
- await page.emulateMedia({ colorScheme: "dark" });
- expect(await plate(page)).toBe(DARK);
-});
-
-test("an ancestor with class dark or data-theme=dark wins over the color-scheme", async ({ page }) => {
- await mount(page);
- await page.evaluate(() => { document.documentElement.style.colorScheme = "light"; document.body.className = "dark"; });
- expect(await plate(page)).toBe(DARK);
- await page.evaluate(() => { document.body.className = ""; document.documentElement.dataset.theme = "dark"; });
- expect(await plate(page)).toBe(DARK);
-});
-
-test("the theme option wins over both", async ({ page }) => {
- await page.evaluate(() => { document.body.className = "dark"; document.documentElement.style.colorScheme = "dark"; });
- await mount(page, { theme: "light" });
- expect(await plate(page)).toBe(LIGHT);
- await page.evaluate(() => window.__hl.figure!.update({ theme: "dark" }));
- await page.evaluate(() => { document.body.className = ""; document.documentElement.style.colorScheme = "light"; });
- expect(await plate(page)).toBe(DARK);
- await page.evaluate(() => window.__hl.figure!.update({ theme: "auto" }));
- expect(await plate(page)).toBe(LIGHT);
-});
-
-test("a --hairline-* property wins over every palette, and a page rule over the stylesheet", async ({ page }) => {
- await mount(page, { theme: "dark" });
- await page.addStyleTag({ content: "#host { --hairline-plate: rgb(1, 2, 3); --hairline-stroke: 2; } [data-hairline] { aspect-ratio: 1; }" });
- expect(await plate(page)).toBe("rgb(1, 2, 3)");
- expect(await page.evaluate(() => getComputedStyle(document.querySelector("#host svg .sil")!).strokeWidth)).toBe("2px");
- const box = (await page.locator("#host").boundingBox())!;
- expect(box.width).toBe(box.height);
-});
-
-test("without constructable stylesheets it falls back to a style element", async ({ context, page }) => {
- await context.addInitScript(() => { delete (Document.prototype as { adoptedStyleSheets?: unknown }).adoptedStyleSheets; });
- await page.goto("/");
- await mount(page, { theme: "dark" });
- await mount(page, { theme: "dark" });
- expect(await page.locator("style[data-hairline-style]").count()).toBe(1);
- expect(await plate(page)).toBe(DARK);
-});
-
-test("without light-dark() it stays light under a dark color-scheme, and the class still works", async ({ context, page }) => {
- await context.addInitScript(() => {
- const supports = CSS.supports.bind(CSS);
- CSS.supports = ((a: string, b?: string) => (String(b ?? a).includes("light-dark") ? false : b === undefined ? supports(a) : supports(a, b))) as typeof CSS.supports;
- });
- await page.goto("/");
- await mount(page);
- await page.evaluate(() => { document.documentElement.style.colorScheme = "dark"; });
- expect(await plate(page)).toBe(LIGHT);
- await page.evaluate(() => { document.body.className = "dark"; });
- expect(await plate(page)).toBe(DARK);
-});
-```
-
-- [ ] **Step 4: Run them**
-
-Run: `pnpm -C packages/hairline test:browser`
-Expected: 19 passed: 6 parity, 6 figures, 7 theme.
-
-- [ ] **Step 5: Prove that parity can fail**
-
-In `packages/hairline/src/figures/turntable-geometry.ts`, change `export const HOME = 45;` to `export const HOME = 46;`.
-
-Run: `pnpm -C packages/hairline exec playwright test parity -g turntable`
-Expected: FAIL. The svg at the first checkpoint differs from the golden.
-
-Revert the change, and confirm the file matches the commit: `git diff --exit-code packages/hairline/src` exits 0.
-
-- [ ] **Step 6: Add the browser tests to CI**
-
-This is CI with the browser step. Task 9 adds the static release gate.
-
-`.github/workflows/ci.yml`
-```yaml
-name: CI
-
-on:
- push:
- branches: [main]
- pull_request:
-
-# A newer push to the same branch or PR cancels the run in flight.
-concurrency:
- group: ci-${{ github.ref }}
- cancel-in-progress: true
-
-permissions:
- contents: read
-
-jobs:
- verify:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v7
-
- # Corepack activates the pnpm pinned in package.json's packageManager.
- - name: Enable Corepack
- run: corepack enable
-
- - uses: actions/setup-node@v7
- with:
- node-version: 22
- cache: pnpm
-
- - name: Install
- run: pnpm install --frozen-lockfile
-
- - name: Build
- run: pnpm build
-
- - name: Typecheck
- run: pnpm typecheck
-
- - name: Unit and component tests
- run: pnpm test
-
- # The browser tests drive the Chrome that ubuntu-latest ships
- # (playwright.config.ts sets channel: "chrome"), so nothing is downloaded.
- - name: Browser tests
- run: pnpm test:browser
-
-```
-
-- [ ] **Step 7: Commit and push**
-
-```bash
-git add packages/hairline/playwright.config.ts packages/hairline/test/browser .github/workflows/ci.yml
-git commit -m "Tests: parity with lucasmarkes.com for all six figures, behaviour and theme in Chrome
-
-Co-Authored-By: Claude <[email protected]>"
-git push
-gh run watch --exit-status "$(gh run list --workflow CI --limit 1 --json databaseId --jq '.[0].databaseId')"
-```
-Expected: CI passes, including "Browser tests". It runs on ubuntu-latest's own Chrome, so nothing is downloaded.
-
-If parity passes locally but fails in CI, stop and report the diff to Lucas. Never re-capture or edit a golden to make CI pass: a figure that draws differently on Linux is a finding, not noise.
-
-### Task 8: The React entry
-
-**Files:**
-- Create: `packages/hairline/src/react.tsx`
-- Modify (replace): `packages/hairline/tsup.config.ts`
-- Test: `packages/hairline/test/react.test.tsx`, `packages/hairline/test/ssr.test.tsx`, `packages/hairline/test/types.test-d.tsx`
-
-**Interfaces:**
-- Consumes:
- - From Task 6: the six functions and six option types from `./index`.
- - From Task 6's tests: `test/dom.ts` (`observers`, `pending`).
-- Produces, the entry `./react`:
- - `type FigureProps<O> = O & Omit<ComponentPropsWithoutRef<"div">, "children" | keyof O>`
- - `type FigureComponent<O> = ForwardRefExoticComponent<FigureProps<O> & RefAttributes<HTMLDivElement>>`
- - The components `Riffle`, `Terrain`, `Exploded`, `Phosphor`, `Slow` and `Turntable`.
- - The types `RiffleProps`, `TerrainProps`, `ExplodedProps`, `PhosphorProps`, `SlowProps` and `TurntableProps`.
- - `dist/react.js`: starts with `"use client";` and imports the core from `"@lucasmarkes/hairline"`. Task 9's tarball gate checks both.
-
-This task holds Review Focus item 4, in `react.test.tsx`: "does not remount, and does not loop, on an inline onRead and inline labels" and "calls a state setter from onRead without looping". `ssr.test.tsx` runs with no DOM at all; it is the spec's `renderToString` check. `types.test-d.tsx` is layer 5: `pnpm typecheck` compiles it, and each `@ts-expect-error` must stay an error.
-
-- [ ] **Step 1: Write the failing tests**
-
-`packages/hairline/test/react.test.tsx`
-```tsx
-// @vitest-environment jsdom
-import { StrictMode, createRef } from "react";
-import { cleanup, render } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { observers, pending } from "./dom";
-import { Exploded, Phosphor, Riffle, Slow, Terrain, Turntable } from "../src/react";
-
-afterEach(cleanup);
-
-const key = (el: Element, k: string) => el.dispatchEvent(new KeyboardEvent("keydown", { key: k, bubbles: true, cancelable: true }));
-
-describe("components", () => {
- it("renders each figure into one div", () => {
- const { container } = render(<><Riffle /><Terrain /><Exploded /><Phosphor /><Slow /><Turntable /></>);
- const ids = [...container.children].map((el) => el.getAttribute("data-hairline"));
- expect(ids).toEqual(["riffle", "terrain", "exploded", "phosphor", "slow", "turntable"]);
- for (const el of container.children) expect(el.querySelectorAll(":scope > svg")).toHaveLength(1);
- });
-
- it("passes div attributes through, forwards the ref, and keeps the options off the DOM", () => {
- const ref = createRef<HTMLDivElement>();
- const { container } = render(<Riffle ref={ref} id="cards" className="w-80" data-x="1" style={{ width: 320 }} stagger={60} bands labels={["a"]} theme="dark" />);
- const el = container.firstElementChild as HTMLDivElement;
- expect(ref.current).toBe(el);
- expect(el.id).toBe("cards");
- expect(el.className).toBe("w-80");
- expect(el.getAttribute("data-x")).toBe("1");
- expect(el.style.width).toBe("320px");
- expect(el.style.aspectRatio).toBe("5 / 4");
- for (const name of ["stagger", "bands", "labels", "theme", "onread"]) expect(el.hasAttribute(name)).toBe(false);
- expect(el.getAttribute("data-hairline-theme")).toBe("dark");
- expect(el.querySelector(".bands")!.classList.contains("show")).toBe(true);
- });
-
- it("lets the style prop override the aspect ratio", () => {
- const { container } = render(<Terrain style={{ aspectRatio: "1 / 1" }} />);
- expect((container.firstElementChild as HTMLElement).style.aspectRatio).toBe("1 / 1");
- });
-
- it("uses the label prop, and aria-label when the caller sets that instead", () => {
- const { container, rerender } = render(<Terrain label="Dunes" />);
- const el = container.firstElementChild!;
- expect(el.getAttribute("aria-label")).toBe("Dunes");
- rerender(<Terrain aria-label="Hills" />);
- expect(el.getAttribute("aria-label")).toBe("Hills");
- });
-
- it("updates the running figure when a prop changes, without remounting", () => {
- const { container, rerender } = render(<Riffle theme="dark" />);
- const el = container.firstElementChild!, svg = el.querySelector("svg");
- rerender(<Riffle theme="light" bands />);
- expect(el.getAttribute("data-hairline-theme")).toBe("light");
- expect(el.querySelector(".bands")!.classList.contains("show")).toBe(true);
- rerender(<Riffle />);
- expect(el.hasAttribute("data-hairline-theme")).toBe(false);
- expect(el.querySelector(".bands")!.classList.contains("show")).toBe(false);
- expect(el.querySelector("svg")).toBe(svg);
- });
-
- // Review Focus 4: a function or an array written inline is new on every render
- it("does not remount, and does not loop, on an inline onRead and inline labels", () => {
- const seen: string[] = [];
- let renders = 0;
- function App({ n }: { n: number }) {
- renders++;
- return <Riffle data-n={n} labels={["Radial menu", "Drum"]} onRead={(t) => seen.push(`${n}:${t}`)} />;
- }
- const { container, rerender } = render(<App n={1} />);
- const el = container.firstElementChild!, svg = el.querySelector("svg");
- rerender(<App n={2} />);
- rerender(<App n={3} />);
- expect(renders).toBe(3);
- expect(el.querySelector("svg")).toBe(svg);
- key(el, "ArrowLeft");
- // one call at mount, and the latest function is the one called afterwards
- expect(seen).toEqual(["1:rest", "3:01 · Radial menu"]);
- });
-
- it("calls a state setter from onRead without looping", () => {
- const onRead = vi.fn();
- const { container } = render(<Slow onRead={onRead} />);
- expect(onRead.mock.calls).toEqual([["rate 1.00×"]]);
- expect(container.firstElementChild!.querySelectorAll("svg")).toHaveLength(1);
- });
-
- it("survives StrictMode's double mount with one drawing", () => {
- const onRead = vi.fn();
- const { container } = render(<StrictMode><Riffle onRead={onRead} /></StrictMode>);
- const el = container.firstElementChild!;
- expect(el.querySelectorAll(":scope > svg")).toHaveLength(1);
- expect(el.querySelectorAll("[data-hairline-live]")).toHaveLength(1);
- expect(observers.size).toBe(1);
- key(el, "ArrowLeft");
- expect(onRead).toHaveBeenLastCalledWith("01");
- });
-
- it("cleans up on unmount", () => {
- const { container, unmount } = render(<><Slow /><Phosphor /></>);
- expect(container.querySelectorAll("svg")).toHaveLength(2);
- unmount();
- expect(pending()).toBe(0);
- expect(observers.size).toBe(0);
- });
-
- it("names the components for the dev tools", () => {
- expect([Riffle, Terrain, Exploded, Phosphor, Slow, Turntable].map((c) => c.displayName))
- .toEqual(["Riffle", "Terrain", "Exploded", "Phosphor", "Slow", "Turntable"]);
- });
-});
-```
-
-`packages/hairline/test/ssr.test.tsx`
-```tsx
-import { createElement } from "react";
-import { renderToString } from "react-dom/server";
-import { describe, expect, it } from "vitest";
-
-/* No DOM here on purpose: this is what a server sees. */
-describe("on the server", () => {
- it("imports both entries without touching a DOM", async () => {
- expect(typeof document).toBe("undefined");
- expect(typeof window).toBe("undefined");
- await expect(import("../src/index")).resolves.toBeTypeOf("object");
- await expect(import("../src/react")).resolves.toBeTypeOf("object");
- });
-
- it("renders a component as an empty box of the right shape", async () => {
- const { Riffle } = await import("../src/react");
- const html = renderToString(createElement(Riffle, { className: "w-80", stagger: 60, labels: ["a"], onRead() {} }));
- expect(html).toBe('<div class="w-80" style="aspect-ratio:5 / 4"></div>');
- });
-
- it("says what is wrong when a figure is mounted without a DOM", async () => {
- const { riffle } = await import("../src/index");
- expect(() => riffle({} as HTMLElement)).toThrow(/needs a DOM/);
- });
-});
-```
-
-`packages/hairline/test/types.test-d.tsx`
-```tsx
-/**
- * Type tests. Nothing here runs: `pnpm typecheck` compiles this file, and an
- * `@ts-expect-error` line fails the build if the line below it stops being
- * an error. Vitest does not pick it up (it is not a `.test.` file).
- */
-import { createRef } from "react";
-import { exploded, ranges, riffle, slow, terrain, type Figure, type RiffleOptions } from "../src/index";
-import { Riffle, Terrain, Turntable, type RiffleProps } from "../src/react";
-
-declare const el: HTMLElement;
-type Equal<A, B> = (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;
-const yes = <T extends true>() => {};
-
-/* each figure takes its own option and no other's */
-riffle(el, { stagger: 60, bands: true, labels: ["a", "b"], theme: "dark", label: "Cards", onRead: (t: string) => t });
-terrain(el, { radius: 4 });
-riffle(el);
-// @ts-expect-error radius is Terrain's
-riffle(el, { radius: 4 });
-// @ts-expect-error stagger is Riffle's
-terrain(el, { stagger: 60 });
-// @ts-expect-error a number, not a string
-slow(el, { rate: "0.4" });
-// @ts-expect-error not a theme
-exploded(el, { theme: "sepia" });
-// @ts-expect-error the element is required
-riffle();
-
-/* the handle */
-const f = riffle(el);
-yes<Equal<typeof f, Figure<RiffleOptions>>>();
-f.update({ stagger: undefined, labels: ["a"] as const });
-f.destroy();
-// @ts-expect-error update takes Riffle's options
-f.update({ radius: 4 });
-/* ranges is literal, so a slider built from it is typed */
-yes<Equal<(typeof ranges)["riffle"]["stagger"]["default"], 40>>();
-yes<Equal<keyof typeof ranges, "riffle" | "terrain" | "exploded" | "phosphor" | "slow" | "turntable">>();
-// @ts-expect-error read-only
-ranges.riffle.stagger.max = 100;
-
-/* components: the options, plus what a div takes */
-const ref = createRef<HTMLDivElement>();
-<Riffle ref={ref} stagger={60} bands labels={["a"]} className="w-80" id="cards" onClick={() => {}} onRead={(text) => text.length} />;
-<Terrain radius={4} style={{ width: 320 }} aria-label="Dunes" data-x="1" />;
-<Turntable />;
-// @ts-expect-error radius is Terrain's
-<Riffle radius={4} />;
-// @ts-expect-error a number, not a string
-<Terrain radius="4" />;
-// @ts-expect-error a figure has no children
-<Riffle>text</Riffle>;
-// @ts-expect-error the ref is to a div
-<Riffle ref={createRef<HTMLSpanElement>()} />;
-const props: RiffleProps = { stagger: 60, className: "w-80" };
-void props;
-```
-
-- [ ] **Step 2: Run them and see them fail**
-
-Run: `pnpm -C packages/hairline exec vitest run test/react.test.tsx test/ssr.test.tsx; pnpm typecheck`
-Expected:
-- Vitest fails with `Failed to resolve import "../src/react"`.
-- `tsc` fails with `Cannot find module '../src/react'` in `types.test-d.tsx`.
-
-- [ ] **Step 3: Write the components**
-
-Each component is one `<div>` with an inline `aspect-ratio`:
-- The figure is mounted in a layout effect, and only when the component mounts.
-- A changed option is passed on as `update`.
-- `onRead` and `labels` are read through refs, so a new function or array on every render neither remounts the figure nor loops.
-
-`packages/hairline/src/react.tsx`
-```tsx
-import {
- forwardRef, useCallback, useEffect, useLayoutEffect, useRef,
- type ComponentPropsWithoutRef, type ForwardRefExoticComponent, type RefAttributes,
-} from "react";
-import {
- exploded, phosphor, riffle, slow, terrain, turntable,
- type BaseOptions, type ExplodedOptions, type Figure, type PhosphorOptions, type RiffleOptions,
- type SlowOptions, type TerrainOptions, type TurntableOptions,
-} from "./index";
-
-/**
- * @lucasmarkes/hairline/react — the six figures as components.
- *
- * A component renders one empty `<div>` and mounts the figure on it in a
- * layout effect, so on the server the box is there and the drawing is not.
- * It mounts once: a changed option reaches the running figure as `update`,
- * and `onRead` is called through a ref, so an inline function never remounts.
- */
-
-/** A figure's options, plus every `<div>` attribute except `children`. */
-export type FigureProps<O> = O & Omit<ComponentPropsWithoutRef<"div">, "children" | keyof O>;
-export type FigureComponent<O> = ForwardRefExoticComponent<FigureProps<O> & RefAttributes<HTMLDivElement>>;
-
-type Loose = Record<string, unknown>;
-
-const useIsoLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
-
-function make<O extends BaseOptions>(
- name: string,
- mount: (el: HTMLElement, options?: O) => Figure<O>,
- keys: readonly (keyof O & string)[],
-): FigureComponent<O> {
- /* the body is typed loosely and the signature strictly: O is generic here, and a props type built from it does not resolve inside */
- const Component = forwardRef<HTMLDivElement, Loose>(function Hairline(props, ref) {
- /* the figure's options out of the props; every key is present, so one that was removed resets */
- const options: Loose = {};
- const rest: Loose = {};
- for (const k in props) if (!(keys as readonly string[]).includes(k) && k !== "onRead") rest[k] = props[k];
- for (const k of keys) options[k] = props[k];
- /* aria-label stays on the div and is the figure's label too, so the two never disagree about the name */
- if (options.label === undefined) options.label = props["aria-label"];
-
- const el = useRef<HTMLDivElement | null>(null);
- const figure = useRef<Figure<O> | null>(null);
- const onRead = useRef(props.onRead as BaseOptions["onRead"]);
- const set = useCallback((node: HTMLDivElement | null) => {
- el.current = node;
- if (typeof ref === "function") ref(node);
- else if (ref) ref.current = node;
- }, [ref]);
-
- useIsoLayoutEffect(() => { onRead.current = props.onRead as BaseOptions["onRead"]; });
-
- useIsoLayoutEffect(() => {
- const f = mount(el.current!, { ...options, onRead: (text: string) => onRead.current?.(text) } as O);
- figure.current = f;
- return () => { f.destroy(); figure.current = null; };
- // mounts once; options reach the figure through the effect below
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
- /* an array made inline is new on every render: compare what is in it */
- const deps = keys.map((k) => { const v = options[k]; return Array.isArray(v) ? v.join("\u0000") : v; });
- useIsoLayoutEffect(() => { figure.current?.update(options as Partial<O>); }, deps); // eslint-disable-line react-hooks/exhaustive-deps
-
- const { style, ...attrs } = rest as ComponentPropsWithoutRef<"div">;
- return <div {...attrs} ref={set} style={{ aspectRatio: "5 / 4", ...style }} />;
- });
- Component.displayName = name;
- return Component as unknown as FigureComponent<O>;
-}
-
-const BASE = ["theme", "label"] as const;
-
-/** A tray of eight cards. The card under the pointer stands up; the arrow keys walk the cards. */
-export const Riffle = make<RiffleOptions>("Riffle", riffle, [...BASE, "stagger", "bands", "labels"]);
-/** Eighty-one pillars on a plinth that rise around the pointer. */
-export const Terrain = make<TerrainOptions>("Terrain", terrain, [...BASE, "radius"]);
-/** An app window in four layers. Moving across opens the gap; moving down picks a layer. */
-export const Exploded = make<ExplodedOptions>("Exploded", exploded, [...BASE, "gap"]);
-/** A seven by seven dot matrix that plays a loop, and fades like phosphor where the pointer paints it. */
-export const Phosphor = make<PhosphorOptions>("Phosphor", phosphor, [...BASE, "afterglow"]);
-/** Crates riding a belt through a gate. Hovering slows the clock without stopping it. */
-export const Slow = make<SlowOptions>("Slow", slow, [...BASE, "rate"]);
-/** Blocks on a turntable. A flick across it spins it; it settles on the nearest quarter turn. */
-export const Turntable = make<TurntableOptions>("Turntable", turntable, [...BASE, "coast"]);
-
-export type RiffleProps = FigureProps<RiffleOptions>;
-export type TerrainProps = FigureProps<TerrainOptions>;
-export type ExplodedProps = FigureProps<ExplodedOptions>;
-export type PhosphorProps = FigureProps<PhosphorOptions>;
-export type SlowProps = FigureProps<SlowOptions>;
-export type TurntableProps = FigureProps<TurntableOptions>;
-```
-
-- [ ] **Step 4: Build the React entry against the core by package name**
-
-`packages/hairline/tsup.config.ts`
-```ts
-import { defineConfig, type Options } from "tsup";
-
-const shared = { format: ["esm"], target: "es2020", dts: true, sourcemap: true } satisfies Options;
-
-/**
- * The React entry imports the figures from "./index" in source, so types and
- * tests need no build. In the bundle that import becomes the package's own
- * name and stays external: both entries then run on one copy of the core, and
- * so on one frame loop.
- */
-const self: NonNullable<Options["esbuildPlugins"]>[number] = {
- name: "core-by-package-name",
- setup(build) {
- build.onResolve({ filter: /^\.\/index$/ }, () => ({ path: "@lucasmarkes/hairline", external: true }));
- },
-};
-
-export default defineConfig([
- { ...shared, entry: ["src/index.ts"] },
- { ...shared, entry: ["src/react.tsx"], external: ["react"], esbuildPlugins: [self], banner: { js: '"use client";' } },
-]);
-```
-
-- [ ] **Step 5: Run the tests and see them pass**
-
-Run: `pnpm test && pnpm typecheck && pnpm build`
-Expected: every Vitest file passes (geometry, ranges, mount, react, ssr), and the typecheck passes, type tests included.
-
-- [ ] **Step 6: Check the built entry**
-
-Run:
-```bash
-cd packages/hairline
-head -c 14 dist/react.js; echo
-grep -c 'from "@lucasmarkes/hairline"' dist/react.js
-grep -c IntersectionObserver dist/react.js || true
-```
-Expected, in order:
-- `"use client";`
-- `1`: one import of the core, by its package name.
-- `0`: no copy of the frame loop in the React entry.
-
-- [ ] **Step 7: Commit**
-
-```bash
-cd ~/estudos/hairline
-git add packages/hairline/src/react.tsx packages/hairline/tsup.config.ts packages/hairline/test
-git commit -m "API: the React entry, a client module that shares the core's frame loop
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-### Task 9: The release gate, the README and CONTRIBUTING
-
-**Files:**
-- Create: `scripts/release.mjs`, `CONTRIBUTING.md`, `assets/hero.gif`
-- Modify (replace the stub): `README.md`
-- Modify: `.github/workflows/ci.yml` (add the static release gate; the file is final after this)
-
-**Interfaces:**
-- Consumes: the built package from Tasks 6–8, and the `size-limit` budgets in `packages/hairline/package.json` (Task 1).
-- Produces:
- - `pnpm run release`: everything.
- - `pnpm run release --static`: no network.
-
- Both print `✓`/`✗` lines and exit 1 on any failure. The full gate calls `node scripts/consumers.mjs` (Task 11), and `node registry/build.mjs` and `node registry/validate.mjs` (Task 10). Until those exist, run only `--static`.
-
- The package's `prepack` copies the root `README.md` and `LICENSE` into `packages/hairline`. Both copies are git-ignored.
-
-The gate is the spec's "Package gates":
-- publint, attw with the ESM-only profile, and the size budgets.
-- A tarball inspection: what ships, no `workspace:` range, no dependencies, `"use client"`, the core imported by package name, and a real README.
-
-- [ ] **Step 1: Write the gate**
-
-`scripts/release.mjs`
-```js
-#!/usr/bin/env node
-/**
- * The release gate. Builds, tests, lints the package, packs it with pnpm and
- * inspects the tarball, then installs that tarball in the consumer fixtures.
- * It never publishes: publishing is .github/workflows/publish.yml, on a tag.
- *
- * pnpm release everything
- * pnpm release --static what needs no network: CI runs this on every push.
- * Skips the consumer fixtures (they install from npm)
- * and the registry checks (they need npm auth).
- */
-import { execFileSync } from "node:child_process";
-import { mkdtempSync, readdirSync, rmSync } from "node:fs";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-
-const PKG = "packages/hairline";
-const NAME = "@lucasmarkes/hairline";
-const STATIC = process.argv.includes("--static");
-
-let failures = 0;
-const fail = (msg) => { failures++; console.error(` ✗ ${msg}`); };
-const pass = (msg) => console.log(` ✓ ${msg}`);
-const note = (msg) => console.log(` – ${msg}`);
-const check = (ok, good, bad) => (ok ? pass(good) : fail(bad));
-const run = (cmd, args, opts = {}) => execFileSync(cmd, args, { encoding: "utf8", stdio: "pipe", ...opts });
-/** Runs a step and reports it; on failure prints the end of what the command said. */
-function step(label, cmd, args, opts) {
- try { run(cmd, args, opts); pass(label); return true; }
- catch (err) { fail(`${label}\n${String((err.stdout ?? "") + (err.stderr ?? "") || err.message).trim().split("\n").slice(-30).join("\n")}`); return false; }
-}
-
-console.log("\n▸ runner");
-const agent = process.env.npm_config_user_agent ?? "";
-check(agent.startsWith("pnpm"), "running under pnpm", "not running under pnpm. Use `pnpm release`: only pnpm rewrites workspace: ranges when it packs.");
-
-console.log("\n▸ build, typecheck, test");
-step("build", "pnpm", ["-w", "build"]);
-step("typecheck (includes the type tests)", "pnpm", ["-w", "typecheck"]);
-step("unit and component tests", "pnpm", ["-w", "test"]);
-step("browser tests (includes parity with the site)", "pnpm", ["-w", "test:browser"]);
-
-console.log("\n▸ package");
-step("publint --strict", "pnpm", ["exec", "publint", "--strict"], { cwd: PKG });
-step("are the types wrong (esm-only)", "pnpm", ["exec", "attw", "--pack", ".", "--profile", "esm-only"], { cwd: PKG });
-step("size budgets", "pnpm", ["exec", "size-limit"], { cwd: PKG });
-
-console.log("\n▸ tarball");
-const staging = mkdtempSync(join(tmpdir(), "hairline-release-"));
-step("pnpm pack", "pnpm", ["pack", "--pack-destination", staging], { cwd: PKG });
-const tgz = readdirSync(staging).filter((f) => f.endsWith(".tgz")).map((f) => join(staging, f))[0];
-let version = "";
-if (!tgz) fail("no tarball was written");
-else {
- const files = run("tar", ["-tzf", tgz]).trim().split("\n").map((f) => f.replace(/^package\//, ""));
- const manifest = JSON.parse(run("tar", ["-xzOf", tgz, "package/package.json"]));
- const text = (file) => run("tar", ["-xzOf", tgz, `package/${file}`]);
- version = manifest.version;
-
- const stray = files.filter((f) => !f.startsWith("dist/") && !["package.json", "README.md", "LICENSE"].includes(f));
- check(stray.length === 0, "only dist, README.md, LICENSE and package.json", `unexpected files: ${stray.join(", ")}`);
- for (const f of ["dist/index.js", "dist/index.d.ts", "dist/react.js", "dist/react.d.ts", "README.md", "LICENSE"]) {
- check(files.includes(f), `ships ${f}`, `missing ${f}`);
- }
- check(files.every((f) => !/\.(cjs|cts)$/.test(f)), "ESM only", "a CommonJS file is in the tarball");
-
- const ranges = Object.entries({ ...manifest.dependencies, ...manifest.peerDependencies, ...manifest.optionalDependencies });
- const unresolved = ranges.filter(([, r]) => String(r).startsWith("workspace:"));
- check(unresolved.length === 0, "no workspace: range", `unresolved ${unresolved.map(([n, r]) => `${n}@${r}`).join(", ")}`);
- check(Object.keys(manifest.dependencies ?? {}).length === 0, "no dependencies", `dependencies: ${Object.keys(manifest.dependencies ?? {}).join(", ")}`);
- check(manifest.peerDependencies?.react === ">=18" && manifest.peerDependenciesMeta?.react?.optional === true,
- "react >=18 is an optional peer", "react must be an optional peer dependency, >=18");
- check(manifest.sideEffects === false, "sideEffects: false", "sideEffects must be false");
- check(manifest.type === "module", "type: module", 'type must be "module"');
- check(manifest.publishConfig?.access === "public", "publishConfig.access = public", 'publishConfig.access must be "public"');
- check(manifest.repository?.url?.includes("github.com/lucasmarkes/hairline") && manifest.repository?.directory === PKG,
- "repository points at the package's directory", "repository.url and repository.directory must point at packages/hairline: provenance compares them with the workflow's repository");
- check(!!manifest.homepage && !!manifest.bugs?.url, "homepage and bugs", "homepage and bugs.url are missing");
-
- if (files.includes("dist/react.js") && files.includes("dist/index.js")) {
- const react = text("dist/react.js"), core = text("dist/index.js");
- check(/^\s*["']use client["'];?/.test(react), 'react.js starts with "use client"', 'react.js does not start with "use client": Server Components would fail to import it');
- check(react.includes(`from "${NAME}"`) && !react.includes("IntersectionObserver"),
- "react.js imports the core by package name", "react.js carries its own copy of the core: two entries would run two frame loops");
- check(!/^\s*["']use client["']/.test(core), "index.js is not a client module", "index.js must not be marked use client");
- check(!/\bfrom\s*["'][^."']/.test(core), "index.js imports nothing", "index.js imports a package");
- }
- check(text("README.md").length > 1500, "README.md is the real one", "README.md is a stub");
-}
-rmSync(staging, { recursive: true, force: true });
-
-console.log("\n▸ consumers");
-if (STATIC) note("skipped (--static): the fixtures install from the npm registry");
-else step("Next.js and Vite fixtures install the tarball, build and draw", "node", ["scripts/consumers.mjs"]);
-
-console.log("\n▸ shadcn item");
-if (STATIC) note("skipped (--static): the schema is fetched from ui.shadcn.com");
-else {
- step("registry/build.mjs", "node", ["registry/build.mjs"]);
- step("the item validates against shadcn's schema", "node", ["registry/validate.mjs"]);
-}
-
-console.log("\n▸ registry");
-if (STATIC) note("skipped (--static): needs network and npm auth");
-else {
- let whoami = "";
- try { whoami = run("npm", ["whoami"]).trim(); } catch { /* not logged in */ }
- if (!whoami) note("not logged in to npm: the scope is unverified (the publish workflow uses NPM_TOKEN)");
- else check(whoami === "lucasmarkes", "logged in as the scope's owner", `logged in as ${whoami}, and the scope is @lucasmarkes`);
- try {
- const res = await fetch(`https://registry.npmjs.org/${NAME.replace("/", "%2f")}`, { signal: AbortSignal.timeout(15_000) });
- if (res.status === 404) pass(`${NAME} is unclaimed on the registry`);
- else if (res.ok) {
- const doc = await res.json();
- check(!doc.versions?.[version], `${version} is not published yet`, `${version} is already on the registry: bump the version`);
- } else fail(`the registry answered ${res.status}`);
- } catch (err) { fail(`could not reach the registry (${err.message})`); }
-}
-
-if (failures > 0) { console.error(`\n✗ ${failures} check(s) failed. Not ready to release.\n`); process.exit(1); }
-console.log(`\n✓ All checks passed for ${NAME}@${version}. Nothing has been published.\n To release: update CHANGELOG.md, commit, then git tag v${version} && git push origin v${version}\n`);
-```
-
-- [ ] **Step 2: Run it and see it fail on the stub README**
-
-Run: `pnpm run release --static`
-Expected: every check passes except one: `✗ README.md is a stub`. The run ends with `✗ 1 check(s) failed. Not ready to release.` and exits 1.
-
-If a size budget fails instead, the build has grown since the budgets were set. Do not raise a budget without asking Lucas.
-
-- [ ] **Step 3: Make the hero clip**
-
-The README shows the lead tweet's board of six. Make it from the website's rendered video:
-
-```bash
-ls ~/estudos/lucasmarkes.com/website/video/out/hairline-grid-x-1080p.mp4
-mkdir -p assets
-ffmpeg -y -v error -i ~/estudos/lucasmarkes.com/website/video/out/hairline-grid-x-1080p.mp4 \
- -vf "fps=20,scale=800:-2:flags=lanczos,split[a][b];[a]palettegen=max_colors=96:stats_mode=diff[p];[b][p]paletteuse=dither=bayer:bayer_scale=4:diff_mode=rectangle" \
- -loop 0 assets/hero.gif
-ls -l assets/hero.gif
-```
-Expected: `assets/hero.gif` is about 3.7 MB and 800 px wide, and it loops. Open it and check that the six tiles move.
-
-If the `.mp4` is missing, render it first. It is git-ignored output from the website's branch `hairline-video`:
-1. `git -C ~/estudos/lucasmarkes.com/website switch hairline-video`.
-2. In that repository, run `pnpm build && pnpm start -p 3124`.
-3. In a second terminal, run `pnpm video:hairline --fig grid`.
-
-- [ ] **Step 4: Write the README**
-
-This is the npm page and the GitHub page. The gif is linked by its raw GitHub URL, so npm can render it. That URL works once the repository is public (Task 16).
-
-`README.md`
-````markdown
-# hairline
-
-Six isometric line figures that answer the pointer. For React and for anything with a DOM.
-
-[![npm](https://img.shields.io/npm/v/@lucasmarkes/hairline)](https://www.npmjs.com/package/@lucasmarkes/hairline)
-[![CI](https://github.com/lucasmarkes/hairline/actions/workflows/ci.yml/badge.svg)](https://github.com/lucasmarkes/hairline/actions/workflows/ci.yml)
-[![license](https://img.shields.io/npm/l/@lucasmarkes/hairline)](./LICENSE)
-
-![The six figures: a tray of cards, a field of pillars, a window in layers, a dot matrix, a conveyor belt and a turntable](https://raw.githubusercontent.com/lucasmarkes/hairline/main/assets/hero.gif)
-
-Live, with a slider for every option: **[hairline.lucasmarkes.com](https://hairline.lucasmarkes.com)**
-
-## Install
-
-```sh
-pnpm add @lucasmarkes/hairline
-```
-
-No dependencies. ESM only. React 18 or later is an optional peer, needed only by `@lucasmarkes/hairline/react`.
-
-With shadcn, which adds the package and a wrapper that reads your theme's tokens:
-
-```sh
-npx shadcn@latest add https://hairline.lucasmarkes.com/r/hairline.json
-```
-
-## Use
-
-### React
-
-```tsx
-import { Terrain } from "@lucasmarkes/hairline/react";
-
-export function Hero() {
- return <Terrain radius={4} className="w-96" />;
-}
-```
-
-The entry is a client module, so a Server Component can render it with no `"use client"` of its own. A component takes its figure's options and every `<div>` attribute, and forwards its ref to the `<div>`.
-
-### Anything else
-
-```ts
-import { terrain } from "@lucasmarkes/hairline";
-
-const figure = terrain(document.getElementById("figure")!, { radius: 4 });
-
-figure.update({ radius: 2 });
-figure.destroy();
-```
-
-A figure draws into the element you give it, at the element's width and a 5:4 aspect ratio. `update` changes options on the running figure; `destroy` removes what the figure added. That is the shape of a Svelte action, so `use:terrain={{ radius }}` works as it is.
-
-## The figures
-
-| Function | Component | What it is | Option | Range | Default |
-| --- | --- | --- | --- | --- | --- |
-| `riffle` | `Riffle` | A tray of eight cards. The card under the pointer stands up; the arrow keys walk the cards. | `stagger` | 0 to 90 ms | 40 |
-| `terrain` | `Terrain` | Eighty-one pillars on a plinth that rise around the pointer. | `radius` | 1.5 to 5 cells | 3 |
-| `exploded` | `Exploded` | An app window in four layers. Moving across opens the gap; moving down picks a layer. | `gap` | 12 to 40 units | 28 |
-| `phosphor` | `Phosphor` | A dot matrix that plays a loop, and fades like phosphor where the pointer paints it. | `afterglow` | 150 to 1500 ms | 520 |
-| `slow` | `Slow` | Crates riding a belt through a gate. Hovering slows the clock without stopping it. | `rate` | 0.05 to 0.6 × | 0.2 |
-| `turntable` | `Turntable` | Blocks on a turntable. A flick spins it; it settles on the nearest quarter turn. | `coast` | 200 to 1500 ms | 650 |
-
-A number outside its range is clamped, and anything that is not a number falls back to the default. The bounds are exported, so a slider or a table never repeats them:
-
-```ts
-import { ranges } from "@lucasmarkes/hairline";
-
-ranges.terrain.radius; // { min: 1.5, max: 5, step: 0.25, default: 3, unit: "cells" }
-```
-
-Riffle takes two more options: `bands` (boolean) shows the bands the pointer is tested against, and `labels` (up to eight strings) names the cards.
-
-Every figure also takes:
-
-| Option | Type | Default | |
-| --- | --- | --- | --- |
-| `theme` | `"auto" \| "light" \| "dark"` | `"auto"` | `"auto"` follows the page: an ancestor with class `dark` or `data-theme="dark"`, then the page's `color-scheme`. |
-| `label` | `string` | a description in English | The accessible name. In React, `aria-label` does the same. |
-| `onRead` | `(text: string) => void` | | The figure's caption, each time it changes: `"03 · Dock"`, `"gap 28.0"`, `"rate 0.20×"`. |
-
-## Theme
-
-Six custom properties, set on the figure or on anything above it:
-
-```css
-.figures {
- --hairline-plate: #101014; /* the fill of every plate: the colour the figure sits on */
- --hairline-hi: #fafafa; /* what is lit */
- --hairline-edge: #a1a1aa; /* silhouettes */
- --hairline-mid: #52525b; /* every other stroke */
- --hairline-lo: #27272a; /* what recedes */
- --hairline-stroke: 0.9; /* stroke width, in CSS pixels at any size */
-}
-```
-
-`--hairline-plate` is the one to get right. Plates are filled, not transparent, because a plate hides what is drawn behind it; on a background that is neither white nor `#08090a`, set it to that background.
-
-The figure's styles have no specificity, so any rule of yours wins without `!important`.
-
-## Notes
-
-- **Accessibility.** A figure is an image with a description you can replace with `label`. Riffle is the exception: it is a focusable group, the arrow keys walk its cards, and a live region reads the card out.
-- **Reduced motion.** With `prefers-reduced-motion`, the figures that play on their own (Phosphor and Slow) hold still, and every figure still answers the pointer.
-- **Performance.** Every figure on a page shares one `requestAnimationFrame` loop. A figure off screen, or at rest, does no work, and the loop stops when nothing is moving.
-- **Server rendering.** On the server a component is an empty box with a 5:4 aspect ratio, so nothing shifts when it draws. The functions need a DOM: call them in an effect, in `onMount`, or in a script after the element.
-- **Shadow DOM.** A figure mounted inside a shadow root styles itself there.
-
-## More
-
-- [hairline.lucasmarkes.com](https://hairline.lucasmarkes.com): every figure live, a theme editor, and snippets for Next.js, Vue, Svelte, Astro and a CDN.
-- [The essay](https://lucasmarkes.com/lab/hairline): how the figures are drawn, and why with lines.
-- [CHANGELOG.md](https://github.com/lucasmarkes/hairline/blob/main/CHANGELOG.md) and [CONTRIBUTING.md](https://github.com/lucasmarkes/hairline/blob/main/CONTRIBUTING.md).
-
-The style is a study of the illustrations on [Linear](https://linear.app)'s home page.
-
-## License
-
-MIT © Lucas Marques
-````
-
-- [ ] **Step 5: Write CONTRIBUTING**
-
-`CONTRIBUTING.md`
-````markdown
-# Contributing
-
-## Setup
-
-Node 22 or later, pnpm 10 (`corepack enable` picks the right one), and Google Chrome for the browser tests.
-
-```sh
-pnpm install
-pnpm build
-```
-
-## Layout
-
-```
-packages/hairline the package: src/core (maths, stage, styles), src/figures (six engines),
- src/mount.ts (the public lifecycle), src/index.ts and src/react.tsx (the two entries)
-apps/site hairline.lucasmarkes.com (Next.js)
-registry the shadcn item: its source, and the scripts that build and validate it
-fixtures two apps that install the packed tarball: Next.js and Vite
-scripts the release gate and what it calls
-```
-
-## Commands
-
-| | |
-| --- | --- |
-| `pnpm build` | Builds the package, then the site. |
-| `pnpm typecheck` | TypeScript, including the type tests in `packages/hairline/test/types.test-d.tsx`. |
-| `pnpm test` | Unit and component tests (Vitest, jsdom). |
-| `pnpm test:browser` | Browser tests in Chrome (Playwright): the figures, the theme, parity, the site. |
-| `pnpm dev` | The site on `localhost:3000`, with the package rebuilding on change. |
-| `pnpm release --static` | The release gate without the steps that need the network. CI runs this. |
-| `pnpm release` | The whole gate. It never publishes. |
-| `node scripts/consumers.mjs` | Packs the package and installs it in both fixtures. |
-
-## The engines, and why their comments mention "the study"
-
-The six engines in `packages/hairline/src/figures`, and `src/core/iso.ts`, `motion.ts` and `stage.ts`, were ported from the essay at [lucasmarkes.com/lab/hairline](https://lucasmarkes.com/lab/hairline), where they are figures 9.1 to 9.6. Their comments still say "the study" and "Fig 9.n": that is the essay.
-
-The port is held to the essay by the parity tests. `packages/hairline/test/parity/golden` holds the SVG each figure drew on the essay's page, under a frozen clock, at four moments of a scripted pointer path; `test/browser/parity.spec.ts` replays the same script against the package, on the same frozen clock, and expects the same SVG and the same caption, character for character.
-
-So a change to an engine that moves a line fails parity, and that is the point. If the change is meant, say so in the pull request and update the golden file for that figure by hand. The goldens are not regenerated from the package: `pnpm -C packages/hairline capture <commit> [url]` records them from the essay's site at that commit, and exists for the day the essay changes.
-
-## Adding an option
-
-1. Add its bounds to `src/ranges.ts`. The site's sliders and tables, and the tests, read them from there.
-2. Add it to the figure's options type in `src/index.ts`, with a doc comment that states the range and the default.
-3. Add its name to the component's key list in `src/react.tsx`.
-4. Describe it in `apps/site/lib/figures.ts`. The site's tests hold its tables and snippets to `ranges`.
-
-## Pull requests
-
-- One change per pull request, with a test that fails without it.
-- `pnpm typecheck && pnpm test && pnpm test:browser` pass.
-- A change a user can see gets a line in `CHANGELOG.md`, under the next version.
-
-## Releasing
-
-Maintainers only.
-
-1. Bump `version` in `packages/hairline/package.json` and add a `## <version> - <date>` section to `CHANGELOG.md`.
-2. `pnpm release` passes.
-3. Commit, then `git tag v<version> && git push origin main v<version>`.
-
-The tag starts `.github/workflows/publish.yml`, which waits for approval in the `release` environment, publishes to npm with provenance, and creates the GitHub Release from the changelog section. A version with a hyphen (`0.2.0-rc.0`) is published under the `next` dist-tag.
-````
-
-- [ ] **Step 6: Run the gate and see it pass**
-
-Run: `pnpm run release --static`
-Expected:
-- Every check passes, including "README.md is the real one" and the three size budgets.
-- The three sections that need the network print `– skipped (--static)`.
-- The last line is `✓ All checks passed for @lucasmarkes/[email protected]. Nothing has been published.`
-
-- [ ] **Step 7: Add the static gate to CI**
-
-This is the final CI:
-
-`.github/workflows/ci.yml`
-```yaml
-name: CI
-
-on:
- push:
- branches: [main]
- pull_request:
-
-# A newer push to the same branch or PR cancels the run in flight.
-concurrency:
- group: ci-${{ github.ref }}
- cancel-in-progress: true
-
-permissions:
- contents: read
-
-jobs:
- verify:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v7
-
- # Corepack activates the pnpm pinned in package.json's packageManager.
- - name: Enable Corepack
- run: corepack enable
-
- - uses: actions/setup-node@v7
- with:
- node-version: 22
- cache: pnpm
-
- - name: Install
- run: pnpm install --frozen-lockfile
-
- - name: Build
- run: pnpm build
-
- - name: Typecheck
- run: pnpm typecheck
-
- - name: Unit and component tests
- run: pnpm test
-
- # The browser tests drive the Chrome that ubuntu-latest ships
- # (playwright.config.ts sets channel: "chrome"), so nothing is downloaded.
- - name: Browser tests
- run: pnpm test:browser
-
- # The release gate without the network: publint, attw, size budgets, pack
- # and tarball inspection. Its build, typecheck and unit tests replay from
- # the turbo cache the steps above filled.
- - name: Release gate (static)
- run: pnpm run release --static
-```
-
-- [ ] **Step 8: Commit and push**
-
-```bash
-git add scripts/release.mjs README.md CONTRIBUTING.md assets/hero.gif .github/workflows/ci.yml
-git commit -m "Release gate: publint, attw, size budgets and the tarball; README and CONTRIBUTING
-
-Co-Authored-By: Claude <[email protected]>"
-git push
-gh run watch --exit-status "$(gh run list --workflow CI --limit 1 --json databaseId --jq '.[0].databaseId')"
-```
-Expected: CI passes, including "Release gate (static)".
-
-### Task 10: The shadcn registry item
-
-**Files:**
-- Create: `scripts/base-url.mjs`, `registry/src/hairline.tsx`, `registry/build.mjs`, `registry/validate.mjs`, `apps/site/.gitignore`
-- Modify: `package.json` (root, via `pnpm add`: `ajv` as a dev dependency), `pnpm-lock.yaml`
-
-**Interfaces:**
-- Consumes: the React entry from Task 8. The item's file imports `* as Hairline from "@lucasmarkes/hairline/react"`, and each of its six components takes `ComponentProps<typeof Hairline.X>`.
-- Produces:
- - `scripts/base-url.mjs`:
- - `FALLBACK = "http://localhost:3000"`
- - `resolveBase(): { url: string; source: "HAIRLINE_REGISTRY_URL" | "VERCEL_PROJECT_PRODUCTION_URL" | "VERCEL_URL" | "fallback" }`
- - `resolveBaseUrl(): string`: the same, without a trailing slash.
-
- The site (Task 12) uses `resolveBaseUrl` in `next.config.mjs`.
- - `node registry/build.mjs` writes `apps/site/public/r/hairline.json` and `apps/site/public/r/registry.json`. That folder is generated and git-ignored. The site's `prebuild` and `predev` (Task 12) and `scripts/consumers.mjs` (Task 11) call it.
- - `node registry/validate.mjs` checks the item against shadcn's schema, fetched from `ui.shadcn.com`, and against the rules below. It exits 1 on any problem. The full release gate (Task 9) calls it.
-
-The item is the spec's "The shadcn registry item":
-- It depends on `@lucasmarkes/hairline` and nothing else.
-- It writes `components/ui/hairline.tsx`, which starts with `"use client";` and re-exports the six components with the token mapping from the spec's table. A `style` the user passes wins over the mapping.
-- The item's URL comes from the environment, never from the source.
-
-`validate.mjs` checks each of these. It also refuses an item that points at localhost when it runs on Vercel.
-
-- [ ] **Step 1: Add the schema validator**
-
-Run: `pnpm add -Dw -E [email protected]`
-Expected: the root `package.json` gains `"ajv": "8.20.0"` under `devDependencies`, and `pnpm-lock.yaml` changes.
-
-- [ ] **Step 2: Write the base URL resolver**
-
-`scripts/base-url.mjs`
-```js
-/**
- * Where this build thinks it lives.
- *
- * Two things need an absolute URL in their output and may not have one in
- * their source: the shadcn registry item, which `shadcn add` fetches by URL,
- * and the Open Graph tags, which crawlers do not resolve relatively. Both ask
- * here, so localhost, a preview and production differ only by environment.
- *
- * The ladder goes from the most specific answer to the least. An explicit
- * override wins; production names itself; anything else on Vercel is a preview
- * and names itself too, which is what makes a preview testable: its registry
- * item installs from that preview.
- */
-
-export const FALLBACK = "http://localhost:3000";
-
-export function resolveBase() {
- const explicit = process.env.HAIRLINE_REGISTRY_URL?.trim();
- if (explicit) return { url: explicit, source: "HAIRLINE_REGISTRY_URL" };
-
- const productionHost = process.env.VERCEL_PROJECT_PRODUCTION_URL?.trim();
- if (process.env.VERCEL_ENV === "production" && productionHost) {
- return { url: `https://${productionHost}`, source: "VERCEL_PROJECT_PRODUCTION_URL" };
- }
-
- const deploymentHost = process.env.VERCEL_URL?.trim();
- if (deploymentHost) return { url: `https://${deploymentHost}`, source: "VERCEL_URL" };
-
- return { url: FALLBACK, source: "fallback" };
-}
-
-/** The same answer without trailing slashes, ready to have a path added. */
-export function resolveBaseUrl() {
- return resolveBase().url.replace(/\/+$/, "");
-}
-```
-
-- [ ] **Step 3: Write the validator first, and see it fail**
-
-`registry/validate.mjs`
-```js
-#!/usr/bin/env node
-/**
- * Checks the generated registry item against shadcn's own schema, fetched
- * from ui.shadcn.com, and against what this repository promises about it.
- *
- * node registry/build.mjs && node registry/validate.mjs
- */
-import { readFileSync } from "node:fs";
-import { join } from "node:path";
-import Ajv from "ajv";
-
-const SCHEMA = "https://ui.shadcn.com/schema/registry-item.json";
-const file = join(import.meta.dirname, "..", "apps", "site", "public", "r", "hairline.json");
-
-let item;
-try { item = JSON.parse(readFileSync(file, "utf8")); }
-catch { console.error(`No item at ${file}. Run \`node registry/build.mjs\` first.`); process.exit(1); }
-
-const response = await fetch(SCHEMA);
-if (!response.ok) { console.error(`Could not fetch ${SCHEMA}: ${response.status}`); process.exit(1); }
-const schema = await response.json();
-// The schema names its draft by an https URL that Ajv does not know; draft-07 is Ajv's default.
-delete schema.$schema;
-const validate = new Ajv({ strict: false, allErrors: true }).compile(schema);
-
-const problems = [];
-if (!validate(item)) for (const e of validate.errors) problems.push(`schema: ${e.instancePath || "/"} ${e.message}`);
-const [source] = item.files ?? [];
-if (item.dependencies?.join() !== "@lucasmarkes/hairline") problems.push("dependencies must be exactly @lucasmarkes/hairline");
-if (source?.path !== "components/ui/hairline.tsx") problems.push("the file must be components/ui/hairline.tsx");
-if (!source?.content?.startsWith('"use client";')) problems.push('the file must start with "use client"');
-for (const name of ["Riffle", "Terrain", "Exploded", "Phosphor", "Slow", "Turntable"]) {
- if (!source?.content?.includes(`export function ${name}(`)) problems.push(`the file does not export ${name}`);
-}
-if (/localhost/.test(JSON.stringify(item)) && process.env.VERCEL) problems.push("the item points at localhost in a deployed build");
-
-if (problems.length) { console.error(problems.map((p) => ` ✗ ${p}`).join("\n")); process.exit(1); }
-console.log(" ✓ hairline.json is a valid shadcn registry item");
-```
-
-Run: `node registry/validate.mjs`
-Expected: FAIL, exit 1, with `No item at …/apps/site/public/r/hairline.json. Run \`node registry/build.mjs\` first.`
-
-- [ ] **Step 4: Write the item's file and the build**
-
-`registry/src/hairline.tsx`
-```tsx
-"use client";
-
-import type { ComponentProps, CSSProperties } from "react";
-import * as Hairline from "@lucasmarkes/hairline/react";
-
-/**
- * hairline, wearing your theme. The six figures from @lucasmarkes/hairline,
- * with their palette mapped to shadcn's tokens, so they follow light, dark and
- * whatever you have made of them. A `style` you pass wins over the mapping.
- *
- * Docs: https://hairline.lucasmarkes.com
- */
-const tokens = {
- "--hairline-plate": "var(--background)",
- "--hairline-hi": "var(--foreground)",
- "--hairline-edge": "var(--muted-foreground)",
- "--hairline-mid": "color-mix(in oklab, var(--muted-foreground) 55%, var(--background))",
- "--hairline-lo": "var(--border)",
-} as CSSProperties;
-
-export function Riffle({ style, ...props }: ComponentProps<typeof Hairline.Riffle>) {
- return <Hairline.Riffle style={{ ...tokens, ...style }} {...props} />;
-}
-
-export function Terrain({ style, ...props }: ComponentProps<typeof Hairline.Terrain>) {
- return <Hairline.Terrain style={{ ...tokens, ...style }} {...props} />;
-}
-
-export function Exploded({ style, ...props }: ComponentProps<typeof Hairline.Exploded>) {
- return <Hairline.Exploded style={{ ...tokens, ...style }} {...props} />;
-}
-
-export function Phosphor({ style, ...props }: ComponentProps<typeof Hairline.Phosphor>) {
- return <Hairline.Phosphor style={{ ...tokens, ...style }} {...props} />;
-}
-
-export function Slow({ style, ...props }: ComponentProps<typeof Hairline.Slow>) {
- return <Hairline.Slow style={{ ...tokens, ...style }} {...props} />;
-}
-
-export function Turntable({ style, ...props }: ComponentProps<typeof Hairline.Turntable>) {
- return <Hairline.Turntable style={{ ...tokens, ...style }} {...props} />;
-}
-```
-
-`registry/build.mjs`
-```js
-#!/usr/bin/env node
-/**
- * Writes the shadcn registry item into the site's public folder.
- *
- * `shadcn add` fetches an item by absolute URL, so a hostname has to be in the
- * output and may not be in the source: it comes from the environment (see
- * scripts/base-url.mjs). Everything under apps/site/public/r is generated.
- */
-import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
-import { join } from "node:path";
-import { FALLBACK, resolveBase } from "../scripts/base-url.mjs";
-
-const SRC = join(import.meta.dirname, "src");
-const OUT = join(import.meta.dirname, "..", "apps", "site", "public", "r");
-
-const resolved = resolveBase();
-if (resolved.source === "fallback") {
- console.warn(`[registry] no site URL in the environment; using ${FALLBACK}.\n[registry] A deployed build that prints this line has published an item that points at localhost.`);
-}
-const BASE = resolved.url.replace(/\/+$/, "");
-
-const item = {
- $schema: "https://ui.shadcn.com/schema/registry-item.json",
- name: "hairline",
- type: "registry:ui",
- title: "Hairline",
- description: "Six isometric line figures that answer the pointer, with their palette mapped to your theme's tokens.",
- dependencies: ["@lucasmarkes/hairline"],
- files: [{ path: "components/ui/hairline.tsx", type: "registry:ui", content: readFileSync(join(SRC, "hairline.tsx"), "utf8") }],
- docs: `Docs: ${BASE}`,
-};
-
-rmSync(OUT, { recursive: true, force: true });
-mkdirSync(OUT, { recursive: true });
-writeFileSync(join(OUT, "hairline.json"), JSON.stringify(item, null, 2) + "\n");
-writeFileSync(join(OUT, "registry.json"), JSON.stringify({ $schema: "https://ui.shadcn.com/schema/registry.json", name: "hairline", homepage: BASE, items: [item] }, null, 2) + "\n");
-
-console.log(`[registry] ${BASE}/r/hairline.json (base from ${resolved.source})`);
-```
-
-The generated folder lives in the site, which Task 12 builds. Ignore it there now, with the site's other build output:
-
-`apps/site/.gitignore`
-```text
-.next/
-next-env.d.ts
-# written by registry/build.mjs before every build
-public/r/
-```
-
-- [ ] **Step 5: Build the item and see it validate**
-
-Run:
-```bash
-node registry/build.mjs
-node registry/validate.mjs
-HAIRLINE_REGISTRY_URL=https://hairline.lucasmarkes.com node registry/build.mjs
-grep -c '"docs": "Docs: https://hairline.lucasmarkes.com"' apps/site/public/r/hairline.json
-```
-Expected, in order:
-1. A warning that names the fallback (`[registry] no site URL in the environment; using http://localhost:3000.`), then `[registry] http://localhost:3000/r/hairline.json (base from fallback)`.
-2. `✓ hairline.json is a valid shadcn registry item`.
-3. `[registry] https://hairline.lucasmarkes.com/r/hairline.json (base from HAIRLINE_REGISTRY_URL)`.
-4. `1`.
-
-Then run `git status --short`. Expected: `apps/site/public/r` is not listed.
-
-The item's file is compiled for real in Task 11, where the Next.js fixture builds it.
-
-- [ ] **Step 6: Commit**
-
-```bash
-git add package.json pnpm-lock.yaml scripts/base-url.mjs registry apps/site/.gitignore
-git commit -m "Registry: the shadcn item, its URL from the environment, validated against shadcn's schema
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-### Task 11: Consumer fixtures: the package as a stranger installs it
-
-**Files:**
-- Create: `fixtures/next-app/.gitignore`, `fixtures/next-app/package.json`, `fixtures/next-app/tsconfig.json`, `fixtures/next-app/next.config.mjs`
-- Create: `fixtures/next-app/app/layout.tsx`, `fixtures/next-app/app/page.tsx`, `fixtures/next-app/app/vanilla.tsx`, `fixtures/next-app/app/registry/page.tsx`
-- Create: `fixtures/vite-vanilla/.gitignore`, `fixtures/vite-vanilla/package.json`, `fixtures/vite-vanilla/tsconfig.json`, `fixtures/vite-vanilla/index.html`, `fixtures/vite-vanilla/src/main.ts`
-- Create: `scripts/consumers.mjs`, `.github/workflows/consumers.yml`
-
-**Interfaces:**
-- Consumes:
- - From Tasks 6 and 8: the built package (`pnpm build`). The fixtures use only its public entries:
- - `riffle`…`turntable`, `ranges`, `Figure` and `RiffleOptions` from `@lucasmarkes/hairline`.
- - `Riffle` and `Slow` from `@lucasmarkes/hairline/react`.
- - From Task 10: `registry/build.mjs` and `apps/site/public/r/hairline.json`.
- - From Task 7: `@playwright/test`, which `consumers.mjs` resolves from `packages/hairline`, using the system Chrome.
-- Produces:
- - `node scripts/consumers.mjs [next|vite]` exits 1 on any failed check. The full release gate (Task 9) calls it.
- - The `Consumers` workflow runs it on pull requests that touch what ships.
-
-This is layer 6 of the spec. The fixtures are not workspace packages: `pnpm-workspace.yaml` lists only `packages/*` and `apps/*`. `consumers.mjs` copies each fixture to a temporary folder outside the repository and installs the packed tarball there with npm, so nothing resolves through a workspace symlink.
-
-What it checks:
-- **Next.js**:
- - A Server Component page renders the React components.
- - The server sends empty `<div>`s and no `<svg>`.
- - A client component on the same page uses the vanilla entry.
- - The registry item's file is written where `shadcn add` writes it, compiled by the app, and draws with the app's `--background`.
-- **Both apps**:
- - Every figure draws at 5:4.
- - All figures share one adopted stylesheet and one frame loop: one `requestAnimationFrame` per frame, however many figures are mounted.
- - The console stays clean.
-- **Vite**: `onRead` reaches the page.
-
-- [ ] **Step 1: Write the Next.js fixture**
-
-`fixtures/next-app/.gitignore`
-```text
-node_modules/
-.next/
-next-env.d.ts
-package-lock.json
-# written by scripts/consumers.mjs from the registry item
-components/
-```
-
-`fixtures/next-app/package.json`
-```json
-{
- "name": "hairline-fixture-next",
- "private": true,
- "scripts": {
- "build": "next build",
- "start": "next start"
- },
- "dependencies": {
- "next": "16.3.8",
- "react": "19.3.0",
- "react-dom": "19.3.0"
- },
- "devDependencies": {
- "@types/node": "^22",
- "@types/react": "^19",
- "@types/react-dom": "^19",
- "typescript": "5.9.3"
- }
-}
-```
-
-`fixtures/next-app/tsconfig.json`
-```json
-{
- "compilerOptions": {
- "target": "ES2020",
- "lib": ["dom", "dom.iterable", "esnext"],
- "strict": true,
- "noEmit": true,
- "esModuleInterop": true,
- "module": "esnext",
- "moduleResolution": "bundler",
- "resolveJsonModule": true,
- "isolatedModules": true,
- "jsx": "react-jsx",
- "incremental": true,
- "skipLibCheck": true,
- "allowJs": true,
- "plugins": [{ "name": "next" }],
- "paths": { "@/*": ["./*"] }
- },
- "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"],
- "exclude": ["node_modules"]
-}
-```
-
-`fixtures/next-app/next.config.mjs`
-```js
-/** A consumer's project, as plain as one gets: no transpilePackages, no aliases. */
-export default {};
-```
-
-`fixtures/next-app/app/layout.tsx`
-```tsx
-import type { ReactNode } from "react";
-
-export const metadata = { title: "hairline fixture", icons: { icon: "data:," } };
-
-export default function RootLayout({ children }: { children: ReactNode }) {
- return (
- <html lang="en">
- <body>{children}</body>
- </html>
- );
-}
-```
-
-`fixtures/next-app/app/page.tsx`
-```tsx
-import { Riffle, Slow } from "@lucasmarkes/hairline/react";
-import { Vanilla } from "./vanilla";
-
-/**
- * A Server Component: no "use client" here. The components come from the
- * React entry, which marks itself as a client module; the third figure comes
- * from the vanilla entry, so the page loads both entries at once.
- */
-export default function Page() {
- return (
- <main style={{ display: "grid", gap: 24, width: 400, margin: "40px auto" }}>
- <Riffle id="riffle" labels={["Radial menu", "Drum"]} />
- <Slow id="slow" rate={0.4} theme="dark" />
- <Vanilla />
- </main>
- );
-}
-```
-
-`fixtures/next-app/app/vanilla.tsx`
-```tsx
-"use client";
-
-import { useEffect, useRef } from "react";
-import { phosphor } from "@lucasmarkes/hairline";
-
-export function Vanilla() {
- const ref = useRef<HTMLDivElement>(null);
- useEffect(() => {
- const figure = phosphor(ref.current!, { afterglow: 900 });
- return () => figure.destroy();
- }, []);
- return <div id="phosphor" ref={ref} />;
-}
-```
-
-`fixtures/next-app/app/registry/page.tsx`
-```tsx
-import type { CSSProperties } from "react";
-import { Terrain } from "@/components/ui/hairline";
-
-/** shadcn's tokens, as a dark theme would define them. */
-const tokens = { "--background": "#101014", "--foreground": "#fafafa", "--muted-foreground": "#a1a1aa", "--border": "#27272a" } as CSSProperties;
-
-/**
- * The shadcn registry item, as `shadcn add` would leave it:
- * scripts/consumers.mjs writes components/ui/hairline.tsx from the built item
- * before it builds this app.
- */
-export default function Page() {
- return (
- <main style={{ width: 400, margin: "40px auto", background: "var(--background)", ...tokens }}>
- <Terrain id="themed" />
- </main>
- );
-}
-```
-
-- [ ] **Step 2: Write the Vite fixture**
-
-`fixtures/vite-vanilla/.gitignore`
-```text
-node_modules/
-dist/
-package-lock.json
-```
-
-`fixtures/vite-vanilla/package.json`
-```json
-{
- "name": "hairline-fixture-vite",
- "private": true,
- "type": "module",
- "scripts": {
- "build": "tsc --noEmit && vite build",
- "preview": "vite preview"
- },
- "devDependencies": {
- "typescript": "5.9.3",
- "vite": "8.3.2"
- }
-}
-```
-
-`fixtures/vite-vanilla/tsconfig.json`
-```json
-{
- "compilerOptions": {
- "target": "ES2020",
- "lib": ["ES2020", "DOM", "DOM.Iterable"],
- "module": "ESNext",
- "moduleResolution": "bundler",
- "strict": true,
- "noEmit": true,
- "skipLibCheck": false
- },
- "include": ["src"]
-}
-```
-
-`fixtures/vite-vanilla/index.html`
-```html
-<!doctype html>
-<html lang="en">
-<head>
-<meta charset="utf-8">
-<meta name="viewport" content="width=device-width, initial-scale=1">
-<title>hairline fixture</title>
-<link rel="icon" href="data:,">
-<style>
- main { display: grid; grid-template-columns: repeat(3, 300px); gap: 24px; margin: 40px; }
-</style>
-</head>
-<body>
- <main>
- <div id="riffle"></div>
- <div id="terrain"></div>
- <div id="exploded"></div>
- <div id="phosphor"></div>
- <div id="slow"></div>
- <div id="turntable"></div>
- </main>
- <output id="read"></output>
- <script type="module" src="/src/main.ts"></script>
-</body>
-</html>
-```
-
-`fixtures/vite-vanilla/src/main.ts`
-```ts
-import { exploded, phosphor, ranges, riffle, slow, terrain, turntable, type Figure, type RiffleOptions } from "@lucasmarkes/hairline";
-
-/** No framework: six elements, six calls. */
-const el = (id: string) => document.getElementById(id)!;
-const read = el("read");
-
-const cards: Figure<RiffleOptions> = riffle(el("riffle"), {
- stagger: ranges.riffle.stagger.max,
- labels: ["Radial menu", "Drum"],
- onRead: (text) => { read.textContent = text; },
-});
-terrain(el("terrain"), { radius: 4 });
-exploded(el("exploded"));
-phosphor(el("phosphor"), { theme: "dark" });
-slow(el("slow"));
-turntable(el("turntable"));
-
-cards.update({ bands: true });
-```
-
-- [ ] **Step 3: Write the runner**
-
-`scripts/consumers.mjs`
-```js
-#!/usr/bin/env node
-/**
- * Layer 6: the package as a stranger gets it. Packs it, installs the tarball
- * with npm into a copy of each fixture (outside the workspace, so nothing
- * resolves through a symlink), builds the fixture with its own toolchain,
- * serves the build and opens it in Chrome.
- *
- * node scripts/consumers.mjs both fixtures
- * node scripts/consumers.mjs next one of them (next | vite)
- *
- * Needs the network (npm installs next, react and vite) and a built package.
- */
-import { execFileSync, spawn } from "node:child_process";
-import { cpSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
-import { createRequire } from "node:module";
-import { tmpdir } from "node:os";
-import { join, resolve } from "node:path";
-
-const ROOT = resolve(import.meta.dirname, "..");
-const PKG = join(ROOT, "packages/hairline");
-const { chromium } = createRequire(join(PKG, "package.json"))("@playwright/test");
-
-const FIXTURES = {
- next: { dir: "fixtures/next-app", port: 4311, serve: (port) => ["npx", ["next", "start", "-p", String(port)]], figures: ["riffle", "slow", "phosphor"] },
- vite: { dir: "fixtures/vite-vanilla", port: 4312, serve: (port) => ["npx", ["vite", "preview", "--port", String(port), "--strictPort"]], figures: ["riffle", "terrain", "exploded", "phosphor", "slow", "turntable"] },
-};
-const only = process.argv[2];
-if (only && !FIXTURES[only]) { console.error(`Unknown fixture "${only}". Use: ${Object.keys(FIXTURES).join(" | ")}`); process.exit(2); }
-
-let failures = 0;
-const fail = (msg) => { failures++; console.error(` ✗ ${msg}`); };
-const pass = (msg) => console.log(` ✓ ${msg}`);
-const check = (ok, good, bad) => (ok ? pass(good) : fail(bad));
-const run = (cmd, args, cwd) => execFileSync(cmd, args, { cwd, encoding: "utf8", stdio: "pipe" });
-function step(label, cmd, args, cwd) {
- try { run(cmd, args, cwd); pass(label); return true; }
- catch (err) { fail(`${label}\n${String((err.stdout ?? "") + (err.stderr ?? "") || err.message).trim().split("\n").slice(-30).join("\n")}`); return false; }
-}
-async function up(url, tries = 100) {
- for (let i = 0; i < tries; i++) {
- try { if ((await fetch(url)).ok) return true; } catch {}
- await new Promise((r) => setTimeout(r, 200));
- }
- return false;
-}
-
-/**
- * Counts the animation frames requested between one frame and the next. A
- * page with any number of figures keeps one loop, so it asks for one frame per
- * frame; a second copy of the engine would ask for two.
- */
-const COUNT_FRAMES = `(() => {
- const raf = window.requestAnimationFrame.bind(window);
- let asked = 0;
- window.__asked = [];
- window.requestAnimationFrame = (fn) => { asked++; return raf(fn); };
- const tally = () => { window.__asked.push(asked); asked = 0; raf(tally); };
- raf(tally);
-})();`;
-
-const staging = mkdtempSync(join(tmpdir(), "hairline-consumers-"));
-console.log("\n▸ tarball");
-step("pnpm pack", "pnpm", ["pack", "--pack-destination", staging], PKG);
-const tgz = readdirSync(staging).filter((f) => f.endsWith(".tgz")).map((f) => join(staging, f))[0];
-if (!tgz) { console.error("\nNo tarball to install.\n"); process.exit(1); }
-
-const browser = await chromium.launch({ channel: "chrome" });
-for (const [name, fx] of Object.entries(FIXTURES)) {
- if (only && only !== name) continue;
- console.log(`\n▸ ${fx.dir}`);
- const dir = join(staging, name);
- cpSync(join(ROOT, fx.dir), dir, { recursive: true, filter: (src) => !/\/(node_modules|\.next|dist)$/.test(src) });
- if (name === "next") {
- // what `shadcn add` does with the registry item: write its file into the app
- run("node", ["registry/build.mjs"], ROOT);
- const item = JSON.parse(readFileSync(join(ROOT, "apps/site/public/r/hairline.json"), "utf8"));
- for (const file of item.files) {
- mkdirSync(join(dir, file.path, ".."), { recursive: true });
- writeFileSync(join(dir, file.path), file.content);
- }
- pass("the registry item's file is in place");
- }
- if (!step("npm install (the tarball, as a dependency)", "npm", ["install", "--no-audit", "--no-fund", tgz], dir)) continue;
- if (!step("build (the fixture's own typecheck and bundler)", "npm", ["run", "build"], dir)) continue;
-
- const [cmd, args] = fx.serve(fx.port);
- const server = spawn(cmd, args, { cwd: dir, stdio: "ignore" });
- try {
- const url = `http://localhost:${fx.port}/`;
- if (!(await up(url))) { fail(`nothing answered at ${url}`); continue; }
-
- if (name === "next") {
- const html = await (await fetch(url)).text();
- check(/<div id="riffle"[^>]*><\/div>/.test(html), "the server renders an empty <div> for a figure", "the server-rendered page has no empty <div id=\"riffle\">");
- check(!html.includes("<svg"), "no figure is drawn on the server", "the server-rendered page already has an <svg>");
- }
-
- const context = await browser.newContext({ viewport: { width: 1200, height: 900 } });
- await context.addInitScript(COUNT_FRAMES);
- const page = await context.newPage();
- const noise = [];
- page.on("console", (m) => { if (m.type() === "error" || m.type() === "warning") noise.push(`${m.type()}: ${m.text()}`); });
- page.on("pageerror", (e) => noise.push(`pageerror: ${e}`));
- await page.goto(url, { waitUntil: "networkidle" });
-
- for (const id of fx.figures) {
- const drawn = await page.locator(`#${id} svg > *`).first().waitFor({ timeout: 5000 }).then(() => true, () => false);
- const box = drawn ? await page.locator(`#${id} svg`).boundingBox() : null;
- check(drawn && box.width > 100 && Math.abs(box.width / box.height - 1.25) < 0.01, `${id} is drawn, 5:4`, `${id} is not drawn (box ${JSON.stringify(box)})`);
- }
- check((await page.locator("style[data-hairline-style]").count()) === 0 && (await page.evaluate(() => document.adoptedStyleSheets.length)) === 1,
- "one adopted stylesheet for every figure", "the figures did not share one adopted stylesheet");
-
- await page.waitForTimeout(500);
- const asked = await page.evaluate(() => { const from = window.__asked.length; return new Promise((r) => setTimeout(() => r(window.__asked.slice(from)), 500)); });
- check(asked.length > 10 && asked.every((n) => n === 1), `one loop for ${fx.figures.length} figures (${asked.length} frames, one request each)`, `expected one frame request per frame, saw ${[...new Set(asked)].join(", ")} over ${asked.length} frames`);
-
- if (name === "next") {
- await page.goto(`${url}registry`, { waitUntil: "networkidle" });
- const fill = await page.locator("#themed svg path").first().evaluate((el) => getComputedStyle(el).fill).catch(() => "");
- check(fill === "rgb(16, 16, 20)", "the registry item draws with the app's tokens", `the registry item's figure is filled ${fill || "(not drawn)"}, not --background`);
- }
- if (name === "vite") check((await page.locator("#read").textContent()) !== "", "onRead reached the page", "onRead never wrote to the page");
- check(noise.length === 0, "console is clean", `console:\n${noise.join("\n")}`);
- await context.close();
- } finally {
- server.kill();
- }
-}
-await browser.close();
-rmSync(staging, { recursive: true, force: true });
-
-if (failures) { console.error(`\n${failures} consumer check${failures > 1 ? "s" : ""} failed.\n`); process.exit(1); }
-console.log("\nBoth consumers install, build and draw.\n");
-```
-
-- [ ] **Step 4: Run it**
-
-Run: `pnpm build && node scripts/consumers.mjs`
-Expected: it ends with `Both consumers install, build and draw.` and exits 0. Every line under `▸ fixtures/next-app` and `▸ fixtures/vite-vanilla` is a `✓`, including:
-- `one loop for 3 figures (… frames, one request each)` for Next.js.
-- `one loop for 6 figures (…)` for Vite.
-- `the registry item draws with the app's tokens`.
-
-It needs the network, because npm installs next, react and vite. The first run takes a few minutes.
-
-A failure here is a real defect in what ships. Fix the package or the item, never the fixture's expectations. In particular:
-- A second request per frame means the React entry bundled its own copy of the core. Check the `core-by-package-name` plugin in Task 8's `tsup.config.ts`.
-- A server-rendered `<svg>` means a figure drew outside an effect.
-
-- [ ] **Step 5: Run the gate's network checks for the first time**
-
-Run: `pnpm run release`
-Expected:
-- Every section passes up to `▸ registry`. The consumers run again inside the gate.
-- Under `▸ registry`:
- - `@lucasmarkes/hairline is unclaimed on the registry`, unless the name was claimed in the meantime. If so, stop and tell Lucas.
- - A note that npm auth is not checked, or `logged in as the scope's owner`.
-- The last line is `✓ All checks passed for @lucasmarkes/[email protected]. Nothing has been published.`
-
-- [ ] **Step 6: Run the fixtures in CI on pull requests**
-
-`.github/workflows/consumers.yml`
-```yaml
-name: Consumers
-
-# Layer 6: the packed tarball installed in a Next.js app and a Vite app, built
-# and opened in a browser. Slow and network-bound, so it runs only when what
-# ships (or what checks it) changes. The release gate runs it too.
-on:
- pull_request:
- paths:
- - 'packages/**'
- - 'fixtures/**'
- - 'scripts/consumers.mjs'
- - '.github/workflows/consumers.yml'
-
-concurrency:
- group: consumers-${{ github.ref }}
- cancel-in-progress: true
-
-permissions:
- contents: read
-
-jobs:
- consumers:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v7
-
- - name: Enable Corepack
- run: corepack enable
-
- - uses: actions/setup-node@v7
- with:
- node-version: 22
- cache: pnpm
-
- - name: Install
- run: pnpm install --frozen-lockfile
-
- - name: Build
- run: pnpm build
-
- - name: Install, build and open the fixtures
- run: node scripts/consumers.mjs
-```
-
-- [ ] **Step 7: Commit and push**
-
-```bash
-git add fixtures scripts/consumers.mjs .github/workflows/consumers.yml
-git commit -m "Tests: the packed tarball installed in a Next.js app and a Vite app, built and opened in Chrome
-
-Co-Authored-By: Claude <[email protected]>"
-git push
-gh run watch --exit-status "$(gh run list --workflow CI --limit 1 --json databaseId --jq '.[0].databaseId')"
-```
-Expected: CI passes. The `Consumers` workflow runs on pull requests only, so this push does not start it.
-
-### Task 12: The site: one page of showcase and docs
-
-**Files:**
-- Create: `apps/site/package.json`, `apps/site/turbo.json`, `apps/site/tsconfig.json`, `apps/site/next.config.mjs`, `apps/site/postcss.config.mjs`, `apps/site/vitest.config.ts`, `apps/site/playwright.config.ts`, `apps/site/public/icon.svg`
-- Create: `apps/site/lib/figures.ts`, `apps/site/lib/snippets.ts`, `apps/site/lib/llms.ts`, `apps/site/lib/highlight.ts`
-- Create: `apps/site/app/globals.css`, `apps/site/app/layout.tsx`, `apps/site/app/page.tsx`, `apps/site/app/llms.txt/route.ts`
-- Create: `apps/site/components/tile.tsx`, `apps/site/components/figure-demo.tsx`, `apps/site/components/tabs.tsx`, `apps/site/components/theme-editor.tsx`
-- Test: `apps/site/test/docs.test.ts`, `apps/site/test/site.spec.ts`
-- Modify: `pnpm-lock.yaml`
-
-**Interfaces:**
-- Consumes:
- - The package through its public entries only, never `src/`:
- - `ranges`, `Range` and the six functions from `@lucasmarkes/hairline`.
- - The six components and their props types from `@lucasmarkes/hairline/react`.
- - From Task 10: `resolveBaseUrl()` from `scripts/base-url.mjs`, and `node registry/build.mjs` as the site's `prebuild` and `predev`.
-- Produces:
- - `@hairline/site`, a private workspace package. Its scripts are `build`, `dev` (port 3000), `start`, `typecheck`, `test` (Vitest) and `test:browser` (Playwright against `next start` on port 4320), so the root's turbo tasks run it with the package.
- - `process.env.NEXT_PUBLIC_SITE_URL`, set at build.
- - `lib/figures.ts`:
- - `FigureId`, `FigureDoc`, `FIGURES`, `CARDS`, `span(range)`, `shown(value, range)`.
- - `Row`, `rows(doc)`, `SHARED`, `THEME`, `NOTES`, `LINKS`.
- - `lib/snippets.ts`: `PACKAGE`, `install(base)`, `react(doc, value)`, `vanilla(doc, value)`, `FRAMEWORKS`, `themeCss(colors, stroke)`.
- - `lib/llms.ts`: `llms(base): string`.
- - `lib/highlight.ts`: `LIVE`, `highlight(code, lang, initial?)`, `plain(code)`.
- - `components/tile.tsx`: `Tile({ id, index, name, options?, style? })`. Task 13's Open Graph route uses it.
- - Routes: `/` and `/llms.txt`, both static, and `/r/*.json`, generated by `prebuild`.
-
-The page is the spec's "The site", in order:
-1. **Hero**: six live tiles and the install tabs (pnpm, npm, yarn, bun, shadcn).
-2. **One section per figure**: a tile, a slider built from `ranges`, React and vanilla code that follows the slider, and the props table.
-3. **Theme**: a live editor that writes the CSS.
-4. **Frameworks**: Next.js, Vue, Svelte, Astro and plain HTML from a CDN.
-5. **Notes**.
-6. **Footer**: GitHub, npm, the essay, the credit to Linear, MIT.
-
-Code is highlighted with Shiki at build. The live value is a span marked with `LIVE` that the client swaps, so no highlighter ships to the browser.
-
-`docs.test.ts` is the spec's "a test asserts that the props tables match `ranges`". It also checks that the snippets install from the address the site is built for, and that `/llms.txt` has no hole in it (no `undefined`, `NaN` or `[object`).
-
-- [ ] **Step 1: Write the site's package and configuration**
-
-`apps/site/package.json`
-```json
-{
- "name": "@hairline/site",
- "version": "0.0.0",
- "private": true,
- "type": "module",
- "scripts": {
- "prebuild": "node ../../registry/build.mjs",
- "build": "next build",
- "predev": "node ../../registry/build.mjs",
- "dev": "next dev -p 3000",
- "start": "next start -p 3000",
- "typecheck": "tsc --noEmit",
- "test": "vitest run",
- "test:browser": "playwright test",
- "clean": "rm -rf .next .turbo public/r"
- },
- "dependencies": {
- "@lucasmarkes/hairline": "workspace:*",
- "@vercel/analytics": "2.0.1",
- "geist": "1.7.2",
- "next": "16.3.8",
- "react": "19.3.0",
- "react-dom": "19.3.0",
- "shiki": "4.5.0"
- },
- "devDependencies": {
- "@playwright/test": "1.63.0",
- "@tailwindcss/postcss": "4.3.3",
- "@types/node": "^22",
- "@types/react": "19.3.0",
- "@types/react-dom": "19.3.0",
- "tailwindcss": "4.3.3",
- "typescript": "5.9.3",
- "vitest": "5.0.3"
- }
-}
-```
-
-The site's build reads files outside its folder and depends on the deploy's address, so its turbo task names both:
-
-`apps/site/turbo.json`
-```json
-{
- "$schema": "https://turbo.build/schema.json",
- "extends": ["//"],
- "tasks": {
- "build": {
- "inputs": ["$TURBO_DEFAULT$", "../../registry/**", "../../scripts/base-url.mjs"],
- "outputs": [".next/**", "!.next/cache/**", "public/r/**"],
- "env": ["HAIRLINE_REGISTRY_URL", "VERCEL_ENV", "VERCEL_URL", "VERCEL_PROJECT_PRODUCTION_URL"]
- }
- }
-}
-```
-
-`apps/site/tsconfig.json`
-```json
-{
- "extends": "../../tsconfig.base.json",
- "compilerOptions": {
- "lib": ["dom", "dom.iterable", "esnext"],
- "noEmit": true,
- "jsx": "react-jsx",
- "allowJs": true,
- "incremental": true,
- "resolveJsonModule": true,
- "plugins": [{ "name": "next" }],
- "paths": { "@/*": ["./*"] }
- },
- "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"],
- "exclude": ["node_modules"]
-}
-```
-
-`apps/site/next.config.mjs`
-```js
-import { resolveBaseUrl } from "../../scripts/base-url.mjs";
-
-/**
- * The site's own address, resolved once at build (see scripts/base-url.mjs):
- * the Open Graph tags, the shadcn command and /llms.txt all need it absolute.
- */
-export default {
- env: { NEXT_PUBLIC_SITE_URL: resolveBaseUrl() },
-};
-```
-
-`apps/site/postcss.config.mjs`
-```js
-export default { plugins: { "@tailwindcss/postcss": {} } };
-```
-
-`apps/site/vitest.config.ts`
-```ts
-import { fileURLToPath } from "node:url";
-import { defineConfig } from "vitest/config";
-
-export default defineConfig({
- resolve: { alias: { "@": fileURLToPath(new URL(".", import.meta.url)) } },
- test: { environment: "node", include: ["test/**/*.test.ts"] },
-});
-```
-
-`apps/site/playwright.config.ts`
-```ts
-import { defineConfig } from "@playwright/test";
-
-/** The built site, served by `next start`. Run `pnpm build` first; turbo does. */
-export default defineConfig({
- testDir: "test",
- testMatch: "*.spec.ts",
- fullyParallel: true,
- reporter: "list",
- use: { channel: "chrome", baseURL: "http://localhost:4320", viewport: { width: 1200, height: 900 } },
- webServer: { command: "pnpm exec next start -p 4320", url: "http://localhost:4320", reuseExistingServer: !process.env.CI },
-});
-```
-
-`apps/site/public/icon.svg`
-```text
-<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="#fff"/><path d="M16 7 26 12.5 16 18 6 12.5Z M6 12.5v7L16 25l10-5.5v-7 M16 18v7" fill="none" stroke="#232327" stroke-width="1.5" stroke-linejoin="round"/></svg>
-```
-
-Run: `pnpm install`
-Expected: the site's dependencies install, and `pnpm-lock.yaml` gains the `apps/site` importer.
-
-- [ ] **Step 2: Write the docs test, and see it fail**
-
-`apps/site/test/docs.test.ts`
-````ts
-import { describe, expect, it } from "vitest";
-import { ranges } from "@lucasmarkes/hairline";
-import * as components from "@lucasmarkes/hairline/react";
-import * as figures from "@lucasmarkes/hairline";
-import { FIGURES, SHARED, rows, span } from "@/lib/figures";
-import { llms } from "@/lib/llms";
-import { FRAMEWORKS, install, react, vanilla } from "@/lib/snippets";
-
-/** The docs are generated from the package, and these check that nothing was written by hand around it. */
-
-describe("the props tables", () => {
- it("have one figure per entry of ranges, in the same order", () => {
- expect(FIGURES.map((f) => f.id)).toEqual(Object.keys(ranges));
- });
-
- it.each(FIGURES)("$name's first row is its numeric option, with the package's default and bounds", (doc) => {
- const range = (ranges[doc.id] as Record<string, { min: number; max: number; default: number }>)[doc.option];
- const [row] = rows(doc);
- expect(range).toBeDefined();
- expect(row.name).toBe(doc.option);
- expect(row.type).toBe("number");
- expect(row.default).toBe(String(range.default));
- expect(row.description).toContain(String(range.min));
- expect(row.description).toContain(String(range.max));
- });
-
- it("list Riffle's two other options and nobody else's", () => {
- expect(rows(FIGURES[0]).map((r) => r.name)).toEqual(["stagger", "bands", "labels"]);
- for (const doc of FIGURES.slice(1)) expect(rows(doc)).toHaveLength(1);
- });
-
- it("list the shared options", () => {
- expect(SHARED.map((r) => r.name)).toEqual(["theme", "label", "onRead"]);
- });
-
- it("write a range the way a person would", () => {
- expect(span(ranges.riffle.stagger)).toBe("0 to 90 ms");
- expect(span(ranges.slow.rate)).toBe("0.05× to 0.6×");
- expect(span(ranges.exploded.gap)).toBe("12 to 40 units");
- });
-});
-
-describe("the snippets", () => {
- it.each(FIGURES)("name an export that exists: $name", (doc) => {
- expect(components).toHaveProperty(doc.name);
- expect(figures).toHaveProperty(doc.id);
- expect(react(doc, 7)).toContain(`<${doc.name} ${doc.option}={7}`);
- expect(vanilla(doc, 7)).toContain(`${doc.id}(document.getElementById("figure")!, { ${doc.option}: 7 })`);
- });
-
- it("install from the address the site is built for", () => {
- const commands = install("https://example.test");
- expect(commands.map((c) => c.label)).toEqual(["pnpm", "npm", "yarn", "bun", "shadcn"]);
- expect(commands[4].code).toBe("npx shadcn@latest add https://example.test/r/hairline.json");
- });
-
- it("cover the five frameworks", () => {
- expect(FRAMEWORKS.map((f) => f.label)).toEqual(["Next.js", "Vue", "Svelte", "Astro", "CDN"]);
- });
-});
-
-describe("/llms.txt", () => {
- const text = llms("https://example.test");
-
- it.each(FIGURES)("documents $name with its range and both snippets", (doc) => {
- expect(text).toContain(`### ${doc.name}`);
- expect(text).toContain(span(doc.range));
- expect(text).toContain(react(doc, doc.range.default).trimEnd());
- expect(text).toContain(vanilla(doc, doc.range.default).trimEnd());
- });
-
- it("names every theme property and the registry item", () => {
- for (const key of ["plate", "hi", "edge", "mid", "lo", "stroke"]) expect(text).toContain(`--hairline-${key}`);
- expect(text).toContain("https://example.test/r/hairline.json");
- });
-
- it("has no hole in it", () => {
- // outside the code blocks, where `undefined` is a word TypeScript uses
- const prose = text.replace(/```[\s\S]*?```/g, "");
- expect(prose).not.toMatch(/undefined|NaN|\[object/);
- });
-});
-````
-
-Run: `pnpm --filter @hairline/site test`
-Expected: FAIL with `Error: Cannot find package '@/lib/figures' imported from …/test/docs.test.ts`.
-
-- [ ] **Step 3: Write the docs data**
-
-Everything the page says about an option comes from `ranges` and from these four files. The page and `/llms.txt` read the same text.
-
-`apps/site/lib/figures.ts`
-```ts
-import { ranges, type Range } from "@lucasmarkes/hairline";
-
-/**
- * The page's copy about each figure. Everything numeric comes from the
- * package's own `ranges`, so a slider, a props table and /llms.txt cannot
- * disagree with what the figure does.
- */
-
-export type FigureId = keyof typeof ranges;
-
-export type FigureDoc = {
- id: FigureId;
- /** The React component, and the figure's name on the page. */
- name: string;
- /** The figure's one numeric option. */
- option: string;
- range: Range;
- summary: string;
- optionDoc: string;
-};
-
-const COPY: Record<FigureId, { name: string; summary: string; optionDoc: string }> = {
- riffle: {
- name: "Riffle",
- summary: "A tray of eight cards. The card under the pointer stands up and its neighbours lean after it. The arrow keys walk the cards.",
- optionDoc: "The delay between one card and the next as they lean.",
- },
- terrain: {
- name: "Terrain",
- summary: "Eighty-one pillars on a plinth. They rise around the pointer and settle back into a dune with two rises.",
- optionDoc: "How far the rise reaches around the pointer.",
- },
- exploded: {
- name: "Exploded",
- summary: "An app window taken apart into four layers. Moving across opens the gap; moving down picks a layer.",
- optionDoc: "The space between two layers when fully open, in viewBox units (the drawing is 400 × 320).",
- },
- phosphor: {
- name: "Phosphor",
- summary: "A seven by seven dot matrix playing a loop. Where the pointer paints, the dots fade like phosphor.",
- optionDoc: "How long a painted dot takes to fade.",
- },
- slow: {
- name: "Slow",
- summary: "Crates riding a belt through a gate. Hovering slows the clock without stopping it.",
- optionDoc: "The clock's speed while the pointer is over the figure, as a multiple of normal.",
- },
- turntable: {
- name: "Turntable",
- summary: "Blocks on a turntable. A flick across it spins it, and it settles on the nearest quarter turn.",
- optionDoc: "How long a flick keeps the table turning.",
- },
-};
-
-export const FIGURES: FigureDoc[] = (Object.keys(ranges) as FigureId[]).map((id) => {
- const [option, range] = Object.entries(ranges[id])[0] as [string, Range];
- return { id, option, range, ...COPY[id] };
-});
-
-/** Names for Riffle's eight cards on this page. */
-export const CARDS = ["Radial menu", "Drum", "Dock", "Condense", "Settle", "Upload", "Badge", "Spark"] as const;
-
-/** "0 to 90 ms", "0.05× to 0.6×", "12 to 40 units" */
-export function span(range: Range): string {
- if (range.unit === "×") return `${range.min}× to ${range.max}×`;
- return `${range.min} to ${range.max} ${range.unit === "u" ? "units" : range.unit}`;
-}
-
-/** A value as the page shows it next to a slider: "40 ms", "0.2×" */
-export function shown(value: number, range: Range): string {
- return range.unit === "×" ? `${value}×` : `${value} ${range.unit}`;
-}
-
-export type Row = { name: string; type: string; default: string; description: string };
-
-/** A figure's own options, the numeric one first. */
-export function rows(doc: FigureDoc): Row[] {
- const out: Row[] = [
- { name: doc.option, type: "number", default: String(doc.range.default), description: `${doc.optionDoc} ${span(doc.range)}.` },
- ];
- if (doc.id === "riffle") {
- out.push(
- { name: "bands", type: "boolean", default: "false", description: "Shows the bands the pointer is tested against." },
- { name: "labels", type: "readonly string[]", default: "[]", description: "Names for the eight cards, card 01 first. A named card is read out as \"03 · Dock\", an unnamed one as \"03\"." },
- );
- }
- return out;
-}
-
-/** The options every figure takes. */
-export const SHARED: Row[] = [
- { name: "theme", type: "\"auto\" | \"light\" | \"dark\"", default: "\"auto\"", description: "\"auto\" follows the page: an ancestor with class dark or data-theme=\"dark\", then the page's color-scheme." },
- { name: "label", type: "string", default: "a description in English", description: "The accessible name. In React, aria-label does the same." },
- { name: "onRead", type: "(text: string) => void", default: "", description: "The figure's caption, each time it changes. Called once at mount with the rest caption." },
-];
-
-/** The public theme: six custom properties, set on the figure or on anything above it. */
-export const THEME: { property: string; role: string }[] = [
- { property: "--hairline-plate", role: "The fill of every plate. It hides what is drawn behind, so it must be the colour the figure sits on." },
- { property: "--hairline-hi", role: "The stroke of what is lit: the card pulled, the layer picked, a dot that is on." },
- { property: "--hairline-edge", role: "Silhouettes, and dots at half strength." },
- { property: "--hairline-mid", role: "Every other stroke." },
- { property: "--hairline-lo", role: "What recedes: guides, and dots that are off." },
- { property: "--hairline-stroke", role: "The stroke width, in CSS pixels at any size. Default 0.9." },
-];
-
-export const NOTES: { title: string; body: string }[] = [
- { title: "Accessibility", body: "A figure is an image with a description you can replace with label. Riffle is the exception: it is a focusable group, the arrow keys walk its cards, and a live region reads the card out." },
- { title: "Reduced motion", body: "With prefers-reduced-motion, the figures that play on their own (Phosphor and Slow) hold still, and every figure still answers the pointer." },
- { title: "Performance", body: "Every figure on a page shares one requestAnimationFrame loop. A figure off screen, or at rest, does no work, and the loop stops when nothing is moving." },
- { title: "Server rendering", body: "On the server a figure is an empty box with a 5:4 aspect ratio, so nothing shifts when it draws. The drawing itself happens in the browser." },
- { title: "Size", body: "No dependencies. A bundle that imports one figure carries one figure." },
-];
-
-export const LINKS = {
- github: "https://github.com/lucasmarkes/hairline",
- npm: "https://www.npmjs.com/package/@lucasmarkes/hairline",
- essay: "https://lucasmarkes.com/lab/hairline",
- linear: "https://linear.app",
-} as const;
-```
-
-`apps/site/lib/snippets.ts`
-```ts
-import type { FigureDoc } from "./figures";
-
-/**
- * Every piece of code the page shows, as plain text. The page highlights it;
- * /llms.txt prints it as it is.
- */
-
-export const PACKAGE = "@lucasmarkes/hairline";
-
-export function install(base: string): { label: string; code: string }[] {
- return [
- { label: "pnpm", code: `pnpm add ${PACKAGE}` },
- { label: "npm", code: `npm install ${PACKAGE}` },
- { label: "yarn", code: `yarn add ${PACKAGE}` },
- { label: "bun", code: `bun add ${PACKAGE}` },
- { label: "shadcn", code: `npx shadcn@latest add ${base}/r/hairline.json` },
- ];
-}
-
-export function react(doc: FigureDoc, value: string | number): string {
- return `import { ${doc.name} } from "${PACKAGE}/react";
-
-export function Figure() {
- return <${doc.name} ${doc.option}={${value}} className="w-80" />;
-}
-`;
-}
-
-export function vanilla(doc: FigureDoc, value: string | number): string {
- return `import { ${doc.id} } from "${PACKAGE}";
-
-const figure = ${doc.id}(document.getElementById("figure")!, { ${doc.option}: ${value} });
-
-// later
-figure.update({ ${doc.option}: ${doc.range.max} });
-figure.destroy();
-`;
-}
-
-export const FRAMEWORKS: { label: string; lang: string; code: string }[] = [
- {
- label: "Next.js",
- lang: "tsx",
- code: `// app/page.tsx — a Server Component. The React entry is a client module,
-// so there is no "use client" to write.
-import { Terrain } from "${PACKAGE}/react";
-
-export default function Page() {
- return <Terrain radius={4} className="w-96" />;
-}
-`,
- },
- {
- label: "Vue",
- lang: "vue",
- code: `<script setup lang="ts">
-import { onBeforeUnmount, onMounted, ref } from "vue";
-import { terrain, type Figure, type TerrainOptions } from "${PACKAGE}";
-
-const el = ref<HTMLElement>();
-let figure: Figure<TerrainOptions> | undefined;
-
-onMounted(() => { figure = terrain(el.value!, { radius: 4 }); });
-onBeforeUnmount(() => figure?.destroy());
-</script>
-
-<template>
- <div ref="el" />
-</template>
-`,
- },
- {
- label: "Svelte",
- lang: "svelte",
- code: `<script lang="ts">
- import { terrain, type TerrainOptions } from "${PACKAGE}";
-
- // A figure has the shape of a Svelte action: { update, destroy }.
- const figure = (el: HTMLElement, options: TerrainOptions) => terrain(el, options);
- let radius = 4;
-</script>
-
-<div use:figure={{ radius }} />
-`,
- },
- {
- label: "Astro",
- lang: "astro",
- code: `<div id="figure"></div>
-
-<script>
- import { terrain } from "${PACKAGE}";
-
- terrain(document.getElementById("figure")!, { radius: 4 });
-</script>
-`,
- },
- {
- label: "CDN",
- lang: "html",
- code: `<div id="figure" style="width: 400px"></div>
-
-<script type="module">
- import { terrain } from "https://esm.sh/${PACKAGE}";
-
- terrain(document.getElementById("figure"), { radius: 4 });
-</script>
-`,
- },
-];
-
-/** What the theme editor prints. */
-export function themeCss(colors: Record<string, string>, stroke: number): string {
- const lines = Object.entries(colors).map(([k, v]) => ` --hairline-${k}: ${v};`);
- return `.figures {\n${lines.join("\n")}\n --hairline-stroke: ${stroke};\n}\n`;
-}
-```
-
-`apps/site/lib/llms.ts`
-````ts
-import { FIGURES, LINKS, NOTES, SHARED, THEME, rows, type Row } from "./figures";
-import { FRAMEWORKS, PACKAGE, install, react, vanilla } from "./snippets";
-
-/** The page as plain text, for a model to read: the same data, the same copy. */
-
-const table = (list: Row[]) => list.map((r) => `- \`${r.name}\` (${r.type}${r.default ? `, default ${r.default}` : ""}): ${r.description}`).join("\n");
-const fence = (lang: string, code: string) => "```" + lang + "\n" + code.trimEnd() + "\n```";
-
-export function llms(base: string): string {
- const out: string[] = [
- "# hairline",
- "",
- `> ${PACKAGE}: six isometric line figures that answer the pointer. SVG, no dependencies, ESM only. A function per figure, and a React component per figure.`,
- "",
- "## Install",
- "",
- fence("sh", install(base).map((i) => i.code).join("\n")),
- "",
- "## Use",
- "",
- `Vanilla: \`import { ${FIGURES.map((f) => f.id).join(", ")} } from "${PACKAGE}"\`. Each function takes an element and options, draws into the element, and returns \`{ update(options), destroy() }\`.`,
- "",
- `React: \`import { ${FIGURES.map((f) => f.name).join(", ")} } from "${PACKAGE}/react"\`. Each component renders a \`<div>\`, takes the figure's options and any \`<div>\` attribute, and forwards its ref. The entry is a client module: render it from a Server Component without writing "use client".`,
- "",
- "A figure fills its element's width at a 5:4 aspect ratio. Give the element a width.",
- "",
- "## Options every figure takes",
- "",
- table(SHARED),
- "",
- "## Figures",
- ];
- for (const doc of FIGURES) {
- out.push("", `### ${doc.name}`, "", doc.summary, "", table(rows(doc)), "", fence("tsx", react(doc, doc.range.default)), "", fence("ts", vanilla(doc, doc.range.default)));
- }
- out.push(
- "", "## Ranges", "",
- `\`import { ranges } from "${PACKAGE}"\` gives every numeric option's \`min\`, \`max\`, \`step\`, \`default\` and \`unit\`. A value outside its range is clamped; a value that is not a number becomes the default.`,
- "", "## Theme", "",
- "Six CSS custom properties, set on the figure or on any ancestor. Without them a figure is light, or dark when an ancestor has class `dark` or `data-theme=\"dark\"`, or when the page's `color-scheme` is dark.",
- "", THEME.map((t) => `- \`${t.property}\`: ${t.role}`).join("\n"),
- "", "## Frameworks",
- );
- for (const f of FRAMEWORKS) out.push("", `### ${f.label}`, "", fence(f.lang, f.code));
- out.push("", "## Notes", "", NOTES.map((n) => `- ${n.title}: ${n.body}`).join("\n"));
- out.push("", "## Links", "", `- Site: ${base}`, `- Source: ${LINKS.github}`, `- npm: ${LINKS.npm}`, `- The essay the figures come from: ${LINKS.essay}`, `- shadcn registry item: ${base}/r/hairline.json`, "");
- return out.join("\n");
-}
-````
-
-`apps/site/lib/highlight.ts`
-```ts
-import { codeToHtml } from "shiki";
-
-/**
- * Highlighting happens here, at build, so no highlighter reaches the browser.
- *
- * A snippet that follows a slider is written with LIVE where the value goes.
- * After highlighting, LIVE becomes a marked span holding the default; the
- * client only ever changes that span's text.
- */
-export const LIVE = "424242";
-
-const escape = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
-
-export async function highlight(code: string, lang: string, initial?: string | number): Promise<string> {
- const html = await codeToHtml(code.trimEnd(), { lang, theme: "min-light" });
- return initial === undefined ? html : html.replaceAll(LIVE, `<span data-live>${escape(String(initial))}</span>`);
-}
-
-/** A shell command, unhighlighted, in the same wrapper the highlighter writes. */
-export function plain(code: string): string {
- return `<pre class="shiki"><code>${escape(code.trimEnd())}</code></pre>`;
-}
-```
-
-Run: `pnpm --filter @hairline/site test`
-Expected: PASS, 26 tests.
-
-- [ ] **Step 4: Write the components**
-
-`apps/site/components/tile.tsx`
-```tsx
-"use client";
-
-import { useState, type ComponentType, type CSSProperties } from "react";
-import { Exploded, Phosphor, Riffle, Slow, Terrain, Turntable } from "@lucasmarkes/hairline/react";
-import { CARDS, type FigureId } from "@/lib/figures";
-
-const COMPONENTS = { riffle: Riffle, terrain: Terrain, exploded: Exploded, phosphor: Phosphor, slow: Slow, turntable: Turntable };
-
-/** A live figure on a white tile, with its number, its name and its caption in the corners. */
-export function Tile({ id, index, name, options, style }: { id: FigureId; index: number; name: string; options?: Record<string, unknown>; style?: CSSProperties }) {
- const [read, setRead] = useState("");
- const Figure = COMPONENTS[id] as unknown as ComponentType<Record<string, unknown>>;
- return (
- <div className="tile" style={style} data-figure={id}>
- <Figure {...(id === "riffle" ? { labels: CARDS } : null)} {...options} onRead={setRead} />
- <span className="cap left-4 top-3">Fig. {index}</span>
- <span className="cap right-4 top-3">{name}</span>
- <span className="cap bottom-3 left-4" data-read aria-hidden="true">{read}</span>
- </div>
- );
-}
-```
-
-`apps/site/components/figure-demo.tsx`
-```tsx
-"use client";
-
-import { useId, useState } from "react";
-import type { Range } from "@lucasmarkes/hairline";
-import { shown, type FigureId } from "@/lib/figures";
-import { Tabs, type Tab } from "./tabs";
-import { Tile } from "./tile";
-
-/** A figure, the slider for its option, and the code that follows the slider. */
-export function FigureDemo({ id, index, name, option, range, tabs }: { id: FigureId; index: number; name: string; option: string; range: Range; tabs: Tab[] }) {
- const [value, setValue] = useState(range.default);
- const slider = useId();
- return (
- <div className="grid items-start gap-6 md:grid-cols-2 [&>*]:min-w-0">
- <Tile id={id} index={index} name={name} options={{ [option]: value }} />
- <div className="grid gap-4 [&>*]:min-w-0">
- <div className="flex items-center gap-4 font-mono text-[13px]">
- <label htmlFor={slider} className="w-20 text-ink">{option}</label>
- <input id={slider} type="range" className="slider" min={range.min} max={range.max} step={range.step} value={value} onChange={(event) => setValue(Number(event.target.value))} />
- <output htmlFor={slider} className="w-20 text-right text-muted">{shown(value, range)}</output>
- </div>
- <Tabs tabs={tabs} label={`${name} code`} live={String(value)} />
- </div>
- </div>
- );
-}
-```
-
-`apps/site/components/tabs.tsx`
-```tsx
-"use client";
-
-import { useEffect, useId, useRef, useState, type KeyboardEvent } from "react";
-
-export type Tab = { label: string; html: string };
-
-/**
- * Code behind tabs, with a copy button. The HTML is highlighted at build; when
- * `live` is given, every span marked data-live shows it, so a snippet follows
- * a slider without a highlighter in the browser.
- */
-export function Tabs({ tabs, label, live }: { tabs: Tab[]; label: string; live?: string }) {
- const [at, setAt] = useState(0);
- const [copied, setCopied] = useState(false);
- const panel = useRef<HTMLDivElement>(null);
- const list = useRef<HTMLDivElement>(null);
- const id = useId();
-
- useEffect(() => {
- if (live === undefined) return;
- panel.current?.querySelectorAll("[data-live]").forEach((node) => { node.textContent = live; });
- }, [live, at]);
-
- useEffect(() => {
- if (!copied) return;
- const timer = setTimeout(() => setCopied(false), 1600);
- return () => clearTimeout(timer);
- }, [copied]);
-
- const copy = async () => {
- try {
- await navigator.clipboard.writeText(panel.current?.textContent ?? "");
- setCopied(true);
- } catch {
- // no clipboard permission: the text is still selectable
- }
- };
-
- const onKeyDown = (event: KeyboardEvent) => {
- const step = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0;
- if (!step) return;
- event.preventDefault();
- const next = (at + step + tabs.length) % tabs.length;
- setAt(next);
- list.current?.querySelectorAll<HTMLButtonElement>("[role=tab]")[next]?.focus();
- };
-
- return (
- <div className="code">
- <div className="code-bar">
- <div ref={list} role="tablist" aria-label={label} onKeyDown={onKeyDown} className="flex gap-1">
- {tabs.map((tab, i) => (
- <button key={tab.label} type="button" role="tab" id={`${id}-tab-${i}`} aria-selected={i === at} aria-controls={`${id}-panel`} tabIndex={i === at ? 0 : -1} onClick={() => setAt(i)} className="code-tab">
- {tab.label}
- </button>
- ))}
- </div>
- <button type="button" onClick={copy} className="code-copy" aria-live="polite">
- {copied ? "Copied" : "Copy"}
- </button>
- </div>
- <div ref={panel} role="tabpanel" id={`${id}-panel`} aria-labelledby={`${id}-tab-${at}`} tabIndex={0} className="code-panel" dangerouslySetInnerHTML={{ __html: tabs[at].html }} />
- </div>
- );
-}
-```
-
-`apps/site/components/theme-editor.tsx`
-```tsx
-"use client";
-
-import { useState, type CSSProperties } from "react";
-import { themeCss } from "@/lib/snippets";
-import { Tile } from "./tile";
-
-type Colors = { plate: string; hi: string; edge: string; mid: string; lo: string };
-
-/** The package's own palettes, and one that is neither. */
-const PRESETS: Record<string, Colors> = {
- Light: { plate: "#ffffff", hi: "#232327", edge: "#a4a4ac", mid: "#c3c3c9", lo: "#e0e0e4" },
- Dark: { plate: "#08090a", hi: "#d0d6e0", edge: "#5b5d64", mid: "#3e3e44", lo: "#29292d" },
- Blueprint: { plate: "#0f2f57", hi: "#eaf2ff", edge: "#8fb2e0", mid: "#5b83ba", lo: "#2b4f80" },
-};
-const KEYS = ["plate", "hi", "edge", "mid", "lo"] as const;
-
-/** The six theme properties, live: change one and the figure and the CSS below both follow. */
-export function ThemeEditor() {
- const [colors, setColors] = useState<Colors>(PRESETS.Light);
- const [stroke, setStroke] = useState(0.9);
- const [copied, setCopied] = useState(false);
- const css = themeCss(colors, stroke);
- const style = { background: colors.plate, "--hairline-stroke": stroke, ...Object.fromEntries(KEYS.map((k) => [`--hairline-${k}`, colors[k]])) } as CSSProperties;
-
- const copy = async () => {
- try {
- await navigator.clipboard.writeText(css);
- setCopied(true);
- setTimeout(() => setCopied(false), 1600);
- } catch {
- // no clipboard permission: the text is still selectable
- }
- };
-
- return (
- <div className="grid items-start gap-6 md:grid-cols-2 [&>*]:min-w-0">
- <Tile id="exploded" index={3} name="Exploded" style={style} />
- <div className="grid gap-4 [&>*]:min-w-0">
- <div className="flex gap-2">
- {Object.entries(PRESETS).map(([name, preset]) => (
- <button key={name} type="button" className="chip" aria-pressed={KEYS.every((k) => colors[k] === preset[k])} onClick={() => setColors(preset)}>
- {name}
- </button>
- ))}
- </div>
- <div className="grid gap-2 font-mono text-[13px]">
- {KEYS.map((key) => (
- <label key={key} className="flex items-center gap-3">
- <input type="color" className="swatch" value={colors[key]} onChange={(event) => setColors({ ...colors, [key]: event.target.value })} />
- <span className="text-ink">--hairline-{key}</span>
- <span className="ml-auto text-muted">{colors[key]}</span>
- </label>
- ))}
- <label className="flex items-center gap-3">
- <span className="text-ink">--hairline-stroke</span>
- <input type="range" className="slider" min={0.5} max={2} step={0.1} value={stroke} onChange={(event) => setStroke(Number(event.target.value))} />
- <span className="w-8 text-right text-muted">{stroke}</span>
- </label>
- </div>
- <div className="code">
- <div className="code-bar">
- <span className="code-tab" aria-selected="true">CSS</span>
- <button type="button" onClick={copy} className="code-copy" aria-live="polite">{copied ? "Copied" : "Copy"}</button>
- </div>
- <pre className="code-panel" data-theme-css>{css}</pre>
- </div>
- </div>
- </div>
- );
-}
-```
-
-- [ ] **Step 5: Write the page and its routes**
-
-`apps/site/app/globals.css`
-```css
-@import "tailwindcss";
-
-/* The look of the tweet videos: warm paper, white tiles with a soft shadow, mono captions in the corners. */
-@theme {
- --font-sans: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
- --font-mono: var(--font-geist-mono), ui-monospace, monospace;
- --color-ground: #efebe5;
- --color-ink: #232327;
- --color-muted: #77736c;
- --color-line: rgba(28, 22, 14, 0.1);
-}
-
-html { color-scheme: light; scroll-behavior: smooth; }
-
-body {
- min-height: 100vh;
- color: var(--color-ink);
- background:
- radial-gradient(60% 75% at 16% 8%, rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 0) 70%) fixed,
- linear-gradient(160deg, #f7f5f2 0%, #f0ece6 55%, #e9e4dd 100%) fixed,
- var(--color-ground);
-}
-
-.tile {
- position: relative;
- overflow: hidden;
- border-radius: 12px;
- background: #fff;
- box-shadow:
- 0 0 0 1px rgba(0, 0, 0, 0.05),
- 0 2px 6px rgba(28, 22, 14, 0.05),
- 0 20px 50px -18px rgba(28, 22, 14, 0.18);
-}
-
-.cap {
- position: absolute;
- font: 500 11px/1 var(--font-mono);
- letter-spacing: 0.02em;
- color: var(--hairline-edge, #a4a4ac);
- pointer-events: none;
- font-variant-numeric: tabular-nums;
-}
-
-.code { overflow: hidden; border-radius: 12px; background: rgba(255, 255, 255, 0.66); box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.05); }
-.code-bar { display: flex; align-items: center; justify-content: space-between; padding: 6px 6px 6px 8px; border-bottom: 1px solid var(--color-line); }
-.code-tab, .code-copy, .chip { border-radius: 7px; padding: 5px 10px; font: 500 12px/1 var(--font-mono); color: var(--color-muted); }
-.code-tab[aria-selected="true"], .chip[aria-pressed="true"] { background: rgba(28, 22, 14, 0.07); color: var(--color-ink); }
-.code-copy:hover, .code-tab:hover, .chip:hover { color: var(--color-ink); }
-.chip { box-shadow: 0 0 0 1px var(--color-line); }
-.code-panel { margin: 0; overflow-x: auto; padding: 14px 16px; font: 400 13px/1.6 var(--font-mono); }
-.code-panel pre { margin: 0; background: transparent !important; }
-.code-panel code { font: inherit; }
-:is(.code-tab, .code-copy, .chip, .code-panel, .slider, .swatch, a):focus-visible { outline: 1.5px solid var(--color-ink); outline-offset: 2px; }
-
-.slider { flex: 1; min-width: 0; height: 18px; appearance: none; background: transparent; cursor: pointer; }
-.slider::-webkit-slider-runnable-track { height: 2px; border-radius: 1px; background: rgba(28, 22, 14, 0.18); }
-.slider::-webkit-slider-thumb { appearance: none; width: 14px; height: 14px; margin-top: -6px; border-radius: 50%; background: var(--color-ink); }
-.slider::-moz-range-track { height: 2px; border-radius: 1px; background: rgba(28, 22, 14, 0.18); }
-.slider::-moz-range-thumb { width: 14px; height: 14px; border: 0; border-radius: 50%; background: var(--color-ink); }
-
-.swatch { width: 26px; height: 26px; padding: 0; border: 0; border-radius: 7px; background: none; cursor: pointer; }
-.swatch::-webkit-color-swatch-wrapper { padding: 0; }
-.swatch::-webkit-color-swatch { border: 1px solid var(--color-line); border-radius: 7px; }
-
-.props { width: 100%; border-collapse: collapse; font-size: 13px; }
-.props th { padding: 8px 12px 8px 0; text-align: left; font: 500 11px/1 var(--font-mono); letter-spacing: 0.04em; text-transform: uppercase; color: var(--color-muted); }
-.props td { padding: 10px 12px 10px 0; vertical-align: top; border-top: 1px solid var(--color-line); }
-.props td:nth-child(-n + 3) { font-family: var(--font-mono); white-space: nowrap; }
-.props td:nth-child(2), .props td:nth-child(3) { color: var(--color-muted); }
-
-@media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } }
-```
-
-The metadata names `/og.png`. Task 13 makes it, and nothing on the page loads it before then.
-
-`apps/site/app/layout.tsx`
-```tsx
-import type { Metadata } from "next";
-import type { ReactNode } from "react";
-import { GeistMono } from "geist/font/mono";
-import { GeistSans } from "geist/font/sans";
-import { Analytics } from "@vercel/analytics/next";
-import "./globals.css";
-
-const SITE = process.env.NEXT_PUBLIC_SITE_URL!;
-const DESCRIPTION = "Six isometric line figures that answer the pointer. SVG, no dependencies, for React and for everything else.";
-
-export const metadata: Metadata = {
- metadataBase: new URL(SITE),
- title: "hairline",
- description: DESCRIPTION,
- alternates: { canonical: "/" },
- openGraph: { title: "hairline", description: DESCRIPTION, url: "/", siteName: "hairline", type: "website", images: [{ url: "/og.png", width: 1200, height: 630, alt: "The six hairline figures on a board." }] },
- twitter: { card: "summary_large_image", title: "hairline", description: DESCRIPTION, images: ["/og.png"], creator: "@lucasmarkes" },
- icons: { icon: "/icon.svg" },
-};
-
-export default function RootLayout({ children }: { children: ReactNode }) {
- return (
- <html lang="en" className={`${GeistSans.variable} ${GeistMono.variable}`}>
- <body className="font-sans antialiased">
- {children}
- <Analytics />
- </body>
- </html>
- );
-}
-```
-
-`apps/site/app/page.tsx`
-```tsx
-import { Exploded, Phosphor, Riffle, Slow, Terrain, Turntable } from "@lucasmarkes/hairline/react";
-import { FigureDemo } from "@/components/figure-demo";
-import { Tabs } from "@/components/tabs";
-import { ThemeEditor } from "@/components/theme-editor";
-import { CARDS, FIGURES, LINKS, NOTES, SHARED, THEME, rows, type Row } from "@/lib/figures";
-import { LIVE, highlight, plain } from "@/lib/highlight";
-import { FRAMEWORKS, install, react, vanilla } from "@/lib/snippets";
-
-const SITE = process.env.NEXT_PUBLIC_SITE_URL!;
-
-function Props({ list }: { list: Row[] }) {
- return (
- <div className="overflow-x-auto">
- <table className="props">
- <thead>
- <tr><th>Option</th><th>Type</th><th>Default</th><th>What it does</th></tr>
- </thead>
- <tbody>
- {list.map((row) => (
- <tr key={row.name}><td>{row.name}</td><td>{row.type}</td><td>{row.default}</td><td>{row.description}</td></tr>
- ))}
- </tbody>
- </table>
- </div>
- );
-}
-
-function Heading({ id, kicker, title, children }: { id: string; kicker: string; title: string; children?: React.ReactNode }) {
- return (
- <header className="mb-8 max-w-[62ch]">
- <p className="font-mono text-[11px] uppercase tracking-[0.08em] text-muted">{kicker}</p>
- <h2 id={id} className="mt-2 scroll-mt-10 text-[28px] font-medium tracking-[-0.03em]">
- <a href={`#${id}`}>{title}</a>
- </h2>
- {children ? <p className="mt-3 text-[16px] leading-[1.55] text-muted">{children}</p> : null}
- </header>
- );
-}
-
-/**
- * The whole site. A Server Component: the six figures in the hero are the
- * package's React components rendered straight from here, so every deploy
- * runs them through server rendering and hydration.
- */
-export default async function Page() {
- const demos = await Promise.all(
- FIGURES.map(async (doc) => [
- { label: "React", html: await highlight(react(doc, LIVE), "tsx", doc.range.default) },
- { label: "Vanilla", html: await highlight(vanilla(doc, LIVE), "ts", doc.range.default) },
- ]),
- );
- const frameworks = await Promise.all(FRAMEWORKS.map(async (f) => ({ label: f.label, html: await highlight(f.code, f.lang) })));
- const commands = install(SITE).map((i) => ({ label: i.label, html: plain(i.code) }));
- const hero = [
- <Riffle key="riffle" labels={CARDS} />, <Terrain key="terrain" />, <Exploded key="exploded" />,
- <Phosphor key="phosphor" />, <Slow key="slow" />, <Turntable key="turntable" />,
- ];
-
- return (
- <main className="mx-auto grid max-w-[1040px] gap-28 px-6 pb-24 pt-20 [&>*]:min-w-0">
- <section aria-labelledby="hairline">
- <div className="max-w-[52ch]">
- <h1 id="hairline" className="text-[44px] font-medium leading-none tracking-[-0.04em]">hairline</h1>
- <p className="mt-4 text-[19px] leading-[1.45] text-muted">
- Six isometric line figures that answer the pointer. SVG, no dependencies, for React and for everything else.
- </p>
- </div>
- <div className="mt-10 grid grid-cols-2 gap-4 md:grid-cols-3" data-hero>
- {FIGURES.map((doc, i) => (
- <a key={doc.id} href={`#${doc.id}`} className="tile" aria-label={`${doc.name}, figure ${i + 1}`}>
- {hero[i]}
- <span className="cap left-4 top-3">Fig. {i + 1}</span>
- <span className="cap right-4 top-3">{doc.name}</span>
- </a>
- ))}
- </div>
- <div className="mt-8 max-w-[560px]" data-install>
- <Tabs tabs={commands} label="Install" />
- </div>
- </section>
-
- {FIGURES.map((doc, i) => (
- <section key={doc.id} aria-labelledby={doc.id} data-section={doc.id}>
- <Heading id={doc.id} kicker={`Fig. ${i + 1}`} title={doc.name}>{doc.summary}</Heading>
- <FigureDemo id={doc.id} index={i + 1} name={doc.name} option={doc.option} range={doc.range} tabs={demos[i]} />
- <div className="mt-8"><Props list={rows(doc)} /></div>
- </section>
- ))}
-
- <section aria-labelledby="options">
- <Heading id="options" kicker="API" title="Options every figure takes">
- A figure fills the width of its element at a 5:4 aspect ratio. In React, every other prop goes to the <code className="font-mono text-[14px]">&lt;div&gt;</code>, and the ref is forwarded.
- </Heading>
- <Props list={SHARED} />
- </section>
-
- <section aria-labelledby="theme">
- <Heading id="theme" kicker="Theme" title="Six properties">
- Set them on a figure or on anything above it. Without them a figure is light, or dark when the page says so. The plate colour hides what is drawn behind each plate, so it has to match what the figure sits on.
- </Heading>
- <ThemeEditor />
- <ul className="mt-8 grid gap-2 text-[14px] leading-[1.5]">
- {THEME.map((t) => (
- <li key={t.property} className="grid gap-x-6 md:grid-cols-[190px_1fr]">
- <code className="font-mono text-[13px]">{t.property}</code>
- <span className="text-muted">{t.role}</span>
- </li>
- ))}
- </ul>
- </section>
-
- <section aria-labelledby="frameworks">
- <Heading id="frameworks" kicker="Use" title="Anywhere there is an element">
- The vanilla entry is a function that takes an element and returns <code className="font-mono text-[14px]">update</code> and <code className="font-mono text-[14px]">destroy</code>, which is all a framework needs.
- </Heading>
- <Tabs tabs={frameworks} label="Frameworks" />
- </section>
-
- <section aria-labelledby="notes">
- <Heading id="notes" kicker="Notes" title="What it does when you are not looking" />
- <dl className="grid gap-x-10 gap-y-6 md:grid-cols-2">
- {NOTES.map((n) => (
- <div key={n.title}>
- <dt className="text-[15px] font-medium">{n.title}</dt>
- <dd className="mt-1 text-[14px] leading-[1.55] text-muted">{n.body}</dd>
- </div>
- ))}
- </dl>
- </section>
-
- <footer className="flex flex-wrap items-baseline gap-x-6 gap-y-2 border-t border-line pt-6 font-mono text-[12px] text-muted">
- <a className="text-ink" href={LINKS.github}>GitHub</a>
- <a className="text-ink" href={LINKS.npm}>npm</a>
- <a className="text-ink" href={LINKS.essay}>The essay</a>
- <a className="text-ink" href="/llms.txt">llms.txt</a>
- <span className="md:ml-auto">
- After the figures on <a className="text-ink" href={LINKS.linear}>Linear</a>’s home page. MIT, Lucas Marques.
- </span>
- </footer>
- </main>
- );
-}
-```
-
-`apps/site/app/llms.txt/route.ts`
-```ts
-import { llms } from "@/lib/llms";
-
-export const dynamic = "force-static";
-
-export function GET() {
- return new Response(llms(process.env.NEXT_PUBLIC_SITE_URL!), { headers: { "content-type": "text/plain; charset=utf-8" } });
-}
-```
-
-Run: `pnpm build && pnpm typecheck`
-Expected:
-- The site builds.
-- The `[registry]` fallback warning prints, which is expected locally.
-- Next's route table lists `○ /` and `○ /llms.txt` as static.
-- The typecheck passes. It runs after the build, because `next build` writes `next-env.d.ts`.
-
-Run `pnpm --filter @hairline/site start`, open `http://localhost:3000`, and look at the page:
-- Thirteen figures move under the pointer: the six in the hero, the six in their sections, and the one in the theme editor.
-- A slider changes its figure and both snippets.
-- The page has no horizontal scroll at phone width.
-
-Stop the server.
-
-- [ ] **Step 6: Write the browser test**
-
-`apps/site/test/site.spec.ts`
-```ts
-import { expect, test, type Page } from "@playwright/test";
-
-const IDS = ["riffle", "terrain", "exploded", "phosphor", "slow", "turntable"];
-
-function watch(page: Page): string[] {
- const noise: string[] = [];
- page.on("console", (m) => {
- // Vercel Analytics' script exists only on Vercel
- if (m.location().url.includes("/_vercel/")) return;
- if (m.type() === "error" || m.type() === "warning") noise.push(`${m.type()}: ${m.text()}`);
- });
- page.on("pageerror", (e) => noise.push(`pageerror: ${e}`));
- return noise;
-}
-
-test("the page prerenders empty boxes and draws thirteen figures with a clean console", async ({ page, request }) => {
- const html = await (await request.get("/")).text();
- expect(html).not.toContain("<svg");
- expect(html).toContain("pnpm add @lucasmarkes/hairline");
-
- const noise = watch(page);
- await page.goto("/");
- // six in the hero, one per section, one in the theme editor
- await expect(page.locator("[data-hairline] > svg")).toHaveCount(13);
- await expect(page.locator("[data-hero] [data-hairline] > svg > *").first()).toBeVisible();
- // every figure but Exploded has a caption at rest
- for (const id of IDS.filter((id) => id !== "exploded")) await expect(page.locator(`[data-section="${id}"] [data-read]`)).not.toBeEmpty();
- expect(noise).toEqual([]);
-});
-
-test("a slider moves the figure's option and both snippets", async ({ page }) => {
- await page.goto("/");
- const section = page.locator('[data-section="riffle"]');
- await expect(section.locator(".code-panel")).toContainText("<Riffle stagger={40}");
- await section.locator("input[type=range]").fill("75");
- await expect(section.locator("output")).toHaveText("75 ms");
- await expect(section.locator(".code-panel")).toContainText("<Riffle stagger={75}");
- await section.getByRole("tab", { name: "Vanilla" }).click();
- await expect(section.locator(".code-panel")).toContainText("{ stagger: 75 }");
-});
-
-test("the install tabs switch and copy", async ({ page, context }) => {
- await context.grantPermissions(["clipboard-read", "clipboard-write"]);
- await page.goto("/");
- const install = page.locator("[data-install]");
- await install.getByRole("tab", { name: "npm", exact: true }).click();
- await expect(install.locator(".code-panel")).toHaveText("npm install @lucasmarkes/hairline");
- await install.getByRole("button", { name: "Copy" }).click();
- await expect(install.getByRole("button", { name: "Copied" })).toBeVisible();
- expect(await page.evaluate(() => navigator.clipboard.readText())).toBe("npm install @lucasmarkes/hairline");
- await install.getByRole("tab", { name: "npm", exact: true }).press("ArrowLeft");
- await expect(install.getByRole("tab", { name: "pnpm" })).toBeFocused();
- await expect(install.locator(".code-panel")).toHaveText("pnpm add @lucasmarkes/hairline");
-});
-
-test("the theme editor repaints the figure and rewrites the CSS", async ({ page }) => {
- await page.goto("/");
- const theme = page.locator("section[aria-labelledby=theme]");
- await theme.getByRole("button", { name: "Dark" }).click();
- await expect(theme.locator("[data-theme-css]")).toContainText("--hairline-plate: #08090a;");
- const fill = await theme.locator("[data-hairline] svg path").first().evaluate((el) => getComputedStyle(el).fill);
- expect(fill).toBe("rgb(8, 9, 10)");
-});
-
-test("llms.txt and the registry item are served", async ({ request }) => {
- const llms = await request.get("/llms.txt");
- expect(llms.headers()["content-type"]).toContain("text/plain");
- expect(await llms.text()).toContain("# hairline");
-
- const item = await (await request.get("/r/hairline.json")).json();
- expect(item.name).toBe("hairline");
- expect(item.dependencies).toEqual(["@lucasmarkes/hairline"]);
- expect(item.files[0].path).toBe("components/ui/hairline.tsx");
- expect(item.files[0].content).toContain('"use client"');
-});
-
-test("the page fits a phone", async ({ page }) => {
- await page.setViewportSize({ width: 390, height: 800 });
- await page.goto("/");
- expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390);
-});
-```
-
-Run: `pnpm --filter @hairline/site test:browser`
-Expected: 6 passed.
-
-- [ ] **Step 7: Run everything**
-
-Run: `pnpm test && pnpm test:browser && pnpm run release --static`
-Expected:
-- Vitest passes in both workspaces: the package's 65 tests and the site's 26.
-- Playwright passes in both: the package's 19 and the site's 6.
-- The static gate ends with `✓ All checks passed`.
-
-- [ ] **Step 8: Commit and push**
-
-```bash
-git add apps/site pnpm-lock.yaml
-git status --short apps/site # expect nothing left: .next, next-env.d.ts and public/r are ignored
-git commit -m "Site: one page of showcase and docs, generated from ranges, with /llms.txt and the registry item
-
-Co-Authored-By: Claude <[email protected]>"
-git push
-gh run watch --exit-status "$(gh run list --workflow CI --limit 1 --json databaseId --jq '.[0].databaseId')"
-```
-Expected: CI passes, and its browser step now runs the site's specs too.
-
-### Task 13: The Open Graph card
-
-**Files:**
-- Create: `apps/site/app/og/page.tsx`, `scripts/og.mjs`, `apps/site/public/og.png`
-
-**Interfaces:**
-- Consumes, from Task 12:
- - `Tile`, `FIGURES`, and the `text-muted` and `text-ink` colours from `globals.css`.
- - The `openGraph` and `twitter` metadata in `layout.tsx`, which already names `/og.png` at 1200 × 630.
-- Produces:
- - `/og`: a 1200 × 630 page with the name, the sentence, the install command and the six tiles. It sets `robots: { index: false }`.
- - `node scripts/og.mjs [base]` photographs `/og` at device scale 2 into `apps/site/public/og.png`. The PNG is committed, so the deploy does not need a browser.
-
-- [ ] **Step 1: Write the card**
-
-`apps/site/app/og/page.tsx`
-```tsx
-import type { Metadata } from "next";
-import { Tile } from "@/components/tile";
-import { FIGURES } from "@/lib/figures";
-
-/** The Open Graph card, as a page: scripts/og.mjs photographs it at 1200 × 630 into public/og.png. */
-export const metadata: Metadata = { robots: { index: false } };
-
-export default function Og() {
- return (
- <main className="flex h-[630px] w-[1200px] items-center gap-14 overflow-hidden px-16">
- <div className="w-[300px] shrink-0">
- <h1 className="text-[56px] font-medium leading-none tracking-[-0.04em]">hairline</h1>
- <p className="mt-5 text-[22px] leading-[1.35] text-muted">Six isometric line figures that answer the pointer.</p>
- <p className="mt-8 font-mono text-[15px] text-ink">npm i @lucasmarkes/hairline</p>
- </div>
- <div className="grid flex-1 grid-cols-3 gap-4">
- {FIGURES.map((doc, i) => <Tile key={doc.id} id={doc.id} index={i + 1} name={doc.name} />)}
- </div>
- </main>
- );
-}
-```
-
-- [ ] **Step 2: Write the photographer**
-
-It waits until all six figures have drawn and the fonts have loaded, then waits a moment more, so that Phosphor and Slow are mid-loop.
-
-`scripts/og.mjs`
-```js
-#!/usr/bin/env node
-/**
- * Photographs the site's /og route into apps/site/public/og.png, the Open
- * Graph card. The result is committed; run this again when the figures or the
- * card change.
- *
- * pnpm build && pnpm --filter @hairline/site start (in one terminal)
- * node scripts/og.mjs [http://localhost:3000] (in another)
- */
-import { createRequire } from "node:module";
-import { join, resolve } from "node:path";
-
-const ROOT = resolve(import.meta.dirname, "..");
-const SITE = join(ROOT, "apps/site");
-const { chromium } = createRequire(join(SITE, "package.json"))("@playwright/test");
-const base = (process.argv[2] ?? "http://localhost:3000").replace(/\/+$/, "");
-
-const browser = await chromium.launch({ channel: "chrome" });
-const page = await browser.newPage({ viewport: { width: 1200, height: 630 }, deviceScaleFactor: 2 });
-try {
- await page.goto(`${base}/og`, { waitUntil: "networkidle" });
-} catch {
- console.error(`Nothing at ${base}/og. Build and start the site first:\n pnpm build && pnpm --filter @hairline/site start`);
- await browser.close();
- process.exit(1);
-}
-await page.waitForFunction(() => document.querySelectorAll("[data-hairline] > svg > *").length >= 6 && document.fonts.status === "loaded");
-// Phosphor and Slow play on their own: give them a moment to be mid-loop.
-await page.waitForTimeout(1200);
-const out = join(SITE, "public/og.png");
-await page.screenshot({ path: out, clip: { x: 0, y: 0, width: 1200, height: 630 } });
-await browser.close();
-console.log(`wrote ${out}`);
-```
-
-- [ ] **Step 3: Take the photograph**
-
-Run: `node scripts/og.mjs`
-Expected: FAIL, exit 1. Nothing is listening yet, so the script prints `Nothing at http://localhost:3000/og. Build and start the site first:` and the two commands.
-
-Then:
-```bash
-pnpm build
-pnpm --filter @hairline/site start &
-SITE=$!
-until curl -sf -o /dev/null http://localhost:3000/og; do sleep 0.5; done
-node scripts/og.mjs
-kill $SITE
-file apps/site/public/og.png
-```
-Expected:
-- `wrote …/apps/site/public/og.png`.
-- `file` reports `PNG image data, 2400 x 1260`.
-
-Open the PNG. Check that:
-- All six tiles are drawn.
-- No figure is cut off.
-- The text is set in Geist, not a fallback font.
-
-If any of that fails, fix `app/og/page.tsx` and take the photograph again.
-
-- [ ] **Step 4: Check that the card is served**
-
-Run:
-```bash
-pnpm build
-pnpm --filter @hairline/site start &
-SITE=$!
-until curl -sf -o /dev/null http://localhost:3000/og; do sleep 0.5; done
-curl -sI http://localhost:3000/og.png | head -1
-curl -s http://localhost:3000/ | grep -o '<meta property="og:image" content="[^"]*"'
-kill $SITE
-```
-Expected:
-- `HTTP/1.1 200 OK`.
-- `<meta property="og:image" content="http://localhost:3000/og.png"`. On Vercel the host is the deployment's own (Task 14).
-
-- [ ] **Step 5: Commit**
-
-```bash
-git add apps/site/app/og/page.tsx scripts/og.mjs apps/site/public/og.png
-git commit -m "Site: the Open Graph card, a route photographed into a committed PNG
-
-Co-Authored-By: Claude <[email protected]>"
-git push
-```
-
-### Task 14: The Vercel project and a preview Lucas reviews
-
-**Files:**
-- Create: `apps/site/vercel.json`
-
-**Interfaces:**
-- Consumes:
- - From Task 12: the site, and its turbo task's `env` list (`VERCEL_ENV`, `VERCEL_URL`, `VERCEL_PROJECT_PRODUCTION_URL`).
- - From Task 10: `scripts/base-url.mjs`, which turns those variables into the site's address.
- - From Task 2: the private GitHub repository `lucasmarkes/hairline`.
-- Produces:
- - The Vercel project `hairline` in the team `lucasmarkes-team-projects`, the same team as motes. Its root directory is `apps/site`, and it is connected to the GitHub repository:
- - A preview for every pull request.
- - Production from `main`, at the project's `*.vercel.app` address. The custom domain waits for Task 16.
- - The PR `Site on Vercel`, merged once Lucas has reviewed its preview.
-
-This task meets phase 4's exit criterion: Lucas has reviewed a Vercel preview. Creating the project and connecting it to GitHub is outward-facing: **confirm** with Lucas before Step 3, and do nothing in the Vercel dashboard or CLI before then.
-
-Vercel installs and builds from the repository root, because the site needs the package built first. The root directory still has to be `apps/site`, so Vercel finds the Next.js app and its output.
-
-- [ ] **Step 1: Write the Vercel configuration on a branch**
-
-```bash
-git switch -c site-on-vercel
-```
-
-`apps/site/vercel.json`
-```json
-{
- "$schema": "https://openapi.vercel.sh/vercel.json",
- "framework": "nextjs",
- "installCommand": "pnpm install --frozen-lockfile",
- "buildCommand": "cd ../.. && pnpm turbo run build --filter=@hairline/site"
-}
-```
-
-```bash
-git add apps/site/vercel.json
-git commit -m "Site: build on Vercel from the repository root, through turbo
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-Do not push yet. The push in Step 4 opens the PR whose preview is the first build.
-
-- [ ] **Step 2: Check the Vercel account**
-
-Run:
-```bash
-vercel whoami
-vercel teams list
-vercel project list --scope lucasmarkes-team-projects | grep -E '^\s*(motes|hairline)\b'
-```
-Expected:
-- `lucasmarkess`.
-- The team list includes `lucasmarkes-team-projects`.
-- `motes` is listed and `hairline` is not.
-
-If `hairline` already exists, stop and ask Lucas.
-
-- [ ] **Step 3: Create the project and connect it (confirm)**
-
-Ask Lucas: "Create the Vercel project `hairline` in `lucasmarkes-team-projects`, with root directory `apps/site`, connected to `lucasmarkes/hairline`, with Web Analytics on?" Run this only after a yes:
-
-```bash
-vercel project add hairline --scope lucasmarkes-team-projects
-vercel project update hairline --root-directory apps/site --framework nextjs --yes --scope lucasmarkes-team-projects
-vercel link --yes --project hairline --team lucasmarkes-team-projects
-vercel git connect --yes
-vercel project web-analytics enable hairline --scope lucasmarkes-team-projects
-vercel project inspect hairline --scope lucasmarkes-team-projects
-```
-Expected:
-- `vercel link` writes `.vercel/project.json` at the repository root. It is git-ignored, and `git status --short` shows nothing new.
-- `vercel git connect` reports `lucasmarkes/hairline` connected.
-- `project inspect` shows `Root Directory: apps/site` and `Framework Preset: Next.js`.
-
-If `git connect` says Vercel cannot access the repository, the Vercel GitHub app is limited to selected repositories. Lucas adds `hairline` to it on GitHub (Settings → Applications → Vercel → Repository access); then run `vercel git connect --yes` again.
-
-- [ ] **Step 4: Open the PR and wait for its preview**
-
-```bash
-git push -u origin site-on-vercel
-gh pr create --title "Site on Vercel" --body "Builds apps/site on Vercel from the repository root, through turbo. The preview is the first deploy of the site."
-gh pr checks --watch
-vercel ls hairline --scope lucasmarkes-team-projects | head -5
-```
-Expected:
-- The PR's checks include the CI job and a Vercel deployment check, and all of them pass.
-- `vercel ls` lists one `Preview` deployment, `● Ready`.
-
-Put its URL in `PREVIEW`, for example `PREVIEW=https://hairline-abc123-lucasmarkes-team-projects.vercel.app`.
-
-If the Vercel build fails, read it with `vercel inspect "$PREVIEW" --logs`. Fix the cause in the repository and push to the branch; never fix it in the dashboard. The build's own `[registry]` line must read `(base from VERCEL_URL)`, not the fallback warning.
-
-- [ ] **Step 5: Check the preview**
-
-Previews sit behind Vercel's deployment protection, so check them with `vercel curl`, which passes it:
-
-```bash
-vercel curl /r/hairline.json --deployment "$PREVIEW" | grep '"docs"'
-vercel curl /llms.txt --deployment "$PREVIEW" | head -3
-vercel curl / --deployment "$PREVIEW" | grep -o '<meta property="og:image" content="[^"]*"'
-```
-Expected:
-- `"docs": "Docs: $PREVIEW"`: the item names the preview itself, not localhost.
-- `# hairline`, then the sentence.
-- `og:image` points at `$PREVIEW/og.png`.
-
-- [ ] **Step 6: Lucas reviews the preview**
-
-Send Lucas the preview URL. Ask them to check, logged in to Vercel, on a laptop and a phone:
-- All thirteen figures answer the pointer.
-- The sliders work.
-- Copy works on every install tab.
-- The theme editor works.
-- The page reads well at phone width.
-
-Wait for their answer. Fix anything they ask for on this branch, push, and send the new preview. This review is the gate for phase 4.
-
-- [ ] **Step 7: Merge, and check the first production build**
-
-After Lucas approves:
-```bash
-gh pr merge --merge --delete-branch
-git switch main && git pull
-vercel ls hairline --environment production --scope lucasmarkes-team-projects | head -5
-```
-Expected: one `Production` deployment, `● Ready`. Put its URL in `PROD`.
-
-The team's `.vercel.app` addresses sit behind deployment protection, production included; only a custom domain is open. So check with `vercel curl` here too:
-```bash
-vercel curl /r/hairline.json --deployment "$PROD" | grep '"docs"'
-```
-Expected: `"docs": "Docs: https://hairline-….vercel.app"`. This is the project's production domain, not `$PROD` itself and not localhost, because `VERCEL_ENV` is `production`.
-
-Task 16 adds the custom domain and builds production again, so that this line names `https://hairline.lucasmarkes.com`.
-
-### Task 15: The changelog, the publish workflow and the release candidate's version
-
-**Files:**
-- Create: `CHANGELOG.md`, `scripts/changelog.mjs`, `.github/workflows/publish.yml`
-- Modify: `packages/hairline/package.json` (`version`: `0.0.0` → `0.1.0-rc.0`)
-
-**Interfaces:**
-- Consumes:
- - From Tasks 9 and 11: `pnpm run release`, the full gate.
- - From Task 1: the package's `prepack`.
-- Produces:
- - `node scripts/changelog.mjs <version>` prints that version's section of `CHANGELOG.md` without its heading. A pre-release with no section of its own (`0.1.0-rc.0`) gets the section of the version it leads to (`0.1.0`). A version with no section exits 1. It also exports `section(changelog, version): string | null`.
- - `.github/workflows/publish.yml` runs on a pushed `v*` tag, in the protected `release` environment. It runs these steps in order, and any failure stops it before the registry:
- 1. It checks that the tag matches the manifest.
- 2. It picks the dist-tag: `next` for a version with a `-`, `latest` otherwise.
- 3. It writes the notes with `changelog.mjs`.
- 4. It runs the full gate.
- 5. It packs with pnpm and publishes that tarball with npm, using `--provenance --access public`.
- 6. It creates the GitHub Release, marked as a pre-release under `next`.
-
-This is the spec's "Release", the motes flow. The workflow cannot run yet. The `release` environment and its `NPM_TOKEN` are created in Task 16, after the repository is public. On a private repository, GitHub's Free and Pro plans do not enforce a required reviewer, and npm provenance needs a public repository anyway.
-
-- [ ] **Step 1: Write the changelog**
-
-`CHANGELOG.md`
-```markdown
-# Changelog
-
-Every release of `@lucasmarkes/hairline`. The format follows
-[Keep a Changelog](https://keepachangelog.com/en/1.1.0/); versions follow
-[semver](https://semver.org/).
-
-## 0.1.0 - 2026-10-01
-
-First release.
-
-### Added
-
-- Six isometric line figures, each a function that draws into an element:
- `riffle`, `terrain`, `exploded`, `phosphor`, `slow`, `turntable`.
-- A React entry, `@lucasmarkes/hairline/react`, with one component per figure.
- It is a client module, so it can be rendered from a Server Component.
-- One option per figure, exported with its bounds as `ranges`.
-- Theming with six CSS custom properties (`--hairline-plate`, `--hairline-hi`,
- `--hairline-edge`, `--hairline-mid`, `--hairline-lo`, `--hairline-stroke`),
- a `theme` option, and automatic light and dark.
-- A shadcn registry item at `https://hairline.lucasmarkes.com/r/hairline.json`.
-```
-
-- [ ] **Step 2: Write the notes script, and check its three cases**
-
-`scripts/changelog.mjs`
-```js
-#!/usr/bin/env node
-/**
- * Prints one version's section of CHANGELOG.md, without its heading: the body
- * of the GitHub Release.
- *
- * node scripts/changelog.mjs 0.1.0
- *
- * A pre-release (0.1.0-rc.0) with no section of its own gets the section of
- * the version it leads to (0.1.0). No section at all is an error.
- */
-import { readFileSync } from "node:fs";
-import { join } from "node:path";
-
-export function section(changelog, version) {
- const lines = changelog.split("\n");
- const heading = (v) => lines.findIndex((l) => l.startsWith("## ") && l.slice(3).trim().replace(/^\[|\].*$| .*$/g, "") === v);
- let start = heading(version);
- if (start < 0 && version.includes("-")) start = heading(version.split("-")[0]);
- if (start < 0) return null;
- let end = lines.findIndex((l, i) => i > start && l.startsWith("## "));
- if (end < 0) end = lines.length;
- return lines.slice(start + 1, end).join("\n").trim();
-}
-
-if (import.meta.filename === process.argv[1]) {
- const version = process.argv[2];
- if (!version) { console.error("Usage: node scripts/changelog.mjs <version>"); process.exit(2); }
- const notes = section(readFileSync(join(import.meta.dirname, "..", "CHANGELOG.md"), "utf8"), version);
- if (!notes) { console.error(`CHANGELOG.md has no "## ${version}" section.`); process.exit(1); }
- console.log(notes);
-}
-```
-
-Run:
-```bash
-node scripts/changelog.mjs 0.1.0 | head -1
-node scripts/changelog.mjs 0.1.0-rc.0 | head -1
-node scripts/changelog.mjs 0.2.0; echo "exit $?"
-```
-Expected, in order:
-1. `First release.`
-2. `First release.`: the release candidate falls back to 0.1.0's section.
-3. `CHANGELOG.md has no "## 0.2.0" section.`, then `exit 1`.
-
-- [ ] **Step 3: Write the publish workflow**
-
-`.github/workflows/publish.yml`
-```yaml
-name: Publish
-
-on:
- push:
- tags:
- - 'v*'
-
-permissions:
- # Writes the GitHub Release.
- contents: write
- # npm provenance: the OIDC token npm exchanges for a signed attestation of
- # where and how the tarball was built.
- id-token: write
-
-jobs:
- publish:
- runs-on: ubuntu-latest
- # The protected `release` environment: a required reviewer approves before
- # any step runs, and NPM_TOKEN exists only here, so a pushed tag alone
- # cannot reach the registry.
- environment: release
- steps:
- - uses: actions/checkout@v7
-
- - name: Enable Corepack
- run: corepack enable
-
- # registry-url writes an .npmrc wired to NODE_AUTH_TOKEN, so the gate's
- # `npm whoami` and the publish below both authenticate with NPM_TOKEN.
- - uses: actions/setup-node@v7
- with:
- node-version: 22
- registry-url: https://registry.npmjs.org
- cache: pnpm
-
- - name: Install
- run: pnpm install --frozen-lockfile
-
- - name: Verify the tag matches the manifest
- run: |
- TAG="${GITHUB_REF_NAME#v}"
- PKG="$(node -p "require('./packages/hairline/package.json').version")"
- echo "tag=$TAG package=$PKG"
- if [ "$TAG" != "$PKG" ]; then
- echo "::error::Tag v$TAG does not match packages/hairline/package.json ($PKG). Refusing to publish."
- exit 1
- fi
- echo "VERSION=$TAG" >> "$GITHUB_ENV"
- # A version with a pre-release suffix (0.1.0-rc.0) goes to the `next`
- # dist-tag, so `npm install @lucasmarkes/hairline` never picks it up.
- case "$TAG" in
- *-*) echo "DIST_TAG=next" >> "$GITHUB_ENV" ;;
- *) echo "DIST_TAG=latest" >> "$GITHUB_ENV" ;;
- esac
-
- # Fails here, before anything is published, if the changelog has no
- # section for this version.
- - name: Release notes from the changelog
- run: node scripts/changelog.mjs "$VERSION" > "$RUNNER_TEMP/notes.md"
-
- # Everything: build, typecheck, every test layer, publint, attw, size
- # budgets, the tarball, both consumer fixtures, npm auth and the registry.
- # It packs but never publishes.
- - name: Release gate (full)
- run: pnpm run release
- env:
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
-
- # pnpm packs (it runs prepack, which copies the README and LICENSE in);
- # npm publishes that exact tarball, because npm signs provenance.
- - name: Publish with provenance
- run: |
- STAGING="$(mktemp -d)"
- pnpm -C packages/hairline pack --pack-destination "$STAGING"
- npm publish "$STAGING/lucasmarkes-hairline-${VERSION}.tgz" --provenance --access public --tag "$DIST_TAG"
- env:
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
-
- - name: GitHub Release
- run: |
- if [ "$DIST_TAG" = "next" ]; then PRE="--prerelease"; else PRE=""; fi
- gh release create "$GITHUB_REF_NAME" --title "$GITHUB_REF_NAME" --notes-file "$RUNNER_TEMP/notes.md" $PRE
- env:
- GH_TOKEN: ${{ github.token }}
-```
-
-- [ ] **Step 4: Set the release candidate's version**
-
-Run:
-```bash
-(cd packages/hairline && npm pkg set version=0.1.0-rc.0)
-grep '"version"' packages/hairline/package.json
-pnpm run release --static
-```
-Expected:
-- `"version": "0.1.0-rc.0",`.
-- The gate ends with `✓ All checks passed for @lucasmarkes/[email protected]. Nothing has been published.`
-
-- [ ] **Step 5: Commit and push**
-
-```bash
-git add CHANGELOG.md scripts/changelog.mjs .github/workflows/publish.yml packages/hairline/package.json
-git commit -m "Release: the changelog, the publish workflow behind the release environment, and 0.1.0-rc.0
-
-Co-Authored-By: Claude <[email protected]>"
-git push
-gh run watch --exit-status "$(gh run list --workflow CI --limit 1 --json databaseId --jq '.[0].databaseId')"
-```
-Expected: CI passes. Publish does not run, because nothing is tagged.
-
-### Task 16: Launch
-
-**Files:**
-- Modify: `packages/hairline/package.json` (`version`: `0.1.0-rc.0` → `0.1.0`)
-- Modify, only if the release date is not 2026-10-01: `CHANGELOG.md` (the date in `## 0.1.0 - …`)
-
-**Interfaces:**
-- Consumes:
- - From Task 15: `publish.yml` and `changelog.mjs`.
- - From Task 14: the Vercel project `hairline`.
- - From Task 12: the site, whose address comes from `VERCEL_PROJECT_PRODUCTION_URL` at build time.
-- Produces:
- - `@lucasmarkes/[email protected]` under `next`, and `@lucasmarkes/[email protected]` under `latest`, both with provenance.
- - Two GitHub Releases.
- - `https://hairline.lucasmarkes.com`.
-
-This is the spec's launch checklist, one step per item, in its order. Each step marked **confirm** is public or hard to undo. Ask Lucas before it, every time; a yes to one step is not a yes to the next. A published npm version can never be reused, even after an unpublish.
-
-- [ ] **Step 1: Make the repository public (confirm)**
-
-First, check that nothing private is in the history:
-```bash
-git log --all --name-only --format= | sort -u | grep -E '(^|/)(\.env|\.vercel/)' || echo "nothing private"
-git grep -nIE 'npm_[A-Za-z0-9]{36}|gh[pousr]_[A-Za-z0-9]{36}' $(git rev-list --all) || echo "no tokens"
-```
-Expected: `nothing private`, then `no tokens`.
-
-Ask Lucas: "Make `lucasmarkes/hairline` public now, with its description, topics and homepage?" After a yes:
-```bash
-gh repo edit lucasmarkes/hairline --visibility public --accept-visibility-change-consequences \
- --description "Six isometric line figures that answer the pointer. SVG, no dependencies, for React and for everything else." \
- --homepage https://hairline.lucasmarkes.com \
- --add-topic svg --add-topic isometric --add-topic animation --add-topic react --add-topic typescript --add-topic shadcn
-gh repo view lucasmarkes/hairline --json visibility,homepageUrl --jq '.visibility + " " + .homepageUrl'
-curl -sI https://raw.githubusercontent.com/lucasmarkes/hairline/main/assets/hero.gif | head -1
-```
-Expected:
-- `PUBLIC https://hairline.lucasmarkes.com`.
-- `HTTP/2 200`: the README's gif now loads, on GitHub and later on npm.
-
-- [ ] **Step 2: Create the `release` environment and its token**
-
-Create the environment, with Lucas as its required reviewer and only `v*` tags allowed to deploy to it:
-```bash
-USER_ID="$(gh api user --jq .id)"
-gh api -X PUT repos/lucasmarkes/hairline/environments/release --input - <<EOF
-{ "reviewers": [{ "type": "User", "id": $USER_ID }],
- "deployment_branch_policy": { "protected_branches": false, "custom_branch_policies": true } }
-EOF
-gh api -X POST repos/lucasmarkes/hairline/environments/release/deployment-branch-policies -f name='v*' -f type=tag
-gh api repos/lucasmarkes/hairline/environments/release --jq '[.protection_rules[].type] | join(",")'
-```
-Expected: `required_reviewers,branch_policy`.
-
-Lucas creates the npm token. Ask Lucas to make it on npmjs.com (Access Tokens → Generate New Token → Granular Access Token) with these settings:
-- Permissions: Read and write.
-- Packages: all packages. `@lucasmarkes/hairline` does not exist yet, so it cannot be picked by name.
-- Expiration: 30 days.
-- Bypass two-factor authentication: on, so the workflow can publish.
-
-Then Lucas stores it themselves, so the token never passes through this session:
-```
-! gh secret set NPM_TOKEN --env release --repo lucasmarkes/hairline
-```
-Check:
-```bash
-gh secret list --env release --repo lucasmarkes/hairline
-```
-Expected: one line, `NPM_TOKEN`.
-
-- [ ] **Step 3: Publish the release candidate (confirm)**
-
-Ask Lucas: "Tag `v0.1.0-rc.0`? It publishes `@lucasmarkes/[email protected]` under `next` once you approve the run." After a yes:
-```bash
-git switch main && git pull
-grep '"version"' packages/hairline/package.json
-git tag v0.1.0-rc.0
-git push origin v0.1.0-rc.0
-gh run list --workflow Publish --limit 1
-```
-Expected: `"version": "0.1.0-rc.0",`, and a Publish run that is `waiting`.
-
-Lucas approves it, in the run's page on GitHub or with `gh run view <id> --web`. Then:
-```bash
-gh run watch --exit-status "$(gh run list --workflow Publish --limit 1 --json databaseId --jq '.[0].databaseId')"
-npm view @lucasmarkes/hairline dist-tags
-gh release view v0.1.0-rc.0 --json isPrerelease --jq .isPrerelease
-```
-Expected:
-- The run passes. The "Release gate (full)" step logs `✓ logged in as the scope's owner`.
-- `{ next: '0.1.0-rc.0' }`.
-- `true`.
-
-If the run fails before "Publish with provenance", nothing was published. Fix the cause and commit it. Then move the tag (`git tag -f v0.1.0-rc.0 && git push -f origin v0.1.0-rc.0`) and approve the new run. If it fails after that step, the version is spent: bump to `0.1.0-rc.1`, and ask Lucas before tagging again.
-
-- [ ] **Step 4: Check the release candidate from outside the repository**
-
-Each check uses only what a stranger has: the npm registry and a CDN. The site's production address stays behind Vercel's protection until Step 6 gives it a domain. Until then, the shadcn item is served from a local build of the site, made for that address.
-
-```bash
-RC=/tmp/hairline-rc && rm -rf "$RC" && mkdir -p "$RC" && cd "$RC"
-
-# A new Next.js app, with a Server Component page
-npx create-next-app@latest next --ts --app --tailwind --no-src-dir --import-alias "@/*" --use-npm --yes
-cd next && npm install @lucasmarkes/hairline@next
-cat > app/page.tsx <<'EOF'
-import { Riffle } from "@lucasmarkes/hairline/react";
-
-export default function Page() {
- return <main style={{ width: 400, margin: "40px auto" }}><Riffle /></main>;
-}
-EOF
-npm run build
-npx next start -p 4400 &
-APP=$!
-until curl -sf -o /dev/null http://localhost:4400; do sleep 0.5; done; open http://localhost:4400
-```
-Expected: the build passes, and the page shows Riffle, answering the pointer, with a clean console. Then `kill $APP`.
-
-```bash
-# The shadcn item, served by a local build of the site
-cd ~/estudos/hairline
-HAIRLINE_REGISTRY_URL=http://localhost:3000 pnpm build
-pnpm --filter @hairline/site start &
-SITE=$!
-until curl -sf -o /dev/null http://localhost:3000/r/hairline.json; do sleep 0.5; done
-cd /tmp/hairline-rc/next
-npx shadcn@latest init --defaults --yes
-npx shadcn@latest add http://localhost:3000/r/hairline.json --yes
-kill $SITE
-head -1 components/ui/hairline.tsx && npm run build
-```
-Expected: `components/ui/hairline.tsx` starts with `"use client";`, and the app still builds. Until 0.1.0 exists, npm has no `latest` version to install. If shadcn stops at its dependency install with `No matching version found`, check that the file was still written; Step 7 repeats this check against production and the final release.
-
-```bash
-cd "$RC"
-# A new Vite app, no framework
-npm create vite@latest vite -- --template vanilla-ts
-cd vite && npm install && npm install @lucasmarkes/hairline@next
-cat > src/main.ts <<'EOF'
-import { terrain } from "@lucasmarkes/hairline";
-
-document.body.innerHTML = '<div id="figure" style="width: 400px"></div>';
-terrain(document.getElementById("figure")!, { radius: 4 });
-EOF
-npm run build
-npx vite preview --port 4401 &
-APP=$!
-until curl -sf -o /dev/null http://localhost:4401; do sleep 0.5; done; open http://localhost:4401
-```
-Expected: the build passes, and Terrain answers the pointer. Then `kill $APP`.
-
-```bash
-cd "$RC"
-# Plain HTML, from a CDN: the site's own CDN snippet, pinned to the release candidate
-cat > cdn.html <<'EOF'
-<div id="figure" style="width: 400px"></div>
-
-<script type="module">
- import { terrain } from "https://esm.sh/@lucasmarkes/[email protected]";
-
- terrain(document.getElementById("figure"), { radius: 4 });
-</script>
-EOF
-npx -y serve -l 4402 . &
-APP=$!
-until curl -sf -o /dev/null http://localhost:4402/cdn.html; do sleep 0.5; done; open http://localhost:4402/cdn.html
-```
-Expected: Terrain draws and answers the pointer. Then `kill $APP`.
-
-If any check fails, it is a defect in what ships. Fix it in the repository, add a fixture check that would have caught it, and publish `0.1.0-rc.1` through Step 3 again.
-
-- [ ] **Step 5: Publish 0.1.0 (confirm)**
-
-```bash
-cd ~/estudos/hairline
-(cd packages/hairline && npm pkg set version=0.1.0)
-date +%F # if this is not 2026-10-01, change the date in CHANGELOG.md's "## 0.1.0 - …" heading to it
-pnpm run release
-```
-Expected: the full gate ends with `✓ All checks passed for @lucasmarkes/[email protected]. Nothing has been published.`
-
-```bash
-git add packages/hairline/package.json CHANGELOG.md
-git commit -m "Release 0.1.0
-
-Co-Authored-By: Claude <[email protected]>"
-git push
-gh run watch --exit-status "$(gh run list --workflow CI --limit 1 --json databaseId --jq '.[0].databaseId')"
-```
-
-Ask Lucas: "Tag `v0.1.0`? It publishes `@lucasmarkes/[email protected]` under `latest` once you approve the run." After a yes:
-```bash
-git tag v0.1.0
-git push origin v0.1.0
-```
-Lucas approves the run. Then:
-```bash
-gh run watch --exit-status "$(gh run list --workflow Publish --limit 1 --json databaseId --jq '.[0].databaseId')"
-npm view @lucasmarkes/hairline dist-tags
-```
-Expected: `{ next: '0.1.0-rc.0', latest: '0.1.0' }`.
-
-- [ ] **Step 6: Add the domain (confirm)**
-
-Ask Lucas: "Add `hairline.lucasmarkes.com` to the Vercel project `hairline`?" After a yes:
-```bash
-vercel domains add hairline.lucasmarkes.com hairline --scope lucasmarkes-team-projects
-vercel project inspect hairline --scope lucasmarkes-team-projects | grep -A4 -i domains
-```
-Expected: the domain is added and listed. `lucasmarkes.com` uses Vercel's nameservers, so there is no DNS record to create, and the certificate is issued within a minute or two.
-
-The site's address is fixed at build time from `VERCEL_PROJECT_PRODUCTION_URL`. Vercel sets that to the shortest custom production domain, so production has to be built again for the registry item and the Open Graph tags to name the domain:
-```bash
-LAST="$(vercel ls hairline --environment production --scope lucasmarkes-team-projects --format json | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>console.log("https://"+JSON.parse(s).deployments[0].url))')"
-vercel redeploy "$LAST" --target production --scope lucasmarkes-team-projects
-```
-Expected: a new production deployment, `● Ready`. In its build log (`vercel inspect <its URL> --logs`), the `[registry]` line reads `https://hairline.lucasmarkes.com/r/hairline.json (base from VERCEL_PROJECT_PRODUCTION_URL)`.
-
-- [ ] **Step 7: Check production**
-
-```bash
-SITE=https://hairline.lucasmarkes.com
-curl -sI "$SITE" | head -1
-curl -s "$SITE/r/hairline.json" | grep '"docs"'
-curl -s "$SITE/llms.txt" | head -1
-curl -s "$SITE" | grep -o '<meta property="og:image" content="[^"]*"'
-curl -sI "$SITE/og.png" | head -1
-npm view @lucasmarkes/[email protected] dist.attestations.provenance.predicateType
-```
-Expected, in order:
-1. `HTTP/2 200`.
-2. `"docs": "Docs: https://hairline.lucasmarkes.com"`.
-3. `# hairline`.
-4. `content="https://hairline.lucasmarkes.com/og.png"`.
-5. `HTTP/2 200`.
-6. `https://slsa.dev/provenance/v1`.
-
-Then, in the release candidate's Next.js app from Step 4:
-```bash
-cd /tmp/hairline-rc/next
-npm install @lucasmarkes/hairline@latest
-npx shadcn@latest add https://hairline.lucasmarkes.com/r/hairline.json --yes --overwrite
-npm run build
-```
-Expected: shadcn installs the dependency and writes the file, and the app builds.
-
-Last, by eye:
-- `https://www.npmjs.com/package/@lucasmarkes/hairline` shows the provenance badge, and the README renders with the gif.
-- The site answers on the domain, on a laptop and a phone.
-- The Open Graph card renders. Lucas pastes the link into a draft post, or checks it on opengraph.xyz.
-
-Then clean up:
-```bash
-rm -rf /tmp/hairline-rc
-```
-
-The launch checklist is complete. Tell Lucas, in order:
-- The npm page, with its version and provenance.
-- The site.
-- The two GitHub Releases.
-- The token's expiry date, since it was made for 30 days. The spec's "After 0.1.0" replaces it with npm trusted publishing.
diff --git a/docs/superpowers/plans/2026-10-01-hairline-skill-page.md b/docs/superpowers/plans/2026-10-01-hairline-skill-page.md
deleted file mode 100644
index 6b99fed..0000000
--- a/docs/superpowers/plans/2026-10-01-hairline-skill-page.md
+++ /dev/null
@@ -1,780 +0,0 @@
-# `/skill` Page Implementation Plan
-
-> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
-
-**Goal:** A `/skill` page on the Hairline site that shows four figures the `hairline-create` skill drew, each live beside the prompt that produced it, and says how to install the skill, how it works and how to use it.
-
-**Architecture:** The four generated pages are copied byte for byte into `apps/site/public/skill/` and shown in same-origin `iframe`s. One module, `lib/skill.ts`, holds the list and the page's copy; it reads each figure's `name` and `means` out of the generated page, so nothing about an example is written twice. The page is a Server Component; two small client components do the copying and fit each frame's height to the page inside it.
-
-**Tech Stack:** Next 16 (App Router), React 19, Tailwind 4 with the site's own classes in `globals.css`, vitest 5, Playwright 1.63 driving Chrome, pnpm 10.20 + turbo, Node 22.
-
-**Spec:** `docs/superpowers/specs/2026-10-01-hairline-skill-page-design.md`
-
-## Global Constraints
-
-- All copy, code and comments are in English, in the site's voice: short, plain, no exclamation marks.
-- The site is light only (`html { color-scheme: light }`). Every frame is loaded with `?theme=light`.
-- The generated pages in `apps/site/public/skill/` are never edited. They are copied from the skill's output and that is all.
-- Nothing in `packages/hairline/src` changes. Nothing in `skills/hairline-create/` changes.
-- No new dependency.
-- The install command is exactly `npx skills add lucasmarkes/hairline`. The skill's command is exactly `/hairline-create`.
-- The four ideas, in page order: `a sales funnel`, `a rate limiter`, `git branches`, `weather over a city`.
-- Shell: prefix commands with `rtk`. The working directory resets after every command, so each command starts with `cd ~/estudos/hairline` (or a folder under it).
-- Commits: stage files by name, never `git add .` or `-A`. Never commit `apps/site/.vitest/`, `apps/site/AGENTS.md`, `apps/site/CLAUDE.md`, `.vercel/`, `.superpowers/`, `.claude/` or `.env.local`. Every commit message ends with `Co-Authored-By: Claude <[email protected]>`.
-- Before any browser run, free the site's test port, or Playwright reuses a server holding an old build: `lsof -ti:4320 | xargs kill 2>/dev/null; true`.
-- The pull request is opened but not merged. Merging needs Lucas's yes.
-
-## Preconditions
-
-These are true before Task 1 starts. Check each; if one is false, stop and say which.
-
-1. Pull request #4 is merged and local `main` has it:
- `cd ~/estudos/hairline && rtk git checkout main && rtk git pull && ls skills/hairline-create/validate.mjs`
-2. The bench takes a `theme` parameter:
- `cd ~/estudos/hairline && rtk proxy grep -n -e 'params.get("theme")' skills/hairline-create/bench.html`
- Expected: one line.
-3. The four regenerated pages exist, one per idea, each under its own folder:
- `cd ~/estudos/hairline && ls .superpowers/trial/rerun/*/hairline-*.html`
- Expected: four files, in the folders `1-sales-funnel`, `2-rate-limiter`, `3-git-branches`, `4-weather-city`.
-4. A branch for this work, with the spec and this plan as its first commit:
-
-```bash
-cd ~/estudos/hairline && rtk git checkout -b skill-page && rtk git add docs/superpowers/specs/2026-10-01-hairline-skill-page-design.md docs/superpowers/plans/2026-10-01-hairline-skill-page.md && rtk git commit -m "Skill page: the design and the plan
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-## Review Focus
-
-Conditions the spec implies and that are most likely to bite a visitor. Each has a test in the task named.
-
-1. **A dark system.** The site is white; a frame that follows the system would be a black plate on it. Expected: every frame's page is light. Test in Task 2.
-2. **A phone.** At 320px the frame's own text wraps to more lines. Expected: no sideways scroll on the page and no scroll inside a frame. Test in Task 2.
-3. **No JavaScript.** The frames cannot be fitted and the copy buttons do nothing. Expected: the install command, the four prompts and the four links to the generated pages are still on the page as text and links. Test in Task 2.
-4. **An example that goes missing or is edited.** A file renamed, deleted or retouched by hand. Expected: the build and the tests fail with a message naming the file, instead of a blank frame in production. Tests in Task 1.
-5. **A link opened on its own.** Someone opens `/skill/hairline-<name>.html` directly from the link or from `llms.txt`. Expected: the page is served as HTML and draws. Test in Task 2.
-
-## File Structure
-
-| File | Responsibility |
-| --- | --- |
-| `apps/site/public/skill/hairline-<name>.html` (four, new) | The skill's output, unaltered. |
-| `apps/site/lib/skill.ts` (new) | `INSTALL`, `COMMAND`, `EXAMPLES`, the page's copy as text, and `examples()`, which adds each figure's declared `name` and `means`. |
-| `apps/site/components/command.tsx` (new) | One line of text in a pill with a copy button. |
-| `apps/site/components/example-frame.tsx` (new) | The `iframe`, fitted to the height of the page inside it. |
-| `apps/site/app/skill/page.tsx` (new) | The page. |
-| `apps/site/app/globals.css` (modify) | The page's layout classes. |
-| `apps/site/components/chrome.tsx` (modify) | The `Skill` link in the top bar. |
-| `apps/site/lib/llms.ts` (modify) | A `## Skill` section. |
-| `apps/site/test/skill.test.ts` (new) | Vitest: the showcase is honest. |
-| `apps/site/test/skill.spec.ts` (new) | Playwright: the page in a browser. |
-| `apps/site/test/site.spec.ts` (modify) | The top bar now holds five items. |
-| `apps/site/test/docs.test.ts` (modify) | `llms.txt` has the skill. |
-
----
-
-### Task 1: The examples and their honesty
-
-**Files:**
-- Create: `apps/site/public/skill/hairline-<name>.html` (four files, copied)
-- Create: `apps/site/lib/skill.ts`
-- Test: `apps/site/test/skill.test.ts`
-
-**Interfaces:**
-- Consumes: `skills/hairline-create/validate.mjs`, run as `node validate.mjs <page.html>`; it exits 0 and prints a line starting `ok` when the page passes, and exits 1 with one line per problem on stderr when it does not.
-- Produces, from `@/lib/skill`:
- - `INSTALL: string`, `COMMAND: string`
- - `type Example = { idea: string; file: string }`
- - `EXAMPLES: Example[]` (four, in page order)
- - `type Shown = Example & { name: string; means: string; prompt: string; href: string }`
- - `declared(html: string, file: string): { name: string; means: string }`
- - `examples(): Shown[]`
- - `SUMMARY: string`, `STEPS: { title: string; text: string }[]`, `FOLDER: string`, `USE: string[]`
-
-- [ ] **Step 1: Copy the four generated pages**
-
-```bash
-cd ~/estudos/hairline && mkdir -p apps/site/public/skill && cp .superpowers/trial/rerun/*/hairline-*.html apps/site/public/skill/ && ls apps/site/public/skill && for d in .superpowers/trial/rerun/*/; do echo "$d -> $(ls $d | grep '^hairline-.*\.html$')"; done
-```
-
-Expected: four `hairline-<name>.html` files listed, then one line per folder saying which file came from which idea. Keep that mapping for Step 3. The files are not opened in an editor and not reformatted.
-
-- [ ] **Step 2: Write the failing test**
-
-Create `apps/site/test/skill.test.ts`:
-
-```ts
-import { spawnSync } from "node:child_process";
-import { readdirSync, readFileSync } from "node:fs";
-import { fileURLToPath } from "node:url";
-import { describe, expect, it } from "vitest";
-import { COMMAND, EXAMPLES, INSTALL, declared, examples } from "@/lib/skill";
-
-/** The showcase is the skill's own output: these fail if an example was edited, renamed, dropped, or left behind by the kernel. */
-
-const PUBLIC = fileURLToPath(new URL("../public/skill/", import.meta.url));
-const VALIDATE = fileURLToPath(new URL("../../../skills/hairline-create/validate.mjs", import.meta.url));
-
-describe("the skill's examples", () => {
- it("are the four ideas, in page order", () => {
- expect(EXAMPLES.map((e) => e.idea)).toEqual(["a sales funnel", "a rate limiter", "git branches", "weather over a city"]);
- });
-
- it("are exactly the files in public/skill", () => {
- expect(EXAMPLES.map((e) => e.file).sort()).toEqual(readdirSync(PUBLIC).sort());
- });
-
- it.each(EXAMPLES)("$file passes the skill's validator untouched", ({ file }) => {
- const run = spawnSync(process.execPath, [VALIDATE, PUBLIC + file], { encoding: "utf8" });
- expect(run.stderr).toBe("");
- expect(run.status).toBe(0);
- });
-
- it("each carry the name their file is called by, a meaning, the prompt and the link", () => {
- for (const e of examples()) {
- expect(e.file).toBe(`hairline-${e.name}.html`);
- expect(e.means.length).toBeGreaterThan(0);
- expect(e.means.length).toBeLessThanOrEqual(140);
- expect(e.prompt).toBe(`${COMMAND} ${e.idea}`);
- expect(e.href).toBe(`/skill/${e.file}`);
- }
- });
-
- it("read the meaning out of the page, escapes undone", () => {
- const page = '<script type="module" id="hl-figure">\nconst tray = { name: "other", means: "not this" };\nhairline({ name: "tiers", means: "A \\"funnel\\" as trays.", rules: [1], range: [0, 1, 2], mount });\n</script>';
- expect(declared(page, "x.html")).toEqual({ name: "tiers", means: 'A "funnel" as trays.' });
- });
-
- it("refuse a page with no figure in it, naming the file", () => {
- expect(() => declared("<html></html>", "hairline-gone.html")).toThrow(/hairline-gone\.html/);
- });
-});
-
-describe("the skill's commands", () => {
- it("are the ones the skill is installed and called by", () => {
- expect(INSTALL).toBe("npx skills add lucasmarkes/hairline");
- expect(COMMAND).toBe("/hairline-create");
- expect(readFileSync(fileURLToPath(new URL("../../../skills/hairline-create/SKILL.md", import.meta.url)), "utf8")).toContain("name: hairline-create");
- });
-});
-```
-
-- [ ] **Step 3: Run it to see it fail**
-
-Run: `cd ~/estudos/hairline/apps/site && rtk proxy pnpm exec vitest run test/skill.test.ts`
-Expected: FAIL, the import of `@/lib/skill` cannot be resolved.
-
-- [ ] **Step 4: Write `lib/skill.ts`**
-
-Create `apps/site/lib/skill.ts`. In `EXAMPLES`, each `file` is the file name Step 1 printed for that idea's folder.
-
-```ts
-import { readFileSync } from "node:fs";
-import { join } from "node:path";
-
-/**
- * The skill, as the site tells it: the two commands, the examples, and the
- * page's copy as plain text, so /skill and /llms.txt say the same thing.
- * Server only: it reads the generated pages from public/skill.
- */
-
-export const INSTALL = "npx skills add lucasmarkes/hairline";
-export const COMMAND = "/hairline-create";
-
-export type Example = { idea: string; file: string };
-
-/** What was typed after the command, and the page the skill wrote for it. The pages are never edited. */
-export const EXAMPLES: Example[] = [
- { idea: "a sales funnel", file: "hairline-<name printed for 1-sales-funnel>.html" },
- { idea: "a rate limiter", file: "hairline-<name printed for 2-rate-limiter>.html" },
- { idea: "git branches", file: "hairline-<name printed for 3-git-branches>.html" },
- { idea: "weather over a city", file: "hairline-<name printed for 4-weather-city>.html" },
-];
-
-export type Shown = Example & { name: string; means: string; prompt: string; href: string };
-
-const FIGURE = /<script type="module" id="hl-figure">([\s\S]*?)<\/script>/;
-const NAME = /\bname:\s*["'`]([a-z][a-z0-9-]*)["'`]/;
-const MEANS = /\bmeans:\s*(["'`])((?:\\.|(?!\1)[^\\])*)\1/;
-
-/** The name and the meaning a generated page declares for its figure. */
-export function declared(html: string, file: string): { name: string; means: string } {
- const figure = FIGURE.exec(html)?.[1] ?? "";
- // the declaration is the page's last call; a `name:` earlier in the figure's own code is not it
- const call = figure.slice(Math.max(0, figure.lastIndexOf("hairline({")));
- const name = NAME.exec(call)?.[1];
- const means = MEANS.exec(call)?.[2];
- if (!name || !means) throw new Error(`skill: ${file} is not a page made by the skill's build.mjs.`);
- return { name, means: means.replace(/\\(.)/g, "$1") };
-}
-
-/** The examples with what their pages declare. `next build` and vitest both run from apps/site. */
-export function examples(): Shown[] {
- return EXAMPLES.map((e) => {
- const html = readFileSync(join(process.cwd(), "public", "skill", e.file), "utf8");
- return { ...e, ...declared(html, e.file), prompt: `${COMMAND} ${e.idea}`, href: `/skill/${e.file}` };
- });
-}
-
-export const SUMMARY = "hairline-create is a skill for coding agents. Give it an idea and it draws a new figure to Hairline's ten rules, on the same engine as the six, as one HTML file.";
-
-export const STEPS: { title: string; text: string }[] = [
- { title: "Concepts", text: "It offers two or three concepts, one line each: the object, what the pointer does, what the read-out says. You pick one." },
- { title: "Build", text: "It writes only the figure. The engine and the page around it are pasted in as they are." },
- { title: "Check", text: "A script checks the file against the rules, then the agent looks at it in a browser." },
- { title: "Hand over", text: "You get the page, the metaphor it used, the rules it leans on, and anything it could not check." },
- { title: "Adjust", text: "Ask for changes while you use it. It edits the figure and checks again." },
-];
-
-export const FOLDER = "What you install is one folder of small text files. There is no npm install, and Node is only needed to run the checks.";
-
-export const USE: string[] = [
- "Type the command with an idea. If you already have the metaphor, say it, and the concepts step is skipped.",
- "Out comes hairline-<name>.html: one file with no dependencies that opens from disk, holding the figure, an intensity slider and a theme switch.",
- "It runs on any agent that reads skills: Claude Code, Cursor, Codex and others.",
-];
-```
-
-- [ ] **Step 5: Run the test to see it pass**
-
-Run: `cd ~/estudos/hairline/apps/site && rtk proxy pnpm exec vitest run test/skill.test.ts`
-Expected: PASS, 10 tests (4 of them from `it.each`).
-
-- [ ] **Step 6: Prove the test catches a retouched example**
-
-```bash
-cd ~/estudos/hairline/apps/site && f=$(ls public/skill | head -1) && cp public/skill/$f /Users/lucasmarques/.claude/jobs/bf2ea971/tmp/$f && printf '\n<!-- touched -->\n<p>x</p>\n' >> public/skill/$f && rtk proxy pnpm exec vitest run test/skill.test.ts; cp /Users/lucasmarques/.claude/jobs/bf2ea971/tmp/$f public/skill/$f && rtk proxy pnpm exec vitest run test/skill.test.ts
-```
-
-Expected: the first run FAILS on "passes the skill's validator untouched" with a `bench:` line in stderr; after the file is restored, the second run PASSES.
-
-- [ ] **Step 7: Run the site's whole unit suite and the typecheck**
-
-Run: `cd ~/estudos/hairline && rtk proxy pnpm --filter @hairline/site test && rtk proxy pnpm --filter @hairline/site typecheck`
-Expected: every test passes; typecheck prints no error.
-
-- [ ] **Step 8: Commit**
-
-```bash
-cd ~/estudos/hairline && rtk git add apps/site/public/skill apps/site/lib/skill.ts apps/site/test/skill.test.ts && rtk git status && rtk git commit -m "Skill page: four figures the skill drew, kept as it wrote them, and a test that fails if one is touched
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-Check `git status` first: only the four pages, `lib/skill.ts` and `test/skill.test.ts` are staged.
-
----
-
-### Task 2: The page
-
-**Files:**
-- Create: `apps/site/components/command.tsx`
-- Create: `apps/site/components/example-frame.tsx`
-- Create: `apps/site/app/skill/page.tsx`
-- Modify: `apps/site/app/globals.css` (append at the end)
-- Test: `apps/site/test/skill.spec.ts`
-
-**Interfaces:**
-- Consumes, from `@/lib/skill` (Task 1): `INSTALL`, `COMMAND`, `SUMMARY`, `STEPS`, `FOLDER`, `USE`, `examples(): Shown[]` where `Shown = { idea, file, name, means, prompt, href }`.
-- Consumes, already in the site: `Topbar`, `Footer` from `@/components/chrome`; `CopyIcon` from `@/components/copy` (props `text`, `select`, `label`); `LINKS.github` from `@/lib/figures`; the classes `.pill`, `.pill-line`, `.doc-section`, `.doc-h2`, `.doc-p`, `.doc-note`, `.doc-more`, `.doc-code`.
-- Consumes, from the generated page: `main` (the page's one column), `#stage`, `#read` (reads `rest` until the pointer picks something), `body` padding of 24px top and bottom, and the `?theme=light` parameter.
-- Produces: the route `/skill`; the hooks `[data-command="install"]`, `[data-command="prompt"]` (the four examples only), `[data-command="usage"]`, `[data-example]`, `[data-steps]`, used by the tests here and in Task 3.
-
-- [ ] **Step 1: Write the failing browser tests**
-
-Create `apps/site/test/skill.spec.ts`:
-
-```ts
-import { expect, test, type FrameLocator, type Page } from "@playwright/test";
-
-const INSTALL = "npx skills add lucasmarkes/hairline";
-const IDEAS = ["a sales funnel", "a rate limiter", "git branches", "weather over a city"];
-
-function watch(page: Page): string[] {
- const noise: string[] = [];
- page.on("console", (m) => {
- // Vercel Analytics' script exists only on Vercel
- if (m.location().url.includes("/_vercel/")) return;
- if (m.type() === "error" || m.type() === "warning") noise.push(`${m.type()}: ${m.text()}`);
- });
- page.on("pageerror", (e) => noise.push(`pageerror: ${e}`));
- return noise;
-}
-
-/** The frames are lazy: each is brought on screen, then waited for until its figure is drawn. */
-async function frames(page: Page): Promise<FrameLocator[]> {
- const out: FrameLocator[] = [];
- for (let i = 0; i < IDEAS.length; i++) {
- const row = page.locator("[data-example]").nth(i);
- await row.scrollIntoViewIfNeeded();
- const frame = row.frameLocator("iframe");
- await expect(frame.locator("#stage svg")).toHaveCount(1);
- out.push(frame);
- }
- return out;
-}
-
-/** How tall the frame is, and how tall the page inside it needs to be. */
-const fit = (frame: FrameLocator) => frame.locator("main").evaluate((main) => ({ frame: window.innerHeight, page: (main as HTMLElement).offsetHeight + 48 }));
-
-test("/skill opens with the install command, four prompts and four live figures, and a clean console", async ({ page }) => {
- const noise = watch(page);
- await page.goto("/skill");
- await expect(page).toHaveTitle("Skill · hairline");
- await expect(page.getByRole("heading", { level: 1 })).toBeVisible();
- await expect(page.locator('[data-command="install"]')).toHaveText(new RegExp(INSTALL));
- await expect(page.locator('[data-command="prompt"]')).toHaveText(IDEAS.map((idea) => new RegExp(`/hairline-create ${idea}$`)));
- await expect(page.locator("[data-steps] > li")).toHaveCount(5);
- await frames(page);
- expect(noise).toEqual([]);
-});
-
-test("a figure on /skill answers the pointer and goes back to rest", async ({ page }) => {
- await page.goto("/skill");
- for (const frame of await frames(page)) {
- const read = frame.locator("#read");
- await expect(read).toHaveText("rest");
- const box = (await frame.locator("#stage").boundingBox())!;
- // somewhere on the stage the figure picks something; walk a grid until it does
- let answered = false;
- for (const fy of [0.5, 0.35, 0.65]) {
- for (const fx of [0.5, 0.35, 0.65]) {
- await page.mouse.move(box.x + box.width * fx, box.y + box.height * fy, { steps: 4 });
- if ((await read.textContent()) !== "rest") { answered = true; break; }
- }
- if (answered) break;
- }
- expect(answered).toBe(true);
- await page.mouse.move(2, 2);
- await expect(read).toHaveText("rest");
- }
-});
-
-test("each frame is named by what its figure means, and its link opens the page the skill wrote", async ({ page, request }) => {
- await page.goto("/skill");
- for (const row of await page.locator("[data-example]").all()) {
- const title = await row.locator("iframe").getAttribute("title");
- expect(title!.length).toBeGreaterThan(20);
- const href = await row.getByRole("link", { name: "Open the page" }).getAttribute("href");
- expect(href).toMatch(/^\/skill\/hairline-[a-z0-9-]+\.html$/);
- const res = await request.get(href!);
- expect(res.status()).toBe(200);
- expect(res.headers()["content-type"]).toContain("text/html");
- expect(await res.text()).toContain('id="hl-figure"');
- }
-});
-
-test("the install command and a prompt copy as they are written", async ({ page, context }) => {
- await context.grantPermissions(["clipboard-read", "clipboard-write"]);
- await page.goto("/skill");
- await page.locator('[data-command="install"] .icopy').click();
- expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(INSTALL);
- await page.locator('[data-command="prompt"] .icopy').nth(2).click();
- expect(await page.evaluate(() => navigator.clipboard.readText())).toBe("/hairline-create git branches");
-});
-
-for (const width of [1200, 320]) {
- test(`at ${width}px /skill does not scroll sideways, and no frame scrolls inside`, async ({ page }) => {
- await page.setViewportSize({ width, height: 800 });
- await page.goto("/skill");
- const list = await frames(page);
- expect(await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth)).toBe(0);
- for (const frame of list) {
- await expect.poll(async () => { const f = await fit(frame); return f.frame - f.page; }).toBe(0);
- }
- });
-}
-
-test.describe("on a dark system", () => {
- test.use({ colorScheme: "dark" });
-
- test("every frame is still light, as the site is", async ({ page }) => {
- await page.goto("/skill");
- for (const frame of await frames(page)) {
- expect(await frame.locator("body").evaluate((body) => getComputedStyle(body).backgroundColor)).toBe("rgb(255, 255, 255)");
- }
- });
-});
-
-test.describe("without JavaScript", () => {
- test.use({ javaScriptEnabled: false });
-
- test("/skill still gives the install command, the prompts and the links to the pages", async ({ page }) => {
- await page.goto("/skill");
- await expect(page.locator('[data-command="install"]')).toHaveText(new RegExp(INSTALL));
- await expect(page.locator('[data-command="prompt"]')).toHaveCount(4);
- await expect(page.getByRole("link", { name: "Open the page" })).toHaveCount(4);
- });
-});
-```
-
-- [ ] **Step 2: Run them to see them fail**
-
-Run: `cd ~/estudos/hairline && lsof -ti:4320 | xargs kill 2>/dev/null; rtk proxy pnpm --filter @hairline/site build && cd apps/site && rtk proxy pnpm exec playwright test skill.spec.ts`
-Expected: every test FAILS, `/skill` is a 404.
-
-- [ ] **Step 3: Write `components/command.tsx`**
-
-```tsx
-"use client";
-
-import { useRef } from "react";
-import { CopyIcon } from "./copy";
-
-/**
- * One line to type, in a pill with a copy icon. `kind` says which line it is,
- * for the tests (`prompt` is an example's, `usage` the bare command); a shell
- * command takes the `$` in front of it.
- */
-export function Command({ code, kind, label }: { code: string; kind: "install" | "prompt" | "usage"; label: string }) {
- const line = useRef<HTMLElement>(null);
- return (
- <div className="pill" data-command={kind}>
- {kind === "install" && <span aria-hidden="true" className="select-none text-faint">$</span>}
- <code ref={line} className="pill-line" title={code}>{code}</code>
- <CopyIcon text={code} select={line} label={label} />
- </div>
- );
-}
-```
-
-- [ ] **Step 4: Write `components/example-frame.tsx`**
-
-```tsx
-"use client";
-
-import { useEffect, useRef } from "react";
-
-/** The generated page's body has 24px of padding above and below its one column. */
-const PAD = 48;
-
-/**
- * A page the skill wrote, in a frame as tall as that page: the frame never
- * scrolls inside. Its height is reserved in CSS before it loads, then fitted
- * to the page's column and kept fitted as the column's text wraps.
- */
-export function ExampleFrame({ src, title }: { src: string; title: string }) {
- const frame = useRef<HTMLIFrameElement>(null);
-
- useEffect(() => {
- const el = frame.current;
- if (!el) return;
- let watch: ResizeObserver | undefined;
- const fit = () => {
- const view = el.contentWindow as (Window & typeof globalThis) | null;
- const main = el.contentDocument?.querySelector("main");
- if (!view || !main) return;
- const size = () => { el.style.height = `${main.offsetHeight + PAD}px`; };
- size();
- watch?.disconnect();
- // the frame's own observer: its column is in the frame's document
- watch = new view.ResizeObserver(size);
- watch.observe(main);
- };
- fit();
- el.addEventListener("load", fit);
- return () => {
- el.removeEventListener("load", fit);
- watch?.disconnect();
- };
- }, []);
-
- return <iframe ref={frame} className="example-frame" src={src} title={title} loading="lazy" />;
-}
-```
-
-- [ ] **Step 5: Add the page's classes**
-
-Append to the end of `apps/site/app/globals.css`:
-
-```css
-/* /skill: the pitch, then each prompt beside the page it produced, then how it works and how to use it. */
-.skill { display: grid; gap: 72px; max-width: 1080px; margin: 0 auto; padding: 64px clamp(18px, 5vw, 28px) 96px; }
-.skill > * { min-width: 0; }
-.skill-install { margin-top: 28px; max-width: 460px; }
-.example { display: grid; gap: 16px; padding: 28px 0; border-top: 1px solid var(--color-line); }
-.example:last-child { border-bottom: 1px solid var(--color-line); }
-.example > * { min-width: 0; }
-.example-prompt { display: grid; gap: 12px; align-content: start; }
-.example-figure { container-type: inline-size; }
-/* the height the generated page takes before it is measured: its 5:4 stage, at most 640px wide, and the lines under it */
-.example-frame { display: block; width: 100%; height: calc(min(100cqw - 32px, 640px) * 0.8 + 190px); border: 0; }
-.skill-steps { display: grid; gap: 12px; max-width: 64ch; counter-reset: step; }
-.skill-steps > li { display: grid; grid-template-columns: 2.2em minmax(0, 1fr); font-size: 15px; line-height: 1.55; color: var(--color-muted); counter-increment: step; }
-.skill-steps > li::before { content: counter(step, decimal-leading-zero); font: 400 12px/1.95 var(--font-mono); color: var(--color-faint); }
-.skill-steps strong { font-weight: 500; color: var(--color-ink); }
-
-@media (min-width: 900px) {
- .example { grid-template-columns: minmax(0, 1fr) minmax(0, 1.5fr); gap: 40px; align-items: start; }
- .example-prompt { position: sticky; top: calc(var(--topbar) + 24px); }
-}
-```
-
-- [ ] **Step 6: Write the page**
-
-Create `apps/site/app/skill/page.tsx`:
-
-```tsx
-import type { Metadata } from "next";
-import { Footer, Topbar } from "@/components/chrome";
-import { Command } from "@/components/command";
-import { ExampleFrame } from "@/components/example-frame";
-import { LINKS } from "@/lib/figures";
-import { COMMAND, FOLDER, INSTALL, STEPS, SUMMARY, USE, examples } from "@/lib/skill";
-
-export const metadata: Metadata = { title: "Skill · hairline", description: SUMMARY, alternates: { canonical: "/skill" } };
-
-/**
- * The skill's page: what it draws first, then how to get it and use it. A
- * Server Component: it reads each example's name and meaning from the page
- * the skill wrote, and that page is shown as it is, in a frame.
- */
-export default function Skill() {
- const shown = examples();
- return (
- <>
- <Topbar />
- <main className="skill">
- <header>
- <h1 className="max-w-[16ch] text-[36px] font-medium leading-[1.05] tracking-[-0.035em] md:text-[44px]">A seventh figure, from one line.</h1>
- <p className="mt-4 max-w-[64ch] text-[16px] leading-[1.55] text-muted">{SUMMARY}</p>
- <div className="skill-install"><Command code={INSTALL} kind="install" label="Copy install command" /></div>
- </header>
-
- <section aria-labelledby="examples-title" className="doc-section">
- <h2 id="examples-title" className="doc-h2">What it draws</h2>
- <p className="doc-p">Each figure below is the page the skill wrote for the line beside it, as it wrote it. Move the pointer over one.</p>
- <div>
- {shown.map((e) => (
- <article key={e.file} className="example" data-example={e.name}>
- <div className="example-prompt">
- <Command code={e.prompt} kind="prompt" label="Copy prompt" />
- <a className="doc-more" href={e.href}>Open the page</a>
- </div>
- <div className="example-figure">
- <ExampleFrame src={`${e.href}?theme=light`} title={e.means} />
- </div>
- </article>
- ))}
- </div>
- </section>
-
- <section aria-labelledby="how-title" className="doc-section">
- <h2 id="how-title" className="doc-h2">How it works</h2>
- <ol className="skill-steps" data-steps>
- {STEPS.map((s) => (
- <li key={s.title}><span><strong>{s.title}.</strong> {s.text}</span></li>
- ))}
- </ol>
- <p className="doc-note">{FOLDER}</p>
- </section>
-
- <section aria-labelledby="use-title" className="doc-section">
- <h2 id="use-title" className="doc-h2">How to use it</h2>
- <div className="max-w-[460px]"><Command code={`${COMMAND} <idea>`} kind="usage" label="Copy command" /></div>
- {USE.map((line) => <p key={line} className="doc-p">{line}</p>)}
- <p className="doc-note">
- The six figures and their options are in <a className="doc-more" href="/docs">the docs</a>. The skill&rsquo;s files are in <a className="doc-more" href={`${LINKS.github}/tree/main/skills/hairline-create`}>its folder on GitHub</a>.
- </p>
- </section>
- </main>
- <Footer />
- </>
- );
-}
-```
-
-The command under "How to use it" has its own kind, `usage`, so `[data-command="prompt"]` counts only the four examples.
-
-- [ ] **Step 7: Build and run the browser tests**
-
-Run: `cd ~/estudos/hairline && lsof -ti:4320 | xargs kill 2>/dev/null; rtk proxy pnpm --filter @hairline/site build && cd apps/site && rtk proxy pnpm exec playwright test skill.spec.ts`
-Expected: PASS, 9 tests. In the build's route list, `/skill` is static (`○`).
-
-If "no frame scrolls inside" fails by a constant, the generated page's body padding is not 24px: read `body { padding: … }` in `skills/hairline-create/bench.html` and set `PAD` in `example-frame.tsx` and the `48` in the test's `fit` to twice its vertical value.
-
-- [ ] **Step 8: Look at it**
-
-```bash
-cd ~/estudos/hairline/apps/site && cat > .shot.mjs <<'EOF'
-import { chromium } from "@playwright/test";
-const out = "/Users/lucasmarques/.claude/jobs/bf2ea971/tmp";
-const browser = await chromium.launch({ channel: "chrome" });
-for (const [name, width] of [["wide", 1200], ["phone", 375]]) {
- const page = await browser.newPage({ viewport: { width, height: 900 } });
- await page.goto("http://localhost:4320/skill");
- for (const row of await page.locator("[data-example]").all()) { await row.scrollIntoViewIfNeeded(); await page.waitForTimeout(900); }
- await page.screenshot({ path: `${out}/skill-${name}.png`, fullPage: true });
- await page.close();
-}
-await browser.close();
-EOF
-(pnpm exec next start -p 4320 >/dev/null 2>&1 &) ; sleep 4; node .shot.mjs; rm -f .shot.mjs; lsof -ti:4320 | xargs kill 2>/dev/null; true
-```
-
-Open both pictures and check, against the home and `/docs`: the headline, the pill and the section titles match the site's type; each prompt sits beside its figure at 1200px and above it at 375px; no frame shows a scrollbar or a band of empty space under its last line; the frame's plate border is the only border around a figure. Fix what is off in `globals.css` and run Step 7 again.
-
-- [ ] **Step 9: Run everything**
-
-Run: `cd ~/estudos/hairline && lsof -ti:4320 | xargs kill 2>/dev/null; rtk proxy pnpm typecheck && rtk proxy pnpm test && rtk proxy pnpm test:browser`
-Expected: all pass. `site.spec.ts:185` (the arrow-keys picker) is known to fail once in a while and pass on a second run; if it is the only failure, run it again and say so in the report.
-
-- [ ] **Step 10: Commit**
-
-```bash
-cd ~/estudos/hairline && rtk git add apps/site/components/command.tsx apps/site/components/example-frame.tsx apps/site/app/skill/page.tsx apps/site/app/globals.css apps/site/test/skill.spec.ts && rtk git status && rtk git commit -m "Skill page: each prompt beside the figure it produced, live, then how the skill works and how to use it
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
----
-
-### Task 3: The way in: top bar and `llms.txt`
-
-**Files:**
-- Modify: `apps/site/components/chrome.tsx` (the `Topbar`'s `nav`)
-- Modify: `apps/site/lib/llms.ts` (before the `## Links` section)
-- Modify: `apps/site/test/site.spec.ts` (the two top-bar tests near lines 42 and 48)
-- Modify: `apps/site/test/docs.test.ts` (the `/llms.txt` describe block)
-- Test: `apps/site/test/skill.spec.ts` (two tests added)
-
-**Interfaces:**
-- Consumes, from `@/lib/skill` (Task 1): `INSTALL`, `COMMAND`, `SUMMARY`, `EXAMPLES` (`{ idea, file }[]`). `llms.ts` uses only these constants; it does not call `examples()`.
-- Produces: a `Skill` link in the top bar, second after `Docs`; a `## Skill` section in `/llms.txt`.
-
-- [ ] **Step 1: Change the top-bar tests and add the new ones**
-
-In `apps/site/test/site.spec.ts`, replace the test that starts at line 42 with:
-
-```ts
-test("the top bar holds the docs, the skill, the story, the version and GitHub, and no llms.txt button", async ({ page }) => {
- await page.goto("/");
- await expect(page.locator(".topbar nav > *")).toHaveCount(5);
- await expect(page.locator(".topbar nav > a").nth(1)).toHaveText("Skill");
- await expect(page.locator(".topbar")).not.toContainText("llms.txt");
-});
-```
-
-In the test that follows it ("the top bar's links sit as one row…"), change `expect(items).toHaveLength(4);` to `expect(items).toHaveLength(5);`.
-
-Append to `apps/site/test/skill.spec.ts`:
-
-```ts
-test("the top bar's Skill link opens /skill", async ({ page }) => {
- await page.goto("/");
- await page.getByRole("banner").getByRole("link", { name: "Skill" }).click();
- await expect(page).toHaveURL(/\/skill$/);
- await expect(page.getByRole("heading", { level: 1 })).toHaveText("A seventh figure, from one line.");
-});
-
-test("the top bar fits a 320px screen with its five items on one row", async ({ page }) => {
- await page.setViewportSize({ width: 320, height: 700 });
- await page.goto("/skill");
- expect(await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth)).toBe(0);
- const tops = await page.locator(".topbar nav > *").evaluateAll((els) => els.filter((el) => getComputedStyle(el).display !== "none").map((el) => Math.round(el.getBoundingClientRect().top)));
- expect(new Set(tops).size).toBe(1);
- const bar = (await page.locator(".topbar").boundingBox())!;
- const last = (await page.locator(".topbar nav > *").last().boundingBox())!;
- expect(last.x + last.width).toBeLessThanOrEqual(bar.x + bar.width);
-});
-```
-
-In `apps/site/test/docs.test.ts`, add the import `import { COMMAND, EXAMPLES, INSTALL } from "@/lib/skill";` beside the other `@/lib` imports, and add inside `describe("/llms.txt", …)`:
-
-```ts
- it("says how to install the skill and links each example to the page it produced", () => {
- expect(text).toContain("## Skill");
- expect(text).toContain(INSTALL);
- for (const e of EXAMPLES) expect(text).toContain(`- \`${COMMAND} ${e.idea}\`: https://example.test/skill/${e.file}`);
- expect(text.indexOf("## Skill")).toBeLessThan(text.indexOf("## Links"));
- });
-```
-
-- [ ] **Step 2: Run them to see them fail**
-
-Run: `cd ~/estudos/hairline/apps/site && rtk proxy pnpm exec vitest run test/docs.test.ts`
-Expected: FAIL on "says how to install the skill…": the text has no `## Skill`.
-
-Run: `cd ~/estudos/hairline/apps/site && lsof -ti:4320 | xargs kill 2>/dev/null; rtk proxy pnpm exec playwright test -g "top bar"`
-Expected: FAIL: the count is 4, and there is no `Skill` link.
-
-- [ ] **Step 3: Add the link**
-
-In `apps/site/components/chrome.tsx`, in `Topbar`, add the `Skill` link after `Docs`, and bring the comment above it up to date:
-
-```tsx
-/** The bar on every page: the name home, the docs, the skill, the story, the version, GitHub. */
-export function Topbar() {
- return (
- <header className="topbar">
- <a href="/" className="text-[15px] font-medium tracking-[-0.02em]">hairline</a>
- <nav className="flex items-center">
- <a className="topbar-link" href="/docs">Docs</a>
- <a className="topbar-link" href="/skill">Skill</a>
- <a className="topbar-link" href="/inspo">Inspo</a>
- <span className="topbar-link tabular-nums" data-version>v{pkg.version}</span>
- <a className="topbar-link" href={LINKS.github} aria-label="GitHub"><GitHub /></a>
- </nav>
- </header>
- );
-}
-```
-
-- [ ] **Step 4: Add the section to `llms.txt`**
-
-In `apps/site/lib/llms.ts`, add the import:
-
-```ts
-import { COMMAND, EXAMPLES, INSTALL, SUMMARY } from "./skill";
-```
-
-In the final `out.push(…)`, put these arguments directly before `"", "## Links", "",`:
-
-```ts
- "", "## Skill", "",
- SUMMARY,
- "", fence("sh", INSTALL),
- "", `Then type \`${COMMAND} <idea>\` in the agent. Four ideas, each with the page the skill wrote for it:`,
- "", EXAMPLES.map((e) => `- \`${COMMAND} ${e.idea}\`: ${base}/skill/${e.file}`).join("\n"),
- "", `More: ${base}/skill`,
-```
-
-- [ ] **Step 5: Build and run**
-
-Run: `cd ~/estudos/hairline && lsof -ti:4320 | xargs kill 2>/dev/null; rtk proxy pnpm typecheck && rtk proxy pnpm test && rtk proxy pnpm test:browser`
-Expected: all pass, the two top-bar tests in `site.spec.ts` and the two new ones in `skill.spec.ts` included.
-
-If "the top bar fits a 320px screen" fails, the five items are wider than the bar. Append to `globals.css`, after the `.topbar-link` rule, and run again:
-
-```css
-/* five items do not fit the narrowest phones: the version gives way first */
-@media (max-width: 359px) { .topbar [data-version] { display: none; } }
-```
-
-If the home's own phone test in `site.spec.ts` ("the page fits a phone…") fails for the same reason, the same rule fixes it; do not change that test.
-
-- [ ] **Step 6: Measure the page**
-
-Run: `cd ~/estudos/hairline && rtk proxy pnpm --filter @hairline/site build 2>&1 | rtk proxy grep -e "skill\|docs\|First Load" ; ls -l apps/site/public/skill`
-Record for the pull request: the `/skill` route's size and First Load JS next to `/docs`'s, and the four files' sizes. Expected: `/skill`'s First Load JS is no larger than `/docs`'s, and each generated page is under 40 KB.
-
-- [ ] **Step 7: Commit**
-
-```bash
-cd ~/estudos/hairline && rtk git add apps/site/components/chrome.tsx apps/site/lib/llms.ts apps/site/test/site.spec.ts apps/site/test/docs.test.ts apps/site/test/skill.spec.ts apps/site/app/globals.css && rtk git status && rtk git commit -m "Skill page: a Skill link in the top bar, and the skill in llms.txt with each example's page
-
-Co-Authored-By: Claude <[email protected]>"
-```
-
-If `globals.css` did not change in this task, leave it out of `git add`.
-
-- [ ] **Step 8: Push and open the pull request**
-
-```bash
-cd ~/estudos/hairline && rtk git push -u origin skill-page && rtk gh pr create --base main --head skill-page --title "/skill: the skill's page, with four figures it drew beside their prompts" --body-file /Users/lucasmarques/.claude/jobs/bf2ea971/tmp/skill-page-pr.md
-```
-
-Write `skill-page-pr.md` first, in English, with: what the page is and who it is for; that the four examples are the skill's output, unaltered, and which test fails if one is touched; the sizes from Step 6; a note that the page should reach production together with the repository going public, because the install command needs it. Do not merge.
-
-Then watch CI: `cd ~/estudos/hairline && rtk gh pr checks --watch`
-Expected: `verify` and the Vercel preview pass.
diff --git a/docs/superpowers/specs/2026-10-01-hairline-create-skill-design.md b/docs/superpowers/specs/2026-10-01-hairline-create-skill-design.md
deleted file mode 100644
index 4e70c5f..0000000
--- a/docs/superpowers/specs/2026-10-01-hairline-create-skill-design.md
+++ /dev/null
@@ -1,130 +0,0 @@
-# `hairline-create`: a skill that draws new Hairline figures
-
-Date: 2026-10-01. Status: design approved in conversation, awaiting review of this document.
-
-## Purpose
-
-Hairline ships six figures. This skill lets anyone with a coding agent make a seventh: they type `/hairline-create <idea>` and get one new isometric line figure that answers the pointer, drawn to the same ten rules and with the same engine as the six in the package.
-
-It is for people outside this repository, on any agent that reads skills (Claude Code, Cursor, Codex and others). Success is a figure Lucas would not be embarrassed to see next to Terrain: rounded, quiet, wordless, designed at rest, calm under the hand.
-
-## Decisions made
-
-| Question | Decision |
-| --- | --- |
-| What comes out | One self-contained HTML file with no dependencies. Published as an Artifact where the agent can publish one; saved as `hairline-<name>.html` where it cannot. Same content either way. |
-| Flow | Concept first: the skill offers two or three one-line concepts, the person picks, then it builds. |
-| Where the code comes from | A ready kernel, extracted from the package's `src/core`, pasted unaltered. The agent writes only the new figure. |
-| How it is checked | A validator script, then a look in a browser. Whatever could not be checked is said at hand-off. |
-| Where it lives | `skills/hairline-create/` in this repository, installed with `npx skills add lucasmarkes/hairline`. |
-| What the page shows | The figure on a bench: stage with corner read-out, one `intensity` slider, light/dark switch, one line saying what the figure means and which rules it leans on. |
-
-## What the person lives through
-
-1. **Concepts.** For `/hairline-create a sales funnel` the skill answers with two or three concepts, one line each: the object, what the pointer does, what the read-out says. If the person arrived with the metaphor already chosen, this step is skipped.
-2. **Build.** The agent assembles one HTML file from three parts: the bench (a fixed template), the kernel (pasted as is), and the figure (the only part it writes).
-3. **Check.** It runs the validator and, with a browser, the look. It fixes what fails before handing anything over.
-4. **Hand-off.** Artifact or file, plus one line each for: the metaphor used, the rules the figure leans on, anything not verified.
-5. **Adjustments.** The person asks for changes while using the bench. The agent edits only the figure and checks again.
-
-What reaches the person's machine on install is the skill folder and nothing else: small text files, no `npm install`, no package. Node is needed only to run the validator.
-
-## Files in `skills/hairline-create/`
-
-| File | Role |
-| --- | --- |
-| `SKILL.md` | The flow above, short. Points to each other file at the moment it is needed. Frontmatter: `name: hairline-create`, a description that says when to use it. |
-| `rules.md` | The ten rules from the study (01 hit, 02 order, 03 reach, 04 accent, 05 rest, 06 honesty, 07 cost, 08 clock, 09 radius, 10 quiet), each with its numbers and with the test that rejects a figure. |
-| `concepts.md` | How to turn an idea into a figure: the ways of answering the pointer already proven in the package, and what makes a concept weak (dead at rest, needs words to be understood, more than one idea, no reason for the pointer). |
-| `kernel.js` | The engine as plain JavaScript, generated from `packages/hairline/src/core`. |
-| `bench.html` | The page template, with two marked slots: kernel and figure. |
-| `build.mjs` | Puts a figure on the bench: `node build.mjs <figure.js>` writes the page. No dependencies. |
-| `examples/terrain.js`, `examples/riffle.js` | Two figures of the package in the skill's format: a continuous field (springs, falloff by distance) and discrete items (stagger, tweens, identity by geometry). |
-| `validate.mjs` | The validator. No dependencies. |
-| `look.md` | The checklist for the look, and how to do it by reading code when there is no browser. |
-
-## The kernel
-
-- **Content.** The four files of `packages/hairline/src/core`: `iso.ts` (camera, projection, rounded solids), `motion.ts` (springs, the 700ms curve, tweens, reduced motion), `stage.ts` (the shared loop that sleeps offscreen, the pointer, disposal), `styles.ts` (the light and dark palettes and the stroke classes).
-- **Generation.** `scripts/kernel.mjs` bundles them with esbuild into one unminified, type-free file that defines a single global, `HL`. Unminified so the agent can read what it is calling.
-- **Marking.** In the output HTML the kernel sits between two marker comments carrying a hash of its content. That is how the validator knows it was not touched.
-- **The package does not change.** Nothing in `packages/hairline/src` is edited and no public API is added.
-
-## The figure contract
-
-The same contract as the six engines (`FigureMount` in `core/stage.ts`): the figure receives `{ stage, svg, read }` and a number, and returns `{ set(value), destroy() }`.
-
-Beside the mount function a figure declares:
-
-- `name`: what the read-out and the file are called.
-- `means`: the one line the bench shows under the stage.
-- `rules`: the rule numbers it leans on.
-- `range`: three numbers, the figure's own value at `intensity` 0, 0.5 and 1, joined by two straight lines, as in the package's `intensity.ts`. The middle one is the default.
-
-The bench owns everything else: it creates the host and the SVG, injects the kernel's stylesheet, maps the slider through `range` and calls `set`, switches the theme, and shows `means` and `rules`.
-
-Figures are pointer-only. The bench's stage is an image, not a focusable group, so the Riffle example leaves out the package's keyboard handling.
-
-## The validator
-
-`node validate.mjs <file.html>` exits non-zero and prints what to fix when:
-
-- the kernel is missing or its hash does not match;
-- the figure creates text in the SVG (`<text>`, `<tspan>`, `createElementNS(…, "text")`): rule 10;
-- the figure sets its own `stroke-width`, or a colour, fill, filter or shadow outside the kernel's classes: rule 04, and the single stroke;
-- the page loads anything from outside (`<script src>`, `<link>`, `fetch`, `import`, remote `url()`);
-- the figure never writes the read-out, or does not return `set` and `destroy`;
-- the figure runs its own clock (`setInterval`, `setTimeout`, `requestAnimationFrame`) or never joins the kernel's loop: rule 07 and reduced motion;
-- the figure listens to the pointer itself, measures what is on screen, or never calls the kernel's `pointer`: rule 01;
-- anything in the page other than the figure differs from the bench;
-- the figure does not declare `name`, `means`, `rules` and `range`;
-- the figure is over 200 lines, a sign the concept is too complicated.
-
-The checks are static, on the text of the file. They catch what is mechanical; the look catches the rest.
-
-## The look
-
-With a browser, the agent opens the file and takes four pictures: at rest and with the pointer over the figure, at 240px wide and at full size. It checks them against `look.md`:
-
-- the silhouette reads at 240px;
-- rest is a composition, not a flat or empty state (rule 05);
-- the answer falls off with distance, or spreads out from the pointer (rules 02, 03);
-- nothing flickers when the pointer sits on a moving edge (rule 01);
-- bright outside, dim inside, no vertical corners drawn (rule 09);
-- the read-out names what is under the pointer and says `rest` when nothing is.
-
-The bench takes two URL parameters for this: `?w=240` narrows the page, and `&at=x,y` holds the pointer at a viewBox point, for tools that cannot hover.
-
-Without a browser the agent answers the same list from the code and says so at hand-off. Without Node it reads the validator's list and says so too.
-
-## Tests
-
-In this repository's CI:
-
-- **Kernel is current.** Regenerate and compare with the committed `kernel.js`. A change to `src/core` that is not followed by a regenerated kernel fails.
-- **Validator.** The two examples, assembled on the bench, pass. A set of deliberately broken files, one per check, each fails with the right message.
-- **Browser (Playwright).** Each example on the bench: clean console; the SVG and the read-out change when the pointer enters and return to rest when it leaves; the slider changes the drawing; the theme switch changes the palette; no horizontal scroll at 240px.
-- **Fidelity.** The Terrain example on the bench draws the same SVG as the package's Terrain along the scripted pointer path of the existing parity tests, under the same frozen clock. This is the proof that the extracted kernel behaves as the original.
-- **Skill shape.** `SKILL.md` has valid frontmatter and every file it points to exists.
-
-## What the tests do not cover
-
-No automatic test proves that an agent turns a new idea into a good figure. Before the skill is announced there is a manual trial: five varied ideas, each in a clean session, judged by Lucas. Every recurring defect becomes a line in `rules.md` or a check in the validator. The trial is part of the work, not a follow-up; its results and the changes they caused are recorded in the pull request.
-
-## Out of scope
-
-- A Claude Code plugin (`.claude-plugin/`). It can be added later without rework.
-- Exporting the figure as a component for a project.
-- More than one figure per file.
-- A section on the site's `/docs`. A separate pull request after the trial, so nothing is announced before its quality is known.
-- Any change to the package's public API.
-
-## Dependencies and risks
-
-- **The repository must be public** for `npx skills add lucasmarkes/hairline` to work. That is step 1 of T16 and waits for Lucas. The skill can be built, tested and tried locally before then.
-- **Kernel size.** Around 600 lines of TypeScript become the kernel; it is pasted into every output and read by the agent. If it weighs too much on context, the agent can be told to copy it by file operation instead of reading it, and to read only a short API summary. The plan measures this in the trial.
-- **Static checks can be fooled.** A figure can break rule 04 in ways a text check misses. The look and the trial are the answer, not a cleverer validator.
-
-## Execution
-
-Lucas asked that the architect (spec, plan, review) run on Fable and the code be written by subagents on Opus.
diff --git a/docs/superpowers/specs/2026-10-01-hairline-docs-design.md b/docs/superpowers/specs/2026-10-01-hairline-docs-design.md
deleted file mode 100644
index a5ebe94..0000000
--- a/docs/superpowers/specs/2026-10-01-hairline-docs-design.md
+++ /dev/null
@@ -1,233 +0,0 @@
-# Hairline: the docs page
-
-The site's `/docs` today is an interim page: a two-step quickstart, the options table, six small figures in rows, and four cards. This spec replaces it with real documentation in the structure of https://cuelume.dev/docs. It is one long page with a sidebar of anchors, written in the site's black-and-white look.
-
-It builds on `2026-10-01-hairline-dx-redesign-design.md`. Nothing here changes the package.
-
-## Goals
-
-- A reader can install, paste and tune a figure without leaving `/docs`.
-- The page says what `/llms.txt` says. Both read the same data in `lib/`, so the two cannot drift.
-- The page is black and white. Geist Sans is used everywhere, and Geist Mono only for code. That includes the syntax highlighting, which becomes grayscale.
-- It stays a static Server Component with no new dependency.
-
-## Non-goals
-
-- Search, an on-this-page table of contents, previous/next links, or a dark mode for the site.
-- Multiple docs pages, MDX, or rendering the page from `llms.txt`.
-- Per-figure controls on the docs. The home inspector already has them.
-
-## Decisions taken in brainstorming
-
-| Question | Decision |
-| --- | --- |
-| Structure | One page, sidebar of anchors (cuelume) |
-| Figure catalog | One row per figure, small and live, text beside it, then one intensity table |
-| Quick start | One code block with tabs: React, Vanilla, CDN |
-| Build approach | Sections in TSX fed by the existing data in `lib/`; no MDX |
-
-## Layout
-
-The top bar and footer are the home's (`components/chrome.tsx`). The page background is `--color-canvas` (white).
-
-**Desktop, 1024px and up.** The two columns sit inside the 1080px container.
-- **Sidebar column.** 220px wide, `position: sticky` just under the top bar.
-- **Content column.** Prose is capped at 64ch. Code blocks and tables take the column's full width.
-
-**The sidebar.** It has three groups, read from `SECTIONS` (below):
-- **Getting started:** Install · Quick start · Options
-- **API:** React · Vanilla · CDN
-- **Reference:** Figures · Theme · Accessibility
-
-Styling:
-- **Group label:** Geist Sans 12px, weight 500, `--color-muted`, sentence case. It is not mono and not uppercase.
-- **Item:** 14px, `--color-muted`, with a 32px row and an 8px radius.
-- **Hover:** the item turns `--color-ink`.
-- **Active item:** `--color-ink` on a `--color-stone` background, with `aria-current="location"`.
-- The background change is a 150ms `background-color, color` transition. Nothing slides, since this changes many times a visit.
-
-**Phone, below 1024px.**
-- The sidebar becomes one sticky horizontal strip under the top bar. It shows the nine items without group labels and scrolls sideways.
-- A 24px fade masks the strip's left and right edges while there is more strip to scroll that way.
-- When the active section changes, the active item is scrolled into the strip with `scrollIntoView({ block: "nearest", inline: "nearest" })`.
-
-**The active section.**
-- An IntersectionObserver watches the nine `<section>` elements, using a band that runs from just under the sticky chrome to 30% down the viewport.
-- The active section is the first, in page order, that intersects the band. When the page is scrolled to its end, the last section is active.
-- Before the first section reaches the band, Install is active.
-
-**Anchor links.**
-- Clicking an item is a plain `<a href="#id">`. The browser scrolls and the hash lands in the URL.
-- `html { scroll-behavior: smooth }` applies only under `prefers-reduced-motion: no-preference`.
-- Every section has `scroll-margin-top`, set from a CSS variable: the top bar on desktop, and the top bar plus the strip on a phone.
-
-**The header of the content column.** It has no eyebrow.
-- **h1:** "Six figures, one set of options." (36px; 44px from `md`)
-- **Lead:** "Every figure takes the same four options and draws itself in SVG, with no dependencies. Install the package, paste a figure, and turn `intensity` up or down." (16px, `--color-muted`)
-
-## Sections
-
-Every section is a `<section id={id} aria-labelledby={id + "-title"}>` with an h2 (Sans, 24px, weight 500). A paragraph under an h2 is 15–16px.
-
-1. **Install** (`install`)
- - "Install the package, then import a figure wherever your interface runs."
- - Below it, the `Install` pill (npm, pnpm, yarn, bun, shadcn), unchanged.
- - Then a muted note: "Click the command to switch package manager. ESM only, no dependencies, {tiny()} gzipped for all six; a bundle that imports one carries one."
-2. **Quick start** (`quick-start`)
- - "Paste a figure. It fills its parent's width at a 5:4 aspect ratio."
- - Below it, `Tabs` with React (`app/page.tsx`, `REACT`), Vanilla (`main.ts`, `VANILLA`) and CDN (`index.html`, `CDN`).
- - The chosen tab is kept in `localStorage` under `hairline:docs-tab`. The server renders React; after mount the stored tab is read inside a try/catch, and if storage fails the tab stays React.
-3. **Options** (`options`)
- - "Every figure takes the same four options, all optional."
- - Below it, the `OPTIONS` table: Option · Type · Default · What it does, with the first three columns in mono. It is the existing `.props` table and its phone layout.
-4. **React** (`react`)
- - A signature `CodeBlock` titled "Signature":
- ```tsx
- <Terrain
- intensity?: number
- theme?: "auto" | "light" | "dark"
- label?: string
- onRead?: (text: string) => void
- {...divProps}
- />
- ```
- - Then the prose from `llms.ts`: import any of the six from `@lucasmarkes/hairline/react`; it renders a `<div>`, takes any `<div>` attribute and forwards its ref; it is a client module, so a Server Component renders it without writing "use client".
- - Then `REACT` in a `CodeBlock` titled `app/page.tsx`.
-5. **Vanilla** (`vanilla`)
- - A signature `CodeBlock`:
- ```ts
- terrain(element: HTMLElement, options?: HairlineOptions): {
- update(options: HairlineOptions): void
- destroy(): void
- }
- ```
- - Then the prose: one function per figure, named in lower case. In `update`, a key set to `undefined` goes back to its default and a key left out stays as it is. `destroy` removes the drawing and its listeners.
- - Then `VANILLA` in a `CodeBlock` titled `main.ts`.
-6. **CDN** (`cdn`)
- - "Without a bundler, import from esm.sh in a module script."
- - Then `CDN` in a `CodeBlock` titled `index.html`.
-7. **Figures** (`figures`)
- - "Every figure takes `intensity`, from 0 to 1. Here is what it turns up."
- - Six rows, one per `FIGURES` entry, reusing `.figure-row`, `.tile` and `data-row`.
- - Each row has the live figure at its defaults in a `.tile` up to 240px wide, and beside it:
- - an h3 with the name (Sans, upright);
- - "Higher intensity: {stronger}";
- - the summary, in muted text.
- - Below 640px a row stacks, text first.
- - Then a table, `data-intensity`: Figure · Parameter · 0 · 0.5 · 1.
- - One row per figure, from `INTENSITY` and `parameter`, with units (for example "stagger" · "0 ms" · "40 ms" · "90 ms"; "rate" · "0.6×" · "0.2×" · "0.05×").
- - The number cells are mono and `tabular-nums`.
- - Then a link: "Try them on the home page →", to `/#try`.
-8. **Theme** (`theme`)
- - Lead from `llms.ts`: six custom properties, set on the figure or on any ancestor. Without them a figure is light, or dark when an ancestor has class `dark` or `data-theme="dark"`, or when the page's `color-scheme` is dark.
- - Then the `THEME` table: Property · Light · Role, with the first two columns in mono.
- - Then `CSS` in a `CodeBlock` titled `globals.css`.
-9. **Accessibility** (`accessibility`). A list of three:
- - Each figure is an image with a description; `label` (or `aria-label` in React) replaces it.
- - Riffle is a focusable group: the arrow keys walk its cards and a live region reads out the card's number.
- - Under `prefers-reduced-motion`, Phosphor and Slow hold still, and every figure still answers the pointer.
-
-After the last section, a muted line closes the page. It is not a section and not in the sidebar: "Anything missing? [Open an issue on GitHub](https://github.com/lucasmarkes/hairline/issues)."
-
-## Code blocks
-
-There is one `CodeBlock` client component (it needs `CopyIcon`). `Tabs` uses the same frame.
-
-- **Frame:** background `#fafafa`, `box-shadow: inset 0 0 0 1px var(--color-stone)`, 12px radius, `overflow: hidden`.
-- **Bar:**
- - The title (file name or "Signature") is in Sans 12px, `--color-muted`.
- - The `CopyIcon` is on the right.
- - In `Tabs`, the tabs sit on the left; the active tab's file name and the copy icon sit on the right.
-- **Body:** Geist Mono 13px/1.65, padding 16px 18px, horizontal scroll. The body wrapper is the block's one tab stop (`tabIndex={0}`). `highlight()` strips the `tabindex` shiki writes on its `pre`, so there are never two stops.
-- **Line numbers:**
- - They come from a CSS counter on shiki's `span.line`, drawn in `::before` in `--color-faint`.
- - They are right-aligned in a 2ch gutter with 16px of space after it.
- - A pseudo-element is in neither the selection nor `textContent`, so copying never carries them.
- - Signature blocks have no line numbers (`data-plain`).
-
-**Grayscale highlighting.**
-- `lib/highlight.ts` passes shiki a theme made by `createCssVariablesTheme({ name: "hairline", variablePrefix: "--code-" })`. So shiki writes `color: var(--code-…)` and no hex.
-- The variables are defined once in `app/globals.css` `:root`. Every value is at least 4.5:1 on `#fafafa`. The mapping below is what shiki 4.5's CSS-variables theme emits for tsx, checked against real output:
-
-| Variable | Value | Covers |
-| --- | --- | --- |
-| `--code-foreground` | `#0a0a0a` | plain text, identifiers, brackets |
-| `--code-token-constant` | `#0a0a0a` | component names, numbers, constants |
-| `--code-token-function` | `#404040` | function names, JSX attributes |
-| `--code-token-parameter` | `#404040` | parameters |
-| `--code-token-string`, `--code-token-string-expression` | `#525252` | strings |
-| `--code-token-keyword`, `--code-token-comment`, `--code-token-punctuation`, `--code-token-link` | `#6b6b6b` | keywords, `=`, comments |
-| `--code-background` | `transparent` | (the frame paints it) |
-
-The home inspector's snippet (`components/code.tsx`) switches its colors to the same variables, keeping its markup:
-- `.t-kw` → keyword
-- `.t-str` → string
-- `.t-tag` → constant (it keeps its weight of 500)
-- `.t-attr` → function
-- `.t-val` → foreground
-
-## Data
-
-- **`lib/docs.ts` (new)** exports `SECTIONS: { id: string; group: "Getting started" | "API" | "Reference"; title: string }[]`, with the nine entries above in page order. The sidebar and the page both map over it, so an anchor cannot exist on only one side.
-- **`lib/snippets.ts`:**
- - `PASTE` becomes `QUICKSTART`: React, Vanilla and CDN, each with `{ label, lang, file, code }`.
- - `CSS` stays and is used by Theme.
- - Two new constants, `REACT_SIGNATURE` and `VANILLA_SIGNATURE`, hold the signature text above.
-- **`lib/figures.ts`:** `CARDS` is removed.
-- **`lib/llms.ts`** is not restructured. It keeps reading `FIGURES`, `OPTIONS`, `THEME` and the snippets.
-- **Highlighting** happens at build in the page's Server Component, as now. No highlighter reaches the browser.
-
-## Files
-
-- **Create:**
- - `lib/docs.ts`
- - `components/sidebar.tsx` (client)
- - `components/code-block.tsx` (client)
- - `app/docs/sections.tsx`: one server component per group, so `GettingStarted`, `Api` and `Reference`, each rendering its sections from props it is given.
-- **Modify:**
- - `app/docs/page.tsx`: the layout, the header, highlighting the snippets, and passing them down.
- - `components/tabs.tsx`: the `CodeBlock` frame, file names and the remembered tab.
- - `lib/highlight.ts`: the CSS-variables theme.
- - `lib/snippets.ts`
- - `lib/figures.ts`
- - `app/globals.css`: the `--code-*` variables, the docs layout, sidebar and strip, the code frame, line numbers, the `data-intensity` table, and a stacked `.figure-row` below 640px.
- - `components/code.tsx`: its CSS only, via the variables.
- - `app/page.tsx`: `id="try"` on the "Try it" section.
-- **Remove:** the CSS for `.card`, `.step`, `.step-title` and `.step-n`, and the old `.code-bar`/`.code-tab` rules.
-
-## Edge cases
-
-- **No JavaScript.**
- - The sidebar is plain links and still works. Only the active highlight is missing.
- - The figures draw nothing, as on the home today.
- - The tabs show React.
-- **Opening `/docs#theme`.** The browser scrolls to it, and `scroll-margin-top` clears the sticky chrome. The observer marks Theme on its first callback.
-- **No clipboard.** `CopyIcon` already falls back to selecting the text.
-- **Storage throws** (private mode, blocked). The tab stays React and nothing throws.
-- **A long line in a code block.** The body scrolls horizontally and the page never does, down to 320px.
-
-## Testing
-
-**vitest (`test/docs.test.ts`)**
-- `SECTIONS` has nine unique ids, in the three groups in order, and every id is a valid fragment (`/^[a-z-]+$/`).
-- `/llms.txt` has a `## ` heading for each docs section it shares: Install, Options, Figures, Theme, Accessibility.
-- Highlighting a snippet writes `var(--code-`, no `#` hex color and no `tabindex`.
-- The quickstart test pastes three ways (React, Vanilla, CDN), each with a file name, and none sets an option the package dropped.
-- "sets all six theme properties" moves from the CSS tab to `CSS`, unchanged.
-- The Tiny-card test is renamed for the Install note; the assertion is unchanged.
-- The intensity table's cells format units the way `scale()` does.
-
-**Playwright (`test/site.spec.ts`)**, against `next start`:
-- The docs prerender six empty boxes, then draw one figure per row with a clean console. This test exists and stays.
-- Get started leads to `/docs`, and the quick start shows three tabs and copies the active one. This test exists; it changes from four tabs to three.
-- Clicking "Theme" in the sidebar puts `#theme` in the URL and `aria-current="location"` on Theme.
-- Scrolling to Accessibility moves `aria-current` to Accessibility.
-- At 390px:
- - the strip is visible and the grouped sidebar is not;
- - `document.documentElement.scrollWidth <= innerWidth`;
- - after a click on Accessibility, its item is inside the strip's box.
-- Copying a `CodeBlock` puts the code on the clipboard with no line numbers: the first line of `REACT` begins `import`.
-- Every `span` inside a docs `pre` has a computed color with equal r, g and b.
-- The one-family test still passes: Sans everywhere, mono only in `code` and `pre`, serif only in the home's `h1 em`.
-
-Both suites, plus `pnpm typecheck` and `pnpm build`, must pass before the work is called done.
diff --git a/docs/superpowers/specs/2026-10-01-hairline-dx-redesign-design.md b/docs/superpowers/specs/2026-10-01-hairline-dx-redesign-design.md
deleted file mode 100644
index 68cc65f..0000000
--- a/docs/superpowers/specs/2026-10-01-hairline-dx-redesign-design.md
+++ /dev/null
@@ -1,213 +0,0 @@
-# Hairline: one prop, and a site that leads with the install
-
-An amendment to `2026-10-01-hairline-package-design.md` (the base spec). It comes from Lucas's review of the first Vercel preview (Task 14 of the base plan). Nothing is published yet, so the API can still change without a major version.
-
-Where this document speaks to a topic, it replaces the base spec on that topic. Everything else in the base spec stands.
-
-## Why
-
-Lucas's review, in short:
-
-1. The six figures each take a differently named option: `stagger`, `radius`, `gap`, `afterglow`, `rate`, `coast`. A consumer has to learn six words and six units to do one thing, which is to make a figure react more or less.
-2. Riffle's `bands` and `labels` make no sense to a consumer. The cards should carry no names at all.
-3. The "Fig. 1 … Fig. 6" corner labels on the site's tiles should go.
-4. The install command should come first.
-5. The site should take its structure from https://cuelume-site.pages.dev/.
-
-## Goals
-
-- One options type for all six figures, with one tuning prop, `intensity`.
-- `<Riffle />` with no props is the complete minimal example.
-- The visual at the default is exactly today's, so the parity goldens still hold.
-- A one-page site, in cuelume's structure: install first, a live inspector, then a two-step quickstart.
-
-## Non-goals
-
-- New figures, new behaviour, or a new look for the figures.
-- Per-figure fine tuning. A consumer who needs a 37 ms stagger is not served by 0.1.0.
-- Changing the theme, the styles, the mount, SSR, the build, the gates or the release flow.
-
-## The package API
-
-### Options
-
-Every figure takes the same options:
-
-```ts
-type HairlineOptions = {
- /** How strongly the figure answers the pointer, from 0 (subtle) to 1 (strong). Default 0.5. */
- intensity?: number;
- /** "auto" follows the page. Default "auto". */
- theme?: "auto" | "light" | "dark";
- /** The accessible name. Each figure has a default description in English. */
- label?: string;
- /** The figure's caption, each time it changes. Called once at mount with the rest caption. */
- onRead?: (text: string) => void;
-};
-
-type Figure = {
- update(options: HairlineOptions): void;
- destroy(): void;
-};
-```
-
-```ts
-import { riffle } from "@lucasmarkes/hairline";
-
-const fig = riffle(el);
-fig.update({ intensity: 0.8 });
-fig.destroy();
-```
-
-The vanilla entry exports the six functions and the types `HairlineOptions` and `Figure`. Each function is `(el: HTMLElement, options?: HairlineOptions) => Figure`.
-
-### What `intensity` does to each figure
-
-Each figure turns `intensity` into its own parameter, internally. The map is two straight lines that meet at 0.5. At 0.5 each parameter has today's default, and 0 and 1 give today's limits:
-
-| Figure | Parameter (internal) | 0 | 0.5 | 1 | What "stronger" means |
-| --- | --- | --- | --- | --- | --- |
-| Riffle | stagger (ms) | 0 | 40 | 90 | The ripple spreads further from the pulled card |
-| Terrain | radius (cells) | 1.5 | 3 | 5 | A wider area rises |
-| Exploded | gap (viewBox units) | 12 | 28 | 40 | The layers open further |
-| Phosphor | afterglow (ms) | 150 | 520 | 1500 | The trail lingers longer |
-| Slow | rate (× normal speed) | 0.6 | 0.2 | 0.05 | Time slows down more |
-| Turntable | coast (ms) | 200 | 650 | 1500 | The spin coasts longer |
-
-For `i` at or below 0.5, the value is `lo + (i / 0.5) * (mid - lo)`. Above 0.5 it is `mid + ((i - 0.5) / 0.5) * (hi - mid)`. The result is rounded to three decimal places, so `0.7` gives Riffle exactly 60 ms and not 59.99999999999999.
-
-The map lives in one internal module, `src/intensity.ts`, with a table of these six rows and one function, `parameter(figure, intensity): number`. It is not exported from either entry.
-
-### Values `intensity` accepts
-
-- A finite number is clamped to 0…1.
-- A numeric string is read as a number, as an attribute or a form field would give it.
-- Anything else (`undefined`, `NaN`, `Infinity`, `""`, an object) means the default, 0.5.
-- `update({ intensity: undefined })` puts the figure back to 0.5. A key absent from `update` leaves that option as it was. The base spec's rule for `theme`, `label` and `onRead` is unchanged.
-
-### Riffle
-
-- `bands` and `labels` are removed.
-- The caption is the card's number only: `"03"` for the third card, `"rest"` at rest.
-- The live region names the pulled card by its number only.
-- The engine no longer draws the hit bands. The band geometry that decides which card is pulled stays as it is: selection does not change.
-
-### Removed from the public API
-
-- The options `stagger`, `radius`, `gap`, `afterglow`, `rate`, `coast`, `bands` and `labels`.
-- The exports `ranges` and `Range`.
-- The types `BaseOptions`, `Theme`, `RiffleOptions`, `TerrainOptions`, `ExplodedOptions`, `PhosphorOptions`, `SlowOptions` and `TurntableOptions`.
-- From the React entry: `FigureProps`, `FigureComponent`, and the six `*Props` types.
-
-### React entry
-
-```tsx
-import { Riffle } from "@lucasmarkes/hairline/react";
-
-<Riffle />
-<Riffle intensity={0.8} onRead={setText} />
-```
-
-Every component takes `HairlineProps`: `HairlineOptions` plus every `<div>` attribute except `children`. `ref` reaches the `<div>`. The React entry exports the six components and the type `HairlineProps`.
-
-The figure fills its parent's width at an aspect ratio of 5 / 4, so no example needs a width class. The site's snippets and the README drop `className="w-80"`.
-
-The rest of the base spec's React section stands: `"use client"`, the inline aspect ratio, the layout effect, StrictMode, the empty box under SSR.
-
-### What is public API
-
-Covered by semver: the six functions, the six components, the types `HairlineOptions`, `Figure` and `HairlineProps`, the six custom property names, and the `data-hairline` and `data-hairline-theme` attributes. The internal parameters behind `intensity`, and the class names inside the SVG, are not.
-
-## Testing
-
-What changes in the base spec's six layers.
-
-1. **Parity.**
- - The goldens stay as they are. They are not captured again.
- - The checkpoints before `set` already run at the default, which is now `intensity: 0.5`.
- - At `set`, the package side sets the `intensity` whose mapped value is the golden's value:
-
- | Figure | Golden value | `intensity` |
- | --- | --- | --- |
- | Riffle | 60 | 0.7 |
- | Terrain | 4 | 0.75 |
- | Exploded | 36 | 5/6 |
- | Phosphor | 900 | 0.5 + 190/980 |
- | Slow | 0.4 | 0.25 |
- | Turntable | 1000 | 0.5 + 175/850 |
-
- `scripts.mjs` keeps the golden's raw value next to each intensity.
- - A unit test asserts that `parameter(figure, intensity)` returns that raw value exactly, for all six.
- - The comparison removes the golden's `<g class="bands">…</g>` group before comparing, the way it already normalises ids. The package no longer draws it.
-2. **Maths.** Unchanged, plus `src/intensity.ts`:
- - For each figure, 0, 0.5 and 1 give the table's three values.
- - The map is monotonic. It rises for five figures and falls for Slow.
- - Clamping, numeric strings, and the default for anything else, with the cases the old `ranges` test had.
-3. **Lifecycle.**
- - The old option tests become `intensity` tests: bad values fall back to 0.5, and `update({ intensity: undefined })` resets.
- - The `bands` and `labels` tests are removed.
- - A new test: Riffle's caption and live region carry only the number.
- - A new test, per figure: `intensity: 0` and `intensity: 1` produce different markup from the default after the same pointer move. This pins that the prop reaches every engine.
-4. **Browser.** Unchanged.
-5. **Types.**
- - `riffle(el, { intensity: 0.8 })` and `<Riffle intensity={0.8} />` compile.
- - `{ stagger: 60 }`, `{ bands: true }`, `{ labels: [] }` and `{ radius: 3 }` are compile errors, on every figure and every component.
- - `HairlineOptions`, `Figure` and `HairlineProps` are exported. `ranges` and the old types are not.
-6. **Real consumers.** The fixtures use `intensity` where they used an option. The rest is unchanged.
-
-## The site
-
-It replaces the base spec's "The site" section. The stack is unchanged: Next.js App Router, statically prerendered, Tailwind, Geist and Geist Mono, the package imported through its public entries, and Shiki at build with a live span the client swaps.
-
-The look follows cuelume: a light ground, generous white space, one centred column, a serif italic accent word in the headline, and mono for code. The figures keep their own palette. No tile carries a "Fig. N" label or a caption corner.
-
-One page, top to bottom:
-
-1. **Top bar.** `hairline` on the left. On the right: the version from the package's `package.json`, a GitHub icon link, and an `llms.txt` button that copies the file's URL.
-2. **Hero, install first.**
- - The headline "Line drawings that *answer* the pointer.", with *answer* in an italic serif.
- - One sentence: "Six isometric figures for the web. SVG, no dependencies, React or plain DOM."
- - The install pill, `$ npm i @lucasmarkes/hairline`. Clicking the manager name cycles npm, pnpm, yarn, bun and shadcn. A copy button copies the current command.
- - Two buttons: "Get started", which scrolls to the quickstart, and "GitHub".
-3. **Live panel.** It replaces the 3 × 2 grid.
- - A large figure on the left.
- - An inspector on the right: six chips naming the figures (one is selected), the `intensity` slider from 0 to 1 in steps of 0.05, and a theme switch for Auto, Light and Dark.
- - Under both, the snippet for the current state, which follows the controls. It shows only the props that differ from the default: `<Terrain />` at rest, `<Terrain intensity={0.8} theme="dark" />` after changes. It has a copy button.
-4. **"One prop, six figures."** One row per figure: its name in italic, one sentence on what `intensity` does to it (from the table above), and a small live figure on the right. No props tables, no "Fig. N".
-5. **Four cards.**
- - *Tiny*: the gzip size of the vanilla entry with all six figures, measured at build with Node's `zlib` from `packages/hairline/dist/index.js`, and rounded to a tenth of a kB.
- - *No dependencies*.
- - *Accessible*: keyboard, screen reader and reduced motion.
- - *Themeable*: six CSS variables.
-6. **Quickstart, "Two steps".**
- - Step 1: install, the same pill as the hero.
- - Step 2: paste, with tabs React, Vanilla, CDN and CSS. CSS shows the six custom properties and the note about `--hairline-plate`.
- - One options table with four rows: `intensity`, `theme`, `label`, `onRead`.
-7. **Footer.** "MIT licensed. Built by Lucas Marques. After Linear's figures." Links: npm, GitHub, `llms.txt`, and the essay at `lucasmarkes.com/lab/hairline`.
-
-Removed from the base spec's page: the six per-figure sections with their props tables, the full theme editor (its job goes to the inspector's theme switch and the CSS tab), the Frameworks section (the CDN tab covers plain HTML), and the Notes section (the Accessible card carries the facts).
-
-Also served, as in the base spec:
-
-- `/llms.txt`, generated at build from `src/intensity.ts`'s table and the page's copy. It describes the four options and what `intensity` does to each figure.
-- `/r/hairline.json`, the registry item.
-- The Open Graph image, captured by `scripts/og.mjs` from a dedicated route, redrawn in the new style: the headline and one large figure.
-- Vercel Analytics.
-
-The site's tests:
-
-- The quickstart's options table matches `HairlineOptions`'s four keys.
-- `/llms.txt` names each figure with its row from the intensity table.
-- The browser test checks that the inspector's slider and chips change the live figure and the snippet, and that copy works on every install manager.
-
-## The shadcn registry item
-
-Unchanged, except that the six re-exported components take `HairlineProps`. The item's file builds in `fixtures/next-app` with `<Riffle intensity={0.8} />`.
-
-## Changelog
-
-The 0.1.0 entry in the base plan's Task 15 describes this API: one `intensity` option for all six figures, no per-figure options, and no `ranges` export.
-
-## Where the work happens
-
-On the branch `site-on-vercel` (PR #1), before it merges. The PR's preview is what Lucas reviews again, which is the gate for phase 4. Tasks 15 and 16 of the base plan follow unchanged, except for the changelog text above.
diff --git a/docs/superpowers/specs/2026-10-01-hairline-package-design.md b/docs/superpowers/specs/2026-10-01-hairline-package-design.md
deleted file mode 100644
index 5356033..0000000
--- a/docs/superpowers/specs/2026-10-01-hairline-package-design.md
+++ /dev/null
@@ -1,335 +0,0 @@
-# hairline — design
-
-Six isometric line figures that answer the pointer, as an npm package. Drop-in for React and for anything with a DOM.
-
-The figures already exist: they are the essay at `lucasmarkes.com/lab/hairline`. People who saw them asked to use them. This project takes them out of the website and ships them as `@lucasmarkes/hairline`, with a site of their own at `hairline.lucasmarkes.com`.
-
-## Goal and success
-
-Someone who saw the tweet installs a figure in their own project with one command and one line of code, and it looks and moves exactly as it did in the video.
-
-Done means:
-
-- `@lucasmarkes/[email protected]` is on npm with provenance.
-- `hairline.lucasmarkes.com` is live, with every figure running and documented.
-- A clean Next.js project and a clean Vite project install the package and draw a figure with no configuration.
-- `lucasmarkes.com/lab/hairline` is unchanged.
-
-## Locked decisions
-
-Do not reopen without asking.
-
-| Decision | Choice |
-| --- | --- |
-| Name | `@lucasmarkes/hairline`. One package, two entries: `.` (vanilla) and `./react`. |
-| Scope of v1 | The six figures, ready to use: Riffle, Terrain, Exploded, Phosphor, Slow, Turntable. The maths and the loop stay private. |
-| What a figure draws | Only the drawing. No frame, no corner text, no slider. |
-| Construction | Port and wrap. The engines move as they are; the public API is a thin layer over them. Parity with the website is tested. |
-| Module format | ESM only. |
-| Repository | New, `lucasmarkes/hairline`. pnpm workspaces and Turborepo, as in motes. |
-| Site | One page, showcase and docs together. Next.js App Router, prerendered. |
-| Distribution | npm, plus one shadcn registry item served by the site. |
-| Website | `lucasmarkes.com/lab/hairline` keeps its own copy of the code. It does not migrate. |
-| Licence | MIT. |
-| Language | TypeScript, strict. English in code, docs and site. |
-
-### Out of scope for v1
-
-- A public kit for drawing your own figures (camera, prisms, springs, loop).
-- The rest pose rendered on the server.
-- CommonJS output.
-- Web Components.
-- Wrappers for Vue, Svelte or Astro. The site shows how to use the vanilla entry in each.
-- A linter or formatter, and Changesets.
-- A Claude skill.
-
-## Source
-
-The code to port is in the website repository, on `main` at `edfebe9`:
-
-| Website path | What it is |
-| --- | --- |
-| `lib/hairline/iso.ts` | Projection and path maths. No DOM. |
-| `lib/hairline/motion.ts` | Springs, tweens, the reduced-motion flag. |
-| `lib/hairline/riffle-geometry.ts`, `turntable-geometry.ts` | Geometry two figures share with their tests. |
-| `lib/hairline/figures.ts` | Labels, hints, slider ranges and defaults. |
-| `components/hairline/stage.ts` | SVG helpers, the shared frame loop, the pointer, tear-down. |
-| `components/hairline/figures/*.ts` | The six engines. Each exports `mount(els, value) → { set, destroy }`. |
-| `components/hairline-figure.tsx` | The React frame. Not ported: it is the website's chrome. |
-| `app/globals.css`, the `.hairline` block | The drawing's styles. |
-| `tests/hairline.spec.ts`, `tests/hairline-geometry.spec.ts` | Existing tests, to port. |
-
-About 1,650 lines, with no dependencies.
-
-## Repository layout
-
-```
-packages/hairline/ @lucasmarkes/hairline
- src/
- core/ iso.ts, motion.ts, stage.ts, styles.ts
- figures/ riffle.ts, terrain.ts, exploded.ts, phosphor.ts, slow.ts, turntable.ts
- mount.ts the public wrapper around an engine
- ranges.ts option ranges and defaults
- index.ts entry "."
- react.tsx entry "./react"
- test/
- parity/ golden SVGs, the pointer scripts, the virtual clock
-apps/site/ hairline.lucasmarkes.com
-registry/ src/hairline.tsx, build.mjs
-fixtures/ next-app/, vite-vanilla/
-scripts/ release.mjs, capture-golden.mjs, base-url.mjs, og.mjs
-.github/workflows/ ci.yml, publish.yml
-```
-
-## The package
-
-### Vanilla entry
-
-```ts
-import { riffle } from "@lucasmarkes/hairline";
-
-const fig = riffle(el, { stagger: 40, onRead: (text) => {} });
-fig.update({ stagger: 60 });
-fig.destroy();
-```
-
-One function per figure: `riffle`, `terrain`, `exploded`, `phosphor`, `slow`, `turntable`. A project that uses one figure does not bundle the other five, and each function accepts only its own options.
-
-```ts
-type Figure<O> = {
- update(options: Partial<O>): void;
- destroy(): void;
-};
-
-type BaseOptions = {
- /** "auto" follows the page. Default "auto". */
- theme?: "auto" | "light" | "dark";
- /** The accessible name. Each figure has a default description in English. */
- label?: string;
- /** The figure's caption, each time it changes. Called once at mount with the rest caption. */
- onRead?: (text: string) => void;
-};
-```
-
-| Function | Options | Range | Default |
-| --- | --- | --- | --- |
-| `riffle` | `stagger` (ms) | 0–90 | 40 |
-| | `bands` (show the hit bands) | boolean | `false` |
-| | `labels` (names for the eight cards) | up to 8 strings | none |
-| `terrain` | `radius` (cells) | 1.5–5 | 3 |
-| `exploded` | `gap` (viewBox units) | 12–40 | 28 |
-| `phosphor` | `afterglow` (ms) | 150–1500 | 520 |
-| `slow` | `rate` (× of normal speed) | 0.05–0.6 | 0.2 |
-| `turntable` | `coast` (ms) | 200–1500 | 650 |
-
-A number outside its range is clamped. Every option has JSDoc with its unit, range and default.
-
-The entry also exports `ranges`: a typed constant with `min`, `max`, `step`, `default` and `unit` for every numeric option. A consumer builds a slider from it; the site builds its controls and its props tables from it.
-
-The captions are the website's read-outs, unchanged (`"cell 3·4"`, `"az 045° · el 30°"`). Riffle reports `"03"` for the third card, or `"03 · Dock"` when `labels` is given.
-
-### What a mount does to the element
-
-`el` is any empty `HTMLElement`. The mount:
-
-1. Destroys a figure already mounted on `el`, if there is one.
-2. Injects the stylesheet into `el`'s root (the document or a shadow root), once per root.
-3. Sets `data-hairline="<figure>"` and, when `theme` is not `"auto"`, `data-hairline-theme`.
-4. Sets `role="img"` and `aria-label`. Riffle gets `role="group"` and `tabindex="0"` instead, because it works from the keyboard. An attribute already on the element is never overwritten.
-5. Appends `<svg viewBox="0 0 400 320" aria-hidden="true">` and runs the engine on it.
-6. For Riffle, appends a visually hidden `aria-live="polite"` element that names the pulled card.
-
-`destroy` removes what the mount added and nothing else. It can be called more than once. Importing the package on a server touches no global; calling a figure function without a DOM throws an error that says so.
-
-### React entry
-
-```tsx
-import { Riffle } from "@lucasmarkes/hairline/react";
-
-<Riffle stagger={40} onRead={setText} className="w-80" />
-```
-
-Six components: `Riffle`, `Terrain`, `Exploded`, `Phosphor`, `Slow`, `Turntable`. Props are the figure's options plus every `<div>` attribute except `children`. `ref` reaches the `<div>`.
-
-- The built file starts with `"use client"`, so a Server Component can render a figure directly.
-- The `<div>` carries `aspect-ratio: 5 / 4` inline, so the box has its size before the stylesheet exists and the page does not shift.
-- The engine mounts in a layout effect and is destroyed on unmount. A changed option reaches it as `update`. StrictMode's double mount is safe.
-- On the server the box is empty. The drawing appears when the component mounts.
-
-### Styles and theme
-
-No CSS import. The stylesheet is about 1 KB and is injected on the first mount through `adoptedStyleSheets`, which a strict Content Security Policy allows and which works inside a shadow root. Where `adoptedStyleSheets` is missing, a `<style>` element is appended instead.
-
-Every selector is wrapped in `:where()`, so the package's rules have zero specificity and any consumer rule wins.
-
-The root is `display: block; position: relative; aspect-ratio: 5 / 4; touch-action: pan-y; user-select: none`. It takes its parent's width. Strokes do not scale: a figure has the same line weight at any size.
-
-Six custom properties are the theme:
-
-| Property | Role | Light | Dark |
-| --- | --- | --- | --- |
-| `--hairline-plate` | Fill of every solid. It hides the lines behind it. | `#ffffff` | `#08090a` |
-| `--hairline-hi` | The lit stroke. | `#232327` | `#d0d6e0` |
-| `--hairline-edge` | Silhouettes. | `#a4a4ac` | `#5b5d64` |
-| `--hairline-mid` | Default stroke. | `#c3c3c9` | `#3e3e44` |
-| `--hairline-lo` | Creases. | `#e0e0e4` | `#29292d` |
-| `--hairline-stroke` | Stroke width, in px. | `0.9` | `0.9` |
-
-Which palette applies, first match wins:
-
-1. `theme: "light"` or `"dark"`.
-2. An ancestor with class `dark` or `data-theme="dark"`.
-3. The page's `color-scheme`, through `light-dark()`.
-4. Light.
-
-`prefers-color-scheme` is not read directly: a site with only a light theme must not get a dark figure because the visitor's system is dark. A browser without `light-dark()` skips step 3.
-
-The root has no background. Solids are filled with `--hairline-plate`, so on a surface of another colour they read as paper shapes. Setting `--hairline-plate` to the surface colour blends them in; the docs say so at the top of the theme section.
-
-### Behaviour kept from the website
-
-- One frame loop for every figure on the page. It stops when all of them have settled.
-- A figure outside the viewport sleeps.
-- `prefers-reduced-motion` is honoured: tweens land at once.
-- Touch: a sideways drag reaches the figure; a vertical one scrolls the page. A lifted finger holds the pose for 1.4 s.
-
-### Build
-
-- tsup, two builds. The React build marks `react` and `@lucasmarkes/hairline` as external and imports the core by the package's own name, so both entries share one copy of the frame loop.
-- ESM only, `target: es2020`, declarations, source maps.
-- `"sideEffects": false`. Styles are injected at mount, not at import.
-- No dependencies. `react >=18` is an optional peer dependency.
-
-```json
-"exports": {
- ".": { "types": "./dist/index.d.ts", "default": "./dist/index.js" },
- "./react": { "types": "./dist/react.d.ts", "default": "./dist/react.js" },
- "./package.json": "./package.json"
-}
-```
-
-### What is public API
-
-Covered by semver: the exports of the two entries, the six custom property names, and the `data-hairline` and `data-hairline-theme` attributes. The class names inside the SVG are not.
-
-## Testing
-
-Six layers.
-
-1. **Parity with the website.** `scripts/capture-golden.mjs` opens a production build of the website's `/lab/hairline` under a virtual clock, runs a fixed pointer script on each figure, and writes the SVG markup and the caption at fixed checkpoints to `packages/hairline/test/parity/golden/<figure>.json`. Each script covers the rest pose, a hover, a leave, and a changed option. The package's Playwright test runs the same scripts on the package and must produce the same markup, with gradient and mask ids normalised. The goldens are committed. After 0.1.0 they are regression snapshots; the script is run again only to re-baseline on purpose.
-2. **Maths** (Vitest, node). The five tests of `hairline-geometry.spec.ts`, ported.
-3. **Lifecycle** (Vitest, jsdom, with `IntersectionObserver` and `matchMedia` stubbed). Mount then destroy leaves no node, listener or attribute. A second mount replaces the first. StrictMode. `renderToString` in node. The stylesheet is injected once per root. Options clamp. Host attributes are not overwritten.
-4. **Behaviour in a browser** (Playwright). Turntable seats on a quarter turn after a flick. Riffle answers the arrow keys and announces the card. The palette follows each of the four theme rules. Reduced motion. No console output.
-5. **Types.** Type tests for both entries: `riffle(el, { radius: 3 })` is a compile error.
-6. **Real consumers.** The release gate packs the tarball and installs it in `fixtures/next-app` (App Router, the component rendered from a Server Component) and `fixtures/vite-vanilla`. Each is built and opened in a browser, and the test checks that the figure is drawn and the console is clean.
-
-### Package gates
-
-- `publint` and `@arethetypeswrong/cli`, with the ESM-only profile.
-- `size-limit`, one budget per entry and one for a single figure imported alone. Each budget is the size of the first green build plus 10%, written into `package.json` in phase 3.
-- Tarball inspection: only `dist`, `README.md`, `LICENSE` and `package.json`; no `workspace:` range; no dependencies; `react.js` starts with `"use client"`.
-
-### CI
-
-On every pull request and every push to `main`: install, build, typecheck, layers 1 to 5, and the static gates (`pnpm release --static`). Layer 6 runs in the release gate and on pull requests that touch `packages/`.
-
-## Release
-
-The motes flow.
-
-1. Bump the version, add the entry to `CHANGELOG.md`, commit, tag `v<version>`.
-2. The tag starts `publish.yml`, which waits for approval in the protected `release` environment.
-3. The workflow checks that the tag matches the manifest, runs the full gate, runs `pnpm pack`, and publishes the tarball with `npm publish --provenance --access public`.
-4. A version with a pre-release suffix (`0.1.0-rc.0`) is published under the `next` dist-tag. Any other goes to `latest`.
-5. The workflow creates the GitHub Release from the changelog entry.
-
-Authentication is an `NPM_TOKEN` secret scoped to the `release` environment.
-
-## The site
-
-`apps/site`, Next.js App Router, statically prerendered, Tailwind, Geist and Geist Mono. It imports the package from the workspace through its public entries only, so every deploy exercises Server Components and hydration against the real API.
-
-The look is the tweet videos': warm paper ground, white tiles with a soft shadow, mono captions in the corners.
-
-One page:
-
-1. **Hero.** The name, one sentence, the six figures live in a 3 × 2 grid, and the install command with tabs for pnpm, npm, yarn, bun and shadcn, each with a copy button.
-2. **One section per figure.** The live figure in a tile with its caption; a slider for its option, built from `ranges`; the code for React and for vanilla, which follows the slider; a copy button; the props table.
-3. **Theme.** The six properties with a live editor, and the note about `--hairline-plate`.
-4. **Frameworks.** Snippets for Next.js, Vue, Svelte, Astro, and plain HTML from a CDN.
-5. **Notes.** Accessibility, reduced motion, performance, and the empty box under SSR.
-6. **Footer.** GitHub, npm, the essay at `lucasmarkes.com/lab/hairline`, the credit to Linear's home page as the inspiration, MIT.
-
-Also served:
-
-- `/llms.txt`: the docs as plain text, generated at build from `ranges` and the same copy as the page.
-- `/r/hairline.json`: the registry item.
-- The Open Graph image, a screenshot of a dedicated route taken by `scripts/og.mjs` and committed.
-- Vercel Analytics.
-
-Code snippets are highlighted at build time. The live value is a marked span the client swaps, so no highlighter ships to the browser. A test asserts that the props tables match `ranges`.
-
-## The shadcn registry item
-
-```
-npx shadcn@latest add https://hairline.lucasmarkes.com/r/hairline.json
-```
-
-One item. It adds `@lucasmarkes/hairline` as a dependency and writes `components/ui/hairline.tsx`: the six components, re-exported with the theme mapped to shadcn's tokens.
-
-| Property | Token |
-| --- | --- |
-| `--hairline-plate` | `var(--background)` |
-| `--hairline-hi` | `var(--foreground)` |
-| `--hairline-edge` | `var(--muted-foreground)` |
-| `--hairline-mid` | `color-mix(in oklab, var(--muted-foreground) 55%, var(--background))` |
-| `--hairline-lo` | `var(--border)` |
-
-The mapping is checked by eye against shadcn's default light and dark themes in phase 5 and adjusted there if a stroke disappears.
-
-`registry/build.mjs` writes the JSON into `apps/site/public/r/` at build time. The item's URL comes from the environment (`HAIRLINE_REGISTRY_URL`, then Vercel's production host, then the deployment's own host, then localhost), as in motes, so a preview's item installs from that preview and no hostname is in the source.
-
-## Deploy
-
-- **GitHub.** `lucasmarkes/hairline`. Private from phase 0, so CI and Vercel previews work before launch. Made public in phase 6, before the first publish: provenance needs a public repository. The `release` environment, with Lucas as required reviewer, and its `NPM_TOKEN` are set up then.
-- **Vercel.** A new project `hairline` in the same team as motes, root directory `apps/site`, connected to the GitHub repository: a preview per pull request, production from `main`.
-- **Domain.** `vercel domains add hairline.lucasmarkes.com` on the project. `lucasmarkes.com` already uses Vercel's nameservers, so there is no DNS record to create.
-
-## Phases
-
-| # | Phase | Done when |
-| --- | --- | --- |
-| 0 | Repository, tooling, CI, private GitHub repository | `pnpm build`, `pnpm typecheck` and `pnpm test` pass on an empty package, locally and in CI |
-| 1 | Goldens captured; engines ported | Parity passes for all six figures |
-| 2 | Public API: vanilla entry, React entry, styles, theme, accessibility | Layers 2 to 5 pass |
-| 3 | Gates and consumer fixtures | `pnpm release --static` passes and layer 6 passes locally |
-| 4 | Site, Vercel project | Lucas has reviewed a Vercel preview |
-| 5 | Registry item, `llms.txt`, README with the hero clip, CONTRIBUTING, CHANGELOG, LICENSE | The registry JSON validates against shadcn's schema and the item's file builds in `fixtures/next-app` |
-| 6 | Launch | The checklist below is complete |
-
-### Launch checklist
-
-Each step marked **confirm** is public or hard to undo, and waits for Lucas.
-
-1. Make the repository public; set its description, topics and homepage. **confirm**
-2. Create the `release` environment. Lucas creates the npm token and stores it as `NPM_TOKEN`.
-3. Tag `v0.1.0-rc.0`. Approve. It publishes under `next`. **confirm**
-4. Verify the release candidate from outside the repository: install in a new Next.js project and a new Vite project; `shadcn add` from the preview URL; import from a CDN in a plain HTML file.
-5. Tag `v0.1.0`. Approve. It publishes under `latest`. **confirm**
-6. Add `hairline.lucasmarkes.com` to the Vercel project. **confirm**
-7. Verify production: the npm page shows provenance and renders the README; the site answers on the domain; the Open Graph card renders; `/llms.txt` and `/r/hairline.json` answer; `shadcn add` works from the production URL.
-
-### After 0.1.0
-
-Not part of this plan: npm trusted publishing in place of the token, the rest pose under SSR, the kit.
-
-## Risks
-
-| Risk | Guard |
-| --- | --- |
-| The port changes how a figure moves. | Parity tests against the website's own SVG, written before the first engine is moved. |
-| The two entries load two copies of the frame loop. | ESM only; the React entry imports the core by package name; the Next.js fixture mounts two figures and asserts one loop. |
-| A bundler strips `"use client"`. | The tarball gate reads the first line of `react.js`; the Next.js fixture renders from a Server Component. |
-| `light-dark()` or `adoptedStyleSheets` is missing. | Light is the fallback palette; a `<style>` element is the fallback injection. Both paths have a browser test. |
-| The parity capture is not deterministic. | A virtual clock, one Chrome channel, and coordinates rounded to two decimals by the engines themselves. |
-| The registry item points at localhost in production. | The build prints a warning when it falls back, as in motes; the launch checklist installs from the production URL. |
diff --git a/docs/superpowers/specs/2026-10-01-hairline-skill-page-design.md b/docs/superpowers/specs/2026-10-01-hairline-skill-page-design.md
deleted file mode 100644
index aa1038c..0000000
--- a/docs/superpowers/specs/2026-10-01-hairline-skill-page-design.md
+++ /dev/null
@@ -1,83 +0,0 @@
-# `/skill`: a page for `hairline-create`
-
-Date: 2026-10-01. Status: design approved in conversation, awaiting review of this document.
-
-## Purpose
-
-The `hairline-create` skill lets anyone with a coding agent draw a new Hairline figure. This page is where someone from outside decides whether to install it. It shows what the skill produces, then says how to install it, how it works and how to use it.
-
-Success is a visitor who moves a figure the skill drew, reads the one-line prompt that produced it, and copies the install command.
-
-This page replaces the `/docs` section on the skill that the skill's spec left for a later pull request.
-
-## Decisions made
-
-| Question | Decision |
-| --- | --- |
-| How an example appears | Live: the generated page in an `iframe`, beside its prompt. |
-| Which examples | Four prompts: a sales funnel, a rate limiter, git branches, weather over a city. The bookshelf is dropped. |
-| Which version of them | Generated again, each in a clean session, after the trial's fixes to the skill are in. Never retouched by hand. |
-| Where the work lands | Its own pull request, branched from `main` after the skill's pull request (#4) is merged. |
-| When it goes live | With the repository going public, so the install command works for whoever reads it. Lucas plans both for today. |
-
-## The examples
-
-- **Source.** Each example is the file the skill wrote, `hairline-<name>.html`, copied byte for byte into `apps/site/public/skill/`.
-- **Prompt.** The prompt shown is the one typed in the session, for example `/hairline-create a sales funnel`.
-- **Embedding.** One `iframe` per example, with `loading="lazy"` and a `title` that is the figure's `means`. Its height is reserved before it loads and then fitted to the generated page, so the frame never scrolls inside and the page does not jump.
-- **Theme.** The site is light only (`color-scheme: light`), and a generated page follows the system. Each frame is loaded with `?theme=light`, a parameter the bench gains in pull request #4, so a visitor on a dark system does not get four dark plates on a white page. The generated page keeps its own switch inside the frame.
-- **Honesty.** A figure drawn by hand, or rebuilt on the package, would not be what the prompt produced. Mounting the figure in React with the kernel was rejected for the same reason, and because it would tie the site to the kernel.
-
-## The page
-
-Route `/skill`, in the site's existing layout, with the top bar and footer every page has. From top to bottom:
-
-1. **Opening.** One sentence saying what the skill does, and the install command, `npx skills add lucasmarkes/hairline`, with a copy button.
-2. **Examples.** Four rows. Each has the prompt on the left, in a code block with a copy button, and the live figure on the right. Under the prompt, a link that opens the generated page on its own. The figure's `means` line is already inside the frame, so it is not repeated. On a narrow screen the prompt sits above the figure.
-3. **How it works.** The skill's five steps, one line each: concepts, build, check, hand over, adjust. Then one sentence on what reaches the person's machine: the skill folder and nothing else, with no `npm install`. Node is needed only for the checks.
-4. **How to use it.** The command `/hairline-create <idea>`; what comes out (one self-contained HTML file); how to ask for changes; the agents it runs on (any agent that reads skills: Claude Code, Cursor, Codex and others).
-5. **Links.** To `/docs` and to the skill's folder on GitHub.
-
-The examples come before the explanation because they are what convinces.
-
-All copy is in English and follows the site's voice: short, plain, no exclamation.
-
-## Files
-
-| File | Role |
-| --- | --- |
-| `apps/site/app/skill/page.tsx` | The page. Uses the existing `code-block`, `copy` and `install` components. |
-| `apps/site/lib/skill.ts` | The four examples, `prompt` and `file`, and the page's copy as plain text. `name` and `means` are read from each generated page at build, so they cannot drift from it. |
-| `apps/site/components/example-frame.tsx` | The frame that fits its height to the generated page. |
-| `apps/site/public/skill/hairline-<name>.html` | The four generated pages, unaltered. |
-| `apps/site/components/chrome.tsx` | A `Skill` link in the top bar, after `Docs`. |
-| `apps/site/lib/llms.ts` | An entry for `/skill` in `llms.txt`. |
-
-Nothing in `packages/hairline/src` changes, and nothing in `skills/hairline-create/` changes in this pull request. The bench's `theme` parameter arrives with pull request #4.
-
-## Tests
-
-- **The showcase is honest (vitest).** Every file in `public/skill/` passes `skills/hairline-create/validate.mjs`. Every entry in `lib/skill.ts` points to a file that exists, and every file there has an entry. So a hand-edited example, or a kernel that moved on without the examples being generated again, fails CI.
-- **Light on a dark system.** With the system set to dark, each frame's page is still light.
-- **No scroll inside a frame.** At 1200px and at 320px, each frame is as tall as the page inside it.
-- **Browser (Playwright).** The page opens with a clean console. The copy buttons put the install command and a prompt on the clipboard. The four frames load, and a figure answers the pointer: its read-out leaves `rest`. There is no horizontal scroll at 320px. The top bar's `Skill` link reaches the page.
-- **`llms.txt`.** It lists `/skill`.
-
-## Out of scope
-
-- Changes to the skill itself. The trial's fixes belong to pull request #4.
-- A gallery of figures made by other people.
-- Running the skill in the browser.
-- A theme switch for the site.
-
-## Dependencies and order
-
-1. Pull request #4 closes: the bookshelf folder is deleted from the trial, the trial's fixes go in, the four prompts are run again in clean sessions, and Lucas sees the results. Its merge needs Lucas's yes.
-2. This pull request branches from `main` after that merge, because its tests run the skill's validator.
-3. Making the repository public and publishing to npm are Lucas's steps, each confirmed by them. This page goes to production with the first.
-
-## Risks
-
-- **A regenerated example comes out weak.** The page shows what the skill makes, so a weak figure is a finding about the skill, fixed in the skill and run again. If a prompt stays weak after that, it is dropped from the list rather than retouched.
-- **Four frames weigh on the page.** Each generated page is about 34 KB and self-contained, and frames below the fold load lazily. The plan measures the page before and after.
-- **The kernel changes later.** The examples then fail the showcase test until they are generated again. That is the intended signal.