Skip to content

Commit 3ccb28c

Browse files
Interpolate gradient color stops outside the 0–100% range (#59774)
* Interpolate gradient color stops outside the 0–100% range CSS lets color stops sit before 0% or after 100%. They still shape the colors inside the gradient through interpolation, but are never painted directly. React Native clamped such stops to the range on iOS, and Android's gradient shaders pin them, so `linear-gradient(red -50%, blue 150%)` rendered as plain `red → blue`, while browsers start at rgb(191, 0, 64). Replace out-of-range stops with stops at the range boundaries, colored as the gradient would be at that point (premultiplied, as CSS and Android's shaders interpolate). Radial gradients only clip negative stops: like Blink, they grow the radius to fit stops past the ending shape, because that area stays visible. Also like Blink, length stops on a zero-length gradient line resolve to 0, so the radius stays finite. Android also dropped negative stop positions while parsing linear and radial gradients, treating them as unpositioned. Allow them. * Add iOS unit tests for out-of-range gradient color stops Mirror the Android ColorStopTest cases for RCTGradientUtils clipColorStops and getFixedColorStops in the React-RCTFabric test spec. Credit the WPT tests that some cases come from, in both the iOS and Kotlin tests. * Quote the CSS spec on out-of-range gradient color stops * Add RNTester examples for gradient color stops outside 0–100% * Reject non-finite gradient color stop positions and clamp them natively
1 parent 1f8cb8b commit 3ccb28c

17 files changed

Lines changed: 841 additions & 25 deletions

File tree

‎packages/react-native/Libraries/StyleSheet/__tests__/processBackgroundImage-itest.js‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,20 @@ describe('processBackgroundImage', () => {
353353
expect(result).toEqual([]);
354354
});
355355

356+
it('should return empty array for non-finite color stop positions', () => {
357+
expect(processBackgroundImage('linear-gradient(red NaN%, blue)')).toEqual(
358+
[],
359+
);
360+
expect(
361+
processBackgroundImage([
362+
{
363+
type: 'linear-gradient' as const,
364+
colorStops: [{color: 'red', positions: ['NaN%']}, {color: 'blue'}],
365+
},
366+
]),
367+
).toEqual([]);
368+
});
369+
356370
it('should process unitless zero color stop position', () => {
357371
const input = 'linear-gradient(red 0, blue 100%)';
358372
const result = processBackgroundImage(input);

‎packages/react-native/Libraries/StyleSheet/processBackgroundImage.js‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,17 @@ export default function processBackgroundImage(
191191
return result;
192192
}
193193

194+
function isValidColorStopPosition(position: unknown): boolean {
195+
if (typeof position === 'number') {
196+
return Number.isFinite(position);
197+
}
198+
return (
199+
typeof position === 'string' &&
200+
position.endsWith('%') &&
201+
Number.isFinite(parseFloat(position))
202+
);
203+
}
204+
194205
function processColorStops(bgImage: BackgroundImageValue): ReadonlyArray<{
195206
color: ColorStopColor,
196207
position: ColorStopPosition,
@@ -210,10 +221,7 @@ function processColorStops(bgImage: BackgroundImageValue): ReadonlyArray<{
210221
positions.length === 1
211222
) {
212223
const position = positions[0];
213-
if (
214-
typeof position === 'number' ||
215-
(typeof position === 'string' && position.endsWith('%'))
216-
) {
224+
if (isValidColorStopPosition(position)) {
217225
processedColorStops.push({
218226
color: null,
219227
position,
@@ -230,10 +238,7 @@ function processColorStops(bgImage: BackgroundImageValue): ReadonlyArray<{
230238
}
231239
if (positions != null && positions.length > 0) {
232240
for (const position of positions) {
233-
if (
234-
typeof position === 'number' ||
235-
(typeof position === 'string' && position.endsWith('%'))
236-
) {
241+
if (isValidColorStopPosition(position)) {
237242
processedColorStops.push({
238243
color: processedColor,
239244
position,
@@ -810,10 +815,11 @@ function getPositionFromCSSValue(position: string) {
810815
}
811816

812817
if (position.endsWith('px')) {
813-
return parseFloat(position);
818+
const value = parseFloat(position);
819+
return Number.isFinite(value) ? value : null;
814820
}
815821

816-
if (position.endsWith('%')) {
822+
if (isValidColorStopPosition(position)) {
817823
return position;
818824
}
819825
}

‎packages/react-native/React/Fabric/Utils/RCTGradientUtils.h‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ NS_ASSUME_NONNULL_BEGIN
1717
(const std::vector<facebook::react::ColorStop> &)colorStops
1818
gradientLineLength:(CGFloat)gradientLineLength;
1919

20+
+ (std::vector<facebook::react::ProcessedColorStop>)
21+
clipColorStops:(const std::vector<facebook::react::ProcessedColorStop> &)colorStops
22+
end:(facebook::react::Float)end;
23+
2024
// CAGradientLayer linear gradient squishes the non-square gradient to square gradient.
2125
// This function fixes the "squished" effect.
2226
// See https://stackoverflow.com/a/43176174 for more information.

‎packages/react-native/React/Fabric/Utils/RCTGradientUtils.mm‎

Lines changed: 78 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@
99
#import <React/RCTAnimationUtils.h>
1010
#import <React/RCTConversions.h>
1111
#import <react/utils/FloatComparison.h>
12+
#include <algorithm>
13+
#include <iterator>
14+
#include <limits>
1215
#include <optional>
1316
#import <vector>
1417

@@ -143,19 +146,48 @@ CGSize calculateMultipliers(CGSize bounds)
143146

144147
} // namespace
145148

149+
// Like Blink, clamp to finite values so that interpolation never divides infinity by infinity.
150+
static Float clampToFinite(Float position)
151+
{
152+
return std::clamp<Float>(position, -std::numeric_limits<float>::max(), std::numeric_limits<float>::max());
153+
}
154+
146155
static std::optional<Float> resolveColorStopPosition(ValueUnit position, CGFloat gradientLineLength)
147156
{
148157
if (position.unit == UnitType::Point) {
149-
return position.resolve(0.0f) / gradientLineLength;
158+
return clampToFinite(gradientLineLength > 0 ? position.resolve(0.0f) / gradientLineLength : 0);
150159
}
151160

152161
if (position.unit == UnitType::Percent) {
153-
return position.resolve(1.0f);
162+
return clampToFinite(position.resolve(1.0f));
154163
}
155164

156165
return std::nullopt;
157166
}
158167

168+
// Interpolates with premultiplied alpha, as CSS does.
169+
// Spec: https://drafts.csswg.org/css-color-4/#interpolation-alpha
170+
static SharedColor interpolateColor(const SharedColor &from, const SharedColor &to, float weight)
171+
{
172+
if (!from || !to) {
173+
return from ? from : to;
174+
}
175+
auto start = colorComponentsFromColor(from);
176+
auto end = colorComponentsFromColor(to);
177+
auto alpha = start.alpha + (end.alpha - start.alpha) * weight;
178+
if (alpha <= 0) {
179+
return clearColor();
180+
}
181+
auto channel = [&](float startChannel, float endChannel) {
182+
return (startChannel * start.alpha * (1 - weight) + endChannel * end.alpha * weight) / alpha;
183+
};
184+
return colorFromComponents(
185+
{.red = channel(start.red, end.red),
186+
.green = channel(start.green, end.green),
187+
.blue = channel(start.blue, end.blue),
188+
.alpha = alpha});
189+
}
190+
159191
// Spec: https://drafts.csswg.org/css-images-4/#coloring-gradient-line (Refer transition hint section)
160192
// Browsers add 9 intermediate color stops when a transition hint is present
161193
// Algorithm is referred from Blink engine
@@ -336,6 +368,50 @@ @implementation RCTGradientUtils
336368
return processColorTransitionHints(fixedColorStops);
337369
}
338370

371+
// Spec: https://drafts.csswg.org/css-images-4/#conic-color-stops
372+
// Color stops outside [0, end] are "never directly consulted for rendering", but "can affect the color of
373+
// color-stops within the rendered region through interpolation". So they are replaced by stops at the range
374+
// boundaries, colored as the gradient would be at that point.
375+
+ (std::vector<ProcessedColorStop>)clipColorStops:(const std::vector<ProcessedColorStop> &)colorStops end:(Float)end
376+
{
377+
if (colorStops.empty() ||
378+
(colorStops.front().position.value_or(0) >= 0 && colorStops.back().position.value_or(0) <= end)) {
379+
return colorStops;
380+
}
381+
382+
auto firstInside = std::find_if(
383+
colorStops.begin(), colorStops.end(), [](const auto &stop) { return stop.position.value_or(0) >= 0; });
384+
auto lastInside = std::find_if(
385+
colorStops.rbegin(), colorStops.rend(), [end](const auto &stop) { return stop.position.value_or(0) <= end; });
386+
if (firstInside == colorStops.end()) {
387+
return {{.color = colorStops.back().color, .position = 0}, {.color = colorStops.back().color, .position = end}};
388+
}
389+
if (lastInside == colorStops.rend()) {
390+
return {{.color = colorStops.front().color, .position = 0}, {.color = colorStops.front().color, .position = end}};
391+
}
392+
393+
auto colorAt = [](const ProcessedColorStop &before, const ProcessedColorStop &after, Float position) {
394+
auto weight = (position - before.position.value()) / (after.position.value() - before.position.value());
395+
return interpolateColor(before.color, after.color, static_cast<float>(weight));
396+
};
397+
398+
std::vector<ProcessedColorStop> clippedColorStops;
399+
if (firstInside != colorStops.begin() && firstInside->position.value() > 0) {
400+
clippedColorStops.push_back({.color = colorAt(*std::prev(firstInside), *firstInside, 0), .position = 0});
401+
}
402+
auto insideEnd = lastInside.base();
403+
if (firstInside < insideEnd) {
404+
clippedColorStops.insert(clippedColorStops.end(), firstInside, insideEnd);
405+
}
406+
if (insideEnd != colorStops.end() && std::prev(insideEnd)->position.value() < end) {
407+
clippedColorStops.push_back({.color = colorAt(*std::prev(insideEnd), *insideEnd, end), .position = end});
408+
}
409+
if (clippedColorStops.size() == 1) {
410+
clippedColorStops.push_back({.color = clippedColorStops.front().color, .position = end});
411+
}
412+
return clippedColorStops;
413+
}
414+
339415
// CAGradientLayer linear gradient squishes the non-square gradient to square gradient.
340416
// This function fixes the "squished" effect.
341417
// See https://stackoverflow.com/a/43176174 for more information.

‎packages/react-native/React/Fabric/Utils/RCTLinearGradient.mm‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,8 +36,9 @@ + (CALayer *)gradientLayerWithSize:(CGSize)size gradient:(const LinearGradient &
3636
CGFloat dx = endPoint.x - startPoint.x;
3737
CGFloat dy = endPoint.y - startPoint.y;
3838
CGFloat gradientLineLength = sqrt(dx * dx + dy * dy);
39-
const auto colorStops = [RCTGradientUtils getFixedColorStops:gradient.colorStops
40-
gradientLineLength:gradientLineLength];
39+
const auto fixedColorStops = [RCTGradientUtils getFixedColorStops:gradient.colorStops
40+
gradientLineLength:gradientLineLength];
41+
const auto colorStops = [RCTGradientUtils clipColorStops:fixedColorStops end:1];
4142
NSMutableArray<id> *colors = [NSMutableArray array];
4243
NSMutableArray<NSNumber *> *locations = [NSMutableArray array];
4344
CGPoint relativeStartPoint = CGPointMake(startPoint.x / size.width, startPoint.y / size.height);

‎packages/react-native/React/Fabric/Utils/RCTRadialGradient.mm‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -175,8 +175,15 @@ + (CALayer *)gradientLayerWithSize:(CGSize)size gradient:(const RadialGradient &
175175
auto [radiusX, radiusY] =
176176
GetRadialGradientRadius(isCircle, gradient.size, centerPoint.x, centerPoint.y, size.width, size.height);
177177
const auto gradientLineLength = std::max(radiusX, radiusY);
178-
const auto colorStops = [RCTGradientUtils getFixedColorStops:gradient.colorStops
179-
gradientLineLength:gradientLineLength];
178+
auto colorStops = [RCTGradientUtils getFixedColorStops:gradient.colorStops gradientLineLength:gradientLineLength];
179+
// Unlike negative stops, stops past the ending shape stay visible outside it, so the radius grows to fit them.
180+
const Float radiusScale = colorStops.empty() ? 1 : std::max<Float>(colorStops.back().position.value_or(1), 1);
181+
colorStops = [RCTGradientUtils clipColorStops:colorStops end:radiusScale];
182+
for (auto &colorStop : colorStops) {
183+
colorStop.position = colorStop.position.value_or(0) / radiusScale;
184+
}
185+
radiusX *= radiusScale;
186+
radiusY *= radiusScale;
180187
gradientLayer.startPoint = CGPointMake(centerPoint.x / size.width, centerPoint.y / size.height);
181188
// endpoint.x is horizontal length and endpoint.y is vertical length
182189
gradientLayer.endPoint = CGPointMake(

0 commit comments

Comments
 (0)