Isometric line figures that answer the pointer. For React and for anything with a DOM.
Core: tour(), an unseen pointer that walks a figure's stops through its own handlers and gives way to a hand
Lucas Marquesce5048ffec6a
diff --git a/packages/hairline/src/core/stage.ts b/packages/hairline/src/core/stage.tsindex 30f4f69..63d9bf2 100644--- a/packages/hairline/src/core/stage.ts+++ b/packages/hairline/src/core/stage.ts@@ -2,7 +2,7 @@ import {ghost, r2,type Camera, type PrismPaths, type Projector, type Sample, type Vec2,} from "./iso";-import { setReducedMotion } from "./motion";+import { EASE_LIFT, reducedMotion, setReducedMotion } from "./motion";/*** Hairline — the DOM side every figure shares: making svg nodes, the helpers@@ -186,6 +186,11 @@ export type PointerHandlers = {leave(e: PointerEvent): void;};+/** The handlers each stage's pointer() was given, so a tour can drive them. */+const handlers = new WeakMap<Element, PointerHandlers>();+/** The tour on each stage, told when a real pointer arrives and leaves. */+const touring = new WeakMap<Element, { hold(): void; release(): void }>();+/*** Pointer input in viewBox units. A mouse leaving acts at once; a finger* lifting holds the pose for 1.4s first, so a tap reads as a look rather than@@ -193,32 +198,131 @@ export type PointerHandlers = {* keeps sending moves. Returns the disposer.*/export function pointer(stage: HTMLElement, on: PointerHandlers): () => void {+ handlers.set(stage, on);let tm = 0;const pt = (e: PointerEvent): Vec2 => {const r = stage.getBoundingClientRect();return [((e.clientX - r.left) / r.width) * 400, ((e.clientY - r.top) / r.height) * 320];};- const move = (e: PointerEvent) => { clearTimeout(tm); on.move(pt(e), e); };+ /* a real pointer holds the stage's tour before the figure hears it, and frees it after the figure hears the leave */+ const move = (e: PointerEvent) => { clearTimeout(tm); touring.get(stage)?.hold(); on.move(pt(e), e); };const down = (e: PointerEvent) => {clearTimeout(tm);+ touring.get(stage)?.hold();if (e.pointerType !== "mouse") stage.releasePointerCapture?.(e.pointerId);if (on.down) on.down(pt(e), e); else on.move(pt(e), e);};const leave = (e: PointerEvent) => {clearTimeout(tm);- tm = window.setTimeout(() => on.leave(e), e.pointerType === "mouse" ? 0 : 1400);+ tm = window.setTimeout(() => { on.leave(e); touring.get(stage)?.release(); }, e.pointerType === "mouse" ? 0 : 1400);};stage.addEventListener("pointermove", move);stage.addEventListener("pointerdown", down);stage.addEventListener("pointerleave", leave);return () => {clearTimeout(tm);+ if (handlers.get(stage) === on) handlers.delete(stage);stage.removeEventListener("pointermove", move);stage.removeEventListener("pointerdown", down);stage.removeEventListener("pointerleave", leave);};}+/* ───── the tour: an unseen pointer that walks a figure's stops ───── */++/** Where an unseen pointer stops: a viewBox point, or null to leave the stage. */+export type Tour = ReadonlyArray<Vec2 | null>;+export type TourHandle = { stop(): void };+/** The default stops: a diamond around the centre, left, up, right, down, then a leave. */+export const LAP: Tour = [[128, 150], [200, 118], [272, 150], [200, 206], null];++const TRAVEL = 900, DWELL = 1200, REST = 1800, RESUME = 1200, STAGGER = 450;+const GHOST = { pointerType: "ghost" } as PointerEvent;+/** How many tours have started on the page: the stagger that keeps a page of them out of step. */+let started = 0;++/** Where a pointer heading for `p` first touches the viewBox: the ray from the centre through `p` meets the edge. */+function entry([x, y]: Vec2): Vec2 {+ const dx = x - 200, dy = y - 160;+ if (!dx && !dy) return [200, 320];+ const k = Math.min(dx ? (dx > 0 ? 200 : -200) / dx : Infinity, dy ? (dy > 0 ? 160 : -160) / dy : Infinity);+ return [200 + dx * k, 160 + dy * k];+}++/**+ * Walks `stops` on the figure under `stage`, calling the handlers its pointer()+ * was given as a hand would: in from the edge, TRAVEL to each stop on EASE_LIFT,+ * DWELL there, leave(GHOST) at a null stop and REST, then round again. A real+ * pointer or focus on the stage holds it; when they go it waits RESUME and+ * starts from the first stop. It is a board in the one loop: it sleeps offscreen+ * and leaves under reduced motion. onStop(i) is called on arriving at stop i,+ * or on leaving for a null stop i. A figure never calls this; the bench and the+ * package do.+ */+export function tour(stage: HTMLElement, stops: Tour, onStop?: (index: number) => void): TourHandle {+ let i = 0; // the stop the ghost is heading to+ let wait = RESUME + STAGGER * (started++ % 4); // ms before the next travel begins+ let t = -1; // ms into the travel; -1 before it begins+ let at: Vec2 | null = null; // where the ghost is; null when off the stage+ let origin: Vec2 = [200, 320]; // where the current travel began+ let hand = false, keys = stage.contains(stage.ownerDocument.activeElement);+ let gone = false;++ const leave = () => { at = null; t = -1; handlers.get(stage)?.leave(GHOST); };+ const tick: Tick = (dt) => {+ if (hand || keys || !stops.length) return false;+ if (reducedMotion()) { if (at) leave(); return false; }+ if (wait > 0) { wait -= dt * 1000; return true; }+ const stop = stops[i];+ if (stop === null) {+ if (at) leave();+ onStop?.(i);+ i = (i + 1) % stops.length;+ wait = REST;+ return true;+ }+ const h = handlers.get(stage);+ if (!h) return true; // the figure has not called pointer() yet, or has let it go+ if (t < 0) { origin = at ?? entry(stop); t = 0; }+ t = Math.min(TRAVEL, t + dt * 1000);+ const k = EASE_LIFT(t / TRAVEL);+ at = [origin[0] + (stop[0] - origin[0]) * k, origin[1] + (stop[1] - origin[1]) * k];+ h.move(at, GHOST);+ if (t < TRAVEL) return true;+ onStop?.(i);+ i = (i + 1) % stops.length;+ t = -1;+ wait = DWELL;+ return true;+ };++ /* a hand or the keyboard owns the handlers: the ghost drops where it was and says nothing until both are gone */+ const take = () => { at = null; t = -1; };+ const give = () => { if (hand || keys) return; i = 0; t = -1; wait = RESUME; board.wake(); };+ const me = {+ hold: () => { hand = true; take(); },+ release: () => { if (!hand) return; hand = false; give(); },+ };+ const focusIn = () => { keys = true; take(); };+ const focusOut = (e: FocusEvent) => { if (keys && !stage.contains(e.relatedTarget as Node | null)) { keys = false; give(); } };+ stage.addEventListener("focusin", focusIn);+ stage.addEventListener("focusout", focusOut);+ touring.set(stage, me);+ const board = register(stage, tick);++ return {+ stop: () => {+ if (gone) return;+ gone = true;+ board.unregister();+ stage.removeEventListener("focusin", focusIn);+ stage.removeEventListener("focusout", focusOut);+ if (touring.get(stage) === me) touring.delete(stage);+ if (at) leave();+ },+ };+}+/* ---------- tear-down ---------- */export type Disposer = {diff --git a/packages/hairline/test/stage.test.ts b/packages/hairline/test/stage.test.tsindex b92ab9f..a765962 100644--- a/packages/hairline/test/stage.test.ts+++ b/packages/hairline/test/stage.test.ts@@ -1,7 +1,9 @@// @vitest-environment jsdom-import { describe, expect, it, vi } from "vitest";+import { afterEach, describe, expect, it, vi } from "vitest";import { frames, host, observers, pending, seen } from "./dom";-import { register } from "../src/core/stage";+import { LAP, pointer, register, tour } from "../src/core/stage";+import { setReducedMotion } from "../src/core/motion";+import type { Vec2 } from "../src/core/iso";describe("register", () => {it("two boards on one stage both see it, and both sleep and wake with it", () => {@@ -41,3 +43,191 @@ describe("register", () => {keep.unregister();});});++type Call = { kind: "move" | "leave"; type: string; p?: Vec2 };+/** A figure's side of the seam: handlers that log every call, through pointer() as a figure's would. */+function stub(el: HTMLElement) {+ const log: Call[] = [];+ const off = pointer(el, {+ move: (p, e) => { log.push({ kind: "move", type: e.pointerType, p: [p[0], p[1]] }); },+ leave: (e) => { log.push({ kind: "leave", type: e.pointerType }); },+ });+ return { log, off };+}+/** Runs frames until `fn` holds, at most `cap` of them; returns whether it holds. */+const until = (fn: () => boolean, cap: number) => { for (let n = 0; n < cap && !fn(); n++) frames(); return fn(); };+const mouse = (el: Element, type: string, x = 50, y = 50) =>+ el.dispatchEvent(new PointerEvent(type, { pointerType: "mouse", pointerId: 1, bubbles: true, clientX: x, clientY: y }));+const tick = () => new Promise((done) => setTimeout(done, 5));++describe("tour", () => {+ afterEach(() => setReducedMotion(false));++ it("walks the stops: enters from the edge, arrives, leaves at null, and loops", () => {+ const el = host(), { log } = stub(el), stops: number[] = [];+ const h = tour(el, [[200, 100], null], (i) => stops.push(i));+ expect(until(() => log.length > 0, 200)).toBe(true);+ /* the ray from the centre through [200, 100] meets the top edge at [200, 0]: the first move is just inside it */+ expect(log[0].type).toBe("ghost");+ expect(log[0].p![0]).toBeCloseTo(200, 0);+ expect(log[0].p![1]).toBeLessThan(20);+ expect(until(() => stops.length === 1, 60)).toBe(true);+ expect(log.at(-1)!.p![0]).toBeCloseTo(200, 0);+ expect(log.at(-1)!.p![1]).toBeCloseTo(100, 0);+ expect(until(() => stops.length === 2, 80)).toBe(true);+ expect(log.at(-1)).toMatchObject({ kind: "leave", type: "ghost" });+ const n = log.length;+ expect(until(() => log.length > n, 120)).toBe(true);+ expect(log[n].p![1]).toBeLessThan(20);+ expect(stops).toEqual([0, 1]);+ h.stop();+ });++ it("a real pointer takes the handlers; after it leaves, the ghost waits and starts the lap again from the edge", async () => {+ const el = host(), { log } = stub(el), stops: number[] = [];+ const h = tour(el, [[200, 100], [300, 160], null], (i) => stops.push(i));+ expect(until(() => stops.length === 1, 240)).toBe(true);+ mouse(el, "pointermove");+ expect(log.at(-1)).toMatchObject({ kind: "move", type: "mouse", p: [50, 50] });+ const n = log.length;+ frames(200);+ expect(log.length).toBe(n);+ mouse(el, "pointerleave");+ await tick();+ expect(log.at(-1)).toMatchObject({ kind: "leave", type: "mouse" });+ frames(60);+ expect(log.length).toBe(n + 1);+ expect(until(() => log.length > n + 1, 30)).toBe(true);+ expect(log.at(-1)).toMatchObject({ kind: "move", type: "ghost" });+ expect(log.at(-1)!.p![1]).toBeLessThan(20);+ expect(until(() => stops.length === 2, 60)).toBe(true);+ expect(stops).toEqual([0, 0]);+ h.stop();+ });++ it("a leave with no pointer before it does not restart the lap", async () => {+ const el = host(), { log } = stub(el), stops: number[] = [];+ const h = tour(el, [[200, 100], null], (i) => stops.push(i));+ expect(until(() => log.length > 10, 200)).toBe(true);+ mouse(el, "pointerleave");+ await tick();+ const n = log.length;+ frames(1);+ expect(log.length).toBe(n + 1);+ expect(log.at(-1)!.type).toBe("ghost");+ h.stop();+ });++ it("focus inside the stage holds it, and a hand that leaves while the keyboard is inside does not free it", async () => {+ const el = host(), { log } = stub(el);+ const btn = document.createElement("button");+ el.append(btn);+ const h = tour(el, [[200, 100], null]);+ expect(until(() => log.length > 0, 200)).toBe(true);+ btn.focus();+ const n = log.length;+ frames(300);+ expect(log.length).toBe(n);+ mouse(el, "pointermove");+ mouse(el, "pointerleave");+ await tick();+ expect(log.slice(n).map((c) => c.type)).toEqual(["mouse", "mouse"]);+ const m = log.length;+ frames(300);+ expect(log.length).toBe(m);+ btn.blur();+ expect(until(() => log.length > m, 100)).toBe(true);+ expect(log.at(-1)).toMatchObject({ kind: "move", type: "ghost" });+ h.stop();+ });++ it("under reduced motion the ghost leaves and rests; woken when the preference clears, it goes on", () => {+ const el = host(), { log } = stub(el);+ const h = tour(el, [[200, 100], null]);+ expect(until(() => log.length > 3, 200)).toBe(true);+ setReducedMotion(true);+ frames(2);+ expect(log.at(-1)).toMatchObject({ kind: "leave", type: "ghost" });+ const n = log.length;+ frames(200);+ expect(log.length).toBe(n);+ setReducedMotion(false);+ seen(el, true); // what the media-query listener does on a change: every board wakes+ expect(until(() => log.length > n, 200)).toBe(true);+ expect(log.at(-1)!.type).toBe("ghost");+ h.stop();+ });++ it("offscreen it sleeps where it is, and goes on from there when seen", () => {+ const el = host(), { log } = stub(el);+ const h = tour(el, [[200, 100], null]);+ expect(until(() => log.length > 5, 200)).toBe(true);+ const last = log.at(-1)!.p!;+ seen(el, false);+ const n = log.length;+ frames(200);+ expect(log.length).toBe(n);+ seen(el, true);+ frames(1);+ expect(log.length).toBe(n + 1);+ expect(Math.hypot(log[n].p![0] - last[0], log[n].p![1] - last[1])).toBeLessThan(30);+ h.stop();+ });++ it("stop() leaves the stage and forgets the tour; a hand after it is just a hand", () => {+ const el = host(), { log } = stub(el);+ const h = tour(el, [[200, 100], null]);+ expect(until(() => log.length > 0, 200)).toBe(true);+ h.stop();+ expect(log.at(-1)).toMatchObject({ kind: "leave", type: "ghost" });+ const n = log.length;+ frames(300);+ expect(log.length).toBe(n);+ expect(pending()).toBe(0);+ mouse(el, "pointermove");+ h.stop();+ expect(log.at(-1)).toMatchObject({ kind: "move", type: "mouse" });+ });++ it("three stages start at three different times", () => {+ const set = [0, 1, 2].map(() => { const el = host(); return { log: stub(el).log, h: tour(el, LAP), first: -1 }; });+ for (let f = 0; f < 200; f++) {+ frames();+ for (const s of set) if (s.first < 0 && s.log.length) s.first = f;+ }+ expect(set.every((s) => s.first >= 0)).toBe(true);+ expect(new Set(set.map((s) => s.first)).size).toBe(3);+ for (const s of set) s.h.stop();+ });++ it("an empty tour does nothing, and a tour started before the figure's pointer() waits for it", () => {+ const el = host(), { log } = stub(el);+ const none = tour(el, []);+ frames(300);+ expect(log.length).toBe(0);+ none.stop();++ const late = host();+ const h = tour(late, [[200, 100], null]);+ frames(200);+ const { log: l2 } = stub(late);+ expect(until(() => l2.length > 0, 5)).toBe(true);+ expect(l2[0].type).toBe("ghost");+ h.stop();+ });++ it("the disposer forgets the handlers, and a new pointer() takes over", () => {+ const el = host(), a = stub(el);+ const h = tour(el, [[200, 100], null]);+ expect(until(() => a.log.length > 0, 200)).toBe(true);+ a.off();+ const n = a.log.length;+ frames(50);+ expect(a.log.length).toBe(n);+ const b = stub(el);+ expect(until(() => b.log.length > 0, 5)).toBe(true);+ expect(b.log[0].type).toBe("ghost");+ h.stop();+ expect(b.log.at(-1)).toMatchObject({ kind: "leave", type: "ghost" });+ });+});diff --git a/skills/hairline-create/kernel.js b/skills/hairline-create/kernel.jsindex 90018ba..de45fa9 100644--- a/skills/hairline-create/kernel.js+++ b/skills/hairline-create/kernel.js@@ -1,4 +1,4 @@-/* hairline kernel sha256:d360e41f54c8465afcec20bb096a0b3eaa8433f089bc9cbd743cb96abf4f69a8 */+/* hairline kernel sha256:713a89cee2645cb50226350c813ef2de043fbe6d2c7b86e418d19665276377fe *//** HL: everything a figure may call. Read this index; the code under it is the* package's src/core, unchanged, and a figure should not need to read it.@@ -102,6 +102,7 @@ var HL = (() => {__export(kernel_exports, {Cam: () => Cam,EASE_LIFT: () => EASE_LIFT,+ LAP: () => LAP,bezier: () => bezier,circ: () => circ,clamp: () => clamp,@@ -140,6 +141,7 @@ var HL = (() => {spring: () => spring,stepS: () => stepS,tdone: () => tdone,+ tour: () => tour,tset: () => tset,tval: () => tval,tween: () => tween,@@ -471,7 +473,10 @@ var HL = (() => {}};}+ var handlers = /* @__PURE__ */ new WeakMap();+ var touring = /* @__PURE__ */ new WeakMap();function pointer(stage, on) {+ handlers.set(stage, on);let tm = 0;const pt = (e) => {const r = stage.getBoundingClientRect();@@ -479,28 +484,144 @@ var HL = (() => {};const move = (e) => {clearTimeout(tm);+ touring.get(stage)?.hold();on.move(pt(e), e);};const down = (e) => {clearTimeout(tm);+ touring.get(stage)?.hold();if (e.pointerType !== "mouse") stage.releasePointerCapture?.(e.pointerId);if (on.down) on.down(pt(e), e);else on.move(pt(e), e);};const leave = (e) => {clearTimeout(tm);- tm = window.setTimeout(() => on.leave(e), e.pointerType === "mouse" ? 0 : 1400);+ tm = window.setTimeout(() => {+ on.leave(e);+ touring.get(stage)?.release();+ }, e.pointerType === "mouse" ? 0 : 1400);};stage.addEventListener("pointermove", move);stage.addEventListener("pointerdown", down);stage.addEventListener("pointerleave", leave);return () => {clearTimeout(tm);+ if (handlers.get(stage) === on) handlers.delete(stage);stage.removeEventListener("pointermove", move);stage.removeEventListener("pointerdown", down);stage.removeEventListener("pointerleave", leave);};}+ var LAP = [[128, 150], [200, 118], [272, 150], [200, 206], null];+ var TRAVEL = 900;+ var DWELL = 1200;+ var REST = 1800;+ var RESUME = 1200;+ var STAGGER = 450;+ var GHOST = { pointerType: "ghost" };+ var started = 0;+ function entry([x, y]) {+ const dx = x - 200, dy = y - 160;+ if (!dx && !dy) return [200, 320];+ const k = Math.min(dx ? (dx > 0 ? 200 : -200) / dx : Infinity, dy ? (dy > 0 ? 160 : -160) / dy : Infinity);+ return [200 + dx * k, 160 + dy * k];+ }+ function tour(stage, stops, onStop) {+ let i = 0;+ let wait = RESUME + STAGGER * (started++ % 4);+ let t = -1;+ let at = null;+ let origin = [200, 320];+ let hand = false, keys = stage.contains(stage.ownerDocument.activeElement);+ let gone = false;+ const leave = () => {+ at = null;+ t = -1;+ handlers.get(stage)?.leave(GHOST);+ };+ const tick = (dt) => {+ if (hand || keys || !stops.length) return false;+ if (reducedMotion()) {+ if (at) leave();+ return false;+ }+ if (wait > 0) {+ wait -= dt * 1e3;+ return true;+ }+ const stop2 = stops[i];+ if (stop2 === null) {+ if (at) leave();+ onStop?.(i);+ i = (i + 1) % stops.length;+ wait = REST;+ return true;+ }+ const h = handlers.get(stage);+ if (!h) return true;+ if (t < 0) {+ origin = at ?? entry(stop2);+ t = 0;+ }+ t = Math.min(TRAVEL, t + dt * 1e3);+ const k = EASE_LIFT(t / TRAVEL);+ at = [origin[0] + (stop2[0] - origin[0]) * k, origin[1] + (stop2[1] - origin[1]) * k];+ h.move(at, GHOST);+ if (t < TRAVEL) return true;+ onStop?.(i);+ i = (i + 1) % stops.length;+ t = -1;+ wait = DWELL;+ return true;+ };+ const take = () => {+ at = null;+ t = -1;+ };+ const give = () => {+ if (hand || keys) return;+ i = 0;+ t = -1;+ wait = RESUME;+ board.wake();+ };+ const me = {+ hold: () => {+ hand = true;+ take();+ },+ release: () => {+ if (!hand) return;+ hand = false;+ give();+ }+ };+ const focusIn = () => {+ keys = true;+ take();+ };+ const focusOut = (e) => {+ if (keys && !stage.contains(e.relatedTarget)) {+ keys = false;+ give();+ }+ };+ stage.addEventListener("focusin", focusIn);+ stage.addEventListener("focusout", focusOut);+ touring.set(stage, me);+ const board = register(stage, tick);+ return {+ stop: () => {+ if (gone) return;+ gone = true;+ board.unregister();+ stage.removeEventListener("focusin", focusIn);+ stage.removeEventListener("focusout", focusOut);+ if (touring.get(stage) === me) touring.delete(stage);+ if (at) leave();+ }+ };+ }function disposer() {let fns = [];return {