diff --git a/docs/output.md b/docs/output.md index adfacbe..9f93213 100644 --- a/docs/output.md +++ b/docs/output.md @@ -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: ``` diff --git a/skills/renderdiff/reference.md b/skills/renderdiff/reference.md index 49b30d6..14a29c3 100644 --- a/skills/renderdiff/reference.md +++ b/skills/renderdiff/reference.md @@ -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 diff --git a/src/cli.ts b/src/cli.ts index 3767064..a9618b2 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -569,6 +569,13 @@ async function probe(a: Args, loads: number): Promise { } } +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)); diff --git a/src/computed.ts b/src/computed.ts index 5c8f395..f88024d 100644 --- a/src/computed.ts +++ b/src/computed.ts @@ -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 = { top: 0, right: 90, bottom: 180, left: 270 }; +const FLIP: Record = { 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); @@ -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) && diff --git a/tests/unit/cli-args.test.ts b/tests/unit/cli-args.test.ts index a321277..e8054b0 100644 --- a/tests/unit/cli-args.test.ts +++ b/tests/unit/cli-args.test.ts @@ -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; diff --git a/tests/unit/computed.test.ts b/tests/unit/computed.test.ts index d1f1d4a..b89eaa8 100644 --- a/tests/unit/computed.test.ts +++ b/tests/unit/computed.test.ts @@ -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("", { "background-image": l }) }, + { body: el("", { "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, right: Record) => + diffSnapshots( + { "body > span": el("", { position: "absolute", ...left }) }, + { "body > span": el("", { 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): Snapshot => ({ + "body > a": el("", { position: "absolute", clip: zero, "clip-path": path }), + "body > a:focus-visible": el("", { 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"] }, diff --git a/tests/visual/computed.test.ts b/tests/visual/computed.test.ts index f12483e..4c5a23c 100644 --- a/tests/visual/computed.test.ts +++ b/tests/visual/computed.test.ts @@ -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 = `
averyveryverylongidentifierwithoutbreaksx
` + `hidden

Some text.

`; @@ -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"], ]); }); @@ -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 = `

a

b

c

d

`; + 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"]]); +});