Skip to content

Commit 73fb523

Browse files
test(css): build the elements structural selectors reach, and hold every corpus to the merge (#22394)
* test(css): build the elements structural selectors reach, and hold every corpus to the merge Place siblings for :nth-*() and build what :has() names, so a printer moving one of those selectors changes what an element computes. Minify every corpus with mergeDistantRules, which retires the merge tier's per-corpus duplicates. * test(css): count the siblings a structural selector already has, and build its `of S` part * test(css): file the Firefox reading of a six-digit `calc(100% / 3)`
1 parent f94df6f commit 73fb523

2 files changed

Lines changed: 191 additions & 70 deletions

File tree

‎test/helpers/syntaxEquivalence.js‎

Lines changed: 175 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -1313,7 +1313,40 @@ const compareStyles = async ({ pairs, types }) => {
13131313
return out;
13141314
};
13151315

1316-
/** @typedef {{ combinator: string, type: string, classes: string[], id: string, attributes: [string, string][] }} Compound */
1316+
/** @typedef {{ combinator: string, type: string, classes: string[], id: string, attributes: [string, string][], before: number, after: number, typed: boolean, counted: string, has: { combinator: string, chain: Compound[] }[] }} Compound */
1317+
1318+
/**
1319+
* The position among its siblings an `An+B` argument picks for an element to
1320+
* stand at: the second it matches, so `odd` is not also `:first-child`.
1321+
* @param {string} argument the argument, an `of S` part included
1322+
* @returns {number} the position, counted from 1, or 0 where none is built
1323+
*/
1324+
const nthPosition = (argument) => {
1325+
const text = argument
1326+
.replace(/\s+of\s[\s\S]*$/i, "")
1327+
.replace(/\s+/g, "")
1328+
.toLowerCase();
1329+
const spelled = text === "odd" ? "2n+1" : text === "even" ? "2n" : text;
1330+
const match = /^(?:([+-]?\d*)n)?([+-]?\d+)?$/.exec(spelled);
1331+
if (match === null || spelled === "") return 0;
1332+
const step =
1333+
match[1] === undefined
1334+
? 0
1335+
: match[1] === "" || match[1] === "+"
1336+
? 1
1337+
: match[1] === "-"
1338+
? -1
1339+
: Number(match[1]);
1340+
const offset = match[2] === undefined ? 0 : Number(match[2]);
1341+
let position = offset;
1342+
if (step > 0) {
1343+
const first =
1344+
offset >= 1 ? offset : offset + step * Math.ceil((1 - offset) / step);
1345+
position = first + step;
1346+
}
1347+
// A sibling list is built for it, so a far position is left unbuilt.
1348+
return position >= 1 && position <= 12 ? position : 0;
1349+
};
13171350

13181351
/**
13191352
* A selector as the compounds an element chain has to carry. A pseudo-class is
@@ -1336,8 +1369,35 @@ const compareStyles = async ({ pairs, types }) => {
13361369
type: "",
13371370
classes: [],
13381371
id: "",
1339-
attributes: []
1372+
attributes: [],
1373+
before: 0,
1374+
after: 0,
1375+
typed: false,
1376+
counted: "",
1377+
has: []
13401378
});
1379+
/**
1380+
* Takes in the first selector of a list when it is one compound, since the
1381+
* element has to match it too.
1382+
* @param {Compound} into the compound to take it into
1383+
* @param {string} list the selector list
1384+
* @returns {void}
1385+
*/
1386+
const absorb = (into, list) => {
1387+
const [first] = splitList(list);
1388+
const inner = parseSelector(first);
1389+
if (inner === null || inner.length !== 1) return;
1390+
const [one] = inner;
1391+
if (one.type !== "") into.type = one.type;
1392+
if (one.id !== "") into.id = one.id;
1393+
into.classes.push(...one.classes);
1394+
into.attributes.push(...one.attributes);
1395+
into.before = Math.max(into.before, one.before);
1396+
into.after = Math.max(into.after, one.after);
1397+
into.typed = into.typed || one.typed;
1398+
if (one.counted !== "") into.counted = one.counted;
1399+
into.has.push(...one.has);
1400+
};
13411401
/** @type {Compound[]} */
13421402
const chain = [];
13431403
let current = fresh("");
@@ -1386,18 +1446,34 @@ const compareStyles = async ({ pairs, types }) => {
13861446
else if (selector[at] === ")" && --depth === 0) break;
13871447
}
13881448
at++;
1389-
if (/^:(?:is|where)$/i.test(name[0])) {
1390-
const [first] = splitList(selector.slice(open + 1, at - 1));
1391-
const inner = parseSelector(first);
1392-
// One compound only: a chain inside cannot stand in this one's place.
1393-
if (inner !== null && inner.length === 1) {
1394-
const [one] = inner;
1395-
if (one.type !== "") current.type = one.type;
1396-
if (one.id !== "") current.id = one.id;
1397-
current.classes.push(...one.classes);
1398-
current.attributes.push(...one.attributes);
1449+
const argument = selector.slice(open + 1, at - 1);
1450+
const pseudo = name[0].toLowerCase();
1451+
if (/^:nth-(?:last-)?(?:child|of-type)$/.test(pseudo)) {
1452+
const position = nthPosition(argument) - 1;
1453+
if (pseudo.startsWith(":nth-last")) {
1454+
current.after = Math.max(current.after, position);
1455+
} else {
1456+
current.before = Math.max(current.before, position);
1457+
}
1458+
if (pseudo.endsWith("of-type")) current.typed = true;
1459+
// `of S` counts only siblings matching S, which it matches too.
1460+
const of = /\sof\s([\s\S]*)$/i.exec(argument);
1461+
if (of !== null) {
1462+
current.counted = of[1].trim();
1463+
absorb(current, of[1]);
1464+
}
1465+
} else if (pseudo === ":has") {
1466+
const [relative] = splitList(argument);
1467+
const leading = /^\s*([>+~]?)\s*/.exec(relative);
1468+
const combinator = leading === null ? "" : leading[1];
1469+
const inner = parseSelector(
1470+
relative.slice(leading === null ? 0 : leading[0].length)
1471+
);
1472+
if (inner !== null) {
1473+
current.has.push({ combinator: combinator || " ", chain: inner });
13991474
}
14001475
}
1476+
if (/^:(?:is|where)$/i.test(name[0])) absorb(current, argument);
14011477
}
14021478
} else {
14031479
const name = IDENTIFIER.exec(rest);
@@ -1438,6 +1514,85 @@ const compareStyles = async ({ pairs, types }) => {
14381514
return element;
14391515
};
14401516

1517+
/**
1518+
* Counts the siblings on one side of an element that its `:nth-*()` counts.
1519+
* @param {Element} element the element
1520+
* @param {Compound} compound what it carries
1521+
* @param {boolean} following whether the ones after it, not before
1522+
* @returns {number} how many there are
1523+
*/
1524+
const countSiblings = (element, compound, following) => {
1525+
let count = 0;
1526+
for (
1527+
let at = following
1528+
? element.nextElementSibling
1529+
: element.previousElementSibling;
1530+
at !== null;
1531+
at = following ? at.nextElementSibling : at.previousElementSibling
1532+
) {
1533+
if (compound.typed && at.localName !== element.localName) continue;
1534+
if (compound.counted !== "") {
1535+
try {
1536+
if (!at.matches(compound.counted)) continue;
1537+
} catch (_err) {
1538+
// A selector the engine will not read counts no sibling.
1539+
continue;
1540+
}
1541+
}
1542+
count++;
1543+
}
1544+
return count;
1545+
};
1546+
1547+
/**
1548+
* Builds a chain where its selector reaches its last element: each compound
1549+
* at the position among its siblings it names, holding what its `:has()` asks.
1550+
* @param {Document} doc the document to build in
1551+
* @param {Compound[]} chain the compounds
1552+
* @param {Element} anchor what the first compound joins
1553+
* @param {string} combinator how it joins it — a relative selector's own
1554+
* @returns {Element | null} the last element, or null where none was built
1555+
*/
1556+
const buildChain = (doc, chain, anchor, combinator) => {
1557+
/** @type {Element | null} */
1558+
let last = null;
1559+
for (const compound of chain) {
1560+
// A document has one of each, and the root already stands inside them.
1561+
if (DOCUMENT_ELEMENTS.has(compound.type)) {
1562+
if (last === null) continue;
1563+
break;
1564+
}
1565+
const element = build(doc, compound);
1566+
const joined = last === null ? combinator : compound.combinator;
1567+
const target = last === null ? anchor : last;
1568+
if (joined === "+" || joined === "~") target.after(element);
1569+
else target.append(element);
1570+
const sibling = () =>
1571+
build(doc, { ...compound, id: "", before: 0, after: 0, has: [] });
1572+
// In front of the pair `+` joins, which cannot be parted.
1573+
const front = joined === "+" ? target : element;
1574+
for (
1575+
let i = compound.before - countSiblings(element, compound, false);
1576+
i > 0;
1577+
i--
1578+
) {
1579+
front.before(sibling());
1580+
}
1581+
for (
1582+
let i = compound.after - countSiblings(element, compound, true);
1583+
i > 0;
1584+
i--
1585+
) {
1586+
element.after(sibling());
1587+
}
1588+
for (const held of compound.has) {
1589+
buildChain(doc, held.chain, element, held.combinator);
1590+
}
1591+
last = element;
1592+
}
1593+
return last;
1594+
};
1595+
14411596
/**
14421597
* @returns {Promise<HTMLIFrameElement>} a frame holding an empty standards-mode document
14431598
*/
@@ -1943,26 +2098,7 @@ const compareStyles = async ({ pairs, types }) => {
19432098
for (const selector of selectors) {
19442099
const chain = chains.get(selector);
19452100
if (chain === undefined) continue;
1946-
const inside = box();
1947-
/** @type {Element | null} */
1948-
let last = null;
1949-
for (const compound of chain) {
1950-
// A document has one of each, and the root already stands inside them.
1951-
if (DOCUMENT_ELEMENTS.has(compound.type)) {
1952-
if (last === null) continue;
1953-
break;
1954-
}
1955-
const element = build(doc, compound);
1956-
if (
1957-
last !== null &&
1958-
(compound.combinator === "+" || compound.combinator === "~")
1959-
) {
1960-
last.after(element);
1961-
} else {
1962-
(last === null ? inside : last).append(element);
1963-
}
1964-
last = element;
1965-
}
2101+
const last = buildChain(doc, chain, box(), "");
19662102
// The element the selector reaches; the ones on the way are reached by
19672103
// selectors of their own.
19682104
if (last !== null) {
@@ -1985,12 +2121,18 @@ const compareStyles = async ({ pairs, types }) => {
19852121
}
19862122
}
19872123
}
2124+
/** @type {Compound} */
19882125
const everything = {
19892126
combinator: "",
19902127
type: "",
19912128
classes: [...classes],
19922129
id: "",
1993-
attributes: [...attributes]
2130+
attributes: [...attributes],
2131+
before: 0,
2132+
after: 0,
2133+
typed: false,
2134+
counted: "",
2135+
has: []
19942136
};
19952137
for (const type of named) {
19962138
const outer = build(doc, { ...everything, type });

‎test/specCases/syntaxEquivalence.spectest.js‎

Lines changed: 16 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,7 @@ const FILED_CONFIG_HTML_DEFECTS = new Map([
207207

208208
const FILED_BENCHMARK_CSS_DEFECTS = new Map([
209209
["UIkit 3", "firefox only: not a printer defect — `rgba(255, 255, 255, 0.7)` prints as `#ffffffb3` (lightningcss writes the same), whose alpha is 179/255. Blink stores alpha in a byte either way, while Gecko keeps 0.702 and its `::placeholder` mix lands one byte from the source's 0.378"],
210+
["Radix Themes 3 (components)", "firefox only: `calc(100% / 3)` prints as `33.3333%`, six digits being calibrated on Blink's 1/64px layout; Gecko lays out in 1/60px, so a `translateX(100%)` over that width moves by 0.03px"],
210211
]);
211212

212213
const FILED_BENCHMARK_HTML_DEFECTS = new Map();
@@ -355,8 +356,9 @@ const cssomDirective = (source) => {
355356
};
356357

357358
const minifyCss = (source) => {
359+
// The merge too, which is off by default: every corpus is then held to it.
358360
/** @type {{ mode: string, [k: string]: EXPECTED_ANY }} */
359-
const options = { mode: "minify" };
361+
const options = { mode: "minify", mergeDistantRules: true };
360362
for (const name of cssomDirective(source)) options[name] = true;
361363
return /** @type {{ code: string }} */ (
362364
new CssSourceProcessor().process(source, options)
@@ -496,7 +498,20 @@ const STYLE_CONTROLS = new Map([
496498
["bad quoted url body", ['.a{--u:url("assets/)#fff")}', '.a{--u:url("assets/)#ffffff")}']],
497499
// A private-use character is a value's own, not a space the printer may write.
498500
["bad private use", [".a{--x:a\uE000b}", ".a{--x:a b}"]],
501+
// An element stands where a structural selector reaches it, so one reaching another position differs.
502+
["bad nth-child", ["li:nth-child(2n+1){color:red}", "li:first-child{color:red}"]],
503+
["bad nth-last-child", ["li:nth-last-child(2){color:red}", "li:nth-child(2){color:red}"]],
504+
["bad nth-of-type", ["p:nth-of-type(3){color:red}", "p:nth-of-type(2){color:red}"]],
505+
["bad has sibling", ["a:has(+ b){color:red}", "a:has(b){color:red}"]],
506+
["bad has child", ["a:has(> b){color:red}", "a:has(> i){color:red}"]],
507+
// The siblings a position counts are built around the ones already there, so what it declares is read.
508+
["bad nth-child of", ["li:nth-child(2 of .x){color:red}", "li:nth-child(2 of .x){color:blue}"]],
509+
["bad nth-child after", [".a+.b:nth-child(3){color:red}", ".a+.b:nth-child(3){color:blue}"]],
510+
["bad nth-child among", [".a~.b:nth-child(3){color:red}", ".a~.b:nth-child(3){color:blue}"]],
511+
["bad nth-of-type after", ["i+p:nth-of-type(2){color:red}", "i+p:nth-of-type(2){color:blue}"]],
499512
["good spelling", [".a{color:red;margin:0px}", ".a{color:#f00;margin:0}"]],
513+
["good nth spellings", ["li:nth-child(odd){color:red}li:nth-child(even){color:blue}", "li:nth-child(2n+1){color:red}li:nth-child(2n){color:blue}"]],
514+
["good has spacing", ["a:has( > b ){color:red}", "a:has(>b){color:red}"]],
500515
["good custom property spacing", [".a{--c:#e9ecef #e9ecef #dee2e6;--f:400 1rem / 1.5 \"Mona Sans\", sans-serif}", ".a{--c:#e9ecef#e9ecef#dee2e6;--f:400/**/1rem/ 1.5\"Mona Sans\",sans-serif}"]],
501516
// CSS Syntax 4.3.6: recovery ends a bad url at the next `)`.
502517
["good bad url", ['.a{--u:url(foo")#fff)}', '.a{--u:url(foo")#ffffff)}']],
@@ -2472,9 +2487,6 @@ const mergePair = (name, source) => {
24722487
return before === after ? null : { name, before, after };
24732488
};
24742489

2475-
// Read while jest collects, one test per stylesheet.
2476-
const mergeStylesheets = benchmarkStylesheets((source) => source);
2477-
24782490
describe("a distant merge keeps every element's cascade", () => {
24792491
/** @type {import("puppeteer-core").Browser} */
24802492
let browser;
@@ -2523,39 +2535,6 @@ describe("a distant merge keeps every element's cascade", () => {
25232535
FILE_TIMEOUT
25242536
);
25252537

2526-
it(
2527-
"over every configCases stylesheet the merge changes",
2528-
async () => {
2529-
/** @type {StylePair[]} */
2530-
const pairs = [];
2531-
for (const fixture of buildCorpus(CONFIG_CASES, ".css", (source) => source)) {
2532-
const pair = mergePair(fixture.name, fixture.raw);
2533-
if (pair !== null) pairs.push(pair);
2534-
}
2535-
// The merge has to have happened somewhere, or this proves nothing.
2536-
expect(pairs.length).toBeGreaterThan(0);
2537-
expect(await differing(pairs)).toEqual([]);
2538-
},
2539-
FILE_TIMEOUT
2540-
);
2541-
2542-
if (mergeStylesheets.length === 0) {
2543-
it(NO_BENCHMARK_CORPUS, () => {
2544-
// No-op: the stylesheets are installed by the benchmark.
2545-
});
2546-
}
2547-
2548-
for (const fixture of mergeStylesheets) {
2549-
it(
2550-
`over ${fixture.name}`,
2551-
async () => {
2552-
const pair = mergePair(fixture.name, fixture.raw);
2553-
if (pair === null) return;
2554-
expect(await differing([pair])).toEqual([]);
2555-
},
2556-
FILE_TIMEOUT
2557-
);
2558-
}
25592538
});
25602539

25612540
// A narrow viewport and a wide one, since media queries switch between them.

0 commit comments

Comments
 (0)