Isometric line figures that answer the pointer. For React and for anything with a DOM.
Skill: look.mjs takes --source and puts the drawing beside rest on the sheet; look.md asks whether rest still reads as it
Lucas Marques90ba55c9076d
diff --git a/packages/hairline/test/browser/look.spec.ts b/packages/hairline/test/browser/look.spec.tsindex 542fad6..208e980 100644--- a/packages/hairline/test/browser/look.spec.ts+++ b/packages/hairline/test/browser/look.spec.ts@@ -45,6 +45,30 @@ function declaring(keys: string) {test.describe("look.mjs", () => {test.setTimeout(60_000);+ test("--source puts the SVG beside rest on the sheet, and says so", async () => {+ const cwd = mkdtempSync(join(tmpdir(), "hl-look-"));+ const svg = fileURLToPath(new URL("../skill/fixtures/rocket.svg", import.meta.url));+ const plain = mkdtempSync(join(tmpdir(), "hl-look-"));+ const [run, without] = await Promise.all([+ look(cwd, `${SKILL}examples/terrain.js`, "--answer", "30,90,0", "--source", svg),+ look(plain, `${SKILL}examples/terrain.js`, "--answer", "30,90,0"),+ ]);+ expect(run.code, run.out).toBe(0);+ expect(run.out).toMatch(/^source .*rocket\.svg is on the sheet beside rest: look\.md, item 14\.$/m);+ wrote(cwd, "hairline-terrain-look.png");+ /* the sheet with a source is taller than the one without: it has one more row */+ const height = (dir: string) => readFileSync(join(dir, "hairline-terrain-look.png")).readUInt32BE(20);+ expect(height(cwd)).toBeGreaterThan(height(plain) + 300);+ });++ test("--source that cannot be read stops before the browser, with exit 2", async () => {+ const cwd = mkdtempSync(join(tmpdir(), "hl-look-"));+ const run = await look(cwd, `${SKILL}examples/terrain.js`, "--source", join(cwd, "missing.svg"));+ expect(run.code).toBe(2);+ expect(run.out).toMatch(/^look: cannot read the source .*missing\.svg$/m);+ expect(existsSync(join(cwd, "hairline-terrain.html"))).toBe(false);+ });+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-"));diff --git a/packages/hairline/test/skill/shape.test.ts b/packages/hairline/test/skill/shape.test.tsindex 33c73d4..ac04927 100644--- a/packages/hairline/test/skill/shape.test.ts+++ b/packages/hairline/test/skill/shape.test.ts@@ -130,3 +130,10 @@ it("SKILL.md has a step 0 that reads an SVG the person brought, and source.md saexpect(source).toContain("the picture wins");expect(skill.split("\n").length).toBeLessThan(120);});++it("look.md names --source and asks whether rest still reads as the source", () => {+ const look = text("look.md");+ expect(look).toContain("[--source <file.svg>]");+ expect(look).toMatch(/^14\. \*\*Rest still reads as the source\.\*\*/m);+ expect(look.split(/^14\. /m)[1].split("\n")[0]).toMatch(/`source\.md` said must survive/);+});diff --git a/skills/hairline-create/look.md b/skills/hairline-create/look.mdindex 99397e1..dd82dd3 100644--- a/skills/hairline-create/look.md+++ b/skills/hairline-create/look.md@@ -6,7 +6,7 @@ The validator reads text. This is what only eyes can check. Do it every time theFrom the person's working directory:-`node <skill folder>/look.mjs <name>.js --answer x,y,z --edge x,y,z`+`node <skill folder>/look.mjs <name>.js --answer x,y,z --edge x,y,z [--source <file.svg>]`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.@@ -15,6 +15,7 @@ It builds `hairline-<name>.html` and validates it, as `build.mjs` and `validate.- 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.+- `--source <file.svg>`, for a figure made from a drawing the person brought (`source.md`), adds a first row to the sheet: that drawing beside the rest picture, at the same size, labelled `source`. It exits 2, before building anything, when the file cannot be read as an SVG.- 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.@@ -62,6 +63,7 @@ Answer each with yes or no. A no is fixed in the figure before anything is hande11. **No words** (rule 10). Nothing in the drawing is a letter, a digit, an arrow or an icon. In a figure made from a mark, the mark itself and a glyph that is part of it are the exception, and so is a glyph built as a solid that is the figure's whole subject; anything else still fails.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.13. **An empty state says something is missing.** Only for an empty state: in the smallest picture, at rest, with no read-out, can you say what the object would hold and that it holds none?+14. **Rest still reads as the source.** Only for a figure made from a drawing, with `--source`: side by side, a person who knows the drawing names the figure without being told. Check the proportions `source.md` said must survive, one by one; a part the source has and the rest pose lacks is a no, unless you called it decoration.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.diff --git a/skills/hairline-create/look.mjs b/skills/hairline-create/look.mjsindex 9a32fb5..942b41e 100644--- a/skills/hairline-create/look.mjs+++ b/skills/hairline-create/look.mjs@@ -2,7 +2,7 @@/*** 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>]+ * node <skill folder>/look.mjs <name>.js --answer x,y,z [--edge x,y,z [--edge x,y,z]] [--zoom <shot>] [--source <file.svg>]** 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@@ -40,7 +40,7 @@ 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>]";+const USAGE = "usage: node look.mjs <name>.js --answer x,y,z [--edge x,y,z [--edge x,y,z]] [--zoom <shot>] [--source <file.svg>]";/** 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. */@@ -208,8 +208,8 @@ async function open(context, url, trap = false) {}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) {+/** The sheet: rest and answering large, the two thumbnails at their own size beside the themes, then the slider's two ends. With a source, a first row puts the drawing beside rest at the same size. */+function sheet(name, shots, source = null) {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>@@ -222,6 +222,7 @@ function sheet(name, shots) {img { display: block; width: 100%; outline: 1px solid #c9c9ce; }.own img { width: auto; }</style><h1>hairline-${esc(name)} · the look</h1>+${source ? `<div class="row">${cell({ label: `source ${source.file}`, png: source.png })}${cell({ label: "rest", png: by.rest.png })}</div>` : ""}<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>`;@@ -247,8 +248,16 @@ 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, given0 = {}, cwd = process.cwd()) {let { answer = null, edge = [] } = given0;- const { zoom = null } = given0;+ const { zoom = null, source = null } = given0;if (zoom && !SHOTS.some(([s]) => s === zoom)) { console.error(`look: no shot "${zoom}". The shots: ${SHOTS.map(([s]) => s).join(", ")}.`); return 2; }+ /* the source is read before anything is built, so a wrong path costs nothing; read.mjs imports this file, so it is imported here, when needed */+ let sourceXml = null, sourceInfo = null;+ if (source) {+ try { sourceXml = readFileSync(source, "utf8"); } catch { console.error(`look: cannot read the source ${resolve(source)}`); return 2; }+ const { scan } = await import("./read.mjs");+ sourceInfo = scan(sourceXml, basename(source));+ if (sourceInfo.error) { console.error(`look: ${sourceInfo.error}`); return 2; }+ }// 1. the page, built and validatedlet file, page;@@ -331,12 +340,17 @@ export async function look(src, given0 = {}, cwd = process.cwd()) {return png;})();const shots = await Promise.all(taking), zoomOut = zoom ? await zooming : null;+ let sourceShot = null;+ if (sourceXml) {+ const { snapshot } = await import("./read.mjs");+ sourceShot = { file: basename(source), png: (await snapshot(browser, sourceXml, sourceInfo.viewBox)).png };+ }// 4. the sheet, composed in the browserfor (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.setContent(sheet(name, shots, sourceShot));await board.evaluate(() => Promise.all([...document.images].map((i) => i.decode())));await board.screenshot({ path: out, fullPage: true });@@ -417,6 +431,7 @@ export async function look(src, given0 = {}, cwd = process.cwd()) {console.log(`3 answer: ${faint ? "warn" : "ok"}. At 240px the pointer moves ${n0(share * 100)}% of the ink, the pixels drawn in one small picture and not the other, over those drawn at rest${faint ? `; under ${n0(FAINT * 100)}% the answer is hard to see in a thumbnail. A change of colour moves no ink: make the answer move more, or say why a small one is right` : ""}.`);}+ if (sourceShot) console.log(`source ${resolve(source)} is on the sheet beside rest: look.md, item 14.`);console.log(`sheet ${out}`);console.log(`blind ${blindOut} holds the small and small-answer pictures with the name and the read-out hidden, as someone who has not seen the figure would meet it: for item 1, look at it that way, or show it to such a reader.`);if (motionOut) console.log(`motion ${motionOut} is the stage while the answer plays: ${motion.length} pictures, rest first, then each labelled with the ms since the pointer reached the answer point. The sheet shows only pictures that held still, so a part that folds, crosses another part, or jumps between two frames on the way is seen only here: look for one, and fix it in the figure.`);@@ -434,7 +449,7 @@ export const same = (a, b, platform = process.platform) => platform === "win32"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" } } });+ args = parseArgs({ allowPositionals: true, options: { answer: { type: "string" }, edge: { type: "string", multiple: true }, zoom: { type: "string" }, source: { type: "string" } } });} catch (e) {console.error(`${e.message}\n${USAGE}`);process.exit(2);@@ -446,5 +461,5 @@ if (process.argv[1] && same(realpathSync(process.argv[1]), realpathSync(here("./console.error(USAGE);process.exit(2);}- process.exit(await look(src, { answer, edge, zoom: values.zoom ?? null }));+ process.exit(await look(src, { answer, edge, zoom: values.zoom ?? null, source: values.source ?? null }));}diff --git a/skills/hairline-create/read.mjs b/skills/hairline-create/read.mjsindex 9cd5bf8..112f12b 100644--- a/skills/hairline-create/read.mjs+++ b/skills/hairline-create/read.mjs@@ -17,10 +17,11 @@ import { readFileSync, realpathSync, writeFileSync } from "node:fs";import { basename, join, resolve } from "node:path";import { fileURLToPath } from "node:url";import { parseArgs } from "node:util";-import { cacheDir, launch, playwright, same } from "./look.mjs";const here = (p) => fileURLToPath(new URL(p, import.meta.url));const USAGE = "usage: node read.mjs <file.svg> [--name <name>]";+/* look.mjs imports this file while it runs, so this file takes look.mjs only inside read(), and compares paths itself */+const same = (a, b, platform = process.platform) => platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;/** The card lists this many shapes at most; the rest are counted on its last line. */const LISTED = 24;@@ -238,6 +239,7 @@ export async function read(src, given = {}, cwd = process.cwd()) {const name = nameFor(src, given.name ?? null);const txt = join(cwd, `hairline-${name}-source.txt`), png = join(cwd, `hairline-${name}-source.png`);+ const { cacheDir, launch, playwright } = await import("./look.mjs");let browser = null, why = "";try { browser = await launch(playwright(cacheDir())); } catch (e) { why = e.message.split("\n")[0]; }let text;