Skip to content

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

Skill: read.mjs measures inside nested svgs, never runs a file's scripts, keeps the not-read line, refuses % sizes and drops a whole DOCTYPE

Lucas Marques4b53069e629a
diff --git a/packages/hairline/test/browser/read.spec.ts b/packages/hairline/test/browser/read.spec.ts
index 6fdbed4..c719039 100644
--- a/packages/hairline/test/browser/read.spec.ts
+++ b/packages/hairline/test/browser/read.spec.ts
@@ -76,6 +76,20 @@ test.describe("read.mjs", () => {
expect(readFileSync(join(cwd, "hairline-moved-source.txt"), "utf8")).toMatch(/^#1 {2}rect {4}g#moved {3}box 20\.\.30 × 40\.\.50 /m);
});
+ test("measures a shape inside a nested <svg> where it is drawn", async () => {
+ const cwd = mkdtempSync(join(tmpdir(), "hl-read-"));
+ const run = await read(cwd, { HAIRLINE_LOOK_CACHE: cache }, FIX + "nested.svg");
+ expect(run.code, run.out).toBe(0);
+ expect(readFileSync(join(cwd, "hairline-nested-source.txt"), "utf8")).toMatch(/^#2 {2}rect {4}- {9}box 0\.\.12 × 0\.\.12 /m);
+ });
+
+ test("never runs the SVG's scripts: the card is of the drawing as written", async () => {
+ const cwd = mkdtempSync(join(tmpdir(), "hl-read-"));
+ const run = await read(cwd, { HAIRLINE_LOOK_CACHE: cache }, FIX + "scripted.svg");
+ expect(run.code, run.out).toBe(0);
+ expect(readFileSync(join(cwd, "hairline-scripted-source.txt"), "utf8")).toMatch(/^#1 {2}rect {4}- {9}box 10\.\.90 × 10\.\.90 /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 */
diff --git a/packages/hairline/test/skill/fixtures/illustrator.svg b/packages/hairline/test/skill/fixtures/illustrator.svg
new file mode 100644
index 0000000..1018961
--- /dev/null
+++ b/packages/hairline/test/skill/fixtures/illustrator.svg
@@ -0,0 +1,7 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd" [
+ <!ENTITY ns_extend "http://ns.adobe.com/Extensibility/1.0/">
+]>
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
+ <rect x="10" y="10" width="80" height="80" fill="#000"/>
+</svg>
diff --git a/packages/hairline/test/skill/fixtures/nested.svg b/packages/hairline/test/skill/fixtures/nested.svg
new file mode 100644
index 0000000..b80c0ab
--- /dev/null
+++ b/packages/hairline/test/skill/fixtures/nested.svg
@@ -0,0 +1,6 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
+ <rect x="0" y="0" width="24" height="24" fill="none" stroke="#000"/>
+ <svg x="0" y="0" width="12" height="12" viewBox="0 0 100 100">
+ <rect x="0" y="0" width="100" height="100" fill="#000"/>
+ </svg>
+</svg>
diff --git a/packages/hairline/test/skill/fixtures/scripted.svg b/packages/hairline/test/skill/fixtures/scripted.svg
new file mode 100644
index 0000000..64038f0
--- /dev/null
+++ b/packages/hairline/test/skill/fixtures/scripted.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
+ <rect id="kept" x="10" y="10" width="80" height="80" fill="#000"/>
+ <script>document.getElementById("kept").remove()</script>
+</svg>
diff --git a/packages/hairline/test/skill/read.test.ts b/packages/hairline/test/skill/read.test.ts
index 9d32a8a..a0e8ccd 100644
--- a/packages/hairline/test/skill/read.test.ts
+++ b/packages/hairline/test/skill/read.test.ts
@@ -1,7 +1,7 @@
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";
+import { card, nameFor, page, 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");
@@ -100,3 +100,28 @@ it("writes the full card with one line per shape, small shapes counted, and 30 l
expect(long.length).toBeLessThanOrEqual(30);
expect(long.at(-1)).toMatch(/^and \d+ more shapes$/);
});
+
+/** Findings of the final review: each pins one failure on a real SVG. */
+it("keeps the not-read line on a busy card, under the 30 lines", () => {
+ const info = { ...scan(svg("rocket.svg"), "rocket.svg"), notRead: { text: 1 } };
+ const rects = Array.from({ length: 30 }, (_, k) => ({ i: k + 1, type: "rect", group: null, box: { x: k * 3, y: 0, w: 2, h: 40 }, filled: true, stroke: null, closed: true, kind: "lines" }));
+ const speck = { ...rects[0], i: 31, box: { x: 0, y: 0, w: 0.1, h: 0.1 } };
+ const lines = card(info, [...rects, speck]).split("\n");
+ expect(lines.length).toBeLessThanOrEqual(30);
+ expect(lines).toContain("not read: 1 <text>");
+ expect(lines).toContain("and 1 small shape");
+});
+
+it("takes width and height in px or absolute units, and refuses % and font units", () => {
+ const root = (w: string, h: string) => `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="${h}"><rect width="1" height="1"/></svg>`;
+ expect(scan(root("24px", "12px"), "a.svg").viewBox).toEqual([0, 0, 24, 12]);
+ expect(scan(root("1in", "0.5in"), "a.svg").viewBox).toEqual([0, 0, 96, 48]);
+ expect(scan(root("100%", "100%"), "a.svg")).toEqual({ error: "a.svg has no viewBox, and its width and height are in %: the card cannot be measured" });
+ expect(scan(root("2em", "2em"), "a.svg")).toEqual({ error: "a.svg has no viewBox, and its width and height are in em: the card cannot be measured" });
+});
+
+it("drops a DOCTYPE with an internal subset whole, so nothing of it lands in the picture", () => {
+ const html = page(svg("illustrator.svg"), [0, 0, 100, 100]);
+ expect(html).not.toContain("]>");
+ expect(html).not.toContain("ENTITY");
+});
diff --git a/skills/hairline-create/read.mjs b/skills/hairline-create/read.mjs
index a988267..fb57fe8 100644
--- a/skills/hairline-create/read.mjs
+++ b/skills/hairline-create/read.mjs
@@ -23,8 +23,8 @@ 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;
+/** The card lists this many shapes at most, so that with the more, small and not-read lines it stays within 30. */
+const LISTED = 23;
/** 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. */
@@ -60,8 +60,15 @@ function tags(xml) {
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);
+/** CSS pixels per unit, for the absolute units a width or height can carry. */
+const PX = { "": 1, px: 1, in: 96, cm: 96 / 2.54, mm: 96 / 25.4, pt: 4 / 3, pc: 16 };
+/** A length attribute: its value in px, or its unit when it is relative (%, em, ex…), or null when it is not one. */
+const len = (v) => {
+ const m = /^\s*([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)\s*([a-z%]*)\s*$/i.exec(v ?? "");
+ if (!m) return null;
+ const unit = m[2].toLowerCase();
+ return unit in PX ? Number(m[1]) * PX[unit] : unit;
+};
/** What the XML alone says of the SVG. An object with `error` when it cannot be read as one. */
export function scan(xml, fileName) {
@@ -72,6 +79,8 @@ export function scan(xml, fileName) {
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);
+ const relative = [w, h].find((v) => typeof v === "string");
+ if (relative) return { error: `${fileName} has no viewBox, and its width and height are in ${relative}: the card cannot be measured` };
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;
@@ -180,7 +189,7 @@ export function card(info, shapes = null) {
/** 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 svg = xml.replace(/<\?xml[\s\S]*?\?>|<!DOCTYPE[^[>]*(?:\[[\s\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">`;
});
@@ -190,7 +199,8 @@ export function page(xml, viewBox) {
/* 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();
+ /* screen CTMs, not getCTM(): getCTM() stops at the nearest viewport, which inside a nested <svg> is not the root */
+ const toRoot = root.getScreenCTM().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 = [];
@@ -199,7 +209,7 @@ const MEASURE = () => {
let b;
try { b = el.getBBox(); } catch { continue; }
if (!(b.width > 0 || b.height > 0)) continue;
- const m = toRoot.multiply(el.getCTM());
+ const m = toRoot.multiply(el.getScreenCTM());
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);
@@ -224,9 +234,9 @@ const MEASURE = () => {
return list;
};
-/** The picture and the shapes, from a fresh context of a browser the caller owns. */
+/** The picture and the shapes, from a fresh context of a browser the caller owns. The SVG's scripts never run and nothing is fetched: a file from anywhere is drawn as written. */
export async function snapshot(browser, xml, viewBox) {
- const context = await browser.newContext({ viewport: { width: 400, height: 400 }, deviceScaleFactor: 2, colorScheme: "light" });
+ const context = await browser.newContext({ viewport: { width: 400, height: 400 }, deviceScaleFactor: 2, colorScheme: "light", javaScriptEnabled: false, offline: true });
try {
const p = await context.newPage();
await p.setContent(page(xml, viewBox));
@@ -260,6 +270,10 @@ export async function read(src, given = {}, cwd = process.cwd()) {
writeFileSync(png, Buffer.from(b64, "base64"));
text = card(info, shapes);
console.log(`picture ${png}`);
+ } catch (e) {
+ /* the browser started but could not draw this file: the reduced card is still a reading */
+ text = card(info);
+ console.log(`no picture: the browser could not draw it: ${e.message.split("\n")[0]}. The card is reduced to what the XML says.`);
} finally {
await browser.close();
}