Isometric line figures that answer the pointer. For React and for anything with a DOM.
Release gate: publint, attw, size budgets and the tarball; README and CONTRIBUTING
Lucas Marques5d4f0e95f03f
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 95e5ef7..13ee70e 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -45,3 +45,8 @@ jobs:- name: Browser testsrun: 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 --staticdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdnew file mode 100644index 0000000..596b18a--- /dev/null+++ b/CONTRIBUTING.md@@ -0,0 +1,65 @@+# 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.diff --git a/README.md b/README.mdindex f54f6e3..63585fe 100644--- a/README.md+++ b/README.md@@ -1,3 +1,120 @@# hairlineSix isometric line figures that answer the pointer. For React and for anything with a DOM.++[](https://www.npmjs.com/package/@lucasmarkes/hairline)+[](https://github.com/lucasmarkes/hairline/actions/workflows/ci.yml)+[](./LICENSE)++++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 Marquesdiff --git a/assets/hero.gif b/assets/hero.gifnew file mode 100644index 0000000..42fa848Binary files /dev/null and b/assets/hero.gif differdiff --git a/scripts/release.mjs b/scripts/release.mjsnew file mode 100644index 0000000..a8e5a55--- /dev/null+++ b/scripts/release.mjs@@ -0,0 +1,121 @@+#!/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`);