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
14 changes: 13 additions & 1 deletion docs/output.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ renderdiff: 2 of 3 routes differ (6 of 15 shots), 0 errors, worst 97.41% /about@
A row covers the widths that agree on height and width delta (`h`, `w`), bands, aligned
score and text; the score and region count are then shown as ranges, and `unstable` as the
largest. Bands are `+` for rows only the left has and `-` for rows only the right has, at
`y`, with `~` when the widths put it in different places. Up to three text-diff lines
`y`, with `~` when the widths put it in different places. A region that is a thin line
across the page shows as `line -1px@y812` instead of counting toward `reg`; past three, `(+N more)`. Up to three text-diff lines
follow (`-"x"` only on the right, `+"x"` only on the left, `(+N more)` past that). Under a
row, `failed` lists stylesheets and font faces a side failed to load (fix those first),
`dom` names up to three elements behind the changes (`@w` when the row covers several
Expand Down Expand Up @@ -63,6 +64,7 @@ because an unmeasured route is not a verified one.
| Can't align | `rows too different to align` | `unaligned` | `bands: null` |
| Text | `text: 0 added, 1 removed` | `text -"Pricing"` | `text: { added: [], removed: ["Pricing"] }` |
| Regions | (on the report card) | `3 reg` | `regions: [...]` |
| Line | `line -1px@y812` | `line -1px@y812` | `regions[i].line: { y: 812, h: 1, side: "right" }` |
| Unstable | `(unstable 1,204px)` | `unstable 1,204px` | `unstablePixels: 1204` |
| Failed assets | `failed left: font Inter 700` | `failed left: font Inter 700` | `failed: { left: ["font Inter 700"], right: [] }` |

Expand All @@ -88,6 +90,11 @@ from the realigned rows, so content a band only pushed down isn't one (above, th
the whole difference, so there are none). The card lists the top five with their pixel
counts; up to three crops cover the bands first, then the largest regions.

A region whose differing pixels sit in one or two rows spanning at least half the page is a
line: a divider, border or focus ring that one side lost. `line -1px@y812` means only the
right (the reference) draws it, `+` only the left, and no sign that both do, differently.
A line barely moves the score, so `99.97% line -1px@y812` is worth opening.

## Bands

Rows only one side has, found by aligning the two images row by row. `-24px at y=196
Expand All @@ -111,6 +118,11 @@ right after the shot. Each is a CSS selector unique on its side, so `--selector`
first. A computed value is a symptom: find the rule that set it.
- `sel x+8` moved without a style of its own changing, so the cause is a neighbour or its
parent, which is listed after it when one of them changed.
- `-sel::before` / `+sel::before` is a pseudo-element only the right / left generates, and
`sel::after height 1px→2px` one on both whose `content`, size, background, top or bottom
border, or `box-shadow` differ. It carries `(re-parented)` when its element does.
- `(re-parented)` after an entry means its ancestors' tags differ between the sides, so the
pairing crossed a structure change: its properties may not be the cause.
- A bare `sel` is on both sides with nothing compared changed or moved, so its own pixels did
(an image's source, a canvas).

Expand Down
8 changes: 6 additions & 2 deletions skills/renderdiff/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ Left is your change, right is the reference: `+` is only/more on the left, `-` o
| `unaligned` | The pages differ in height but share too few identical rows to align, so no bands. Either they are very different, the edits total more than 2,000 rows, or sub-threshold noise touches every row. Use the height delta and regions. |
| `dom sel margin-left 24px→16px` | That element is on both sides and those computed values differ, left first. The value is a symptom: find the rule that sets it, and check it changed on purpose. |
| `dom +sel "x"` / `dom -sel "x"` | That element exists only on the left (your change) / only on the right. |
| `dom -sel::before` / `+sel::before` | That pseudo-element is generated only on the right / only on the left; `sel::before height 1px→2px` is one on both that differs. A lost divider often shows only here. |
| `dom … (re-parented)` | Paired across a structure change (ancestor tags differ), so the listed properties may not be the cause. Open the crop. |
| `line -1px@yN` | A 1–2px line across the page that only the right draws (`+`: only the left, no sign: both, differently). Small in pixels, large visually: a lost border or divider. Check `dom` for a `::before`/`::after`. |
| `dom sel x+8` | It moved but no style of its own changed: the neighbour or parent listed after it is the cause; with none listed, look above it. |
| `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. |
Expand Down Expand Up @@ -51,8 +54,9 @@ Report colouring (`--open`, for a human): green above 99.5%, amber to 97%, red b
## results.json

Scripts, and drilling into one route: every score, region (`x,y,w,h,pixels`, left-page
px), band, their `elements` (`selector`, `side`, each side's box, `changed`, `text`, and
`rightSelector` when the right was found under another selector; absent when not looked
px, `line` `{ y, h, side }` when it is a thin line), band, their `elements` (`selector`, `side`, each side's box, `changed`, `text`, and
`rightSelector` when the right was found under another selector, `reparented` when paired
across a structure change; absent when not looked
at, `[]` when nothing was named), full text diff, image path and crop (`kind`, each side's box with `h` 0 at an
insertion point, `layout` `stacked` = left on top or `side` = left on the left, `scale`,
`clipped`), `selector` (`{ left, right }` or null), with `--computed` a `computed` per result
Expand Down
89 changes: 81 additions & 8 deletions src/compare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ export interface Region {
h: number;
/** Differing pixels inside it. */
pixels: number;
/** When it is a thin horizontal run across the page: its row, height and the side that draws it. */
line?: Line;
/** The elements under it; absent when not looked at. */
elements?: ElementDiff[];
/** Both sides' pixels under it, hashed, for matching it against accepted ones. */
Expand All @@ -35,6 +37,15 @@ export interface Region {
accepted?: string;
}

export interface Line {
/** Top row, in left page px. */
y: number;
/** 1 or 2. */
h: number;
/** Which side draws it; null when both do, e.g. a recolour. */
side: "left" | "right" | null;
}

/** Rows one side has that the other lacks, at `y` in that side's own coordinates. */
export interface Band {
side: "left" | "right";
Expand Down Expand Up @@ -150,7 +161,7 @@ export async function compare(left: Shot, right: Shot): Promise<Diff> {
const aligned = diffPixels
? align(l, r, w, cw, lh, rh)
: { bands: [], alignedScore: null, regions: [], spots: [] };
const found = aligned.regions ?? regions(out, w, cw, Math.min(lh, rh));
const found = aligned.regions ?? regions(out, w, cw, Math.min(lh, rh), l, r);
const spots = aligned.regions
? aligned.spots
: [
Expand Down Expand Up @@ -262,17 +273,24 @@ function textDiff(a: string[], b: string[]): TextDiff {

/**
* Connected components (8-way) over 16px cells holding any pixel pixelmatch painted as a diff,
* within the top-left `w`×`h` of the `stride`-wide diff.
* within the top-left `w`×`h` of the `stride`-wide diff of `a` and `b`.
*/
function regions(out: Buffer, stride: number, w: number, h: number): Region[] {
function regions(
out: Buffer,
stride: number,
w: number,
h: number,
a: Buffer,
b: Buffer,
): Region[] {
const cw = Math.ceil(w / CELL),
ch = Math.ceil(h / CELL);
const cells = new Uint32Array(cw * ch);
for (let y = 0; y < h; y++) {
const row = ((y / CELL) | 0) * cw;
for (let x = 0, o = y * stride * 4; x < w; x++, o += 4) {
// diffColor red; unchanged pixels are grey and AA ones yellow, so neither matches.
if (out[o] === 255 && out[o + 1] === 0 && out[o + 2] === 0) {
if (red(out, o)) {
cells[row + ((x / CELL) | 0)]!++;
}
}
Expand Down Expand Up @@ -307,17 +325,68 @@ function regions(out: Buffer, stride: number, w: number, h: number): Region[] {
}
}
}
found.push({
const g: Region = {
x: x0 * CELL,
y: y0 * CELL,
w: Math.min(w, (x1 + 1) * CELL) - x0 * CELL,
h: Math.min(h, (y1 + 1) * CELL) - y0 * CELL,
pixels,
});
};
const l = g.h <= 2 * CELL && line(g, out, stride, w, h, a, b);
found.push(l ? { ...g, line: l } : g);
}
return found.sort((a, b) => b.pixels - a.pixels);
}

const red = (out: Buffer, o: number) => out[o] === 255 && out[o + 1] === 0 && out[o + 2] === 0;

/**
* A region whose red pixels sit in 1–2 rows spanning at least half the width and filling most of
* that run. A side draws it when its pixels there differ from the rows on both sides of it.
*/
function line(
g: Region,
out: Buffer,
stride: number,
w: number,
h: number,
a: Buffer,
b: Buffer,
): Line | null {
let x0 = w,
y0 = h,
x1 = -1,
y1 = -1,
n = 0;
for (let y = g.y; y < g.y + g.h; y++)
for (let x = g.x; x < g.x + g.w; x++)
if (red(out, (y * stride + x) * 4)) {
x0 = Math.min(x0, x);
x1 = Math.max(x1, x);
y0 = Math.min(y0, y);
y1 = Math.max(y1, y);
n++;
}
const lh = y1 - y0 + 1,
lw = x1 - x0 + 1;
// ponytail: half the compared width counts as across the page; full width only if it misfires
if (lh > 2 || lw < w / 2 || n < 0.5 * lw * lh) return null;
const around = [y0 - 1, y1 + 1].filter((y) => y >= 0 && y < h);
if (!around.length) return null;
const pa = new Uint32Array(a.buffer, a.byteOffset, (a.length / 4) | 0),
pb = new Uint32Array(b.buffer, b.byteOffset, (b.length / 4) | 0);
let da = 0,
db = 0;
for (let y = y0; y <= y1; y++)
for (let x = x0; x <= x1; x++) {
if (!red(out, (y * stride + x) * 4)) continue;
if (around.every((n) => pa[y * stride + x] !== pa[n * stride + x])) da++;
if (around.every((n) => pb[y * stride + x] !== pb[n * stride + x])) db++;
}
const [sa, sb] = [da > n / 2, db > n / 2];
return { y: y0, h: lh, side: sa === sb ? null : sa ? "left" : "right" };
}

/** FNV-1a over each row's RGBA words. */
function rowHashes(raw: Buffer, w: number, rows: number): Uint32Array {
const px = new Uint32Array(raw.buffer, raw.byteOffset, w * rows);
Expand Down Expand Up @@ -422,12 +491,16 @@ function align(l: Buffer, r: Buffer, w: number, cw: number, lh: number, rh: numb
const out = Buffer.alloc(rows.length * stride);
const diff = pixelmatch(a, b, out, w, rows.length, PIXELMATCH);
const measured = rows.length * w - masked;
const found = diff ? regions(out, w, cw, rows.length) : [];
const found = diff ? regions(out, w, cw, rows.length, a, b) : [];
const side = (g: Region, s: 0 | 1) => {
const y = rows[g.y]![s];
return { y, h: rows[g.y + g.h - 1]![s] + 1 - y };
};
const regs = found.map((g) => ({ ...g, ...side(g, 0) }));
const regs = found.map((g) => ({
...g,
...side(g, 0),
...(g.line ? { line: { ...g.line, y: rows[g.line.y]![0] } } : {}),
}));
found.forEach((g, i) => {
spots.push({
kind: "region",
Expand Down
10 changes: 8 additions & 2 deletions src/format.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Line } from "./compare.ts";
import type { ElementDiff } from "./locate.ts";

/** Number formatting shared by the console summary (`run.ts`) and the HTML report. */
Expand All @@ -16,6 +17,10 @@ export const fmtRegion = (r: { x: number; y: number; w: number; h: number }) =>
export const fmtBand = (b: { side: "left" | "right"; y: number; h: number }) =>
`${b.side === "left" ? "+" : "-"}${b.h}px at y=${b.y} (${b.side})`;

/** `line -1px@y812`: signed like a band, − when only the reference draws it; `~` when approximate. */
export const fmtLine = (l: Line, approx = false) =>
`line ${l.side === "left" ? "+" : l.side === "right" ? "-" : ""}${l.h}px@y${approx ? "~" : ""}${l.y}`;

/** `+sel "text"` / `-sel "text"` for one side only, `sel prop l→r`, else its box deltas (left − right). */
export const fmtElements = (els: ElementDiff[], props = 2) =>
els
Expand All @@ -25,11 +30,12 @@ export const fmtElements = (els: ElementDiff[], props = 2) =>
const changed = Object.entries(e.changed)
.slice(0, props)
.map(([p, [l, r]]) => (p === "text" ? `"${l}"→"${r}"` : `${p} ${l}→${r}`));
if (changed.length) return `${e.selector} ${changed.join(", ")}`;
const re = e.reparented ? " (re-parented)" : "";
if (changed.length) return `${e.selector} ${changed.join(", ")}${re}`;
const moved = (["x", "y", "w", "h"] as const).flatMap((k) => {
const d = e.left![k] - e.right![k];
return d ? [`${k}${signed(d)}`] : [];
});
return [e.selector, ...moved].join(" ");
return [e.selector, ...moved].join(" ") + re;
})
.join("; ");
80 changes: 76 additions & 4 deletions src/locate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ export interface ElementDiff {
text: string;
/** The right side's selector, when it was found by its text under a different one. */
rightSelector?: string;
/** Paired although its parent's or grandparent's tags differ, so the props may not be the cause. */
reparented?: true;
}

const MAX_SPOTS = 5;
Expand Down Expand Up @@ -76,6 +78,10 @@ interface Seen {
text: string;
box: Box;
styles: string[];
/** Its grandparent's and parent's tags, e.g. `section>div`. */
up: string;
/** `::before` and `::after` when generated: their content, size, background and borders. */
pseudo: (Record<string, string> | null)[];
}

interface Hit extends Seen {
Expand Down Expand Up @@ -117,6 +123,11 @@ function probe({ boxes, find, masked, props, perSpot, walk, root }: ProbeArgs) {
const unique = (s: string) => document.querySelectorAll(s).length === 1;
const snippet = (e: Element) =>
((e as HTMLElement).innerText ?? e.textContent ?? "").replace(/\s+/g, " ").trim().slice(0, 40);
const generated = (e: Element, pseudo: string) => {
const ps = getComputedStyle(e, pseudo);
const c = ps.getPropertyValue("content");
return c !== "none" && c !== "normal" ? ps : null;
};

/** Tag, a naming attribute and up to two classes that don't look generated. */
const base = (e: Element, sorted: boolean) => {
Expand Down Expand Up @@ -186,6 +197,36 @@ function probe({ boxes, find, masked, props, perSpot, walk, root }: ProbeArgs) {
h: Math.round(r.height),
},
styles: props.map((p) => cs.getPropertyValue(p)),
up: (() => {
const tags: string[] = [];
for (let n = e.parentElement; n && tags.length < 2; n = n.parentElement)
tags.unshift(n.localName);
return tags.join(">");
})(),
pseudo: ["::before", "::after"].map((p) => {
const ps = generated(e, p);
return (
ps &&
Object.fromEntries(
[
"content",
"width",
"height",
"background-color",
"background-image",
"border-top-width",
"border-top-color",
"border-bottom-width",
"border-bottom-color",
"box-shadow",
].map((q) => [
q,
// A url() resolves against each side's origin.
ps.getPropertyValue(q).replaceAll(location.origin, ""),
]),
)
);
}),
};
};
const hit = (e: Element) => {
Expand Down Expand Up @@ -241,10 +282,8 @@ function probe({ boxes, find, masked, props, perSpot, walk, root }: ProbeArgs) {
snap[key] = { html: html(e), styles: props.map((p) => cs.getPropertyValue(p)) };
if (cs.display === "none") return;
for (const pseudo of ["::before", "::after"]) {
const ps = getComputedStyle(e, pseudo);
const content = ps.getPropertyValue("content");
if (content !== "none" && content !== "normal")
snap[key + pseudo] = { html: "", styles: props.map((p) => ps.getPropertyValue(p)) };
const ps = generated(e, pseudo);
if (ps) snap[key + pseudo] = { html: "", styles: props.map((p) => ps.getPropertyValue(p)) };
}
// Indexed among every child, as :nth-of-type counts, so the key works with querySelector.
const ofType = new Map<string, number>();
Expand Down Expand Up @@ -372,6 +411,32 @@ function element([l, r]: Pair, origins: Shot["origin"][]): ElementDiff {
};
}

/** `sel::before` / `sel::after` where the pseudo-element exists on one side only, or differs. */
function pseudos([l, r]: [Seen, Seen], origins: Shot["origin"][]): ElementDiff[] {
return ["::before", "::after"].flatMap((name, i) => {
const [p, q] = [l.pseudo[i], r.pseudo[i]];
if (!p && !q) return [];
const changed = Object.fromEntries(
p && q
? Object.keys(p)
.filter((k) => p[k] !== q[k])
.map((k): [string, [string, string]] => [k, [p[k]!, q[k]!]])
: [],
);
if (p && q && !Object.keys(changed).length) return [];
const host = element([p ? l : null, q ? r : null], origins);
return [
{
...host,
selector: host.selector + name,
changed,
text: "",
...(host.rightSelector ? { rightSelector: host.rightSelector + name } : {}),
},
];
});
}

/** Without text to compare, a selector naming both is only the same element if the box agrees. */
const same = (a: Seen, b: Seen) =>
!!(a.text || b.text) ||
Expand Down Expand Up @@ -482,7 +547,14 @@ export async function locate(
const out: ElementDiff[] = [];
for (const [a, b] of pairs.slice(0, PER_SPOT)) {
const el = element([a, b], [shots[0].origin, shots[1].origin]);
if (a && b && a.up !== b.up) el.reparented = true;
out.push(el);
if (a && b)
out.push(
...pseudos([a, b], [shots[0].origin, shots[1].origin]).map((p) =>
el.reparented ? { ...p, reparented: el.reparented } : p,
),
);
// ponytail: one level of cause; a deeper cascade search if agents ask for it
if (el.left && el.right && !Object.keys(el.changed).length && moved(el.left, el.right)) {
for (const [p, q] of [
Expand Down
Loading
Loading