diff --git a/docs/output.md b/docs/output.md index ae8abdb..d45da04 100644 --- a/docs/output.md +++ b/docs/output.md @@ -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": [{ diff --git a/docs/scoping.md b/docs/scoping.md index 38465af..865c2dd 100644 --- a/docs/scoping.md +++ b/docs/scoping.md @@ -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`. diff --git a/skills/renderdiff/reference.md b/skills/renderdiff/reference.md index 09cc7b1..3be52b8 100644 --- a/skills/renderdiff/reference.md +++ b/skills/renderdiff/reference.md @@ -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 `, 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 `, config `masks` with `reason`, `--mask-media`, `data-renderdiff-mask=""` 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 ""` | 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. | @@ -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 @@ -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 diff --git a/src/capture.ts b/src/capture.ts index 26a5a0d..acf1026 100644 --- a/src/capture.ts +++ b/src/capture.ts @@ -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[]; } /** @@ -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; @@ -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; @@ -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; } } diff --git a/src/config.ts b/src/config.ts index b2cb862..552db1c 100644 --- a/src/config.ts +++ b/src/config.ts @@ -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. */ diff --git a/src/report.ts b/src/report.ts index 36b2ef3..0699cb0 100644 --- a/src/report.ts +++ b/src/report.ts @@ -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. */ @@ -459,7 +461,12 @@ const listed = (errors: ErrorResult[], stale: Accepted[]) =>
    ${stale.map((a) => `
  • ${esc(a.route)} @${a.width}px — ${esc(a.reason)}
  • `).join("")}
` : ""); -const neutralized = (meta: RunMeta) => `
+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 `
What was neutralized

Blocked on both sides — analytics, consent, and A/B tooling that would otherwise rewrite the DOM differently on each load:

@@ -467,8 +474,8 @@ const neutralized = (meta: RunMeta) => `

Masked, because they drift — painted over on both sides, so they can neither pass nor fail:

${ - meta.masks.length - ? `
    ${meta.masks.map((m) => `
  • ${esc(m.reason)}
  • `).join("")}
` + reasons.length + ? `
    ${reasons.map((r) => `
  • ${esc(r)}
  • `).join("")}
` : `

None configured.

` }

Pinned on both sides: clock starts at ${esc(meta.clock)} on every load, a seeded @@ -484,6 +491,7 @@ const neutralized = (meta: RunMeta) => `

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.

`; +}; export async function writeReport( results: RouteResult[], @@ -521,7 +529,7 @@ ${stats(compared).sorted.map(card).join("\n")} ${listed(errors, stale)} -${neutralized(meta)} +${neutralized(meta, results)} `; @@ -668,7 +676,7 @@ ${ : "" } -${neutralized(meta)} +${neutralized(meta, results)} `; const out = path.join(outDir, "evidence.html"); diff --git a/src/run.ts b/src/run.ts index c4c5949..1552431 100644 --- a/src/run.ts +++ b/src/run.ts @@ -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", @@ -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() } : {}), }); diff --git a/tests/fixtures/pages/README.md b/tests/fixtures/pages/README.md index 8354436..804d90a 100644 --- a/tests/fixtures/pages/README.md +++ b/tests/fixtures/pages/README.md @@ -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 diff --git a/tests/fixtures/pages/cooperate/left.html b/tests/fixtures/pages/cooperate/left.html new file mode 100644 index 0000000..c5e398b --- /dev/null +++ b/tests/fixtures/pages/cooperate/left.html @@ -0,0 +1,29 @@ + + + + +Cooperating page + + + + + +
+

Cooperating page

+

This pair is deliberately different in three boxes. The page marks one for masking and hides another when it knows renderdiff is looking.

+

Measure twice, cut once.

+

Ad slot A

+

Version one

+
+

Notes

+

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.

+
+
+ + diff --git a/tests/fixtures/pages/cooperate/right.html b/tests/fixtures/pages/cooperate/right.html new file mode 100644 index 0000000..ac1abc6 --- /dev/null +++ b/tests/fixtures/pages/cooperate/right.html @@ -0,0 +1,29 @@ + + + + +Cooperating page + + + + + +
+

Cooperating page

+

This pair is deliberately different in three boxes. The page marks one for masking and hides another when it knows renderdiff is looking.

+

Well begun is half done.

+

Ad slot B

+

Version two

+
+

Notes

+

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.

+
+
+ + diff --git a/tests/helpers/corpus.ts b/tests/helpers/corpus.ts index af14b7c..ff9818a 100644 --- a/tests/helpers/corpus.ts +++ b/tests/helpers/corpus.ts @@ -55,6 +55,7 @@ export const GUARDRAILS = [ "video", "hang", "origin", + "cooperate", ] as const; export const ALL: string[] = [...EQUIVALENCE, ...CONTROLS, ...GUARDRAILS]; diff --git a/tests/unit/compare.test.ts b/tests/unit/compare.test.ts index 7150a69..2c26eb6 100644 --- a/tests/unit/compare.test.ts +++ b/tests/unit/compare.test.ts @@ -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 () => { diff --git a/tests/visual/guardrails.test.ts b/tests/visual/guardrails.test.ts index 85afb2d..d20fa60 100644 --- a/tests/visual/guardrails.test.ts +++ b/tests/visual/guardrails.test.ts @@ -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)}`);