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
2 changes: 1 addition & 1 deletion docs/output.md
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ pulls a route), scores rounded down to four decimals (so a shot that differs nev
"results": [
{
"url": "/about", "left": "/about", "right": "/about", // a pair: "/a::/b", "/a", "/b"
"selector": null, "hook": false, // hook: a before hook ran
"selector": null, "hook": false, // hook: a before or beforeShot hook ran
"width": 1440, "status": "compared",
"score": 0.9714, // share of measured pixels that match
"alignedScore": 1, // score over the aligned rows; null unless there are bands
Expand Down
17 changes: 13 additions & 4 deletions docs/scoping.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,10 @@ it, with the clock and seeded `Math.random` already in force:
export default {
routes: [
{ left: "/", before: async (page) => { await page.click("[aria-label=Menu]"); } },
{ left: "/docs", beforeShot: async (page) => { await page.click("[data-tab=intro]"); } },
],
// For every route without its own `before` (which replaces it), CLI routes included.
// For every route without its own `before` (which replaces it), CLI routes included;
// a top-level `beforeShot` works the same way.
before: async (page, { side, route, width }) => {
const accept = page.getByRole("button", { name: "Accept" });
if (await accept.isVisible()) await accept.click();
Expand All @@ -80,10 +82,17 @@ export default {
`side` is `"left"` or `"right"`, `route` the route's name (`/a` or `/a::/b`), `width` the
viewport width. Use `side` only where the markup legitimately differs (the button has a
different selector on each side), never to make the sides look alike. A hook that throws
is a route error, `before hook failed on left: …`, and isn't retried. A route that ran one
has `"hook": true` in `results.json` and a `before hook` badge on its report card.
is a route error, `before hook failed on left: …` (or `beforeShot …`), and isn't retried.
A route that ran one has `"hook": true` in `results.json` and a `hook` badge on its report
card.
Actions in a hook use Playwright's 30s default timeout, so check before clicking what may
not be there (as above); `hideSelectors` and `extraCss` apply after the hook.
not be there (as above); `hideSelectors` and `extraCss` apply after `before` and before `beforeShot`.

The settle scrolls the whole page to load lazy content, so a state the scroll changes (a
scroll-spy nav, a container re-measured on scroll) doesn't survive a `before` hook. Set it in
a `beforeShot` hook instead: same signature, but it runs after the settle, right before masks
and the shot. renderdiff doesn't settle again after it, so await whatever it changes. On a
`selector` route the element is still scrolled into view after it.

## Signed-in pages

Expand Down
8 changes: 5 additions & 3 deletions skills/renderdiff/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,8 @@ Report (`--open`, for a human): green from 99.5%, amber to 97%, red below.
| `page is Npx tall at Wpx wide, past the …px sanity ceiling …` | Taller than 57,600,000px ÷ width (never under 40,000px): a runaway layout, not a page. |
| `selector "…" matched N elements on left (/a), expected 1` | Make it unique (an id, `data-test`, `>> nth=0`), or list the route once per element. |
| `selector "…" has no box on …` / `is off the page on …` | Matched an element not rendered (`display: none`, zero size) or outside the page. |
| `before hook failed on left: …` | The hook threw. Never retried. |
| `timeout after 120s at settle on left` | That side never finished the step (`load`, `before hook`, `settle`, `screenshot`): a hung script, a dead renderer, a hook that never resolves. Retried once in a fresh page, except a hung hook. For a page that is just very slow, raise `RENDERDIFF_SHOT_TIMEOUT` (seconds). |
| `before hook failed on left: …` | The hook threw (`beforeShot hook failed …` for that hook). Never retried. |
| `timeout after 120s at settle on left` | That side never finished the step (`load`, `before hook`, `settle`, `beforeShot hook`, `screenshot`): a hung script, a dead renderer, a hook that never resolves. Retried once in a fresh page, except a hung hook. For a page that is just very slow, raise `RENDERDIFF_SHOT_TIMEOUT` (seconds). |

A failed `--computed` snapshot (`snapshot failed on /a@1440 (…)` on the `computed:` line) is
not a route error: the pixel result stands.
Expand Down Expand Up @@ -258,6 +258,8 @@ computed: 2 findings; dom identical on 2 of 3 route(s), differs /pricing (1), so
banner *both* sides show, sign in, set a carousel to slide 1 on both. Not: branching on
`side` to make the sides look alike, hiding or removing an element on one side. `side` is for
markup that legitimately differs. Say in the verdict that a hook ran (`hook: true`).
`beforeShot` (same forms) runs after settle, right before masks and the shot: for state the
settle's scroll pass changes, e.g. a scroll-spy nav. Nothing settles after it, so await it.
- **Signed-in pages:** `npx playwright codegen --save-storage=auth.json <login url>`, then
`--storage-state auth.json` (or `--left-storage-state`/`--right-storage-state`, or config
`storageState`, relative to the config file). The file holds live session tokens: never
Expand Down Expand Up @@ -287,7 +289,7 @@ export default {
A mask takes exactly one of `selector` or `locate: (page) => Locator`; without `urlPath` it
applies to every route, and on a pair it matches either side's path. `--mask <sel>` adds to the
config's masks. Also: `threshold`, `outDir`, `concurrency`, `extraCss`, `before`,
`storageState`. `hideSelectors`: match the element **exactly** (consent scripts stamp classes on
`beforeShot`, `storageState`. `hideSelectors`: match the element **exactly** (consent scripts stamp classes on
`<html>`; a loose selector blanks the whole document and blank matches blank), and they hide
rather than remove.

Expand Down
7 changes: 6 additions & 1 deletion src/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,12 @@ export const REPLAY_TTL = 60 * 60_000;

/** A shot's identity in a recording: what decides which requests its load makes. */
export const shotId = (route: Route, width: number) =>
JSON.stringify([route.right, width, route.before && String(route.before)]);
JSON.stringify([
route.right,
width,
route.before && String(route.before),
route.beforeShot && String(route.beforeShot),
]);

/** Everything that changes what the right origin serves, so one recording never answers another. */
export function cacheFile(cfg: ResolvedConfig, browser: { name: string; version: string }): string {
Expand Down
17 changes: 11 additions & 6 deletions src/capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ async function networkIdle(page: Page, quiet: number, timeout: number): Promise<
while (Date.now() < end && (net.open.size || Date.now() - net.last < quiet)) await sleep(25);
}

/** A `before` hook threw. Never retried: the hook may have half-run against the page. */
/** A `before` or `beforeShot` hook threw. Never retried: the hook may have half-run against the page. */
export class HookError extends Error {}

/**
Expand Down Expand Up @@ -201,16 +201,19 @@ export async function capture(
const type = res.headers()["content-type"]!.split(";")[0]!.trim();
throw new Error(`not an HTML page: server sent ${type} at ${url}`);
}
if (route.before) {
step.set(page, "before hook");
const hook = async (name: "before" | "beforeShot") => {
const fn = route[name];
if (!fn) return;
step.set(page, `${name} hook`);
try {
await route.before(page, { side, route: label(route), width });
await fn(page, { side, route: label(route), width });
} catch (e) {
throw new HookError(
`before hook failed on ${side}: ${e instanceof Error ? e.message : String(e)}`,
`${name} hook failed on ${side}: ${e instanceof Error ? e.message : String(e)}`,
);
}
}
};
await hook("before");
step.set(page, "settle");
await page.addStyleTag({ content: cfg.neutralizeCss });
// Before the scroll too, so autoplay never starts and page state driven by playback stays put.
Expand Down Expand Up @@ -253,6 +256,8 @@ export async function capture(
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
await hook("beforeShot");
step.set(page, "settle");

const selector = route.selector?.[side];
const where = `on ${side} (${route[side]})`;
Expand Down
6 changes: 4 additions & 2 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,8 @@ const HELP = `
With --storage-state, each side starts with that Playwright storage state (cookies,
localStorage), e.g. signed in. Make one with:
npx playwright codegen --save-storage=auth.json <url>
A before hook in the config runs on each page before it is shot, e.g. to open a menu.
A before hook in the config runs on each page before it settles, e.g. to open a menu;
a beforeShot hook runs after, right before the shot.

--accept "<reason>" records this run's differences in renderdiff.accepted.json (next to
the config, or in cwd); later runs report them as accepted, and anything new still shows.
Expand Down Expand Up @@ -347,6 +348,7 @@ async function sitemapRoutes(spec: string | true, routes: Route[]): Promise<Rout
pages.filter((p) => !covered.has(p)),
args.selector,
fileConfig.before,
fileConfig.beforeShot,
);
}

Expand Down Expand Up @@ -423,7 +425,7 @@ if (!rawRoutes.length && !args.sitemap) {

let routes: Route[];
try {
routes = parseRoutes(rawRoutes, args.selector, fileConfig.before);
routes = parseRoutes(rawRoutes, args.selector, fileConfig.before, fileConfig.beforeShot);
} catch (e) {
die(e instanceof Error ? e.message : String(e));
}
Expand Down
43 changes: 30 additions & 13 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@ export interface Route {
right: string;
selector: Sides | null;
before: Hook | null;
beforeShot: Hook | null;
}

/**
* Runs on each side after the page loads and before it settles and is shot, e.g. to open a
* menu. `route` is the route's name (`/a`, or `/a::/b` for a pair), the same on both sides.
* Runs on each side, e.g. to open a menu: `before` after the page loads, before it settles;
* `beforeShot` after it settles, right before masks and the shot. `route` is the route's name
* (`/a`, or `/a::/b` for a pair), the same on both sides.
*/
export type Hook = (
page: Page,
Expand All @@ -41,7 +43,7 @@ export type Hook = (
*/
export type RouteSpec =
| string
| { left: string; right?: string; selector?: string | Sides; before?: Hook };
| { left: string; right?: string; selector?: string | Sides; before?: Hook; beforeShot?: Hook };

/** `pricing` / `/pricing/` -> `/pricing`; `/` stays `/`. */
export const normalize = (url: string) => {
Expand All @@ -64,9 +66,14 @@ export const name = (r: Pick<Route, "left" | "right" | "selector">) =>
* Specs -> normalized, deduplicated routes; throws on an empty side or a glob. A string is a
* pair when it has a `::` followed by `/` (or ending it, so `/a::` is an empty side, not a
* literal), which keeps `?q=std::vector` and `/wiki/Talk:Foo` single routes. A CLI
* `selector` replaces every route's own; a route's own `before` replaces the top-level one.
* `selector` replaces every route's own; a route's own `before` (or `beforeShot`) replaces the top-level one.
*/
export function parseRoutes(specs: RouteSpec[], selector?: Sides, before?: Hook): Route[] {
export function parseRoutes(
specs: RouteSpec[],
selector?: Sides,
before?: Hook,
beforeShot?: Hook,
): Route[] {
const out = new Map<string, Route>();
for (const spec of specs) {
let sides: [string, string];
Expand All @@ -90,18 +97,20 @@ export function parseRoutes(specs: RouteSpec[], selector?: Sides, before?: Hook)
right: normalize(sides[1]),
selector: selector ?? (typeof own === "string" ? { left: own, right: own } : (own ?? null)),
before: (typeof spec === "string" ? undefined : spec.before) ?? before ?? null,
beforeShot: (typeof spec === "string" ? undefined : spec.beforeShot) ?? beforeShot ?? null,
};
const same = out.get(name(route));
// JSON drops a function but keeps a null, so `before` is compared on its own below.
// JSON drops a function but keeps a null, so hooks are compared on their own below.
if (
same &&
JSON.stringify({ ...same, before: 0 }) !== JSON.stringify({ ...route, before: 0 })
JSON.stringify({ ...same, before: 0, beforeShot: 0 }) !==
JSON.stringify({ ...route, before: 0, beforeShot: 0 })
) {
throw new Error(`two routes both read as ${name(route)}; change one of their selectors`);
}
if (same && same.before !== route.before) {
if (same && (same.before !== route.before || same.beforeShot !== route.beforeShot)) {
throw new Error(
`two routes both read as ${name(route)}; they have different before hooks — merge them into one route`,
`two routes both read as ${name(route)}; they have different hooks — merge them into one route`,
);
}
out.set(name(route), route);
Expand Down Expand Up @@ -237,10 +246,12 @@ export interface RenderdiffConfig {
left?: string;
/** Right origin, e.g. `https://example.com`. A trailing slash is stripped. */
right?: string;
/** Routes to diff when none are passed on the command line. A route object may take a `selector` and a `before`. */
/** Routes to diff when none are passed on the command line. A route object may take a `selector`, `before` and `beforeShot`. */
routes?: RouteSpec[];
/** A {@link Hook} for every route without its own `before`, CLI routes included. */
before?: Hook;
/** A {@link Hook} for every route without its own `beforeShot`, CLI routes included. */
beforeShot?: Hook;
/**
* Playwright storage state files (cookies, localStorage) to start each side with, e.g. to be
* signed in. One path for both sides, or per side. Relative to the config file.
Expand Down Expand Up @@ -394,6 +405,7 @@ function validate(c: Record<string, unknown>, file: string) {
}
const hook = "a function (page, { side, route, width }) => Promise<void>";
if (c.before !== undefined && typeof c.before !== "function") bad("before", hook);
if (c.beforeShot !== undefined && typeof c.beforeShot !== "function") bad("beforeShot", hook);
const s = c.storageState as Record<string, unknown> | undefined;
if (
s !== undefined &&
Expand All @@ -414,18 +426,23 @@ function validate(c: Record<string, unknown>, file: string) {
(c.routes as unknown[]).forEach((r, i) => {
if (typeof r === "string") return;
if (typeof r !== "object" || r === null || Array.isArray(r)) {
bad(`routes[${i}]`, "a string or an object { left, right?, selector?, before? }");
bad(
`routes[${i}]`,
"a string or an object { left, right?, selector?, before?, beforeShot? }",
);
}
const o = r as Record<string, unknown>;
for (const key of Object.keys(o)) {
if (!["left", "right", "selector", "before"].includes(key)) {
if (!["left", "right", "selector", "before", "beforeShot"].includes(key)) {
throw new Error(
`${file}: \`routes[${i}].${key}\` is not a route key (left, right, selector, before)`,
`${file}: \`routes[${i}].${key}\` is not a route key (left, right, selector, before, beforeShot)`,
);
}
}
if (o.before !== undefined && typeof o.before !== "function")
bad(`routes[${i}].before`, hook);
if (o.beforeShot !== undefined && typeof o.beforeShot !== "function")
bad(`routes[${i}].beforeShot`, hook);
const sel = o.selector as Record<string, unknown> | undefined;
if (
sel !== undefined &&
Expand Down
4 changes: 2 additions & 2 deletions src/report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ interface BaseResult {
right: string;
/** The element compared on each side; null for the whole page. */
selector: Sides | null;
/** A `before` hook ran on both sides before the shot, so the page was measured in its state. */
/** A `before` or `beforeShot` hook ran on both sides before the shot, so the page was measured in its state. */
hook: boolean;
width: number;
}
Expand Down Expand Up @@ -424,7 +424,7 @@ const head = (r: ComparedResult) => `
<span class="score ${band(r.score)}">${pct(r.score)}</span>
<code>${esc(name(r))}</code>
<span class="w">@${r.width}px</span>
${r.hook ? `<span class="hook">before hook</span>` : ""}
${r.hook ? `<span class="hook">hook</span>` : ""}
${r.accepted ? `<span class="accepted">accepted: ${esc(reasons(r))}</span>` : ""}
${r.heightDelta ? `<span class="delta">height ${signed(r.heightDelta)}px</span>` : ""}
${r.widthDelta ? `<span class="delta">width ${signed(r.widthDelta)}px</span>` : ""}
Expand Down
11 changes: 8 additions & 3 deletions src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,8 +313,13 @@ export async function run({
for (let job = queue.shift(); job; job = queue.shift()) {
const { route, width } = job;
const key = name(route);
const { before, ...where } = route;
const entry = { url: label(route), ...where, hook: before !== null, width };
const { before, beforeShot, ...where } = route;
const entry = {
url: label(route),
...where,
hook: before !== null || beforeShot !== null,
width,
};
const tag = `${label(route)} @${width}`;
// Its own line: parse.ts reads the route on the row as one \S+ token.
const sel = route.selector ? `selector ${selectorText(route.selector)}` : "";
Expand Down Expand Up @@ -733,7 +738,7 @@ async function shoot(
await page.close();
pages[side] = await page.context().newPage();
await prepare(pages[side], cfg, now);
const E = at === "before hook" ? HookError : errors.TimeoutError;
const E = at === "before hook" || at === "beforeShot hook" ? HookError : errors.TimeoutError;
throw new E(`timeout after ${SHOT_TIMEOUT / 1000}s at ${at} on ${side}`);
};
try {
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`, `unsettled-once`, `sprite`, `short`, `tall-region`, `reorder`, `stripe`, `frameset`, `menu`, `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`.
One per defence in `src/capture.ts` / `src/config.ts`.

## Authoring rules
Expand Down
Loading
Loading