Skip to content

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

API: the React entry, a client module that shares the core's frame loop

Lucas Marquesee03b6ba9ea3
diff --git a/packages/hairline/src/react.tsx b/packages/hairline/src/react.tsx
new file mode 100644
index 0000000..62df854
--- /dev/null
+++ b/packages/hairline/src/react.tsx
@@ -0,0 +1,93 @@
+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>;
diff --git a/packages/hairline/test/react.test.tsx b/packages/hairline/test/react.test.tsx
new file mode 100644
index 0000000..87cf695
--- /dev/null
+++ b/packages/hairline/test/react.test.tsx
@@ -0,0 +1,109 @@
+// @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"]);
+ });
+});
diff --git a/packages/hairline/test/ssr.test.tsx b/packages/hairline/test/ssr.test.tsx
new file mode 100644
index 0000000..92e722c
--- /dev/null
+++ b/packages/hairline/test/ssr.test.tsx
@@ -0,0 +1,24 @@
+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/);
+ });
+});
diff --git a/packages/hairline/test/types.test-d.tsx b/packages/hairline/test/types.test-d.tsx
new file mode 100644
index 0000000..c0a0269
--- /dev/null
+++ b/packages/hairline/test/types.test-d.tsx
@@ -0,0 +1,56 @@
+/**
+ * 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;
diff --git a/packages/hairline/tsup.config.ts b/packages/hairline/tsup.config.ts
index 17c9be2..80bfba2 100644
--- a/packages/hairline/tsup.config.ts
+++ b/packages/hairline/tsup.config.ts
@@ -1,3 +1,21 @@
-import { defineConfig } from "tsup";
+import { defineConfig, type Options } from "tsup";
-export default defineConfig([{ format: ["esm"], target: "es2020", dts: true, sourcemap: true, entry: ["src/index.ts"] }]);
+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";' } },
+]);