diff --git a/docs/output.md b/docs/output.md index 39198de..eaa319a 100644 --- a/docs/output.md +++ b/docs/output.md @@ -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 @@ -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: [] }` | @@ -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 @@ -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). diff --git a/skills/renderdiff/reference.md b/skills/renderdiff/reference.md index 41ad42e..0ff2bfc 100644 --- a/skills/renderdiff/reference.md +++ b/skills/renderdiff/reference.md @@ -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. | @@ -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 diff --git a/src/compare.ts b/src/compare.ts index aa4783a..7d8030e 100644 --- a/src/compare.ts +++ b/src/compare.ts @@ -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. */ @@ -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"; @@ -150,7 +161,7 @@ export async function compare(left: Shot, right: Shot): Promise { 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 : [ @@ -262,9 +273,16 @@ 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); @@ -272,7 +290,7 @@ function regions(out: Buffer, stride: number, w: number, h: number): Region[] { 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)]!++; } } @@ -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); @@ -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", diff --git a/src/format.ts b/src/format.ts index e0fff5a..43cdec8 100644 --- a/src/format.ts +++ b/src/format.ts @@ -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. */ @@ -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 @@ -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("; "); diff --git a/src/locate.ts b/src/locate.ts index 042e4ce..5c89c66 100644 --- a/src/locate.ts +++ b/src/locate.ts @@ -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; @@ -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 | null)[]; } interface Hit extends Seen { @@ -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) => { @@ -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) => { @@ -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(); @@ -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) || @@ -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 [ diff --git a/src/report.ts b/src/report.ts index f2a5bb8..ad81456 100644 --- a/src/report.ts +++ b/src/report.ts @@ -5,7 +5,16 @@ import { fmtComputed, groupFindings, type ComputedDiff, type Finding } from "./c import type { Band, Box, Region, TextDiff } from "./compare.ts"; import { CONTEXT_OPTIONS, name, type ResolvedConfig, type Sides } from "./config.ts"; import type { ElementDiff } from "./locate.ts"; -import { floor4, fmtBand, fmtElements, fmtFailed, fmtRegion, pct, signed } from "./format.ts"; +import { + floor4, + fmtBand, + fmtElements, + fmtFailed, + fmtLine, + fmtRegion, + pct, + signed, +} from "./format.ts"; interface BaseResult { /** The route: `/a`, or `/a::/b` for a pair. */ @@ -224,7 +233,7 @@ function findings(r: ComparedResult): string { .slice(0, LIST_CAP) .map( (g) => - `
  • ${fmtRegion(g)} — ${g.pixels.toLocaleString("en-US")} px${dom(g.elements)}
  • `, + `
  • ${fmtRegion(g)} — ${g.pixels.toLocaleString("en-US")} px${g.line ? `, ${fmtLine(g.line)}` : ""}${dom(g.elements)}
  • `, ) .join("")}`, ); diff --git a/src/run.ts b/src/run.ts index ee222fd..e9e6e77 100644 --- a/src/run.ts +++ b/src/run.ts @@ -7,7 +7,7 @@ import { chromium, errors, type Browser, type Page } from "playwright"; import { applyAccepted, readAccepted, updateAccepted } from "./accept.ts"; import { CACHE_DIR, cacheFile, replayable, REPLAY_TTL, saveRecording, shotId } from "./cache.ts"; import { cancelUnstable, capture, HookError, prepare, type Shot } from "./capture.ts"; -import { compare, crops, type Band } from "./compare.ts"; +import { compare, crops, type Band, type Region } from "./compare.ts"; import { diffSnapshots, fmtComputed } from "./computed.ts"; import { locate, snapshot, type ElementDiff } from "./locate.ts"; import { @@ -20,7 +20,7 @@ import { type ResolvedConfig, type Route, } from "./config.ts"; -import { fmtBand, fmtElements, fmtFailed, fmtRegion, pct, signed } from "./format.ts"; +import { fmtBand, fmtElements, fmtFailed, fmtLine, fmtRegion, pct, signed } from "./format.ts"; import { stats, writeReport, @@ -396,6 +396,7 @@ export async function run({ regions.length ? `${regions.length} region${regions.length > 1 ? "s" : ""}, largest ${fmtRegion(regions[0]!)}` : "", + ...more(regions.flatMap((g) => (g.line ? [fmtLine(g.line)] : []))), ...(bands ?? []).map((b) => `band ${fmtBand(b)}`), alignedScore !== null ? `aligned ${pct(alignedScore)}` : "", bands === null ? "rows too different to align" : "", @@ -750,6 +751,10 @@ export function compact( return out.join("\n"); } +/** The first three, and how many more there are. */ +const more = (lines: string[]) => + lines.length > 3 ? [...lines.slice(0, 3), `(+${lines.length - 3} more)`] : lines; + /** One compact row for comparisons that agree on everything but score, regions and unstable px. */ function row(g: ComparedResult[]): string { const [r] = g as [ComparedResult]; @@ -757,7 +762,15 @@ function row(g: ComparedResult[]): string { const [lo, hi] = [Math.min(...ns), Math.max(...ns)]; return lo === hi ? f(lo) : `${f(lo)}–${f(hi)}`; }; - const regions = g.map((x) => x.regions.length); + const drawn = (c: Region) => c.line && !c.accepted; + const regions = g.map((x) => x.regions.filter((c) => !drawn(c)).length); + const lined = g.find((x) => x.regions.some(drawn)) ?? r; + const ys = (x: ComparedResult) => + x.regions + .filter(drawn) + .map((c) => c.line!.y) + .join(); + const approx = new Set(g.map(ys)).size > 1; const accepted = g.map( (x) => [...(x.bands ?? []), ...x.regions].filter((c) => c.accepted).length, ); @@ -775,6 +788,7 @@ function row(g: ComparedResult[]): string { r.bands === null ? "unaligned" : "", ...(r.bands ?? []).map((b) => `band ${b.side === "left" ? "+" : "-"}${b.h}${y(b)}`), r.alignedScore !== null ? `aligned ${pct(r.alignedScore)}` : "", + ...more(lined.regions.flatMap((c) => (drawn(c) ? [fmtLine(c.line!, approx)] : []))), Math.max(...regions) ? `${span(regions, String)} reg` : "", unstable ? `unstable ${unstable.toLocaleString("en-US")}px` : "", Math.max(...accepted) ? `${span(accepted, String)} accepted` : "", diff --git a/tests/fixtures/pages/README.md b/tests/fixtures/pages/README.md index b47039e..48dc006 100644 --- a/tests/fixtures/pages/README.md +++ b/tests/fixtures/pages/README.md @@ -12,11 +12,12 @@ Three groups: `inline-block-vs-flex`. The two sides are visually identical and built with different CSS. These must score ≈100%. They are the corpus's central claim: the score tracks pixels, not markup, so a CSS refactor that changed nothing visible reads as "nothing changed". -- **Controls** — `shifted`, `taller`, `color`, `tint`, `nav`, `margin`. Deliberately different. These must score low. +- **Controls** — `shifted`, `taller`, `color`, `tint`, `nav`, `margin`, `divider`. Deliberately different. These must score low. A corpus of only passing cases proves nothing; without these, a tool that returned 100% unconditionally would pass the suite. They also pin the diff regions (`color`), the row alignment (`taller`, `nav`, and `shifted`, which has no band), the text diff (`nav`) and the - elements each change names (`margin`, `color`, `nav`). + 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`. One per defence in `src/capture.ts` / `src/config.ts`. diff --git a/tests/fixtures/pages/divider/left.html b/tests/fixtures/pages/divider/left.html new file mode 100644 index 0000000..12861be --- /dev/null +++ b/tests/fixtures/pages/divider/left.html @@ -0,0 +1,29 @@ + + + + +Divider control + + + + +
    +

    Divider control

    +

    This pair is deliberately different. A one-pixel divider drawn by a pseudo-element is gone on the left, and a card moved into a new wrapper.

    +
    +
    +

    Notes

    +

    The pixels say a thin line vanished and a card moved. The element list should say which pseudo-element went, and that the card's pairing crossed a structure change.

    +
    +
    Card
    +
    + + diff --git a/tests/fixtures/pages/divider/right.html b/tests/fixtures/pages/divider/right.html new file mode 100644 index 0000000..5cdc399 --- /dev/null +++ b/tests/fixtures/pages/divider/right.html @@ -0,0 +1,29 @@ + + + + +Divider control + + + + +
    +

    Divider control

    +

    This pair is deliberately different. A one-pixel divider drawn by a pseudo-element is gone on the left, and a card moved into a new wrapper.

    +
    +
    +

    Notes

    +

    The pixels say a thin line vanished and a card moved. The element list should say which pseudo-element went, and that the card's pairing crossed a structure change.

    +
    +
    Card
    +
    + + diff --git a/tests/helpers/corpus.ts b/tests/helpers/corpus.ts index 3452b4c..640866b 100644 --- a/tests/helpers/corpus.ts +++ b/tests/helpers/corpus.ts @@ -21,7 +21,7 @@ export const EQUIVALENCE = [ ] as const; /** Deliberately different. Must score low — otherwise the suite proves nothing. */ -export const CONTROLS = ["shifted", "taller", "color", "tint", "nav", "margin"] as const; +export const CONTROLS = ["shifted", "taller", "color", "tint", "nav", "margin", "divider"] as const; /** One per defence in src/capture.ts and src/config.ts. */ export const GUARDRAILS = [ diff --git a/tests/helpers/parse.ts b/tests/helpers/parse.ts index 444489f..62bb25d 100644 --- a/tests/helpers/parse.ts +++ b/tests/helpers/parse.ts @@ -268,7 +268,7 @@ export interface ReportCard { /** Null when the card shows no aligned score. */ alignedScore: number | null; /** The listed regions (the card caps the list), each with the elements line it shows, or null. */ - regions: (Box & { pixels: number; dom: string | null })[]; + regions: (Box & { pixels: number; line: string | null; dom: string | null })[]; /** The listed bands: `+24px at y=196 (left)` and the elements line, or null. */ bands: { text: string; dom: string | null }[]; /** The text-diff lines listed on the card: left-only and right-only. */ @@ -349,7 +349,7 @@ export function parseReport(html: string): Report { alignedScore: aligned ? Number(aligned[1]) / 100 : null, regions: [ ...card.matchAll( - /
  • (\d+)×(\d+) at \((\d+),(\d+)\) — ([\d,]+) px(?: — (.*?)<\/span>)?<\/li>/g, + /
  • (\d+)×(\d+) at \((\d+),(\d+)\) — ([\d,]+) px(?:, (line [^<]*))?(?: — (.*?)<\/span>)?<\/li>/g, ), ].map((m) => ({ w: Number(m[1]), @@ -357,7 +357,8 @@ export function parseReport(html: string): Report { x: Number(m[3]), y: Number(m[4]), pixels: num(m[5]!), - dom: m[6] ? unesc(m[6]) : null, + line: m[6] ?? null, + dom: m[7] ? unesc(m[7]) : null, })), bands: [ ...card.matchAll(/
  • band ([^<]*)(?: — (.*?)<\/span>)?<\/li>/g), diff --git a/tests/unit/compare.test.ts b/tests/unit/compare.test.ts new file mode 100644 index 0000000..7150a69 --- /dev/null +++ b/tests/unit/compare.test.ts @@ -0,0 +1,59 @@ +/** Thin horizontal regions come out labelled as lines, with the side that draws them. */ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import sharp from "sharp"; +import { compare } from "../../src/compare.ts"; +import { fmtLine } from "../../src/format.ts"; + +const W = 400, + H = 200; +const png = (paint: (px: Buffer) => void) => { + const px = Buffer.alloc(W * H * 4, 255); + paint(px); + return sharp(px, { raw: { width: W, height: H, channels: 4 } }) + .png() + .toBuffer(); +}; +const rect = (px: Buffer, x: number, y: number, w: number, h: number) => { + for (let j = y; j < y + h; j++) + for (let i = x; i < x + w; i++) px.fill(0x33, (j * W + i) * 4, (j * W + i) * 4 + 3); +}; +const shot = async (paint: (px: Buffer) => void) => ({ + png: await png(paint), + unstable: null, + blank: null, + text: [], + origin: { x: 0, y: 0 }, + failed: [], +}); + +test("a lost 1px divider is a line drawn by the right side", async () => { + const d = await compare(await shot(() => {}), await shot((px) => rect(px, 0, 100, W, 1))); + assert.deepEqual(d.regions[0]!.line, { y: 100, h: 1, side: "right" }); + assert.equal(fmtLine(d.regions[0]!.line!), "line -1px@y100"); +}); + +test("a 2px line only the left draws is +2px", async () => { + const d = await compare(await shot((px) => rect(px, 20, 47, 360, 2)), await shot(() => {})); + assert.deepEqual(d.regions[0]!.line, { y: 47, h: 2, side: "left" }); +}); + +test("a box is not a line", async () => { + const d = await compare(await shot(() => {}), await shot((px) => rect(px, 40, 40, 40, 40))); + assert.equal(d.regions.length, 1); + assert.equal(d.regions[0]!.line, undefined); +}); + +test("a divider lost above a dark footer is still the right side's", async () => { + const footer = (px: Buffer) => { + for (let i = 101 * W * 4; i < px.length; i += 4) px.fill(0x60, i, i + 3); + }; + const d = await compare( + await shot(footer), + await shot((px) => { + footer(px); + rect(px, 0, 100, W, 1); + }), + ); + assert.deepEqual(d.regions[0]!.line, { y: 100, h: 1, side: "right" }); +}); diff --git a/tests/visual/controls.test.ts b/tests/visual/controls.test.ts index c1c2532..0ce1b54 100644 --- a/tests/visual/controls.test.ts +++ b/tests/visual/controls.test.ts @@ -23,6 +23,7 @@ import fs from "node:fs"; import path from "node:path"; import sharp from "sharp"; import { after, before, test } from "node:test"; +import { fmtLine } from "../../src/format.ts"; import { CONTROLS, toPath } from "../helpers/corpus.ts"; import { cleanupTempDirs, @@ -141,7 +142,7 @@ for (const width of WIDTHS) { assert.deepEqual(r.text, { added: [], removed: [] }, "a recolour changes no text"); const listed = card(report, "/color", width).regions; assert.deepEqual( - listed.map(({ dom, ...b }) => b), + listed.map(({ dom, line, ...b }) => b), [{ x: g.x, y: g.y, w: g.w, h: g.h, pixels: g.pixels }], "the card lists the same single region", ); @@ -189,7 +190,7 @@ for (const width of WIDTHS) { }); } -for (const route of ["/color", "/nav"]) { +for (const route of ["/color", "/nav", "/divider"]) { for (const width of WIDTHS) { test(`results.json agrees with the report card for ${route} @${width}`, () => { const r = result(results(run.outDir), route, width); @@ -202,7 +203,9 @@ for (const route of ["/color", "/nav"]) { assert.equal(r.widthDelta, c.widthDelta); assert.equal(r.unstablePixels, c.unstablePixels); assert.deepEqual( - r.regions.slice(0, 5).map(({ elements, hash, ...g }) => g), + r.regions + .slice(0, 5) + .map(({ elements, hash, line, ...g }) => ({ ...g, line: line ? fmtLine(line) : null })), c.regions.map(({ dom, ...g }) => g), ); assert.deepEqual(r.text, { added: c.added, removed: c.removed }); @@ -257,6 +260,29 @@ for (const width of WIDTHS) { }); } +for (const width of WIDTHS) { + test(`divider @${width} names the lost ::before line, and the card's re-parented pairing`, () => { + const r = result(results(run.outDir), "/divider", width); + const line = r.regions.find((g) => g.line); + assert.deepEqual(line && [line.line!.side, line.line!.h], ["right", 1], context(run)); + const named = r.regions.flatMap((g) => g.elements ?? []); + const rule = named.find((e) => e.selector.endsWith(".rule::before")); + assert.equal(rule?.side, "right", JSON.stringify(named)); + const card = named.find((e) => e.selector.endsWith(".card")); + assert.equal(card?.reparented, true, JSON.stringify(named)); + const border = named.find((e) => e.selector.endsWith(".card::after")); + assert.deepEqual(border?.changed["border-top-width"], ["0px", "1px"], JSON.stringify(named)); + assert.equal(border?.reparented, true); + const rows = parseSummary(run.stdout).routes.get("/divider")!.rows; + assert.ok( + rows.some((x) => /line -1px@y/.test(x.text)), + context(run), + ); + assert.match(run.stdout, /-div\.rule::before/, context(run)); + assert.match(run.stdout, /\(re-parented\)/, context(run)); + }); +} + test("a named element's selector is unique on both sides, so --selector takes it", async () => { const [blog] = result(results(run.outDir), "/margin", 1440) .regions.flatMap((g) => g.elements ?? [])