Skip to content

Commit 8a6c7c8

Browse files
feat(css): expose the declined color conversions as an option
`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 d7e0fd9 commit 8a6c7c8

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
@@ -2019,6 +2019,7 @@ const _setupParse = (input, lc) => {
20192019
_mathFunctionDepth = 0;
20202020
_steppedFunctionDepth = 0;
20212021
_convertLengthUnits = false;
2022+
_convertApproximateColors = false;
20222023
_unusedSymbols = null;
20232024
_unusedRules = null;
20242025
_pseudoClasses = null;
@@ -4099,6 +4100,7 @@ const TOP_LEVEL_CONSUMERS = {
40994100
* @property {string=} content the input's contents for the map's `sourcesContent`; only read while printing
41004101
* @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
41014102
* @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
4103+
* @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
41024104
* @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
41034105
* @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
41044106
* @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
@@ -6691,6 +6693,8 @@ const grammar = (input, visitors, writer, options) => {
66916693
_printing = writer !== undefined;
66926694
_convertLengthUnits =
66936695
writer !== undefined && writer.options.convertLengthUnits === true;
6696+
_convertApproximateColors =
6697+
writer !== undefined && writer.options.convertApproximateColors === true;
66946698
const unused =
66956699
writer === undefined ? undefined : writer.options.unusedSymbols;
66966700
_unusedSymbols =
@@ -6982,7 +6986,7 @@ const _dropSeparatorAfter = (cc) =>
69826986
* What the CSS printer may be told, on top of the `mode` every language has —
69836987
* the printing slice of `CssProcessOptions`, named once so nothing outside CSS
69846988
* has to enumerate it.
6985-
* @typedef {Pick<CssProcessOptions, "environment" | "convertLengthUnits" | "mergeDistantRules" | "rewriteCustomProperties" | "renderEmbeddedSource" | "deferEmbeddedSource" | "transforms" | "unusedSymbols" | "pseudoClasses">} CssPrintOptions
6989+
* @typedef {Pick<CssProcessOptions, "environment" | "convertLengthUnits" | "convertApproximateColors" | "mergeDistantRules" | "rewriteCustomProperties" | "renderEmbeddedSource" | "deferEmbeddedSource" | "transforms" | "unusedSymbols" | "pseudoClasses">} CssPrintOptions
69866990
*/
69876991

69886992
/** @typedef {import("../util/SourceProcessor").PrintContext<CssPath, Node, CssPrintOptions>} PrintContext */
@@ -9785,8 +9789,9 @@ const _COLOR_ARGUMENT_RE = /[^\s,/]+/g;
97859789
* only place implementations disagree — it is why esbuild and lightningcss emit
97869790
* different bytes for `hwb(194 0% 0%)`. And a Lab-family color outside the sRGB
97879791
* gamut keeps its function too: hex cannot express it, so converting would clip
9788-
* it to a different color. Both are limitations, not correctness gaps — the
9789-
* declined share is small and every other minifier converts them regardless.
9792+
* it to a different color. Both are limitations, not correctness gaps, and
9793+
* `convertApproximateColors` lifts them: the first to the byte other minifiers
9794+
* write anyway, the second past where any of them goes.
97909795
*
97919796
* Both guards are about *replacing* the function. A fallback stands before the
97929797
* function rather than in its place, so it is only ever read by an engine with
@@ -9922,14 +9927,20 @@ const _colorFromChannels = (raw, alpha, conversion, hexAlpha, forFallback) => {
99229927
/** @type {number[]} */
99239928
const channels = [];
99249929
let clipped = false;
9930+
// A space read through a transfer of the engine's own is not a margin away
9931+
// from agreeing, so the option that takes the nearest byte anyway does not
9932+
// reach it: the hex would name a color the engine never paints.
9933+
const approximate =
9934+
_convertApproximateColors && conversion !== ENGINE_TRANSFER_DIFFERS;
99259935
// The color's own magnitude, which the conversion's error is relative to.
99269936
const scale = Math.max(
99279937
...raw.map((value) => Math.abs(_gammaDecode(value / 255)))
99289938
);
99299939
for (const value of raw) {
9930-
const byte = forFallback
9931-
? _clamp255(value)
9932-
: _channelByte(value, _conversionMargin(value, conversion, scale));
9940+
const byte =
9941+
forFallback || approximate
9942+
? _clamp255(value)
9943+
: _channelByte(value, _conversionMargin(value, conversion, scale));
99339944
if (byte === null) return null;
99349945
if (Math.abs(byte - value) > 0.5) clipped = true;
99359946
channels.push(byte);
@@ -15509,6 +15520,9 @@ const _mergeDistantRules = (items, texts) => {
1550915520
for (let i = 0; i < items.length; i++) {
1551015521
if (texts[i].length === 0) continue;
1551115522
const entry = _ruleEntryOf(items[i], texts[i]);
15523+
// TODO join two `@media` a rule stands between as well, which is this
15524+
// same question asked of every property the body declares — csso loses
15525+
// ~12,900 Tailwind classes to doing it without asking it.
1551215526
if (entry.prelude === -1 || entry.atRule || !_entryListable(entry)) {
1551315527
continue;
1551415528
}
@@ -17879,6 +17893,10 @@ let _steppedFunctionDepth = 0;
1787917893
// asset is compressed, and `cssnano` disables it in its default preset too. Time
1788017894
// is not gated: it is uncontested and every minifier does it.
1788117895
let _convertLengthUnits = false;
17896+
// Whether a color may be written as the nearest hex where that hex only
17897+
// approximates it. Off by default: webpack converts where it can prove an
17898+
// engine's own conversion lands on the same bytes, and declines the rest.
17899+
let _convertApproximateColors = false;
1788217900
// Whether a rule may take the selectors of a later one printing the same block,
1788317901
// past what stands between them. Off by default: it reorders the cascade.
1788417902
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)