Isometric line figures that answer the pointer. For React and for anything with a DOM.
Skill: read.mjs scans an SVG into a card, with no browser yet: name, viewBox, ids, counts, relations
Lucas Marquesb3a66bd63a7a
diff --git a/packages/hairline/test/skill/fixtures/broken.txt b/packages/hairline/test/skill/fixtures/broken.txtnew file mode 100644index 0000000..d6e4fb0--- /dev/null+++ b/packages/hairline/test/skill/fixtures/broken.txt@@ -0,0 +1 @@+this is not an svgdiff --git a/packages/hairline/test/skill/fixtures/mark.svg b/packages/hairline/test/skill/fixtures/mark.svgnew file mode 100644index 0000000..67605ba--- /dev/null+++ b/packages/hairline/test/skill/fixtures/mark.svg@@ -0,0 +1,5 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">+ <path d="M10 90 L50 10 L90 90 Z" fill="#000"/>+ <path d="M30 90 L50 50 L70 90 Z" fill="#fff"/>+ <path d="M45 95 L55 95 L55 100 L45 100 Z" fill="#000"/>+</svg>diff --git a/packages/hairline/test/skill/fixtures/mixed.svg b/packages/hairline/test/skill/fixtures/mixed.svgnew file mode 100644index 0000000..0bede52--- /dev/null+++ b/packages/hairline/test/skill/fixtures/mixed.svg@@ -0,0 +1,11 @@+<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="48" height="32">+ <defs>+ <clipPath id="clip"><rect x="0" y="0" width="48" height="32"/></clipPath>+ <symbol id="dot"><circle cx="2" cy="2" r="2"/></symbol>+ </defs>+ <rect x="4" y="4" width="40" height="24" rx="4" fill="none" stroke="#000"/>+ <use href="#dot" x="8" y="8"/>+ <use xlink:href="icons.svg#other" x="20" y="8"/>+ <text x="24" y="20">Hi</text>+ <image href="photo.png" x="30" y="10" width="10" height="10"/>+</svg>diff --git a/packages/hairline/test/skill/fixtures/rocket.svg b/packages/hairline/test/skill/fixtures/rocket.svgnew file mode 100644index 0000000..38ea2bd--- /dev/null+++ b/packages/hairline/test/skill/fixtures/rocket.svg@@ -0,0 +1,12 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">+ <title>Deploy</title>+ <g id="rocket">+ <path id="body" d="M12 2 C9 5 8 9 8 13 L8 17 L16 17 L16 13 C16 9 15 5 12 2 Z"/>+ <circle id="window" cx="12" cy="8.5" r="1.5" fill="currentColor" stroke="none"/>+ <path id="fin-left" d="M8 12 L5 15 L5 17 L8 17 Z"/>+ <path id="fin-right" d="M16 12 L19 15 L19 17 L16 17 Z"/>+ </g>+ <g id="flame">+ <path d="M10 17 C10 20 12 22 12 22 C12 22 14 20 14 17 Z" fill="currentColor" stroke="none"/>+ </g>+</svg>diff --git a/packages/hairline/test/skill/read.test.ts b/packages/hairline/test/skill/read.test.tsnew file mode 100644index 0000000..9d32a8a--- /dev/null+++ b/packages/hairline/test/skill/read.test.ts@@ -0,0 +1,102 @@+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { expect, it } from "vitest";+import { card, nameFor, relate, scan } from "../../../../skills/hairline-create/read.mjs";++const FIX = fileURLToPath(new URL("./fixtures/", import.meta.url));+const svg = (f: string) => readFileSync(FIX + f, "utf8");++/** nameFor: a name build.mjs accepts, from --name or the file name. */+it("takes the name from the file, lowercased and hyphenated, or from --name", () => {+ expect(nameFor("icons/deploy.svg")).toBe("deploy");+ expect(nameFor("My Icon.svg")).toBe("my-icon");+ expect(nameFor("3d-box.svg")).toBe("x3d-box");+ expect(nameFor("a__b..c.svg")).toBe("a-b-c");+ expect(nameFor("deploy.svg", "Rocket")).toBe("rocket");+});++/** scan: what the XML alone says. */+it("reads the viewBox, the title, the ids, the groups and the counts of an icon", () => {+ const info = scan(svg("rocket.svg"), "rocket.svg");+ expect(info).toMatchObject({+ file: "rocket.svg", viewBox: [0, 0, 24, 24], synthesised: false, title: "Deploy",+ ids: ["rocket", "body", "window", "fin-left", "fin-right", "flame"], groups: 2,+ counts: { path: 4, circle: 1 }, notRead: {},+ });+});++it("reads a logo of paths with no title and no ids", () => {+ const info = scan(svg("mark.svg"), "mark.svg");+ expect(info).toMatchObject({ viewBox: [0, 0, 100, 100], title: null, ids: [], groups: 0, counts: { path: 3 }, notRead: {} });+ expect(card(info)).toContain("title: none ids: none");+});++it("synthesises a viewBox from width and height, skips <defs>, and lists what it does not read", () => {+ const info = scan(svg("mixed.svg"), "mixed.svg");+ expect(info.viewBox).toEqual([0, 0, 48, 32]);+ expect(info.synthesised).toBe(true);+ /* the rect under <defs> and the circle under <symbol> are not painted */+ expect(info.counts).toEqual({ rect: 1 });+ /* a <use> inside the file is a shape by reference; one pointing outside, text and image are not read */+ expect(info.notRead).toEqual({ use: 1, text: 1, image: 1 });+});++it("refuses what has no size and what is not an SVG", () => {+ expect(scan('<svg xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1"/></svg>', "x.svg")).toEqual({ error: "x.svg has no viewBox and no width and height: the card cannot be measured" });+ expect(scan(svg("broken.txt"), "broken.txt")).toEqual({ error: "broken.txt is not an SVG: no <svg> root" });+});++/** relate: one relation per shape, from the boxes alone. */+const ink = { x: 5, y: 2, w: 14, h: 20 };+const S = (i: number, x: number, y: number, w: number, h: number) => ({ i, type: "path", group: null, box: { x, y, w, h }, filled: true, stroke: null, closed: true, kind: "lines" });+it("says inside and where, above or below, left or right, and mirror of", () => {+ const body = S(1, 8, 2, 8, 15), win = S(2, 10.5, 7, 3, 3), finL = S(3, 5, 12, 3, 5), finR = S(4, 16, 12, 3, 5), flame = S(5, 10, 17, 4, 5);+ expect(relate([body, win, finL, finR, flame], ink)).toEqual([+ "",+ "inside #1, middle",+ "left of #1, touching",+ "mirror of #3",+ "below #1, touching",+ ]);+});++it("says nothing for a shape apart from every other", () => {+ expect(relate([S(1, 0, 0, 2, 2), S(2, 50, 50, 2, 2)], { x: 0, y: 0, w: 52, h: 52 })).toEqual(["", ""]);+});++/** card: the text the agent reads. */+it("writes the reduced card from a scan, and says the picture was not taken", () => {+ const text = card(scan(svg("mixed.svg"), "mixed.svg"));+ expect(text.split("\n")[0]).toBe("mixed.svg viewBox 0 0 48 32 (from width and height) (1.5:1) 1 shape in 0 groups");+ expect(text).toContain("title: none ids: clip, dot");+ expect(text).toContain("shapes: 1 rect");+ expect(text).toContain("not read: 1 <use> outside the file, 1 <text>, 1 <image>");+ expect(text).toContain("no browser: boxes and the picture were not taken; read the SVG's own text for them");+});++it("writes the full card with one line per shape, small shapes counted, and 30 lines at most", () => {+ const info = scan(svg("rocket.svg"), "rocket.svg");+ const shapes = [+ { i: 1, type: "path", group: "rocket", box: { x: 8, y: 2, w: 8, h: 15 }, filled: false, stroke: 1.5, closed: true, kind: "curves and lines" },+ { i: 2, type: "circle", group: "rocket", box: { x: 10.5, y: 7, w: 3, h: 3 }, filled: true, stroke: null, closed: true, kind: "curves" },+ { i: 3, type: "path", group: "rocket", box: { x: 5, y: 12, w: 3, h: 5 }, filled: false, stroke: 1.5, closed: true, kind: "lines" },+ { i: 4, type: "path", group: "rocket", box: { x: 16, y: 12, w: 3, h: 5 }, filled: false, stroke: 1.5, closed: true, kind: "lines" },+ { i: 5, type: "path", group: "flame", box: { x: 10, y: 17, w: 4, h: 5 }, filled: true, stroke: null, closed: true, kind: "curves and lines" },+ { i: 6, type: "circle", group: null, box: { x: 0, y: 0, w: 0.1, h: 0.1 }, filled: true, stroke: null, closed: true, kind: "curves" },+ ];+ const text = card(info, shapes);+ const lines = text.split("\n");+ expect(lines[0]).toBe("rocket.svg viewBox 0 0 24 24 (1:1) 6 shapes in 2 groups");+ expect(lines[1]).toBe("title: \"Deploy\" ids: rocket, body, window, fin-left, fin-right, flame");+ expect(lines[2]).toBe("ink: 5..19 × 2..22 (58% × 83% of the viewBox)");+ expect(text).toMatch(/^#1 +path +g#rocket +box 8\.\.16 × 2\.\.17 centre 12,9\.5 stroke 1\.5 closed, curves and lines \(tall, 1:1\.9\)$/m);+ expect(text).toMatch(/^#2 +circle +g#rocket +box 10\.5\.\.13\.5 × 7\.\.10 centre 12,8\.5 filled closed, curves inside #1, middle$/m);+ expect(text).toMatch(/^#4 +path +g#rocket +box 16\.\.19 × 12\.\.17 centre 17\.5,14\.5 stroke 1\.5 closed, lines mirror of #3$/m);+ expect(text).toContain("and 1 small shape");+ expect(lines.length).toBeLessThanOrEqual(30);+ /* forty shapes: the card lists some and counts the rest */+ const many = Array.from({ length: 40 }, (_, k) => ({ ...shapes[0], i: k + 1, box: { x: k, y: 2, w: 8, h: 15 } }));+ const long = card(info, many).split("\n");+ expect(long.length).toBeLessThanOrEqual(30);+ expect(long.at(-1)).toMatch(/^and \d+ more shapes$/);+});diff --git a/skills/hairline-create/read.mjs b/skills/hairline-create/read.mjsnew file mode 100644index 0000000..7f7e7d1--- /dev/null+++ b/skills/hairline-create/read.mjs@@ -0,0 +1,163 @@+#!/usr/bin/env node+/**+ * Reads an SVG the person already has, for a figure built from it:+ *+ * node <skill folder>/read.mjs <file.svg> [--name <name>]+ *+ * It writes, in the working directory, hairline-<name>-source.png, the SVG+ * drawn at 400 × 400 on white, and hairline-<name>-source.txt, the card: the+ * viewBox, the title and ids, the ink's box, and one line per painted shape+ * with its type, group, box, centre, fill or stroke, and its relation to the+ * shape it sits in or touches. source.md says how to read it. The boxes come+ * from the browser look.mjs installs; without one the card is reduced to what+ * 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";++/** The card lists this many shapes at most; the rest are counted on its last line. */+const LISTED = 24;+/** A shape smaller than this share of the ink's box, both ways, is counted, not listed. */+const SMALL = 0.02;+/** Boxes this close, as a share of the ink's size, touch; a mirror matches within it too. */+const NEAR = 0.05;++const SHAPES = ["path", "rect", "circle", "ellipse", "line", "polyline", "polygon"];+const UNREAD = ["text", "image", "foreignObject"];+/** Elements whose children are not painted where they stand. */+const HIDDEN = ["defs", "symbol", "clipPath", "mask", "pattern", "marker"];++/** A name build.mjs accepts: --name, else the file's, lowercased, runs of anything else as one hyphen, a digit first prefixed with x. */+export function nameFor(file, given = null) {+ const raw = (given ?? basename(file).replace(/\.svg$/i, "")).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");+ return /^[a-z]/.test(raw) ? raw : `x${raw}`;+}++/** The tags of an SVG in order, with their attributes; comments, CDATA and declarations skipped. Enough to count, never to draw. */+function tags(xml) {+ const out = [];+ const re = /<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<[?!][\s\S]*?>|<\/([\w:.-]+)\s*>|<([\w:.-]+)((?:\s+[\w:.-]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>/g;+ for (let m; (m = re.exec(xml));) {+ if (m[1]) out.push({ close: m[1] });+ else if (m[2]) {+ const attrs = {};+ for (const a of m[3].matchAll(/([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)) attrs[a[1]] = a[2] ?? a[3];+ out.push({ open: m[2], attrs, self: !!m[4] });+ }+ }+ return out;+}++/** A length attribute as a number, units dropped; null when it is not one. */+const len = (v) => (v === undefined ? null : Number.isFinite(parseFloat(v)) ? parseFloat(v) : null);++/** What the XML alone says of the SVG. An object with `error` when it cannot be read as one. */+export function scan(xml, fileName) {+ const list = tags(xml);+ const root = list.find((t) => t.open === "svg");+ if (!root) return { error: `${fileName} is not an SVG: no <svg> root` };+ let viewBox = (root.attrs.viewBox ?? "").trim().split(/[\s,]+/).map(Number);+ let synthesised = false;+ if (viewBox.length !== 4 || !viewBox.every(Number.isFinite) || !(viewBox[2] > 0 && viewBox[3] > 0)) {+ const w = len(root.attrs.width), h = len(root.attrs.height);+ if (!(w > 0) || !(h > 0)) return { error: `${fileName} has no viewBox and no width and height: the card cannot be measured` };+ viewBox = [0, 0, w, h];+ synthesised = true;+ }+ const ids = [], counts = {}, notRead = {}, open = [];+ let groups = 0;+ const title = /<title[^>]*>([\s\S]*?)<\/title>/.exec(xml)?.[1].trim() || null;+ for (const t of list) {+ if (t.close) { open.pop(); continue; }+ if (t.attrs.id) ids.push(t.attrs.id);+ const hidden = open.some((o) => HIDDEN.includes(o)) || HIDDEN.includes(t.open);+ if (!t.self) open.push(t.open);+ if (hidden) continue;+ if (t.open === "g") groups++;+ else if (SHAPES.includes(t.open)) counts[t.open] = (counts[t.open] ?? 0) + 1;+ else if (UNREAD.includes(t.open)) notRead[t.open] = (notRead[t.open] ?? 0) + 1;+ else if (t.open === "use" && !(t.attrs.href ?? t.attrs["xlink:href"] ?? "").startsWith("#")) notRead.use = (notRead.use ?? 0) + 1;+ }+ return { file: fileName, viewBox, synthesised, title, ids, groups, counts, notRead };+}++const r1 = (v) => Math.round(v * 10) / 10;+const span = (b) => `${r1(b.x)}..${r1(b.x + b.w)} × ${r1(b.y)}..${r1(b.y + b.h)}`;+const centre = (b) => [b.x + b.w / 2, b.y + b.h / 2];+const area = (b) => b.w * b.h;+const inside = (a, b) => a.x >= b.x - 1e-6 && a.y >= b.y - 1e-6 && a.x + a.w <= b.x + b.w + 1e-6 && a.y + a.h <= b.y + b.h + 1e-6 && area(a) < area(b);++/** One relation per shape, read from the boxes: inside the largest shape that holds it; else the mirror of an earlier shape; else touching the largest it touches; else nothing. */+export function relate(shapes, ink) {+ const near = NEAR * Math.max(ink.w, ink.h);+ const gap = (a, b) => Math.max(b.x - (a.x + a.w), a.x - (b.x + b.w), 0) + Math.max(b.y - (a.y + a.h), a.y - (b.y + b.h), 0);+ const side = (a, b) => {+ const [ax, ay] = centre(a), [bx, by] = centre(b);+ return Math.abs(ax - bx) * b.h >= Math.abs(ay - by) * b.w ? (ax < bx ? "left of" : "right of") : (ay < by ? "above" : "below");+ };+ const third = (a, b) => { const k = (centre(a)[1] - b.y) / b.h; return k < 1 / 3 ? "upper third" : k > 2 / 3 ? "lower third" : "middle"; };+ const axis = ink.x + ink.w / 2;+ return shapes.map((s) => {+ const others = shapes.filter((o) => o !== s);+ const holder = others.filter((o) => inside(s.box, o.box)).sort((a, b) => area(b.box) - area(a.box))[0];+ if (holder) return `inside #${holder.i}, ${third(s.box, holder.box)}`;+ const mirror = others.find((o) => o.i < s.i && Math.abs(o.box.w - s.box.w) <= near && Math.abs(o.box.h - s.box.h) <= near+ && Math.abs(o.box.y - s.box.y) <= near && Math.abs(axis - centre(o.box)[0] - (centre(s.box)[0] - axis)) <= near+ && Math.abs(centre(s.box)[0] - axis) > near);+ if (mirror) return `mirror of #${mirror.i}`;+ const touched = others.filter((o) => area(o.box) > area(s.box) && gap(s.box, o.box) <= near).sort((a, b) => area(b.box) - area(a.box))[0];+ if (touched) return `${side(s.box, touched.box)} #${touched.i}, touching`;+ return "";+ });+}++/** The box round a list of boxes. */+const union = (boxes) => {+ const x0 = Math.min(...boxes.map((b) => b.x)), y0 = Math.min(...boxes.map((b) => b.y));+ return { x: x0, y: y0, w: Math.max(...boxes.map((b) => b.x + b.w)) - x0, h: Math.max(...boxes.map((b) => b.y + b.h)) - y0 };+};+const ratio = (w, h) => (w >= h ? `${r1(w / h)}:1` : `1:${r1(h / w)}`);+const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;+const pad = (s, n) => String(s).padEnd(n);++/** The card. With `shapes` null it is the reduced card: what scan() read, and a line saying the rest was not taken. */+export function card(info, shapes = null) {+ const [vx, vy, vw, vh] = info.viewBox;+ const total = shapes ? shapes.length : Object.values(info.counts).reduce((a, b) => a + b, 0);+ const lines = [+ `${info.file} viewBox ${vx} ${vy} ${vw} ${vh}${info.synthesised ? " (from width and height)" : ""} (${ratio(vw, vh)}) ${plural(total, "shape")} in ${plural(info.groups, "group")}`,+ `title: ${info.title ? `"${info.title}"` : "none"} ids: ${info.ids.length ? info.ids.join(", ") : "none"}`,+ ];+ const unread = Object.entries(info.notRead).map(([k, n]) => `${n} <${k}>${k === "use" ? " outside the file" : ""}`);+ if (!shapes) {+ lines.push(`shapes: ${Object.entries(info.counts).map(([k, n]) => `${n} ${k}`).join(", ") || "none"}`);+ if (unread.length) lines.push(`not read: ${unread.join(", ")}`);+ lines.push("no browser: boxes and the picture were not taken; read the SVG's own text for them");+ return lines.join("\n");+ }+ if (!shapes.length) {+ lines.push("ink: none: nothing is painted");+ if (unread.length) lines.push(`not read: ${unread.join(", ")}`);+ return lines.join("\n");+ }+ const all = union(shapes.map((s) => s.box));+ const small = shapes.filter((s) => s.box.w < SMALL * all.w && s.box.h < SMALL * all.h);+ const listed = shapes.filter((s) => !small.includes(s));+ /* the ink is the listed shapes' box: a speck at the corner does not stretch it */+ const ink = union((listed.length ? listed : shapes).map((s) => s.box));+ lines.push(`ink: ${span(ink)} (${Math.round((ink.w / vw) * 100)}% × ${Math.round((ink.h / vh) * 100)}% of the viewBox)`, "");+ const rel = relate(listed, ink);+ const shown = listed.slice(0, LISTED);+ shown.forEach((s, k) => {+ const [cx, cy] = centre(s.box);+ const paint = [s.filled && "filled", s.stroke !== null && `stroke ${r1(s.stroke)}`].filter(Boolean).join(", ") || "no paint";+ const shape = [s.closed ? "closed" : "open", s.kind].filter(Boolean).join(", ");+ const tall = s.box.h > s.box.w * 1.5 ? ` (tall, ${ratio(s.box.w, s.box.h)})` : s.box.w > s.box.h * 1.5 ? ` (wide, ${ratio(s.box.w, s.box.h)})` : "";+ const note = rel[k] ? ` ${rel[k]}` : tall;+ lines.push(`#${pad(s.i, 2)} ${pad(s.type, 7)} ${pad(s.group ? `g#${s.group}` : "-", 9)} box ${span(s.box)} centre ${r1(cx)},${r1(cy)} ${paint} ${shape}${note}`);+ });+ if (listed.length > shown.length) lines.push(`and ${listed.length - shown.length} more shapes`);+ if (small.length) lines.push(`and ${plural(small.length, "small shape")}`);+ if (unread.length) lines.push(`not read: ${unread.join(", ")}`);+ return lines.slice(0, 30).join("\n");+}