Isometric line figures that answer the pointer. For React and for anything with a DOM.
Skill: the validator, which rejects a changed kernel or bench and a figure that breaks a mechanical rule
Lucas Marques30f20d424bf8
diff --git a/packages/hairline/test/skill/validate.test.ts b/packages/hairline/test/skill/validate.test.tsnew file mode 100644index 0000000..dd1a42d--- /dev/null+++ b/packages/hairline/test/skill/validate.test.ts@@ -0,0 +1,104 @@+import { execFileSync, 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 { describe, expect, it } from "vitest";++/**+ * validate.mjs passes the two examples and fails a page broken in one way,+ * naming that way and no other. The broken pages are Terrain with one change.+ */+const SKILL = fileURLToPath(new URL("../../../../skills/hairline-create/", import.meta.url));+const dir = mkdtempSync(join(tmpdir(), "hl-validate-"));+const terrain = readFileSync(SKILL + "examples/terrain.js", "utf8");+let n = 0;++/** Builds a figure's page, changes the page if asked, and validates it. */+function check(figure: string, change?: (page: string) => string, script = SKILL + "validate.mjs") {+ const src = join(dir, `f${++n}.js`), out = join(dir, `f${n}.html`);+ writeFileSync(src, figure);+ execFileSync("node", [SKILL + "build.mjs", src, out]);+ if (change) writeFileSync(out, change(readFileSync(out, "utf8")));+ const run = spawnSync("node", [script, out], { encoding: "utf8" });+ return { status: run.status, out: run.stdout, err: run.stderr };+}+/** Terrain with a line of code just before its declaration. */+const plus = (code: string) => terrain.replace("hairline({", () => `${code}\nhairline({`);++describe("pages that pass", () => {+ for (const name of ["terrain", "riffle"]) {+ it(`the ${name} example`, () => {+ const figure = readFileSync(`${SKILL}examples/${name}.js`, "utf8");+ expect(figure.trim().split("\n").length).toBeLessThanOrEqual(200);+ const run = check(figure);+ expect(run.err).toBe("");+ expect(run.status).toBe(0);+ expect(run.out).toMatch(/^ok .*kernel and bench intact/);+ });+ }++ it("a page saved with CRLF line endings", () => {+ expect(check(terrain, (page) => page.replace(/\n/g, "\r\n")).status).toBe(0);+ });++ it("a range that falls, as Slow's does", () => {+ expect(check(terrain.replace("range: [1.5, 3, 5]", "range: [5, 3, 1.5]")).status).toBe(0);+ });++ it("through a symlink to the skill folder", () => {+ const link = join(dir, "linked");+ symlinkSync(SKILL, link);+ const run = check(terrain, undefined, join(link, "validate.mjs"));+ expect(run.status).toBe(0);+ expect(run.out).toMatch(/^ok /);+ });+});++const BROKEN: [id: string, why: string, figure: string, change?: (page: string) => string][] = [+ ["kernel", "the kernel was edited", terrain, (page) => page.replace("var HL = ", "var HL = /* mine */ ")],+ ["bench", "the bench was edited", terrain, (page) => page.replace("</main>", "<p>better</p></main>")],+ ["text", "a text element", plus('mk("text", {}, document.querySelector("svg"));')],+ ["text", "markup written as a string", plus('document.querySelector("svg").innerHTML = "";')],+ ["paint", "a fill of its own", plus('mk("path", { fill: "red" });')],+ ["paint", "a stroke width of its own", plus('mk("path", { "stroke-width": 2 });')],+ ["paint", "an inline style", plus('document.body.style.background = "#000";')],+ ["outside", "a fetch", plus('fetch("https://example.com/data.json");')],+ ["outside", "a node made by hand", plus('document.createElementNS("http://www.w3.org/2000/svg", "path");')],+ ["outside", "a script tag in a string", plus('const s = "</script>";')],+ ["clock", "its own frame", plus("requestAnimationFrame(() => {});")],+ ["clock", "its own timer", plus("setTimeout(() => {}, 100);")],+ ["clock", "no kernel loop", terrain.replace("register(stage,", "((s, t) => ({ wake() {}, unregister() {} }))(stage,")],+ ["hit", "a box measured on screen", plus("stage.getBoundingClientRect();")],+ ["hit", "its own listener", plus('stage.addEventListener("pointermove", () => {});')],+ ["hit", "no pointer", terrain.replace("bag.add(pointer(stage,", "bag.add(((s, h) => () => {})(stage,")],+ ["readout", "no read-out", terrain.replace(/read\.textContent = [^;]+;/g, "")],+ ["handle", "no destroy", terrain.replace("destroy: bag.dispose", "stop: bag.dispose")],+ ["declare", "no means", terrain.replace(/\n {2}means: .*\n/, "\n")],+ ["declare", "a range that turns back", terrain.replace("range: [1.5, 3, 5]", "range: [1.5, 5, 3]")],+ ["declare", "a rule that does not exist", terrain.replace("rules: [1, 3, 5, 9]", "rules: [1, 11]")],+ ["declare", "no declaration", terrain.replace(/hairline\(\{[\s\S]*$/, "")],+ ["length", "over 200 lines", plus(Array.from({ length: 200 }, (_, i) => `const pad${i} = ${i};`).join("\n"))],+];++describe("pages that fail, each for its own reason", () => {+ for (const [id, why, figure, change] of BROKEN) {+ it(`${id}: ${why}`, () => {+ const run = check(figure, change);+ expect(run.status).toBe(1);+ const ids = run.err.split("\n").map((line) => /^([a-z]+): /.exec(line)?.[1]).filter(Boolean);+ expect(ids.length).toBeGreaterThan(0);+ expect([...new Set(ids)]).toEqual([id]);+ expect(run.err).toMatch(/\d+ to fix in /);+ });+ }+});++it("says how to call it when it is given nothing, and when the file is not there", () => {+ const none = spawnSync("node", [SKILL + "validate.mjs"], { encoding: "utf8" });+ expect(none.status).toBe(2);+ expect(none.stderr).toContain("usage: node validate.mjs <page.html>");+ const gone = spawnSync("node", [SKILL + "validate.mjs", join(dir, "nope.html")], { encoding: "utf8" });+ expect(gone.status).toBe(2);+ expect(gone.stderr).toContain("cannot read");+});diff --git a/skills/hairline-create/validate.mjs b/skills/hairline-create/validate.mjsnew file mode 100644index 0000000..3e2a356--- /dev/null+++ b/skills/hairline-create/validate.mjs@@ -0,0 +1,121 @@+#!/usr/bin/env node+/**+ * Checks a page made by build.mjs: `node validate.mjs hairline-<name>.html`.+ * It prints what to fix and exits 1, or prints `ok` and exits 0. The checks+ * read the text of the file, so they catch what is mechanical; the look+ * (look.md) catches the rest. Each line it prints starts with the check's name:+ *+ * kernel the kernel in the page is this folder's kernel.js, untouched+ * bench nothing but the figure differs from bench.html+ * text no words inside the figure (rule 10)+ * paint no stroke width, colour, fill, filter or shadow of its own (rule 04)+ * outside nothing loaded or reached outside the file; every node from HL.mk+ * clock no timers or frames of its own; it joins HL.register (rule 07)+ * hit input only through HL.pointer; nothing measured on screen (rule 01)+ * readout it writes read.textContent+ * handle mount returns { set, destroy }+ * declare the file ends with hairline({ name, means, rules, range, mount })+ * length at most 200 lines+ */+import { createHash } from "node:crypto";+import { readFileSync, realpathSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { assemble } from "./build.mjs";++const here = (p) => fileURLToPath(new URL(p, import.meta.url));+const LIMIT = 200;+const unix = (s) => s.replace(/\r\n/g, "\n");+/** A figure's source without its comments, so its prose is never read as code. A `//` after a colon or inside a quote is kept: it is a URL. */+const bare = (src) => src.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:\\"'`])\/\/.*$/gm, "$1");++/** What a figure must not contain. */+const BAD = [+ ["text", /<\s*(?:text|tspan|textPath|foreignObject)\b|["'`](?:text|tspan|textPath|foreignObject)["'`]|\b(?:innerHTML|outerHTML|insertAdjacentHTML|innerText)\b/,+ "rule 10. No words inside the figure, and no markup written as a string. Say it with geometry (a punch, a dot code, a bright edge); names go to read.textContent."],+ ["paint", /stroke-width|strokeWidth|stroke-dasharray|["'`](?:fill|stroke|filter|style|color|stop-color)["'`]|\b(?:fill|stroke|filter|style)\s*:|\.style\b|#[0-9a-fA-F]{3,8}\b|\b(?:rgba?|hsla?|oklch|oklab|color-mix)\(|drop-shadow|box-shadow|feDropShadow|feGaussianBlur|[Gg]radient/,+ "rule 04. The figure sets a stroke width, colour, fill, filter, gradient or shadow of its own. Use the kernel's classes and nothing else: sil, hi, lo, nf, fo, dash, dot, dot m, dot off."],+ ["outside", /\bfetch\s*\(|\bimport\b|XMLHttpRequest|WebSocket|EventSource|sendBeacon|https?:\/\/|\burl\(|<\/?script|<(?:link|img|iframe|style)\b|new\s+Image\b|createElement|\beval\s*\(|new\s+Function\b|localStorage|sessionStorage|\.cookie\b/,+ "the figure reaches outside the file or makes nodes by hand. One self-contained file: no fetch, import, URL, script tag or storage, and every node comes from HL.mk."],+ ["clock", /\bsetInterval\b|\bsetTimeout\b|\brequestAnimationFrame\b|\.animate\s*\(|<animate|IntersectionObserver|\bmatchMedia\b/,+ "rule 07. The figure runs a clock of its own. Move inside HL.register(stage, tick), with springs (stepS) or tweens (tset, tval); a delay is a tween's delay. The loop sleeps offscreen and honours reduced motion for you."],+ ["hit", /getBoundingClientRect|elementFromPoint|elementsFromPoint|:hover|(?:addEventListener|\.on)\s*\(\s*(?:\w+\s*,\s*)?["'`](?:mouse|pointer|touch|click)|\bon(?:mouse|pointer|touch|click)\w*\s*=/,+ "rule 01. The figure listens to the pointer itself or measures what is on screen. Take the pointer from HL.pointer(stage, { move, leave }) and test it against the rest or target pose, in world units."],+];++/** What a figure must contain. */+const NEED = [+ ["clock", /\bregister\s*\(/, "rule 07. The figure never joins the kernel's loop. Draw inside HL.register(stage, tick), and give its unregister to destroy."],+ ["hit", /\bpointer\s*\(/, "the figure never listens to the pointer. Call HL.pointer(stage, { move, leave }) and answer it."],+ ["readout", /\bread\.textContent\s*=/, 'the figure never writes the read-out. Set read.textContent to what is under the pointer, and to "rest" when nothing is.'],+ ["handle", /\bset\s*[:(]/, "mount must return { set(value), destroy() }, and set is missing. It takes the slider's number."],+ ["handle", /\bdestroy\s*[:(]/, "mount must return { set(value), destroy() }, and destroy is missing. It undoes everything mount did: bag.dispose."],+];++/** The declaration at the end of the file, read as text. */+function declared(code) {+ const say = (what) => `declare: the file must end with hairline({ name, means, rules, range, mount }). ${what}`;+ const m = /\bhairline\s*\(\s*\{([\s\S]*?)\}\s*\)\s*;?\s*$/.exec(code.trimEnd());+ if (!m) return [say("That call is missing, or is not the last statement.")];+ const d = m[1], wrong = [];+ const list = (key) => {+ const a = new RegExp(`\\b${key}:\\s*\\[([^\\]]*)\\]`).exec(d);+ return a ? a[1].split(",").map((s) => s.trim()).filter(Boolean).map(Number) : null;+ };+ if (!/\bname:\s*(["'`])[a-z][a-z0-9-]{1,30}\1/.test(d)) wrong.push("name (lowercase letters, digits and hyphens)");+ if (!/\bmeans:\s*(["'`])(?:(?!\1).){1,140}\1/.test(d)) wrong.push("means (one sentence, at most 140 characters)");+ const rules = list("rules"), range = list("range");+ if (!rules || !rules.length || rules.some((r) => !Number.isInteger(r) || r < 1 || r > 10)) wrong.push("rules (the numbers, 1 to 10, of the rules it leans on)");+ const oneWay = range && range.length === 3 && range.every(Number.isFinite) && range[0] !== range[2] && (range[1] - range[0]) * (range[2] - range[1]) >= 0;+ if (!oneWay) wrong.push("range (three numbers that move one way: the figure's value at intensity 0, 0.5 and 1)");+ if (!/\bmount\b/.test(d)) wrong.push("mount");+ return wrong.length ? [say(`Wrong or missing: ${wrong.join("; ")}.`)] : [];+}++/** Everything wrong with a page, one line each; empty when it passes. */+export function validate(input) {+ const page = unix(input), out = [];++ const kernel = unix(readFileSync(here("./kernel.js"), "utf8")).trimEnd();+ const cut = kernel.indexOf("\n");+ const hash = /sha256:([0-9a-f]{64})/.exec(kernel.slice(0, cut))?.[1];+ if (hash !== createHash("sha256").update(kernel.slice(cut + 1) + "\n").digest("hex")) {+ out.push("kernel: kernel.js in the skill folder has been edited. Install the skill again; the kernel is never changed by hand.");+ }++ const fig = /<script type="module" id="hl-figure">\n([\s\S]*?)\n<\/script>/.exec(page);+ if (!fig) return [...out, "bench: the page has no figure slot. Make it with `node build.mjs <figure.js>`, not by hand."];+ if (!page.includes(kernel)) {+ out.push("kernel: the kernel in the page is not kernel.js. Build again with `node build.mjs`; never edit or retype the kernel.");+ } else if (page.trimEnd() !== assemble(fig[1]).trimEnd()) {+ out.push("bench: the page differs from bench.html outside the figure. Build again with `node build.mjs`; the bench is fixed, and a change belongs in the figure.");+ }++ const src = fig[1], code = bare(src);+ for (const [id, re, say] of BAD) if (re.test(code)) out.push(`${id}: ${say}`);+ for (const [id, re, say] of NEED) if (!re.test(code)) out.push(`${id}: ${say}`);+ out.push(...declared(code));+ const lines = src.split("\n").length;+ if (lines > LIMIT) out.push(`length: the figure is ${lines} lines and the limit is ${LIMIT}. A figure this long is usually two ideas: cut the concept down to one.`);+ return out;+}++/* 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("./validate.mjs"))) {+ const file = process.argv[2];+ if (!file) {+ console.error("usage: node validate.mjs <page.html>");+ process.exit(2);+ }+ let page;+ try { page = readFileSync(file, "utf8"); } catch {+ console.error(`cannot read ${file}`);+ process.exit(2);+ }+ const problems = validate(page);+ if (problems.length) {+ for (const p of problems) console.error(p);+ console.error(`${problems.length} to fix in ${file}`);+ process.exit(1);+ }+ console.log(`ok ${file}: kernel and bench intact, and the figure passes the static checks. Now the look: look.md.`);+}