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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,8 @@ renderdiff <left-origin> <right-origin> <route…> [options]
| `--selector <sel>` | Compare the one element this Playwright selector matches, on both sides, instead of the whole page. Applies to every route, over the config's per-route `selector`. |
| `--left-selector <sel>`, `--right-selector <sel>` | That side's selector, over `--selector`. One without the other side (or `--selector`) is an error. |
| `--mask <sel>` | Paint this Playwright selector over on both sides, on every route; repeatable. Added to the config's masks and listed in the report as coverage given up. |
| `--mask-media` | Mask every `iframe`, `video` and `.vjs-text-track-display` (video.js text tracks) on every route, as config `maskMedia: true` does. |
| `--mask-media` | Mask every `iframe` on every route, as config `maskMedia: true` does. Video isn't masked: it is frozen by default, so the player's box and styles are still compared. |
| `--no-freeze-video` | Leave videos playing and video.js overlays visible, as config `freezeVideo: false` does. By default no `video` plays, from the page's first script on, so each shows its poster (one that started anyway is paused at frame 0), and `.vjs-text-track-display` / `.vjs-control-bar` are hidden. Without freezing, videos play through the lazy-load scroll and the shots, so expect unstable pixels or `did not settle`; with `--mask-media` too, they are neither masked nor frozen. |
| `--storage-state <file>` | Start both sides with this Playwright storage state (cookies, localStorage), e.g. signed in. Relative to cwd. Over the config's `storageState`. |
| `--left-storage-state <file>`, `--right-storage-state <file>` | That side's storage state, over `--storage-state`. One side alone is fine. |
| `--accept <reason>` | Record this run's differences as accepted, with a reason. See **Accepted differences and reruns**. |
Expand Down Expand Up @@ -308,7 +309,7 @@ Paths are relative to the out dir. Results are in route-then-width order.
- **Refuses to start** unless both origins answer: two error pages would score ~100%.
- **Refuses a shot** with an HTTP status ≥ 400, or where both sides look blank.
- **Blocks analytics, consent and A/B tooling** at the network layer, on both sides.
- **Pins what varies between loads**: clock, `Math.random`, timezone, locale, colour scheme, reduced motion, video frames.
- **Pins what varies between loads**: clock, `Math.random`, timezone, locale, colour scheme, reduced motion, video frames and video.js overlays.
- **Kills animation, transitions and caret blink**, and hides common consent banners and dev toolbars.
- **Settles the page**: lazy images, fonts and network idle before the shot.
- **Shoots until stable**, and excludes pixels still moving as `unstable`.
Expand Down
2 changes: 1 addition & 1 deletion docs/how-it-works.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ honestly. This is what renderdiff does to make sure of that.
- **Pins what varies between loads**, identically on both sides: the clock starts at one
instant per run (floored to the minute) on every load and then runs, `Math.random` is
seeded, timezone (UTC), locale (en-US), colour scheme (light) and
`prefers-reduced-motion` are fixed, and videos are paused at frame 0. A clock that shows
`prefers-reduced-motion` are fixed, and videos are kept from playing (each shows its poster) with video.js captions and control bars hidden (`--no-freeze-video` opts out). A clock that shows
seconds can still tick between the two sides and may need a mask.
- **Kills animation, transitions and caret blink**, and hides common consent banners and
dev toolbars.
Expand Down
2 changes: 1 addition & 1 deletion renderdiff.config.example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ export default {
//
// Each needs exactly one of `selector` (a Playwright selector) or `locate`. Without
// `urlPath` it applies to every route; on a pair it matches either side's path.
// `maskMedia: true` (or --mask-media) adds one for iframes, video and video.js text tracks.
// `maskMedia: true` (or --mask-media) adds one for iframes.
masks: [
{
// Baked in at build time from a nightly job, so a local tree and a production
Expand Down
2 changes: 1 addition & 1 deletion skills/renderdiff/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ legitimate: [reference.md](reference.md).
pagination and admin. `--dry-run` shows the URL pairs.
2. **Baseline first.** Before changing code, run the base against the reference. Against
the base build that is base vs base, so whatever differs varies per load: mask it
(`--mask-media` for iframes, video and video.js text tracks; `--mask <sel>` or a config
(`--mask-media` for iframes; video is frozen by default; `--mask <sel>` or a config
mask with a `reason` for the rest), then rerun until the baseline is clean. Against
production, `--accept "differs before the change"` what is stable drift. Mask or accept
only what you looked at, never to get green.
Expand Down
6 changes: 3 additions & 3 deletions skills/renderdiff/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ Left is your change, right is the reference: `+` is only/more on the left, `-` o
| `dom sel` (nothing after it) | On both sides, and no compared style changed and it didn't move: its own pixels did (an image's source, a canvas, an SVG). Open the crop. |
| No `dom` line | Nothing was found under the change, a band whose rows hold nothing only one side has, past the first five bands and regions, or the probe timed out. Open the crop. |
| `band …@y~N` | Widths collapsed into one row put the band at different `y`; `N` is the first width's. |
| `unstable Npx` | Pixels that kept changing between shots of the same load on one origin (a ticker, a carousel, a video). Painted out on both sides and excluded from the score. A large number means a big area went unmeasured: look at the magenta on the full shots. Such a route is never on the `clean:` line. |
| `unstable Npx` | Pixels that kept changing between shots of the same load on one origin (a ticker, a carousel, a video with `--no-freeze-video`). Painted out on both sides and excluded from the score. A large number means a big area went unmeasured: look at the magenta on the full shots. Such a route is never on the `clean:` line. |
| `ERROR selector "…" matched N elements on left (/a), expected 1` | A selector must match exactly one element per side. Make it more specific (`>> nth=0`, an id, `data-test`), or list the route once per element. |
| `ERROR selector "…" has no box on …` | It matched an element that isn't rendered (`display: none`, zero size). |
| `accepted: /a /b` | Every difference on those routes matches `renderdiff.accepted.json`. Known, not verified again: say so in the verdict. |
Expand All @@ -44,7 +44,7 @@ Report colouring (`--open`, for a human): green above 99.5%, amber to 97%, red b
| "It's probably just fonts / antialiasing." | "Probably" is exactly what the crop resolves. Look. |
| "`dom` says margin, done." | It's a computed value. Confirm the source rule changed on purpose, and still open the crop when the region is large or `dom` names nothing. |
| "The crops looked fine, done." | There are at most three: bands, then the largest regions. Check the region count, any `clipped` crop in results.json, and open the diff PNG for the rest and for any height delta: padding is never cropped. |
| "Masking the header gets this to 100%." | Every mask is coverage surrendered. Mask only content *proven* to vary per load (clocks, star counts, rotating quotes), with a `reason`, which the report prints verbatim. Differing base vs base is that proof; `--mask-media` still gives up every iframe and video. |
| "Masking the header gets this to 100%." | Every mask is coverage surrendered. Mask only content *proven* to vary per load (clocks, star counts, rotating quotes), with a `reason`, which the report prints verbatim. Differing base vs base is that proof; `--mask-media` still gives up every iframe. |
| "I'll `--accept` it so the run is green." | Accept only differences you opened and that exist before your change (or are intended), with a reason that says which. |
| "I'll lower `--threshold` until it passes." | `--threshold` relaxes the exit code; the difference is still there. It's a CI gate, not a dial for reaching green. |
| "That route errors, I'll drop it from the list." | Shrinking the route list shrinks what you verified. Fix it, or say it's unverified. |
Expand Down Expand Up @@ -94,7 +94,7 @@ A mask takes exactly one of `selector` or `locate: (page) => Locator`; without `
applies to every route, and on a pair it matches either side's path and paints both. A plain
`export default {}` needs no import; a type import from "renderdiff" is for editor types only. Without a config, `--mask <sel>` (repeatable) adds a mask on every
route, after the config's; `--mask-media` (config `maskMedia: true`) adds one for
`iframe, video, .vjs-text-track-display`. Both are listed in the report like any mask. [`renderdiff.config.example.ts`](https://github.com/tmashara/renderdiff/blob/main/renderdiff.config.example.ts)
`iframe`; videos are already kept from playing, with video.js overlays hidden, unless `--no-freeze-video`. Both are listed in the report like any mask. [`renderdiff.config.example.ts`](https://github.com/tmashara/renderdiff/blob/main/renderdiff.config.example.ts)
annotates every field.

Two rules for `hideSelectors`: match the element **exactly** (consent scripts also stamp
Expand Down
10 changes: 9 additions & 1 deletion src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,15 @@ export function cacheFile(cfg: ResolvedConfig, browser: { name: string; version:
const state = cfg.storageState.right && fs.readFileSync(cfg.storageState.right, "utf8");
const key = createHash("sha256")
.update(
JSON.stringify([version(), browser, cfg.right, state, CONTEXT_OPTIONS, cfg.blockUrlPatterns]),
JSON.stringify([
version(),
browser,
cfg.right,
state,
CONTEXT_OPTIONS,
cfg.blockUrlPatterns,
cfg.freezeVideo,
]),
)
.digest("hex")
.slice(0, 16);
Expand Down
45 changes: 41 additions & 4 deletions src/capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,32 @@ export interface Shot {
failed: string[];
}

/**
* Runs in the page, behind `prepare`'s init script: pause every video, open shadow roots
* included. One that played anyway is rewound to frame 0; one that hasn't keeps its poster.
*/
function freezeVideo() {
const videos = (root: Document | ShadowRoot): HTMLVideoElement[] => [
...Array.from(root.querySelectorAll("video")),
...Array.from(root.querySelectorAll("*")).flatMap((e) =>
e.shadowRoot ? videos(e.shadowRoot) : [],
),
];
return Promise.all(
videos(document).map((v) => {
v.autoplay = false;
v.pause();
if (!v.readyState || (!v.played.length && !v.currentTime)) return;
const seeked = new Promise((r) => {
v.addEventListener("seeked", r, { once: true });
setTimeout(r, 2_000);
});
v.currentTime = 0;
return seeked;
}),
);
}

/**
* 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 @@ -100,6 +126,18 @@ export async function prepare(page: Page, cfg: ResolvedConfig, now: number): Pro
}
// Time flows, so Date-based debounce and busy-waits work; `capture` rewinds it per load.
await page.clock.install({ time: now });
// From the first script on, so no video starts and each keeps its poster however fast it loads.
if (cfg.freezeVideo)
await page.addInitScript(() => {
HTMLMediaElement.prototype.play = () => Promise.resolve();
document.addEventListener(
"loadstart",
(e) => {
if (e.target instanceof HTMLMediaElement) e.target.autoplay = false;
},
true,
);
});
// mulberry32 with a fixed seed, re-seeded on every navigation.
await page.addInitScript(() => {
let s = 0x9e3779b9;
Expand Down Expand Up @@ -143,17 +181,15 @@ export async function capture(
}
}
await page.addStyleTag({ content: cfg.neutralizeCss });
// Before the scroll too, so autoplay never starts and page state driven by playback stays put.
if (cfg.freezeVideo) await page.evaluate(freezeVideo);

// Native lazy images go eager; JS lazy loaders see every viewport-height slice, one
// frame each, since a scroll inside one synchronous loop never paints.
await page.evaluate(async (maxHeight) => {
// The fake clock drives rAF too, so add wall time for a real paint per slice.
const frame = () => new Promise((r) => requestAnimationFrame(() => setTimeout(r, 32)));
Array.from(document.images).forEach((img) => (img.loading = "eager"));
document.querySelectorAll("video").forEach((v) => {
v.pause();
v.currentTime = 0;
});
const h = Math.min(document.documentElement.scrollHeight, maxHeight);
for (let y = 0; y < h; y += window.innerHeight) {
window.scrollTo(0, y);
Expand All @@ -179,6 +215,7 @@ export async function capture(
return failed;
});
await networkIdle(page, 250, 3_000);
if (cfg.freezeVideo) await page.evaluate(freezeVideo);
const failed = [...new Set([...network.get(page)!.failed, ...fonts])];
await page.addStyleTag({ content: cfg.neutralizeCss }); // anything injected late

Expand Down
4 changes: 3 additions & 1 deletion src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ function parseArgs(argv: string[]): Args {
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 === "--no-freeze-video") a.freezeVideo = false;
else if (v === "--accept") {
a.accept = next().trim();
if (!a.accept) throw new Error("--accept needs a reason");
Expand Down Expand Up @@ -203,7 +204,8 @@ const HELP = `
--left-selector <sel>, --right-selector <sel>
That side's selector, over --selector.
--mask <sel> Paint this selector over on both sides, every route; repeatable.
--mask-media Mask iframe, video and .vjs-text-track-display on every route.
--mask-media Mask every iframe on every route.
--no-freeze-video Leave videos playing and video.js overlays visible.
--storage-state <file>
Start both sides with this storage state JSON. Never commit it.
--left-storage-state <file>, --right-storage-state <file>
Expand Down
24 changes: 19 additions & 5 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,10 +225,10 @@ export type Mask = {
| { /** The escape hatch for what a selector can't say. */ locate: (page: Page) => Locator }
);

/** The `maskMedia` / `--mask-media` preset: embeds and players that differ per load. */
/** The `maskMedia` / `--mask-media` preset: embeds that differ per load. Video is frozen instead. */
export const MEDIA_MASK: Mask = {
selector: "iframe, video, .vjs-text-track-display",
reason: "iframes, video and video.js text tracks (--mask-media)",
selector: "iframe",
reason: "iframes (--mask-media)",
};

/** The shape a `renderdiff.config.*` file default-exports. Every field is optional. */
Expand Down Expand Up @@ -264,8 +264,10 @@ export interface RenderdiffConfig {
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. */
/** Mask every `iframe` on every route. */
maskMedia?: boolean;
/** Keep every video from playing, so it shows its poster, and hide video.js overlays. Default true. */
freezeVideo?: boolean;
}

/** A fully merged config. Everything the run needs, nothing optional. */
Expand All @@ -285,6 +287,7 @@ export interface ResolvedConfig {
/** Absolute storage state paths, checked to be JSON; null for a side without one. */
storageState: { left: string | null; right: string | null };
computed: boolean;
freezeVideo: boolean;
}

/** package.json's version; the same relative path resolves from `src/` and `dist/`. */
Expand Down Expand Up @@ -482,6 +485,8 @@ function validate(c: Record<string, unknown>, file: string) {
});
}
if (c.maskMedia !== undefined && typeof c.maskMedia !== "boolean") bad("maskMedia", "a boolean");
if (c.freezeVideo !== undefined && typeof c.freezeVideo !== "boolean")
bad("freezeVideo", "a boolean");
}

/** CLI-supplied values. `undefined` means "not passed", so the config file wins. */
Expand All @@ -498,6 +503,7 @@ export interface CliOverrides {
/** From --mask, appended to the config's masks. */
masks?: string[];
maskMedia?: boolean;
freezeVideo?: boolean;
}

/** Merge built-in defaults, the config file, and CLI flags into one resolved config. */
Expand All @@ -522,6 +528,7 @@ export function resolveConfig(file: RenderdiffConfig, cli: CliOverrides): Resolv
: file.storageState;

const hideSelectors = [...DEFAULT_HIDE_SELECTORS, ...(file.hideSelectors ?? [])];
const freezeVideo = cli.freezeVideo ?? file.freezeVideo ?? true;

return {
left: left.replace(/\/+$/, ""),
Expand All @@ -533,7 +540,13 @@ export function resolveConfig(file: RenderdiffConfig, cli: CliOverrides): Resolv
blockUrlPatterns: [...DEFAULT_BLOCK_URL_PATTERNS, ...(file.blockUrlPatterns ?? [])],
hideSelectors,
neutralizeCss:
STILL_CSS + `${hideSelectors.join(",")}{display:none!important}\n` + (file.extraCss ?? ""),
STILL_CSS +
`${hideSelectors.join(",")}{display:none!important}\n` +
// visibility, not display, so the player keeps its layout.
(freezeVideo
? ".vjs-text-track-display,.vjs-control-bar,.vjs-control-bar *{visibility:hidden!important}\n"
: "") +
(file.extraCss ?? ""),
masks: [
...(file.masks ?? []).map((m) =>
m.urlPath === undefined ? m : { ...m, urlPath: normalize(m.urlPath) },
Expand All @@ -546,6 +559,7 @@ export function resolveConfig(file: RenderdiffConfig, cli: CliOverrides): Resolv
right: storageFile(cli.storageState?.right ?? fileState?.right),
},
computed: cli.computed ?? file.computed ?? false,
freezeVideo,
};
}

Expand Down
4 changes: 3 additions & 1 deletion src/report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,9 @@ ${
<p>Pinned on both sides: clock starts at <code>${esc(meta.clock)}</code> on every load, a seeded
<code>Math.random</code>, timezone <code>${CONTEXT_OPTIONS.timezoneId}</code>, locale
<code>${CONTEXT_OPTIONS.locale}</code>, <code>${CONTEXT_OPTIONS.colorScheme}</code> colour
scheme, reduced motion, CSS animations and transitions off, videos paused at frame 0.</p>
scheme, reduced motion, CSS animations and transitions off${
cfg.freezeVideo ? ", videos kept from playing with video.js overlays hidden" : ""
}.</p>
<p>Unstable pixels — ones that changed between two shots of the same load — are painted
magenta on both sides, counted on each card, and excluded from the measurement. A route
more than 25% unstable is an error.</p>
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`, `consent`,
`drifting`, `tracker`, `clock`, `ticker`, `unsettled`, `sprite`, `short`, `tall-region`, `reorder`, `stripe`, `frameset`, `menu`, `signed-in`, `fixed`, `inserted`, `labelled`, `broken-asset`, `media`, `long`.
`drifting`, `tracker`, `clock`, `ticker`, `unsettled`, `sprite`, `short`, `tall-region`, `reorder`, `stripe`, `frameset`, `menu`, `signed-in`, `fixed`, `inserted`, `labelled`, `broken-asset`, `media`, `long`, `video`.
One per defence in `src/capture.ts` / `src/config.ts`.

## Authoring rules
Expand Down
Loading
Loading