Isometric line figures that answer the pointer. For React and for anything with a DOM.
API: every figure takes HairlineOptions, with one intensity in place of six options
Lucas Marquesa61d2bd330f8
diff --git a/packages/hairline/src/index.ts b/packages/hairline/src/index.tsindex b8ec36f..9f5fd32 100644--- a/packages/hairline/src/index.ts+++ b/packages/hairline/src/index.ts@@ -1,5 +1,4 @@-import { create, type BaseOptions, type Figure } from "./mount";-import { ranges } from "./ranges";+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";@@ -10,121 +9,70 @@ 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+ * 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 { ranges, type Range } from "./ranges";-export type { BaseOptions, Figure, Theme } from "./mount";+export type { Figure, HairlineOptions } 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> {+/** 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",- 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> {+/** 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",- 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> {+/** 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: "",- 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> {+/** 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",- 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> {+/** 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×",- 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> {+/** 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°",- key: "coast",- range: ranges.turntable.coast,engine: turntableEngine,}, el, options);}diff --git a/packages/hairline/src/mount.ts b/packages/hairline/src/mount.tsindex dec88ee..9446c3e 100644--- a/packages/hairline/src/mount.ts+++ b/packages/hairline/src/mount.ts@@ -1,6 +1,6 @@import { inject } from "./core/styles";-import type { FigureEls, FigureHandle, Readout } from "./core/stage";-import { number, type Range } from "./ranges";+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@@ -11,39 +11,35 @@ import { number, type Range } from "./ranges";* attributes the host did not already have.*/-export type Theme = "auto" | "light" | "dark";--export type BaseOptions = {+/** 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?: Theme;+ 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<O> = {- /** Changes options on the running figure. A key set to `undefined` goes back to its default. */- update(options: Partial<O>): 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, the one number it takes, and what it says about itself. */-export type Spec<O extends BaseOptions, H extends FigureHandle> = {- id: string;+/** 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;- /** The numeric option, and its range. */- key: keyof O & string;- range: Range;- engine: (els: FigureEls, value: number) => H;+ engine: FigureMount;/** 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";@@ -55,7 +51,7 @@ const report = (err: unknown) => {else setTimeout(() => { throw err; });};-export function create<O extends BaseOptions, H extends FigureHandle>(spec: Spec<O, H>, el: HTMLElement, options?: O): Figure<O> {+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.`);}@@ -64,7 +60,7 @@ export function create<O extends BaseOptions, H extends FigureHandle>(spec: Spec}mounted.get(el)?.();- const opts = { ...options } as O;+ const opts: HairlineOptions = { ...options };const doc = el.ownerDocument;const root = el.getRootNode();inject(root.nodeType === 9 || "host" in root ? (root as Document | ShadowRoot) : doc);@@ -111,9 +107,8 @@ export function create<O extends BaseOptions, H extends FigureHandle>(spec: Spec},};- let value = number(opts[spec.key], spec.range);+ let value = parameter(spec.id, opts.intensity);const engine = spec.engine({ stage: el, svg, read }, value);- spec.apply?.(engine, opts);if (text === null) read.textContent = spec.rest;let dead = false;@@ -132,14 +127,15 @@ export function create<O extends BaseOptions, H extends FigureHandle>(spec: Specreturn {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];+ /* 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 = number(opts[spec.key], spec.range);+ const v = parameter(spec.id, opts.intensity);if (v !== value) { value = v; engine.set(v); }dress();- spec.apply?.(engine, opts);},destroy,};diff --git a/packages/hairline/src/ranges.ts b/packages/hairline/src/ranges.tsdeleted file mode 100644index a06769b..0000000--- a/packages/hairline/src/ranges.ts+++ /dev/null@@ -1,29 +0,0 @@-/** 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));-}diff --git a/packages/hairline/src/react.tsx b/packages/hairline/src/react.tsxindex 62df854..1c4cc89 100644--- a/packages/hairline/src/react.tsx+++ b/packages/hairline/src/react.tsx@@ -2,11 +2,7 @@ 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";+import { exploded, phosphor, riffle, slow, terrain, turntable, type Figure, type HairlineOptions } from "./index";/*** @lucasmarkes/hairline/react — the six figures as components.@@ -17,77 +13,55 @@ import {* 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>;+/** 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<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];+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 */- if (options.label === undefined) options.label = props["aria-label"];+ const named = 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 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(() => { onRead.current = props.onRead as BaseOptions["onRead"]; });+ useIsoLayoutEffect(() => { read.current = onRead; });useIsoLayoutEffect(() => {- const f = mount(el.current!, { ...options, onRead: (text: string) => onRead.current?.(text) } as O);+ 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}, []);- /* 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+ /* 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]);- 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>;+ return Component;}-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>;+/** 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);diff --git a/packages/hairline/test/browser/figures.spec.ts b/packages/hairline/test/browser/figures.spec.tsindex 5c44be9..621c986 100644--- 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");diff --git a/packages/hairline/test/browser/parity.spec.ts b/packages/hairline/test/browser/parity.spec.tsindex 03b85de..8c449a3 100644--- a/packages/hairline/test/browser/parity.spec.ts+++ b/packages/hairline/test/browser/parity.spec.ts@@ -1,7 +1,7 @@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";+import { FIGURES, INTENSITY, SCRIPTS } from "../parity/scripts.mjs";/*** The package draws what the site draws. Each golden is the site's svg at@@ -11,18 +11,24 @@ import { FIGURES, OPTION, SCRIPTS } from "../parity/scripts.mjs";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"];+/*+ * 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 [key, value] = (OPTION as unknown as Record<string, [string, number]>)[id];+ const intensity = (INTENSITY as Record<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);+ 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 */@@ -31,13 +37,13 @@ for (const id of FIGURES as string[]) {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),+ 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(want.read);- expect(got[i].svg, `drawing at "${want.at}"`).toBe(want.svg);+ 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));}});}diff --git a/packages/hairline/test/mount.test.ts b/packages/hairline/test/mount.test.tsindex b594e17..b16b15b 100644--- a/packages/hairline/test/mount.test.ts+++ b/packages/hairline/test/mount.test.ts@@ -111,29 +111,61 @@ describe("options", () => {});// 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) => {+ 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 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 });+ 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();}});+});- 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("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]));});});@@ -153,33 +185,23 @@ describe("the caption", () => {expect(onRead.mock.calls).toEqual([["rate 1.00×"]]);});- it("reads a pulled card out by number, and by name when it has one", () => {+ it("reads a pulled card out by its number alone, in the caption and the live region", () => {const el = host(), onRead = vi.fn();- const f = riffle(el, { onRead });+ /* 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", "Drum"] });- expect(onRead).toHaveBeenLastCalledWith("01 · Radial menu");+ f.update({ labels: ["Radial menu"] } as never);key(el, "ArrowRight");- expect(onRead).toHaveBeenLastCalledWith("02 · Drum");- key(el, "ArrowRight");- expect(onRead).toHaveBeenLastCalledWith("03"); // fewer than eight names: the rest go by number+ 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");});- 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 loopit("reports an onRead that throws and keeps every figure running", () => {const reported = vi.fn();@@ -211,7 +233,7 @@ describe("teardown", () => {const el = host();const f = terrain(el);f.destroy();- f.update({ theme: "dark", label: "late", radius: 5 });+ f.update({ theme: "dark", label: "late", intensity: 1 });expect(el.outerHTML).toBe("<div></div>");});diff --git a/packages/hairline/test/ranges.test.ts b/packages/hairline/test/ranges.test.tsdeleted file mode 100644index 3014690..0000000--- a/packages/hairline/test/ranges.test.ts+++ /dev/null@@ -1,34 +0,0 @@-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);- }- }- });-});diff --git a/packages/hairline/test/react.test.tsx b/packages/hairline/test/react.test.tsxindex 87cf695..32b75d1 100644--- a/packages/hairline/test/react.test.tsx+++ b/packages/hairline/test/react.test.tsx@@ -2,12 +2,18 @@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 { 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", () => {@@ -19,7 +25,7 @@ describe("components", () => {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 { 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");@@ -27,9 +33,9 @@ describe("components", () => {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);+ for (const name of ["intensity", "theme", "label", "onread"]) expect(el.hasAttribute(name)).toBe(false);expect(el.getAttribute("data-hairline-theme")).toBe("dark");- expect(el.querySelector(".bands")!.classList.contains("show")).toBe(true);+ expect(el.getAttribute("aria-label")).toBe("Cards");});it("lets the style prop override the aspect ratio", () => {@@ -47,33 +53,42 @@ describe("components", () => {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 />);+ const el = container.firstElementChild!, drawing = el.querySelector("svg");+ rerender(<Riffle theme="light" />);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);+ expect(el.querySelector("svg")).toBe(drawing);});- // 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", () => {+ // 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} labels={["Radial menu", "Drum"]} onRead={(t) => seen.push(`${n}:${t}`)} />;+ return <Riffle data-n={n} onRead={(t) => seen.push(`${n}:${t}`)} />;}const { container, rerender } = render(<App n={1} />);- const el = container.firstElementChild!, svg = el.querySelector("svg");+ 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(svg);+ 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 · Radial menu"]);+ expect(seen).toEqual(["1:rest", "3:01"]);});it("calls a state setter from onRead without looping", () => {diff --git a/packages/hairline/test/ssr.test.tsx b/packages/hairline/test/ssr.test.tsxindex 92e722c..593e79c 100644--- 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>');});diff --git a/packages/hairline/test/types.test-d.tsx b/packages/hairline/test/types.test-d.tsxindex c0a0269..1108c89 100644--- a/packages/hairline/test/types.test-d.tsx+++ b/packages/hairline/test/types.test-d.tsx@@ -4,53 +4,77 @@* 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";+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>() => {};-/* 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 });+/* every figure takes the same options */+riffle(el, { intensity: 0.8, theme: "dark", label: "Cards", onRead: (t: string) => t });riffle(el);-// @ts-expect-error radius is Terrain's-riffle(el, { radius: 4 });-// @ts-expect-error stagger is Riffle's-terrain(el, { stagger: 60 });+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, { rate: "0.4" });+slow(el, { intensity: "0.8" });// @ts-expect-error not a themeexploded(el, { theme: "sepia" });// @ts-expect-error the element is requiredriffle();+yes<Equal<keyof HairlineOptions, "intensity" | "theme" | "label" | "onRead">>();/* the handle */const f = riffle(el);-yes<Equal<typeof f, Figure<RiffleOptions>>>();-f.update({ stagger: undefined, labels: ["a"] as const });+yes<Equal<typeof f, Figure>>();+f.update({ intensity: undefined, theme: "light" });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;+// @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} 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} />;+<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 radius="4" />;+<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: RiffleProps = { stagger: 60, className: "w-80" };+const props: HairlineProps = { intensity: 0.8, className: "w-80" };void props;