Skip to content

Commit eab04a5

Browse files
fix(css): join the rules a gathered @layer block leaves side by side
A named `@layer` block gathered into an earlier sibling makes the earlier block's last rule and the incoming block's first rule neighbours, but the streamed path folded the bodies as text and never offered that pair the join two siblings are offered. Minifying the same sheet twice then joined them only on the second pass: over Tailwind 4 + daisyUI 5 the printer's own idempotence sweep reported a 75-byte drift. The collected path already joins the seam through `_joinRuleEntries`; the streamed one now does it with the span primitives the piece is keyed by, so both agree. Also read an at-rule between two rules `mergeDistantRules` would join for what its own rules declare, rather than taking it as declaring everything. A condition only narrows which elements read the block it holds, so what it can shadow is what its rules declare; `@layer` and anything whose declarations cannot be read still stand in the way whatever they say. Over the comparison fixtures that is -418 raw / -48 gzip on daisyUI, -151 raw on Foundation and -39 raw on Bulma, with nothing lost elsewhere. Gathering two blocks of one condition is left declined with the reason measured in place: it moves a body up into a rule merge's way, for +835 raw and +25 gzip bytes over daisyUI.
1 parent 4ffacc7 commit eab04a5

10 files changed

Lines changed: 234 additions & 41 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+
Join the rules a gathered `@layer` block leaves side by side, and read a condition between two rules `mergeDistantRules` would join for what its own rules declare.

‎lib/css/cssMinify.js‎

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,16 +42,17 @@ const cssMinify = async (input, sourceMap, minimizerOptions = {}) => {
4242
require(/** @type {string} */ ("webpack"))
4343
);
4444

45-
// TODO two things other minifiers do that no switch here turns on yet:
46-
// dropping a declaration a later one merely overrides, and merging
47-
// non-adjacent `@media` — each has a TODO where it would be written.
45+
// TODO one thing other minifiers do that no switch here turns on yet: merging
46+
// two `@media` a rule stands between — there is a TODO where it would be written.
4847

49-
// WHY: each transform webpack declines is on in other minifiers, and each costs
50-
// something measured.
48+
// WHY: each transform webpack declines, or asks for rather than assumes, is on
49+
// unconditionally in other minifiers, and each costs something measured.
5150
// - Dropping a declaration a later one overrides loses a fallback pair an
52-
// engine that cannot read the newer spelling depends on.
53-
// - Merging rules a third stands between, and merging non-adjacent `@media`,
54-
// both reorder the cascade (csso loses ~12,900 Tailwind classes to it).
51+
// engine that cannot read the newer spelling depends on, so it waits for
52+
// `dropOverriddenDeclarations`.
53+
// - Merging rules a third stands between, and merging two blocks of one
54+
// condition, both reorder the cascade (csso loses ~12,900 Tailwind classes
55+
// to doing it without asking), so both wait for `mergeDistantRules`.
5556
// Adjacent rules sharing a block do join, nothing being between them to step
5657
// over — only where every selector is a shape each engine parses, since one
5758
// it cannot invalidates the whole list and loses the rest with it.

‎lib/css/syntax.js‎

Lines changed: 128 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4119,7 +4119,7 @@ const TOP_LEVEL_CONSUMERS = {
41194119
* @property {CssEnvironment=} environment what the target can read (the CSS entries of `output.environment`), so a spelling it would not understand is never reached for; only read while printing, and an absent entry means the modern spelling is available
41204120
* @property {boolean=} convertLengthUnits rewrite a length into a shorter unit it is exactly equal in (`16px` -> `1pc`); off by default because it earns nothing once the asset is compressed, and only read while printing. A time is always rewritten
41214121
* @property {boolean=} convertApproximateColors write a polar or Lab color as the nearest hex even where that hex only approximates it: a channel too near a `.5` boundary for two engines to round it alike, and a color outside the sRGB gamut, which hex can only clip. Off by default, and only read while printing; a space engines read through transfers of their own (`a98-rgb`, `prophoto-rgb`) is left alone either way
4122-
* @property {boolean=} mergeDistantRules give a rule the selectors of a later one printing the same block, past the rules between them; off by default, since it reorders the cascade and is sound only where nothing between declares what the block does
4122+
* @property {boolean=} mergeDistantRules give a rule the selectors of a later one printing the same block, past the rules between them; off by default, since it reorders the cascade and is sound only where nothing between declares what the block does — a condition between counting for what its own rules declare
41234123
* @property {boolean=} dropOverriddenDeclarations drop a declaration a later one in the same block overrides even where nothing states that the target can read the later value; off by default, and only read while printing. With a `browserslist` selection the drop is already made wherever every browser it names is known to read the later value, so this widens the case where no target is selected — a selection naming a browser the tables do not cover still answers for the whole of it
41244124
* @property {boolean=} rewriteCustomProperties shorten a custom property's value the way any other value is shortened (`--x:#ffffff` -> `#fff`); off by default because `getPropertyValue()` hands that text back, and only read while printing. What it may rewrite is what any other value's tokens may be, a color in a substitution's fallback included — that being the property's value rather than the function's own argument
41254125
* @property {EmbeddedSourceRenderer=} renderEmbeddedSource renders source this stylesheet embeds: the payload of a `url()` `data:` URL whose media type names a language webpack knows (SVG, CSS, HTML, JSON, JavaScript). Absent, a data URL is emitted exactly as written
@@ -5002,6 +5002,7 @@ const _streamEmitChild = (d, child) => {
50025002
writer.rewriteRetractable(grown.piece, grown.text);
50035003
for (const span of inner) span.at += base;
50045004
_noteSpans(writer, grown, inner, chain);
5005+
_joinGatheredSeam(writer, grown, base + opener.length, entry);
50055006
return;
50065007
}
50075008
const at = writer.emitRetractable(body);
@@ -5559,6 +5560,64 @@ const _growSpanList = (writer, taken, span, prelude, addition) => {
55595560
}
55605561
};
55615562

5563+
/**
5564+
* Offer the pair a gathered layer block left side by side the join two siblings
5565+
* are offered. The gather is what makes them neighbors, so nothing else ever
5566+
* reads them as adjacent, and the same sheet minified twice would join them
5567+
* only on the second pass.
5568+
* @param {PrintContext} writer the print context
5569+
* @param {TakenPiece} taken the piece the gather grew
5570+
* @param {number} at where the gathered body starts in it
5571+
* @param {RuleEntry | null} entry the gathered block's entry, where it kept one
5572+
* @returns {void}
5573+
*/
5574+
const _joinGatheredSeam = (writer, taken, at, entry) => {
5575+
if (entry === null || entry.children === null) return;
5576+
const first = entry.children[0];
5577+
// Only a plain qualified rule lends its selectors, and only the whole of one:
5578+
// a block a nested rule split is described by spans of its own.
5579+
if (first === undefined || first.atRule || first.prelude <= 0) return;
5580+
if (!_entryListable(first)) return;
5581+
const block = first.text.slice(first.prelude);
5582+
/** @type {RuleSpan | undefined} */
5583+
let before;
5584+
/** @type {RuleSpan | undefined} */
5585+
let after;
5586+
// A rule nested in the one at the seam closes inside it, so only the seam's
5587+
// own pair meets these two offsets.
5588+
for (const span of taken.spans) {
5589+
if (span.len === 0) continue;
5590+
if (span.at + span.len === at) before = span;
5591+
else if (span.at === at && span.len === first.text.length) after = span;
5592+
}
5593+
if (before === undefined || after === undefined) return;
5594+
const prelude = before.len - block.length;
5595+
if (prelude <= 0 || !taken.text.startsWith(block, before.at + prelude)) {
5596+
return;
5597+
}
5598+
if (
5599+
!_isJoinablePrelude(
5600+
taken.text.slice(before.at, before.at + prelude),
5601+
first.listKind === LIST_KIND_KEYFRAME,
5602+
first.listKind === LIST_KIND_NESTED
5603+
)
5604+
) {
5605+
return;
5606+
}
5607+
if (
5608+
!_lendSelectorsTo(
5609+
writer,
5610+
taken,
5611+
before,
5612+
prelude,
5613+
first.text.slice(0, first.prelude)
5614+
)
5615+
) {
5616+
return;
5617+
}
5618+
_cutSpan(writer, taken, after);
5619+
};
5620+
55625621
/**
55635622
* Cut the rules a cut left empty. A block a later rule emptied says nothing the
55645623
* printer would have written it for, and emptying it can empty the one holding
@@ -6132,19 +6191,27 @@ const _joinsPriorEntry = (writer, prior, entry, parted) => {
61326191
const _noteDistantRule = (taken, entry) => {
61336192
_distantSeq++;
61346193
const plain = entry.prelude !== -1 && !entry.atRule && entry.plain;
6135-
if (!plain) {
6194+
// A condition only narrows which elements read the block it holds, so an
6195+
// at-rule this can read shadows what its own rules declare and no more.
6196+
const written = plain
6197+
? _blockProperties(entry.text.slice(entry.prelude + 1, -1))
6198+
: entry.prelude !== -1 && entry.atRule && _readableCondition(entry)
6199+
? _atRuleDeclaredProperties(entry)
6200+
: null;
6201+
if (written === null) {
61366202
_distantDeclaredAt.set("all", _distantSeq);
61376203
return;
61386204
}
6139-
const block = entry.text.slice(entry.prelude);
61406205
const seq = _distantSeq;
61416206
const declaredAt = _distantDeclaredAt;
61426207
const note = (/** @type {string} */ name) => {
61436208
declaredAt.set(name, seq);
61446209
};
6145-
for (const property of _blockProperties(block.slice(1, -1))) {
6210+
for (const property of written) {
61466211
_eachPropertyName(property, note);
61476212
}
6213+
if (!plain) return;
6214+
const block = entry.text.slice(entry.prelude);
61486215
// One selector an engine cannot parse invalidates the list it stands in, so a
61496216
// rule that cannot lend its selectors cannot borrow one either.
61506217
if (taken === null || !_entryListable(entry) || _distantRules.has(block)) {
@@ -15763,30 +15830,74 @@ const _mergeNamedLayerBlocks = (items, texts) => {
1576315830
};
1576415831

1576515832
/**
15766-
* Whether every rule between two siblings leaves the shared block's properties
15767-
* alone, so moving a selector past them cannot change what any element reads.
15768-
* Anything that is not a plain qualified rule — a declaration, an at-rule whose
15769-
* own nested rules this cannot see into — is taken as standing in the way.
15833+
* Whether every rule between two siblings leaves the moved block's properties
15834+
* alone, so moving it past them cannot change what any element reads. Anything
15835+
* whose declarations this cannot read — a raw item, a rule with a nested one in
15836+
* it, an at-rule a later one by its name replaces — stands in the way whatever
15837+
* it says.
1577015838
* @param {Node[]} items the parent's children in source order
1577115839
* @param {string[]} texts their printed texts
15772-
* @param {number} from the index the selector would move to
15840+
* @param {number} from the index the block would move to
1577315841
* @param {number} to the index it moves from
15774-
* @param {Set<string>} declared the shared block's properties
15842+
* @param {Set<string>} declared the moved block's properties
1577515843
* @returns {boolean} true when nothing between can shadow them
1577615844
*/
1577715845
const _nothingBetweenShadows = (items, texts, from, to, declared) => {
1577815846
for (let i = from + 1; i < to; i++) {
1577915847
if (texts[i].length === 0) continue;
1578015848
const between = _ruleEntryOf(items[i], texts[i]);
15781-
if (between.prelude === -1 || between.atRule || !between.plain) {
15782-
return false;
15783-
}
15784-
const body = between.text.slice(between.prelude + 1, -1);
15785-
if (_propertiesOverlap(declared, _blockProperties(body))) return false;
15849+
if (between.prelude === -1) return false;
15850+
// A condition only narrows which elements read the block it holds, so what
15851+
// it can shadow is what its own rules declare.
15852+
const written = between.atRule
15853+
? _readableCondition(between)
15854+
? _atRuleDeclaredProperties(between)
15855+
: null
15856+
: between.plain
15857+
? _blockProperties(between.text.slice(between.prelude + 1, -1))
15858+
: null;
15859+
if (written === null) return false;
15860+
if (_propertiesOverlap(declared, written)) return false;
1578615861
}
1578715862
return true;
1578815863
};
1578915864

15865+
/**
15866+
* Whether this at-rule states a condition its own rules are read under, so what
15867+
* it declares is what they declare. `@layer` is not one: where a layer is first
15868+
* named fixes its order, and a block written into it from anywhere is read where
15869+
* the layer sits rather than where it stands.
15870+
* @param {RuleEntry} entry a printed at-rule
15871+
* @returns {boolean} true where its block may be read for what it declares
15872+
*/
15873+
const _readableCondition = (entry) => {
15874+
const name = _atRuleName(entry.text.slice(0, entry.prelude));
15875+
return name !== "layer" && MERGEABLE_AT_RULES.has(name);
15876+
};
15877+
15878+
/**
15879+
* The properties an at-rule's block declares, or null where it holds a child
15880+
* this cannot read the declarations of — and so cannot say what moving the
15881+
* block past a rule would shadow.
15882+
* @param {RuleEntry} entry a printed at-rule
15883+
* @returns {Set<string> | null} the property names, lowercased
15884+
*/
15885+
const _atRuleDeclaredProperties = (entry) => {
15886+
const children = entry.children;
15887+
if (children === null) return null;
15888+
/** @type {Set<string>} */
15889+
const out = new Set();
15890+
for (const child of children) {
15891+
if (child.prelude === -1 || child.atRule || !child.plain) return null;
15892+
for (const property of _blockProperties(
15893+
child.text.slice(child.prelude + 1, -1)
15894+
)) {
15895+
out.add(property);
15896+
}
15897+
}
15898+
return out;
15899+
};
15900+
1579015901
/**
1579115902
* Join sibling rules that print the same block with other rules between them.
1579215903
* Unlike `_mergeAdjacentRules` this moves a selector past what stands in its
@@ -15807,9 +15918,8 @@ const _mergeDistantRules = (items, texts) => {
1580715918
for (let i = 0; i < items.length; i++) {
1580815919
if (texts[i].length === 0) continue;
1580915920
const entry = _ruleEntryOf(items[i], texts[i]);
15810-
// TODO join two `@media` a rule stands between as well, which is this
15811-
// same question asked of every property the body declares — csso loses
15812-
// ~12,900 Tailwind classes to doing it without asking it.
15921+
// TODO gather two blocks of one condition as well. Measured over daisyUI 5 it
15922+
// loses: the body it moves up is then in a rule merge's way, +25 gzip bytes.
1581315923
if (entry.prelude === -1 || entry.atRule || !_entryListable(entry)) {
1581415924
continue;
1581515925
}

‎schemas/WebpackOptions.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4045,7 +4045,7 @@
40454045
"added": "5.111.0"
40464046
},
40474047
"mergeDistantRules": {
4048-
"description": "Give a rule the selectors of a later one printing the same block, past the rules standing between them. Off by default because it reorders the cascade, so it holds only where nothing between the two declares a property the shared block does. A block repeated at a distance already compresses on its own, so the join is taken only where the copy of the block it drops is worth more than twice the selector it writes instead. `mergeRules` is the safe half of this, joining only what nothing stands between.",
4048+
"description": "Give a rule the selectors of a later one printing the same block, past the rules standing between them. Off by default because it reorders the cascade, so it holds only where nothing between the two declares a property the shared block does — a condition between counts for what its own rules declare, while `@layer` and anything else whose declarations cannot be read stands in the way whatever it says. A block repeated at a distance already compresses on its own, so the join is taken only where the copy of the block it drops is worth more than twice the selector it writes instead. `mergeRules` is the safe half of this, joining only what nothing stands between.",
40494049
"type": "boolean",
40504050
"added": "5.111.0"
40514051
},

‎test/configCases/css/minimize-merge-distant-rules/__snapshots__/ConfigCacheTest.snap‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@
22

33
exports[`ConfigCacheTestCases css minimize-merge-distant-rules minimize-merge-distant-rules should compile 1`] = `
44
Array [
5-
".alpha,.gamma{color:red;background:blue}.spacer{margin:0}.delta{color:blue}.between{color:green}.epsilon{color:blue}.zeta{margin-top:0}.shorthand{margin:1px}.eta{margin-top:0}.theta{padding:0}@media print{.printed{width:0}}.iota{padding:0}.kappa{outline:0}.spacing{margin:2px}.lambda-is-a-long-name{outline:0}",
5+
".alpha,.gamma{color:red;background:blue}.spacer{margin:0}.delta{color:blue}.between{color:green}.epsilon{color:blue}.zeta{margin-top:0}.shorthand{margin:1px}.eta{margin-top:0}.iota,.theta{padding:0}@media print{.printed{width:0}}.mu{border-width:0}@media print{.bordered{border:1px solid red}}.nu{border-width:0}.xi{inset:0}@keyframes spin{0%{rotate:0deg}}.omicron{inset:0}.kappa{outline:0}.spacing{margin:2px}.lambda-is-a-long-name{outline:0}@layer wrapped{.pi,.sigma{padding:3px 4px 5px 6px}@media print{.rho{margin:0}}.tau{padding:7px 8px 9px 10px}@media print{.upsilon{padding-top:0}}.phi{padding:7px 8px 9px 10px}.chi{outline:1px dashed red}@layer inner{.psi{margin:0}}.omega{outline:1px dashed red}}",
66
]
77
`;

‎test/configCases/css/minimize-merge-distant-rules/__snapshots__/ConfigTest.snap‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,6 @@
22

33
exports[`ConfigTestCases css minimize-merge-distant-rules minimize-merge-distant-rules should compile 1`] = `
44
Array [
5-
".alpha,.gamma{color:red;background:blue}.spacer{margin:0}.delta{color:blue}.between{color:green}.epsilon{color:blue}.zeta{margin-top:0}.shorthand{margin:1px}.eta{margin-top:0}.theta{padding:0}@media print{.printed{width:0}}.iota{padding:0}.kappa{outline:0}.spacing{margin:2px}.lambda-is-a-long-name{outline:0}",
5+
".alpha,.gamma{color:red;background:blue}.spacer{margin:0}.delta{color:blue}.between{color:green}.epsilon{color:blue}.zeta{margin-top:0}.shorthand{margin:1px}.eta{margin-top:0}.iota,.theta{padding:0}@media print{.printed{width:0}}.mu{border-width:0}@media print{.bordered{border:1px solid red}}.nu{border-width:0}.xi{inset:0}@keyframes spin{0%{rotate:0deg}}.omicron{inset:0}.kappa{outline:0}.spacing{margin:2px}.lambda-is-a-long-name{outline:0}@layer wrapped{.pi,.sigma{padding:3px 4px 5px 6px}@media print{.rho{margin:0}}.tau{padding:7px 8px 9px 10px}@media print{.upsilon{padding-top:0}}.phi{padding:7px 8px 9px 10px}.chi{outline:1px dashed red}@layer inner{.psi{margin:0}}.omega{outline:1px dashed red}}",
66
]
77
`;

‎test/configCases/css/minimize-merge-distant-rules/style.css‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,43 @@
1313
.shorthand { margin: 1px }
1414
.eta { margin-top: 0 }
1515

16-
/* An at-rule between is read as declaring everything. */
16+
/* A condition between only narrows what reads it, so what it can shadow is
17+
what its own rules declare — `width` here, which leaves `padding` alone. */
1718
.theta { padding: 0 }
1819
@media print { .printed { width: 0 } }
1920
.iota { padding: 0 }
2021

22+
/* The same condition, declaring the property this time. */
23+
.mu { border-width: 0 }
24+
@media print { .bordered { border: 1px solid red } }
25+
.nu { border-width: 0 }
26+
27+
/* An at-rule a later one of its name replaces is read as declaring
28+
everything, since its block is not a set of conditioned rules. */
29+
.xi { inset: 0 }
30+
@keyframes spin { from { rotate: 0deg } }
31+
.omicron { inset: 0 }
32+
2133
/* The copy dropped is not worth twice the selector written, so these stay apart. */
2234
.kappa { outline: 0 }
2335
.spacing { margin: 2px }
2436
.lambda-is-a-long-name { outline: 0 }
37+
38+
/* Inside a block the same gates are asked a second way, the rules there being
39+
joined as the block is assembled rather than as the stylesheet streams. */
40+
@layer wrapped {
41+
.pi { padding: 3px 4px 5px 6px }
42+
@media print { .rho { margin: 0 } }
43+
.sigma { padding: 3px 4px 5px 6px }
44+
45+
/* `padding` between them, inside a condition, so these stay apart. */
46+
.tau { padding: 7px 8px 9px 10px }
47+
@media print { .upsilon { padding-top: 0 } }
48+
.phi { padding: 7px 8px 9px 10px }
49+
50+
/* Where a layer is first named fixes its order, so what it holds is read
51+
where the layer sits rather than where the block stands. */
52+
.chi { outline: 1px dashed red }
53+
@layer inner { .psi { margin: 0 } }
54+
.omega { outline: 1px dashed red }
55+
}

‎test/configCases/css/minimize-merge-distant-rules/test.config.js‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,18 @@ module.exports = {
99
afterExecute(options) {
1010
const sections = readMinifiedSections(options.output.path, "bundle0.css");
1111
expect(sections).toMatchSnapshot();
12-
// What the option is for, and the four shapes it declines.
12+
// What the option is for, and the shapes it declines.
1313
const css = sections.join("");
1414
expect(css).toContain(".alpha,.gamma");
15+
expect(css).toContain(".iota,.theta");
1516
expect(css).not.toContain(".delta,.epsilon");
1617
expect(css).not.toContain(".zeta,.eta");
17-
expect(css).not.toContain(".theta,.iota");
18+
expect(css).not.toContain(".mu,.nu");
19+
expect(css).not.toContain(".xi,.omicron");
1820
expect(css).not.toContain(".kappa,.lambda-is-a-long-name");
21+
// The same gates, asked of a block's children rather than of the sheet.
22+
expect(css).toContain(".pi,.sigma");
23+
expect(css).not.toContain(".tau,.phi");
24+
expect(css).not.toContain(".chi,.omega");
1925
}
2026
};

0 commit comments

Comments
 (0)