Skip to content

Commit 7188f8f

Browse files
feat(css): resolve @custom-selector under one option with @custom-media
The two are one draft and one build-time substitution, so the minimizer takes one switch for both: `customMedia` becomes `resolveCustomAtRules`, which now also writes what a `@custom-selector` name stands for. A name is written as `:is(…)` whatever its list holds, matching what `module.parser.css.customSelectors` already writes, so the same stylesheet reads the same either way.
1 parent e7c50ab commit 7188f8f

13 files changed

Lines changed: 220 additions & 68 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": minor
3+
---
4+
5+
Lower CSS nesting, add `resolveCustomAtRules` / `rewriteDirSelector`, back `color-mix()`.

‎.changeset/018-css-lower-nesting-dir-custom-media.md‎

Lines changed: 0 additions & 5 deletions
This file was deleted.

‎declarations/WebpackOptions.d.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2433,11 +2433,6 @@ export interface OptimizationMinimizeCss {
24332433
* @since 5.110.0
24342434
*/
24352435
convertLengthUnits?: boolean;
2436-
/**
2437-
* Write the query a `@custom-media` names wherever a condition asks for it, and drop the rule that named it where no target reads one. `@custom-media --wide (width>400px)` and `@media (--wide)` become `@media (width>400px)`. Off until asked for: `@custom-media` is a draft no browser ships unflagged, so a stylesheet using it is opting into a syntax webpack resolves at build time rather than one an engine reads. Only a name stated before the condition asking for it is written out — the rules are read in the order they are written — and a condition naming one this has not come to is left as the author had it.
2438-
* @since 5.111.0
2439-
*/
2440-
customMedia?: boolean;
24412436
/**
24422437
* Write a spelling the `browserslist` target cannot read as one it can — the same value said another way, rather than left for an engine that will drop it: a 4-/8-digit hex as `rgba()`, a double-position gradient stop as the two stops it names, `inset` / `overflow` / `place-*` as the longhands they set, `text-decoration` as its own longhands where a slot is newer than the shorthand, `system-ui` as the stack of platform font names it stands for, a `:lang()` or `:not()` holding a list as the `:is()` that means it, a media feature range as the `min-`/`max-` pair, and `light-dark()` as the custom-property pair a color scheme switches. On by default, and only in effect for a `browserslist` target — any other target names no browsers to answer for. Off leaves every such spelling as written, which is how a stylesheet one of these rewrites gets wrong is minified; it never makes the minifier write a spelling the target cannot read.
24432438
* @since 5.111.0
@@ -2478,6 +2473,11 @@ export interface OptimizationMinimizeCss {
24782473
* @since 5.110.0
24792474
*/
24802475
removeDeadRules?: boolean;
2476+
/**
2477+
* Resolve the `@custom-media` and `@custom-selector` at-rules: write the query or the selector list a name stands for wherever one asks for it, and drop the rule that named it. `@custom-media --wide (width>400px)` with `@media (--wide)` becomes `@media (width>400px)`, and `@custom-selector :--heading h1, h2` with `:--heading` becomes `:is(h1, h2)`. Off until asked for: `module.parser.css.customMedia` and `module.parser.css.customSelectors` already resolve both in every stylesheet webpack parses, so this is for a `.css` asset that reached the minimizer without being parsed — one emitted by `asset/resource` or copied in. Only a name stated before the rule asking for it is written out — the rules are read in the order they are written — and a rule naming one this has not come to is left as the author had it. A selector list is written as `:is(…)`, so a name is substituted only where the target reads `:is()`.
2478+
* @since 5.111.0
2479+
*/
2480+
resolveCustomAtRules?: boolean;
24812481
/**
24822482
* Shorten the values of custom properties (`--x: #ffffff` -> `#fff`, `--y: 0.5rem` -> `.5rem`), which are otherwise written back exactly as authored. Off by default: `getComputedStyle().getPropertyValue()` hands this text back, so a rewritten value is a different CSSOM — the one place a declaration's authored text survives. What it may rewrite is exactly what any other value's tokens may be, a color in a substitution's fallback included — that fallback being the property's value rather than the function's own argument.
24832483
* @since 5.110.0

‎lib/css/syntax.js‎

Lines changed: 79 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2057,6 +2057,7 @@ const _setupParse = (input, lc) => {
20572057
_loweringNesting = false;
20582058
_pendingNested.length = 0;
20592059
_customMedia.clear();
2060+
_customSelectors.clear();
20602061
_isSelectorAllowed = true;
20612062
_langArgumentListAllowed = true;
20622063
_notSelectorListAllowed = true;
@@ -4062,7 +4063,7 @@ const TOP_LEVEL_CONSUMERS = {
40624063
* @property {boolean=} colorFallbacks write a color the target cannot read as an extra declaration before it, in a spelling it does read
40634064
* @property {boolean=} lowerUnsupported write a spelling the target cannot read as one it can — the same value, said another way
40644065
* @property {(boolean | "all" | "some" | string | RegExp | ((comment: string) => boolean))=} comments which comments survive: `"some"` (the default) the ones that carry something, `true` / `"all"` every one, `false` none, or the ones a pattern matches / a predicate accepts, over the comment's own text
4065-
* @property {boolean=} customMedia write the query a `@custom-media` names wherever a condition asks for it, and drop the rule that named it
4066+
* @property {boolean=} resolveCustomAtRules write the query or selector list a `@custom-media` / `@custom-selector` names wherever one asks for it, and drop the rule that named it
40664067
* @property {boolean=} mergeLonghands write a family of longhands as the one shorthand that sets them
40674068
* @property {boolean=} mergeRules join rules that print the same block, at-rules that share a prelude, and a named `@layer` block a later sibling opens again
40684069
* @property {boolean=} normalizeQuotes normalize a string's, `url()`'s, font family's and attribute value's quoting
@@ -5748,7 +5749,7 @@ const _ALL_TRANSFORMS = Object.freeze({
57485749
colorFallbacks: true,
57495750
lowerUnsupported: true,
57505751
comments: "some",
5751-
customMedia: false,
5752+
resolveCustomAtRules: false,
57525753
mergeLonghands: true,
57535754
mergeRules: true,
57545755
normalizeQuotes: true,
@@ -10451,6 +10452,59 @@ const _writeCustomMedia = (parts) => {
1045110452
}
1045210453
};
1045310454

10455+
// `@custom-selector :--name <selector-list>`, as printed: the name and the list.
10456+
const _CUSTOM_SELECTOR_RE = /^@[^\s]+\s+:(--[^\s]+)\s+([^]+)$/;
10457+
10458+
// One selector naming a `@custom-selector`, as printed after its `:`.
10459+
const _CUSTOM_SELECTOR_NAME_RE = /^--[^\s(),]+$/;
10460+
10461+
/**
10462+
* Take down what a `@custom-selector` prelude names, so a selector asking for it
10463+
* is written as the list instead. False where the prelude states no list.
10464+
* @param {string} prelude the rule's printed prelude
10465+
* @returns {boolean} true when the name was taken down
10466+
*/
10467+
const _takeCustomSelector = (prelude) => {
10468+
const found = _CUSTOM_SELECTOR_RE.exec(prelude);
10469+
if (found === null) return false;
10470+
_customSelectors.set(found[1], found[2]);
10471+
return true;
10472+
};
10473+
10474+
/**
10475+
* Write each selector naming a `@custom-selector` as the list it stands for, in
10476+
* the printed parts, in place.
10477+
*
10478+
* The list is always written as `:is(…)`: it may name alternatives, and even a
10479+
* lone type selector cannot be spliced into a compound another part opened.
10480+
* Only a name already taken down, as with `@custom-media`.
10481+
* @param {string[]} parts the prelude's printed parts
10482+
* @returns {void}
10483+
*/
10484+
const _writeCustomSelector = (parts) => {
10485+
// The two non-empty parts before the current one: the `:` a pseudo is written
10486+
// after, and whether a second `:` made it a pseudo-element, which this never is.
10487+
let first = -1;
10488+
let second = -1;
10489+
for (let i = 0; i < parts.length; i++) {
10490+
if (parts[i].length === 0) continue;
10491+
if (
10492+
_CUSTOM_SELECTOR_NAME_RE.test(parts[i]) &&
10493+
second !== -1 &&
10494+
parts[second] === ":" &&
10495+
!(first !== -1 && parts[first] === ":")
10496+
) {
10497+
const list = _customSelectors.get(parts[i]);
10498+
if (list !== undefined) {
10499+
parts[second] = "";
10500+
parts[i] = `:is(${list})`;
10501+
}
10502+
}
10503+
first = second;
10504+
second = i;
10505+
}
10506+
};
10507+
1045410508
// `:dir(ltr)` / `:dir(rtl)`, as printed: the name and its one argument.
1045510509
const _DIR_PSEUDO_RE = /^dir\(\s*([a-zA-Z-]+)\s*\)$/i;
1045610510

@@ -14208,7 +14262,7 @@ const _rulePrelude = (path, writer, minify, outParts) => {
1420814262
// author's own and case-sensitive.
1420914263
if (media) {
1421014264
// Before the passes below, which read the query this writes in.
14211-
if (_transforms.customMedia && _customMedia.size !== 0) {
14265+
if (_transforms.resolveCustomAtRules && _customMedia.size !== 0) {
1421214266
_writeCustomMedia(parts);
1421314267
}
1421414268
_lowercaseConditionParts(parts);
@@ -14221,6 +14275,10 @@ const _rulePrelude = (path, writer, minify, outParts) => {
1422114275
}
1422214276
}
1422314277
if (minify && path.type() === T_QUALIFIED_RULE) {
14278+
// Before the fold, so what a name stands for is what every pass below reads.
14279+
if (_transforms.resolveCustomAtRules && _customSelectors.size !== 0) {
14280+
_writeCustomSelector(parts);
14281+
}
1422414282
_foldPseudoNames(parts);
1422514283
// After the fold, which is what makes the names above match, and before the
1422614284
// class replacement, so a pseudo written as a class is one either way.
@@ -15555,13 +15613,24 @@ const printer = (path, writer) => {
1555515613
// not come to yet still needs it, and so does an engine that reads it.
1555615614
if (
1555715615
minify &&
15558-
_transforms.customMedia &&
15616+
_transforms.resolveCustomAtRules &&
1555915617
equalsLowerCase(path.name(), "custom-media") &&
1556015618
_takeCustomMedia(prelude) &&
1556115619
!_customMediaAllowed
1556215620
) {
1556315621
return "";
1556415622
}
15623+
// No engine reads `@custom-selector`, so the rule always goes once its
15624+
// name is down — but only where `:is()` can carry what it stands for.
15625+
if (
15626+
minify &&
15627+
_transforms.resolveCustomAtRules &&
15628+
_isSelectorAllowed &&
15629+
equalsLowerCase(path.name(), "custom-selector") &&
15630+
_takeCustomSelector(prelude)
15631+
) {
15632+
return "";
15633+
}
1556515634
return `${prelude};`;
1556615635
}
1556715636
// Read before the body: composing it is what leaves the block empty, and
@@ -16144,6 +16213,12 @@ const _pendingNested = [];
1614416213
* @type {Map<string, string>}
1614516214
*/
1614616215
const _customMedia = new Map();
16216+
/**
16217+
* Each `@custom-selector` name taken down so far, to the selector list it
16218+
* stands for, in the order the rules were written.
16219+
* @type {Map<string, string>}
16220+
*/
16221+
const _customSelectors = new Map();
1614716222
let _isSelectorAllowed = true;
1614816223
let _langArgumentListAllowed = true;
1614916224
let _notSelectorListAllowed = true;

‎schemas/WebpackOptions.check.js‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎schemas/WebpackOptions.json‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3764,11 +3764,6 @@
37643764
"type": "boolean",
37653765
"added": "5.110.0"
37663766
},
3767-
"customMedia": {
3768-
"description": "Write the query a `@custom-media` names wherever a condition asks for it, and drop the rule that named it where no target reads one. `@custom-media --wide (width>400px)` and `@media (--wide)` become `@media (width>400px)`. Off until asked for: `@custom-media` is a draft no browser ships unflagged, so a stylesheet using it is opting into a syntax webpack resolves at build time rather than one an engine reads. Only a name stated before the condition asking for it is written out — the rules are read in the order they are written — and a condition naming one this has not come to is left as the author had it.",
3769-
"type": "boolean",
3770-
"added": "5.111.0"
3771-
},
37723767
"lowerUnsupported": {
37733768
"description": "Write a spelling the `browserslist` target cannot read as one it can — the same value said another way, rather than left for an engine that will drop it: a 4-/8-digit hex as `rgba()`, a double-position gradient stop as the two stops it names, `inset` / `overflow` / `place-*` as the longhands they set, `text-decoration` as its own longhands where a slot is newer than the shorthand, `system-ui` as the stack of platform font names it stands for, a `:lang()` or `:not()` holding a list as the `:is()` that means it, a media feature range as the `min-`/`max-` pair, and `light-dark()` as the custom-property pair a color scheme switches. On by default, and only in effect for a `browserslist` target — any other target names no browsers to answer for. Off leaves every such spelling as written, which is how a stylesheet one of these rewrites gets wrong is minified; it never makes the minifier write a spelling the target cannot read.",
37743769
"type": "boolean",
@@ -3809,6 +3804,11 @@
38093804
"type": "boolean",
38103805
"added": "5.110.0"
38113806
},
3807+
"resolveCustomAtRules": {
3808+
"description": "Resolve the `@custom-media` and `@custom-selector` at-rules: write the query or the selector list a name stands for wherever one asks for it, and drop the rule that named it. `@custom-media --wide (width>400px)` with `@media (--wide)` becomes `@media (width>400px)`, and `@custom-selector :--heading h1, h2` with `:--heading` becomes `:is(h1, h2)`. Off until asked for: `module.parser.css.customMedia` and `module.parser.css.customSelectors` already resolve both in every stylesheet webpack parses, so this is for a `.css` asset that reached the minimizer without being parsed — one emitted by `asset/resource` or copied in. Only a name stated before the rule asking for it is written out — the rules are read in the order they are written — and a rule naming one this has not come to is left as the author had it. A selector list is written as `:is(…)`, so a name is substituted only where the target reads `:is()`.",
3809+
"type": "boolean",
3810+
"added": "5.111.0"
3811+
},
38123812
"rewriteCustomProperties": {
38133813
"description": "Shorten the values of custom properties (`--x: #ffffff` -> `#fff`, `--y: 0.5rem` -> `.5rem`), which are otherwise written back exactly as authored. Off by default: `getComputedStyle().getPropertyValue()` hands this text back, so a rewritten value is a different CSSOM — the one place a declaration's authored text survives. What it may rewrite is exactly what any other value's tokens may be, a color in a substitution's fallback included — that fallback being the property's value rather than the function's own argument.",
38143814
"type": "boolean",

‎test/CssSyntax.unittest.js‎

Lines changed: 81 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -9494,21 +9494,21 @@ describe("CssSyntax minify — `:dir()` as the attribute it approximates", () =>
94949494
});
94959495
});
94969496

9497-
describe("CssSyntax minify — `@custom-media`", () => {
9497+
describe("CssSyntax minify — `@custom-media` / `@custom-selector`", () => {
94989498
const sheet = "@custom-media --m (width>400px);@media (--m){a{color:red}}";
94999499

95009500
it("writes the query wherever a condition asks for it", () => {
9501-
expect(minifyForWith(sheet, ["chrome 120"], { customMedia: true })).toBe(
9502-
"@media (width>400px){a{color:red}}"
9503-
);
9501+
expect(
9502+
minifyForWith(sheet, ["chrome 120"], { resolveCustomAtRules: true })
9503+
).toBe("@media (width>400px){a{color:red}}");
95049504
});
95059505

95069506
it("writes it into a condition an `and` joins", () => {
95079507
expect(
95089508
minifyForWith(
95099509
"@custom-media --m (width>400px);@media screen and (--m){a{color:red}}",
95109510
["chrome 120"],
9511-
{ customMedia: true }
9511+
{ resolveCustomAtRules: true }
95129512
)
95139513
).toBe("@media screen and (width>400px){a{color:red}}");
95149514
});
@@ -9523,14 +9523,14 @@ describe("CssSyntax minify — `@custom-media`", () => {
95239523
const list = "@custom-media --m (width>400px),(orientation:portrait);";
95249524
expect(
95259525
minifyForWith(`${list}@media (--m){a{color:red}}`, ["chrome 120"], {
9526-
customMedia: true
9526+
resolveCustomAtRules: true
95279527
})
95289528
).toBe("@media (width>400px),(orientation:portrait){a{color:red}}");
95299529
expect(
95309530
minifyForWith(
95319531
`${list}@media screen and (--m){a{color:red}}`,
95329532
["chrome 120"],
9533-
{ customMedia: true }
9533+
{ resolveCustomAtRules: true }
95349534
)
95359535
).toBe("@media screen and (--m){a{color:red}}");
95369536
});
@@ -9540,14 +9540,16 @@ describe("CssSyntax minify — `@custom-media`", () => {
95409540
minifyForWith(
95419541
"@custom-media --w (width>400px);@media screen and (--w){a{color:red}}",
95429542
["chrome 120"],
9543-
{ customMedia: true }
9543+
{ resolveCustomAtRules: true }
95449544
)
95459545
).toBe("@media screen and (width>400px){a{color:red}}");
95469546
});
95479547

95489548
it("leaves a rule stating no query alone", () => {
95499549
const css = "@custom-media --m;@media (--m){a{color:red}}";
9550-
expect(minifyForWith(css, ["chrome 120"], { customMedia: true })).toBe(css);
9550+
expect(
9551+
minifyForWith(css, ["chrome 120"], { resolveCustomAtRules: true })
9552+
).toBe(css);
95519553
});
95529554

95539555
it("leaves a name nothing states alone", () => {
@@ -9557,7 +9559,7 @@ describe("CssSyntax minify — `@custom-media`", () => {
95579559
minifyForWith(
95589560
"@custom-media --m (width>400px);@media (--nope){a{color:red}}",
95599561
["chrome 120"],
9560-
{ customMedia: true }
9562+
{ resolveCustomAtRules: true }
95619563
)
95629564
).toBe("@media (--nope){a{color:red}}");
95639565
});
@@ -9569,12 +9571,80 @@ describe("CssSyntax minify — `@custom-media`", () => {
95699571
minifyForWith(
95709572
"@media (--m){a{color:red}}@custom-media --m (width>400px);",
95719573
["chrome 120"],
9572-
{ customMedia: true }
9574+
{ resolveCustomAtRules: true }
95739575
)
95749576
).toBe("@media (--m){a{color:red}}");
95759577
});
95769578
});
95779579

9580+
describe("CssSyntax minify — `@custom-selector`", () => {
9581+
const sheet = "@custom-selector :--h h1,h2;:--h{color:red}";
9582+
const on = { resolveCustomAtRules: true };
9583+
9584+
it("writes the list wherever a selector asks for it", () => {
9585+
expect(minifyForWith(sheet, ["chrome 120"], on)).toBe(
9586+
":is(h1,h2){color:red}"
9587+
);
9588+
});
9589+
9590+
it("writes a list of one as `:is()` too", () => {
9591+
// A lone type selector cannot be spliced into a compound another part
9592+
// opened, so the wrapper is what makes every position the same.
9593+
expect(
9594+
minifyForWith(
9595+
"@custom-selector :--h h1;x:--h{color:red}",
9596+
["chrome 120"],
9597+
on
9598+
)
9599+
).toBe("x:is(h1){color:red}");
9600+
});
9601+
9602+
it("writes it where the name stands in a compound", () => {
9603+
expect(
9604+
minifyForWith(
9605+
"@custom-selector :--h h1,h2;.x:--h .y{color:red}",
9606+
["chrome 120"],
9607+
on
9608+
)
9609+
).toBe(".x:is(h1,h2) .y{color:red}");
9610+
});
9611+
9612+
it("is off until asked for", () => {
9613+
expect(minifyFor(sheet, ["chrome 120"])).toBe(sheet);
9614+
});
9615+
9616+
it("leaves a pseudo-element spelling alone", () => {
9617+
const css = "@custom-selector :--h h1;::--h{color:red}";
9618+
expect(minifyForWith(css, ["chrome 120"], on)).toBe("::--h{color:red}");
9619+
});
9620+
9621+
it("leaves a name nothing states alone", () => {
9622+
expect(
9623+
minifyForWith(
9624+
"@custom-selector :--h h1;:--nope{color:red}",
9625+
["chrome 120"],
9626+
on
9627+
)
9628+
).toBe(":--nope{color:red}");
9629+
});
9630+
9631+
it("leaves a selector standing before the rule that names it", () => {
9632+
expect(
9633+
minifyForWith(
9634+
":--h{color:red}@custom-selector :--h h1;",
9635+
["chrome 120"],
9636+
on
9637+
)
9638+
).toBe(":--h{color:red}");
9639+
});
9640+
9641+
it("keeps the rule where the target reads no `:is()`", () => {
9642+
// Nothing to write the name as, so dropping what states it would leave
9643+
// every selector asking for it unreadable instead of merely unresolved.
9644+
expect(minifyForWith(sheet, ["chrome 60"], on)).toBe(sheet);
9645+
});
9646+
});
9647+
95789648
describe("CssSyntax minify — a `color-mix()` the target cannot read", () => {
95799649
it("writes the color it mixes to before it", () => {
95809650
expect(

0 commit comments

Comments
 (0)