diff --git a/README.md b/README.md
index 3c24649..e93f15d 100644
--- a/README.md
+++ b/README.md
@@ -110,6 +110,7 @@ renderdiff [options]
| `--accept ` | Record this run's differences as accepted, with a reason. See **Accepted differences and reruns**. |
| `--rerun-failed` | Rerun only what the last run in `--out` didn't find clean or accepted, keeping the rest. |
| `--cache-right` | Replay the right side's network traffic from the last `--cache-right` run in `--out`, when it's under an hour old and covers every shot; otherwise load it live and record it. Keeps `/.cache/` when the out dir is wiped. See **Accepted differences and reruns**. |
+| `--computed` | Also diff the computed style of every rendered element and its `::before`/`::after`, and say per route whether the markup is identical apart from asset hashes. Pixels still decide the score and exit code. See [docs/output.md](docs/output.md#computed-styles---computed). |
| `--dry-run` | Print the URL pairs and exit. No browser. |
| `--open` | Open the report when the run finishes. |
| `--progress` | A line per shot as it finishes, then the worst scores. The default on a terminal; piped, renderdiff prints one compact summary at the end. |
@@ -194,6 +195,7 @@ only.
| `dom +sel` / `-sel` | Element only on the left / only on the right. |
| `dom sel x+8` | It moved without its own style changing; the neighbour or parent listed after it is the cause. |
| `dom sel` | On both sides and unchanged in style or position, so its own pixels changed (an image or canvas). |
+| `computed: N findings` | With `--computed`: each `key prop left→right` once, with the routes and widths it was seen at; `dom identical`: the markup matches apart from asset hashes and generated class names, so look at CSS or script. |
| `crops …` | Up to 3 PNGs per comparison, bands first, relative to `results.json`. Left is on top or on the left, and the change is boxed in red. |
| `ERROR …` | Unmeasured, which is neither a pass nor a fail. Exits 3. |
| `accepted:` / `stale accepted:` | Shots whose every difference was accepted, and accepted entries the run no longer saw. See below. |
@@ -276,6 +278,7 @@ Everything lands in the out dir (`./renderdiff-out` by default):
}],
"text": { "added": [], "removed": ["Pricing"] }, // added: left only; removed: right only
"failed": { "left": [], "right": [] }, // stylesheets and font faces that didn't load: "font Inter 700", "stylesheet https://…"
+ "computed": { "dom": 1, "changes": [], "truncated": 0, "unmatched": { "left": [], "right": ["body > nav > a[href=\"/pricing\"]"] } }, // --computed only; null: snapshot failed, "computedError" says why
"images": { "left": "about.1440.left.png", "right": "about.1440.right.png", "diff": "about.1440.diff.png" },
"crops": [{
"path": "about.1440.c1.png", "kind": "band", // or "region"
@@ -292,7 +295,8 @@ Everything lands in the out dir (`./renderdiff-out` by default):
"belowThreshold": 0, // accepted shots aside
"differing": 1, // shots with any differing pixel, accepted ones aside
"accepted": 0, // shots whose every difference was accepted
- "stale": [] // accepted entries the run measured but didn't see
+ "stale": [], // accepted entries the run measured but didn't see
+ "computed": [] // --computed: { key, prop, values: [left, right], at: [{ url, widths }] }
}
}
```
diff --git a/docs/output.md b/docs/output.md
index efdbfdf..39198de 100644
--- a/docs/output.md
+++ b/docs/output.md
@@ -120,6 +120,64 @@ band names only what one side added, not what it pushed down, so it can name not
fixed chrome covers isn't named. Probing gives up after 5s, leaving the elements out. Shadow
DOM and iframes aren't searched.
+## Computed styles (`--computed`)
+
+With `--computed`, after the shot renderdiff reads the computed style of every rendered
+element on both sides: the properties `dom` compares, plus `content`, and `::before` and
+`::after` wherever they generate content. Masked subtrees and `script`/`style`-like tags
+are skipped; a `display: none` element is read, its subtree isn't. Script-driven
+animations are finished first. The summary gets one block, after the rows:
+
+```
+computed: 2 findings; dom identical on 2 of 3 route(s), differs /pricing (1), so findings there are hints
+ body > div.page > nav.chips > a[href="#blog"] margin-left 24px→16px /about@1440,375 /@1440,375
+ body > footer > a.cta::after content "→"→none /about@1440
+ unmatched /pricing@1440 -body > main > section.plans:nth-of-type(3)
+```
+
+- Each finding is `key property left→right`, left first like `dom`, followed by every
+ route and width it was seen at. The same change on 300 pages is one line, most widespread
+ first, accepted shots included. The summary shows 20; `summary.computed` in results.json
+ has them all. Each result's `computed.changes` keeps its first 500, and `truncated`
+ counts the rest (the summary says where).
+- The key is a selector path from `body`, or from `:scope` with `--selector`, where only
+ the selected element's subtree is walked. Each step is the id, or the tag with a naming
+ attribute and up to two classes that don't look generated (sorted). `:nth-of-type` is
+ added only where siblings would otherwise share the step, a duplicated id included. The
+ key works with `querySelector`.
+ - Elements are matched by key, not by position, so a cookie banner injected on one side
+ doesn't misalign everything after it.
+ - An inserted sibling of the same tag and classes still shifts the `:nth-of-type` of the
+ ones after it.
+ - A class renamed on an ancestor unmatches its whole subtree.
+- One change high in the tree is one finding. An inherited property (`font-*`,
+ `line-height`, `letter-spacing`, `text-*`, `white-space`, `color`, `visibility`) is
+ dropped where the parent has the same change, so a `body` font change is one line, not
+ one per element. A `width` is dropped inside a parent whose width changed, and a
+ `height` around a child whose height changed, so the box that caused it is what's left.
+- An element shown on one side and `display: none` on the other is one `display` finding;
+ its subtree counts neither as unmatched nor against `dom identical`.
+- A `::before`/`::after` that only one side generates shows as `content` against `none`.
+ That is how a removed rule that drew an icon shows up.
+- `dom identical` means that on every width, each walked element's tag, attributes and own
+ text are the same on both sides.
+ - Bundler hashes in `src`/`href`/`srcset` are ignored (`hero.3f9a8c1d.png`, `?v=…`), and
+ so are generated class names (`css-1q2w3e`, `Button_root__a1b2c`).
+ - A pixel difference on such a route comes from CSS or script, not from walked markup.
+ SVG internals, shadow DOM, iframes and `display: none` subtrees aren't walked.
+ - Hash-shaped tokens only: 8 or more letters and digits that alternate, between
+ separators in a file name. `team_photo_2024.jpg` and `/p/abcdef123456` count as changes.
+- `dom differs (N)` counts the elements that differ or that one side lacks. Treat that
+ route's findings as hints.
+- `unmatched` lists the outermost elements only one side has: `+` left, `-` right. The
+ summary shows five routes, five each.
+- The HTML report shows the same block and puts `dom identical` / `dom differs (N)` on each
+ card. A snapshot that fails, takes over 15s or meets more than 50,000 elements is
+ reported as failed, with why (`computed: null`, `computedError`), and the pixel result
+ stands. Pixels still decide the score and the exit code.
+
+`:hover`/`:focus` states aren't snapshotted.
+
## Text
A line diff of each side's visible text (`document.body.innerText`, or the element's with a
diff --git a/renderdiff.config.example.ts b/renderdiff.config.example.ts
index d12be20..9485ef7 100644
--- a/renderdiff.config.example.ts
+++ b/renderdiff.config.example.ts
@@ -79,6 +79,10 @@ export default {
// a selector list cannot express.
extraCss: `.hero video { visibility: hidden !important }`,
+ // Also diff every element's computed style, and say whether the markup is identical
+ // apart from asset hashes. Same as --computed. Pixels still decide the score.
+ computed: false,
+
// Content that renders on both sides but whose value drifts. Painted over on both,
// so the noise cancels out instead of scoring against you.
//
diff --git a/skills/renderdiff/SKILL.md b/skills/renderdiff/SKILL.md
index cc2f7fd..9a28e5f 100644
--- a/skills/renderdiff/SKILL.md
+++ b/skills/renderdiff/SKILL.md
@@ -41,6 +41,9 @@ legitimate: [reference.md](reference.md).
6. `dom` before crops. `sel prop l→r`: computed value, left first; find the *rule*.
`+sel`/`-sel`: only left/right. `sel x+8`: moved; the cause is listed after it.
Bare `sel`: its own pixels changed (image, canvas).
+ CSS refactor or dead-CSS removal: add `--computed`. Each `computed:` finding is
+ `key prop left→right`, collapsed across routes and widths. `dom identical` means the
+ cause is CSS or JS, not markup.
7. `Read` the crops under each row (next to results.json) for what `dom` doesn't explain.
Left is on top or left; red box = change, red seam = missing rows.
8. Fix or justify every band, region and text line. After each migration step,
diff --git a/skills/renderdiff/reference.md b/skills/renderdiff/reference.md
index f16efc4..41ad42e 100644
--- a/skills/renderdiff/reference.md
+++ b/skills/renderdiff/reference.md
@@ -55,10 +55,12 @@ px), band, their `elements` (`selector`, `side`, each side's box, `changed`, `te
`rightSelector` when the right was found under another selector; absent when not looked
at, `[]` when nothing was named), full text diff, image path and crop (`kind`, each side's box with `h` 0 at an
insertion point, `layout` `stacked` = left on top or `side` = left on the left, `scale`,
-`clipped`), `selector` (`{ left, right }` or null), one result per line, so `grep '"url":"/about"'` pulls a route.
+`clipped`), `selector` (`{ left, right }` or null), with `--computed` a `computed` per result
+(`dom`, the count of elements whose markup differs, with 0 meaning identical; `changes`
+`{ key, prop, values }`, the first 500, `truncated` counting the rest; `unmatched` keys per side; null if the snapshot failed, with `computedError`), one result per line, so `grep '"url":"/about"'` pulls a route.
Paths are relative to the out dir. `summary` has `compared`, `errors`, `mean`, `worst`,
`belowThreshold` and `differing` (unaccepted shots with any differing pixel: without
-`--threshold`, any exits 1); `meta` records origins, widths, threshold, the pinned clock, block
+`--threshold`, any exits 1), plus `computed` with `--computed`: every change once, with the routes and widths it was seen at. `meta` records origins, widths, threshold, the pinned clock, block
patterns, hidden selectors, mask reasons, the browser (`chromium`, or `chrome` when it fell
back to the system Chrome), each side's storage state file name, and `rightReplayedFrom`
(with `--cache-right`, when the replayed recording was made; also on each replayed result). `hook: true` marks a
diff --git a/src/cli.ts b/src/cli.ts
index 16fe9f0..d72e678 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -89,6 +89,7 @@ function parseArgs(argv: string[]): Args {
else if (v === "--no-progress") a.progress = false;
else if (v === "--rerun-failed") a.rerunFailed = true;
else if (v === "--cache-right") a.cacheRight = true;
+ else if (v === "--computed") a.computed = true;
else if (v === "--mask-media") a.maskMedia = true;
else if (v === "--accept") {
a.accept = next().trim();
@@ -213,6 +214,8 @@ const HELP = `
--cache-right Replay the right side's network from the last --cache-right run
in --out, if under an hour old and covering every shot; else load
it live and record it. The page still renders and is shot fresh.
+ --computed Also diff every element's computed style and ::before/::after,
+ and say whether the markup is identical. Pixels still decide.
--dry-run Print the URL pairs and exit. No browser.
--open Open the report when the run finishes.
--progress A line per shot as it finishes. The default on a terminal;
diff --git a/src/computed.ts b/src/computed.ts
new file mode 100644
index 0000000..62a6170
--- /dev/null
+++ b/src/computed.ts
@@ -0,0 +1,232 @@
+import { name } from "./config.ts";
+import { PROPS } from "./locate.ts";
+import type { ComparedResult, RouteResult } from "./report.ts";
+
+/** `--computed`: every rendered element's computed style on both sides, diffed by a stable key. */
+
+/** Selector path -> its opening tag with own text, and `PROPS` then `content`, computed. */
+export type Snapshot = Record;
+
+export interface StyleChange {
+ /** Selector path from `body`, e.g. `body > div.page > nav.chips > a[href="#blog"]`; `::before` on a pseudo-element. */
+ key: string;
+ prop: string;
+ /** [left, right], as in `ElementDiff.changed`. */
+ values: [string, string];
+}
+
+export interface ComputedDiff {
+ /** Elements whose tag, attributes (asset hashes and generated classes aside) or own text differ, or that one side lacks; 0 is "dom identical". */
+ dom: number;
+ /** At most `MAX_CHANGES`, inherited repeats of a parent's change dropped. */
+ changes: StyleChange[];
+ /** Changes past `MAX_CHANGES`, left out of `changes`. */
+ truncated: number;
+ /** Elements only that side has, outermost only, at most `MAX_UNMATCHED` per side. */
+ unmatched: { left: string[]; right: string[] };
+}
+
+/** One change, with every route and width it was seen at. */
+export interface Finding extends StyleChange {
+ at: { url: string; widths: number[] }[];
+}
+
+const MAX_CHANGES = 500;
+const MAX_UNMATCHED = 20;
+const FIELDS = [...PROPS, "content"];
+
+const INHERITED = new Set([
+ "font-family",
+ "font-size",
+ "font-weight",
+ "line-height",
+ "letter-spacing",
+ "text-align",
+ "text-transform",
+ "white-space",
+ "color",
+ "visibility",
+]);
+const DISPLAY = FIELDS.indexOf("display");
+
+const PSEUDO = /::(before|after)$/;
+const isPseudo = (key: string) => PSEUDO.test(key);
+
+const parentOf = (key: string) => {
+ if (isPseudo(key)) return key.replace(PSEUDO, "");
+ const i = key.lastIndexOf(" > ");
+ return i >= 0 ? key.slice(0, i) : "";
+};
+
+/** Letters and digits alternating at least twice: `3f9a8c1d`, not `banner2024` or `photo`. */
+const hashy = (t: string) => (t.match(/\d+|[A-Za-z]+/g)?.length ?? 0) >= 4;
+
+/** In URL attributes, bundler hashes in a file name (`main.3f9a8c1d.png`, `?v=…`) read the same on both sides. */
+export const normalizeAssets = (html: string) =>
+ // ponytail: hex/base36 hashes between separators; add a framework's build-id path when one shows up
+ html.replace(/ (src|href|srcset|poster)="([^"]*)"/g, (_, n: string, v: string) => {
+ const u = v
+ .replace(
+ /([.\-_])([A-Za-z0-9]{8,})(?=(?:[.\-_][A-Za-z0-9]+)*\.[A-Za-z0-9]{2,5}(?:$|[?#\s,]))/g,
+ (m, sep: string, t: string) => (hashy(t) ? `${sep}#` : m),
+ )
+ .replace(/([?&](?:v|ver|version|hash)=)[\w.-]+/g, "$1#");
+ return ` ${n}="${u}"`;
+ });
+
+/**
+ * Drops what a change elsewhere explains: an inherited property's change the parent has too,
+ * a width inside a parent whose width changed, a height around a child whose height changed.
+ */
+export function collapseInherited(changes: StyleChange[]): StyleChange[] {
+ const raw = new Set(changes.map((c) => `${c.key}\0${c.prop}\0${c.values.join("\0")}`));
+ const wide = new Set(changes.filter((c) => c.prop === "width").map((c) => c.key));
+ const tallKid = new Set(changes.filter((c) => c.prop === "height").map((c) => parentOf(c.key)));
+ return changes.filter((c) => {
+ const p = parentOf(c.key);
+ if (INHERITED.has(c.prop)) return !raw.has(`${p}\0${c.prop}\0${c.values.join("\0")}`);
+ if (c.prop === "width") return !wide.has(p);
+ if (c.prop === "height") return !tallKid.has(c.key);
+ return true;
+ });
+}
+
+export function diffSnapshots(left: Snapshot, right: Snapshot): ComputedDiff {
+ const html = (s: Snapshot, k: string) => (s[k] ? normalizeAssets(s[k].html) : null);
+ // Under an element `b` has display:none, so `b` never walked it: a style change, not markup.
+ const hiddenIn = (b: Snapshot, k: string) => {
+ for (let p = parentOf(k); p; p = parentOf(p)) {
+ const e = b[p];
+ if (e) return e.styles[DISPLAY] === "none";
+ }
+ return false;
+ };
+ const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
+ let dom = 0;
+ for (const k of keys) {
+ if (isPseudo(k) || html(left, k) === html(right, k)) continue;
+ if (!left[k] && hiddenIn(left, k)) continue;
+ if (!right[k] && hiddenIn(right, k)) continue;
+ dom++;
+ }
+
+ const changes: StyleChange[] = [];
+ const content = FIELDS.length - 1;
+ for (const key of keys) {
+ const [l, r] = [left[key], right[key]];
+ if (l && r) {
+ // Styles of a box that isn't rendered are noise beside the display change itself.
+ const shown = [l, r].filter((x) => x.styles[DISPLAY] !== "none").length;
+ if (shown === 1) {
+ changes.push({ key, prop: "display", values: [l.styles[DISPLAY]!, r.styles[DISPLAY]!] });
+ continue;
+ }
+ FIELDS.forEach((prop, i) => {
+ if (l.styles[i] !== r.styles[i])
+ changes.push({ key, prop, values: [l.styles[i]!, r.styles[i]!] });
+ });
+ } else if (isPseudo(key) && left[parentOf(key)] && right[parentOf(key)]) {
+ // A pseudo-element one side no longer generates: the removed rule's own finding.
+ changes.push({
+ key,
+ prop: "content",
+ values: [l?.styles[content] ?? "none", r?.styles[content] ?? "none"],
+ });
+ }
+ }
+
+ const only = (a: Snapshot, b: Snapshot) => {
+ const ks = Object.keys(a).filter((k) => !isPseudo(k) && !b[k] && !hiddenIn(b, k));
+ const set = new Set(ks);
+ return ks.filter((k) => !set.has(parentOf(k))).slice(0, MAX_UNMATCHED);
+ };
+ const kept = collapseInherited(changes);
+ return {
+ dom,
+ changes: kept.slice(0, MAX_CHANGES),
+ truncated: Math.max(0, kept.length - MAX_CHANGES),
+ unmatched: { left: only(left, right), right: only(right, left) },
+ };
+}
+
+const computedOf = (rs: RouteResult[]) =>
+ rs.filter((r): r is ComparedResult => r.status === "compared" && !!r.computed);
+
+/** Every change across routes and widths, one per (key, property, values), most widespread first. */
+export function groupFindings(results: RouteResult[]): Finding[] {
+ const out = new Map();
+ for (const r of computedOf(results)) {
+ for (const c of r.computed!.changes) {
+ const id = `${c.key}\0${c.prop}\0${c.values.join("\0")}`;
+ const f = out.get(id) ?? { ...c, at: [] };
+ out.set(id, f);
+ const url = name(r);
+ const at = f.at.find((a) => a.url === url);
+ if (at) at.widths.push(r.width);
+ else f.at.push({ url, widths: [r.width] });
+ }
+ }
+ const shots = (f: Finding) => f.at.reduce((n, a) => n + a.widths.length, 0);
+ return [...out.values()].sort((a, b) => shots(b) - shots(a) || a.key.localeCompare(b.key));
+}
+
+/** Findings shown in the console summary; results.json has them all. */
+const SHOWN = 20;
+const AT_ROUTES = 3;
+/** Unmatched routes, and keys per route, in the console summary. */
+const UNMATCHED_SHOWN = 5;
+
+/** The console block: dom per route, then one line per finding, `left→right` like `dom`. */
+export function fmtComputed(results: RouteResult[], routes: string[]): string[] {
+ const rows = results.filter(
+ (r): r is ComparedResult => r.status === "compared" && "computed" in r,
+ );
+ if (!rows.length) return [];
+ const findings = groupFindings(results);
+ const differs: string[] = [];
+ const failed: string[] = [];
+ let identical = 0;
+ for (const route of routes) {
+ const rs = rows.filter((r) => name(r) === route);
+ if (!rs.length) continue;
+ const bad = rs.find((r) => !r.computed);
+ if (bad) failed.push(`${route}@${bad.width} (${bad.computedError ?? "unknown"})`);
+ const dom = Math.max(...rs.map((r) => r.computed?.dom ?? 0));
+ if (dom) differs.push(`${route} (${dom})`);
+ else if (rs.some((r) => r.computed)) identical++;
+ }
+ const out = [
+ `computed: ${findings.length} finding${findings.length === 1 ? "" : "s"}; ` +
+ `dom identical on ${identical} of ${identical + differs.length} route(s)` +
+ (differs.length ? `, differs ${differs.join(" ")}, so findings there are hints` : "") +
+ (failed.length ? `; snapshot failed on ${failed.join(" ")}` : ""),
+ ];
+ for (const f of findings.slice(0, SHOWN)) {
+ const at = f.at
+ .slice(0, AT_ROUTES)
+ .map((a) => `${a.url}@${a.widths.join(",")}`)
+ .join(" ");
+ const more = f.at.length > AT_ROUTES ? ` +${f.at.length - AT_ROUTES} routes` : "";
+ out.push(` ${f.key} ${f.prop} ${f.values.join("→")} ${at}${more}`);
+ }
+ if (findings.length > SHOWN) out.push(` (+${findings.length - SHOWN} more in results.json)`);
+ const cut = computedOf(rows).filter((r) => r.computed!.truncated);
+ if (cut.length)
+ out.push(
+ ` truncated: only the first ${MAX_CHANGES} changes kept on ` +
+ cut.map((r) => `${name(r)}@${r.width} (+${r.computed!.truncated})`).join(" "),
+ );
+ const unmatched = routes.flatMap((route) => {
+ const r = computedOf(rows).find((x) => name(x) === route && x.computed!.dom);
+ if (!r) return [];
+ const { left, right } = r.computed!.unmatched;
+ const keys = [...left.map((k) => `+${k}`), ...right.map((k) => `-${k}`)];
+ if (!keys.length) return [];
+ const more = keys.length > UNMATCHED_SHOWN ? ` (+${keys.length - UNMATCHED_SHOWN} more)` : "";
+ return [` unmatched ${route}@${r.width} ${keys.slice(0, UNMATCHED_SHOWN).join(" ")}${more}`];
+ });
+ out.push(...unmatched.slice(0, UNMATCHED_SHOWN));
+ if (unmatched.length > UNMATCHED_SHOWN)
+ out.push(` (+${unmatched.length - UNMATCHED_SHOWN} more routes with unmatched elements)`);
+ return out;
+}
diff --git a/src/config.ts b/src/config.ts
index 676d3f0..6cec2b4 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -262,6 +262,8 @@ export interface RenderdiffConfig {
extraCss?: string;
/** Per-route regions painted over on both sides. */
masks?: Mask[];
+ /** Also diff every element's computed style, and say whether the markup is identical. */
+ computed?: boolean;
/** Mask every `iframe`, `video` and video.js text track on every route. */
maskMedia?: boolean;
}
@@ -282,6 +284,7 @@ export interface ResolvedConfig {
masks: Mask[];
/** Absolute storage state paths, checked to be JSON; null for a side without one. */
storageState: { left: string | null; right: string | null };
+ computed: boolean;
}
/** package.json's version; the same relative path resolves from `src/` and `dist/`. */
@@ -442,6 +445,7 @@ function validate(c: Record, file: string) {
bad("widths", "an array of positive numbers");
}
}
+ if (c.computed !== undefined && typeof c.computed !== "boolean") bad("computed", "a boolean");
if (c.threshold !== undefined) {
const t = c.threshold;
if (typeof t !== "number" || !Number.isFinite(t) || t < 0 || t > 1) {
@@ -490,6 +494,7 @@ export interface CliOverrides {
concurrency?: number;
/** Per side, from --storage-state / --left-storage-state / --right-storage-state. */
storageState?: { left?: string; right?: string };
+ computed?: boolean;
/** From --mask, appended to the config's masks. */
masks?: string[];
maskMedia?: boolean;
@@ -540,6 +545,7 @@ export function resolveConfig(file: RenderdiffConfig, cli: CliOverrides): Resolv
left: storageFile(cli.storageState?.left ?? fileState?.left),
right: storageFile(cli.storageState?.right ?? fileState?.right),
},
+ computed: cli.computed ?? file.computed ?? false,
};
}
diff --git a/src/index.ts b/src/index.ts
index a02d0e6..1934dee 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -38,4 +38,5 @@ export {
export { type Band, type Box, type Region, type TextDiff } from "./compare.ts";
export { type ElementDiff } from "./locate.ts";
+export { type ComputedDiff, type Finding, type StyleChange } from "./computed.ts";
export { type Accepted, type Fingerprint } from "./accept.ts";
diff --git a/src/locate.ts b/src/locate.ts
index 610873f..042e4ce 100644
--- a/src/locate.ts
+++ b/src/locate.ts
@@ -1,6 +1,7 @@
import type { Locator, Page } from "playwright";
import type { Shot } from "./capture.ts";
import type { Box, Spot } from "./compare.ts";
+import type { Snapshot } from "./computed.ts";
/** Names the DOM elements behind each change, from the pages still holding the shot's document. */
@@ -25,7 +26,7 @@ const PER_SPOT = 3;
const MAX_CHANGED = 6;
/** Layout first; width and height last, since they are usually a consequence. */
-const PROPS = [
+export const PROPS = [
"display",
"position",
"float",
@@ -99,10 +100,14 @@ interface ProbeArgs {
masked: Node[];
props: string[];
perSpot: number;
+ /** Snapshot every element's `props` instead of picking, giving up after this many ms. */
+ walk?: number;
+ /** Where the walk starts, keyed `:scope`; the body, keyed `body`, when null. */
+ root?: Node | null;
}
/** Runs in the page. At scroll 0 a client rect is page px, below the fold too. */
-function probe({ boxes, find, masked, props, perSpot }: ProbeArgs) {
+function probe({ boxes, find, masked, props, perSpot, walk, root }: ProbeArgs) {
const MAX_SCAN = 50_000;
const HASHED = /\d{3,}|^(css|sc|jsx|svelte)-|__[\w-]{5,}$|^_/;
const TEST = ["data-testid", "data-test", "data-test-id", "data-cy", "data-qa"];
@@ -113,7 +118,8 @@ function probe({ boxes, find, masked, props, perSpot }: ProbeArgs) {
const snippet = (e: Element) =>
((e as HTMLElement).innerText ?? e.textContent ?? "").replace(/\s+/g, " ").trim().slice(0, 40);
- const part = (e: Element) => {
+ /** Tag, a naming attribute and up to two classes that don't look generated. */
+ const base = (e: Element, sorted: boolean) => {
const tag = e.localName;
let s = CSS.escape(tag);
const href = e.getAttribute("href");
@@ -129,11 +135,20 @@ function probe({ boxes, find, masked, props, perSpot }: ProbeArgs) {
}
}
// ponytail: hashed-class heuristic, attributes and nth-of-type are the fallback
- s += Array.from(e.classList)
- .filter((c) => !HASHED.test(c))
- .slice(0, 2)
- .map((c) => `.${CSS.escape(c)}`)
- .join("");
+ const classes = Array.from(e.classList).filter((c) => !HASHED.test(c));
+ if (sorted) classes.sort();
+ return (
+ s +
+ classes
+ .slice(0, 2)
+ .map((c) => `.${CSS.escape(c)}`)
+ .join("")
+ );
+ };
+
+ const part = (e: Element) => {
+ const tag = e.localName;
+ let s = base(e, false);
const siblings = e.parentElement ? Array.from(e.parentElement.children) : [];
if (siblings.some((c) => c !== e && c.matches(s))) {
s += `:nth-of-type(${siblings.filter((c) => c.localName === tag).indexOf(e) + 1})`;
@@ -186,6 +201,77 @@ function probe({ boxes, find, masked, props, perSpot }: ProbeArgs) {
const hidden = new Set();
for (const m of masked as Element[])
[m, ...Array.from(m.querySelectorAll("*"))].forEach((e) => hidden.add(e));
+
+ if (walk) {
+ // STILL_CSS stops CSS animations; this settles ones started from script.
+ for (const a of document.getAnimations()) {
+ try {
+ a.finish();
+ } catch {
+ a.cancel();
+ }
+ }
+ const snap: Record = {};
+ const SKIP = new Set(["script", "style", "link", "meta", "template", "noscript"]);
+ let n = 0;
+ const end = performance.now() + walk;
+ // Generated class names change with the CSS, so they aren't markup changes.
+ const html = (e: Element) => {
+ const attrs = Array.from(e.attributes, (a) => {
+ const v =
+ a.name === "class"
+ ? Array.from(e.classList)
+ .filter((c) => !HASHED.test(c))
+ .sort()
+ .join(" ")
+ : a.value;
+ return ` ${a.name}="${v.replace(/"/g, """)}"`;
+ }).join("");
+ const text = Array.from(e.childNodes, (c) => (c.nodeType === 3 ? c.textContent : ""))
+ .join("")
+ .replace(/\s+/g, " ")
+ .trim();
+ return `<${e.localName}${attrs}>${text}`;
+ };
+ // A display:none element is kept, so a rule that hid it is a style change; its subtree isn't.
+ const visit = (e: Element, key: string) => {
+ if (++n > MAX_SCAN) throw new Error(`more than ${MAX_SCAN} elements`);
+ if (performance.now() > end) throw new Error(`took over ${walk}ms`);
+ const cs = getComputedStyle(e);
+ snap[key] = { html: html(e), styles: props.map((p) => cs.getPropertyValue(p)) };
+ if (cs.display === "none") return;
+ for (const pseudo of ["::before", "::after"]) {
+ const ps = getComputedStyle(e, pseudo);
+ const content = ps.getPropertyValue("content");
+ if (content !== "none" && content !== "normal")
+ snap[key + pseudo] = { html: "", styles: props.map((p) => ps.getPropertyValue(p)) };
+ }
+ // Indexed among every child, as :nth-of-type counts, so the key works with querySelector.
+ const ofType = new Map();
+ const kids = Array.from(e.children, (c) => {
+ const k = (ofType.get(c.localName) ?? 0) + 1;
+ ofType.set(c.localName, k);
+ return { c, k };
+ }).filter(
+ ({ c }) => !hidden.has(c) && !SKIP.has(c.localName) && !(c as SVGElement).ownerSVGElement,
+ );
+ // The id, or the tag with a naming attribute and classes; with the index where siblings share it.
+ const segs = kids.map(({ c }) =>
+ c.id && !HASHED.test(c.id)
+ ? `${CSS.escape(c.localName)}#${CSS.escape(c.id)}`
+ : base(c, true),
+ );
+ const count = new Map();
+ for (const g of segs) count.set(g, (count.get(g) ?? 0) + 1);
+ kids.forEach(({ c, k }, i) => {
+ const g = segs[i]!;
+ visit(c, `${key} > ${count.get(g)! > 1 ? `${g}:nth-of-type(${k})` : g}`);
+ });
+ };
+ const start = (root as Element | null) ?? document.body;
+ if (start) visit(start, root ? ":scope" : "body");
+ return { picks: [], found: [], snap };
+ }
const els = document.body?.querySelectorAll("*") ?? [];
for (let i = 0; i < els.length && i < MAX_SCAN; i++) {
const e = els[i]!;
@@ -260,7 +346,7 @@ function probe({ boxes, find, masked, props, perSpot }: ProbeArgs) {
return e ? hit(e) : null;
});
- return { picks, found };
+ return { picks, found, snap: null };
}
type Pair = [Seen | null, Seen | null];
@@ -293,6 +379,32 @@ const same = (a: Seen, b: Seen) =>
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[]) =>
+ (await Promise.all(ls.map((l) => l.elementHandles()))).flat();
+
+/**
+ * Every rendered element's computed `PROPS` and `content`, and its `::before`/`::after` when
+ * generated, keyed by a selector path; masked and `display: none` subtrees are skipped.
+ * Finishes the page's animations, so it runs after `locate`.
+ */
+export async function snapshot(
+ page: Page,
+ masks: Locator[],
+ budget: number,
+ root: Locator | null,
+): Promise {
+ const { snap } = await page.evaluate(probe, {
+ root: root && (await root.elementHandle()),
+ boxes: [],
+ find: [],
+ masked: await handles(masks),
+ props: [...PROPS, "content"],
+ perSpot: 0,
+ walk: budget,
+ });
+ return snap!;
+}
+
/**
* The elements behind each of the first `MAX_SPOTS` spots, in spot order. Each side picks the
* elements that best fill its box, then the other side looks for each by selector.
@@ -305,9 +417,7 @@ export async function locate(
): Promise {
const todo = spots.slice(0, MAX_SPOTS);
if (!todo.length) return [];
- const masked = await Promise.all(
- masks.map(async (ls) => (await Promise.all(ls.map((l) => l.elementHandles()))).flat()),
- );
+ const masked = await Promise.all(masks.map(handles));
const boxes = (s: 0 | 1) =>
todo.map((t) => {
const b = s ? t.right : t.left;
diff --git a/src/report.ts b/src/report.ts
index ae867f3..f2a5bb8 100644
--- a/src/report.ts
+++ b/src/report.ts
@@ -1,6 +1,7 @@
import fs from "node:fs";
import path from "node:path";
import type { Accepted } from "./accept.ts";
+import { fmtComputed, groupFindings, type ComputedDiff, type Finding } from "./computed.ts";
import type { Band, Box, Region, TextDiff } from "./compare.ts";
import { CONTEXT_OPTIONS, name, type ResolvedConfig, type Sides } from "./config.ts";
import type { ElementDiff } from "./locate.ts";
@@ -47,6 +48,9 @@ export interface ComparedResult extends BaseResult {
failed: { left: string[]; right: string[] };
/** With `--cache-right`: when the recording the right side was replayed from was made, ISO. */
rightReplayedFrom?: string;
+ /** With `--computed`: the computed-style diff; null when the snapshot failed, with `computedError` saying why. */
+ computed?: ComputedDiff | null;
+ computedError?: string;
}
/** A crop of one change: left and right panels, a 1px red box round it, or a 2px red seam. */
@@ -114,6 +118,8 @@ export interface Summary {
accepted: number;
/** Accepted differences for a measured route and width that weren't seen: prune them. */
stale: Accepted[];
+ /** With `--computed`: each style change once, with the routes and widths it was seen at. */
+ computed?: Finding[];
}
/** The shape of `results.json`, written to the out dir on every run. */
@@ -158,6 +164,7 @@ export function writeResults(
differing: open.filter((r) => r.diffPixels > 0).length,
accepted: compared.filter((r) => r.accepted).length,
stale,
+ ...(compared.some((r) => "computed" in r) ? { computed: groupFindings(results) } : {}),
},
};
const rows = results.map((r) => ` ${JSON.stringify(r, round)}`).join(",\n");
@@ -270,6 +277,7 @@ function card(r: ComparedResult): string {
${r.widthDelta ? `width ${signed(r.widthDelta)}px` : ""}
${r.unstablePixels ? `${r.unstablePixels.toLocaleString("en-US")} px unstable` : ""}
${r.alignedScore !== null ? `aligned ${pct(r.alignedScore)}` : ""}
+ ${r.computed ? `${r.computed.dom ? `dom differs (${r.computed.dom})` : "dom identical"}` : ""}
${r.diffPixels.toLocaleString()} / ${r.totalPixels.toLocaleString()} px differ
${findings(r)}
@@ -343,6 +351,13 @@ export async function writeReport(
${meta.rightReplayedFrom ? `· right replayed from a recording of ${esc(meta.rightReplayedFrom)}` : ""}