Skip to content

Commit db24532

Browse files
feat(css): expose the declined color conversions as an option (#22157)
`shortenColors` writes a polar or Lab color as hex only where webpack can prove an engine's own conversion lands on the same bytes, and keeps the function in the two places it cannot: a channel too near a `.5` boundary for two implementations to round it alike, and a color outside the sRGB gamut, which hex can only clip. `optimization.minimize.css.convertApproximateColors` takes the nearest byte in both. It is off by default, and the two halves are not the same trade: on the boundary it writes the byte esbuild, lightningcss and cssnano write anyway — `hsl(134,50%,50%)` is `#40bf5e` for all of them — while outside the gamut it goes further than any of them, lightningcss keeping the function there and writing a fallback before it, which is what `colorFallbacks` already does. The `colorFallbacks` path had rounded and clipped this way all along, so the one guard left standing is `a98-rgb` / `prophoto-rgb`: an engine reads those through a transfer of its own, so the hex would name a color it never paints rather than a near one.
1 parent 5c91ba0 commit db24532

20 files changed

Lines changed: 226 additions & 21 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+
Add `optimization.minimize.css.convertApproximateColors`.

‎lib/css/cssMinify.js‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
* re-resolves in the worker — via the installed package, or the dev self-link.
3434
* @param {{ [file: string]: string | Buffer }} input a single `{ filename: code }` entry; a `Buffer` is read as UTF-8
3535
* @param {object=} sourceMap the asset's input source map — the plugin chains it onto the map returned here, so it isn't read directly
36-
* @param {{ as?: "stylesheet" | "block-contents", environment?: CssEnvironment, convertLengthUnits?: boolean, mergeDistantRules?: boolean, rewriteCustomProperties?: boolean, unusedSymbols?: string[], pseudoClasses?: { [name: string]: string }, renderEmbeddedSource?: AsyncEmbeddedSourceRenderer } & CssTransformOptions=} minimizerOptions minimizer options — `environment` carries the target's CSS abilities (see `output.environment`), so a spelling the target cannot read is not reached for; the rest is `optimization.minimize.css` (e.g. `convertLengthUnits`, and the per-transform switches). `renderEmbeddedSource` minifies source this stylesheet embeds, and may be asynchronous: one parse serves both it and the output
36+
* @param {{ as?: "stylesheet" | "block-contents", environment?: CssEnvironment, convertLengthUnits?: boolean, convertApproximateColors?: boolean, mergeDistantRules?: boolean, rewriteCustomProperties?: boolean, unusedSymbols?: string[], pseudoClasses?: { [name: string]: string }, renderEmbeddedSource?: AsyncEmbeddedSourceRenderer } & CssTransformOptions=} minimizerOptions minimizer options — `environment` carries the target's CSS abilities (see `output.environment`), so a spelling the target cannot read is not reached for; the rest is `optimization.minimize.css` (e.g. `convertLengthUnits`, and the per-transform switches). `renderEmbeddedSource` minifies source this stylesheet embeds, and may be asynchronous: one parse serves both it and the output
3737
* @returns {Promise<{ code: string, map?: SourceMap, warnings?: (Error | string)[], errors?: (Error | string)[] }>} the minified CSS, its input->output source map (one anchor for the whole of a `block-contents` print, which is emitted as one piece), and what a renderer reported over what this embeds
3838
*/
3939
const cssMinify = async (input, sourceMap, minimizerOptions = {}) => {
@@ -42,9 +42,9 @@ const cssMinify = async (input, sourceMap, minimizerOptions = {}) => {
4242
require(/** @type {string} */ ("webpack"))
4343
);
4444

45-
// TODO expose the remaining declined transforms on `optimization.minimize.css`
46-
// like `convertLengthUnits` — the switches below turn off what webpack does
47-
// make, not what it declines.
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.
4848

4949
// WHY: each transform webpack declines is on in other minifiers, and each costs
5050
// something measured.
@@ -55,11 +55,11 @@ const cssMinify = async (input, sourceMap, minimizerOptions = {}) => {
5555
// Adjacent rules sharing a block do join, nothing being between them to step
5656
// over — only where every selector is a shape each engine parses, since one
5757
// it cannot invalidates the whole list and loses the rest with it.
58-
// - Two color conversions are declined rather than guessed. Every polar and Lab
59-
// function converts to hex, except a channel landing near a `.5` boundary,
60-
// where implementations round opposite ways (which is why esbuild and
61-
// lightningcss emit different bytes for `hwb(194 0% 0%)`), and a Lab-family
62-
// color outside the sRGB gamut, which hex would clip rather than respell.
58+
// - The two declined color conversions are `convertApproximateColors`, off
59+
// until asked for: a channel landing near a `.5` boundary, where
60+
// implementations round opposite ways (which is why esbuild and lightningcss
61+
// emit different bytes for `hwb(194 0% 0%)`), and a Lab-family color outside
62+
// the sRGB gamut, which hex clips rather than respells.
6363

6464
// WHY: which longhand families merge into their shorthand is decided in
6565
// `tooling/generate-css-data.js`, where three kinds are excluded for good
@@ -95,6 +95,7 @@ const cssMinify = async (input, sourceMap, minimizerOptions = {}) => {
9595
as,
9696
environment,
9797
convertLengthUnits,
98+
convertApproximateColors,
9899
mergeDistantRules,
99100
rewriteCustomProperties,
100101
unusedSymbols,
@@ -111,6 +112,7 @@ const cssMinify = async (input, sourceMap, minimizerOptions = {}) => {
111112
content: code,
112113
environment,
113114
convertLengthUnits,
115+
convertApproximateColors,
114116
mergeDistantRules,
115117
rewriteCustomProperties,
116118
unusedSymbols,

‎lib/css/syntax.js‎

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2036,6 +2036,7 @@ const _setupParse = (input, lc) => {
20362036
_mathFunctionDepth = 0;
20372037
_steppedFunctionDepth = 0;
20382038
_convertLengthUnits = false;
2039+
_convertApproximateColors = false;
20392040
_unusedSymbols = null;
20402041
_unusedRules = null;
20412042
_pseudoClasses = null;
@@ -4116,6 +4117,7 @@ const TOP_LEVEL_CONSUMERS = {
41164117
* @property {string=} content the input's contents for the map's `sourcesContent`; only read while printing
41174118
* @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
41184119
* @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
4120+
* @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
41194121
* @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
41204122
* @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
41214123
* @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
@@ -6711,6 +6713,8 @@ const grammar = (input, visitors, writer, options) => {
67116713
_printing = writer !== undefined;
67126714
_convertLengthUnits =
67136715
writer !== undefined && writer.options.convertLengthUnits === true;
6716+
_convertApproximateColors =
6717+
writer !== undefined && writer.options.convertApproximateColors === true;
67146718
const unused =
67156719
writer === undefined ? undefined : writer.options.unusedSymbols;
67166720
_unusedSymbols =
@@ -7004,7 +7008,7 @@ const _dropSeparatorAfter = (cc) =>
70047008
* What the CSS printer may be told, on top of the `mode` every language has —
70057009
* the printing slice of `CssProcessOptions`, named once so nothing outside CSS
70067010
* has to enumerate it.
7007-
* @typedef {Pick<CssProcessOptions, "environment" | "convertLengthUnits" | "mergeDistantRules" | "rewriteCustomProperties" | "renderEmbeddedSource" | "deferEmbeddedSource" | "transforms" | "unusedSymbols" | "pseudoClasses">} CssPrintOptions
7011+
* @typedef {Pick<CssProcessOptions, "environment" | "convertLengthUnits" | "convertApproximateColors" | "mergeDistantRules" | "rewriteCustomProperties" | "renderEmbeddedSource" | "deferEmbeddedSource" | "transforms" | "unusedSymbols" | "pseudoClasses">} CssPrintOptions
70087012
*/
70097013

70107014
/** @typedef {import("../util/SourceProcessor").PrintContext<CssPath, Node, CssPrintOptions>} PrintContext */
@@ -9910,8 +9914,9 @@ const _COLOR_ARGUMENT_RE = /[^\s,/]+/g;
99109914
* only place implementations disagree — it is why esbuild and lightningcss emit
99119915
* different bytes for `hwb(194 0% 0%)`. And a Lab-family color outside the sRGB
99129916
* gamut keeps its function too: hex cannot express it, so converting would clip
9913-
* it to a different color. Both are limitations, not correctness gaps — the
9914-
* declined share is small and every other minifier converts them regardless.
9917+
* it to a different color. Both are limitations, not correctness gaps, and
9918+
* `convertApproximateColors` lifts them: the first to the byte other minifiers
9919+
* write anyway, the second past where any of them goes.
99159920
*
99169921
* Both guards are about *replacing* the function. A fallback stands before the
99179922
* function rather than in its place, so it is only ever read by an engine with
@@ -10047,14 +10052,20 @@ const _colorFromChannels = (raw, alpha, conversion, hexAlpha, forFallback) => {
1004710052
/** @type {number[]} */
1004810053
const channels = [];
1004910054
let clipped = false;
10055+
// A space read through a transfer of the engine's own is not a margin away
10056+
// from agreeing, so the option that takes the nearest byte anyway does not
10057+
// reach it: the hex would name a color the engine never paints.
10058+
const approximate =
10059+
_convertApproximateColors && conversion !== ENGINE_TRANSFER_DIFFERS;
1005010060
// The color's own magnitude, which the conversion's error is relative to.
1005110061
const scale = Math.max(
1005210062
...raw.map((value) => Math.abs(_gammaDecode(value / 255)))
1005310063
);
1005410064
for (const value of raw) {
10055-
const byte = forFallback
10056-
? _clamp255(value)
10057-
: _channelByte(value, _conversionMargin(value, conversion, scale));
10065+
const byte =
10066+
forFallback || approximate
10067+
? _clamp255(value)
10068+
: _channelByte(value, _conversionMargin(value, conversion, scale));
1005810069
if (byte === null) return null;
1005910070
if (Math.abs(byte - value) > 0.5) clipped = true;
1006010071
channels.push(byte);
@@ -15750,6 +15761,9 @@ const _mergeDistantRules = (items, texts) => {
1575015761
for (let i = 0; i < items.length; i++) {
1575115762
if (texts[i].length === 0) continue;
1575215763
const entry = _ruleEntryOf(items[i], texts[i]);
15764+
// TODO join two `@media` a rule stands between as well, which is this
15765+
// same question asked of every property the body declares — csso loses
15766+
// ~12,900 Tailwind classes to doing it without asking it.
1575315767
if (entry.prelude === -1 || entry.atRule || !_entryListable(entry)) {
1575415768
continue;
1575515769
}
@@ -18122,6 +18136,10 @@ let _steppedFunctionDepth = 0;
1812218136
// asset is compressed, and `cssnano` disables it in its default preset too. Time
1812318137
// is not gated: it is uncontested and every minifier does it.
1812418138
let _convertLengthUnits = false;
18139+
// Whether a color may be written as the nearest hex where that hex only
18140+
// approximates it. Off by default: webpack converts where it can prove an
18141+
// engine's own conversion lands on the same bytes, and declines the rest.
18142+
let _convertApproximateColors = false;
1812518143
// Whether a rule may take the selectors of a later one printing the same block,
1812618144
// past what stands between them. Off by default: it reorders the cascade.
1812718145
let _mergingDistantRules = false;

‎lib/html/builtinEmbeddedRenderer.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ const { CSS_TYPE } = require("../ModuleSourceTypeConstants");
1313
/**
1414
* What this minifies inline CSS with: the CSS minifier's own options, so an
1515
* inline declaration is held to the rules a `.css` asset is.
16-
* @typedef {Pick<CssProcessOptions, "environment" | "convertLengthUnits" | "rewriteCustomProperties" | "transforms" | "unusedSymbols" | "pseudoClasses">} BuiltinEmbeddedRendererOptions
16+
* @typedef {Pick<CssProcessOptions, "environment" | "convertLengthUnits" | "convertApproximateColors" | "rewriteCustomProperties" | "transforms" | "unusedSymbols" | "pseudoClasses">} BuiltinEmbeddedRendererOptions
1717
*/
1818

1919
// Both are loaded on first render rather than at module load: a document that

‎lib/html/htmlMinify.js‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@
3535
* re-resolves in the worker — via the installed package, or the dev self-link.
3636
* @param {{ [file: string]: string | Buffer }} input a single `{ filename: code }` entry; a `Buffer` is read as UTF-8
3737
* @param {(RawSourceMap | undefined)=} sourceMap input source map (unused: safe serialize keeps positions token-coarse, so no map is produced yet)
38-
* @param {Omit<HtmlPrintOptions, "renderEmbeddedSource" | "deferEmbeddedSource"> & { environment?: CssEnvironment, css?: { convertLengthUnits?: boolean, rewriteCustomProperties?: boolean, unusedSymbols?: string[], pseudoClasses?: { [name: string]: string } }, minifyConditionalComments?: boolean, renderEmbeddedSource?: AsyncEmbeddedSourceRenderer }=} minimizerOptions minimizer options — `environment` and `css` (`optimization.minimize.css`, whole) reach the CSS minifier this runs over inline CSS; the rest is `optimization.minimize.html`. The two stand apart rather than merged: both languages name a `quotes` and a `comments`, and one flat object would hand each the other's answer. `renderEmbeddedSource` minifies source this document embeds and may be asynchronous — one parse serves both it and the output. What it declines this minifies itself, for the languages webpack ships a minifier for
38+
* @param {Omit<HtmlPrintOptions, "renderEmbeddedSource" | "deferEmbeddedSource"> & { environment?: CssEnvironment, css?: { convertLengthUnits?: boolean, convertApproximateColors?: boolean, rewriteCustomProperties?: boolean, unusedSymbols?: string[], pseudoClasses?: { [name: string]: string } }, minifyConditionalComments?: boolean, renderEmbeddedSource?: AsyncEmbeddedSourceRenderer }=} minimizerOptions minimizer options — `environment` and `css` (`optimization.minimize.css`, whole) reach the CSS minifier this runs over inline CSS; the rest is `optimization.minimize.html`. The two stand apart rather than merged: both languages name a `quotes` and a `comments`, and one flat object would hand each the other's answer. `renderEmbeddedSource` minifies source this document embeds and may be asynchronous — one parse serves both it and the output. What it declines this minifies itself, for the languages webpack ships a minifier for
3939
* @returns {Promise<{ code: string, warnings?: (Error | string)[], errors?: (Error | string)[] }>} the minified HTML, and what a renderer reported over what it embeds
4040
*/
4141
const htmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
@@ -83,6 +83,7 @@ const htmlMinify = async (input, sourceMap, minimizerOptions = {}) => {
8383
const builtin = builtinEmbeddedRenderer({
8484
environment,
8585
convertLengthUnits: css.convertLengthUnits,
86+
convertApproximateColors: css.convertApproximateColors,
8687
rewriteCustomProperties: css.rewriteCustomProperties,
8788
unusedSymbols: css.unusedSymbols,
8889
pseudoClasses: css.pseudoClasses,

‎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
@@ -4014,6 +4014,11 @@
40144014
],
40154015
"added": "5.110.0"
40164016
},
4017+
"convertApproximateColors": {
4018+
"description": "Write a polar or Lab color as the nearest hex even where that hex only approximates it. `shortenColors` converts one only where webpack can prove an engine's own conversion lands on the same bytes, and keeps the function in the two places it cannot: a channel sitting too near a `.5` boundary for two implementations to round it alike (it is why esbuild and lightningcss emit different bytes for `hwb(194 0% 0%)`), and a color outside the sRGB gamut, which hex can only clip to a different color. Off by default, for those two reasons, and the two are not the same trade: on the boundary this writes the byte esbuild, lightningcss and cssnano write anyway, while outside the gamut it goes further than any of them — lightningcss keeps the function there and writes a fallback before it, which is what `colorFallbacks` does. A space engines read through transfers of their own (`a98-rgb`, `prophoto-rgb`) is left alone either way, the hex there naming a color no engine paints rather than a near one. This is about replacing the function: a fallback stands before it rather than in its place, so it already clips and rounds this way.",
4019+
"type": "boolean",
4020+
"added": "5.112.0"
4021+
},
40174022
"convertLengthUnits": {
40184023
"description": "Rewrite a length into a shorter unit it is exactly equal in (`16px` -> `1pc`). Off by default: the authored unit is lost, and once the asset is compressed the rewrite rarely earns anything.",
40194024
"type": "boolean",

0 commit comments

Comments
 (0)