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
1 change: 1 addition & 0 deletions docs/output.md
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,7 @@ pulls a route), scores rounded down to four decimals (so a shot that differs nev
"text": { "added": [], "removed": ["Pricing"] }, // added: left only; removed: right only
"accepted": false, // every band and region matched renderdiff.accepted.json
"failed": { "left": [], "right": [] }, // stylesheets and font faces that didn't load: "font Inter 700", "stylesheet https://…"
"masked": ["rotating quote (data-renderdiff-mask)"], // absent unless a side marked elements data-renderdiff-mask
"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": [{
Expand Down
11 changes: 11 additions & 0 deletions docs/scoping.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,14 @@ starts. The file's contents are never printed; `meta.storageState` and the repor
each side's file. It holds live session tokens: **never commit it**, and add it to
`.gitignore`. The out dir then holds signed-in screenshots, and their text in
`results.json`, so don't publish or commit that either; add the out dir to `.gitignore` too.

## Cooperating pages

Every page renderdiff loads has `window.__RENDERDIFF__` set to `true` before its first
script, so it can skip what it knows will differ (a live chat widget, a rotating quote).
Do it in both builds, or the side that doesn't is the one that differs.

An element marked `data-renderdiff-mask` is masked like a config mask, on every route and
both sides. The attribute's value is its reason in the report, `rotating quote
(data-renderdiff-mask)` for `data-renderdiff-mask="rotating quote"`, and in the result's
`masked` in `results.json`.
11 changes: 7 additions & 4 deletions skills/renderdiff/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ computed: 2 findings; dom identical on 2 of 3 route(s), differs /pricing (1), so

| Tool | Legitimate for | Never for |
| --- | --- | --- |
| Mask (`--mask <sel>`, config `masks` with `reason`, `--mask-media`) | Content *proven* to vary per load: a base-vs-base baseline differs there (clocks, star counts, rotating quotes, embeds). | Anything that differs only after your change. |
| Mask (`--mask <sel>`, config `masks` with `reason`, `--mask-media`, `data-renderdiff-mask="<reason>"` in the page) | Content *proven* to vary per load: a base-vs-base baseline differs there (clocks, star counts, rotating quotes, embeds). | Anything that differs only after your change. |
| `--accept "<reason>"` | A difference you opened that exists before your change (baseline vs production) or is intended, with a reason saying which. | Getting green. |
| `--threshold <0..1>` | A CI gate on the exit code. | Reaching green; the difference is still there. |

Expand All @@ -180,6 +180,8 @@ computed: 2 findings; dom identical on 2 of 3 route(s), differs /pricing (1), so
shows its poster, video.js captions and control bars hidden), so its box is still compared.
`--no-freeze-video` lets it play: expect `unstable` or `did not settle`.
- Masks hide text too, so masked text leaves the text diff.
- Pages see `window.__RENDERDIFF__ === true` before their first script; anything hidden on it
must be hidden in both builds.
- Accepted entries go to `renderdiff.accepted.json` next to the config (or cwd), one per band
or region, scoped by the run's routes and widths. A match ignores `y` and needs the same
kind, side, box, pixel hash (4 bits a channel) and named elements, so anything else drawn
Expand Down Expand Up @@ -308,9 +310,10 @@ For scripts and drilling into one route; the loop doesn't need it. One result pe
`y`, `h`, or null when unaligned); each with `elements` (`selector`, `side`, each side's box,
`changed` `{ prop: [left, right] }`, `text`, `rightSelector`, `reparented`; absent when not
looked at, `[]` when nothing was named); `text` `{ added, removed }`; `failed` `{ left, right }`;
`images`; `crops` (`kind`, each side's box with `h` 0 at an insertion point, `layout`, `scale`,
`clipped`); `accepted`; `rightReplayedFrom`; with `--computed`, `computed` (`dom`, 0 =
identical; `changes` `{ key, prop, values }`, first 500; `truncated`; `unmatched`) or null with
`masked` (reasons of `data-renderdiff-mask` elements, absent when none); `images`; `crops`
(`kind`, each side's box with `h` 0 at an insertion point, `layout`, `scale`, `clipped`);
`accepted`; `rightReplayedFrom`; with `--computed`, `computed` (`dom`, 0 = identical;
`changes` `{ key, prop, values }`, first 500; `truncated`; `unmatched`) or null with
`computedError`.
- **`summary`:** `compared`, `errors`, `mean` and `worst` (accepted shots aside),
`belowThreshold`, `differing` (unaccepted shots with any differing pixel; without
Expand Down
13 changes: 11 additions & 2 deletions src/capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ export interface Shot {
origin: { x: number; y: number };
/** Stylesheets and font faces that failed to load, e.g. `font Inter 700 italic`, `stylesheet https://…`. */
failed: string[];
/** Reasons of the page's `data-renderdiff-mask` elements, e.g. `rotating quote (data-renderdiff-mask)`. */
marked: string[];
}

/**
Expand Down Expand Up @@ -151,6 +153,7 @@ export async function prepare(page: Page, cfg: ResolvedConfig, now: number): Pro
});
// mulberry32 with a fixed seed, re-seeded on every navigation.
await page.addInitScript(() => {
(window as unknown as { __RENDERDIFF__: boolean }).__RENDERDIFF__ = true;
let s = 0x9e3779b9;
Math.random = () => {
s = (s + 0x6d2b79f5) | 0;
Expand Down Expand Up @@ -267,6 +270,12 @@ export async function capture(
),
);
}
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;
Expand Down Expand Up @@ -351,9 +360,9 @@ export async function capture(
for (let n = 2; ; n++) {
await page.waitForTimeout(50);
const png = await shoot();
if (png.equals(prev)) return { png, unstable: null, blank, text, origin, failed };
if (png.equals(prev)) return { png, unstable: null, blank, text, origin, failed, marked };
if (n === tries)
return { png, unstable: await differing(prev, png), blank, text, origin, failed };
return { png, unstable: await differing(prev, png), blank, text, origin, failed, marked };
prev = png;
}
}
Expand Down
11 changes: 8 additions & 3 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -306,9 +306,14 @@ export function defineConfig(config: RenderdiffConfig): RenderdiffConfig {
}

export function masksFor(cfg: ResolvedConfig, page: Page, route: Route): Locator[] {
return cfg.masks
.filter((m) => m.urlPath === undefined || m.urlPath === route.left || m.urlPath === route.right)
.map((m) => ("selector" in m ? page.locator(m.selector) : m.locate(page)));
return [
...cfg.masks
.filter(
(m) => m.urlPath === undefined || m.urlPath === route.left || m.urlPath === route.right,
)
.map((m) => ("selector" in m ? page.locator(m.selector) : m.locate(page))),
page.locator("[data-renderdiff-mask]"),
];
}

/** Config filenames probed in cwd, in order. */
Expand Down
18 changes: 13 additions & 5 deletions src/report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,8 @@ export interface ComparedResult extends BaseResult {
alignedScore: number | null;
/** innerText line diff; `added` is on left only, `removed` on right only. */
text: TextDiff;
/** Reasons of `data-renderdiff-mask` elements either side carried. Absent when none did. */
masked?: string[];
/** Paths relative to the out dir. */
images: { left: string; right: string; diff: string };
/** At most three: bands, tallest first, then the largest regions. Not one per region. */
Expand Down Expand Up @@ -459,16 +461,21 @@ const listed = (errors: ErrorResult[], stale: Accepted[]) =>
<ul>${stale.map((a) => `<li><code>${esc(a.route)}</code> @${a.width}px — ${esc(a.reason)}</li>`).join("")}</ul></section>`
: "");

const neutralized = (meta: RunMeta) => `<details>
const neutralized = (meta: RunMeta, results: RouteResult[]) => {
const reasons = [
...meta.masks.map((m) => m.reason),
...new Set(results.flatMap((r) => (r.status === "compared" ? (r.masked ?? []) : []))),
];
return `<details>
<summary>What was neutralized</summary>
<p>Blocked on both sides — analytics, consent, and A/B tooling that would otherwise
rewrite the DOM differently on each load:</p>
<ul>${meta.blockUrlPatterns.map((p) => `<li><code>${esc(p)}</code></li>`).join("")}</ul>
<p>Masked, because they drift — painted over on both sides, so they can neither pass
nor fail:</p>
${
meta.masks.length
? `<ul>${meta.masks.map((m) => `<li>${esc(m.reason)}</li>`).join("")}</ul>`
reasons.length
? `<ul>${reasons.map((r) => `<li>${esc(r)}</li>`).join("")}</ul>`
: `<p><em>None configured.</em></p>`
}
<p>Pinned on both sides: clock starts at <code>${esc(meta.clock)}</code> on every load, a seeded
Expand All @@ -484,6 +491,7 @@ const neutralized = (meta: RunMeta) => `<details>
<p>Magenta is also padding where one page is taller or wider than the other. It counts
against the score on purpose — see the height delta on the row.</p>
</details>`;
};

export async function writeReport(
results: RouteResult[],
Expand Down Expand Up @@ -521,7 +529,7 @@ ${stats(compared).sorted.map(card).join("\n")}

${listed(errors, stale)}

${neutralized(meta)}
${neutralized(meta, results)}
</main>
`;

Expand Down Expand Up @@ -668,7 +676,7 @@ ${
: ""
}

${neutralized(meta)}
${neutralized(meta, results)}
`;

const out = path.join(outDir, "evidence.html");
Expand Down
2 changes: 2 additions & 0 deletions src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,7 @@ export async function run({
]);

if (!rightShot.failed.length) recorded.push(shotId(route, width));
const marked = [...new Set([...leftShot.marked, ...rightShot.marked])];
results.push({
...entry,
status: "compared",
Expand All @@ -453,6 +454,7 @@ export async function run({
crops: cropped,
accepted: false,
failed: { left: leftShot.failed, right: rightShot.failed },
...(marked.length ? { masked: marked } : {}),
...computed,
...(replayedAt ? { rightReplayedFrom: new Date(replayedAt).toISOString() } : {}),
});
Expand Down
2 changes: 1 addition & 1 deletion tests/fixtures/pages/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ Three groups:
elements each change names (`margin`, `color`, `nav`), and a lost `::before` line and a
re-parented pairing (`divider`).
- **Guard rails** — `blank`, `tall`, `animated`, `lazy`, `lazy-deep`, `lazy-js`, `lazy-grow`, `consent`,
`drifting`, `tracker`, `clock`, `ticker`, `unsettled`, `sprite`, `short`, `tall-region`, `reorder`, `stripe`, `frameset`, `menu`, `signed-in`, `fixed`, `inserted`, `labelled`, `broken-asset`, `media`, `long`, `video`, `hang`, `origin`.
`drifting`, `tracker`, `clock`, `ticker`, `unsettled`, `sprite`, `short`, `tall-region`, `reorder`, `stripe`, `frameset`, `menu`, `signed-in`, `fixed`, `inserted`, `labelled`, `broken-asset`, `media`, `long`, `video`, `hang`, `origin`, `cooperate`.
One per defence in `src/capture.ts` / `src/config.ts`.

## Authoring rules
Expand Down
29 changes: 29 additions & 0 deletions tests/fixtures/pages/cooperate/left.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cooperating page</title>
<link rel="stylesheet" href="/shared/base.css">
<script>if (window.__RENDERDIFF__) document.documentElement.classList.add("rd");</script>
<style>
/* GUARD RAIL for page cooperation. Each box differs between the sides: one carries
data-renderdiff-mask, one the page hides under window.__RENDERDIFF__, one is neither. */
.box { width: 416px; height: 160px; background: var(--accent); color: #fff; }
.box + .box { margin-top: 160px; }
.rd .flagged { visibility: hidden; }
</style>
</head>
<body>
<div class="page">
<h1>Cooperating page</h1>
<p class="lede">This pair is deliberately different in three boxes. The page marks one for masking and hides another when it knows renderdiff is looking.</p>
<div class="box marked" data-renderdiff-mask="rotating quote"><p>Measure twice, cut once.</p></div>
<div class="box flagged"><p>Ad slot A</p></div>
<div class="box control"><p>Version one</p></div>
<section class="notes">
<h2>Notes</h2>
<p>Only the last box should show up in the diff, since nothing neutralizes it. The other two are the page telling renderdiff what it may skip.</p>
</section>
</div>
</body>
</html>
29 changes: 29 additions & 0 deletions tests/fixtures/pages/cooperate/right.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cooperating page</title>
<link rel="stylesheet" href="/shared/base.css">
<script>if (window.__RENDERDIFF__) document.documentElement.classList.add("rd");</script>
<style>
/* GUARD RAIL for page cooperation. Each box differs between the sides: one carries
data-renderdiff-mask, one the page hides under window.__RENDERDIFF__, one is neither. */
.box { width: 416px; height: 160px; background: var(--accent); color: #fff; }
.box + .box { margin-top: 160px; }
.rd .flagged { visibility: hidden; }
</style>
</head>
<body>
<div class="page">
<h1>Cooperating page</h1>
<p class="lede">This pair is deliberately different in three boxes. The page marks one for masking and hides another when it knows renderdiff is looking.</p>
<div class="box marked" data-renderdiff-mask="rotating quote"><p>Well begun is half done.</p></div>
<div class="box flagged"><p>Ad slot B</p></div>
<div class="box control"><p>Version two</p></div>
<section class="notes">
<h2>Notes</h2>
<p>Only the last box should show up in the diff, since nothing neutralizes it. The other two are the page telling renderdiff what it may skip.</p>
</section>
</div>
</body>
</html>
1 change: 1 addition & 0 deletions tests/helpers/corpus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export const GUARDRAILS = [
"video",
"hang",
"origin",
"cooperate",
] as const;

export const ALL: string[] = [...EQUIVALENCE, ...CONTROLS, ...GUARDRAILS];
Expand Down
1 change: 1 addition & 0 deletions tests/unit/compare.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const shot = async (paint: (px: Buffer) => void) => ({
text: [],
origin: { x: 0, y: 0 },
failed: [],
marked: [],
});

test("a lost 1px divider is a line drawn by the right side", async () => {
Expand Down
17 changes: 17 additions & 0 deletions tests/visual/guardrails.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,23 @@ describe("masks", () => {
]);
});

test("a page masks what it marks and hides what it flags, and the report lists the mark's reason", async () => {
const run = await capture(["/cooperate"]);
assert.equal(run.code, 1, `the control box still differs${context(run)}`);
const r = result(results(run.outDir), "/cooperate", 1440);
assert.ok(r.diffPixels > 0, context(run));
assert.ok(r.regions.length > 0, context(run));
for (const g of r.regions) {
assert.ok(g.elements?.length, `a region was not located${context(run)}`);
for (const e of g.elements) assert.match(e.selector, /control/, context(run));
}
assert.deepEqual([r.text.added, r.text.removed], [["Version one"], ["Version two"]]);
assert.deepEqual(r.masked, ["rotating quote (data-renderdiff-mask)"]);
assert.deepEqual(parseReport(run.report()!).maskReasons, [
"rotating quote (data-renderdiff-mask)",
]);
});

test("content that varies per load is painted out, clean and listed", async () => {
const run = await capture(["/drifting", "/color"]);
assert.equal(run.code, 1, `/color still differs${context(run)}`);
Expand Down
Loading