Skip to content

Commit 5b9d080

Browse files
fix(css): minify @import media queries and exponent numbers
Read an @import's media query as a @media one, space a @supports and/or where only a dropped comment parted it from a condition, and write a number with an exponent the shortest exact way, keeping it a <number> wherever an <integer> may be read.
1 parent 288b6b3 commit 5b9d080

13 files changed

Lines changed: 369 additions & 29 deletions

File tree

‎.changeset/037-css-supports-conditions.md‎

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

5-
Trim CSS `@supports` whitespace and keep `@import` supports() values as written.
5+
Minify CSS `@supports` and `@import` conditions, and numbers with an exponent.

‎lib/css/syntax-parser.js‎

Lines changed: 181 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4408,6 +4408,8 @@ const _walkValue = (node, parent, index, writer) => {
44084408
) {
44094409
enteredSupports = true;
44104410
_S._inSupportsPrelude = true;
4411+
// Its `(…)` tests a declaration, which no media feature spelling reaches.
4412+
_S._inMediaConditionPrelude = false;
44114413
}
44124414
for (let i = vs; i < ve; i++) {
44134415
_walkValue(_nodeRef(_flat[i]), node, i - vs, writer);
@@ -4417,7 +4419,10 @@ const _walkValue = (node, parent, index, writer) => {
44174419
_exitNode(node, parent, index, b, writer);
44184420
if (enteredMath) _S._mathFunctionDepth--;
44194421
if (enteredStepped) _S._steppedFunctionDepth--;
4420-
if (enteredSupports) _S._inSupportsPrelude = false;
4422+
if (enteredSupports) {
4423+
_S._inSupportsPrelude = false;
4424+
_S._inMediaConditionPrelude = true;
4425+
}
44214426
};
44224427

44234428
/**
@@ -4581,9 +4586,13 @@ const _enterAtRulePrelude = (i0) => {
45814586
if (atName === "supports") {
45824587
_S._inSupportsPrelude = true;
45834588
}
4584-
// `@media` and `@container` are the two preludes whose `(…)` holds a media
4585-
// feature, the only place the range spelling is a spelling of.
4586-
else if (atName === "media" || atName === "container") {
4589+
// `@media`, `@container` and an `@import`'s media query are where a `(…)`
4590+
// holds a media feature, the only place the range spelling is a spelling of.
4591+
else if (
4592+
atName === "media" ||
4593+
atName === "container" ||
4594+
atName === "import"
4595+
) {
45874596
_S._inMediaConditionPrelude = true;
45884597
}
45894598
};
@@ -7782,6 +7791,62 @@ const _normalizeNumber = (num) => {
77827791
return sign + s;
77837792
};
77847793

7794+
/**
7795+
* Write a number spelled with an exponent the shortest exact way: plainly where
7796+
* that is no longer (`0.2e2`→`20`), else on an integer mantissa (`10E3`→`1e4`).
7797+
* An exponent makes a `<number>`, never an `<integer>` (§4.3.12), so where that
7798+
* is read `keepNumberType` keeps a spelling that is still not an integer.
7799+
* @param {string} num numeric text with an exponent (may carry a sign)
7800+
* @param {boolean} keepNumberType whether an integer spelling is ruled out
7801+
* @returns {string} the normalized number
7802+
*/
7803+
const _normalizeExponent = (num, keepNumberType) => {
7804+
let sign = "";
7805+
let s = num;
7806+
const c0 = s.charCodeAt(0);
7807+
if (c0 === CC_PLUS_SIGN || c0 === CC_HYPHEN_MINUS) {
7808+
if (c0 === CC_HYPHEN_MINUS) sign = "-";
7809+
s = s.slice(1);
7810+
}
7811+
let e = s.indexOf("e");
7812+
if (e === -1) e = s.indexOf("E");
7813+
const mantissa = s.slice(0, e);
7814+
const dot = mantissa.indexOf(".");
7815+
let digits =
7816+
dot === -1 ? mantissa : mantissa.slice(0, dot) + mantissa.slice(dot + 1);
7817+
// Where the decimal point falls in `digits` once the exponent has moved it.
7818+
let point = (dot === -1 ? mantissa.length : dot) + Number(s.slice(e + 1));
7819+
let start = 0;
7820+
while (start < digits.length && digits.charCodeAt(start) === CC_0) start++;
7821+
let end = digits.length;
7822+
while (end > start && digits.charCodeAt(end - 1) === CC_0) end--;
7823+
if (start === end) return keepNumberType ? `${sign}0e0` : `${sign}0`;
7824+
point -= start;
7825+
digits = digits.slice(start, end);
7826+
const scale = point - digits.length;
7827+
const exponent = `${digits}e${scale}`;
7828+
// Built only when it could win, so `1e999` never writes a thousand zeros.
7829+
const plainLength =
7830+
point <= 0
7831+
? 1 - point + digits.length
7832+
: scale >= 0
7833+
? point
7834+
: digits.length + 1;
7835+
if (
7836+
plainLength > exponent.length ||
7837+
(keepNumberType && point >= digits.length)
7838+
) {
7839+
return sign + exponent;
7840+
}
7841+
const plain =
7842+
point <= 0
7843+
? `.${"0".repeat(-point)}${digits}`
7844+
: scale >= 0
7845+
? digits + "0".repeat(scale)
7846+
: `${digits.slice(0, point)}.${digits.slice(point)}`;
7847+
return sign + plain;
7848+
};
7849+
77857850
// WHY: Chromium serializes a computed number at 6 significant digits and lays a
77867851
// length out in 1/64px, so 6 digits sit below what a stylesheet can observe
77877852
// until the value reaches ~23000px, which no real one does. Measured across
@@ -10603,6 +10668,103 @@ const _writeCustomMedia = (parts) => {
1060310668
}
1060410669
};
1060510670

10671+
// WHY: CSS Conditional 3 as first published asked for whitespace on both sides
10672+
// of a `@supports` `and` / `or` (`S+ AND S+`), and engines built on it read
10673+
// `(a)and (b)` as invalid. So where a dropped comment was all that parted a `)`
10674+
// from one, a space is written back; the one after is `_join`'s already.
10675+
/**
10676+
* @param {string[]} parts the condition's printed parts, one per child from `offset`
10677+
* @param {Node} node the node whose children they are
10678+
* @param {number} offset the index of its first child's part
10679+
* @returns {void}
10680+
*/
10681+
const _spaceConditionKeywords = (parts, node, offset) => {
10682+
const i0 = _nodeIndex(node);
10683+
const first = _listStarts[i0];
10684+
const count = _listLens[i0];
10685+
// The child before, or -1 once whitespace has parted it from the next.
10686+
let previous = -1;
10687+
for (let k = 0; k < count; k++) {
10688+
const child = _flat[first + k];
10689+
if (_types[child] === T_WHITESPACE) {
10690+
previous = -1;
10691+
continue;
10692+
}
10693+
const part = parts[offset + k];
10694+
if (
10695+
previous !== -1 &&
10696+
_ends[_flat[first + previous]] !== _starts[child] &&
10697+
(equalsLowerCase(part, "and") || equalsLowerCase(part, "or"))
10698+
) {
10699+
const before = parts[offset + previous];
10700+
if (before.charCodeAt(before.length - 1) === CC_RIGHT_PARENTHESIS) {
10701+
parts[offset + k] = ` ${part}`;
10702+
}
10703+
}
10704+
previous = k;
10705+
}
10706+
};
10707+
10708+
/**
10709+
* Minify a media or container query's printed parts, in place, after its first
10710+
* part — the rule's name, which none of the passes read.
10711+
* @param {string[]} parts the prelude's printed parts
10712+
* @param {boolean} media whether it is a media query rather than a container one
10713+
* @returns {void}
10714+
*/
10715+
const _minifyMediaQueryParts = (parts, media) => {
10716+
// Only a media query's top level is media types and the keywords between
10717+
// them; `@container`'s leads with a container name, which is the author's own
10718+
// and case-sensitive.
10719+
if (media) {
10720+
// Before the passes below, which read the query this writes in.
10721+
if (_S._transforms.resolveCustomAtRules && _customMedia.size !== 0) {
10722+
_writeCustomMedia(parts);
10723+
}
10724+
if (_S._transforms.foldCase) _lowercaseConditionParts(parts);
10725+
if (_S._transforms.shortenMediaQueries) _dropImpliedMediaType(parts);
10726+
}
10727+
if (_S._rangeSpellingAllowed) {
10728+
_collapseRangeInterval(parts);
10729+
}
10730+
// A `@container` query is itself newer than the range spelling, so a target
10731+
// that reads one reads the other and there is nothing to lower.
10732+
else if (media && _S._transforms.lowerUnsupported) {
10733+
_useMinMaxSpelling(parts);
10734+
}
10735+
};
10736+
10737+
/**
10738+
* Where an `@import`'s media query starts in its printed parts: past the URL,
10739+
* then a `layer` and a `supports()` where written, each of which is one part.
10740+
* @param {string[]} parts the prelude's printed parts, `@import` first
10741+
* @returns {number} the index of the query's first part, or -1 when it has none
10742+
*/
10743+
const _importMediaStart = (parts) => {
10744+
// 0: the URL is next, 1: a `layer`, 2: a `supports()`, 3: the query.
10745+
let expecting = 0;
10746+
for (let i = 1; i < parts.length; i++) {
10747+
const part = parts[i];
10748+
if (part.length === 0 || part === _SEP) continue;
10749+
if (expecting === 0) {
10750+
expecting = 1;
10751+
continue;
10752+
}
10753+
const open = part.indexOf("(");
10754+
const name = asciiLowerCaseName(
10755+
unescapeIdentifier(open === -1 ? part : part.slice(0, open))
10756+
);
10757+
if (expecting === 1 && name === "layer") {
10758+
expecting = 2;
10759+
} else if (expecting !== 3 && open !== -1 && name === "supports") {
10760+
expecting = 3;
10761+
} else {
10762+
return i;
10763+
}
10764+
}
10765+
return -1;
10766+
};
10767+
1060610768
// One selector naming a `@custom-selector`, as printed after its `:`.
1060710769
const _CUSTOM_SELECTOR_NAME_RE = /^--[^\s(),]+$/;
1060810770

@@ -13929,31 +14091,25 @@ const _rulePrelude = (path, writer, minify, outParts) => {
1392914091
const media = name === "media";
1393014092
const container = name === "container";
1393114093
// Every prelude that is a chain of conditions, whichever rule states it.
14094+
const supports = equalsLowerCase(name, "supports");
1393214095
if (
1393314096
_S._transforms.shortenMediaQueries &&
13934-
(media || container || equalsLowerCase(name, "supports"))
14097+
(media || container || supports)
1393514098
) {
1393614099
_dropRepeatedConditions(parts);
1393714100
}
14101+
if (supports) _spaceConditionKeywords(parts, path.node, 1);
1393814102
if (media || container) {
13939-
// Only `@media`'s top level is media types and the keywords between
13940-
// them; `@container`'s leads with a container name, which is the
13941-
// author's own and case-sensitive.
13942-
if (media) {
13943-
// Before the passes below, which read the query this writes in.
13944-
if (_S._transforms.resolveCustomAtRules && _customMedia.size !== 0) {
13945-
_writeCustomMedia(parts);
13946-
}
13947-
if (_S._transforms.foldCase) _lowercaseConditionParts(parts);
13948-
if (_S._transforms.shortenMediaQueries) _dropImpliedMediaType(parts);
13949-
}
13950-
if (_S._rangeSpellingAllowed) {
13951-
_collapseRangeInterval(parts);
13952-
}
13953-
// A `@container` query is itself newer than the range spelling, so a
13954-
// target that reads one reads the other and there is nothing to lower.
13955-
else if (media && _S._transforms.lowerUnsupported) {
13956-
_useMinMaxSpelling(parts);
14103+
_minifyMediaQueryParts(parts, media);
14104+
} else if (name === "import") {
14105+
// Its media query follows the URL, `layer` and `supports()`, and is read
14106+
// as a `@media` one; the rest names or tests, and stays as it is.
14107+
const start = _importMediaStart(parts);
14108+
if (start !== -1) {
14109+
const query = parts.splice(start);
14110+
query.unshift("");
14111+
_minifyMediaQueryParts(query, true);
14112+
for (let i = 1; i < query.length; i++) parts.push(query[i]);
1395714113
}
1395814114
}
1395914115
}
@@ -15639,6 +15795,7 @@ module.exports._NO_RULE_SPANS = _NO_RULE_SPANS;
1563915795
module.exports._NUMERIC_RE = _NUMERIC_RE;
1564015796
module.exports._S = _S;
1564115797
module.exports._SEP = _SEP;
15798+
module.exports._spaceConditionKeywords = _spaceConditionKeywords;
1564215799
module.exports._TRIM_COMBINATORS = _TRIM_COMBINATORS;
1564315800
module.exports._TRIM_CONDITIONS = _TRIM_CONDITIONS;
1564415801
module.exports._TRIM_MATH = _TRIM_MATH;
@@ -15677,6 +15834,7 @@ module.exports._lowercaseConditionParts = _lowercaseConditionParts;
1567715834
module.exports._minifyColorFunction = _minifyColorFunction;
1567815835
module.exports._minifyPolarColorFunction = _minifyPolarColorFunction;
1567915836
module.exports._neededPrefixes = _neededPrefixes;
15837+
module.exports._normalizeExponent = _normalizeExponent;
1568015838
module.exports._normalizeNumber = _normalizeNumber;
1568115839
module.exports._opaqueEntry = _opaqueEntry;
1568215840
module.exports._openerKey = _openerKey;

‎lib/css/syntax-printer.js‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,7 @@ const {
185185
_minifyColorFunction,
186186
_minifyPolarColorFunction,
187187
_neededPrefixes,
188+
_normalizeExponent,
188189
_normalizeNumber,
189190
_opaqueEntry,
190191
_openerKey,
@@ -199,6 +200,7 @@ const {
199200
_shortestColor,
200201
_shortestFlexValue,
201202
_shorthandSlotsReadable,
203+
_spaceConditionKeywords,
202204
_splitSelectorList,
203205
_splitTopLevelArguments,
204206
_splitTopLevelSpaces,
@@ -462,6 +464,9 @@ const _keepFraction = (num) => {
462464
: out;
463465
};
464466

467+
// A unit that would continue a number's exponent: `e3`, `E-1`.
468+
const _EXPONENT_LIKE_UNIT_RE = /^e[+-]?\d/i;
469+
465470
/**
466471
* Normalize a number / dimension / percentage token: normalize the numeric part,
467472
* then round it and reach for a shorter equal unit. Neither is done inside a
@@ -496,7 +501,23 @@ const _normalizeNumericToken = (text) => {
496501
// The token as written is the answer 9 times in 10, so it is handed back
497502
// itself wherever nothing below changed a part of it.
498503
const numText = end === text.length ? text : text.slice(0, end);
499-
const num = _normalizeNumber(numText);
504+
let num = _normalizeNumber(numText);
505+
// `_normalizeNumber` hands an exponent back as written; a tested or
506+
// substituted one stays so, and elsewhere an unknown context may read `<integer>`.
507+
// A unit like `e3` would read as the exponent of a number written plainly.
508+
if (
509+
num === numText &&
510+
(num.includes("e") || num.includes("E")) &&
511+
!_EXPONENT_LIKE_UNIT_RE.test(written) &&
512+
!_S._inSupportsPrelude &&
513+
!_S._inCustomProperty &&
514+
_S._steppedFunctionDepth === 0
515+
) {
516+
num = _normalizeExponent(
517+
num,
518+
unit === "" && (_S._valueDeclaration === null || _inIntegerProperty())
519+
);
520+
}
500521
const same = num === numText && unit === written;
501522
// An all-zero fraction still makes this a `<number>`, not an `<integer>`
502523
// (`grid-row:1.0` computes `auto`). Property read last, it is the costlier one.
@@ -506,6 +527,7 @@ const _normalizeNumericToken = (text) => {
506527
dot !== -1 &&
507528
dot < end &&
508529
!num.includes(".") &&
530+
!num.includes("e") &&
509531
_inIntegerProperty()
510532
) {
511533
return _keepFraction(num);
@@ -4022,6 +4044,9 @@ const printer = (path, writer) => {
40224044
/** @type {string[]} */
40234045
const parts = [];
40244046
_appendChildTexts(path.node, writer, parts);
4047+
if (minify && trim === _TRIM_CONDITIONS) {
4048+
_spaceConditionKeywords(parts, path.node, 0);
4049+
}
40254050
// A selector function's argument is a selector like the prelude's, so
40264051
// the universal a compound implies says nothing there either — except
40274052
// under test in a `@supports` condition, where only whitespace goes.
@@ -4408,6 +4433,9 @@ const printer = (path, writer) => {
44084433
if (_S._transforms.foldCase) _lowercaseConditionParts(parts);
44094434
if (_S._rangeSpellingAllowed) _useRangeSpelling(parts);
44104435
}
4436+
if (minify && structural && open === "(" && _S._inSupportsPrelude) {
4437+
_spaceConditionKeywords(parts, path.node, 0);
4438+
}
44114439
let trim =
44124440
minify && _S._mathFunctionDepth !== 0 ? _TRIM_MATH : _TRIM_NOTHING;
44134441
if (structural && open === "(") {

‎test/configCases/css/minimize-supports/__snapshots__/ConfigCacheTest.snap‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,6 @@ Array [
1818
"/*! kept: the selector under test */@supports selector(*.a:HOVER){.k03{color:red}}",
1919
"/*! kept: calc() needs its spaces */@supports (width:calc(1px + 2px)){.k04{color:red}}",
2020
"/*! kept: a value that is newer when shortened */@supports (color:rgba(0,0,0,.5)){.k05{color:red}}",
21+
"/*! supports: a space where a comment parted a condition and its keyword */@supports (display:grid) and (gap:1px){.s12{color:red}}",
2122
]
2223
`;

‎test/configCases/css/minimize-supports/__snapshots__/ConfigTest.snap‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,6 @@ Array [
1818
"/*! kept: the selector under test */@supports selector(*.a:HOVER){.k03{color:red}}",
1919
"/*! kept: calc() needs its spaces */@supports (width:calc(1px + 2px)){.k04{color:red}}",
2020
"/*! kept: a value that is newer when shortened */@supports (color:rgba(0,0,0,.5)){.k05{color:red}}",
21+
"/*! supports: a space where a comment parted a condition and its keyword */@supports (display:grid) and (gap:1px){.s12{color:red}}",
2122
]
2223
`;

‎test/configCases/css/minimize-supports/style.css‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,5 @@
3434
@supports (width: calc(1px + 2px)) { .k04 { color: red } }
3535
/*! kept: a value that is newer when shortened */
3636
@supports (color: rgba(0, 0, 0, .5)) { .k05 { color: red } }
37+
/*! supports: a space where a comment parted a condition and its keyword */
38+
@supports (display: grid)/* c */and/* d */(gap: 1px) { .s12 { color: red } }

‎test/configCases/css/minimize-timing-functions/__snapshots__/ConfigCacheTest.snap‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ Array [
1010
"/*! timing: cubic-bezier(0, 0, 0.58, 1) */.t06{animation-timing-function:ease-out}",
1111
"/*! timing: cubic-bezier(0.42, 0, 0.58, 1) */.t07{animation-timing-function:ease-in-out}",
1212
"/*! timing: cubic-bezier(0.58, 0.2, 0.11, 1.2) */.t08{animation-timing-function:cubic-bezier(.58,.2,.11,1.2)}",
13-
"/*! timing: cubic-bezier(0.250, 1e-1px, 0.250, 1) */.t09{animation-timing-function:cubic-bezier(.25,1e-1px,.25,1)}",
13+
"/*! timing: cubic-bezier(0.250, 1e-1px, 0.250, 1) */.t09{animation-timing-function:cubic-bezier(.25,.1px,.25,1)}",
1414
"/*! timing: cubic-bezier(0.25, var(--foo), 0.25, 1) */.t10{animation-timing-function:cubic-bezier(.25,var(--foo),.25,1)}",
1515
"/*! timing: cubic-bezier(var(--a), var(--b), var(--c), var(--d)) */.t11{animation-timing-function:cubic-bezier(var(--a),var(--b),var(--c),var(--d))}",
1616
"/*! timing: cubic-bezier() */.t12{animation-timing-function:cubic-bezier()}",

‎test/configCases/css/minimize-timing-functions/__snapshots__/ConfigTest.snap‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ Array [
1010
"/*! timing: cubic-bezier(0, 0, 0.58, 1) */.t06{animation-timing-function:ease-out}",
1111
"/*! timing: cubic-bezier(0.42, 0, 0.58, 1) */.t07{animation-timing-function:ease-in-out}",
1212
"/*! timing: cubic-bezier(0.58, 0.2, 0.11, 1.2) */.t08{animation-timing-function:cubic-bezier(.58,.2,.11,1.2)}",
13-
"/*! timing: cubic-bezier(0.250, 1e-1px, 0.250, 1) */.t09{animation-timing-function:cubic-bezier(.25,1e-1px,.25,1)}",
13+
"/*! timing: cubic-bezier(0.250, 1e-1px, 0.250, 1) */.t09{animation-timing-function:cubic-bezier(.25,.1px,.25,1)}",
1414
"/*! timing: cubic-bezier(0.25, var(--foo), 0.25, 1) */.t10{animation-timing-function:cubic-bezier(.25,var(--foo),.25,1)}",
1515
"/*! timing: cubic-bezier(var(--a), var(--b), var(--c), var(--d)) */.t11{animation-timing-function:cubic-bezier(var(--a),var(--b),var(--c),var(--d))}",
1616
"/*! timing: cubic-bezier() */.t12{animation-timing-function:cubic-bezier()}",

‎test/configCases/css/minimize-values/__snapshots__/ConfigCacheTest.snap‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,5 +222,8 @@ Array [
222222
keyword it would be replaced by is a different computed value under one */.initial-length{outline-width:initial;border-top-width:initial;font-size:initial}",
223223
"/*! a keyword that is not a length is the value \`initial\` computes to */.initial-keyword{float:none;display:inline}",
224224
"/*! \`mdn-data\` writes this one's initial as prose, so the keyword is supplemented */.initial-prose{text-align:start}",
225+
"/*! scientific: an exponent is written plainly where that is no longer */.sci01{opacity:2;line-height:2.5;width:.001px;font-weight:400}",
226+
"/*! scientific: ...else on an integer mantissa */.sci02{width:1e4px;margin-left:15e-8px;transition-duration:1s}",
227+
"/*! scientific: an integer property keeps a <number>, which it throws out */.sci03{z-index:2e0;order:1e0;column-count:3e0}",
225228
]
226229
`;

0 commit comments

Comments
 (0)