An agent skill for creating detailed, interactive isometric illustrations of real-world machines and complex systems. Generates polished SVGs with optional WebGL shaders and 3D effects.
fix(browser): honor explicitly requested figure selectors
Rudy Celekli42a9820c466b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex fe3a3ed..b21e7f2 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,8 @@ All notable changes to Anatomy are recorded here. The format follows [Keep a Cha### Fixed+- Honor explicit capture, drive and line-check selectors, and scope reported readouts to the requested figure.+- `scripts/drive.mjs` now fails when a browser evaluation throws or rejects, rather than reporting a clean successful session.- The arcade cabinet now accepts coins with reduced motion enabled, preserving the meter, credit and power-on events when the coin animation is skipped.- The turning dial stops its idle tour when reduced motion is enabled while the page is open and cancels its pending automatic restart while preserving keyboard and pointer input.diff --git a/scripts/capture-selector.test.mjs b/scripts/capture-selector.test.mjsnew file mode 100644index 0000000..089f02e--- /dev/null+++ b/scripts/capture-selector.test.mjs@@ -0,0 +1,131 @@+import assert from "node:assert/strict";+import { execFile } from "node:child_process";+import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { promisify } from "node:util";+import test from "node:test";++const execute = promisify(execFile);++async function capture(selector, svgOnly = false, keys = false) {+ const directory = await mkdtemp(join(tmpdir(), "anatomy-capture-target-"));+ try {+ const page = join(directory, "figure.html");+ const out = join(directory, "capture.png");+ const content = svgOnly+ ? '<svg width="80" height="40" xmlns="http://www.w3.org/2000/svg"><rect width="80" height="40" fill="green"/></svg>'+ : `<div class="iso-plate" tabindex="0" id="first" style="width:100px;height:80px;background:blue"><span data-readout>first:0</span></div><div class="iso-plate" tabindex="0" id="second" style="width:60px;height:40px;background:red"><span data-readout>second:0</span></div><script>for(const plate of document.querySelectorAll('.iso-plate'))plate.addEventListener('keydown',e=>{if(e.key==='ArrowRight')plate.querySelector('[data-readout]').textContent=plate.id+':1'})</script>`;+ await writeFile(page, '<!doctype html><style>body{margin:20px}</style>' + content);+ const args = ["scripts/capture.mjs", page, "--out", out, "--wait", "0", "--scale", "1"];+ if (selector !== undefined) args.push("--select", selector);+ if (keys) args.push("--key", "ArrowRight");+ let result;+ try {+ result = { code: 0, ...await execute(process.execPath, args, { timeout: 30000 }) };+ } catch (error) {+ result = { code: error.code, stdout: error.stdout, stderr: error.stderr };+ }+ let png;+ try {+ await access(out);+ png = await readFile(out);+ } catch {}+ return { ...result, png };+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+}++function dimensions(png) {+ assert.ok(png);+ assert.equal(png.subarray(1, 4).toString(), "PNG");+ return [png.readUInt32BE(16), png.readUInt32BE(20)];+}++test("an absent explicit figure selector fails without an unrelated screenshot", async () => {+ const result = await capture("#removed-figure");+ assert.equal(result.code, 1);+ assert.match(result.stderr, /Capture target not found: #removed-figure/);+ assert.equal(result.png, undefined);+ assert.doesNotMatch(result.stdout, /saved /);+});++test("a malformed explicit selector retains an actionable capture diagnostic", async () => {+ const result = await capture("[invalid");+ assert.equal(result.code, 1);+ assert.match(result.stderr, /Capture target not found: \[invalid/);+ assert.equal(result.png, undefined);+});++test("a matching selector captures the requested second figure", async () => {+ const result = await capture("#second");+ assert.equal(result.code, 0, result.stderr);+ assert.deepEqual(dimensions(result.png), [72, 52]);+ assert.match(result.stdout, /60x40/);+});++test("default selection retains the first plate", async () => {+ const result = await capture(undefined);+ assert.equal(result.code, 0, result.stderr);+ assert.deepEqual(dimensions(result.png), [112, 92]);+ assert.match(result.stdout, /100x80/);+});++test("default selection retains the standalone SVG fallback", async () => {+ const result = await capture(undefined, true);+ assert.equal(result.code, 0, result.stderr);+ assert.deepEqual(dimensions(result.png), [92, 52]);+ assert.match(result.stdout, /80x40/);+});++test("an explicit target reports that figure's readout", async () => {+ const result = await capture("#second");+ assert.equal(result.code, 0, result.stderr);+ assert.match(result.stdout, /readout "second:0"/);+});++test("keyboard interaction reaches the explicitly selected figure", async () => {+ const result = await capture("#second", false, true);+ assert.equal(result.code, 0, result.stderr);+ assert.match(result.stdout, /readout "second:1"/);+ assert.deepEqual(dimensions(result.png), [72, 52]);+});++async function driveTarget(actions, standaloneLines = false) {+ const directory=await mkdtemp(join(tmpdir(),"anatomy-drive-target-"));+ try{+ const page=join(directory,"figure.html"),out=join(directory,"selected.png"),file=join(directory,"actions.json");+ const svg='<svg width="60" height="40" viewBox="0 0 60 40"><rect x="10" y="10" width="30" height="20" fill="none" stroke="black"/><path class="iso-line" d="M10 20L40 20" fill="none" stroke="black"/></svg>';+ await writeFile(page,`<!doctype html><style>body{margin:20px}</style><div class="iso-plate" id="first" tabindex="0" style="width:100px;height:80px"><span data-readout>first:0</span>${svg}</div><div class="iso-plate" id="second" tabindex="0" style="width:60px;height:40px"><span data-readout>second:0</span>${svg}</div><script>for(const el of document.querySelectorAll('.iso-plate'))el.addEventListener('keydown',event=>{if(event.key==='ArrowRight')el.querySelector('[data-readout]').textContent=el.id+':1'})</script>`);+ await writeFile(file,JSON.stringify(actions.map(action=>action.map(value=>value==='OUTPUT'?out:value))));+ const args=standaloneLines?["scripts/lines.mjs",page,"--select","#missing","--wait","0"]:["scripts/drive.mjs",page,"--actions",file];+ let result;try{result={code:0,...await execute(process.execPath,args,{timeout:30000})};}catch(error){result={code:error.code,stdout:error.stdout,stderr:error.stderr};}+ let png;try{png=await readFile(out);}catch{}return{...result,png};+ }finally{await rm(directory,{recursive:true,force:true});}+}+for(const [name,action] of [+ ["shot",["shot","OUTPUT","#missing"]],+ ["move",["move","#missing",.5,.5]],+ ["click",["click","#missing"]],+ ["drag",["drag","#missing",0,0,1,1]],+ ["scroll",["scroll","#missing"]],+ ["key",["key","ArrowRight","#missing"]],+ ["lines",["lines",null,"#missing"]],+])test(`drive ${name} rejects an absent explicit target instead of continuing`,async()=>{+ const result=await driveTarget([action,["eval","'after missing target'"]]);assert.equal(result.code,1,result.stdout);assert.match(result.stderr,/(Drive|Line) target not found: #missing/);assert.doesNotMatch(result.stdout,/after missing target/);assert.equal(result.png,undefined);+});+test("standalone lines rejects an absent selected figure",async()=>{+ const result=await driveTarget([],true);assert.equal(result.code,1,result.stdout);assert.match(result.stderr,/Line target not found: #missing/);+});+test("drive targets the requested figure for keyboard input screenshot and reported readout",async()=>{+ const result=await driveTarget([["key","ArrowRight","#second"],["shot","OUTPUT","#second"],["eval","document.querySelector('#first [data-readout]').textContent"]]);+ assert.equal(result.code,0,result.stderr);assert.match(result.stdout,/readout "second:1"/);assert.match(result.stdout,/eval: "first:0"/);assert.deepEqual(dimensions(result.png),[68,48]);+});+test("drive defaults preserve first-figure keyboard focus and reporting",async()=>{+ const result=await driveTarget([["key","ArrowRight"],["shot","OUTPUT"],["eval","document.querySelector('#second [data-readout]').textContent"]]);+ assert.equal(result.code,0,result.stderr);assert.match(result.stdout,/readout "first:1"/);assert.match(result.stdout,/eval: "second:0"/);assert.deepEqual(dimensions(result.png),[108,88]);+});+test("line selection preserves real rooted-line checks on the requested SVG",async()=>{+ const result=await driveTarget([["lines",null,"#second svg"]]);assert.equal(result.code,0,result.stderr);assert.match(result.stdout,/line ends: 0 of [1-9]\d* ends on [1-9]\d* lines float/);+});diff --git a/scripts/capture.mjs b/scripts/capture.mjsindex f3ed72f..1622fdc 100644--- a/scripts/capture.mjs+++ b/scripts/capture.mjs@@ -160,8 +160,11 @@ async function main() {await evaluate(`(async()=>{const h=document.documentElement.scrollHeight;for(let y=0;y<h;y+=400){scrollTo(0,y);await new Promise(r=>setTimeout(r,60))}scrollTo(0,0)})()`);await sleep(Math.max(0, options.wait - 1500));const select = options.select ?? ".iso-plate";- const boxOf = async () =>- evaluate(`(()=>{const el=document.querySelector(${JSON.stringify(select)})||document.querySelector("svg")||document.body;el.scrollIntoView({block:"center"});const r=el.getBoundingClientRect();return {x:r.left+scrollX,y:r.top+scrollY,w:r.width,h:r.height,vx:r.left,vy:r.top}})()`);+ const boxOf = async () => {+ const box = await evaluate(`(()=>{let el;try{el=document.querySelector(${JSON.stringify(select)})}catch{};if(!el&&${options.select === undefined})el=document.querySelector("svg")||document.body;if(!el)return null;el.scrollIntoView({block:"center"});const r=el.getBoundingClientRect();return {x:r.left+scrollX,y:r.top+scrollY,w:r.width,h:r.height,vx:r.left,vy:r.top}})()`);+ if (!box) throw new Error(`Capture target not found: ${select}`);+ return box;+ };let box = await boxOf();if (options.hover) {await sleep(300);@@ -177,7 +180,8 @@ async function main() {await sleep(1200);}if (options.keys) {- await evaluate(`(()=>{const f=document.querySelector('[tabindex="0"]');if(f)f.focus()})()`);+ const focus = options.select === undefined ? `document.querySelector('[tabindex="0"]')` : `(()=>{const el=document.querySelector(${JSON.stringify(select)});return el.matches('[tabindex="0"]')?el:el.querySelector('[tabindex="0"]')||el.closest('[tabindex="0"]')||el})()`;+ await evaluate(`(()=>{const f=${focus};if(f)f.focus()})()`);const named = { " ": "Space", "-": "Minus", "=": "Equal", ",": "Comma", ".": "Period", "/": "Slash", ";": "Semicolon", "'": "Quote", "[": "BracketLeft", "]": "BracketRight", "\\": "Backslash", "`": "Backquote" };for (const entry of options.keys) {if (entry === "Tab") continue;@@ -202,15 +206,16 @@ async function main() {const first = clipOf();await shoot(out, first.clip, first.scale);const shotAt = Date.now();+ const readoutOf = () => evaluate(options.select === undefined ? `(document.querySelector("[data-readout]")||{}).textContent||""` : `(()=>{const el=document.querySelector(${JSON.stringify(select)});const plate=el.closest(".iso-plate")||el.querySelector(".iso-plate")||el;return(plate.querySelector("[data-readout]")||{}).textContent||""})()`);const readouts = [];for (const delay of [...options.times].sort((a, b) => a - b)) {await sleep(Math.max(0, shotAt + delay - Date.now()));const next = clipOf();await shoot(out.replace(/\.png$/, `-${delay}.png`), next.clip, next.scale);- readouts.push(`+${delay}ms "${await evaluate(`(document.querySelector("[data-readout]")||{}).textContent||""`)}"`);+ readouts.push(`+${delay}ms "${await readoutOf()}"`);}const sideways = await evaluate(`document.documentElement.scrollWidth > innerWidth + 1`);- const readout = await evaluate(`(document.querySelector("[data-readout]")||{}).textContent||""`);+ const readout = await readoutOf();console.log(`saved ${out}`);console.log(`clip ${Math.round(box.x)},${Math.round(box.y)} ${Math.round(box.w)}x${Math.round(box.h)} · readout "${readout}" · scrolls sideways: ${sideways ? "YES" : "no"}`);if (readouts.length) console.log(`readout over time: ${readouts.join(" · ")}`);diff --git a/scripts/drive.mjs b/scripts/drive.mjsindex 89507bf..e8d60af 100644--- a/scripts/drive.mjs+++ b/scripts/drive.mjs@@ -172,8 +172,9 @@ async function main() {if (navigation.error) throw new Error(`Navigation failed: ${navigation.error.message}`);if (navigation.result?.errorText) throw new Error(`Navigation failed: ${navigation.result.errorText}`);await sleep(1200);- const boxOf = (selector) => evaluate(`(()=>{const el=document.querySelector(${JSON.stringify(selector ?? ".iso-plate")})||document.body;const r=el.getBoundingClientRect();return {x:r.left,y:r.top,w:r.width,h:r.height,sx:scrollX,sy:scrollY}})()`);- const readout = () => evaluate(`(document.querySelector("[data-readout]")||{}).textContent||""`);+ const targetOf = (selector, fallback = ".iso-plate") => `(()=>{const select=${JSON.stringify(selector ?? null)};const el=document.querySelector(select??${JSON.stringify(fallback)});if(select!==null&&!el)throw new Error("Drive target not found: "+select);return el})()`;+ const boxOf = (selector) => evaluate(`(()=>{const el=${targetOf(selector)}||document.body;const r=el.getBoundingClientRect();return {x:r.left,y:r.top,w:r.width,h:r.height,sx:scrollX,sy:scrollY}})()`);+ const readout = (selector) => evaluate(selector == null ? `(document.querySelector("[data-readout]")||{}).textContent||""` : `(()=>{const el=${targetOf(selector)};return(el.matches('[data-readout]')?el:el.querySelector('[data-readout]')||el.closest('.iso-plate')?.querySelector('[data-readout]')||{}).textContent||""})()`);const capture = async (selector, scale = 1, region) => {const box = await boxOf(selector);const x = box.x + box.sx;@@ -191,7 +192,7 @@ async function main() {for (const action of actions) {const [kind, ...args] = action;if (kind === "wait") await sleep(args[0]);- else if (kind === "scroll") await evaluate(`(()=>{const el=document.querySelector(${JSON.stringify(args[0] ?? ".iso-plate")});if(el)el.scrollIntoView({block:"center"})})()`);+ else if (kind === "scroll") await evaluate(`(()=>{const el=${targetOf(args[0])};if(el)el.scrollIntoView({block:"center"})})()`);else if (kind === "move") {const box = await boxOf(args[0]);const to = [box.x + box.w * args[1], box.y + box.h * args[2]];@@ -221,7 +222,7 @@ async function main() {await send("Input.dispatchMouseEvent", { type: "mouseReleased", x: to[0], y: to[1], button: "left", buttons: 0, clickCount: 1 });mouse = to;} else if (kind === "key") {- await evaluate(`(()=>{const el=document.querySelector(${JSON.stringify(args[1] ?? '[tabindex="0"]')});if(el)el.focus()})()`);+ await evaluate(`(()=>{const el=${targetOf(args[1], '[tabindex="0"]')};if(el)el.focus()})()`);const key = args[0];const named = { " ": "Space", "-": "Minus", "=": "Equal", ",": "Comma", ".": "Period", "/": "Slash", ";": "Semicolon", "'": "Quote", "[": "BracketLeft", "]": "BracketRight", "\\": "Backslash", "`": "Backquote" };const code = args[2] ?? (named[key] ?? (/^[0-9]$/.test(key) ? `Digit${key}` : key.length === 1 ? `Key${key.toUpperCase()}` : key));@@ -244,7 +245,7 @@ async function main() {else if (kind === "shot") {const [out, selector, scale, region] = args;save(out, await capture(selector, scale ?? 1, region));- console.log(`shot ${out} · readout "${await readout()}"`);+ console.log(`shot ${out} · readout "${await readout(selector)}"`);} else if (kind === "sheet") {const [out, every, count, selector, scale, region, columns] = args;const frames = [];@@ -252,7 +253,7 @@ async function main() {for (let index = 0; index < count; index++) {if (index) await sleep(every);frames.push(await capture(selector, scale ?? 0.5, region));- texts.push(await readout());+ texts.push(await readout(selector));}const tiled = await evaluate(`(async()=>{const frames=${JSON.stringify(frames)};const cols=${columns ?? Math.min(count, 6)};const images=await Promise.all(frames.map(src=>new Promise(done=>{const image=new Image();image.onload=()=>done(image);image.src="data:image/png;base64,"+src})));const w=images[0].width,h=images[0].height,rows=Math.ceil(images.length/cols);const canvas=document.createElement("canvas");canvas.width=w*cols;canvas.height=h*rows;const ctx=canvas.getContext("2d");ctx.fillStyle="#808080";ctx.fillRect(0,0,canvas.width,canvas.height);images.forEach((image,index)=>{ctx.drawImage(image,(index%cols)*w,Math.floor(index/cols)*h);ctx.fillStyle="#ff00aa";ctx.font="bold 12px monospace";ctx.fillText(String(index),(index%cols)*w+6,Math.floor(index/cols)*h+16)});return canvas.toDataURL("image/png").split(",")[1]})()`);save(out, tiled);diff --git a/scripts/line-ends.mjs b/scripts/line-ends.mjsindex 4fc4085..51491c8 100644--- a/scripts/line-ends.mjs+++ b/scripts/line-ends.mjs@@ -1,5 +1,6 @@function lineEnds({ select = null, tolerance = 1, root: rootSlack = 2, mark = 7, least = 0.3, cover = 0.5, show = false } = {}) {- const plate = (select && document.querySelector(select)) || document.querySelector(".iso-plate") || document.body;+ const plate = select == null ? document.querySelector(".iso-plate") || document.body : document.querySelector(select);+ if (!plate) throw new Error(`Line target not found: ${select}`);const box = plate.getBoundingClientRect();const style = document.createElement("style");style.textContent = `${select || ".iso-plate"} *{pointer-events:none!important}${select || ".iso-plate"} svg,${select || ".iso-plate"} svg *{pointer-events:visiblePainted!important}`;