diff --git a/docs/accepted.md b/docs/accepted.md index 24f1ece..3f3dd80 100644 --- a/docs/accepted.md +++ b/docs/accepted.md @@ -50,7 +50,9 @@ the same page with different fonts and anti-aliasing, so entries accepted on a M back stale on a Linux CI runner. For CI, accept in CI ([github-action.md](github-action.md)). The same goes for renderdiff upgrades that change what counts as a changed pixel (0.3.2 lowered the threshold): accepted regions can come back with a new box, so re-accept once -you've looked. +you've looked. Likewise, a region whose element only resized inside a parent whose own style +changed now names that parent too, so its accepted entry no longer matches: re-accept it, in +CI. A shot whose pages differ in width, or in height without the rows aligning into bands, is never accepted: the padding past the shorter page belongs to no band or region, so no diff --git a/docs/output.md b/docs/output.md index e3f48ad..adfacbe 100644 --- a/docs/output.md +++ b/docs/output.md @@ -58,7 +58,7 @@ per-shot output when piped, `--no-progress` the summary on a terminal. | `text -"Pricing"` | A line of visible text only the reference has (`+`: only your change). Up to three, then `(+N more)`. | | `dom sel prop a→b` | Element on both sides whose computed `prop` differs, left value first. | | `dom +sel` / `-sel` | Element only on the left / only on the right. `+sel::before` / `-sel::after`: a pseudo-element only that side generates. | -| `dom sel x+8` | It moved without its own style changing; the neighbour or parent listed after it is the cause. | +| `dom sel x+8` | It moved or only resized (a width or height change alone is usually a consequence); a neighbour or parent that changed is listed after it. None listed: its own size rule or something higher up is the cause, so use `--computed`. | | `dom sel` | On both sides and unchanged in style or position, so its own pixels changed (an image or canvas). | | `(re-parented)` | After a `dom` entry: paired across a structure change, so its properties may not be the cause. | | `1 accepted` | That many of the shot's changes are accepted; the rest are new. | @@ -152,8 +152,10 @@ right after the shot. Each is a CSS selector unique on its side, so `--selector` - `-sel "text"` exists only on the right, `+sel` only on the left. - `sel margin-left 24px→16px` is on both, with the computed properties that differ, left first. A computed value is a symptom: find the rule that set it. -- `sel x+8` moved without a style of its own changing, so the cause is a neighbour or its - parent, which is listed after it when one of them changed. +- `sel x+8` or `sel width 230px→254px` moved or only resized: a width or height change alone + is usually a consequence. A neighbour or parent that changed is listed after it; for an + element that resized, a parent whose only change is its width isn't. None listed, its own + size rule or something higher up is the cause, so use `--computed`. - `-sel::before` / `+sel::before` is a pseudo-element only the right / left generates, and `sel::after height 1px→2px` one on both whose `content`, size, background, top or bottom border, or `box-shadow` differ. It carries `(re-parented)` when its element does. @@ -337,8 +339,9 @@ aria: identical on 2 of 3 route(s), differs /pricing A line diff of each side's visible text (`document.body.innerText`, or the element's with a selector). `+` / `text.added`: lines only your change (left) has. `-` / `text.removed`: lines only the reference (right) has. The card lists the first 20. Masked elements are left -out. Unmasked text that changes per load (a ticker, a clock) shows up here whenever the two -sides differed at capture time, even when its pixels were painted out as unstable. +out, and so are the ones a `varies` recheck painted out when it located them. Text that changes within one +load (a ticker) shows up here whenever the two sides differed at capture time, even when its +pixels were painted out as unstable. ## Unstable pixels diff --git a/skills/renderdiff/reference.md b/skills/renderdiff/reference.md index 4d426f5..49b30d6 100644 --- a/skills/renderdiff/reference.md +++ b/skills/renderdiff/reference.md @@ -117,7 +117,7 @@ on stderr: `✗ 2 routes differ (10 shots).` (`below 97.00%` with `--threshold`) | ` dom …` | Up to three elements behind the changes, two properties each. `dom @1440 …`: from the first width of the row. | | ` crops …` | At most three crop PNGs per shot (bands first, tallest first, then largest regions), relative to `results.json`. | | ` @w ERROR …` | Unmeasured. Grouped across widths sharing a message. See Errors. | -| `varies /a @1440 Npx sel` | A differing shot's right side, reloaded in a fresh context, differed from its first load there. Painted out on both sides like a mask, left out of the score (clean if nothing else differs), never accepted. Then ` --mask '…'` and ` masks: [{ …, reason: "varies per load" }]`: confirm it with a base-vs-base baseline before you use either. Ends in `layout moved` (a named element was pushed elsewhere, same text): no suggestion, the page itself shifts per load. Off with `--no-recheck` and under `--cache-right`. | +| `varies /a @1440 Npx sel` | A differing shot's right side, reloaded in a fresh context, differed from its first load there. Painted out on both sides like a mask, its text left out of `text` like masked text when the element was located, left out of the score (clean if nothing else differs), never accepted. Then ` --mask '…'` and ` masks: [{ …, reason: "varies per load" }]`: confirm it with a base-vs-base baseline before you use either. Ends in `layout moved` (a named element was pushed elsewhere, same text): no suggestion, the page itself shifts per load. Off with `--no-recheck` and under `--cache-right`. | | `renderdiff: D of R routes differ (S of T shots), E errors, worst …` | `S` counts unaccepted shots with any differing pixel; `worst` leaves accepted shots out. With unstable pixels: `, U unstable (max Npx)` after the errors. With `--threshold`: `, K below 97.00%`. | **Row tokens**, in order @@ -133,7 +133,7 @@ on stderr: `✗ 2 routes differ (10 shots).` (`below 97.00%` with `--threshold`) | `3 reg` / `2–3 reg` | Regions: connected patches of differing pixels on a 16px grid. With bands, from the realigned rows, so content a band merely pushed isn't one. | | `unstable 1,204px within 928×160 at (256,168)` | Pixels that kept changing between shots of the same load on one origin (ticker, carousel, video with `--no-freeze-video`), and the one box holding them all (`@w`: from that width). Painted out on both sides, excluded from the score; the route is never clean. `unstableBox` in results.json; don't search the PNG's magenta, masks are magenta too. | | `1 accepted` | That many of the shot's bands and regions are accepted; the rest are new. `dom` names only the new. | -| `text +"x" -"y"` | Lines of visible text only on the left (`+`) / right (`-`), added first. Up to three, then `(+N more)`. Masked elements are left out. | +| `text +"x" -"y"` | Lines of visible text only on the left (`+`) / right (`-`), added first. Up to three, then `(+N more)`. Masked elements, and located `varies` ones, are left out. | | `findings: N repeated on 2+ routes` | After the routes: each `dom` entry, text line or element-less `band -24px` seen on 2+ routes once, `×N routes /a@1440,375 …`, most widespread first, accepted aside; text lines on exactly the same shots share one line (`text -"Users" -"Docs" (+9 more)`), N counts printed lines; top 20, all in `summary.findings`, one per text line. One cause: fix it once. The same selector can be a different element per route: check one crop. | **`dom` entries** (left first, `;`-separated) @@ -144,7 +144,7 @@ on stderr: `✗ 2 routes differ (10 shots).` (`below 97.00%` with `--threshold`) | `sel "old"→"new"` | Its text differs. | | `+sel "x"` / `-sel "x"` | Only on the left / only on the right. | | `+sel::before` / `-sel::after` | A pseudo-element only the left / right generates. `sel::before height 1px→2px`: on both, differing in `content`, size, background, top/bottom border or `box-shadow`. A lost divider often shows only here. | -| `sel x+8 y-4` | It moved or resized, no style of its own changed: the neighbour or parent listed after it is the cause; none listed, look above it. | +| `sel x+8 y-4` | It moved or only resized: a width or height change alone is usually a consequence. A neighbour or parent that changed is listed after it (for one that resized, not a parent that only changed width). None listed: its own size rule or something higher up is the cause, so use `--computed`. | | `sel` (nothing after) | On both, unchanged and unmoved: its own pixels changed (image source, canvas, SVG). Open the crop. | | `… (re-parented)` | Paired across a structure change (grandparent/parent tags differ); its properties may not be the cause. Open the crop. | | no `dom` line | Nothing named: a band holds nothing only one side has, past the first five bands and regions, fixed chrome covering it, shadow DOM or iframe, or the 5s probe timed out. Open the crop. | diff --git a/src/capture.ts b/src/capture.ts index 25d8ffd..9f49248 100644 --- a/src/capture.ts +++ b/src/capture.ts @@ -269,6 +269,63 @@ function adoptCss(css: string) { document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet]; } +/** + * `root`'s innerText lines (the body's when null), whitespace collapsed, empty lines dropped, + * read with `masks` hidden; visibility keeps layout. Also what the blank check needs. + */ +export async function readText(page: Page, root: Locator | null, masks: Locator[]) { + const hidden: (string | null)[][] = []; + try { + for (const l of masks) { + hidden.push( + await l.evaluateAll((els) => + els.map((e) => { + const prev = e.getAttribute("style"); + (e as HTMLElement).style.visibility = "hidden"; + return prev; + }), + ), + ); + } + const { innerText, ...rest } = await (root ?? page.locator(":root")).evaluate((root) => { + const body = document.body ?? document.documentElement; + return { + scrollHeight: document.documentElement.scrollHeight, + innerText: + ((root === document.documentElement ? body : root) as HTMLElement).innerText || "", + pageText: body.innerText?.length ?? 0, + media: Array.from( + document.querySelectorAll( + "img, svg, canvas, video, iframe, input, textarea, select, [data-renderdiff-rendered]", + ), + ).some((e) => { + const r = e.getBoundingClientRect(); + return r.width * r.height >= 1024; + }), + }; + }); + const text = innerText + .split("\n") + .map((line) => line.replace(/\s+/g, " ").trim()) + .filter(Boolean); + return { text, ...rest }; + } finally { + // Reverse order, so an element two masks share gets its original value back. + // The attribute itself: an emptied `style=""` would read as a markup change to --computed. + for (let i = hidden.length - 1; i >= 0; i--) { + await masks[i]!.evaluateAll( + (els, prev) => + els.forEach((e, j) => { + const v = prev[j]; + if (v === null || v === undefined) e.removeAttribute("style"); + else e.setAttribute("style", v); + }), + hidden[i]!, + ); + } + } +} + export async function capture( page: Page, url: string, @@ -378,56 +435,14 @@ export async function capture( throw new Error(`selector "${selector}" matched ${n} elements ${where}, expected 1`); } - // Masks only paint the PNG, so hide them for the text read too; visibility keeps layout. const masks = masksFor(cfg, page, route); - const hidden: string[][] = []; - for (const l of masks) { - hidden.push( - await l.evaluateAll((els) => - els.map((e) => { - const prev = (e as HTMLElement).style.visibility; - (e as HTMLElement).style.visibility = "hidden"; - return prev; - }), - ), - ); - } const marked = await page.locator("[data-renderdiff-mask]").evaluateAll((els) => els.map((e) => { const v = e.getAttribute("data-renderdiff-mask"); return v ? `${v} (data-renderdiff-mask)` : "data-renderdiff-mask"; }), ); - const { scrollHeight, innerText, pageText, media } = await (el ?? page.locator(":root")).evaluate( - (root) => { - const body = document.body ?? document.documentElement; - return { - scrollHeight: document.documentElement.scrollHeight, - innerText: - ((root === document.documentElement ? body : root) as HTMLElement).innerText || "", - pageText: body.innerText?.length ?? 0, - media: Array.from( - document.querySelectorAll( - "img, svg, canvas, video, iframe, input, textarea, select, [data-renderdiff-rendered]", - ), - ).some((e) => { - const r = e.getBoundingClientRect(); - return r.width * r.height >= 1024; - }), - }; - }, - ); - // Reverse order, so an element two masks share gets its original value back. - for (let i = masks.length - 1; i >= 0; i--) { - await masks[i]!.evaluateAll( - (els, prev) => els.forEach((e, j) => ((e as HTMLElement).style.visibility = prev[j] ?? "")), - hidden[i]!, - ); - } - const text = innerText - .split("\n") - .map((line) => line.replace(/\s+/g, " ").trim()) - .filter(Boolean); + const { scrollHeight, text, pageText, media } = await readText(page, el, masks); const blank = pageText < 200 && !media ? `height=${scrollHeight}, text=${pageText} chars` : null; step.set(page, "screenshot"); diff --git a/src/locate.ts b/src/locate.ts index 9ffc163..261282d 100644 --- a/src/locate.ts +++ b/src/locate.ts @@ -531,6 +531,10 @@ const same = (a: Seen, b: Seen) => !!(a.text || b.text) || (a.tag === b.tag && Math.abs(a.box.w - b.box.w) <= 4 && Math.abs(a.box.h - b.box.h) <= 4); +/** A change besides width and height, which are usually a consequence. */ +const own = (changed: ElementDiff["changed"]) => + Object.keys(changed).some((p) => p !== "width" && p !== "height"); + const moved = (a: Box, b: Box) => a.x !== b.x || a.y !== b.y || a.w !== b.w || a.h !== b.h; const handles = async (ls: Locator[]) => @@ -709,8 +713,10 @@ export async function locate( el.reparented ? { ...p, reparented: el.reparented } : p, ), ); - // ponytail: one level of cause; a deeper cascade search if agents ask for it - if (el.left && el.right && !Object.keys(el.changed).length && moved(el.left, el.right)) { + // ponytail: one level of cause; deeper than the parent, --computed names the rule + if (el.left && el.right && !own(el.changed) && moved(el.left, el.right)) { + // A pushed element's cause can be a parent that only resized; a resized one's can't. + const resized = Object.keys(el.changed).length > 0; for (const [p, q] of [ [a!.prev, b!.prev], [a!.parent, b!.parent], @@ -718,7 +724,7 @@ export async function locate( if (!p || !q || p.sel !== q.sel) continue; const cause = element([p, q], [shots[0].origin, shots[1].origin]); if ( - Object.keys(cause.changed).length && + (resized ? own(cause.changed) : Object.keys(cause.changed).length) && !out.some((o) => o.selector === cause.selector) ) { out.push(cause); diff --git a/src/run.ts b/src/run.ts index cf3e1ac..ce17c38 100644 --- a/src/run.ts +++ b/src/run.ts @@ -7,7 +7,16 @@ import { chromium, errors, type Browser, type BrowserContext, type Page } from " import sharp from "sharp"; import { applyAccepted, readAccepted, unacceptable, updateAccepted } from "./accept.ts"; import { CACHE_DIR, cacheFile, replayable, REPLAY_TTL, saveRecording, shotId } from "./cache.ts"; -import { bbox, cancelUnstable, capture, HookError, prepare, step, type Shot } from "./capture.ts"; +import { + bbox, + cancelUnstable, + capture, + HookError, + prepare, + readText, + step, + type Shot, +} from "./capture.ts"; import { compare, crops, type Band, type Box, type Region } from "./compare.ts"; import { diffAria, @@ -480,10 +489,36 @@ export async function run({ return own.length ? own : [g]; }), ); + // Only what changed its text: a pushed element's text is still the page's. + const sels = variesSels( + regions + .flatMap((g) => g.elements ?? []) + .filter((e) => e.side !== "both" || e.changed.text), + ); + // Both or neither, each settled so no page is left hidden when locate reads it. + const [lt, rt] = sels.length + ? await Promise.all( + (["left", "right"] as const).map((side) => + readText( + pages[side], + route.selector ? pages[side].locator(route.selector[side]) : null, + [ + ...masksFor(cfg, pages[side], route), + ...sels.map((s) => pages[side].locator(s)), + ], + ).then( + (t) => t.text, + () => null, + ), + ), + ) + : []; + const both = lt && rt; const u = rightShot.unstable; - const l = { ...leftShot, png: raw[0] }; + const l = { ...leftShot, png: raw[0], ...(both && { text: lt }) }; const r = { ...rightShot, + ...(both && { text: rt }), png: raw[1], unstable: u ? mask.map((v, i) => v | u[i]!) : mask, }; @@ -1096,16 +1131,16 @@ async function boxMask(png: Buffer, boxes: Box[]): Promise { /** A selector ending in a bare tag, maybe `:nth-of-type(n)`: masking it would hide real changes. */ const BARE = /(^|[\s>+~])[a-z][\w-]*(:nth-of-type\(\d+\))?$/; +/** Distinct selectors of `els`, a pseudo-element's as its host's. */ +const variesSels = (els: ElementDiff[]) => [ + ...new Set(els.map((e) => e.selector.replace(/::\w+$/, ""))), +]; + /** Routes whose right side differed between two loads, and the mask that would cover it. */ export function fmtVaries(results: RouteResult[], routes: string[]): string[] { const rows = results.filter((r): r is ComparedResult => r.status === "compared" && !!r.varies); - const selectors = (rs: ComparedResult[]) => [ - ...new Set( - rs.flatMap((r) => - r.varies!.flatMap((g) => g.elements ?? []).map((e) => e.selector.replace(/::\w+$/, "")), - ), - ), - ]; + const selectors = (rs: ComparedResult[]) => + variesSels(rs.flatMap((r) => r.varies!.flatMap((g) => g.elements ?? []))); // Pushed, not changed itself: a counter resizes its own box, a reflow moves its neighbours'. const moved = (r: ComparedResult) => r.varies!.some((g) => diff --git a/tests/visual/computed.test.ts b/tests/visual/computed.test.ts index 3692a0d..f12483e 100644 --- a/tests/visual/computed.test.ts +++ b/tests/visual/computed.test.ts @@ -8,7 +8,7 @@ import { after, before, test } from "node:test"; import { chromium, type Browser, type Page } from "playwright"; import { diffSnapshots } from "../../src/computed.ts"; import { locate, PROPS, snapshot, snapshotStates } from "../../src/locate.ts"; -import type { Shot } from "../../src/capture.ts"; +import { readText, type Shot } from "../../src/capture.ts"; import type { Region } from "../../src/compare.ts"; let browser: Browser; @@ -210,3 +210,13 @@ test("a lint autofix swapping wrapping or clipping keywords is a finding, not in ["body > span.h", "clip-path"], ]); }); + +test("hiding for the text read leaves each style attribute as it was", async () => { + const body = `

a

b

c

`; + const p = await page(body); + const ps = p.locator("p:nth-of-type(-n + 2)"); + const { text } = await readText(p, null, [ps, ps]); + assert.deepEqual(text, ["c"]); + assert.equal(await p.evaluate(() => document.body.innerHTML), body); + await p.close(); +}); diff --git a/tests/visual/controls.test.ts b/tests/visual/controls.test.ts index f94a938..71d2449 100644 --- a/tests/visual/controls.test.ts +++ b/tests/visual/controls.test.ts @@ -29,6 +29,7 @@ import { cleanupTempDirs, context, runCli, + tempDir, renderdiffArgs, type CliResult, } from "../helpers/cli.ts"; @@ -267,6 +268,71 @@ for (const width of WIDTHS) { }); } +const hooked = (body: string) => { + const file = path.join(tempDir(), "hook.mjs"); + fs.writeFileSync(file, `export default { before: async (page, { side }) => { ${body} } };\n`); + return runCli( + renderdiffArgs({ + left: site.left, + right: site.right, + routes: ["/flex-vs-grid"], + widths: [1440], + config: file, + }), + ); +}; + +test("an element that only resized names the parent whose own style changed, after it", async () => { + const r = await hooked( + `if (side === "left") await page.addStyleTag({ content: ".deck .card:nth-child(2) { padding-left: 40px }" });`, + ); + const named = result(results(r.outDir), "/flex-vs-grid", 1440).regions.flatMap( + (g) => g.elements ?? [], + ); + const card = named.find((e) => e.selector === "article.card:nth-of-type(2)"); + assert.deepEqual(card?.changed, { "padding-left": ["40px", "16px"] }, context(r)); + assert.ok( + named.some((e) => e.selector === "article.card:nth-of-type(2) > h3"), + context(r), + ); + assert.match( + parseSummary(r.stdout).routes.get("/flex-vs-grid")!.rows[0]!.dom ?? "", + /^(?:[^;]+; ){0,2}article\.card:nth-of-type\(2\) padding-left/, + ); +}); + +test("an element only pushed names the parent that only resized", async () => { + const r = await hooked( + `await page.evaluate(() => document.querySelector(".page").insertAdjacentHTML("afterbegin", '
')); + await page.addStyleTag({ content: ".wrap { max-width: 400px } .box { width: 96px; height: 48px; margin: 0 auto; background: #c62828 }" + (side === "left" ? " .wrap { max-width: 600px }" : "") });`, + ); + const named = result(results(r.outDir), "/flex-vs-grid", 1440).regions.flatMap( + (g) => g.elements ?? [], + ); + const box = named.find((e) => e.selector.endsWith("div.box")); + assert.deepEqual(box && [box.changed, box.left!.x - box.right!.x], [{}, 100], context(r)); + const wrap = named.find((e) => e.selector.endsWith("div.wrap")); + assert.deepEqual(wrap?.changed, { width: ["600px", "400px"] }, context(r)); +}); + +test("an element whose own width changed, or whose parent only resized, gets no cause", async () => { + const r = await hooked( + `await page.evaluate(() => { const c = document.querySelectorAll(".deck .card")[4]; const d = document.createElement("div"); d.className = "inner"; d.append(...c.childNodes); c.append(d); }); + if (side === "left") await page.addStyleTag({ content: ".deck .card:nth-child(4) p { width: 200px } .deck .inner { width: 200px }" });`, + ); + const named = result(results(r.outDir), "/flex-vs-grid", 1440).regions.flatMap( + (g) => g.elements ?? [], + ); + assert.deepEqual( + named.map((e) => [e.selector, Object.keys(e.changed)]).sort(), + [ + ["article.card:nth-of-type(4) > p", ["width", "height"]], + ["div.inner > p", ["width", "height"]], + ], + context(r), + ); +}); + for (const width of WIDTHS) { test(`divider @${width} names the lost ::before line, and the card's re-parented pairing`, () => { const r = result(results(run.outDir), "/divider", width); diff --git a/tests/visual/guardrails.test.ts b/tests/visual/guardrails.test.ts index dd2928a..cb8ccf9 100644 --- a/tests/visual/guardrails.test.ts +++ b/tests/visual/guardrails.test.ts @@ -622,6 +622,8 @@ describe("masks", () => { assert.equal(r.diffPixels, 0, context(run)); assert.ok(r.variesPixels! > 0, context(run)); assert.match(r.varies![0]!.elements![0]!.selector, /drift/, context(run)); + assert.deepEqual(r.text, { added: [], removed: [] }, context(run)); + assert.doesNotMatch(run.stdout, /text: |text [+-]"/, context(run)); assert.match(run.stdout, /^varies \/drifting @1440 [\d,]+px painted out /m); assert.match(run.stdout, /^ {2}--mask '/m); assert.match(run.stdout, /urlPath: "\/drifting", reason: "varies per load" \}\]$/m); @@ -640,12 +642,17 @@ describe("masks", () => { const hook = path.join(dir, "hook.mjs"); fs.writeFileSync( hook, - `export default { before: async (page, { side }) => { if (side === "left") await page.addStyleTag({ content: "h1 { color: red }" }); } };\n`, + `export default { before: async (page, { side }) => { if (side === "left") { await page.addStyleTag({ content: "h1 { color: red }" }); await page.evaluate(() => (document.querySelector("h1").textContent += " changed")); } } };\n`, ); const run = await capture(["/drifting"], { config: hook, extra: ["--accept", "x"] }); const r = result(results(run.outDir), "/drifting", 1440); assert.ok(r.diffPixels > 0, context(run)); assert.ok(r.variesPixels! > 0, context(run)); + assert.deepEqual( + r.text, + { added: ["Drifting value guard rail changed"], removed: ["Drifting value guard rail"] }, + context(run), + ); assert.match( run.stdout, /not accepted: 1 differing shot\(s\) can't be \(1 varies per load\)/,