Skip to content

Commit c4f1e17

Browse files
fix(css): keep a color whose channels are read back as written (#21923)
* fix(css): keep a color whose channels are read back as written A relative color reads its origin's channels off as the `r` / `l` / `h` keywords, and `color-mix()` interpolates its arguments the way a gradient does, so converting one through an 8-bit hex moves the color the engine computes rather than only its spelling — `lch(from lch(50% 20 30) l c h)` computes `lch(50.0415 19.8356 30.1479)` once the origin is a hex. The gradient guard becomes one flag over every such context, keyed on the `from` the arguments open with so an unknown function guards its origin too, and an `rgb()` whose channels are not already bytes is declined there as well. * chore(deps): bump the test262 and wpt submodules Same bumps as #21917 — the wpt corpus they bring is what the printer fix in the previous commit is held to. * fix(css): read an escaped name before deciding a color is an operand `\66 rom` names the relative-color keyword, and an escaped `color-mix` or gradient name names those, so the guard compared a spelling the source need not use. The escaped gradient name was already folding before this branch.
1 parent f570a41 commit c4f1e17

7 files changed

Lines changed: 162 additions & 24 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"webpack": patch
3+
---
4+
5+
Keep a color the CSS minifier would round where its channels are read back.

‎lib/css/syntax.js‎

Lines changed: 103 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,7 @@ const CC_LOWER_U = "u".charCodeAt(0);
325325
const CC_LOWER_R = "r".charCodeAt(0);
326326
const CC_LOWER_L = "l".charCodeAt(0);
327327
const CC_LOWER_T = "t".charCodeAt(0);
328+
const CC_LOWER_X = "x".charCodeAt(0);
328329
const CC_LOWER_Z = "z".charCodeAt(0);
329330
const CC_EXCLAMATION = "!".charCodeAt(0);
330331
const CC_UPPER_A = "A".charCodeAt(0);
@@ -2006,7 +2007,7 @@ const _setupParse = (input, lc) => {
20062007
_inFeatureValuesRule = false;
20072008
_inCustomProperty = false;
20082009
_inSubstitutedValue = false;
2009-
_inGradient = false;
2010+
_inColorOperand = false;
20102011
_substitutionSpanFrom = -1;
20112012
_substitutionSpanTo = -1;
20122013
_substitutionSpanHas = false;
@@ -4206,20 +4207,18 @@ const _walkValue = (node, parent, index, writer) => {
42064207
_steppedFunctionDepth++;
42074208
}
42084209
}
4209-
const previousGradient = _inGradient;
4210+
const previousColorOperand = _inColorOperand;
42104211
if (
42114212
ty === T_FUNCTION &&
4212-
// Every gradient name ends in `gradient`, so one code point rejects the
4213-
// rest before the name is sliced.
4214-
(_input.charCodeAt(_aux0[i0] - 1) | 0x20) === CC_LOWER_T &&
4215-
GRADIENT_FUNCTION_RE.test(_gradientName(i0))
4213+
!_inColorOperand &&
4214+
_readsColorsAsNumbers(i0, vs, ve)
42164215
) {
4217-
_inGradient = true;
4216+
_inColorOperand = true;
42184217
}
42194218
for (let i = vs; i < ve; i++) {
42204219
_walkValue(_nodeRef(_flat[i]), node, i - vs, writer);
42214220
}
4222-
_inGradient = previousGradient;
4221+
_inColorOperand = previousColorOperand;
42234222
}
42244223
_exitNode(node, parent, index, b, writer);
42254224
if (enteredMath) _mathFunctionDepth--;
@@ -4236,6 +4235,84 @@ const GRADIENT_FUNCTION_RE = /(?:^|-)(?:linear|radial|conic)-gradient$/i;
42364235
*/
42374236
const _gradientName = (i0) => _input.slice(_starts[i0], _aux0[i0]);
42384237

4238+
/**
4239+
* Whether a source range holds an escape, so its unescaped spelling is the one
4240+
* a name has to be read from.
4241+
* @param {number} start range start
4242+
* @param {number} end range end (exclusive)
4243+
* @returns {boolean} true when the range holds a `\`
4244+
*/
4245+
const _rangeHasEscape = (start, end) => {
4246+
for (let i = start; i < end; i++) {
4247+
if (_input.charCodeAt(i) === CC_REVERSE_SOLIDUS) return true;
4248+
}
4249+
return false;
4250+
};
4251+
4252+
/** Longest `from` spelling: each code point as `\` + 6 hex digits + CRLF. */
4253+
const MAX_ESCAPED_FROM_LENGTH = 4 * (1 + 6 + 2);
4254+
4255+
/**
4256+
* Whether an ident names the relative-color keyword — `\66 rom` names it too,
4257+
* and only an escaped ident is longer than the four bytes it spells.
4258+
* @param {number} start ident start offset
4259+
* @param {number} end ident end offset (exclusive)
4260+
* @returns {boolean} true when the ident names `from`
4261+
*/
4262+
const _identNamesFrom = (start, end) => {
4263+
const length = end - start;
4264+
if (length === 4) return rangeEqualsLowerCase(_input, start, end, "from");
4265+
if (length < 4 || length > MAX_ESCAPED_FROM_LENGTH) return false;
4266+
return (
4267+
_rangeHasEscape(start, end) &&
4268+
equalsLowerCase(unescapeIdentifier(_input.slice(start, end)), "from")
4269+
);
4270+
};
4271+
4272+
/**
4273+
* Whether a function reads the colors below it as numbers rather than showing
4274+
* them: a gradient interpolates its stops, `color-mix()` its arguments, and a
4275+
* relative color reads its origin's channels off as the `r` / `l` / `h`
4276+
* keywords. The origin is the `from` its arguments open with, so a function
4277+
* webpack knows nothing about guards its origin too.
4278+
* @param {number} i0 the function's node index
4279+
* @param {number} vs its first child's slot
4280+
* @param {number} ve one past its last child's slot
4281+
* @returns {boolean} true when a color below it is an operand, not a value
4282+
*/
4283+
const _readsColorsAsNumbers = (i0, vs, ve) => {
4284+
const start = _starts[i0];
4285+
const end = _aux0[i0];
4286+
if (_rangeHasEscape(start, end)) {
4287+
// An escape spells either name too, so the unescaped spelling decides.
4288+
const name = unescapeIdentifier(_input.slice(start, end));
4289+
if (GRADIENT_FUNCTION_RE.test(name) || equalsLowerCase(name, "color-mix")) {
4290+
return true;
4291+
}
4292+
} else {
4293+
// Every gradient name ends in `gradient` and `color-mix` in `mix`, so one
4294+
// code point rejects the rest before either name is sliced.
4295+
const last = _input.charCodeAt(end - 1) | 0x20;
4296+
if (last === CC_LOWER_T) {
4297+
if (GRADIENT_FUNCTION_RE.test(_gradientName(i0))) return true;
4298+
} else if (
4299+
last === CC_LOWER_X &&
4300+
rangeEqualsLowerCase(_input, start, end, "color-mix")
4301+
) {
4302+
return true;
4303+
}
4304+
}
4305+
for (let i = vs; i < ve; i++) {
4306+
const child = _flat[i];
4307+
const childType = _types[child];
4308+
if (childType === T_WHITESPACE) continue;
4309+
return (
4310+
childType === T_IDENT && _identNamesFrom(_starts[child], _ends[child])
4311+
);
4312+
}
4313+
return false;
4314+
};
4315+
42394316
/**
42404317
* Set the flags an at-rule's own name decides, on the way into its prelude:
42414318
* which of them is set is the same question wherever the walk asks it, and the
@@ -7017,9 +7094,10 @@ const _clamp255 = (x) => (x < 0 ? 0 : x > 255 ? 255 : Math.round(x));
70177094
* @param {string} fn the lowercased function name
70187095
* @param {string} inner the already-joined argument text
70197096
* @param {boolean} hexAlpha whether the target reads a 4-/8-digit hex (see `output.environment`)
7097+
* @param {boolean} operand whether the color is read as numbers here, which only an exact conversion survives
70207098
* @returns {string | null} the shortest color, or null to keep the function
70217099
*/
7022-
const _minifyColorFunction = (fn, inner, hexAlpha) => {
7100+
const _minifyColorFunction = (fn, inner, hexAlpha, operand) => {
70237101
if ((fn !== "rgb" && fn !== "rgba") || !_transforms.shortenColors) {
70247102
return null;
70257103
}
@@ -7060,6 +7138,7 @@ const _minifyColorFunction = (fn, inner, hexAlpha) => {
70607138
const channels = [];
70617139
let alpha = 1;
70627140
let percentChannelCount = 0;
7141+
let roundedChannel = false;
70637142
for (let i = 0; i < args.length; i++) {
70647143
const s = args[i];
70657144
if (!/^[+-]?(?:\d+\.?\d*|\.\d+)%?$/.test(s)) return null;
@@ -7070,12 +7149,17 @@ const _minifyColorFunction = (fn, inner, hexAlpha) => {
70707149
alpha = pct ? v / 100 : v;
70717150
} else {
70727151
if (pct) percentChannelCount++;
7073-
channels.push(_clamp255(pct ? (v * 255) / 100 : v));
7152+
const channel = pct ? (v * 255) / 100 : v;
7153+
// A hex is the same color only where the channel is already a byte —
7154+
// `rgb(50% 50% 50%)` is 127.5, not `gray`. One out of range is: it clamps.
7155+
if (!Number.isInteger(channel)) roundedChannel = true;
7156+
channels.push(_clamp255(channel));
70747157
}
70757158
}
70767159
// Mixed number/percentage channels are invalid CSS (ignored by browsers);
70777160
// rewriting would activate a dead declaration.
70787161
if (percentChannelCount !== 0 && percentChannelCount !== 3) return null;
7162+
if (operand && roundedChannel) return null;
70797163
// Fully transparent *black* only — `transparent` is `rgba(0,0,0,0)`, so a
70807164
// non-black transparent (e.g. `rgba(255,0,0,0)`) is a different value.
70817165
if (
@@ -12230,15 +12314,13 @@ const printer = (path, writer) => {
1223012314
// engines that read `#0000` are not the ones that read `rgba(0,0,0,0)`,
1223112315
// so rewriting it asks a different question (esbuild, clean-css and
1223212316
// lightningcss leave the condition alone too).
12233-
// A gradient stop outside sRGB is handed back as written rather than
12234-
// computed, so converting one moves the value the CSSOM reports — and
12235-
// where the gradient names the space its stops interpolate in, it moves
12236-
// the ramp itself. The legacy sRGB forms all compute to `rgb(…)`
12237-
// whichever way they are spelled, so those still fold.
12317+
// A color read as numbers — a gradient stop, a `color-mix()` argument, a
12318+
// relative color's origin — is left as written unless converting it is
12319+
// exact, which the legacy sRGB forms are where their channels are bytes.
1223812320
const color = _inSupportsPrelude
1223912321
? null
12240-
: _minifyColorFunction(fn, inner, _hexAlphaAllowed) ||
12241-
(_inGradient
12322+
: _minifyColorFunction(fn, inner, _hexAlphaAllowed, _inColorOperand) ||
12323+
(_inColorOperand
1224212324
? null
1224312325
: _minifyPolarColorFunction(fn, inner, _hexAlphaAllowed));
1224412326
if (
@@ -12995,11 +13077,10 @@ let _inCustomProperty = false;
1299513077
let _rewriteCustomProperties = false;
1299613078
let _inSubstitutedValue = false;
1299713079

12998-
// Whether the value being printed sits inside a gradient. A stop in a space
12999-
// other than sRGB is echoed there rather than computed, and where the gradient
13000-
// names the space its stops interpolate in, converting one through sRGB maps it
13001-
// back as a different point — so the ramp is not the one the source paints.
13002-
let _inGradient = false;
13080+
// Whether the color being printed is read as numbers rather than shown — a
13081+
// gradient stop, a `color-mix()` argument, a relative color's origin — where an
13082+
// 8-bit hex moves the color the engine computes, not only how it is spelled.
13083+
let _inColorOperand = false;
1300313084
// How many math functions the walk is inside. Non-zero is where `*` and `/` are
1300413085
// operators that need no whitespace rather than value separators; above one is
1300513086
// where a folded term is an operand of an outer expression rather than a value.

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,5 +61,17 @@ Array [
6161
"/*! declined without a space too: a stop outside sRGB is handed back as written
6262
rather than computed, so converting one moves what the CSSOM reports */.g03{background-image:linear-gradient(90deg,red,lch(50 20 30))}",
6363
"/*! the legacy sRGB forms all compute to \`rgb(…)\` however they are spelled */.g04{background-image:linear-gradient(90deg,red,#010203)}",
64+
"/*! declined: a relative color reads its origin's channels off as the \`r\` / \`l\` /
65+
\`h\` keywords, so a hex — 8 bits a channel — is a different origin */.r01{color:lch(from lch(50% 20 30) l c h)}.r02{color:rgb(from lch(50% 20 30) r g b)}.r03{color:hsl(from hsl(120 50% 50%) h s l)}.r04{color:rgb(from rgb(50% 50% 50%) r g b)}",
66+
"/*! declined whatever the function is named: \`from\` says the argument after it is
67+
read the same way, which is the only thing an unknown function states */.r05{color:alpha(from lch(50% 20 30) / .5)}",
68+
"/*! ...and the keyword is the first argument however the call is spaced */.r06{color:lch(from lch(50% 20 30) l c h)}",
69+
"/*! an origin already written as bytes converts exactly, so it still folds — one
70+
out of range with it, since the engine clamps that to the same byte */.r07{color:rgb(from #781e28 r g b)}.r08{color:rgb(from red r g b)}",
71+
"/*! ...and \`from\` heading a function's name is not the keyword */.r09{color:from(#976c67)}",
72+
"/*! declined: \`color-mix()\` interpolates its arguments the way a gradient does */.m01{color:color-mix(in oklab,lch(50% 20 30),red)}.m02{color:color-mix(in srgb,hsl(120 50% 50%),red)}",
73+
"/*! the legacy sRGB forms fold there too, where their channels are already bytes */.m03{color:color-mix(in srgb,#010203,red)}",
74+
"/*! declined however the keyword is spelled: \`\\\\66 rom\` names it too, as an
75+
escaped \`color-mix\` or gradient name names those */.r10{color:rgb(from rgb(50% 50% 50%) r g b)}.m04{color:color-\\\\6d ix(in oklab,lch(50% 20 30),red)}.g05{background-image:linear-\\\\67 radient(lch(50 20 30),red)}",
6476
]
6577
`;

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

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,5 +61,17 @@ Array [
6161
"/*! declined without a space too: a stop outside sRGB is handed back as written
6262
rather than computed, so converting one moves what the CSSOM reports */.g03{background-image:linear-gradient(90deg,red,lch(50 20 30))}",
6363
"/*! the legacy sRGB forms all compute to \`rgb(…)\` however they are spelled */.g04{background-image:linear-gradient(90deg,red,#010203)}",
64+
"/*! declined: a relative color reads its origin's channels off as the \`r\` / \`l\` /
65+
\`h\` keywords, so a hex — 8 bits a channel — is a different origin */.r01{color:lch(from lch(50% 20 30) l c h)}.r02{color:rgb(from lch(50% 20 30) r g b)}.r03{color:hsl(from hsl(120 50% 50%) h s l)}.r04{color:rgb(from rgb(50% 50% 50%) r g b)}",
66+
"/*! declined whatever the function is named: \`from\` says the argument after it is
67+
read the same way, which is the only thing an unknown function states */.r05{color:alpha(from lch(50% 20 30) / .5)}",
68+
"/*! ...and the keyword is the first argument however the call is spaced */.r06{color:lch(from lch(50% 20 30) l c h)}",
69+
"/*! an origin already written as bytes converts exactly, so it still folds — one
70+
out of range with it, since the engine clamps that to the same byte */.r07{color:rgb(from #781e28 r g b)}.r08{color:rgb(from red r g b)}",
71+
"/*! ...and \`from\` heading a function's name is not the keyword */.r09{color:from(#976c67)}",
72+
"/*! declined: \`color-mix()\` interpolates its arguments the way a gradient does */.m01{color:color-mix(in oklab,lch(50% 20 30),red)}.m02{color:color-mix(in srgb,hsl(120 50% 50%),red)}",
73+
"/*! the legacy sRGB forms fold there too, where their channels are already bytes */.m03{color:color-mix(in srgb,#010203,red)}",
74+
"/*! declined however the keyword is spelled: \`\\\\66 rom\` names it too, as an
75+
escaped \`color-mix\` or gradient name names those */.r10{color:rgb(from rgb(50% 50% 50%) r g b)}.m04{color:color-\\\\6d ix(in oklab,lch(50% 20 30),red)}.g05{background-image:linear-\\\\67 radient(lch(50 20 30),red)}",
6476
]
6577
`;

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

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,3 +126,31 @@
126126
.g03 { background-image: linear-gradient(90deg, red, lch(50 20 30)) }
127127
/*! the legacy sRGB forms all compute to `rgb(…)` however they are spelled */
128128
.g04 { background-image: linear-gradient(90deg, red, rgb(1, 2, 3)) }
129+
130+
/*! declined: a relative color reads its origin's channels off as the `r` / `l` /
131+
`h` keywords, so a hex — 8 bits a channel — is a different origin */
132+
.r01 { color: lch(from lch(50% 20 30) l c h) }
133+
.r02 { color: rgb(from lch(50% 20 30) r g b) }
134+
.r03 { color: hsl(from hsl(120 50% 50%) h s l) }
135+
.r04 { color: rgb(from rgb(50% 50% 50%) r g b) }
136+
/*! declined whatever the function is named: `from` says the argument after it is
137+
read the same way, which is the only thing an unknown function states */
138+
.r05 { color: alpha(from lch(50% 20 30) / 0.5) }
139+
/*! ...and the keyword is the first argument however the call is spaced */
140+
.r06 { color: lch( from lch(50% 20 30) l c h) }
141+
/*! an origin already written as bytes converts exactly, so it still folds — one
142+
out of range with it, since the engine clamps that to the same byte */
143+
.r07 { color: rgb(from rgb(120 30 40) r g b) }
144+
.r08 { color: rgb(from rgb(300 0 0) r g b) }
145+
/*! ...and `from` heading a function's name is not the keyword */
146+
.r09 { color: from(lch(50% 20 30)) }
147+
/*! declined: `color-mix()` interpolates its arguments the way a gradient does */
148+
.m01 { color: color-mix(in oklab, lch(50% 20 30), red) }
149+
.m02 { color: color-mix(in srgb, hsl(120 50% 50%), red) }
150+
/*! the legacy sRGB forms fold there too, where their channels are already bytes */
151+
.m03 { color: color-mix(in srgb, rgb(1, 2, 3), red) }
152+
/*! declined however the keyword is spelled: `\66 rom` names it too, as an
153+
escaped `color-mix` or gradient name names those */
154+
.r10 { color: rgb(\66 rom rgb(50% 50% 50%) r g b) }
155+
.m04 { color: color-\6d ix(in oklab, lch(50% 20 30), red) }
156+
.g05 { background-image: linear-\67 radient(lch(50 20 30), red) }

‎test/wpt‎

Submodule wpt updated 582 files

0 commit comments

Comments
 (0)