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
5 changes: 3 additions & 2 deletions docs/how-it-works.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions skills/renderdiff/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
111 changes: 82 additions & 29 deletions src/capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof clipped>;
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
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -463,24 +520,20 @@ type Box = { x: number; y: number; width: number; height: number };

async function paintBoxes(png: Buffer, boxes: Box[]): Promise<Buffer> {
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();
}

/**
Expand Down
4 changes: 3 additions & 1 deletion src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions tests/fixtures/configs/mask-geometry.mjs
Original file line number Diff line number Diff line change
@@ -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" },
],
};
5 changes: 3 additions & 2 deletions 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`, `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
Expand Down Expand Up @@ -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

Expand Down
61 changes: 61 additions & 0 deletions tests/fixtures/pages/mask-geometry/left.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Mask geometry</title>
<link rel="stylesheet" href="/shared/base.css">
<style>
/* GUARD RAIL for mask geometry. Three masked boxes differ per side: one moves after settle,
one is cut by an overflow:hidden wrapper, one has a child painted above it. The stage is
placed absolutely, so the test can probe fixed page pixels. */
.stage { position: absolute; top: 300px; left: 16px; width: 416px; height: 1400px; }
.stage > * { position: absolute; left: 0; width: 416px; }
.stage div { color: #fff; }
.moves { top: 0; height: 160px; background: var(--accent); }
.wrap { top: 440px; height: 120px; overflow: hidden; }
.clipped { height: 300px; background: var(--accent); }
.below { top: 580px; height: 200px; background: var(--fill); }
.player { top: 880px; height: 200px; background: var(--ink); }
.poster { position: absolute; top: -44px; left: 0; width: 416px; height: 44px; background: var(--accent); }
.track { position: relative; height: 100px; overflow: hidden; }
.slide { position: absolute; top: 0; left: 500px; width: 300px; height: 100px; background: var(--accent); }
.menu { position: absolute; top: 100%; left: 0; width: 416px; height: 200px; background: var(--accent); opacity: 0; }
.under { top: 1100px; height: 200px; background: var(--fill); }
.stage > .notes { top: 1320px; }
</style>
</head>
<body>
<div class="page">
<h1>Mask geometry</h1>
<p class="lede">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.</p>
<div class="stage">
<div class="moves"><p>Version one</p></div>
<div class="wrap"><div class="clipped"><p>Version one</p></div></div>
<div class="below"></div>
<div class="player">
<div class="poster">Version one</div>
<div class="track"><div class="slide">Slide</div></div>
<div class="menu">Menu</div>
</div>
<div class="under"></div>
<section class="notes">
<h2>Notes</h2>
<p>The first box moves 200px down once renderdiff has read its text, standing in for a pinned section that re-lays out after settle.</p>
</section>
</div>
</div>
<script>
// Stands in for a ScrollTrigger pin refresh. Couples to the text read, which hides each mask
// and restores it: the move lands a moment after the restore.
const box = document.querySelector(".moves");
let hidden = false;
new MutationObserver(() => {
if (box.style.visibility === "hidden") hidden = true;
else if (hidden) {
hidden = false;
setTimeout(() => (box.style.top = "200px"), 30);
}
}).observe(box, { attributes: true, attributeFilter: ["style"] });
</script>
</body>
</html>
61 changes: 61 additions & 0 deletions tests/fixtures/pages/mask-geometry/right.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Mask geometry</title>
<link rel="stylesheet" href="/shared/base.css">
<style>
/* GUARD RAIL for mask geometry. Three masked boxes differ per side: one moves after settle,
one is cut by an overflow:hidden wrapper, one has a child painted above it. The stage is
placed absolutely, so the test can probe fixed page pixels. */
.stage { position: absolute; top: 300px; left: 16px; width: 416px; height: 1400px; }
.stage > * { position: absolute; left: 0; width: 416px; }
.stage div { color: #fff; }
.moves { top: 0; height: 160px; background: var(--accent); }
.wrap { top: 440px; height: 120px; overflow: hidden; }
.clipped { height: 300px; background: var(--accent); }
.below { top: 580px; height: 200px; background: var(--fill); }
.player { top: 880px; height: 200px; background: var(--ink); }
.poster { position: absolute; top: -44px; left: 0; width: 416px; height: 44px; background: var(--accent); }
.track { position: relative; height: 100px; overflow: hidden; }
.slide { position: absolute; top: 0; left: 500px; width: 300px; height: 100px; background: var(--accent); }
.menu { position: absolute; top: 100%; left: 0; width: 416px; height: 200px; background: var(--accent); opacity: 0; }
.under { top: 1100px; height: 200px; background: var(--fill); }
.stage > .notes { top: 1320px; }
</style>
</head>
<body>
<div class="page">
<h1>Mask geometry</h1>
<p class="lede">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.</p>
<div class="stage">
<div class="moves"><p>Version two</p></div>
<div class="wrap"><div class="clipped"><p>Version two</p></div></div>
<div class="below"></div>
<div class="player">
<div class="poster">Version two</div>
<div class="track"><div class="slide">Slide</div></div>
<div class="menu">Menu</div>
</div>
<div class="under"></div>
<section class="notes">
<h2>Notes</h2>
<p>The first box moves 200px down once renderdiff has read its text, standing in for a pinned section that re-lays out after settle.</p>
</section>
</div>
</div>
<script>
// Stands in for a ScrollTrigger pin refresh. Couples to the text read, which hides each mask
// and restores it: the move lands a moment after the restore.
const box = document.querySelector(".moves");
let hidden = false;
new MutationObserver(() => {
if (box.style.visibility === "hidden") hidden = true;
else if (hidden) {
hidden = false;
setTimeout(() => (box.style.top = "200px"), 30);
}
}).observe(box, { attributes: true, attributeFilter: ["style"] });
</script>
</body>
</html>
1 change: 1 addition & 0 deletions tests/helpers/corpus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export const GUARDRAILS = [
"hang",
"origin",
"cooperate",
"mask-geometry",
] as const;

export const ALL: string[] = [...EQUIVALENCE, ...CONTROLS, ...GUARDRAILS];
Expand Down
32 changes: 32 additions & 0 deletions tests/visual/guardrails.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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", () => {
Expand Down
Loading