Skip to content

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

Skill: read.mjs takes the picture and measures the shapes in the look's browser, and runs from the command line

Lucas Marques1d36a5fa8a2a
diff --git a/packages/hairline/test/browser/read.spec.ts b/packages/hairline/test/browser/read.spec.ts
new file mode 100644
index 0000000..6fdbed4
--- /dev/null
+++ b/packages/hairline/test/browser/read.spec.ts
@@ -0,0 +1,104 @@
+import { expect, test } from "@playwright/test";
+import { execFile } from "node:child_process";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync } 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 read.mjs, run as an agent runs it: from a working directory, on
+ * a fixture, with the look's cache 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 FIX = fileURLToPath(new URL("../skill/fixtures/", 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-read-cache-"));
+mkdirSync(join(cache, "node_modules"));
+symlinkSync(CORE, join(cache, "node_modules", "playwright-core"), "dir");
+
+type Run = { code: number; out: string };
+/** read.mjs with these arguments; node is named by its path, so a test can empty the PATH. */
+function read(cwd: string, env: Record<string, string>, ...args: string[]): Promise<Run> {
+ return new Promise((done) => {
+ execFile(process.execPath, [SKILL + "read.mjs", ...args], { cwd, env: { ...process.env, ...env }, 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("read.mjs", () => {
+ test.setTimeout(60_000);
+
+ test("writes the picture and the full card for an icon, and prints the card", async () => {
+ const cwd = mkdtempSync(join(tmpdir(), "hl-read-"));
+ const run = await read(cwd, { HAIRLINE_LOOK_CACHE: cache }, FIX + "rocket.svg");
+ expect(run.code, run.out).toBe(0);
+ const png = join(cwd, "hairline-rocket-source.png"), txt = join(cwd, "hairline-rocket-source.txt");
+ const bytes = readFileSync(png);
+ expect(bytes.subarray(0, 8).toString("hex")).toBe(PNG);
+ /* 400 × 400 CSS pixels, taken at twice the density */
+ expect([bytes.readUInt32BE(16), bytes.readUInt32BE(20)]).toEqual([800, 800]);
+ const card = readFileSync(txt, "utf8");
+ expect(run.out).toContain(card.trimEnd());
+ expect(card.split("\n")[0]).toBe("rocket.svg viewBox 0 0 24 24 (1:1) 5 shapes in 2 groups");
+ expect(card).toContain('title: "Deploy" ids: rocket, body, window, fin-left, fin-right, flame');
+ /* getBBox is geometry: the body's box is the path's, 8..16 × 2..17 */
+ expect(card).toMatch(/^#1 {2}path {4}g#rocket {2}box 8\.\.16 × 2\.\.17 {2}centre 12,9\.5 {2}stroke 1\.5 {2}closed, curves and lines/m);
+ expect(card).toMatch(/^#2 {2}circle {2}g#rocket {2}box 10\.5\.\.13\.5 × 7\.\.10 .* filled {2}closed, curves {2}inside #1, middle$/m);
+ expect(card).toMatch(/^#4 {2}path {4}g#rocket .* mirror of #3$/m);
+ expect(card).toMatch(/^#5 {2}path {4}g#flame .* filled {2}closed, curves {2}below #1, touching$/m);
+ expect(run.out).toMatch(/^picture .*hairline-rocket-source\.png$/m);
+ expect(run.out).toMatch(/^card .*hairline-rocket-source\.txt$/m);
+ });
+
+ test("measures a file with width and height and no viewBox, and leaves <defs> out", async () => {
+ const cwd = mkdtempSync(join(tmpdir(), "hl-read-"));
+ const run = await read(cwd, { HAIRLINE_LOOK_CACHE: cache }, FIX + "mixed.svg", "--name", "Mixed One");
+ expect(run.code, run.out).toBe(0);
+ const card = readFileSync(join(cwd, "hairline-mixed-one-source.txt"), "utf8");
+ expect(card.split("\n")[0]).toBe("mixed.svg viewBox 0 0 48 32 (from width and height) (1.5:1) 2 shapes in 0 groups");
+ /* the rect, and the circle the <use> brings in at 8,8; nothing from <defs> itself */
+ expect(card).toMatch(/^#1 {2}rect /m);
+ expect(card).toMatch(/^#2 {2}use {5}- {9}box 8\.\.12 × 8\.\.12 /m);
+ expect(card).not.toMatch(/^#3 /m);
+ expect(card).toContain("not read: 1 <use> outside the file, 1 <text>, 1 <image>");
+ });
+
+ test("puts a transformed shape where it is drawn, not where its own coordinates say", async () => {
+ const cwd = mkdtempSync(join(tmpdir(), "hl-read-"));
+ const run = await read(cwd, { HAIRLINE_LOOK_CACHE: cache }, FIX + "moved.svg");
+ expect(run.code, run.out).toBe(0);
+ expect(readFileSync(join(cwd, "hairline-moved-source.txt"), "utf8")).toMatch(/^#1 {2}rect {4}g#moved {3}box 20\.\.30 × 40\.\.50 /m);
+ });
+
+ test("without a browser, writes the reduced card, no picture, and exits 0", async () => {
+ const cwd = mkdtempSync(join(tmpdir(), "hl-read-"));
+ /* an empty cache, no npm on the PATH and no NODE_PATH (pnpm sets one): playwright-core cannot be had */
+ const empty = mkdtempSync(join(tmpdir(), "hl-read-nocache-"));
+ const run = await read(cwd, { HAIRLINE_LOOK_CACHE: empty, PATH: "", NODE_PATH: "" }, FIX + "rocket.svg");
+ expect(run.code, run.out).toBe(0);
+ expect(existsSync(join(cwd, "hairline-rocket-source.png"))).toBe(false);
+ const card = readFileSync(join(cwd, "hairline-rocket-source.txt"), "utf8");
+ expect(card).toContain("shapes: 4 path, 1 circle");
+ expect(card).toContain("no browser: boxes and the picture were not taken");
+ expect(run.out).toMatch(/^no browser: /m);
+ });
+
+ test("refuses what it cannot read, with one line and exit 2", async () => {
+ const cwd = mkdtempSync(join(tmpdir(), "hl-read-"));
+ const bad = await read(cwd, { HAIRLINE_LOOK_CACHE: cache }, FIX + "broken.txt");
+ expect(bad.code).toBe(2);
+ expect(bad.out.trim()).toBe("read: broken.txt is not an SVG: no <svg> root");
+ const none = await read(cwd, { HAIRLINE_LOOK_CACHE: cache }, join(cwd, "missing.svg"));
+ expect(none.code).toBe(2);
+ expect(none.out).toMatch(/^read: cannot read .*missing\.svg$/m);
+ const usage = await read(cwd, { HAIRLINE_LOOK_CACHE: cache });
+ expect(usage.code).toBe(2);
+ expect(usage.out).toMatch(/^usage: node read\.mjs <file\.svg> \[--name <name>\]$/m);
+ });
+});
diff --git a/packages/hairline/test/skill/fixtures/moved.svg b/packages/hairline/test/skill/fixtures/moved.svg
new file mode 100644
index 0000000..6ef4b0e
--- /dev/null
+++ b/packages/hairline/test/skill/fixtures/moved.svg
@@ -0,0 +1,5 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
+ <g id="moved" transform="translate(20 40)">
+ <rect x="0" y="0" width="10" height="10" fill="#000"/>
+ </g>
+</svg>
diff --git a/skills/hairline-create/read.mjs b/skills/hairline-create/read.mjs
index 7f7e7d1..9cd5bf8 100644
--- a/skills/hairline-create/read.mjs
+++ b/skills/hairline-create/read.mjs
@@ -13,7 +13,14 @@
* the XML says, and no picture is written. The SVG gives the identity, not
* the paths: nothing here is traced.
*/
-import { basename } from "node:path";
+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>]";
/** The card lists this many shapes at most; the rest are counted on its last line. */
const LISTED = 24;
@@ -161,3 +168,108 @@ export function card(info, shapes = null) {
if (unread.length) lines.push(`not read: ${unread.join(", ")}`);
return lines.slice(0, 30).join("\n");
}
+
+/** The page the picture is taken of: the SVG at 400 × 400 on white, kept whole inside the box. */
+export function page(xml, viewBox) {
+ const svg = xml.replace(/<\?xml[\s\S]*?\?>|<!DOCTYPE[\s\S]*?>/gi, "").replace(/<svg\b([^>]*)>/, (m, attrs) => {
+ const kept = attrs.replace(/\s(width|height|viewBox|preserveAspectRatio)\s*=\s*(?:"[^"]*"|'[^']*')/g, "");
+ return `<svg${kept} viewBox="${viewBox.join(" ")}" width="400" height="400" preserveAspectRatio="xMidYMid meet">`;
+ });
+ return `<!doctype html><meta charset="utf-8"><style>html,body{margin:0;background:#fff}#box{width:400px;height:400px;color:#18181b}#box>svg{display:block}</style><div id="box">${svg}</div>`;
+}
+
+/* Measured in the page: every painted shape in paint order, its box in the root's viewBox units with every transform applied. A <use> that points inside the file is one shape, by what it draws. */
+const MEASURE = () => {
+ const root = document.querySelector("#box > svg");
+ const toRoot = root.getCTM().inverse();
+ const hidden = "defs, symbol, clipPath, mask, pattern, marker";
+ const els = [...root.querySelectorAll("path, rect, circle, ellipse, line, polyline, polygon, use")].filter((el) => !el.parentElement.closest(hidden));
+ const list = [];
+ for (const el of els) {
+ if (el.tagName === "use" && !(el.getAttribute("href") ?? el.getAttribute("xlink:href") ?? "").startsWith("#")) continue;
+ let b;
+ try { b = el.getBBox(); } catch { continue; }
+ if (!(b.width > 0 || b.height > 0)) continue;
+ const m = toRoot.multiply(el.getCTM());
+ const pts = [[b.x, b.y], [b.x + b.width, b.y], [b.x, b.y + b.height], [b.x + b.width, b.y + b.height]].map(([x, y]) => new DOMPoint(x, y).matrixTransform(m));
+ const xs = pts.map((p) => p.x), ys = pts.map((p) => p.y);
+ const x = Math.min(...xs), y = Math.min(...ys);
+ const cs = getComputedStyle(el);
+ const d = el.getAttribute("d") ?? "";
+ const tag = el.tagName;
+ const kind = tag === "path"
+ ? [/[CcSsQqTtAa]/.test(d) && "curves", /[LlHhVv]/.test(d) && "lines"].filter(Boolean).join(" and ")
+ : ["circle", "ellipse"].includes(tag) ? "curves"
+ : tag === "rect" && Number(el.getAttribute("rx") || el.getAttribute("ry") || 0) > 0 ? "curves and lines"
+ : tag === "use" ? "" : "lines";
+ const closed = tag === "path" ? /[Zz]/.test(d) : !["line", "polyline"].includes(tag);
+ const sw = parseFloat(cs.strokeWidth);
+ list.push({
+ i: list.length + 1, type: tag, group: el.parentElement.closest("g[id]")?.id ?? null,
+ box: { x, y, w: Math.max(...xs) - x, h: Math.max(...ys) - y },
+ filled: cs.fill !== "none" && parseFloat(cs.fillOpacity) !== 0,
+ stroke: cs.stroke !== "none" && sw > 0 ? sw : null,
+ closed, kind,
+ });
+ }
+ return list;
+};
+
+/** The picture and the shapes, from a fresh context of a browser the caller owns. */
+export async function snapshot(browser, xml, viewBox) {
+ const context = await browser.newContext({ viewport: { width: 400, height: 400 }, deviceScaleFactor: 2, colorScheme: "light" });
+ try {
+ const p = await context.newPage();
+ await p.setContent(page(xml, viewBox));
+ const shapes = await p.evaluate(MEASURE);
+ const png = (await p.screenshot({ clip: { x: 0, y: 0, width: 400, height: 400 } })).toString("base64");
+ return { png, shapes };
+ } finally {
+ await context.close();
+ }
+}
+
+/** The reading of one SVG. Prints as it goes and returns the exit code. */
+export async function read(src, given = {}, cwd = process.cwd()) {
+ let xml;
+ try { xml = readFileSync(src, "utf8"); } catch { console.error(`read: cannot read ${resolve(src)}`); return 2; }
+ const info = scan(xml, basename(src));
+ if (info.error) { console.error(`read: ${info.error}`); return 2; }
+ const name = nameFor(src, given.name ?? null);
+ const txt = join(cwd, `hairline-${name}-source.txt`), png = join(cwd, `hairline-${name}-source.png`);
+
+ let browser = null, why = "";
+ try { browser = await launch(playwright(cacheDir())); } catch (e) { why = e.message.split("\n")[0]; }
+ let text;
+ if (!browser) {
+ text = card(info);
+ console.log(`no browser: ${why || "neither Chrome nor Playwright's Chromium would start"}. The card is reduced to what the XML says, and no picture was taken.`);
+ } else {
+ try {
+ const { png: b64, shapes } = await snapshot(browser, xml, info.viewBox);
+ writeFileSync(png, Buffer.from(b64, "base64"));
+ text = card(info, shapes);
+ console.log(`picture ${png}`);
+ } finally {
+ await browser.close();
+ }
+ }
+ writeFileSync(txt, text + "\n");
+ console.log(`card ${txt}`);
+ console.log(text);
+ return 0;
+}
+
+/* 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("./read.mjs")))) {
+ let args;
+ try {
+ args = parseArgs({ allowPositionals: true, options: { name: { type: "string" } } });
+ } catch (e) {
+ console.error(`${e.message}\n${USAGE}`);
+ process.exit(2);
+ }
+ const { positionals: [src], values } = args;
+ if (!src) { console.error(USAGE); process.exit(2); }
+ process.exit(await read(src, { name: values.name ?? null }));
+}