Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/accepted.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 8 additions & 5 deletions docs/output.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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

Expand Down
6 changes: 3 additions & 3 deletions skills/renderdiff/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
Expand All @@ -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. |
Expand Down
101 changes: 58 additions & 43 deletions src/capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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");
Expand Down
12 changes: 9 additions & 3 deletions src/locate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[]) =>
Expand Down Expand Up @@ -709,16 +713,18 @@ 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],
] as Pair[]) {
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);
Expand Down
53 changes: 44 additions & 9 deletions src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
};
Expand Down Expand Up @@ -1096,16 +1131,16 @@ async function boxMask(png: Buffer, boxes: Box[]): Promise<Uint8Array> {
/** 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) =>
Expand Down
12 changes: 11 additions & 1 deletion tests/visual/computed.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 = `<p>a</p><p style="color: red">b</p><p>c</p>`;
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();
});
Loading
Loading