Skip to content

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

API: the vanilla entry, six functions over one mount, with styles injected per root

Lucas Marques8b0b35bcae8f
diff --git a/packages/hairline/src/core/styles.ts b/packages/hairline/src/core/styles.ts
new file mode 100644
index 0000000..8ff5aa9
--- /dev/null
+++ b/packages/hairline/src/core/styles.ts
@@ -0,0 +1,80 @@
+/**
+ * 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);
+}
diff --git a/packages/hairline/src/index.ts b/packages/hairline/src/index.ts
index cb0ff5c..b8ec36f 100644
--- a/packages/hairline/src/index.ts
+++ b/packages/hairline/src/index.ts
@@ -1 +1,130 @@
-export {};
+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);
+}
diff --git a/packages/hairline/src/mount.ts b/packages/hairline/src/mount.ts
new file mode 100644
index 0000000..dec88ee
--- /dev/null
+++ b/packages/hairline/src/mount.ts
@@ -0,0 +1,146 @@
+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,
+ };
+}
diff --git a/packages/hairline/test/dom.ts b/packages/hairline/test/dom.ts
new file mode 100644
index 0000000..44a4dff
--- /dev/null
+++ b/packages/hairline/test/dom.ts
@@ -0,0 +1,70 @@
+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;
+}
diff --git a/packages/hairline/test/mount.test.ts b/packages/hairline/test/mount.test.ts
new file mode 100644
index 0000000..b594e17
--- /dev/null
+++ b/packages/hairline/test/mount.test.ts
@@ -0,0 +1,251 @@
+// @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();
+ });
+});