diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 4c69f65..b9678bb 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -67,8 +67,9 @@ honestly. This is what renderdiff does to make sure of that. - **Stitches tall pages.** A single screenshot past 16,384px can come out truncated or wrapped (Chrome repeats the top of the page; recent headless Chromium does not), so taller pages, and element shots taller than that, are captured as tiles through CDP and stitched - back together. Masks are painted onto the final image from each element's bounding box, - so they apply the same way on both paths. Past 57.6 million pixels (40,000px tall at + back together. Masks are painted onto the final image from each element's box and what + its children paint outside it, clipped to its overflow ancestors and read again at every + shot, so they apply the same way on both paths. Past 57.6 million pixels (40,000px tall at 1440px wide, about 150,000px at 375px) it errors — that's a broken layout, not a page. Every run's report ends with a "What was neutralized" section listing the actual block diff --git a/skills/renderdiff/reference.md b/skills/renderdiff/reference.md index 20c58c4..f5e2d0f 100644 --- a/skills/renderdiff/reference.md +++ b/skills/renderdiff/reference.md @@ -184,6 +184,9 @@ computed: 2 findings; dom identical on 2 of 3 route(s), differs /pricing (1), so 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. +- A mask covers what its element's children paint outside it (a video.js poster), cut to the + `overflow` ancestors that clip them, so one mask per player is enough. Boxes are read at + every shot: a mask that moves between shots shows as `unstable`, not as a stale rect. - 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 diff --git a/src/capture.ts b/src/capture.ts index e0e6a19..5b0a1f8 100644 --- a/src/capture.ts +++ b/src/capture.ts @@ -57,6 +57,55 @@ function freezeVideo() { ); } +/** + * Runs in the page: each element's box, plus every descendant's that paints outside it, + * each cut to the overflow of the ancestors that clip it. Null inside a frame. + */ +function maskRects(els: Element[]) { + if (window !== window.top) return null; + const clipped = (e: Element) => { + let { left, top, right, bottom } = e.getBoundingClientRect(); + let pos = getComputedStyle(e).position; + // body's overflow belongs to the viewport, which paintBoxes already clamps to. + for ( + let a = e.parentElement; + a && a !== document.body && pos !== "fixed"; + a = a.parentElement + ) { + const s = getComputedStyle(a); + if (s.display === "contents") continue; + // An absolute box escapes the overflow of ancestors below its containing block. + if (pos === "absolute" && s.position === "static" && s.transform === "none") continue; + pos = s.position; + if (s.display === "inline") continue; + const r = a.getBoundingClientRect(); + if (s.overflowX !== "visible") + [left, right] = [Math.max(left, r.left), Math.min(right, r.right)]; + if (s.overflowY !== "visible") + [top, bottom] = [Math.max(top, r.top), Math.min(bottom, r.bottom)]; + } + return { x: left, y: top, width: right - left, height: bottom - top }; + }; + type B = ReturnType; + const outside = (b: B, o: B) => + b.x < o.x || b.y < o.y || b.x + b.width > o.x + o.width || b.y + b.height > o.y + o.height; + return els.flatMap((e) => { + const own = clipped(e); + const spill = Array.from(e.querySelectorAll("*")) + .filter((d) => { + const r = d.getBoundingClientRect(); + return ( + r.width * r.height > 0 && + outside(r, own) && + d.checkVisibility({ opacityProperty: true, visibilityProperty: true }) + ); + }) + .map(clipped) + .filter((b) => outside(b, own)); + return [own, ...spill].filter((b) => b.width > 0 && b.height > 0); + }); +} + /** * Chromium's screenshot backing store caps at this in any dimension; a single * `fullPage` or clip shot past it can come out truncated or wrapped. Rather than refuse, a @@ -348,22 +397,30 @@ export async function capture( throw new Error(`selector "${selector}" is off the page ${where}`); } } - const boxes = ( - await Promise.all( - (await Promise.all(masks.map((l) => l.all()))).flat().map((m) => m.boundingBox()), + const read = async () => + ( + await Promise.all( + masks.map( + async (l) => + (await l.evaluateAll(maskRects)) ?? + // A frame's rects are in its own viewport; Playwright maps boxes to the page. + (await Promise.all((await l.all()).map((m) => m.boundingBox()))), + ), + ) ) - ) - .filter((b) => b !== null) - .map((b) => (clip ? { ...b, x: b.x - clip.x, y: b.y - clip.y } : b)); + .flat() + .filter((b) => b !== null) + .map((b) => (clip ? { ...b, x: b.x - clip.x, y: b.y - clip.y } : b)); const area = clip ?? { x: 0, y: 0, width, height: scrollHeight }; const tiled = area.height > MAX_CAPTURE_HEIGHT; - const shoot = async () => - paintBoxes( - tiled - ? await captureTiled(page, area) - : await page.screenshot({ fullPage: true, clip, animations: "disabled" }), - boxes, - ); + // Read on both sides of the shot, so a box that moves while it is taken stays covered. + const shoot = async () => { + const before = await read(); + const png = tiled + ? await captureTiled(page, area) + : await page.screenshot({ fullPage: true, clip, animations: "disabled" }); + return paintBoxes(png, [...before, ...(await read())]); + }; // A tiled shot is expensive, so it gets one comparison. const tries = tiled ? 2 : 3; @@ -463,24 +520,20 @@ type Box = { x: number; y: number; width: number; height: number }; async function paintBoxes(png: Buffer, boxes: Box[]): Promise { if (!boxes.length) return png; - const { width: W = 0, height: H = 0 } = await sharp(png).metadata(); - const rects = boxes.flatMap((b) => { + const { data, info } = await decode(png); + const { width: W, height: H } = info; + const px = Buffer.from(`${MASK_COLOR.slice(1)}ff`, "hex"); + for (const b of boxes) { const left = Math.max(0, Math.floor(b.x)); const top = Math.max(0, Math.floor(b.y)); - const width = Math.min(W, Math.ceil(b.x + b.width)) - left; - const height = Math.min(H, Math.ceil(b.y + b.height)) - top; - if (width <= 0 || height <= 0) return []; - return [ - { - input: { - create: { width, height, channels: 4 as const, background: MASK_COLOR }, - }, - left, - top, - }, - ]; - }); - return rects.length ? sharp(png).composite(rects).png().toBuffer() : png; + const right = Math.min(W, Math.ceil(b.x + b.width)); + const bottom = Math.min(H, Math.ceil(b.y + b.height)); + if (right <= left) continue; + for (let y = top; y < bottom; y++) data.fill(px, (y * W + left) * 4, (y * W + right) * 4); + } + return sharp(data, { raw: { width: W, height: H, channels: 4 } }) + .png() + .toBuffer(); } /** diff --git a/src/config.ts b/src/config.ts index d31bc59..c8f6667 100644 --- a/src/config.ts +++ b/src/config.ts @@ -209,7 +209,9 @@ export const MASK_COLOR = "#FF00FF"; /** * Content that renders on both sides but whose value drifts — live counters, clocks, - * "N minutes ago". Painted over on both sides, so the noise cancels. + * "N minutes ago". Painted over on both sides, so the noise cancels: the element and + * anything it draws outside its box, cut to its `overflow` ancestors, read again at every + * shot. * * Masks rather than CSS: these occupy a box, and hiding one reflows the page. * `visibility:hidden` is no better — "9.9k" and "10.0k" size their box differently and diff --git a/tests/fixtures/configs/mask-geometry.mjs b/tests/fixtures/configs/mask-geometry.mjs new file mode 100644 index 0000000..6b5ec20 --- /dev/null +++ b/tests/fixtures/configs/mask-geometry.mjs @@ -0,0 +1,8 @@ +/** Masks the three boxes of `/mask-geometry`: one that moves, one clipped, one overflowing. */ +export default { + masks: [ + { urlPath: "/mask-geometry", reason: "moves after settle", selector: ".moves" }, + { urlPath: "/mask-geometry", reason: "cut by its wrapper", selector: ".clipped" }, + { urlPath: "/mask-geometry", reason: "player with a poster above it", selector: ".player" }, + ], +}; diff --git a/tests/fixtures/pages/README.md b/tests/fixtures/pages/README.md index b496a4a..bd9edea 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`, `unsettled-once`, `sprite`, `short`, `tall-region`, `reorder`, `stripe`, `frameset`, `menu`, `scroll-spy`, `signed-in`, `fixed`, `inserted`, `labelled`, `broken-asset`, `media`, `long`, `video`, `video-seek`, `hang`, `origin`, `cooperate`. + `drifting`, `tracker`, `clock`, `ticker`, `unsettled`, `unsettled-once`, `sprite`, `short`, `tall-region`, `reorder`, `stripe`, `frameset`, `menu`, `scroll-spy`, `signed-in`, `fixed`, `inserted`, `labelled`, `broken-asset`, `media`, `long`, `video`, `video-seek`, `hang`, `origin`, `cooperate`, `mask-geometry`. One per defence in `src/capture.ts` / `src/config.ts`. ## Authoring rules @@ -60,7 +60,8 @@ Breaking any of these produces a flaky suite, and the flake looks like a renderd 9. **No animation** except in `animated`, which exists to prove `STILL_CSS` and the image-animation launch flag kill it, `ticker`, whose timer exists to be caught by the stability check, `unsettled`, which recolours the whole page to trip the - unstable-pixel cap, and `unsettled-once`, which does so on its first render only. + unstable-pixel cap, `unsettled-once`, which does so on its first render only, and + `mask-geometry`, whose box moves once after settle. ## Adding a route diff --git a/tests/fixtures/pages/mask-geometry/left.html b/tests/fixtures/pages/mask-geometry/left.html new file mode 100644 index 0000000..40da2dc --- /dev/null +++ b/tests/fixtures/pages/mask-geometry/left.html @@ -0,0 +1,61 @@ + + + + +Mask geometry + + + + +
+

Mask geometry

+

Each masked box below differs between the two sides. A mask has to follow its element, stay inside the overflow that cuts it, and cover what its children paint outside it.

+
+

Version one

+

Version one

+
+
+
Version one
+
Slide
+ +
+
+
+

Notes

+

The first box moves 200px down once renderdiff has read its text, standing in for a pinned section that re-lays out after settle.

+
+
+
+ + + diff --git a/tests/fixtures/pages/mask-geometry/right.html b/tests/fixtures/pages/mask-geometry/right.html new file mode 100644 index 0000000..8ce5766 --- /dev/null +++ b/tests/fixtures/pages/mask-geometry/right.html @@ -0,0 +1,61 @@ + + + + +Mask geometry + + + + +
+

Mask geometry

+

Each masked box below differs between the two sides. A mask has to follow its element, stay inside the overflow that cuts it, and cover what its children paint outside it.

+
+

Version two

+

Version two

+
+
+
Version two
+
Slide
+ +
+
+
+

Notes

+

The first box moves 200px down once renderdiff has read its text, standing in for a pinned section that re-lays out after settle.

+
+
+
+ + + diff --git a/tests/helpers/corpus.ts b/tests/helpers/corpus.ts index 39915d7..995cb39 100644 --- a/tests/helpers/corpus.ts +++ b/tests/helpers/corpus.ts @@ -59,6 +59,7 @@ export const GUARDRAILS = [ "hang", "origin", "cooperate", + "mask-geometry", ] as const; export const ALL: string[] = [...EQUIVALENCE, ...CONTROLS, ...GUARDRAILS]; diff --git a/tests/visual/guardrails.test.ts b/tests/visual/guardrails.test.ts index 5e7dc79..f3805cb 100644 --- a/tests/visual/guardrails.test.ts +++ b/tests/visual/guardrails.test.ts @@ -497,6 +497,38 @@ describe("masks", () => { context(run), ); }); + + test("unmasked, the moving, clipped and overflowing boxes all differ", async () => { + const run = await capture(["/mask-geometry"]); + assert.ok(result(results(run.outDir), "/mask-geometry", 1440).diffPixels > 0, context(run)); + }); + + test("a mask follows its element, stays inside its overflow and covers what its children paint outside it", async () => { + const run = await capture(["/mask-geometry"], { + config: path.join(CONFIGS, "mask-geometry.mjs"), + }); + assert.equal(run.code, 0, context(run)); + assert.equal(result(results(run.outDir), "/mask-geometry", 1440).diffPixels, 0, context(run)); + const pixel = async (file: string, x: number, y: number) => [ + ...(await sharp(run.file(file)) + .extract({ left: x, top: y, width: 1, height: 1 }) + .removeAlpha() + .raw() + .toBuffer()), + ]; + // The stage sits at page (16, 300); see the fixture's style. + for (const side of ["left", "right"]) { + const file = `mask-geometry.1440.${side}.png`; + const magenta = async (x: number, y: number) => + (await pixel(file, x, y)).join() === "255,0,255"; + assert.ok(await magenta(216, 580), `the moved box is unmasked on ${side}${context(run)}`); + assert.ok(await magenta(216, 800), `the clipped box is unmasked on ${side}`); + assert.ok(!(await magenta(216, 920)), `the mask spilled out of its wrapper on ${side}`); + assert.ok(await magenta(216, 1158), `the poster above the player is unmasked on ${side}`); + assert.ok(!(await magenta(666, 1230)), `the clipped slide was masked on ${side}`); + assert.ok(!(await magenta(216, 1480)), `the transparent menu was masked on ${side}`); + } + }); }); describe("selector masks", () => {