Skip to content

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

Skill: the bench and its build script, with Terrain on it drawing what the package draws

Lucas Marquesdf808cef468c
diff --git a/packages/hairline/test/browser/serve.mjs b/packages/hairline/test/browser/serve.mjs
index 3241ba6..1695d74 100644
--- a/packages/hairline/test/browser/serve.mjs
+++ b/packages/hairline/test/browser/serve.mjs
@@ -1,19 +1,26 @@
/**
* The browser tests' server: the harness page and the package source, bundled
- * by esbuild at start. Playwright starts it (playwright.config.ts).
+ * by esbuild at start, and the skill's bench with its examples on it, built at
+ * start too. 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";
+import { assemble } from "../../../../skills/hairline-create/build.mjs";
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 });
+/* The skill's bench (skills/hairline-create), with a figure on it: what its agent hands over. */
+const example = (name) => assemble(readFileSync(here(`../../../../skills/hairline-create/examples/${name}.js`), "utf8"));
+const THROWS = `hairline({ name: "throws", means: "A figure that fails at mount.", rules: [5], range: [0, 1, 2], mount() { throw new Error("no drawing today"); } });`;
const routes = {
"/": ["text/html", readFileSync(here("./harness.html"))],
"/entry.js": ["text/javascript", bundle.outputFiles[0].contents],
+ "/bench/terrain": ["text/html", example("terrain")],
+ "/bench/throws": ["text/html", assemble(THROWS)],
};
createServer((req, res) => {
diff --git a/packages/hairline/test/browser/skill.spec.ts b/packages/hairline/test/browser/skill.spec.ts
new file mode 100644
index 0000000..0df6792
--- /dev/null
+++ b/packages/hairline/test/browser/skill.spec.ts
@@ -0,0 +1,160 @@
+import { expect, test, type Page } from "@playwright/test";
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { play } from "../parity/driver.mjs";
+import { INTENSITY, SCRIPTS } from "../parity/scripts.mjs";
+
+/**
+ * The skill's bench (skills/hairline-create) with its examples on it: the page
+ * an agent hands over. It answers the pointer, its controls reach the figure,
+ * and it draws what the package draws, so the extracted kernel is the engine.
+ */
+const file = (p: string) => readFileSync(new URL(p, import.meta.url), "utf8");
+const SKILL = fileURLToPath(new URL("../../../../skills/hairline-create/", import.meta.url));
+const clock = file("../parity/clock.js") + "\nwindow.__freeze(1000);";
+
+type Step = Record<string, unknown>;
+type Checkpoint = { at: string; read: string; svg: string };
+/** Each example: a viewBox point that is on the figure, what the slider shows at its two ends, and how much of the package's script it can play. */
+const EXAMPLES = {
+ terrain: { at: [200, 160], ends: ["1.5", "5"], steps: (SCRIPTS as Record<string, Step[]>).terrain },
+} as Record<string, { at: [number, number]; ends: [string, string]; steps: Step[] }>;
+
+const svg = (page: Page) => page.locator("#stage > svg").evaluate((el) => el.innerHTML);
+const read = (page: Page) => page.locator("#read").innerText();
+const setIntensity = (page: Page, value: number) => page.locator("#intensity").evaluate((el, value) => {
+ (el as HTMLInputElement).value = String(value);
+ el.dispatchEvent(new Event("input", { bubbles: true }));
+}, value);
+/** Everything the page complains about. */
+function watch(page: 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()); });
+ return problems;
+}
+/* a figure sleeps until its IntersectionObserver reports it on screen, and that report comes on the browser's own time */
+const settle = (page: Page) => page.evaluate(() => new Promise((done) => window.__realTimeout(done, 500)));
+
+for (const [id, ex] of Object.entries(EXAMPLES)) {
+ test(`${id} answers the pointer and comes back to rest, with nothing on the console`, async ({ page }) => {
+ const problems = watch(page);
+ await page.goto(`/bench/${id}`);
+ const stage = page.locator("#stage");
+ await expect(stage.locator("svg > *").first()).toBeAttached();
+ await expect(page.locator("#read")).toHaveText("rest");
+ await expect(page.locator("#name")).toHaveText(id);
+ await expect(page.locator("#means")).not.toBeEmpty();
+ await expect(page.locator("#rules")).toHaveText(/^\d\d [a-z]+( · \d\d [a-z]+)*$/);
+ const box = (await stage.boundingBox())!;
+ expect(box.width / box.height).toBeCloseTo(5 / 4, 2);
+ const rest = await svg(page);
+
+ await page.mouse.move(box.x + (ex.at[0] / 400) * box.width, box.y + (ex.at[1] / 320) * box.height, { steps: 4 });
+ await expect(page.locator("#read")).not.toHaveText("rest");
+ await expect.poll(() => svg(page)).not.toBe(rest);
+
+ await page.mouse.move(2, 2);
+ await expect(page.locator("#read")).toHaveText("rest");
+ await expect.poll(() => svg(page), { timeout: 8000 }).toBe(rest);
+ expect(problems).toEqual([]);
+ });
+
+ test(`${id}: the slider reaches the figure`, async ({ context, page }) => {
+ await context.addInitScript(clock);
+ const drawn = async (value: number) => {
+ await page.goto(`/bench/${id}`);
+ await page.locator("#stage svg > *").first().waitFor();
+ await settle(page);
+ const [cp] = await play(page, {
+ stage: page.locator("#stage"),
+ snap: async () => ({ svg: await svg(page), read: await read(page) }),
+ set: () => setIntensity(page, value),
+ }, [{ set: true }, { move: ex.at }, { adv: 12 }, { cp: "answering" }]) as Checkpoint[];
+ return { svg: cp.svg, value: await page.locator("#value").innerText() };
+ };
+ const low = await drawn(0), high = await drawn(1);
+ expect([low.value, high.value]).toEqual(ex.ends);
+ expect(low.svg).not.toBe(high.svg);
+ });
+
+ test(`${id} on the bench draws what the package draws`, async ({ context, page }) => {
+ const golden = (JSON.parse(file(`../parity/golden/${id}.json`)) as { checkpoints: Checkpoint[] }).checkpoints;
+ /* the goldens hold Riffle's hidden hit bands and the names the site gives its cards; neither is drawn or said here */
+ const strip = (s: string) => s.replace(/<g class="bands">.*?<\/g>/, "");
+ const unname = (s: string) => s.replace(/ · .*$/, "");
+ await context.addInitScript(clock);
+ await page.goto(`/bench/${id}`);
+ const stage = page.locator("#stage");
+ await stage.locator("svg > *").first().waitFor();
+ await settle(page);
+
+ const got = await play(page, {
+ stage,
+ snap: async () => ({ svg: await svg(page), read: await read(page) }),
+ set: () => setIntensity(page, (INTENSITY as Record<string, number>)[id]),
+ }, ex.steps) as Checkpoint[];
+
+ expect(got.length).toBeGreaterThanOrEqual(4);
+ for (const [i, have] of got.entries()) {
+ expect(have.at).toBe(golden[i].at);
+ expect(have.read, `caption at "${have.at}"`).toBe(unname(golden[i].read));
+ expect(strip(have.svg), `drawing at "${have.at}"`).toBe(strip(golden[i].svg));
+ }
+ });
+}
+
+test("the theme switch changes the palette, and wins over the system's theme both ways", async ({ page }) => {
+ const stroke = () => page.locator("#stage path.sil").first().evaluate((el) => getComputedStyle(el).stroke);
+ await page.goto("/bench/terrain");
+ await expect.poll(stroke).toBe("rgb(164, 164, 172)");
+ await expect(page.locator("#theme")).toHaveText("light");
+ await page.locator("#theme").click();
+ await expect.poll(stroke).toBe("rgb(91, 93, 100)");
+ await expect(page.locator("body")).toHaveCSS("background-color", "rgb(8, 9, 10)");
+ await expect(page.locator("#theme")).toHaveText("dark");
+
+ await page.emulateMedia({ colorScheme: "dark" });
+ await page.reload();
+ await expect.poll(stroke).toBe("rgb(91, 93, 100)");
+ await page.locator("#theme").click();
+ await expect.poll(stroke).toBe("rgb(164, 164, 172)");
+ await expect(page.locator("body")).toHaveCSS("background-color", "rgb(255, 255, 255)");
+});
+
+test("the page fits a 240px screen without scrolling sideways", async ({ page }) => {
+ await page.setViewportSize({ width: 240, height: 700 });
+ await page.goto("/bench/terrain");
+ await expect(page.locator("#stage svg > *").first()).toBeAttached();
+ const { scroll, client } = await page.evaluate(() => ({ scroll: document.documentElement.scrollWidth, client: document.documentElement.clientWidth }));
+ expect(scroll).toBeLessThanOrEqual(client);
+ expect((await page.locator("#stage").boundingBox())!.width).toBeGreaterThan(180);
+});
+
+test("destroy leaves the svg empty", async ({ page }) => {
+ await page.goto("/bench/terrain");
+ await expect(page.locator("#stage svg > *").first()).toBeAttached();
+ await page.evaluate(() => (window as unknown as { hairline: { figure: { destroy(): void } } }).hairline.figure.destroy());
+ expect(await page.locator("#stage > svg").evaluate((el) => el.childElementCount)).toBe(0);
+});
+
+test("a figure that throws says so under the stage", async ({ page }) => {
+ await page.goto("/bench/throws");
+ await expect(page.locator("#error")).toBeVisible();
+ await expect(page.locator("#error")).toContainText("no drawing today");
+});
+
+test("the built file draws when opened from disk, narrowed and with the pointer held by its URL", async ({ page }) => {
+ const problems = watch(page);
+ const out = join(mkdtempSync(join(tmpdir(), "hl-page-")), "hairline-terrain.html");
+ execFileSync("node", [SKILL + "build.mjs", SKILL + "examples/terrain.js", out]);
+ await page.goto(pathToFileURL(out).href + "?w=240&at=200,160");
+ await expect(page.locator("#stage svg > *").first()).toBeAttached();
+ await expect(page.locator("#read")).toHaveText(/^cell \d·\d$/);
+ expect((await page.locator("#stage").boundingBox())!.width).toBeLessThanOrEqual(240);
+ await expect(page).toHaveTitle("Hairline · terrain");
+ expect(problems).toEqual([]);
+});
diff --git a/packages/hairline/test/skill/build.test.ts b/packages/hairline/test/skill/build.test.ts
new file mode 100644
index 0000000..2dbd43f
--- /dev/null
+++ b/packages/hairline/test/skill/build.test.ts
@@ -0,0 +1,55 @@
+import { spawnSync } from "node:child_process";
+import { mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { expect, it } from "vitest";
+
+/** build.mjs puts a figure on the bench: the page is the bench, the kernel and the figure, and nothing else. */
+const SKILL = fileURLToPath(new URL("../../../../skills/hairline-create/", import.meta.url));
+const dir = mkdtempSync(join(tmpdir(), "hl-build-"));
+const terrain = readFileSync(SKILL + "examples/terrain.js", "utf8");
+const node = (args: string[], cwd = dir) => spawnSync("node", args, { cwd, encoding: "utf8" });
+
+it("writes the bench with the kernel and the figure in their slots", () => {
+ const out = join(dir, "page.html");
+ const run = node([SKILL + "build.mjs", SKILL + "examples/terrain.js", out]);
+ expect(run.stderr).toBe("");
+ expect(run.status).toBe(0);
+ expect(run.stdout.trim()).toBe(out);
+ const page = readFileSync(out, "utf8");
+ expect(page).toContain(readFileSync(SKILL + "kernel.js", "utf8").trimEnd());
+ expect(page).toContain(terrain.trim());
+ expect(page).not.toContain("/*KERNEL*/");
+ expect(page).not.toContain("/*FIGURE*/");
+});
+
+it("names the page after the figure when no path is given", () => {
+ const run = node([SKILL + "build.mjs", SKILL + "examples/terrain.js"]);
+ expect(run.status).toBe(0);
+ expect(run.stdout.trim().endsWith("hairline-terrain.html")).toBe(true);
+ expect(readFileSync(run.stdout.trim(), "utf8")).toContain("<title>");
+});
+
+it("pastes text literally, so a figure may hold $& and $1", () => {
+ const src = join(dir, "dollar.js"), out = join(dir, "dollar.html");
+ const figure = terrain.replace("hairline({", () => 'const odd = "$& and $1 and $$";\nhairline({');
+ writeFileSync(src, figure);
+ expect(node([SKILL + "build.mjs", src, out]).status).toBe(0);
+ expect(readFileSync(out, "utf8")).toContain('const odd = "$& and $1 and $$";');
+});
+
+it("runs when the skill folder is reached through a symlink", () => {
+ const link = join(dir, "linked");
+ symlinkSync(SKILL, link);
+ const out = join(dir, "linked.html");
+ const run = node([join(link, "build.mjs"), join(link, "examples/terrain.js"), out]);
+ expect(run.status).toBe(0);
+ expect(run.stdout.trim()).toBe(out);
+});
+
+it("says how to call it when it is given nothing", () => {
+ const run = node([SKILL + "build.mjs"]);
+ expect(run.status).toBe(2);
+ expect(run.stderr).toContain("usage: node build.mjs <figure.js> [out.html]");
+});
diff --git a/skills/hairline-create/bench.html b/skills/hairline-create/bench.html
new file mode 100644
index 0000000..29a6192
--- /dev/null
+++ b/skills/hairline-create/bench.html
@@ -0,0 +1,145 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>Hairline figure</title>
+<link rel="icon" href="data:,">
+<style>
+ :root { color-scheme: light; --ground: #ffffff; --ink: #232327; --muted: #6f6f78; --line: #e0e0e4; }
+ @media (prefers-color-scheme: dark) {
+ :root:not([data-theme="light"]) { color-scheme: dark; --ground: #08090a; --ink: #d0d6e0; --muted: #8a8c95; --line: #29292d; }
+ }
+ :root[data-theme="dark"] { color-scheme: dark; --ground: #08090a; --ink: #d0d6e0; --muted: #8a8c95; --line: #29292d; }
+ :root[data-theme="light"] { color-scheme: light; }
+ * { box-sizing: border-box; }
+ body {
+ margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px 16px;
+ background: var(--ground); color: var(--ink);
+ font: 13px/1.5 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; -webkit-font-smoothing: antialiased;
+ }
+ main { width: 100%; max-width: 640px; }
+ .plate { position: relative; border: 1px solid var(--line); border-radius: 14px; overflow: hidden; }
+ .tag, .label, output, button { font: 11px/1 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; letter-spacing: 0.02em; }
+ .tag { position: absolute; top: 12px; z-index: 1; color: var(--muted); pointer-events: none; }
+ #name { left: 14px; }
+ #read { right: 14px; color: var(--ink); font-variant-numeric: tabular-nums; }
+ .controls { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 12px; margin-top: 14px; }
+ .label { color: var(--muted); }
+ input[type="range"] {
+ flex: 1 1 96px; min-width: 0; height: 32px; margin: 0; background: transparent; cursor: pointer;
+ -webkit-appearance: none; appearance: none;
+ }
+ input[type="range"]::-webkit-slider-runnable-track { height: 1px; background: var(--muted); }
+ input[type="range"]::-webkit-slider-thumb {
+ -webkit-appearance: none; width: 13px; height: 13px; margin-top: -6px; border-radius: 50%;
+ border: 1px solid var(--ink); background: var(--ground);
+ }
+ input[type="range"]::-moz-range-track { height: 1px; background: var(--muted); }
+ input[type="range"]::-moz-range-thumb { width: 11px; height: 11px; border-radius: 50%; border: 1px solid var(--ink); background: var(--ground); }
+ input[type="range"]:focus-visible, button:focus-visible { outline: 1.5px solid var(--ink); outline-offset: 2px; }
+ output { min-width: 4ch; text-align: right; font-variant-numeric: tabular-nums; }
+ button {
+ height: 32px; padding: 0 12px; border: 1px solid var(--line); border-radius: 8px;
+ background: transparent; color: var(--ink); cursor: pointer;
+ }
+ #means { margin: 14px 0 0; text-wrap: pretty; }
+ #rules { margin: 6px 0 0; line-height: 1.6; }
+ #error { margin: 12px 0 0; padding-left: 10px; border-left: 1px solid var(--ink); }
+</style>
+</head>
+<body>
+<main>
+ <div class="plate">
+ <span class="tag" id="name"></span>
+ <span class="tag" id="read"></span>
+ <div id="stage"></div>
+ </div>
+ <div class="controls">
+ <label class="label" for="intensity">intensity</label>
+ <input id="intensity" type="range" min="0" max="1" step="0.01" value="0.5">
+ <output id="value" for="intensity"></output>
+ <span class="label">theme</span>
+ <button id="theme" type="button" aria-label="Switch between the light and the dark theme"></button>
+ </div>
+ <p id="means"></p>
+ <p id="rules" class="label"></p>
+ <p id="error" role="alert" hidden></p>
+</main>
+<script id="hl-kernel">/*KERNEL*/</script>
+<script id="hl-bench">
+/*
+ * The bench: the page a figure is shown on. It makes the host and the svg the
+ * way the package's mount does, hands them to the figure, and owns everything
+ * around it: the read-out, the slider, the theme, the line under the stage.
+ */
+(() => {
+ const RULES = ["hit", "order", "reach", "accent", "rest", "honesty", "cost", "clock", "radius", "quiet"];
+ const $ = (id) => document.getElementById(id);
+ const root = document.documentElement, params = new URLSearchParams(location.search);
+
+ /* the theme: the system's until the switch is pressed, then the switch's */
+ const dark = () => (root.dataset.theme ? root.dataset.theme === "dark" : matchMedia("(prefers-color-scheme: dark)").matches);
+ const label = () => { $("theme").textContent = dark() ? "dark" : "light"; };
+ $("theme").addEventListener("click", () => { root.dataset.theme = dark() ? "light" : "dark"; label(); });
+ label();
+
+ /* ?w=240 narrows the page, for a look at the size of a thumbnail */
+ const w = Number(params.get("w"));
+ if (w > 0) document.querySelector("main").style.maxWidth = w + "px";
+
+ /* a figure that fails says so under the stage, instead of leaving an empty plate */
+ addEventListener("error", (e) => {
+ $("error").hidden = false;
+ $("error").textContent = String((e.error && e.error.message) || e.message);
+ });
+
+ let mounted = false;
+ window.hairline = (figure) => {
+ if (mounted) throw new Error("hairline: one figure per page.");
+ mounted = true;
+ const stage = $("stage"), slider = $("intensity");
+
+ /* intensity to the figure's own number: two straight lines that meet at 0.5, as in the package */
+ const [lo, mid, hi] = figure.range;
+ const at = (i) => Math.round((i <= 0.5 ? lo + (i / 0.5) * (mid - lo) : mid + ((i - 0.5) / 0.5) * (hi - mid)) * 1000) / 1000;
+
+ HL.inject(document);
+ stage.setAttribute("data-hairline", figure.name);
+ stage.setAttribute("role", "img");
+ stage.setAttribute("aria-label", figure.means);
+ const svg = HL.mk("svg", { viewBox: "0 0 400 320", "aria-hidden": "true" }, stage);
+
+ let text = null;
+ const read = {
+ get textContent() { return text; },
+ set textContent(value) { text = value == null ? "" : String(value); $("read").textContent = text; },
+ };
+
+ document.title = "Hairline · " + figure.name;
+ $("name").textContent = figure.name;
+ $("means").textContent = figure.means;
+ $("rules").textContent = figure.rules.map((n) => String(n).padStart(2, "0") + " " + RULES[n - 1]).join(" · ");
+ const show = () => { $("value").textContent = String(at(Number(slider.value))); };
+ show();
+
+ const handle = figure.mount({ stage, svg, read }, at(0.5));
+ if (text === null) read.textContent = "rest";
+ slider.addEventListener("input", () => { show(); handle.set(at(Number(slider.value))); });
+ window.hairline.figure = handle;
+
+ /* ?at=200,160 holds the pointer at a viewBox point, for a picture of the answer without a mouse */
+ const p = (params.get("at") || "").split(",").map(Number);
+ if (p.length === 2 && p.every(Number.isFinite)) {
+ const r = stage.getBoundingClientRect();
+ stage.dispatchEvent(new PointerEvent("pointermove", {
+ pointerType: "mouse", pointerId: 1, bubbles: true,
+ clientX: r.left + (p[0] / 400) * r.width, clientY: r.top + (p[1] / 320) * r.height,
+ }));
+ }
+ };
+})();
+</script>
+<script type="module" id="hl-figure">/*FIGURE*/</script>
+</body>
+</html>
diff --git a/skills/hairline-create/build.mjs b/skills/hairline-create/build.mjs
new file mode 100644
index 0000000..dc4fcfb
--- /dev/null
+++ b/skills/hairline-create/build.mjs
@@ -0,0 +1,36 @@
+#!/usr/bin/env node
+/**
+ * Puts a figure on the bench: `node build.mjs <figure.js> [out.html]` writes
+ * one self-contained page, bench.html with kernel.js and the figure in its two
+ * slots and nothing else changed, and prints where it is. Without a path the
+ * page is hairline-<name>.html in the working directory.
+ */
+import { readFileSync, realpathSync, writeFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = (p) => fileURLToPath(new URL(p, import.meta.url));
+
+/** The page for a figure's source. The replacements are functions so `$&` in the kernel or the figure is pasted as it is. */
+export function assemble(figure) {
+ const kernel = readFileSync(here("./kernel.js"), "utf8").replace(/\r\n/g, "\n").trimEnd();
+ return readFileSync(here("./bench.html"), "utf8").replace(/\r\n/g, "\n")
+ .replace("/*KERNEL*/", () => `\n${kernel}\n`)
+ .replace("/*FIGURE*/", () => `\n${figure.replace(/\r\n/g, "\n").trim()}\n`);
+}
+
+/** The figure's name, read from its declaration. */
+export const nameOf = (figure) => /\bname:\s*["'`]([a-z][a-z0-9-]*)["'`]/.exec(figure)?.[1] ?? null;
+
+/* The skill is often installed as a symlink, so the path Node was given is resolved before it is compared. */
+if (process.argv[1] && realpathSync(process.argv[1]) === realpathSync(here("./build.mjs"))) {
+ const [src, out] = process.argv.slice(2);
+ if (!src) {
+ console.error("usage: node build.mjs <figure.js> [out.html]");
+ process.exit(2);
+ }
+ const figure = readFileSync(src, "utf8");
+ const file = resolve(out ?? `hairline-${nameOf(figure) ?? "figure"}.html`);
+ writeFileSync(file, assemble(figure));
+ console.log(file);
+}
diff --git a/skills/hairline-create/examples/terrain.js b/skills/hairline-create/examples/terrain.js
new file mode 100644
index 0000000..651382e
--- /dev/null
+++ b/skills/hairline-create/examples/terrain.js
@@ -0,0 +1,107 @@
+/**
+ * Terrain: a field of 81 pillars on a rounded plinth. The pointer is projected
+ * back onto the ground, and each pillar takes its height from its distance to
+ * it, on its own spring. At rest the field is a dune with two rises. A 3 × 3
+ * dot mark rides the lid of the pillar under the pointer, or the peak at rest;
+ * pillars above half height take the bright stroke. The slider is the radius,
+ * in cells.
+ *
+ * The pattern: a continuous field. Springs, a falloff by distance, a hit test
+ * on the ground plane (which never moves), and a rest that is a composition.
+ */
+const {
+ Cam, clamp, facing, fit, prism, proj, rings, unproj, spring, stepS,
+ flatDot, mk, place, pointer, put, register, disposer, solid,
+} = HL;
+
+const N = 9, CELL = 14, FOOT = 11, HMAX = 58, EXT = N * CELL, PB = 5;
+
+/** The share of full height at u radii from the pointer: 1 → .31 at 42% → .09 at the edge and beyond. */
+const falloff = (u) =>
+ u <= 0 ? 1 : u <= 0.417 ? 1 - (u / 0.417) * 0.6875 : u <= 1 ? 0.3125 - ((u - 0.417) / 0.583) * 0.2185 : 0.094;
+
+function mount({ stage, svg, read }, value) {
+ const bag = disposer();
+ const C = Cam(45, 0.5, 1.58);
+ fit(C, [[-6, -6, -PB], [EXT + 6, EXT + 6, -PB], [EXT + 6, -6, -PB], [-6, EXT + 6, -PB], [0, 0, HMAX * 0.75]], 200, 166);
+ const P = proj(C), front = facing(C);
+ let R = value * CELL, over = null;
+
+ const g = mk("g", {}, svg), cols = [];
+ const [pr, pi] = rings(-6, -6, EXT + 6, EXT + 6, 9, 2.2);
+ put(solid(g), prism(P, front, pr, pi, -PB, 0));
+ // Diagonal by diagonal from the back corner, so appending is painting back to front.
+ for (let s = 0; s <= 2 * (N - 1); s++) for (let i = 0; i < N; i++) {
+ const j = s - i;
+ if (j < 0 || j >= N) continue;
+ const u = i / (N - 1), v = j / (N - 1);
+ const h0 = 4 + 25 * Math.exp(-((u - 0.22) ** 2 + (v - 0.74) ** 2) / 0.07) + 12 * Math.exp(-((u - 0.8) ** 2 + (v - 0.26) ** 2) / 0.035);
+ const x0 = i * CELL + (CELL - FOOT) / 2, y0 = j * CELL + (CELL - FOOT) / 2;
+ const [ring, inner] = rings(x0, y0, x0 + FOOT, y0 + FOOT, 2.6, 0.9);
+ cols.push({ i, j, h0, ring, inner, sp: spring(h0, { eps: 0.04 }), el: solid(g), drawn: NaN });
+ }
+
+ // The mark: a 3 × 3 of dots riding the lid of one pillar, moved in the paint
+ // order to just after it, so the pillars in front still cover it.
+ const mark = mk("g", {}, g), md = [];
+ for (let k = 0; k < 9; k++) md.push(flatDot(mark, C, 0.55, k === 4 ? "dot" : "dot m"));
+ const peak = cols.reduce((a, b) => (b.h0 > a.h0 ? b : a));
+ const byCell = new Map();
+ cols.forEach((c) => byCell.set(c.i + "," + c.j, c));
+ let mc = null, want = peak;
+
+ function drawMark() {
+ if (want !== mc) { mc = want; mc.el.g.after(mark); }
+ const cx = (mc.i + 0.5) * CELL, cy = (mc.j + 0.5) * CELL, h = Math.max(0.6, mc.sp.x);
+ md.forEach((el, k) => place(el, P(cx + ((k % 3) - 1) * 2.5, cy + (Math.floor(k / 3) - 1) * 2.5, h)));
+ }
+ // A pillar whose spring hasn't moved keeps its paths: most of the 81 are still on most frames.
+ function drawCol(c) {
+ const h = Math.max(0.6, c.sp.x);
+ if (h === c.drawn) return;
+ c.drawn = h;
+ put(c.el, prism(P, front, c.ring, c.inner, 0, h));
+ c.el.sil.classList.toggle("hi", h > HMAX * 0.5);
+ }
+
+ const B = register(stage, (dt) => {
+ let m = false;
+ for (const c of cols) { if (stepS(c.sp, dt)) m = true; drawCol(c); }
+ drawMark();
+ return m;
+ });
+ bag.add(B.unregister);
+
+ function retarget() {
+ for (const c of cols) {
+ if (!over) { c.sp.t = c.h0; continue; }
+ const dx = (c.i + 0.5) * CELL - over[0], dy = (c.j + 0.5) * CELL - over[1];
+ c.sp.t = HMAX * falloff(Math.hypot(dx, dy) / R);
+ }
+ if (over) {
+ const i = clamp(Math.floor(over[0] / CELL), 0, N - 1), j = clamp(Math.floor(over[1] / CELL), 0, N - 1);
+ want = byCell.get(i + "," + j);
+ read.textContent = `cell ${i}·${j}`;
+ } else { want = peak; read.textContent = "rest"; }
+ B.wake();
+ }
+
+ bag.add(pointer(stage, {
+ move: (p) => { over = unproj(C, p[0], p[1], 0); retarget(); },
+ leave: () => { over = null; retarget(); },
+ }));
+ bag.add(() => svg.replaceChildren());
+
+ return {
+ set: (v) => { R = v * CELL; if (over) retarget(); },
+ destroy: bag.dispose,
+ };
+}
+
+hairline({
+ name: "terrain",
+ means: "A field of pillars rises under the pointer and falls off with distance.",
+ rules: [1, 3, 5, 9],
+ range: [1.5, 3, 5],
+ mount,
+});