Isometric line figures that answer the pointer. For React and for anything with a DOM.
Tests: parity with lucasmarkes.com for all six figures, behaviour and theme in Chrome
Lucas Marquesf82e9abf51f8
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 0bbd574..95e5ef7 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -40,3 +40,8 @@ jobs:- name: Unit and component testsrun: pnpm test+ # The browser tests drive the Chrome that ubuntu-latest ships+ # (playwright.config.ts sets channel: "chrome"), so nothing is downloaded.+ - name: Browser tests+ run: pnpm test:browser+diff --git a/packages/hairline/playwright.config.ts b/packages/hairline/playwright.config.tsnew file mode 100644index 0000000..caa448b--- /dev/null+++ b/packages/hairline/playwright.config.ts@@ -0,0 +1,18 @@+import { defineConfig } from "@playwright/test";++/** Browser tests run in the installed Chrome, against the harness page (test/browser/serve.mjs). */+export default defineConfig({+ testDir: "test/browser",+ testMatch: "*.spec.ts",+ fullyParallel: true,+ forbidOnly: !!process.env.CI,+ reporter: process.env.CI ? "github" : "list",+ use: {+ baseURL: "http://localhost:4310",+ channel: "chrome",+ viewport: { width: 1200, height: 900 },+ deviceScaleFactor: 1,+ colorScheme: "light",+ },+ webServer: { command: "node test/browser/serve.mjs", url: "http://localhost:4310", reuseExistingServer: !process.env.CI },+});diff --git a/packages/hairline/test/browser/entry.ts b/packages/hairline/test/browser/entry.tsnew file mode 100644index 0000000..02c97e4--- /dev/null+++ b/packages/hairline/test/browser/entry.ts@@ -0,0 +1,33 @@+import * as hairline from "../../src/index";++/**+ * The harness page's script: the package, on `window`, with one figure at a+ * time on #host. Tests drive it through page.evaluate.+ */+type Id = "riffle" | "terrain" | "exploded" | "phosphor" | "slow" | "turntable";+type Loose = Record<string, unknown>;+type Mount = (el: HTMLElement, options?: Loose) => { update(o: Loose): void; destroy(): void };++const api = {+ hairline,+ /** Every caption the current figure has written, in order. */+ reads: [] as string[],+ figure: null as ReturnType<Mount> | null,+ /** Mounts a figure on `el` (default #host), recording its captions. */+ mount(id: Id, options: Loose = {}, el: HTMLElement = document.getElementById("host")!) {+ api.reads = [];+ api.figure = (hairline[id] as unknown as Mount)(el, { ...options, onRead: (text: string) => api.reads.push(text) });+ return api.figure;+ },+ read: () => api.reads[api.reads.length - 1] ?? null,+};++declare global {+ interface Window {+ __hl: typeof api;+ /** test/parity/clock.js, when a test adds it */+ __realTimeout: typeof setTimeout;+ __advance(ms: number): number;+ }+}+window.__hl = api;diff --git a/packages/hairline/test/browser/figures.spec.ts b/packages/hairline/test/browser/figures.spec.tsnew file mode 100644index 0000000..5c44be9--- /dev/null+++ b/packages/hairline/test/browser/figures.spec.ts@@ -0,0 +1,129 @@+import { expect, test, type Page } from "@playwright/test";++/** The figures in a real browser: input, focus, reduced motion, shadow roots, a clean console. */++const IDS = ["riffle", "terrain", "exploded", "phosphor", "slow", "turntable"] as const;+type Id = (typeof IDS)[number];++const mount = (page: Page, id: Id, options: Record<string, unknown> = {}) =>+ page.evaluate(([id, options]) => { window.__hl.mount(id, options); }, [id, options] as const);+const read = (page: Page) => page.evaluate(() => window.__hl.read());+/** A pointer event at a point of the 400 × 320 viewBox; no point is a leave. */+const fire = (page: Page, type: string, pt?: [number, number]) => page.locator("#host").evaluate((el, [type, pt]) => {+ const r = el.getBoundingClientRect();+ el.dispatchEvent(new PointerEvent(type, {+ pointerType: "mouse", pointerId: 1, bubbles: type !== "pointerleave",+ clientX: pt ? r.left + (pt[0] / 400) * r.width : r.left - 40,+ clientY: pt ? r.top + (pt[1] / 320) * r.height : r.top - 40,+ }));+}, [type, pt] as const);++test.beforeEach(async ({ page }) => { await page.goto("/"); });++test("every figure mounts, answers the pointer and leaves, with nothing on the console", async ({ page }) => {+ const problems: string[] = [];+ page.on("pageerror", (e) => problems.push(String(e)));+ page.on("console", (m) => { if (m.type() === "error" || m.type() === "warning") problems.push(m.text()); });+ for (const id of IDS) {+ await mount(page, id);+ const host = page.locator("#host");+ await expect(host.locator("svg > *").first()).toBeAttached();+ const box = (await host.boundingBox())!;+ expect(box.width / box.height).toBeCloseTo(5 / 4, 2);+ await host.hover({ position: { x: box.width * 0.45, y: box.height * 0.5 } });+ await page.mouse.move(box.x + box.width * 0.6, box.y + box.height * 0.45, { steps: 6 });+ await page.waitForTimeout(150);+ await page.mouse.move(2, 2);+ await page.evaluate(() => window.__hl.figure!.destroy());+ expect(await host.evaluate((el) => el.outerHTML)).toBe('<div id="host"></div>');+ }+ expect(problems).toEqual([]);+});++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"] });+ 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 page.keyboard.press("ArrowRight");+ await expect(live).toHaveText("02 · Drum");+ await page.keyboard.press("ArrowRight");+ await expect(live).toHaveText("03");+ await page.keyboard.press("Escape");+ await expect(live).toHaveText("rest");+ await page.keyboard.press("ArrowLeft");+ await host.blur();+ await expect(live).toHaveText("rest");+ /* read, not seen */+ const box = (await live.boundingBox())!;+ expect(box.width).toBeLessThanOrEqual(1);+ expect(box.height).toBeLessThanOrEqual(1);+});++test("Turntable settles on a quarter turn after a flick", async ({ page }) => {+ await mount(page, "turntable");+ expect(await read(page)).toBe("az 045° · el 30°");+ for (const x of [50, 120, 200, 280, 350]) { await fire(page, "pointermove", [x, 176]); await page.waitForTimeout(16); }+ await fire(page, "pointerleave");+ await expect.poll(() => read(page), { timeout: 8000 }).toMatch(/^az (045|135|225|315)° · el 30°$/);+ const settled = await read(page);+ await page.waitForTimeout(400);+ expect(await read(page)).toBe(settled);+ expect(await page.evaluate(() => window.__hl.reads.length)).toBeGreaterThan(3);+});++test("under reduced motion the loops hold still", async ({ browser }) => {+ const context = await browser.newContext({ reducedMotion: "reduce" });+ const page = await context.newPage();+ await page.goto("/");+ for (const id of ["phosphor", "slow"] as const) {+ await mount(page, id);+ await page.waitForTimeout(700);+ const a = await page.locator("#host > svg").innerHTML();+ await page.waitForTimeout(500);+ expect(await page.locator("#host > svg").innerHTML(), id).toBe(a);+ }+ await context.close();+});++test("a figure in a shadow root is styled there, and only there", async ({ page }) => {+ const fill = await page.evaluate(() => {+ const outer = document.createElement("div");+ document.body.append(outer);+ const root = outer.attachShadow({ mode: "open" });+ const el = document.createElement("div");+ el.style.width = "400px";+ root.append(el);+ window.__hl.mount("terrain", { theme: "dark" }, el);+ return {+ fill: getComputedStyle(el.querySelector("svg .sil")!).fill,+ position: getComputedStyle(el).position,+ inShadow: root.adoptedStyleSheets.length,+ inDocument: document.adoptedStyleSheets.length + document.querySelectorAll("style[data-hairline-style]").length,+ };+ });+ expect(fill).toEqual({ fill: "rgb(8, 9, 10)", position: "relative", inShadow: 1, inDocument: 0 });+});++// Review Focus 5: frameworks build a node first and attach it afterwards+test("a figure mounted on a detached element is drawn and styled once attached", async ({ page }) => {+ const result = await page.evaluate(async () => {+ const el = document.createElement("div");+ el.style.width = "400px";+ window.__hl.mount("slow", {}, el);+ const before = el.querySelector("svg")!.childElementCount;+ document.body.append(el);+ await new Promise((done) => setTimeout(done, 300));+ const first = el.querySelector("svg")!.innerHTML;+ await new Promise((done) => setTimeout(done, 300));+ return {+ before: before > 0,+ box: [el.offsetWidth, el.offsetHeight],+ fill: getComputedStyle(el.querySelector("svg .sil")!).fill,+ running: el.querySelector("svg")!.innerHTML !== first,+ };+ });+ expect(result).toEqual({ before: true, box: [400, 320], fill: "rgb(255, 255, 255)", running: true });+});diff --git a/packages/hairline/test/browser/harness.html b/packages/hairline/test/browser/harness.htmlnew file mode 100644index 0000000..a6770c0--- /dev/null+++ b/packages/hairline/test/browser/harness.html@@ -0,0 +1,16 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<title>hairline — test harness</title>+<link rel="icon" href="data:,">+<style>+ body { margin: 0; padding: 40px; }+ #host { width: 640px; }+</style>+</head>+<body>+ <div id="host"></div>+ <script type="module" src="/entry.js"></script>+</body>+</html>diff --git a/packages/hairline/test/browser/parity.spec.ts b/packages/hairline/test/browser/parity.spec.tsnew file mode 100644index 0000000..03b85de--- /dev/null+++ b/packages/hairline/test/browser/parity.spec.ts@@ -0,0 +1,43 @@+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";++/**+ * The package draws what the site draws. Each golden is the site's svg at+ * every checkpoint of a pointer script (test/parity/capture.mjs); the same+ * script is played here against the package, on the same virtual clock.+ */+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"];++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];+ 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);+ 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 */+ await page.evaluate(() => new Promise((done) => window.__realTimeout(done, 500)));++ 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),+ }, (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);+ }+ });+}diff --git a/packages/hairline/test/browser/serve.mjs b/packages/hairline/test/browser/serve.mjsnew file mode 100644index 0000000..3241ba6--- /dev/null+++ b/packages/hairline/test/browser/serve.mjs@@ -0,0 +1,23 @@+/**+ * The browser tests' server: the harness page and the package source, bundled+ * by esbuild at start. Playwright starts it (playwright.config.ts).+ */+import { build } from "esbuild";+import { readFileSync } from "node:fs";+import { createServer } from "node:http";+import { fileURLToPath } from "node:url";++const PORT = 4310;+const here = (p) => fileURLToPath(new URL(p, import.meta.url));++const bundle = await build({ entryPoints: [here("./entry.ts")], bundle: true, format: "esm", target: "es2020", write: false });+const routes = {+ "/": ["text/html", readFileSync(here("./harness.html"))],+ "/entry.js": ["text/javascript", bundle.outputFiles[0].contents],+};++createServer((req, res) => {+ const hit = routes[new URL(req.url, "http://x").pathname];+ if (!hit) { res.writeHead(404).end(); return; }+ res.writeHead(200, { "content-type": `${hit[0]}; charset=utf-8`, "cache-control": "no-store" }).end(hit[1]);+}).listen(PORT, () => console.log(`harness on http://localhost:${PORT}`));diff --git a/packages/hairline/test/browser/theme.spec.ts b/packages/hairline/test/browser/theme.spec.tsnew file mode 100644index 0000000..9b8cdff--- /dev/null+++ b/packages/hairline/test/browser/theme.spec.ts@@ -0,0 +1,79 @@+import { expect, test, type Page } from "@playwright/test";++/**+ * The palette rules, in the order the stylesheet applies them: the `theme`+ * option, an ancestor that says dark, the page's color-scheme, light. Read+ * off a real computed style: the plate colour a silhouette is filled with.+ */+const LIGHT = "rgb(255, 255, 255)", DARK = "rgb(8, 9, 10)";++const plate = (page: Page) => page.evaluate(() => getComputedStyle(document.querySelector("#host svg .sil")!).fill);+const mount = (page: Page, options: Record<string, unknown> = {}) =>+ page.evaluate((options) => { window.__hl.mount("terrain", options); }, options);++test.beforeEach(async ({ page }) => { await page.goto("/"); });++test("light when nothing says otherwise", async ({ page }) => {+ await mount(page);+ expect(await plate(page)).toBe(LIGHT);+});++test("follows the page's color-scheme", async ({ page }) => {+ await mount(page);+ await page.evaluate(() => { document.documentElement.style.colorScheme = "dark"; });+ expect(await plate(page)).toBe(DARK);+ await page.evaluate(() => { document.documentElement.style.colorScheme = "light dark"; });+ expect(await plate(page)).toBe(LIGHT);+ await page.emulateMedia({ colorScheme: "dark" });+ expect(await plate(page)).toBe(DARK);+});++test("an ancestor with class dark or data-theme=dark wins over the color-scheme", async ({ page }) => {+ await mount(page);+ await page.evaluate(() => { document.documentElement.style.colorScheme = "light"; document.body.className = "dark"; });+ expect(await plate(page)).toBe(DARK);+ await page.evaluate(() => { document.body.className = ""; document.documentElement.dataset.theme = "dark"; });+ expect(await plate(page)).toBe(DARK);+});++test("the theme option wins over both", async ({ page }) => {+ await page.evaluate(() => { document.body.className = "dark"; document.documentElement.style.colorScheme = "dark"; });+ await mount(page, { theme: "light" });+ expect(await plate(page)).toBe(LIGHT);+ await page.evaluate(() => window.__hl.figure!.update({ theme: "dark" }));+ await page.evaluate(() => { document.body.className = ""; document.documentElement.style.colorScheme = "light"; });+ expect(await plate(page)).toBe(DARK);+ await page.evaluate(() => window.__hl.figure!.update({ theme: "auto" }));+ expect(await plate(page)).toBe(LIGHT);+});++test("a --hairline-* property wins over every palette, and a page rule over the stylesheet", async ({ page }) => {+ await mount(page, { theme: "dark" });+ await page.addStyleTag({ content: "#host { --hairline-plate: rgb(1, 2, 3); --hairline-stroke: 2; } [data-hairline] { aspect-ratio: 1; }" });+ expect(await plate(page)).toBe("rgb(1, 2, 3)");+ expect(await page.evaluate(() => getComputedStyle(document.querySelector("#host svg .sil")!).strokeWidth)).toBe("2px");+ const box = (await page.locator("#host").boundingBox())!;+ expect(box.width).toBe(box.height);+});++test("without constructable stylesheets it falls back to a style element", async ({ context, page }) => {+ await context.addInitScript(() => { delete (Document.prototype as { adoptedStyleSheets?: unknown }).adoptedStyleSheets; });+ await page.goto("/");+ await mount(page, { theme: "dark" });+ await mount(page, { theme: "dark" });+ expect(await page.locator("style[data-hairline-style]").count()).toBe(1);+ expect(await plate(page)).toBe(DARK);+});++test("without light-dark() it stays light under a dark color-scheme, and the class still works", async ({ context, page }) => {+ await context.addInitScript(() => {+ const supports = CSS.supports.bind(CSS);+ CSS.supports = ((a: string, b?: string) => (String(b ?? a).includes("light-dark") ? false : b === undefined ? supports(a) : supports(a, b))) as typeof CSS.supports;+ });+ await page.goto("/");+ await mount(page);+ await page.evaluate(() => { document.documentElement.style.colorScheme = "dark"; });+ expect(await plate(page)).toBe(LIGHT);+ await page.evaluate(() => { document.body.className = "dark"; });+ expect(await plate(page)).toBe(DARK);+});