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
9 changes: 9 additions & 0 deletions docs/output.md
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,15 @@ changed:
- Paint: `background-color`, `background-image`, `box-shadow`, `opacity`, `transform`,
`visibility`, `clip`, `clip-path`, `mask`, `content`.

A `linear-gradient` (or `repeating-`) in `background-image` compares by what it paints: a
side keyword and its angle (`to right`, `90deg`), an angle past 180° and the reversed stops,
a corner and its opposite with reversed stops, and default `0%`/`100%` positions are equal.
Stops in px, `calc()`, colour hints and `increasing`, `decreasing` or `longer` hue still
compare as written. A `clip` or `clip-path` change on an element fully clipped on both sides
is no finding; its other properties still are. Fully clipped is a `%` `clip-path: inset()`
with top + bottom ≥ 100% or left + right ≥ 100%, or a zero-area `clip` rect on an
absolutely or fixed positioned element.

The summary gets one block, after the rows:

```
Expand Down
8 changes: 5 additions & 3 deletions skills/renderdiff/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,10 +214,12 @@ computed: 2 findings; dom identical on 2 of 3 route(s), differs /pricing (1), so
whose height changed (unless set in px). Shown on one side and `display: none` on the other
is one `display` finding. A pseudo-element one side no longer generates is `content` against
`none`. An `auto` margin reads as `auto`, not the px it resolved to, which varies with
layout.
layout. `clip`/`clip-path` changes on an element fully clipped on both sides (sr-only) are
dropped. Linear gradients compare by what they paint (`to right` = `90deg`, reversed stops).
- A finding on a clean route is a change you can't see in this state: a hidden element
(closed menu), another breakpoint, hover on non-interactive elements, open menus. Decide it; a
`before` hook can open the state.
(closed menu), another breakpoint, hover on non-interactive elements, open menus. Or it is
notation that renders the same but isn't normalized (a radial gradient, px stops, a colour
hint). Decide it; a `before` hook can open the state.
- Fails per shot (reported, pixels stand) past 15s or 50,000 elements. Not walked: SVG
internals, shadow DOM, iframes, masked and `display: none` subtrees.
- `rules: N changed groups, X never matched, Y matched on some shots`: style rules only one
Expand Down
7 changes: 7 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,13 @@ async function probe(a: Args, loads: number): Promise<never> {
}
}

if (
["report", "merge", "pack"].includes(process.argv[2]!) &&
process.argv.slice(3).some((t) => t === "--help" || t === "-h")
) {
console.log(HELP.trimEnd());
process.exit(0);
}
if (process.argv[2] === "report") await report(process.argv.slice(3));
if (process.argv[2] === "merge" || process.argv[2] === "pack")
await outCommand(process.argv[2], process.argv.slice(3));
Expand Down
100 changes: 98 additions & 2 deletions src/computed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,98 @@ const INHERITED = new Set([
"visibility",
]);
const DISPLAY = FIELDS.indexOf("display");
const POSITION = FIELDS.indexOf("position");
const CLIP = FIELDS.indexOf("clip");
const CLIP_PATH = FIELDS.indexOf("clip-path");

const splitTop = (s: string) => {
const out: string[] = [];
let depth = 0;
let start = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] === "(") depth++;
else if (s[i] === ")") depth--;
else if (s[i] === "," && !depth) {
out.push(s.slice(start, i).trim());
start = i + 1;
}
}
return [...out, s.slice(start).trim()];
};

const SIDES: Record<string, number> = { top: 0, right: 90, bottom: 180, left: 270 };
const FLIP: Record<string, string> = { top: "bottom", bottom: "top", left: "right", right: "left" };

/**
* One linear gradient layer as `angle, color pos%, …` pointing into [0, 180), so equal
* gradients written another way compare equal; null when it can't be read exactly.
*/
function canonLinear(layer: string): string | null {
const m = /^((?:repeating-)?linear-gradient)\((.*)\)$/.exec(layer);
if (!m) return null;
const args = splitTop(m[2]!);
const dir = /^(?:to ([a-z ]+?)|(-?[\d.]+(?:e[+-]?\d+)?)deg)? ?(in [a-z -]+)?$/.exec(args[0]!);
if (dir && (dir[1] || dir[2] || dir[3])) args.shift();
const interp = dir?.[3] ?? "";
if (/increasing|decreasing|longer/.test(interp)) return null;
const words = dir?.[1]?.split(" ") ?? [];
let angle = dir?.[2] ? Number(dir[2]) : words.length === 1 ? SIDES[words[0]!] : 180;
if (angle === undefined || words.length > 2 || !words.every((w) => w in FLIP)) return null;
angle = ((angle % 360) + 360) % 360;
const stops: { color: string; pos?: number }[] = [];
for (const a of args) {
const s = /^(.*?)(?: (-?[\d.]+)(%|px))?$/.exec(a)!;
let bare = s[1]!;
while (/\([^()]*\)/.test(bare)) bare = bare.replace(/\([^()]*\)/g, "");
// A colour has no space outside parentheses nor ends in a number, so either is a position we can't flip.
if (
!/[a-z]/i.test(bare) ||
bare.includes(" ") ||
/\d[a-z%]*$/i.test(bare) ||
s[1]!.includes("calc(")
)
return null;
if (s[3] === "px" && Number(s[2]) !== 0) return null;
stops.push({ color: s[1]!, ...(s[2] === undefined ? {} : { pos: Number(s[2]) }) });
}
if (stops.length < 2) return null;
stops[0]!.pos ??= 0;
stops.at(-1)!.pos ??= 100;
let max = -Infinity;
for (const s of stops) if (s.pos !== undefined) s.pos = max = Math.max(max, s.pos);
// A zero-length repeat paints one colour that depends on stop order.
if (stops[0]!.pos === stops.at(-1)!.pos) return null;
let corner = words.length === 2 ? words : null;
if (corner ? corner.includes("bottom") : angle >= 180) {
if (corner) corner = corner.map((w) => FLIP[w]!);
else angle -= 180;
stops.reverse();
for (const s of stops) if (s.pos !== undefined) s.pos = 100 - s.pos;
}
const head = corner ? `to ${corner.join(" ")}` : `${angle}deg`;
return `${m[1]}(${[head, interp].filter(Boolean).join(" ")}, ${stops.map((s) => (s.pos === undefined ? s.color : `${s.color} ${+s.pos.toFixed(4)}%`)).join(", ")})`;
}

/** Same `background-image` once each linear gradient layer is canonical; other layers as written. */
const sameImage = (a: string, b: string) => {
const canon = (v: string) => splitTop(v).map((l) => canonLinear(l) ?? l);
const [x, y] = [canon(a), canon(b)];
return x.length === y.length && x.every((l, i) => l === y[i]);
};

/** Paints nothing: a zero-area `clip` rect where clip applies, or a `%` `clip-path: inset()` that meets itself. */
const fullClip = (styles: string[]) => {
const r = /^rect\((-?[\d.]+)px, (-?[\d.]+)px, (-?[\d.]+)px, (-?[\d.]+)px\)$/
.exec(styles[CLIP]!)
?.slice(1)
.map(Number);
if (r && /^(absolute|fixed)$/.test(styles[POSITION]!) && (r[2]! <= r[0]! || r[1]! <= r[3]!))
return true;
const ins = /^inset\(([\d.% ]+)\)$/.exec(styles[CLIP_PATH]!)?.[1]!.split(" ");
if (!ins?.every((v) => v.endsWith("%"))) return false;
const [t, rt = t, b = t, l = rt] = ins.map(parseFloat) as [number, number?, number?, number?];
return t + b >= 100 || rt + l >= 100;
};

const PSEUDO = /::(before|after)$/;
const isPseudo = (key: string) => PSEUDO.test(key);
Expand Down Expand Up @@ -210,8 +302,12 @@ export function diffSnapshots(
continue;
}
FIELDS.forEach((prop, i) => {
if (l.styles[i] !== r.styles[i])
changes.push({ key, prop, values: [l.styles[i]!, r.styles[i]!] });
const [a, b] = [l.styles[i]!, r.styles[i]!];
if (a === b) return;
if (prop === "background-image" && sameImage(a, b)) return;
// Skipped here, not later, so a resting change dropped can't hide a state's real one.
if ((i === CLIP || i === CLIP_PATH) && fullClip(l.styles) && fullClip(r.styles)) return;
changes.push({ key, prop, values: [a, b] });
});
} else if (
isPseudo(key) &&
Expand Down
19 changes: 19 additions & 0 deletions tests/unit/cli-args.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,25 @@ describe("help and version", () => {
assert.equal(short.stdout, long.stdout);
});

test("each subcommand takes --help or -h anywhere and prints the help; other flags still fail", async () => {
const long = await runCli(["--help"], { noOut: true });
const runs = await Promise.all(
[
["report", "--help"],
["merge", "a", "b", "-h"],
["pack", "-h", "out"],
["probe", "--help"],
["report", "out", "--nope"],
].map((argv) => runCli(argv, { noOut: true })),
);
for (const r of runs.slice(0, -1)) {
assert.equal(r.code, 0, r.stderr);
assert.equal(r.stdout, long.stdout);
}
assert.equal(runs.at(-1)!.code, 2);
assert.match(runs.at(-1)!.stderr, /unexpected argument: --nope/);
});

test("--version prints the package version", async () => {
const pkg = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, "package.json"), "utf8")) as {
version: string;
Expand Down
93 changes: 93 additions & 0 deletions tests/unit/computed.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,99 @@ describe("diffSnapshots", () => {
]);
});

test("a background-image written another way is no change; a different gradient is", () => {
const bg = (l: string, r: string) =>
diffSnapshots(
{ body: el("<body>", { "background-image": l }) },
{ body: el("<body>", { "background-image": r }) },
).changes.length;
const [A, B] = ["rgb(255, 0, 0)", "rgb(0, 0, 255)"];
const same = [
[`linear-gradient(to top, ${A}, ${B} 90%)`, `linear-gradient(${B} 10%, ${A})`],
[`linear-gradient(to right, ${A}, ${B})`, `linear-gradient(90deg, ${A}, ${B})`],
[`linear-gradient(0deg, ${B}, ${A})`, `linear-gradient(${A}, ${B})`],
[`linear-gradient(-90deg, ${A}, ${B})`, `linear-gradient(270deg, ${A} 0px, ${B} 100%)`],
[`linear-gradient(to right top, ${A}, ${B})`, `linear-gradient(to left bottom, ${B}, ${A})`],
[
`repeating-linear-gradient(to top, ${A}, ${B} 20%)`,
`repeating-linear-gradient(${B} 80%, ${A})`,
],
[
`url("a.png"), linear-gradient(to left, ${A}, ${B})`,
`url("a.png"), linear-gradient(90deg, ${B}, ${A})`,
],
];
for (const [l, r] of same) assert.equal(bg(l!, r!), 0, `${l} vs ${r}`);
const differ = [
[`linear-gradient(${A}, ${B})`, `linear-gradient(${A}, rgb(0, 128, 0))`],
[`linear-gradient(${A}, ${B} 90%)`, `linear-gradient(${A}, ${B} 80%)`],
[`linear-gradient(45deg, ${A}, ${B})`, `linear-gradient(90deg, ${A}, ${B})`],
[`linear-gradient(to right top, ${A}, ${B})`, `linear-gradient(45deg, ${A}, ${B})`],
[`linear-gradient(${A}, 30%, ${B})`, `linear-gradient(0deg, ${B}, 70%, ${A})`],
[`linear-gradient(${A} 20px, ${B})`, `linear-gradient(0deg, ${B}, ${A} calc(100% - 20px))`],
[
`linear-gradient(to right, ${A}, ${B}), linear-gradient(${A}, ${B})`,
`linear-gradient(90deg, ${A}, ${B}), linear-gradient(${B}, ${A})`,
],
[
`linear-gradient(in oklch longer hue, ${A}, ${A})`,
`linear-gradient(to top in oklch longer hue, ${A}, ${A})`,
],
[
`repeating-linear-gradient(rgb(0, 0, 0) 50%, rgb(0, 255, 0) 50%)`,
`repeating-linear-gradient(to top, rgb(0, 255, 0) 50%, rgb(0, 0, 0) 50%)`,
],
[`linear-gradient(1e-05deg, ${A}, ${B})`, `linear-gradient(1e-05deg, ${A} 50%, ${B})`],
];
for (const [l, r] of differ) assert.equal(bg(l!, r!), 1, `${l} vs ${r}`);
});

test("clip and clip-path changes on a box fully clipped on both sides are dropped, not other props", () => {
const sr = (left: Record<string, string>, right: Record<string, string>) =>
diffSnapshots(
{ "body > span": el("<span>", { position: "absolute", ...left }) },
{ "body > span": el("<span>", { position: "absolute", ...right }) },
).changes.map((c) => c.prop);
const zero = "rect(0px, 0px, 0px, 0px)";
assert.deepEqual(
sr(
{ clip: "auto", "clip-path": "inset(50%)", color: "red" },
{ clip: zero, "clip-path": "inset(50%)", color: "blue" },
),
["color"],
);
assert.deepEqual(
sr({ clip: "auto", "clip-path": "inset(50%)" }, { clip: zero, "clip-path": "none" }),
[],
);
assert.deepEqual(
sr({ clip: "auto", "clip-path": "inset(50%)" }, { clip: "auto", "clip-path": "none" }),
["clip-path"],
);
assert.deepEqual(
sr(
{ clip: zero, "clip-path": "none", position: "static" },
{ clip: "auto", "clip-path": "inset(50%)", position: "static" },
),
["clip", "clip-path"],
);
});

test("a skip link that no longer shows on focus is kept though its resting clip change is dropped", () => {
const zero = "rect(0px, 0px, 0px, 0px)";
const link = (path: string, focused: Record<string, string>): Snapshot => ({
"body > a": el("<a>", { position: "absolute", clip: zero, "clip-path": path }),
"body > a:focus-visible": el("<a>", { position: "absolute", ...focused }),
});
const d = diffSnapshots(
link("inset(50%)", { clip: "auto", "clip-path": "inset(50%)" }),
link("none", { clip: "auto", "clip-path": "none" }),
);
assert.deepEqual(d.changes, [
{ key: "body > a:focus-visible", prop: "clip-path", values: ["inset(50%)", "none"] },
]);
});

test("a descendant that changed differently from its parent is kept", () => {
const changes = collapseInherited([
{ key: "body", prop: "color", values: ["red", "blue"] },
Expand Down
15 changes: 12 additions & 3 deletions tests/visual/computed.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ test("past 500 links the rest are counted, and the page is left resting", async
await p.close();
});

test("a lint autofix swapping wrapping or clipping keywords is a finding, not inherited down", async () => {
test("a lint autofix swapping wrapping keywords is a finding, not inherited down; a hidden box's clipping isn't", async () => {
const body =
`<div style="width:120px"><code>averyveryverylongidentifierwithoutbreaks<b>x</b></code></div>` +
`<span class="h">hidden</span><p>Some text.</p>`;
Expand All @@ -206,8 +206,6 @@ test("a lint autofix swapping wrapping or clipping keywords is a finding, not in
assert.deepEqual(changed(d), [
["body > div > code", "word-break"],
["body > div > code", "overflow-wrap"],
["body > span.h", "clip"],
["body > span.h", "clip-path"],
]);
});

Expand All @@ -220,3 +218,14 @@ test("hiding for the text read leaves each style attribute as it was", async ()
assert.equal(await p.evaluate(() => document.body.innerHTML), body);
await p.close();
});

test("gradients Chrome serializes differently but that paint the same are no finding", async () => {
const body = `<p class="a">a</p><p class="b">b</p><p class="c">c</p><p class="d">d</p>`;
const { d } = await diff(body, body, [
".a { background: linear-gradient(to top, #f00, #00f 90%) } .b { background: linear-gradient(to right, red, blue) }" +
" .c { background: linear-gradient(0deg, blue, red) } .d { background: linear-gradient(to right top, red, blue) }",
".a { background: linear-gradient(#00f 10%, #f00) } .b { background: linear-gradient(90deg, red, blue) }" +
" .c { background: linear-gradient(red, blue) } .d { background: linear-gradient(45deg, red, blue) }",
]);
assert.deepEqual(changed(d), [["body > p.d", "background-image"]]);
});
Loading