Skip to content

Commit ffdf76d

Browse files
feat(css): write a fallback for a color the browserslist target cannot read
A `lab()` / `lch()` / `oklab()` / `oklch()` / `hwb()` color only converts to hex where the two agree exactly, so a target reading none of those functions was left with a declaration it drops. The color each names is now written as an extra declaration before it — `color:#c65d06;color:oklch(59.686% .15619 49.7694)` — so the modern spelling still reaches the engines that read it while the others get a color. The two refusals the conversion makes are about replacing the function, not standing before it: a fallback is only ever read where there is no better answer, so it clips into the sRGB gamut and takes whichever byte rounding picks, and writes an `rgba()` where the target has no hex alpha either. Nothing is written where the author already set the property earlier in the block, where the color holds a relative reference or a call this cannot fold, or where the fallback would still name a function the target cannot read — the engine drops such a fallback exactly as it drops the declaration it precedes. `optimization.minimize.css.colorFallbacks` turns it off.
1 parent 44718ec commit ffdf76d

13 files changed

Lines changed: 617 additions & 223 deletions

File tree

‎.changeset/010-css-lower-unsupported-spellings.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 a CSS spelling the `browserslist` target cannot read into one it can.
5+
Lower a CSS spelling a target cannot read and write a color fallback before one.

‎declarations/WebpackOptions.d.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2413,6 +2413,11 @@ export interface OptimizationMinimizeOptions {
24132413
* @since 5.110.0
24142414
*/
24152415
export interface OptimizationMinimizeCss {
2416+
/**
2417+
* Write a color the `browserslist` target cannot read as an extra declaration before the one naming it, in a spelling it does read: `color: oklch(59.686% 0.15619 49.7694)` is written as `color: #c65d06` and then the `oklch()` itself, so an engine reading neither the Lab family nor `hwb()` is left with a color rather than with nothing. The fallback is that color clipped into the sRGB gamut and rounded, which the declaration standing after it corrects wherever it is read. Nothing is written where the author already set the property earlier in the same block, where the color holds a substitution or a relative reference this cannot fold, or where the fallback would still name a function the target cannot read. On by default, and only in effect for a `browserslist` target — any other target names no browsers to answer for.
2418+
* @since 5.111.0
2419+
*/
2420+
colorFallbacks?: boolean;
24162421
/**
24172422
* Which comments survive. `"some"`, the default, keeps a `/*!` banner and a comment annotated `@license` or `@preserve`; `true` (or `"all"`) keeps every comment and `false` keeps none; a string is read as a regular expression source, and it, a `RegExp` or a `(comment) => boolean` predicate is asked about each comment's own text and keeps the ones it accepts — standing in for the default rule rather than beside it, as terser's `format.comments` does, so a pattern that names nothing else drops the ones `"some"` would have kept. A `/*#` source-map pragma is a link rather than a comment, so `"some"` and `"all"` keep it; `false`, a pattern or a predicate decides it like any other. A predicate is handed to the minimizer's worker pool as source, so it must not close over anything.
24182423
* @since 5.110.0

‎lib/css/data.js‎

Lines changed: 217 additions & 204 deletions
Large diffs are not rendered by default.

‎lib/css/syntax.js‎

Lines changed: 168 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2022,6 +2022,13 @@ const _setupParse = (input, lc) => {
20222022
_hexAlphaAllowed = true;
20232023
_doublePositionAllowed = true;
20242024
_displayTwoValuesAllowed = true;
2025+
_colorFunctionAllowed = true;
2026+
_colorMixAllowed = true;
2027+
_hwbColorsAllowed = true;
2028+
_labColorsAllowed = true;
2029+
_lightDarkAllowed = true;
2030+
_oklabColorsAllowed = true;
2031+
_colorFallbacksNeeded = false;
20252032
_insetShorthandAllowed = true;
20262033
_rangeSpellingAllowed = true;
20272034
_placeShorthandAllowed = true;
@@ -4013,6 +4020,7 @@ const TOP_LEVEL_CONSUMERS = {
40134020
* What the minifying printer may rewrite. Every entry is on unless it is
40144021
* `false`, so a document one transform breaks can still be minified by the rest.
40154022
* @typedef {object} CssTransformOptions
4023+
* @property {boolean=} colorFallbacks write a color the target cannot read as an extra declaration before it, in a spelling it does read
40164024
* @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
40174025
* @property {boolean=} mergeLonghands write a family of longhands as the one shorthand that sets them
40184026
* @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
@@ -5680,6 +5688,7 @@ const _isKeptComment = (src, start, end) => {
56805688
// what the walk-only passes hold. Frozen, since it is shared rather than copied.
56815689
/** @type {Required<CssTransformOptions>} */
56825690
const _ALL_TRANSFORMS = Object.freeze({
5691+
colorFallbacks: true,
56835692
comments: "some",
56845693
mergeLonghands: true,
56855694
mergeRules: true,
@@ -5842,6 +5851,14 @@ const grammar = (input, visitors, writer, options) => {
58425851
_hexAlphaAllowed = _targetSupports("colorHexAlpha");
58435852
_doublePositionAllowed = _targetSupports("gradientDoublePosition");
58445853
_displayTwoValuesAllowed = _targetSupports("displayTwoValues");
5854+
_colorFunctionAllowed = _targetSupports("colorFunction");
5855+
_colorMixAllowed = _targetSupports("colorMix");
5856+
_hwbColorsAllowed = _targetSupports("hwbColors");
5857+
_labColorsAllowed = _targetSupports("labColors");
5858+
_lightDarkAllowed = _targetSupports("lightDark");
5859+
_oklabColorsAllowed = _targetSupports("oklabColors");
5860+
_colorFallbacksNeeded =
5861+
!_hwbColorsAllowed || !_labColorsAllowed || !_oklabColorsAllowed;
58455862
_insetShorthandAllowed = _targetSupports("insetShorthand");
58465863
_rangeSpellingAllowed = _targetSupports("mediaQueryRange");
58475864
_placeShorthandAllowed = _targetSupports("placeShorthand");
@@ -7026,8 +7043,10 @@ const _shortestAlphaColor = (r, g, b, a) => {
70267043
* The shortest `<alpha-value>` naming one of the 256 bytes a hex alpha spells.
70277044
* The engine quantizes the channel to 8 bits, so any decimal that rounds back to
70287045
* the same byte is the same color — `.5` for `80`. Every byte round-trips at
7029-
* three decimals or fewer, so the search always ends.
7030-
* @param {number} a alpha 0..255
7046+
* three decimals or fewer, so the search always ends. `255` is not one of them:
7047+
* an opaque color is written without an alpha at all, so both callers take that
7048+
* path before reaching here.
7049+
* @param {number} a alpha 0..254
70317050
* @returns {string} the alpha text
70327051
*/
70337052
const _alphaByteText = (a) => {
@@ -8242,13 +8261,24 @@ const _LAB_SCALES = new Map([
82428261
* gamut keeps its function too: hex cannot express it, so converting would clip
82438262
* it to a different color. Both are limitations, not correctness gaps — the
82448263
* declined share is small and every other minifier converts them regardless.
8264+
*
8265+
* Both guards are about *replacing* the function. A fallback stands before the
8266+
* function rather than in its place, so it is only ever read by an engine with
8267+
* no better answer: `forFallback` clamps into the gamut and takes whichever byte
8268+
* rounding picks, and writes an `rgba()` where the target has no hex alpha.
82458269
* @param {string} fn the lowercased function name
82468270
* @param {string} inner the already-joined argument text
82478271
* @param {boolean} hexAlpha whether the target reads a 4-/8-digit hex (see `output.environment`)
8272+
* @param {boolean=} forFallback whether this is the fallback for a function the target cannot read, rather than a replacement for one it can
82488273
* @returns {string | null} the shortest color, or null to keep the function
82498274
*/
8250-
const _minifyPolarColorFunction = (fn, inner, hexAlpha) => {
8251-
if (!_transforms.shortenColors) return null;
8275+
const _minifyPolarColorFunction = (
8276+
fn,
8277+
inner,
8278+
hexAlpha,
8279+
forFallback = false
8280+
) => {
8281+
if (!forFallback && !_transforms.shortenColors) return null;
82528282
const isHsl = fn === "hsl" || fn === "hsla";
82538283
const labScale = _LAB_SCALES.get(fn);
82548284
if (!isHsl && fn !== "hwb" && labScale === undefined) return null;
@@ -8264,8 +8294,8 @@ const _minifyPolarColorFunction = (fn, inner, hexAlpha) => {
82648294
alpha = Number(parsed[1]) / (parsed[2] === "%" ? 100 : 1);
82658295
if (!(alpha >= 0 && alpha <= 1)) return null;
82668296
// A partly transparent color needs the hex-alpha spelling, which is the
8267-
// target's question, not this one's.
8268-
if (alpha < 1 && !hexAlpha) return null;
8297+
// target's question, not this one's — a fallback answers it with `rgba()`.
8298+
if (alpha < 1 && !hexAlpha && !forFallback) return null;
82698299
}
82708300
/** @type {number[]} */
82718301
let raw;
@@ -8317,24 +8347,102 @@ const _minifyPolarColorFunction = (fn, inner, hexAlpha) => {
83178347
/** @type {number[]} */
83188348
const channels = [];
83198349
for (const value of raw) {
8320-
const byte = _channelByte(value, margin);
8350+
const byte = forFallback ? _clamp255(value) : _channelByte(value, margin);
83218351
if (byte === null) return null;
83228352
channels.push(byte);
83238353
}
8324-
if (alpha < 1) {
8325-
// The alpha is the author's own number rather than a conversion's output, so
8326-
// it takes no boundary guard: the engine quantizes it to 8 bits either way,
8327-
// exactly as `rgba()`'s does.
8328-
return _shortestAlphaColor(
8329-
channels[0],
8330-
channels[1],
8331-
channels[2],
8332-
_clamp255(alpha * 255)
8333-
);
8354+
// The alpha is the author's own number rather than a conversion's output, so
8355+
// it takes no boundary guard: the engine quantizes it to 8 bits either way,
8356+
// exactly as `rgba()`'s does — and one that quantizes to `255` is the opaque
8357+
// color, which is written without an alpha at all.
8358+
const opacity = alpha < 1 ? _clamp255(alpha * 255) : 255;
8359+
if (opacity !== 255) {
8360+
return hexAlpha
8361+
? _shortestAlphaColor(channels[0], channels[1], channels[2], opacity)
8362+
: `rgba(${channels[0]},${channels[1]},${channels[2]},${_alphaByteText(
8363+
opacity
8364+
)})`;
83348365
}
83358366
return _shortestColor(channels[0], channels[1], channels[2]);
83368367
};
83378368

8369+
// One color function a target may not read, printed with no call of its own
8370+
// inside it — a relative color or a `calc()` argument is not one to fold. The
8371+
// leading character keeps `--my-lab(1)` from reading as `lab(1)`.
8372+
const _FALLBACK_COLOR_FUNCTION_RE =
8373+
/(^|[^-\w])(hwb|lab|lch|oklab|oklch)\(([^()]*)\)/gi;
8374+
8375+
/**
8376+
* Whether a color function is one some target does not read, so a declaration
8377+
* naming it needs a fallback before it — and a fallback still naming one is no
8378+
* fallback. Only the names `_FALLBACK_COLOR_FUNCTION_RE` and
8379+
* `_UNREADABLE_COLOR_CALL_RE` match reach here.
8380+
* @param {string} fn the lowercased function name
8381+
* @returns {boolean} true when the target cannot read it
8382+
*/
8383+
const _unreadableColorFunction = (fn) => {
8384+
if (fn === "hwb") return !_hwbColorsAllowed;
8385+
if (fn === "lab" || fn === "lch") return !_labColorsAllowed;
8386+
if (fn === "oklab" || fn === "oklch") return !_oklabColorsAllowed;
8387+
if (fn === "color") return !_colorFunctionAllowed;
8388+
if (fn === "color-mix") return !_colorMixAllowed;
8389+
return !_lightDarkAllowed;
8390+
};
8391+
8392+
// The name of any color function a target may not read, wherever it stands —
8393+
// the arguments are not read here, so one holding a call of its own still
8394+
// matches. `color-mix` before `color`, which is its prefix.
8395+
const _UNREADABLE_COLOR_CALL_RE =
8396+
/(^|[^-\w])(hwb|lab|lch|oklab|oklch|color-mix|color|light-dark)\(/gi;
8397+
8398+
/**
8399+
* The declaration to write before one whose value names a color function the
8400+
* target cannot read: the same declaration with every such color written in a
8401+
* spelling it does read. Null where there is none to write.
8402+
*
8403+
* A fallback still naming a function the target cannot read is no fallback — the
8404+
* engine drops it just as it drops the declaration it stands before — so a color
8405+
* this cannot fold whole (a relative color, an argument holding a `calc()`, one
8406+
* nested in a `color-mix()`) leaves the declaration alone rather than adding
8407+
* bytes nothing reads.
8408+
* @param {string} text one printed declaration
8409+
* @param {number} colon where its `:` sits
8410+
* @returns {string | null} the fallback declaration, or null
8411+
*/
8412+
const _colorFallbackDeclaration = (text, colon) => {
8413+
// A custom property's value is handed back as written, and holds no
8414+
// declaration of its own to stand before.
8415+
if (text.charCodeAt(1) === CC_HYPHEN_MINUS) return null;
8416+
const value = text.slice(colon + 1);
8417+
let folded = false;
8418+
const written = value.replace(
8419+
_FALLBACK_COLOR_FUNCTION_RE,
8420+
(whole, before, name, inner) => {
8421+
const fn = asciiLowerCaseName(name);
8422+
if (!_unreadableColorFunction(fn)) return whole;
8423+
const color = _minifyPolarColorFunction(
8424+
fn,
8425+
inner,
8426+
_hexAlphaAllowed,
8427+
true
8428+
);
8429+
if (color === null) return whole;
8430+
folded = true;
8431+
return before + color;
8432+
}
8433+
);
8434+
if (!folded) return null;
8435+
_UNREADABLE_COLOR_CALL_RE.lastIndex = 0;
8436+
for (
8437+
let match = _UNREADABLE_COLOR_CALL_RE.exec(written);
8438+
match !== null;
8439+
match = _UNREADABLE_COLOR_CALL_RE.exec(written)
8440+
) {
8441+
if (_unreadableColorFunction(asciiLowerCaseName(match[2]))) return null;
8442+
}
8443+
return text.slice(0, colon + 1) + written;
8444+
};
8445+
83388446
// Some mobile WebKit builds honor `-webkit-tap-highlight-color:rgba(0,0,0,0)`
83398447
// but ignore the equivalent `transparent`, so that one property keeps the
83408448
// function form (cssnano guards the same property).
@@ -12361,6 +12469,34 @@ const _composeBlockBody = (path, decls, rules, writer, minify, nl, owner) => {
1236112469
}
1236212470
}
1236312471
}
12472+
// A color the target cannot read gets the declaration it names written again
12473+
// before it, in a spelling it does. Only where the selection names a function
12474+
// no target reads, which keeps this off every other block.
12475+
/** @type {Map<number, string> | null} */
12476+
let addedFallback = null;
12477+
if (minify && _colorFallbacksNeeded && _transforms.colorFallbacks) {
12478+
/** @type {Set<string>} */
12479+
const alreadyWritten = new Set();
12480+
for (let i = 0; i < items.length; i++) {
12481+
const text = texts[i];
12482+
if (path.type(items[i]) !== T_DECLARATION || text.length === 0) continue;
12483+
// One the body never writes is no fallback the author left.
12484+
if (superseded !== null && superseded.has(i)) continue;
12485+
if (droppedPrefix !== null && droppedPrefix.has(i)) continue;
12486+
const colon = text.indexOf(":");
12487+
const property = _printedProperty(text, colon);
12488+
// An earlier declaration of the same property already is the fallback the
12489+
// author wrote, whatever it says.
12490+
if (!alreadyWritten.has(property) && text.includes("(")) {
12491+
const fallback = _colorFallbackDeclaration(text, colon);
12492+
if (fallback !== null) {
12493+
if (addedFallback === null) addedFallback = new Map();
12494+
addedFallback.set(i, fallback);
12495+
}
12496+
}
12497+
alreadyWritten.add(property);
12498+
}
12499+
}
1236412500
// Every child has printed by now, so the sibling set they shared goes.
1236512501
if (_seenPrefixRules !== null && owner !== null) {
1236612502
_seenPrefixRules.delete(owner);
@@ -12391,6 +12527,12 @@ const _composeBlockBody = (path, decls, rules, writer, minify, nl, owner) => {
1239112527
if (text.length === 0) continue;
1239212528
if (superseded !== null && superseded.has(i)) continue;
1239312529
if (deadPrefixed !== null && deadPrefixed.has(items[i])) continue;
12530+
// Before the vendor spellings: this one is the oldest of the set, and the
12531+
// only one an engine reading none of the others is left with.
12532+
if (addedFallback !== null) {
12533+
const fallback = addedFallback.get(i);
12534+
if (fallback !== undefined) body += nl + fallback;
12535+
}
1239412536
if (addedPrefix !== null) {
1239512537
const add = addedPrefix.get(i);
1239612538
if (add !== undefined) body += add;
@@ -13488,6 +13630,15 @@ let _hexAlphaAllowed = true;
1348813630
let _doublePositionAllowed = true;
1348913631
// CSS Position 3 added `inset` long after the four longhands it merges, CSS 1.
1349013632
let _displayTwoValuesAllowed = true;
13633+
let _colorFunctionAllowed = true;
13634+
let _colorMixAllowed = true;
13635+
let _hwbColorsAllowed = true;
13636+
let _labColorsAllowed = true;
13637+
let _lightDarkAllowed = true;
13638+
let _oklabColorsAllowed = true;
13639+
// Whether any color function this print may meet is one the target cannot read,
13640+
// so a block holding none is never scanned for a fallback.
13641+
let _colorFallbacksNeeded = false;
1349113642
let _insetShorthandAllowed = true;
1349213643
let _rangeSpellingAllowed = true;
1349313644
// CSS Box Alignment 3's `place-*`, newer than the `align-*` / `justify-*` pairs.

‎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 & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3731,6 +3731,11 @@
37313731
"type": "object",
37323732
"additionalProperties": false,
37333733
"properties": {
3734+
"colorFallbacks": {
3735+
"description": "Write a color the `browserslist` target cannot read as an extra declaration before the one naming it, in a spelling it does read: `color: oklch(59.686% 0.15619 49.7694)` is written as `color: #c65d06` and then the `oklch()` itself, so an engine reading neither the Lab family nor `hwb()` is left with a color rather than with nothing. The fallback is that color clipped into the sRGB gamut and rounded, which the declaration standing after it corrects wherever it is read. Nothing is written where the author already set the property earlier in the same block, where the color holds a substitution or a relative reference this cannot fold, or where the fallback would still name a function the target cannot read. On by default, and only in effect for a `browserslist` target — any other target names no browsers to answer for.",
3736+
"type": "boolean",
3737+
"added": "5.111.0"
3738+
},
37343739
"comments": {
37353740
"description": "Which comments survive. `\"some\"`, the default, keeps a `/*!` banner and a comment annotated `@license` or `@preserve`; `true` (or `\"all\"`) keeps every comment and `false` keeps none; a string is read as a regular expression source, and it, a `RegExp` or a `(comment) => boolean` predicate is asked about each comment's own text and keeps the ones it accepts — standing in for the default rule rather than beside it, as terser's `format.comments` does, so a pattern that names nothing else drops the ones `\"some\"` would have kept. A `/*#` source-map pragma is a link rather than a comment, so `\"some\"` and `\"all\"` keep it; `false`, a pattern or a predicate decides it like any other. A predicate is handed to the minimizer's worker pool as source, so it must not close over anything.",
37363741
"anyOf": [

0 commit comments

Comments
 (0)