Isometric line figures that answer the pointer. For React and for anything with a DOM.
Skill: the look is one command, look.mjs, that builds, validates and takes the eight pictures on one sheet
Lucas Marquese47683e5fa01
diff --git a/packages/hairline/test/browser/look.spec.ts b/packages/hairline/test/browser/look.spec.tsnew file mode 100644index 0000000..960c55a--- /dev/null+++ b/packages/hairline/test/browser/look.spec.ts@@ -0,0 +1,65 @@+import { expect, test } from "@playwright/test";+import { execFile } from "node:child_process";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs";+import { createRequire } from "node:module";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++/**+ * The skill's look.mjs, run as an agent runs it: from a working directory, on+ * the examples and on a figure that throws. Its cache is a folder holding this+ * repo's playwright-core, so nothing is installed, and it drives the same Chrome.+ */+const SKILL = fileURLToPath(new URL("../../../../skills/hairline-create/", import.meta.url));+const from = (pkg: string, at: string) => createRequire(at).resolve(pkg + "/package.json");+const CORE = dirname(from("playwright-core", from("playwright", from("@playwright/test", import.meta.url))));++const cache = mkdtempSync(join(tmpdir(), "hl-look-cache-"));+mkdirSync(join(cache, "node_modules"));+symlinkSync(CORE, join(cache, "node_modules", "playwright-core"), "dir");++type Run = { code: number; out: string };+/** look.mjs with these arguments, in a fresh working directory. */+function look(cwd: string, ...args: string[]): Promise<Run> {+ return new Promise((done) => {+ execFile("node", [SKILL + "look.mjs", ...args], { cwd, env: { ...process.env, HAIRLINE_LOOK_CACHE: cache }, timeout: 50_000 }, (err, stdout, stderr) => {+ done({ code: err ? (typeof err.code === "number" ? err.code : -1) : 0, out: stdout + stderr });+ });+ });+}+const PNG = "89504e470d0a1a0a";++test.describe("look.mjs", () => {+ test.setTimeout(60_000);++ for (const [name, answer, read] of [["terrain", "30,90,0", "cell 2·6"], ["riffle", "42,28,52", "05"]]) {+ test(`passes ${name}, writes its sheet and prints the read-outs`, async () => {+ const cwd = mkdtempSync(join(tmpdir(), "hl-look-"));+ const run = await look(cwd, `${SKILL}examples/${name}.js`, "--answer", answer, "--zoom", "answer");+ expect(run.code, run.out).toBe(0);+ expect(run.out).toMatch(new RegExp(`^answer ${answer} -> at=\\d+,\\d+$`, "m"));+ expect(run.out).toMatch(/^9 frame: ok\. /m);+ expect(run.out).toMatch(/^8 read-out: ok\. rest "rest", answer "/m);+ expect(run.out).toContain(`answer "${read}"`);+ expect(run.out).toMatch(/^12 console: ok\. /m);+ /* 4 is information: a busy machine can say moving, so only its shape is held */+ expect(run.out).toMatch(/^4 flicker: (still|moving)\. .* Information, not a check: look\.md, item 4\.$/m);+ for (const png of [`hairline-${name}-look.png`, `hairline-${name}-answer.png`]) {+ expect(existsSync(join(cwd, png)), png).toBe(true);+ expect(readFileSync(join(cwd, png)).subarray(0, 8).toString("hex"), png).toBe(PNG);+ }+ });+ }++ test("fails a figure that throws when it mounts", async () => {+ const cwd = mkdtempSync(join(tmpdir(), "hl-look-"));+ const src = readFileSync(SKILL + "examples/terrain.js", "utf8").replace(/^(function mount\(.*\{)$/m, '$1\n throw new Error("no drawing today");');+ expect(src).toContain("no drawing today");+ writeFileSync(join(cwd, "terrain.js"), src);+ const run = await look(cwd, "terrain.js", "--answer", "30,90,0");+ expect(run.code, run.out).toBe(1);+ expect(run.out).toMatch(/^12 console: fail/m);+ expect(run.out).toContain("no drawing today");+ });+});diff --git a/packages/hairline/test/skill/shape.test.ts b/packages/hairline/test/skill/shape.test.tsindex bc7e23e..3b25f82 100644--- a/packages/hairline/test/skill/shape.test.ts+++ b/packages/hairline/test/skill/shape.test.ts@@ -7,10 +7,10 @@ import { expect, it } from "vitest";/** The skill folder is what an agent installs: these hold its shape. */const SKILL = fileURLToPath(new URL("../../../../skills/hairline-create/", import.meta.url));-const FILES = ["SKILL.md", "bench.html", "build.mjs", "concepts.md", "examples/riffle.js", "examples/terrain.js", "kernel.js", "look.md", "rules.md", "validate.mjs"];+const FILES = ["SKILL.md", "bench.html", "build.mjs", "concepts.md", "examples/riffle.js", "examples/terrain.js", "kernel.js", "look.md", "look.mjs", "rules.md", "validate.mjs"];const text = (p: string) => readFileSync(SKILL + p, "utf8");-it("holds exactly its ten files", () => {+it("holds exactly its eleven files", () => {const found = (readdirSync(SKILL, { recursive: true, withFileTypes: true }) as import("node:fs").Dirent[]).filter((e) => e.isFile()).map((e) => (e.parentPath + "/" + e.name).slice(SKILL.length).replace(/^\//, ""));@@ -61,13 +61,22 @@ it("look.md runs build.mjs by its path in the skill folder, as SKILL.md says, soexpect(text("look.md")).not.toMatch(/`node build\.mjs /);});-it("look.md's look.mjs is one script Node can parse, which reads the console and prints ?at= points", () => {- const blocks = [...text("look.md").matchAll(/^```js\n([\s\S]*?)^```$/gm)].map((m) => m[1]);- expect(blocks).toHaveLength(1);- for (const want of ['from "playwright"', '"pageerror"', '"warning"', "waitForTimeout(1500)", "window.P", "process.exit"]) expect(blocks[0], want).toContain(want);- const file = join(mkdtempSync(join(tmpdir(), "hl-look-")), "look.mjs");- writeFileSync(file, blocks[0]);- const run = spawnSync("node", ["--check", file], { encoding: "utf8" });+it("look.mjs is one script Node can parse, and look.md runs it instead of holding one of its own", () => {+ const run = spawnSync("node", ["--check", SKILL + "look.mjs"], { encoding: "utf8" });expect(run.stderr).toBe("");expect(run.status).toBe(0);+ expect(text("look.md")).not.toMatch(/^```js$/m);+ expect(text("look.md")).toContain("`node <skill folder>/look.mjs <name>.js --answer");+ for (const want of ["\"pageerror\"", "\"warning\"", "window.P", "WAIT = 1500", "process.exit"]) expect(text("look.mjs"), want).toContain(want);+});++it("look.mjs reads points as world or viewBox points, and keeps its cache outside the skill", async () => {+ const look = await import(SKILL + "look.mjs");+ expect(look.point("42,28,52")).toEqual([42, 28, 52]);+ expect(look.point("220,120")).toEqual([220, 120]);+ for (const bad of ["", "1", "1,2,3,4", "a,b", "1,,2"]) expect(look.point(bad), bad).toBeNull();+ expect(look.cacheDir({ HAIRLINE_LOOK_CACHE: "/x" }, "linux", "/h")).toBe("/x");+ expect(look.cacheDir({}, "darwin", "/h")).toBe(join("/h", "Library", "Caches", "hairline-look"));+ expect(look.cacheDir({}, "linux", "/h")).toBe(join("/h", ".cache", "hairline-look"));+ expect(look.SHOTS.map((s: string[]) => s[0])).toEqual(["rest", "answer", "small", "small-answer", "low", "high", "dark", "light"]);});diff --git a/skills/hairline-create/SKILL.md b/skills/hairline-create/SKILL.mdindex be94800..bcd066c 100644--- a/skills/hairline-create/SKILL.md+++ b/skills/hairline-create/SKILL.md@@ -10,7 +10,7 @@ You are making one figure in the Hairline style: an isometric line drawing, builYou write one thing: the figure. The engine (`kernel.js`) and the page (`bench.html`) are fixed. Never edit them, never paste a changed copy of them, and never write again what the kernel already gives you.-Every file named below is in this skill's folder. The figure and the page are written in the person's working directory: run `build.mjs` and `validate.mjs` from there, by their path in this folder.+Every file named below is in this skill's folder. The figure and the page are written in the person's working directory: run `build.mjs`, `validate.mjs` and `look.mjs` from there, by their path in this folder.## 1. Concept@@ -32,12 +32,14 @@ One figure, one idea. A concept that needs a label to be understood is not a con- `means`: one sentence, 140 characters at most, saying what the figure shows. It is the line under the stage.- `rules`: the numbers of the rules this figure leans on most.- `range`: the one number the slider drives, at intensity 0, 0.5 and 1. The middle one is the default, and the three move one way. `mount`'s `value`, and the `value` that `set(value)` gets when the slider moves, is this number: the figure's own, read on `range`, not 0 to 1.-5. Assemble it: `node build.mjs <name>.js` writes `hairline-<name>.html`. Without Node, copy `bench.html` and put the contents of `kernel.js` where `/*KERNEL*/` is and your figure where `/*FIGURE*/` is, by file operation, changing nothing else.+5. Assemble it: `node build.mjs <name>.js` writes `hairline-<name>.html`, and so does each run of `look.mjs` in step 3. Without Node, copy `bench.html` and put the contents of `kernel.js` where `/*KERNEL*/` is and your figure where `/*FIGURE*/` is, by file operation, changing nothing else.## 3. Check-1. `node validate.mjs hairline-<name>.html`. Fix every line it prints, build again, run it again. Without Node, read the list of checks at the top of `validate.mjs` and answer each one from your code.-2. The look: follow `look.md`. Fix what fails, then go back to 1.+1. `node look.mjs <name>.js --answer x,y,z --edge x,y,z`, the points being world points of your figure, as `look.md` says. It builds the page, validates it, takes the eight pictures on one sheet, `hairline-<name>-look.png`, and checks the frame, the read-out and the console. Fix every line it prints as failed, and run it again until it exits 0.+2. Read `look.md`, then the sheet, and answer its twelve questions. Fix what fails, then go back to 1.++`look.mjs` needs a browser and installs `playwright-core` once, outside this folder. Without one, check with `node validate.mjs hairline-<name>.html` after each build and do the look as `look.md` says under "Without a browser". Without Node, read the list of checks at the top of `validate.mjs` and answer each one from your code.Do not hand over a page the validator rejects. Do not say the look is done if you did not look.@@ -51,7 +53,7 @@ Publish `hairline-<name>.html` as an artifact if you can. If you cannot, leave t## 5. Adjust-When the person asks for a change, edit only `<name>.js`, then build, validate and look again. The tenth version is held to the same bar as the first.+When the person asks for a change, edit only `<name>.js`, then run `look.mjs` again and read the new sheet. The tenth version is held to the same bar as the first.## What goes wrongdiff --git a/skills/hairline-create/look.md b/skills/hairline-create/look.mdindex c0df0bc..3f08aa5 100644--- a/skills/hairline-create/look.md+++ b/skills/hairline-create/look.md@@ -2,84 +2,67 @@The validator reads text. This is what only eyes can check. Do it every time the figure changes.-## Pictures+## One command-Open `hairline-<name>.html` in a browser and take the four base pictures, then the four for items 9 and 10. Four parameters in the address help; join two with `&`:+From the person's working directory:++`node <skill folder>/look.mjs <name>.js --answer x,y,z --edge x,y,z`++It builds `hairline-<name>.html` and validates it, as `build.mjs` and `validate.mjs` do. If the validator rejects the page, it prints the lines to fix and stops before opening a browser. Otherwise it opens the eight pictures of the table below at once, in one browser, takes each once its drawing holds still, and writes them, labelled, on one sheet: `hairline-<name>-look.png`. Then it prints one line for each of items 9, 8, 12 and 4, and the sheet's path. It exits 1 when the validator rejects the page or item 9, 8 or 12 fails, and 0 otherwise. Read every line it prints, then read the sheet and answer the rest.++- `--answer x,y,z` is a world point on the part that should answer the pointer: a point on the part's top in its rest pose. `look.mjs` runs it through the `P` your figure made with its own camera and prints the `?at=` point it got. For the riffle example, the top edge of card 05 at rest: `--answer 42,28,52` prints `answer 42,28,52 -> at=220,120`, and the answering pictures read `05`.+- `--edge x,y,z` is a world point at the figure's edge, for the slider's two ends (item 9). Give it twice for a point per end: the first is taken at intensity 0, the second at 1. Without it, the ends hold the `--answer` point.+- Either takes a viewBox point `x,y` instead, used as it is.+- Without `--answer`, the answering pictures are taken at rest, and it says so. That is not a finished look.+- `--zoom <shot>` also writes one picture's stage at three times the pixels, as `hairline-<name>-<shot>.png`, for what is too small on the sheet: a crease, a far edge, a dot. The shots are `rest`, `answer`, `small`, `small-answer`, `low`, `high`, `dark` and `light`, in the table's order.+- In place of `<name>.js` it takes a page already built, `hairline-<name>.html`.++A change that moves the fit or the scale moves every `?at=` point with it. The world points stay where they are: give the same ones again and the new `?at=` points come out.++The first run installs `playwright-core` once, into a cache folder of yours (`~/Library/Caches/hairline-look` on macOS, `%LOCALAPPDATA%\hairline-look` on Windows, `~/.cache/hairline-look` elsewhere; `HAIRLINE_LOOK_CACHE` moves it), and never into the skill or the working directory. It drives your Chrome, or Playwright's Chromium when there is no Chrome. With neither, it prints the one command that installs Chromium and exits 2. It exits 2 as well when it cannot install; then do the look as "Without a browser" says.++## The pictures++These are the eight `look.mjs` takes. Four parameters in the address make them, and they work in any browser, for a look by hand; join two with `&`:- `?w=240` narrows the page to 240px, the size of a thumbnail.-- `?at=x,y` holds the pointer at a point of the 400 × 320 viewBox, for tools that cannot hover. x runs to the right and y down, from the viewBox's top-left corner. Take the point from your own figure: the screen point `P(x, y, z)` of the part you want answered, rounded. `P` exists only inside the page; `look.mjs`, below, prints it for you.+- `?at=x,y` holds the pointer at a point of the 400 × 320 viewBox, for tools that cannot hover. x runs to the right and y down, from the viewBox's top-left corner. Take the point from your own figure: the screen point `P(x, y, z)` of the part you want answered, rounded. `P` exists only inside the page; `look.mjs` prints it for you.- `?intensity=` sets the slider, from 0 to 1, before the figure mounts.- `?theme=light` or `?theme=dark` sets the theme, as pressing its button does.-| Picture | Address |-| --- | --- |-| full size, at rest | `hairline-<name>.html` |-| full size, answering | `hairline-<name>.html?at=<x>,<y>` |-| 240px, at rest | `hairline-<name>.html?w=240` |-| 240px, answering | `hairline-<name>.html?w=240&at=<x>,<y>` |-| slider at 0, pointer at the figure's edge (item 9) | `hairline-<name>.html?intensity=0&at=<x>,<y>` |-| slider at 1, pointer at the figure's edge (item 9) | `hairline-<name>.html?intensity=1&at=<x>,<y>` |-| dark theme, answering (item 10) | `hairline-<name>.html?theme=dark&at=<x>,<y>` |-| light theme, answering (item 10) | `hairline-<name>.html?theme=light&at=<x>,<y>` |--Keep the window at least 800 × 900 for every picture. `?w=240` narrows the page, not the window. A headless Chrome window narrower than 500px still lays the page out 500px wide and keeps only its left part, so the small picture comes out cropped.--Wait 1.5 seconds after loading before each picture. Strokes fade over 260ms, tweens take 700ms and springs about a second, so a picture taken sooner catches the figure mid-way. In a browser you drive, wait in your script. Chrome's command line (`--screenshot`) fires at load and does not land the motion, with `--virtual-time-budget` or without. Playwright's command line does, with the window and the wait in one command:--`npx playwright screenshot --channel chrome --viewport-size "800, 900" --wait-for-timeout 1500 "file:///<path>/hairline-<name>.html?at=<x>,<y>" shot.png`--It needs Node and an installed Chrome; without Chrome, run `npx playwright install chromium` once and drop `--channel chrome` from the command.--## The console and the points--That command cannot show the console, which item 12 needs. Make a folder of its own, run `npm i playwright` in it once, and paste this into `look.mjs` there:--```js-import { chromium } from "playwright";-const [url, ...points] = process.argv.slice(2);-const browser = await chromium.launch({ channel: "chrome" }).catch(() => chromium.launch());-const page = await browser.newPage({ viewport: { width: 800, height: 900 } });-const bad = [];-page.on("console", (m) => { if (m.type() === "error" || m.type() === "warning") bad.push(`console ${m.type()}: ${m.text()}`); });-page.on("pageerror", (e) => bad.push(`page error: ${e.message}`));-// keeps the P the figure makes from its own camera, so a world point can be turned into an ?at= point-await page.addInitScript(() => {- let hl;- Object.defineProperty(window, "HL", { get: () => hl, set: (v) => { hl = { ...v, proj: (C) => (window.P = v.proj(C)) }; } });-});-await page.goto(url);-await page.waitForTimeout(1500);-for (const p of points) console.log(`${p} -> at=${(await page.evaluate((q) => window.P(...q), p.split(",").map(Number))).map(Math.round)}`);-console.log(`read-out: ${await page.textContent("#read")}`);-for (const line of bad) console.log(line);-await browser.close();-process.exit(bad.length ? 1 : 0);-```--`node look.mjs "file:///<path>/hairline-<name>.html"`, run from that folder, opens the page at 800 × 900, waits 1.5 seconds, and prints the read-out and every console error, console warning and page error. It exits 1 if there was any. It uses your Chrome, or Playwright's Chromium if there is no Chrome (`npx playwright install chromium` once).--For an `?at=` point, put world points `x,y,z` after the address. The script runs each through the `P` your figure made with its own camera. Take a point on the part's top in its rest pose. For the riffle example, the top edge of card 05 at rest: `node look.mjs "file:///<path>/hairline-riffle.html" 42,28,52` prints `42,28,52 -> at=220,120`. Then check the point: `node look.mjs "file:///<path>/hairline-riffle.html?at=220,120"` prints `read-out: 05`.--A change that moves the fit or the scale moves every `?at=` point with it. Take the points again from the figure, with the script, before the next pictures.+| Shot | Picture | Address |+| --- | --- | --- |+| `rest` | full size, at rest | `hairline-<name>.html` |+| `answer` | full size, answering | `hairline-<name>.html?at=<x>,<y>` |+| `small` | 240px, at rest | `hairline-<name>.html?w=240` |+| `small-answer` | 240px, answering | `hairline-<name>.html?w=240&at=<x>,<y>` |+| `low` | slider at 0, pointer at the figure's edge (item 9) | `hairline-<name>.html?intensity=0&at=<x>,<y>` |+| `high` | slider at 1, pointer at the figure's edge (item 9) | `hairline-<name>.html?intensity=1&at=<x>,<y>` |+| `dark` | dark theme, answering (item 10) | `hairline-<name>.html?theme=dark&at=<x>,<y>` |+| `light` | light theme, answering (item 10) | `hairline-<name>.html?theme=light&at=<x>,<y>` |++By hand, keep the window at least 800 × 900 for every picture. `?w=240` narrows the page, not the window. A headless Chrome window narrower than 500px still lays the page out 500px wide and keeps only its left part, so the small picture comes out cropped. And wait 1.5 seconds after loading before each picture: strokes fade over 260ms, tweens take 700ms and springs about a second, so a picture taken sooner catches the figure mid-way.++On the sheet, `rest` and `answer` are large; `small` and `small-answer` are at their own size, 240px, beside `dark` and `light`; `low` and `high` close it. Each picture keeps the plate, the controls and the line under the stage, and its label holds the address and the read-out.## What to see-Answer each with yes or no. A no is fixed in the figure before anything is handed over.+Answer each with yes or no. A no is fixed in the figure before anything is handed over. `look.mjs` answers 8, 9 and 12, and measures part of 4; the rest are answered from the sheet. Zoom when a line is too small to judge.1. **The silhouette reads at 240px.** You can say what the object is from the small picture alone.2. **Rest is a composition** (rule 05). Not flat, not empty, not a regular grid; something is bright where the eye should start.3. **The answer falls off with distance, or spreads out from the pointer** (rules 02 and 03). It is not everything at once, and not one part alone.-4. **Nothing flickers** (rule 01). Hold `at` on an edge that moves when touched and take two pictures a second apart: they are the same. `at` moves the pointer once, so also read the hit test: it picks from the rest pose or the target, never from the pose on screen.+4. **Nothing flickers** (rule 01). With the pointer held on a part that moves when touched, the drawing comes to rest. `look.mjs` waits 1.5 seconds after each page loads, then until its drawing holds still for a quarter of a second, for 5 seconds at most. `still` is a yes, and says how long the slowest took. `moving` names the pictures that never held still: answering pictures moving while rest held still is a flicker loop; every picture moving is an ambient figure, or a loop that never ends. A machine too busy to keep up says `moving` too, so run it again before you believe it. `at` moves the pointer once, so also read the hit test: it picks from the rest pose or the target, never from the pose on screen.5. **Bright outside, dim inside** (rule 09). Every solid is a silhouette and one crease; no vertical corner is drawn; no corner is sharp.6. **Nothing shows through** (rule 06). No far edge crosses a near solid; no guide crosses its own plate.7. **One highlight** (rule 04). At rest, one bright mark says where the eye should start. When the pointer chooses, the bright goes to what it chose and the rest mark gives it up. One highlight may cover the parts of one thing, a tray's rim and its beads, but it marks one place and means one thing. It is a stroke or a dot, never a fill.-8. **The read-out names what is under the pointer**, in a few characters, and says `rest` at rest.-9. **Nothing leaves the frame.** With the slider at each end (`?intensity=0`, `?intensity=1`) and the pointer at the figure's edges, every part stays inside the plate.+8. **The read-out names what is under the pointer**, in a few characters, and says `rest` at rest. `look.mjs` prints every picture's read-out, and fails when the rest picture's is not `rest`. A warning that an answering picture still says `rest` means the `--answer` point misses the part, or the hit test does. Whether the name is right is for you to say.+9. **Nothing leaves the frame.** With the slider at each end (`?intensity=0`, `?intensity=1`) and the pointer at the figure's edges, every part stays inside the plate. `look.mjs` fails when the drawing's box leaves the 400 × 320 viewBox in any picture. The box is the geometry: a stroke reaches half its width past it, so a line on the frame's edge is still a no. It also says how much of the frame the rest pose covers, and warns below a quarter; the examples cover 36%.10. **Both themes.** In `?theme=dark` and `?theme=light`, nothing vanishes and nothing is left the wrong colour.11. **No words** (rule 10). Nothing in the drawing is a letter, a digit, an arrow or an icon.-12. **The page is clean.** No line under the stage reporting an error, and nothing on the console: `look.mjs` exits 0.+12. **The page is clean.** No line under the stage reporting an error, and nothing on the console. `look.mjs` reads both, on every picture, and fails on any console error, console warning or page error.-If you are unsure whether the figure's weight is right, build an example the same way and put the two side by side: `node <skill folder>/build.mjs <skill folder>/examples/terrain.js`.+If you are unsure whether the figure's weight is right, build an example the same way and put the two side by side: `node <skill folder>/build.mjs <skill folder>/examples/terrain.js`. Or look at it: `node <skill folder>/look.mjs <skill folder>/examples/terrain.js --answer 30,90,0` writes its sheet beside yours.## Without a browserdiff --git a/skills/hairline-create/look.mjs b/skills/hairline-create/look.mjsnew file mode 100644index 0000000..d4b409b--- /dev/null+++ b/skills/hairline-create/look.mjs@@ -0,0 +1,311 @@+#!/usr/bin/env node+/**+ * The look in one command, run from the person's working directory:+ *+ * node <skill folder>/look.mjs <name>.js --answer x,y,z [--edge x,y,z [--edge x,y,z]] [--zoom <shot>]+ *+ * It builds and validates the page as build.mjs and validate.mjs do, opens+ * look.md's eight addresses at once in one browser, and writes the eight+ * pictures, labelled, on one sheet: hairline-<name>-look.png. Then it prints+ * what can be measured, one line each, under look.md's item numbers: 9 the+ * frame, 8 the read-out, 12 the console, 4 the flicker. It exits 1 when the+ * validator rejects the page or one of those fails, 2 when it cannot run, and+ * 0 otherwise. Everything else is for eyes, on the sheet.+ *+ * A point is a world point x,y,z, run through the P the figure made with its+ * own camera, or a viewBox point x,y, taken as it is. --answer is on the part+ * that should answer the pointer. --edge is at the figure's edge, for the two+ * ends of the slider; given twice, the first is for intensity 0 and the second+ * for 1. --zoom writes one shot's stage at three times the pixels.+ *+ * The browser is Playwright's. playwright-core is installed once into a cache+ * folder of the user's (HAIRLINE_LOOK_CACHE moves it), never into the skill or+ * the working directory, and it drives the installed Chrome, or Playwright's+ * own Chromium when there is no Chrome.+ */+import { spawnSync } from "node:child_process";+import { mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";+import { createRequire } from "node:module";+import { homedir } from "node:os";+import { basename, dirname, join, resolve } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import { parseArgs } from "node:util";+import { assemble, nameOf } from "./build.mjs";+import { validate } from "./validate.mjs";++const here = (p) => fileURLToPath(new URL(p, import.meta.url));+const USAGE = "usage: node look.mjs <name>.js --answer x,y,z [--edge x,y,z [--edge x,y,z]] [--zoom <shot>]";+/** Each picture waits 1.5 seconds after its page loads, then until its drawing holds still for a quarter of a second, and no longer than 5 seconds from the load. */+const WAIT = 1500, STILL = 250, CAP = 5000;+/** A rest pose whose box covers less of the frame than this is reported as small. Both examples' rest boxes cover 36%: Terrain's 297 × 155, Riffle's 226 × 205. */+const SMALL = 0.25;++/** look.md's eight pictures, in its order: the shot's name, what it adds to the address, and which point it holds. */+export const SHOTS = [+ ["rest", "", null],+ ["answer", "", "answer"],+ ["small", "w=240", null],+ ["small-answer", "w=240", "answer"],+ ["low", "intensity=0", "low"],+ ["high", "intensity=1", "high"],+ ["dark", "theme=dark", "answer"],+ ["light", "theme=light", "answer"],+];++/** The folder playwright-core is installed into: the user's cache folder, or HAIRLINE_LOOK_CACHE. */+export function cacheDir(env = process.env, platform = process.platform, home = homedir()) {+ if (env.HAIRLINE_LOOK_CACHE) return resolve(env.HAIRLINE_LOOK_CACHE);+ if (platform === "darwin") return join(home, "Library", "Caches", "hairline-look");+ if (platform === "win32") return join(env.LOCALAPPDATA || join(home, "AppData", "Local"), "hairline-look");+ return join(env.XDG_CACHE_HOME || join(home, ".cache"), "hairline-look");+}++/** A point given on the command line: three numbers for the world, two for the viewBox, or null. */+export function point(s) {+ const n = String(s ?? "").split(",").map((v) => (v.trim() === "" ? NaN : Number(v)));+ return (n.length === 2 || n.length === 3) && n.every(Number.isFinite) ? n : null;+}++/** playwright-core from the cache, installed there first when it is not. Throws with a reason when it cannot be had. */+function playwright(dir) {+ const req = createRequire(join(dir, "look.cjs"));+ const has = () => { try { return req.resolve("playwright-core/package.json"); } catch { return null; } };+ if (!has()) {+ console.log(`installing playwright-core once, into ${dir}`);+ mkdirSync(dir, { recursive: true });+ try { writeFileSync(join(dir, "package.json"), '{ "private": true }\n', { flag: "wx" }); } catch { /* already there */ }+ const win = process.platform === "win32";+ const run = spawnSync(win ? "npm.cmd" : "npm", ["install", "playwright-core@1", "--prefix", dir, "--no-audit", "--no-fund", "--loglevel=error"], { encoding: "utf8", shell: win });+ const why = run.error?.code === "ENOENT" ? "npm is not on the PATH" : run.error?.message ?? /Error: (.*)$/m.exec(run.stderr)?.[1] ?? run.stderr.trim().split("\n")[0];+ if (run.status !== 0 || !has()) throw new Error(why || "npm failed");+ }+ return { chromium: req("playwright-core").chromium, cli: join(dirname(has()), "cli.js") };+}++/* Keeps the P the figure makes from its own camera, so a world point can be turned into an ?at= point. */+const TRAP = () => {+ let hl;+ Object.defineProperty(window, "HL", { configurable: true, get: () => hl, set: (v) => { hl = { ...v, proj: (C) => (window.P = v.proj(C)) }; } });+};++/**+ * What the page shows after the wait: the drawing's box in viewBox units, the+ * read-out, the line under the stage, and the part of the page a picture+ * keeps, from the plate's top to the last line under it. The box is getBBox's,+ * so it is geometry: a stroke reaches half its width past it.+ */+const STATE = () => {+ const $ = (s) => document.querySelector(s), svg = $("#stage > svg"), err = $("#error");+ const b = svg && svg.childElementCount ? svg.getBBox() : null;+ const plate = $(".plate").getBoundingClientRect();+ const bottom = Math.max(...["#means", "#error"].map((s) => $(s)).filter((el) => !el.hidden).map((el) => el.getBoundingClientRect().bottom));+ return {+ box: b && { x: b.x, y: b.y, w: b.width, h: b.height },+ read: $("#read").textContent,+ error: err.hidden ? "" : err.textContent,+ clip: { x: Math.max(0, plate.left - 8), y: Math.max(0, plate.top - 8), width: plate.width + 16, height: bottom - plate.top + 16 },+ stage: { x: plate.left, y: plate.top, width: plate.width, height: plate.height },+ };+};++/** A browser context with look.md's window: 800 × 900, so ?w=240 narrows the page and not the window. */+const window800 = (browser, scale = 1) => browser.newContext({ viewport: { width: 800, height: 900 }, deviceScaleFactor: scale, colorScheme: "light" });+const sleep = (ms) => new Promise((done) => setTimeout(done, ms));+const drawing = (page) => page.evaluate(() => document.querySelector("#stage > svg")?.innerHTML ?? "");++/** Waits out the settle, then until the drawing holds still. Returns the seconds from the load to the still drawing, or null when it never held still. */+async function settle({ page, loaded }) {+ await sleep(loaded + WAIT - Date.now());+ for (let was = await drawing(page); Date.now() + STILL - loaded <= CAP;) {+ await sleep(STILL);+ const now = await drawing(page);+ if (now === was) return (Date.now() - loaded) / 1000;+ was = now;+ }+ return null;+}++/**+ * Opens a page and collects what it says on the console. The pages of one+ * context are each laid out in a viewport of their own, so every figure's+ * IntersectionObserver finds it on screen and its loop runs.+ */+async function open(context, url, trap = false) {+ const page = await context.newPage(), bad = [];+ page.on("console", (m) => { if (m.type() === "error" || m.type() === "warning") bad.push(`console ${m.type()}: ${m.text()}`); });+ page.on("pageerror", (e) => bad.push(`page error: ${e.message}`));+ if (trap) await page.addInitScript(TRAP);+ await page.goto(url);+ return { page, bad, loaded: Date.now() };+}++const esc = (s) => String(s).replace(/[&<>"]/g, (c) => `&#${c.charCodeAt(0)};`);+/** The sheet: rest and answering large, the two thumbnails at their own size beside the themes, then the slider's two ends. */+function sheet(name, shots) {+ const cell = (s, cls = "") => `<figure class="${cls}"><figcaption>${esc(s.label)}</figcaption><img src="data:image/png;base64,${s.png}"></figure>`;+ const by = Object.fromEntries(shots.map((s) => [s.name, s]));+ return `<!doctype html><meta charset="utf-8"><style>+ body { margin: 0; padding: 16px; width: 1400px; box-sizing: border-box; background: #ececef; color: #18181b; font: 13px/1.3 ui-monospace, Menlo, Consolas, monospace; }+ h1 { font: inherit; margin: 0 0 10px; color: #55555c; }+ .row { display: flex; gap: 16px; align-items: flex-start; margin-bottom: 16px; }+ figure { margin: 0; flex: 1 1 0; min-width: 0; }+ figure.own { flex: 0 0 272px; }+ figcaption { margin: 0 0 6px; overflow-wrap: anywhere; }+ img { display: block; width: 100%; outline: 1px solid #c9c9ce; }+ .own img { width: auto; }+</style><h1>hairline-${esc(name)} · the look</h1>+<div class="row">${cell(by.rest)}${cell(by.answer)}</div>+<div class="row">${cell(by.small, "own")}${cell(by["small-answer"], "own")}${cell(by.dark)}${cell(by.light)}</div>+<div class="row">${cell(by.low)}${cell(by.high)}</div>`;+}++/** Whether a box leaves the 400 × 320 viewBox. */+const outside = (b) => b.x < 0 || b.y < 0 || b.x + b.w > 400 || b.y + b.h > 320;+const n0 = (v) => Math.round(v);++/** The look of one figure (a .js, built here, or a page build.mjs made). Prints as it goes and returns the exit code. */+export async function look(src, { answer = null, edge = [], zoom = null } = {}, cwd = process.cwd()) {+ if (zoom && !SHOTS.some(([s]) => s === zoom)) { console.error(`look: no shot "${zoom}". The shots: ${SHOTS.map(([s]) => s).join(", ")}.`); return 2; }++ // 1. the page, built and validated+ let file, page;+ try { page = readFileSync(src, "utf8"); } catch { console.error(`look: cannot read ${src}`); return 2; }+ if (src.endsWith(".html")) file = resolve(src);+ else {+ file = join(cwd, `hairline-${nameOf(page) ?? "figure"}.html`);+ page = assemble(page);+ writeFileSync(file, page);+ }+ const name = /^hairline-(.+)\.html$/.exec(basename(file))?.[1] ?? basename(file, ".html");+ const problems = validate(page);+ if (problems.length) {+ for (const p of problems) console.log(p);+ console.log(`${problems.length} to fix in ${file}. Fix the figure and run this again; no browser was opened.`);+ return 1;+ }+ console.log(`${src.endsWith(".html") ? "read" : "built"} ${file}, and the validator passes it`);++ // the browser, from the cache+ const dir = cacheDir();+ let pw;+ try { pw = playwright(dir); } catch (e) {+ console.error(`look: could not install playwright-core into ${dir}: ${e.message}`);+ console.error('Check the network and run this again, or look without a browser: look.md, "Without a browser".');+ return 2;+ }+ const browser = await pw.chromium.launch({ channel: "chrome" }).catch(() => pw.chromium.launch()).catch(() => null);+ if (!browser) {+ console.error(`look: no Chrome, and no Chromium of Playwright's. Install one once:\n node "${pw.cli}" install chromium`);+ console.error('Then run this again. Without a browser, look.md says what to do: "Without a browser".');+ return 2;+ }++ try {+ const url = pathToFileURL(file).href, address = (q) => (q ? `${url}?${q}` : url);++ // 2. the points, through the figure's own P, from the rest page+ const context = await window800(browser);+ const rest = await open(context, url, true);+ const given = { answer, low: edge[0] ?? answer, high: edge[1] ?? edge[0] ?? answer }, at = {}, said = [];+ for (const [key, p] of Object.entries({ answer, edge0: edge[0], edge1: edge[1] })) {+ if (!p) continue;+ const v = p.length === 2 ? p : await rest.page.evaluate((q) => (window.P ? window.P(...q).map(Math.round) : null), p);+ if (!v) { said.push(`${p} -> no P: the figure stopped before it called HL.proj`); continue; }+ for (const use of Object.keys(given)) if (given[use] === p) at[use] = v.join(",");+ said.push(`${key === "answer" ? "answer" : "edge"} ${p} -> at=${v.join(",")}`);+ }+ if (said.length) console.log(said.join(" · "));+ if (!answer) console.log("no --answer: the answering shots are taken at rest. Give --answer x,y,z, a world point on the part that should answer.");+ else if (!edge.length) console.log("no --edge: the slider's two ends are taken with the pointer at the --answer point.");++ // 3. the other seven, and the zoom, opened at once; each waits from its own load, so the waits overlap+ const queryOf = (q, use) => [q, use && at[use] && `at=${at[use]}`].filter(Boolean).join("&");+ const taking = SHOTS.map(async ([shot, q, use]) => {+ const query = queryOf(q, use);+ const s = { name: shot, query, answering: !!(use && at[use]), ...(shot === "rest" ? rest : await open(context, address(query))) };+ s.held = await settle(s);+ Object.assign(s, await s.page.evaluate(STATE));+ s.png = (await s.page.screenshot({ clip: s.clip })).toString("base64");+ return s;+ });+ const zooming = zoom && (async () => {+ const [, q, use] = SHOTS.find(([s]) => s === zoom), z = await open(await window800(browser, 3), address(queryOf(q, use)));+ await settle(z);+ const png = join(cwd, `hairline-${name}-${zoom}.png`);+ await z.page.screenshot({ path: png, clip: (await z.page.evaluate(STATE)).stage });+ return png;+ })();+ const shots = await Promise.all(taking), zoomOut = zoom ? await zooming : null;++ // 4. the sheet, composed in the browser+ for (const s of shots) s.label = `${s.name} ${s.query ? "?" + s.query : "(plain)"} read: ${s.read}${s.box && outside(s.box) ? " OUT OF FRAME" : ""}`;+ const out = join(cwd, `hairline-${name}-look.png`);+ const board = await (await browser.newContext({ viewport: { width: 1400, height: 800 } })).newPage();+ await board.setContent(sheet(name, shots));+ await board.evaluate(() => Promise.all([...document.images].map((i) => i.decode())));+ await board.screenshot({ path: out, fullPage: true });++ // 5. what can be measured+ let failed = false;+ const fail = (line) => { failed = true; console.log(line); };++ const away = shots.filter((s) => s.box && outside(s.box));+ const box = shots[0].box;+ const fills = box && `Rest fills ${n0(box.w)} × ${n0(box.h)}, ${n0((100 * box.w * box.h) / 128000)}% of it`;+ if (!box) fail("9 frame: fail. The rest shot's svg is empty: the figure drew nothing.");+ else if (away.length) {+ const x0 = Math.min(...away.map((s) => s.box.x)), x1 = Math.max(...away.map((s) => s.box.x + s.box.w));+ const y0 = Math.min(...away.map((s) => s.box.y)), y1 = Math.max(...away.map((s) => s.box.y + s.box.h));+ fail(`9 frame: fail. ${away.length === shots.length ? "Every shot" : away.map((s) => s.name).join(", ")} leaves the 400 × 320 viewBox: the drawing reaches x ${n0(x0)} to ${n0(x1)} and y ${n0(y0)} to ${n0(y1)}.`);+ } else {+ const small = (box.w * box.h) / 128000 < SMALL;+ console.log(`9 frame: ${small ? "warn" : "ok"}. Every shot stays inside the 400 × 320 viewBox. ${fills}${small ? `; the examples' cover 36%. Raise S, or say why the figure is small` : ""}.`);+ }++ const reads = shots.map((s) => `${s.name} "${s.read}"`).join(", ");+ const still = shots.filter((s) => s.answering && ["answer", "small-answer", "dark", "light"].includes(s.name) && s.read === "rest");+ if (shots[0].read !== "rest") fail(`8 read-out: fail. At rest it says "${shots[0].read}", not "rest". ${reads}.`);+ else console.log(`8 read-out: ${still.length ? `warn. ${still.map((s) => s.name).join(", ")} still say "rest": the --answer point is not on the part, or the hit test misses it` : "ok"}. ${reads}.`);++ // each complaint once, with the shots that made it+ const noise = new Map();+ for (const s of shots) for (const b of [...s.bad, ...(s.error ? [`error line under the stage: ${s.error}`] : [])]) noise.set(b, [...(noise.get(b) ?? []), s.name]);+ const heard = [...noise].map(([b, where]) => `${b} (${where.length === shots.length ? "every shot" : where.join(", ")})`);+ if (heard.length) fail(`12 console: fail. ${heard.slice(0, 4).join("; ")}${heard.length > 4 ? `; and ${heard.length - 4} more` : ""}.`);+ else console.log("12 console: ok. No console error or warning, no page error, no error line under the stage.");++ // a drawing that never held still: a flicker loop, an ambient figure, or a machine too busy to finish the motion in time+ const restless = shots.filter((s) => s.held === null), slowest = Math.max(...shots.map((s) => s.held ?? 0));+ console.log(`4 flicker: ${restless.length+ ? `moving. ${restless.length === shots.length ? "Every shot" : restless.map((s) => s.name).join(", ")} still moving ${CAP / 1000} seconds after loading${shots[0].held === null ? "" : ", while rest held still"}`+ : `still. Every shot held still within ${slowest.toFixed(1)} seconds of loading`}. Information, not a check: look.md, item 4.`);++ console.log(`sheet ${out}`);+ if (zoomOut) console.log(`zoom ${zoomOut}`);+ return failed ? 1 : 0;+ } finally {+ await browser.close();+ }+}++/** Whether two resolved paths are one file. Windows paths ignore case, and the drive letter's case can differ between the two. */+export const same = (a, b, platform = process.platform) => platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;++/* The skill is often installed as a symlink, so the path Node was given is resolved before it is compared. */+if (process.argv[1] && same(realpathSync(process.argv[1]), realpathSync(here("./look.mjs")))) {+ let args;+ try {+ args = parseArgs({ allowPositionals: true, options: { answer: { type: "string" }, edge: { type: "string", multiple: true }, zoom: { type: "string" } } });+ } catch (e) {+ console.error(`${e.message}\n${USAGE}`);+ process.exit(2);+ }+ const { positionals: [src], values } = args;+ const answer = values.answer === undefined ? null : point(values.answer);+ const edge = (values.edge ?? []).map(point);+ if (!src || (values.answer !== undefined && !answer) || edge.some((p) => !p) || edge.length > 2) {+ console.error(USAGE);+ process.exit(2);+ }+ process.exit(await look(src, { answer, edge, zoom: values.zoom ?? null }));+}