Skip to content

Commit 0078d85

Browse files
feat(css): put case folding and escape rewriting under options
Both rewrote a stylesheet with every option already off, so a caller asking the printer to change nothing still got a changed sheet. Over the repository's 619 stylesheets that closes 29 of the 42 that did not round trip, leaving `!important` (a keyword the printer writes rather than copies), a `data:` payload's percent escapes, and error recovery.
1 parent 9a26bcd commit 0078d85

8 files changed

Lines changed: 190 additions & 16 deletions

File tree

‎.changeset/018-css-lower-nesting-dir-and-custom-at-rules.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,4 @@
22
"webpack": minor
33
---
44

5-
Lower CSS nesting and `:dir()`, resolve custom at-rules, back `color-mix()`.
5+
Lower CSS nesting, `:dir()` and custom at-rules; gate case folding and escapes.

‎declarations/WebpackOptions.d.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2433,6 +2433,11 @@ export interface OptimizationMinimizeCss {
24332433
* @since 5.110.0
24342434
*/
24352435
convertLengthUnits?: boolean;
2436+
/**
2437+
* Write a name that matches ASCII case-insensitively in lowercase: an at-rule name, a property name, a pseudo-class or pseudo-element name, a function name, a unit, and a keyword standing in a value whose grammar takes keywords alone. `@MEDIA`, `COLOR`, `:NTH-CHILD`, `URL(`, `1PX` and `currentColor` become `@media`, `color`, `:nth-child`, `url(`, `1px` and `currentcolor`. On by default, and exact: CSS matches every one of these ASCII case-insensitively, so the fold names the same thing. What it never touches is a name the author chose — a custom property, a custom ident such as an animation or grid-area name, an id, a class, a type selector, an attribute's value, or anything inside a substituted value. `@charset` is left as written, being read as bytes rather than matched, and `!important` is always written in lowercase because the printer writes the keyword rather than copying it.
2438+
* @since 5.111.0
2439+
*/
2440+
foldCase?: boolean;
24362441
/**
24372442
* 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.
24382443
* @since 5.111.0
@@ -2488,6 +2493,11 @@ export interface OptimizationMinimizeCss {
24882493
* @since 5.111.0
24892494
*/
24902495
rewriteDirSelector?: boolean;
2496+
/**
2497+
* Write an escaped identifier the shortest way that names the same thing, in a value or an id: `grid-area:\66oot` becomes `grid-area:foot` and `#\41 x` becomes `#Ax`. On by default, and exact: the escape and what replaces it are the same identifier. Off leaves every escape as the author wrote it, which is what a consumer comparing the text rather than reading the identifier needs.
2498+
* @since 5.111.0
2499+
*/
2500+
rewriteEscapes?: boolean;
24912501
/**
24922502
* Write each color in the shortest spelling of the same value: `#ffffff` -> `#fff`, `rgb(1 2 3)` -> `#010203`, a named color where the property takes no identifier of the author's own, and every polar and Lab function the target agrees with hex on. On by default.
24932503
* @since 5.110.0

‎lib/css/syntax.js‎

Lines changed: 29 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4062,6 +4062,8 @@ const TOP_LEVEL_CONSUMERS = {
40624062
* @typedef {object} CssTransformOptions
40634063
* @property {boolean=} colorFallbacks write a color the target cannot read as an extra declaration before it, in a spelling it does read
40644064
* @property {boolean=} lowerUnsupported write a spelling the target cannot read as one it can — the same value, said another way
4065+
* @property {boolean=} foldCase write a name that matches ASCII case-insensitively — an at-rule, property, pseudo, function, unit or keyword — in lowercase
4066+
* @property {boolean=} rewriteEscapes write an escaped identifier the shortest way that names it, in a value or an id
40654067
* @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
40664068
* @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
40674069
* @property {boolean=} mergeLonghands write a family of longhands as the one shorthand that sets them
@@ -5748,6 +5750,8 @@ const _isKeptComment = (src, start, end) => {
57485750
const _ALL_TRANSFORMS = Object.freeze({
57495751
colorFallbacks: true,
57505752
lowerUnsupported: true,
5753+
foldCase: true,
5754+
rewriteEscapes: true,
57515755
comments: "some",
57525756
resolveCustomAtRules: false,
57535757
mergeLonghands: true,
@@ -6619,7 +6623,7 @@ const _normalizeNumericToken = (text) => {
66196623
const lowered = unit.toLowerCase();
66206624
// A substituted value is handed back as the tokens it was written as, so the
66216625
// spelling there is the author's; `lowered` still answers the angle question.
6622-
if (lowered !== unit && !_inSubstitutedValue) {
6626+
if (lowered !== unit && !_inSubstitutedValue && _transforms.foldCase) {
66236627
// Only a unit that carried a capital can have a canonical spelling to look
66246628
// up, so the table is read for the shouted units alone.
66256629
const folded = asciiLowerCaseName(unit);
@@ -10564,7 +10568,7 @@ const _foldPseudoNames = (parts) => {
1056410568
// folds its own name, its argument being the author's.
1056510569
if (second !== -1 && parts[second] === ":") {
1056610570
const lowered = asciiLowerCaseName(part);
10567-
if (lowered !== part && !part.includes("(")) {
10571+
if (_transforms.foldCase && lowered !== part && !part.includes("(")) {
1056810572
part = lowered;
1056910573
parts[i] = lowered;
1057010574
}
@@ -14238,7 +14242,8 @@ const _rulePrelude = (path, writer, minify, outParts) => {
1423814242
// `@charset` is the one at-keyword read as bytes rather than matched
1423914243
// (CSS Syntax 3 §3.2), so lowercasing `@CHARSET` would turn a rule the
1424014244
// engine drops into one that sets the sheet's encoding.
14241-
const lower = minify && !equalsLowerCase(name, "charset");
14245+
const lower =
14246+
minify && _transforms.foldCase && !equalsLowerCase(name, "charset");
1424214247
parts.push(`@${lower ? asciiLowerCaseName(name) : name}`);
1424314248
}
1424414249
_appendChildTexts(path.node, writer, parts);
@@ -14265,7 +14270,7 @@ const _rulePrelude = (path, writer, minify, outParts) => {
1426514270
if (_transforms.resolveCustomAtRules && _customMedia.size !== 0) {
1426614271
_writeCustomMedia(parts);
1426714272
}
14268-
_lowercaseConditionParts(parts);
14273+
if (_transforms.foldCase) _lowercaseConditionParts(parts);
1426914274
if (_transforms.shortenMediaQueries) _dropImpliedMediaType(parts);
1427014275
}
1427114276
if (_rangeSpellingAllowed) _collapseRangeInterval(parts);
@@ -15100,11 +15105,12 @@ const printer = (path, writer) => {
1510015105
// As with a unit: a name already lowercase is its own answer, and only a
1510115106
// shouted one is looked up. The lookup key still folds inside a
1510215107
// substituted value; only the printed spelling stays as written.
15103-
const out = _inSubstitutedValue
15104-
? name
15105-
: fn === name
15106-
? fn
15107-
: CANONICAL_NAMES.get(fn) || fn;
15108+
const out =
15109+
_inSubstitutedValue || !_transforms.foldCase
15110+
? name
15111+
: fn === name
15112+
? fn
15113+
: CANONICAL_NAMES.get(fn) || fn;
1510815114
// An+B in a selector: `2n+1` is what `odd` names, and shorter written so.
1510915115
if (!path.inValue() && NTH_PSEUDO_FUNCTIONS.has(fn)) {
1511015116
return _minifyAnPlusB(out, inner);
@@ -15277,7 +15283,7 @@ const printer = (path, writer) => {
1527715283
// url, and every url but a shouted one folds to itself. Inside a
1527815284
// substituted value the spelling is the author's, so nothing is read.
1527915285
let head = null;
15280-
if (!_inSubstitutedValue) {
15286+
if (!_inSubstitutedValue && _transforms.foldCase) {
1528115287
for (let i = 0; i < open; i++) {
1528215288
const c = raw.charCodeAt(i);
1528315289
if (c >= CC_UPPER_A && c <= CC_UPPER_Z) {
@@ -15404,6 +15410,7 @@ const printer = (path, writer) => {
1540415410
// are read against the function's own grammar, where a name may be
1540515411
// the author's.
1540615412
if (
15413+
_transforms.foldCase &&
1540715414
lowered !== raw &&
1540815415
path.parent === _valueDeclaration &&
1540915416
_inKeywordOnlyValue()
@@ -15412,7 +15419,7 @@ const printer = (path, writer) => {
1541215419
if (folded !== raw) return folded;
1541315420
}
1541415421
}
15415-
return _minifyIdentEscapes(raw);
15422+
return _transforms.rewriteEscapes ? _minifyIdentEscapes(raw) : raw;
1541615423
}
1541715424
case T_SIMPLE_BLOCK: {
1541815425
const open = path.blockToken();
@@ -15432,7 +15439,7 @@ const printer = (path, writer) => {
1543215439
_appendChildTexts(path.node, writer, parts);
1543315440
}
1543415441
if (structural && open === "(" && _inMediaConditionPrelude) {
15435-
_lowercaseConditionParts(parts);
15442+
if (_transforms.foldCase) _lowercaseConditionParts(parts);
1543615443
if (_rangeSpellingAllowed) _useRangeSpelling(parts);
1543715444
}
1543815445
let trim =
@@ -15582,7 +15589,11 @@ const printer = (path, writer) => {
1558215589
// does not, which is what `custom` already stands for — nor does an
1558315590
// `@font-feature-values` sub-rule's, which names a feature value.
1558415591
const printedName =
15585-
minify && !custom && !_inFeatureValuesRule && lowered !== name
15592+
minify &&
15593+
_transforms.foldCase &&
15594+
!custom &&
15595+
!_inFeatureValuesRule &&
15596+
lowered !== name
1558615597
? asciiLowerCaseName(name)
1558715598
: name;
1558815599
return `${printedName}:${soft}${value}${important};`;
@@ -15870,7 +15881,11 @@ const printer = (path, writer) => {
1587015881
// former. Works at any value depth (e.g. inside a gradient). An id still
1587115882
// gets its escapes shortened; the `#` is held back so the name's first code
1587215883
// point is judged as first.
15873-
if (!path.inValue()) return `#${_minifyIdentEscapes(raw.slice(1))}`;
15884+
if (!path.inValue()) {
15885+
return _transforms.rewriteEscapes
15886+
? `#${_minifyIdentEscapes(raw.slice(1))}`
15887+
: raw;
15888+
}
1587415889
// Inside a function, only known color functions take color hashes —
1587515890
// and a substitution's fallback, which is not the function's own
1587615891
// argument but the property's value, so a hash there is as much a color

‎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: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3764,6 +3764,11 @@
37643764
"type": "boolean",
37653765
"added": "5.110.0"
37663766
},
3767+
"foldCase": {
3768+
"description": "Write a name that matches ASCII case-insensitively in lowercase: an at-rule name, a property name, a pseudo-class or pseudo-element name, a function name, a unit, and a keyword standing in a value whose grammar takes keywords alone. `@MEDIA`, `COLOR`, `:NTH-CHILD`, `URL(`, `1PX` and `currentColor` become `@media`, `color`, `:nth-child`, `url(`, `1px` and `currentcolor`. On by default, and exact: CSS matches every one of these ASCII case-insensitively, so the fold names the same thing. What it never touches is a name the author chose — a custom property, a custom ident such as an animation or grid-area name, an id, a class, a type selector, an attribute's value, or anything inside a substituted value. `@charset` is left as written, being read as bytes rather than matched, and `!important` is always written in lowercase because the printer writes the keyword rather than copying it.",
3769+
"type": "boolean",
3770+
"added": "5.111.0"
3771+
},
37673772
"lowerUnsupported": {
37683773
"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.",
37693774
"type": "boolean",
@@ -3819,6 +3824,11 @@
38193824
"type": "boolean",
38203825
"added": "5.111.0"
38213826
},
3827+
"rewriteEscapes": {
3828+
"description": "Write an escaped identifier the shortest way that names the same thing, in a value or an id: `grid-area:\\66oot` becomes `grid-area:foot` and `#\\41 x` becomes `#Ax`. On by default, and exact: the escape and what replaces it are the same identifier. Off leaves every escape as the author wrote it, which is what a consumer comparing the text rather than reading the identifier needs.",
3829+
"type": "boolean",
3830+
"added": "5.111.0"
3831+
},
38223832
"shortenColors": {
38233833
"description": "Write each color in the shortest spelling of the same value: `#ffffff` -> `#fff`, `rgb(1 2 3)` -> `#010203`, a named color where the property takes no identifier of the author's own, and every polar and Lab function the target agrees with hex on. On by default.",
38243834
"type": "boolean",

‎test/CssSyntax.unittest.js‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9708,6 +9708,71 @@ describe("CssSyntax minify — `@custom-media` / `@custom-selector`", () => {
97089708
});
97099709
});
97109710

9711+
describe("CssSyntax minify — `foldCase`", () => {
9712+
const shouted = [
9713+
[
9714+
"at-rule name",
9715+
"@MEDIA screen{a{color:red}}",
9716+
"@media screen{a{color:red}}"
9717+
],
9718+
["property name", ".a{COLOR:red}", ".a{color:red}"],
9719+
["pseudo name", ":NTH-CHILD(2n){color:red}", ":nth-child(2n){color:red}"],
9720+
["function name", ".a{background:URL(x.png)}", ".a{background:url(x.png)}"],
9721+
["unit", ".a{margin:1PX}", ".a{margin:1px}"],
9722+
["keyword value", ".a{color:currentColor}", ".a{color:currentcolor}"],
9723+
["media type", "@media SCREEN{a{color:red}}", "@media screen{a{color:red}}"]
9724+
];
9725+
9726+
for (const [what, source, folded] of shouted) {
9727+
it(`folds a ${what} on, and leaves it alone off`, () => {
9728+
expect(minifyForWith(source, ["chrome 120"], { foldCase: true })).toBe(
9729+
folded
9730+
);
9731+
expect(minifyForWith(source, ["chrome 120"], { foldCase: false })).toBe(
9732+
source
9733+
);
9734+
});
9735+
}
9736+
9737+
it("never folds a name the author chose", () => {
9738+
// A custom property, a custom ident and an id are case-sensitive, so the
9739+
// fold has to stop at each of them however loudly they are written.
9740+
const css =
9741+
"@keyframes Spin{0%{opacity:0}}.a{--Foo:1;animation-name:Spin;color:var(--Foo)}#Abc{grid-area:Foot}";
9742+
expect(minifyForWith(css, ["chrome 120"], { foldCase: true })).toBe(css);
9743+
});
9744+
9745+
it("leaves `@charset` as written", () => {
9746+
// It is read as bytes rather than matched, so folding it would turn a rule
9747+
// the engine drops into one that sets the sheet's encoding.
9748+
const css = '@CHARSET "utf-8";a{color:red}';
9749+
expect(
9750+
minifyForWith(css, ["chrome 120"], {
9751+
foldCase: true,
9752+
removeDeadRules: false
9753+
})
9754+
).toBe(css);
9755+
});
9756+
});
9757+
9758+
describe("CssSyntax minify — `rewriteEscapes`", () => {
9759+
const written = [
9760+
["a value's ident", ".a{grid-area:\\66oot}", ".a{grid-area:foot}"],
9761+
["an id", "#\\41 x{color:red}", "#Ax{color:red}"]
9762+
];
9763+
9764+
for (const [what, source, shorter] of written) {
9765+
it(`rewrites ${what} on, and leaves it alone off`, () => {
9766+
expect(
9767+
minifyForWith(source, ["chrome 120"], { rewriteEscapes: true })
9768+
).toBe(shorter);
9769+
expect(
9770+
minifyForWith(source, ["chrome 120"], { rewriteEscapes: false })
9771+
).toBe(source);
9772+
});
9773+
}
9774+
});
9775+
97119776
describe("CssSyntax minify — `@custom-selector`", () => {
97129777
const sheet = "@custom-selector :--h h1,h2;:--h{color:red}";
97139778
const on = { resolveCustomAtRules: true };

0 commit comments

Comments
 (0)