Skip to content

Commit f9ed9d1

Browse files
fix(css): fold no block of a layer over a streamed block of that layer (#22044)
* test(css): hold the printers to real framework stylesheets The equivalence check ran over configCases and test/wpt, both written to exercise a rule rather than to ship. The tool comparisons already install thirty framework stylesheets and two documents, so this reads them back as a corpus of their own and holds both printers to what Chrome makes of them. Each comparison now runs only as the entry point and says where its fixtures land, so the corpus is read from where it is declared rather than copied. A cache that has not been built is reported, not skipped silently. Co-authored-by: aryanraj45 <[email protected]> * ci: install the comparison corpus for the equivalence suite The stylesheets and documents the tool comparisons install are read by the equivalence suite, which until now found them only on a machine that had run a comparison by hand. Each script gains a `--setup` mode that installs the fixtures without measuring anything, and the job runs it. The install is not fatal: the suite already reads whichever fixtures are there and names the tier as not built when there are none, so a registry outage costs that corpus rather than the job. Co-authored-by: aryanraj45 <[email protected]> * test(css): read a repeated selector's properties from its own blocks A selector written twice was compared through a round trip: the blocks were concatenated as `cssText` and re-parsed, and the properties read off that. Chrome serializes a shorthand awaiting substitution as longhands with no value, which do not re-parse, so `border-bottom:var(--x) solid` lost its style and width longhands and the rule compared unequal to the same rule written once. The concatenation still stands, since a percentage resolves against the earlier declarations, but the properties and their specified values now come from the blocks themselves. Co-authored-by: aryanraj45 <[email protected]> * fix(css): fold no block of a layer over a streamed block of that layer Sibling blocks of one named layer are gathered into the first, which is sound because a named layer's blocks are one layer wherever they stand and the order within it is kept. A block large enough to stream is emitted without passing through that gather, so it neither folded nor cleared it, and a later block of its layer folded in front of it. The order within a layer is the one the cascade reads, so that moved rules past ones that could override them. A streamed block now clears its parent's gather, which is what a block the gather cannot see has to do. Co-authored-by: aryanraj45 <[email protected]> * test(css): read a repeated selector's importance as the cascade does A selector written twice took the later block's value for every property, but CSS Cascade 4 §6.2 keeps an important declaration over a normal one written after it — so `.a{--x:red!important}.a{--x:blue}` compared unequal to the one rule the cascade reads it as. The comparison corpus is installed in one step per cache too: `run` stops at the first command that fails, so a single block cost both corpora where only one install went wrong. Co-authored-by: aryanraj45 <[email protected]> --------- Co-authored-by: aryanraj45 <[email protected]>
1 parent b5817d1 commit f9ed9d1

9 files changed

Lines changed: 306 additions & 49 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
Keep a CSS layer's blocks in order where one of them streams.

‎.github/workflows/test.yml‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,31 @@ jobs:
328328

329329
- run: yarn link webpack --frozen-lockfile
330330

331+
# Keyed on the scripts that declare the package lists; a cache that
332+
# predates a fixture being added is rebuilt by the install below, which
333+
# reinstalls whenever the recorded list differs from the wanted one.
334+
- name: Cache the comparison corpus
335+
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
336+
with:
337+
path: |
338+
node_modules/.cache/css-tool-comparison
339+
node_modules/.cache/html-tool-comparison
340+
key: comparison-corpus-${{ runner.os }}-${{ hashFiles('tooling/compare-css-tools.js', 'tooling/compare-html-tools.js') }}
341+
342+
# The third corpus: the framework stylesheets and documents the tool
343+
# comparisons install. Not fatal — the suite reads whichever fixtures are
344+
# there and reports the tier as not built when the install did not land, so
345+
# a registry outage costs that corpus rather than the job.
346+
# One step each: `run` stops at the first command that fails, so a single
347+
# block would cost both corpora where only one install went wrong.
348+
- name: Install the CSS comparison corpus
349+
continue-on-error: true
350+
run: yarn benchmark:css-tools:setup
351+
352+
- name: Install the HTML comparison corpus
353+
continue-on-error: true
354+
run: yarn benchmark:html-tools:setup
355+
331356
- name: Cache jest result
332357
uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
333358
with:

‎lib/css/syntax.js‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4990,6 +4990,13 @@ const _streamClose = (d, rule) => {
49904990
_frameSeenDeclarations[d] = null;
49914991
_frameSeenRules[d] = null;
49924992
_frameSeenLayers[d] = null;
4993+
// A streamed block is one its parent's gather never saw, so nothing folds
4994+
// back over it — it may write into a layer already noted there.
4995+
if (d === 0) {
4996+
if (_seenTopLevelLayers !== null) _seenTopLevelLayers.clear();
4997+
} else if (_frameSeenLayers[d - 1] !== null) {
4998+
/** @type {Map<string, SeenLayer>} */ (_frameSeenLayers[d - 1]).clear();
4999+
}
49935000
if (writer.isPending(_framePendingDepth[d])) {
49945001
// Nothing inside printed. An empty rule paints nothing, so dropping it
49955002
// leaves the cascade as it was — but only where the block itself carries no

‎package.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,9 @@
5454
"build:examples": "cd examples && node buildAll.js",
5555
"benchmark": "node --max-old-space-size=6144 --experimental-vm-modules --trace-deprecation --hash-seed=1 --random-seed=1 --no-opt --predictable --predictable-gc-schedule --interpreted-frames-native-stack --allow-natives-syntax --expose-gc --no-concurrent-sweeping ./test/BenchmarkTestCases.benchmark.mjs",
5656
"benchmark:css-tools": "node tooling/compare-css-tools.js",
57+
"benchmark:css-tools:setup": "node tooling/compare-css-tools.js --setup",
5758
"benchmark:html-tools": "node tooling/compare-html-tools.js",
59+
"benchmark:html-tools:setup": "node tooling/compare-html-tools.js --setup",
5860
"benchmark:js-tools": "node tooling/compare-js-tools.js",
5961
"measure:color-agreement": "node tooling/measure-color-agreement.js",
6062
"pretest": "yarn lint",

‎test/CssSyntax.unittest.js‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -934,6 +934,17 @@ describe("CssSyntax — block streaming", () => {
934934
expect(out.slice(at, at + victim.length)).toBe(victim);
935935
});
936936

937+
it("folds no block of a layer over a streamed block of that layer", () => {
938+
// A streamed block is one its parent's gather never saw, so a later block
939+
// of its layer must not fold in front of it — that order is the cascade's.
940+
const src = `@layer outer{@layer a{.one{color:red}}@layer a{${BIG}}@layer a{.three{color:teal}}}`;
941+
// The middle block has to stream for the gather to be the one under test.
942+
expect(childCount(`@layer a{${BIG}}`)).toBe(0);
943+
const out = minify(src);
944+
expect(out.indexOf(".one")).toBeLessThan(out.indexOf(".c0"));
945+
expect(out.indexOf(".c0")).toBeLessThan(out.indexOf(".three"));
946+
});
947+
937948
it("enters a streamed rule before its children and exits after them", () => {
938949
const seq = walk(`@media screen{${SMALL}}`, { recurseBlocks: true });
939950
expect(seq[0]).toBe("+AtRule|0|0");

‎test/helpers/syntaxEquivalence.js‎

Lines changed: 116 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,19 @@
88

99
const fs = require("fs");
1010
const path = require("path");
11+
// Read from the comparisons, so a fixture added to one is added here.
12+
const {
13+
CACHE: CSS_CACHE,
14+
GENERATED_FIXTURES,
15+
INSTALLED_FIXTURES
16+
} = require("../../tooling/compare-css-tools");
17+
const {
18+
APP_SHELL,
19+
CACHE: HTML_CACHE,
20+
INLINED_STYLESHEETS,
21+
INSTALLED_DOCUMENTS,
22+
inlineCssPage
23+
} = require("../../tooling/compare-html-tools");
1124

1225
/** @typedef {{ name: string, raw: string, min: string }} Fixture */
1326

@@ -61,6 +74,76 @@ const buildCorpus = (dir, extension, minify) => {
6174
});
6275
};
6376

77+
/**
78+
* Read a benchmark cache as a corpus. A file the cache does not hold is left
79+
* out: each cache is built by the comparison that installs it.
80+
* @param {string} cache the cache directory
81+
* @param {[string, string][]} entries `[label, path within the cache]`
82+
* @param {(source: string) => string} minify the printer to run
83+
* @returns {Fixture[]} the corpus, empty when the cache is not there
84+
*/
85+
const readBenchmarkCache = (cache, entries, minify) => {
86+
/** @type {Fixture[]} */
87+
const out = [];
88+
for (const [label, within] of entries) {
89+
const file = path.join(cache, within);
90+
if (!fs.existsSync(file)) continue;
91+
const raw = fs.readFileSync(file, "utf8");
92+
out.push({ name: label, raw, min: minify(raw) });
93+
}
94+
return out;
95+
};
96+
97+
/**
98+
* The stylesheets `yarn benchmark:css-tools` installs and builds.
99+
* @param {(source: string) => string} minify the printer to run
100+
* @returns {Fixture[]} the corpus, empty until that has been run once
101+
*/
102+
const benchmarkStylesheets = (minify) =>
103+
readBenchmarkCache(
104+
CSS_CACHE,
105+
[
106+
...INSTALLED_FIXTURES.map(
107+
(/** @type {[string, string]} */ [label, file]) =>
108+
/** @type {[string, string]} */ ([label, `node_modules/${file}`])
109+
),
110+
...GENERATED_FIXTURES
111+
],
112+
minify
113+
);
114+
115+
/**
116+
* The documents `yarn benchmark:html-tools` installs, and the pages it builds
117+
* around a whole framework stylesheet. Those pages are the ones carrying a
118+
* `<style>`, which is what reaches the css minifier nested in the html one.
119+
* @param {(source: string) => string} minify the printer to run
120+
* @returns {Fixture[]} the corpus, empty until that has been run once
121+
*/
122+
const benchmarkDocuments = (minify) => {
123+
const out = readBenchmarkCache(
124+
HTML_CACHE,
125+
INSTALLED_DOCUMENTS.map(
126+
(/** @type {[string, string]} */ [label, file]) =>
127+
/** @type {[string, string]} */ ([label, `node_modules/${file}`])
128+
),
129+
minify
130+
);
131+
if (out.length > 0) {
132+
out.push({
133+
name: "App shell (inline critical CSS)",
134+
raw: APP_SHELL,
135+
min: minify(APP_SHELL)
136+
});
137+
}
138+
for (const [label, file] of INLINED_STYLESHEETS) {
139+
const sheet = path.join(HTML_CACHE, "node_modules", file);
140+
if (!fs.existsSync(sheet)) continue;
141+
const raw = inlineCssPage(label, fs.readFileSync(sheet, "utf8"));
142+
out.push({ name: label, raw, min: minify(raw) });
143+
}
144+
return out;
145+
};
146+
64147
/**
65148
* @typedef {{ kind: string, condition: string }} Condition
66149
* @typedef {{ chain: Condition[], text: string, label?: string, list?: string[], block?: string }} Rule
@@ -493,9 +576,10 @@ const installHelpers = () => {
493576
* substitution is compared as parsed because `var(--a)` and `var(--b)` both
494577
* compute to nothing on a probe with no ancestor to resolve them.
495578
* @param {string} declaration the declaration block
496-
* @param {CSSStyleDeclaration=} own the block's own declarations, when it has
497-
* them: Chrome serializes an unterminated `var(--a` as `var(--a;`, which no
498-
* longer re-parses, so the probe alone would lose it
579+
* @param {CSSStyleDeclaration[]=} own the blocks' own declarations, later
580+
* winning: a round trip through `cssText` is lossy, so the probe alone would
581+
* lose an unterminated `var(--a` (serialized as `var(--a;`) and every
582+
* longhand of a shorthand awaiting substitution (serialized with no value)
499583
* @returns {string[]} one entry per property it sets, unordered
500584
*/
501585
const computed = (declaration, own) => {
@@ -505,15 +589,26 @@ const installHelpers = () => {
505589
// the previous rule's value, and the computed style would be read in flight.
506590
for (const animation of probe.getAnimations()) animation.cancel();
507591
const style = getComputedStyle(probe);
508-
const source = own || probe.style;
509-
/** @type {string[]} */
510-
const out = [];
592+
/** @type {Map<string, [string, string]>} */
593+
const stated = new Map();
511594
// Indexed rather than iterated: a `@function` body's `result` descriptor is
512595
// counted and named by `item()`, but Chrome's iterator hands back nothing.
513-
for (let at = 0; at < source.length; at++) {
514-
const property = source.item(at);
515-
const specified = source.getPropertyValue(property);
516-
const bang = source.getPropertyPriority(property) === "" ? "" : "!";
596+
for (const source of own || [probe.style]) {
597+
for (let at = 0; at < source.length; at++) {
598+
const property = source.item(at);
599+
// CSS Cascade 4 §6.2: an important declaration is not overridden by a
600+
// normal one written after it, so the later block does not take it.
601+
const priority = source.getPropertyPriority(property);
602+
const earlier = stated.get(property);
603+
if (earlier === undefined || priority !== "" || earlier[1] === "") {
604+
stated.set(property, [source.getPropertyValue(property), priority]);
605+
}
606+
}
607+
}
608+
/** @type {string[]} */
609+
const out = [];
610+
for (const [property, [specified, priority]] of stated) {
611+
const bang = priority === "" ? "" : "!";
517612
// A custom property is a token stream the engine keeps verbatim, so it is
518613
// compared as written too — the whitespace and comments between its
519614
// tokens say nothing once it is substituted.
@@ -556,7 +651,7 @@ const installHelpers = () => {
556651
/** @type {Rule[]} */
557652
const out = [];
558653
// What each selector has been told so far, under each chain of conditions.
559-
/** @type {Map<string, string>} */
654+
/** @type {Map<string, { css: string, styles: CSSStyleDeclaration[] }>} */
560655
const carried = new Map();
561656
// A nested declaration block is its own interface, so it can be recognized
562657
// rather than guessed at from the shape of its text.
@@ -791,7 +886,7 @@ const installHelpers = () => {
791886
// about that selector so far: a printer is free to move a selector
792887
// between two adjacent lists, so only the per-selector sequence is
793888
// the thing both sides have to agree on.
794-
const own = computed(style.cssText, style);
889+
const own = computed(style.cssText, [style]);
795890
const block = ` { ${[...own].sort().join(";")} }`;
796891
const where = held
797892
.map((one) => `${one.kind}\u0001${conditionKey(one)}`)
@@ -802,12 +897,15 @@ const installHelpers = () => {
802897
const css =
803898
earlier === undefined
804899
? style.cssText
805-
: `${earlier};${style.cssText}`;
806-
carried.set(key, css);
900+
: `${earlier.css};${style.cssText}`;
901+
const styles =
902+
earlier === undefined ? [style] : [...earlier.styles, style];
903+
carried.set(key, { css, styles });
807904
// Read as one block, which is what the cascade reads: a
808905
// percentage or a `min()` here resolves against the earlier
809-
// declarations, so the two lists cannot simply be added.
810-
const list = earlier === undefined ? own : computed(css);
906+
// declarations, so the two lists cannot simply be added. The
907+
// declarations themselves still say which properties are set.
908+
const list = earlier === undefined ? own : computed(css, styles);
811909
out.push({
812910
chain: held,
813911
label: one,
@@ -1727,6 +1825,8 @@ const compareRules = (before, after, signatures) => {
17271825
};
17281826

17291827
module.exports = {
1828+
benchmarkDocuments,
1829+
benchmarkStylesheets,
17301830
buildCorpus,
17311831
collectFixtures,
17321832
compareRules,

‎test/syntaxEquivalence.spectest.js‎

Lines changed: 55 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ const {
3030
const expectNoDeprecations = require("./helpers/expectNoDeprecations");
3131
const launchChrome = require("./helpers/launchChrome");
3232
const {
33+
benchmarkDocuments,
34+
benchmarkStylesheets,
3335
buildCorpus,
3436
compareRules,
3537
conditionSignatures,
@@ -74,6 +76,10 @@ const FILED_CONFIG_CSS_DEFECTS = new Map();
7476

7577
const FILED_CONFIG_HTML_DEFECTS = new Map();
7678

79+
const FILED_BENCHMARK_CSS_DEFECTS = new Map();
80+
81+
const FILED_BENCHMARK_HTML_DEFECTS = new Map();
82+
7783
const FILED_WPT_HTML_DEFECTS = new Map([
7884
[
7985
"test/wpt/html/syntax/parsing/misnested-form-in-template.html",
@@ -237,6 +243,21 @@ const buildCorpora = () => {
237243
filedCss: FILED_CONFIG_CSS_DEFECTS
238244
}
239245
];
246+
// Real projects, where `configCases` and wpt are both written to exercise a
247+
// rule rather than to ship.
248+
const benchHtml = benchmarkDocuments((source) => source);
249+
const benchCss = benchmarkStylesheets(minifyCss);
250+
if (benchHtml.length > 0 || benchCss.length > 0) {
251+
built.push({
252+
label: "benchmark corpus",
253+
html: variant(benchHtml, {}),
254+
htmlAllImpliedTags: variant(benchHtml, { removeImpliedTags: true }),
255+
htmlSmartTags: variant(benchHtml, { removeImpliedTags: "smart" }),
256+
css: benchCss,
257+
filedHtml: FILED_BENCHMARK_HTML_DEFECTS,
258+
filedCss: FILED_BENCHMARK_CSS_DEFECTS
259+
});
260+
}
240261
if (!hasCorpus()) return built;
241262
/** @type {Fixture[]} */
242263
const wptHtml = [];
@@ -289,6 +310,9 @@ const inBatches = async (page, items, evaluate) => {
289310
const NO_CORPUS =
290311
"wpt submodule not initialized (run `git submodule update --init --depth 1 test/wpt`)";
291312

313+
const NO_BENCHMARK_CORPUS =
314+
"comparison caches not built (run `yarn benchmark:css-tools` / `yarn benchmark:html-tools`)";
315+
292316
expectNoDeprecations();
293317

294318
describe("printer output in real Chrome", () => {
@@ -631,6 +655,28 @@ describe("printer output in real Chrome", () => {
631655
FILE_TIMEOUT
632656
);
633657

658+
// CSS Cascade 4 §6.2: a normal declaration written after an important one
659+
// does not override it, so the later block is the dead one.
660+
it(
661+
"reads a repeated selector's importance as the cascade does",
662+
async () => {
663+
const differences = await compareStylesheets([
664+
{
665+
name: "important-then-normal",
666+
raw: ".a{--x:red!important}.a{--x:blue}",
667+
min: ".a{--x:red!important}"
668+
},
669+
{
670+
name: "normal-then-normal",
671+
raw: ".a{--y:red}.a{--y:blue}",
672+
min: ".a{--y:blue}"
673+
}
674+
]);
675+
expect(differences).toEqual([]);
676+
},
677+
FILE_TIMEOUT
678+
);
679+
634680
// A value that is not itself a color still carries them, and the computed
635681
// value keeps the space each was written in.
636682
it(
@@ -695,10 +741,15 @@ describe("printer output in real Chrome", () => {
695741
// Which corpora were built depends on what is checked out, so each names
696742
// itself, and one that could not be built says so rather than going quiet.
697743
for (const at of corpora.keys()) describeCorpus(at);
698-
if (!corpora.some((one) => one.label === "wpt")) {
699-
describe("wpt", () => {
700-
it(NO_CORPUS, () => {
701-
// No-op: the corpus is an optional git submodule.
744+
for (const [label, why] of [
745+
["wpt", NO_CORPUS],
746+
["benchmark corpus", NO_BENCHMARK_CORPUS]
747+
]) {
748+
if (corpora.some((one) => one.label === label)) continue;
749+
750+
describe(label, () => {
751+
it(why, () => {
752+
// No-op: both are optional, and each is built outside this suite.
702753
});
703754
});
704755
}

0 commit comments

Comments
 (0)