Skip to content

Commit

Permalink
Properly support degenerate channel values
Browse files Browse the repository at this point in the history
  • Loading branch information
nex3 committed Jul 9, 2024
1 parent 2d01ae8 commit 3d7eace
Show file tree
Hide file tree
Showing 6 changed files with 40 additions and 64 deletions.
37 changes: 15 additions & 22 deletions lib/src/functions/color.dart
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,7 @@ final global = UnmodifiableListView([
}

var result = color.changeHsl(
lightness: (color.lightness + amount.valueInRange(0, 100, "amount"))
.clamp(0, 100));
lightness: clampLikeCss(color.lightness + amount.valueInRange(0, 100, "amount"),0, 100));

warnForDeprecation(
"lighten() is deprecated. "
Expand All @@ -156,8 +155,8 @@ final global = UnmodifiableListView([
}

var result = color.changeHsl(
lightness: (color.lightness - amount.valueInRange(0, 100, "amount"))
.clamp(0, 100));
lightness: clampLikeCss(color.lightness - amount.valueInRange(0, 100, "amount"),
0, 100));

warnForDeprecation(
"darken() is deprecated. "
Expand Down Expand Up @@ -187,8 +186,7 @@ final global = UnmodifiableListView([
}

var result = color.changeHsl(
saturation: (color.saturation + amount.valueInRange(0, 100, "amount"))
.clamp(0, 100));
saturation: clampLikeCss(color.saturation + amount.valueInRange(0, 100, "amount"), 0, 100));

warnForDeprecation(
"saturate() is deprecated. "
Expand All @@ -210,8 +208,7 @@ final global = UnmodifiableListView([
}

var result = color.changeHsl(
saturation: (color.saturation - amount.valueInRange(0, 100, "amount"))
.clamp(0, 100));
saturation: clampLikeCss(color.saturation - amount.valueInRange(0, 100, "amount"),0, 100));

warnForDeprecation(
"desaturate() is deprecated. "
Expand Down Expand Up @@ -946,8 +943,7 @@ SassColor _adjustColor(
channelArgs[2]),
// The color space doesn't matter for alpha, as long as it's not
// strictly bounded.
_adjustChannel(color, ColorChannel.alpha, color.alphaOrNull, alphaArg)
?.clamp(0, 1));
_adjustChannel(color, ColorChannel.alpha, color.alphaOrNull, alphaArg).andThen((alpha) => clampLikeCss(alpha, 0, 1)));

/// Returns [oldValue] adjusted by [adjustmentArg] according to the definition
/// in [color]'s space's [channel].
Expand Down Expand Up @@ -1063,8 +1059,8 @@ Value _rgb(String name, List<Value> arguments) {
arguments[1].assertNumber("green"),
arguments[2].assertNumber("blue"),
alpha.andThen((alpha) =>
_percentageOrUnitless(alpha.assertNumber("alpha"), 1, "alpha")
.clamp(0, 1)) ??
clampLikeCss(_percentageOrUnitless(alpha.assertNumber("alpha"), 1, "alpha"),
0, 1)) ??
1,
fromRgbFunction: true);
}
Expand Down Expand Up @@ -1101,7 +1097,7 @@ Value _rgbTwoArg(String name, List<Value> arguments) {

var alpha = arguments[1].assertNumber("alpha");
return color
.changeAlpha(_percentageOrUnitless(alpha, 1, "alpha").clamp(0, 1));
.changeAlpha(clampLikeCss(_percentageOrUnitless(alpha, 1, "alpha"), 0, 1));
}

/// The implementation of the three- and four-argument `hsl()` and `hsla()`
Expand All @@ -1121,8 +1117,7 @@ Value _hsl(String name, List<Value> arguments) {
arguments[1].assertNumber("saturation"),
arguments[2].assertNumber("lightness"),
alpha.andThen((alpha) =>
_percentageOrUnitless(alpha.assertNumber("alpha"), 1, "alpha")
.clamp(0, 1)) ??
clampLikeCss(_percentageOrUnitless(alpha.assertNumber("alpha"), 1, "alpha"), 0, 1)) ??
1);
}

Expand Down Expand Up @@ -1236,8 +1231,7 @@ SassColor _opacify(String name, List<Value> arguments) {
}

var result = color.changeAlpha(
(color.alpha + amount.valueInRangeWithUnit(0, 1, "amount", ""))
.clamp(0, 1));
clampLikeCss((color.alpha + amount.valueInRangeWithUnit(0, 1, "amount", "")), 0, 1));

warnForDeprecation(
"$name() is deprecated. "
Expand All @@ -1259,8 +1253,7 @@ SassColor _transparentize(String name, List<Value> arguments) {
}

var result = color.changeAlpha(
(color.alpha - amount.valueInRangeWithUnit(0, 1, "amount", ""))
.clamp(0, 1));
clampLikeCss((color.alpha - amount.valueInRangeWithUnit(0, 1, "amount", "")), 0, 1));

warnForDeprecation(
"$name() is deprecated. "
Expand Down Expand Up @@ -1390,8 +1383,8 @@ Value _parseChannels(String functionName, Value input,
var alpha = switch (alphaValue) {
null => 1.0,
SassString(hasQuotes: false, text: 'none') => null,
_ => _percentageOrUnitless(alphaValue.assertNumber(name), 1, 'alpha')
.clamp(0, 1)
_ => clampLikeCss(_percentageOrUnitless(alphaValue.assertNumber(name), 1, 'alpha')
, 0, 1)
.toDouble()
};

Expand Down Expand Up @@ -1550,7 +1543,7 @@ double? _channelFromValue(ColorChannel channel, SassNumber? value,
LinearChannel() when !clamp =>
_percentageOrUnitless(value, channel.max, channel.name),
LinearChannel(:var lowerClamped, :var upperClamped) =>
_percentageOrUnitless(value, channel.max, channel.name).clamp(
clampLikeCss(_percentageOrUnitless(value, channel.max, channel.name),
lowerClamped ? channel.min : double.negativeInfinity,
upperClamped ? channel.max : double.infinity),
_ => value.coerceValueToUnit('deg', channel.name) % 360
Expand Down
7 changes: 4 additions & 3 deletions lib/src/js/legacy/value/color.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import 'package:js/js.dart';

import '../../../util/nullable.dart';
import '../../../util/number.dart';
import '../../../value.dart';
import '../../reflection.dart';
Expand Down Expand Up @@ -46,7 +47,7 @@ final JSClass legacyColorClass = createJSClass('sass.types.Color',
}

thisArg.dartValue = SassColor.rgb(
_clamp(red), _clamp(green), _clamp(blue), alpha?.clamp(0, 1) ?? 1);
_clamp(red), _clamp(green), _clamp(blue), alpha.andThen((alpha) => clampLikeCss(alpha.toDouble(), 0, 1)) ?? 1);
})
..defineMethods({
'getR': (_NodeSassColor thisArg) => thisArg.dartValue.red,
Expand All @@ -63,10 +64,10 @@ final JSClass legacyColorClass = createJSClass('sass.types.Color',
thisArg.dartValue = thisArg.dartValue.changeRgb(blue: _clamp(value));
},
'setA': (_NodeSassColor thisArg, num value) {
thisArg.dartValue = thisArg.dartValue.changeRgb(alpha: value.clamp(0, 1));
thisArg.dartValue = thisArg.dartValue.changeRgb(alpha: clampLikeCss(value.toDouble(), 0, 1));
}
});

/// Clamps [channel] within the range 0, 255 and rounds it to the nearest
/// integer.
int _clamp(num channel) => fuzzyRound(channel.clamp(0, 255));
int _clamp(num channel) => fuzzyRound(clampLikeCss(channel.toDouble(), 0, 255));
6 changes: 6 additions & 0 deletions lib/src/util/number.dart
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,12 @@ double moduloLikeSass(double num1, double num2) {
return result == 0 ? 0 : result + num2;
}

//// Returns [num] clamped between [lowerBound] and [upperBound], with `NaN`
//// preferring the lower bound (unlike Dart for which it prefers the upper
//// bound).
double clampLikeCss(double number, double lowerBound, double upperBound) =>
number.isNaN ? lowerBound : number.clamp(lowerBound, upperBound);

/// Returns the square root of [number].
SassNumber sqrt(SassNumber number) {
number.assertNoUnits("number");
Expand Down
16 changes: 0 additions & 16 deletions lib/src/value/color.dart
Original file line number Diff line number Diff line change
Expand Up @@ -523,22 +523,6 @@ class SassColor extends Value {
alpha.andThen((alpha) => fuzzyAssertRange(alpha, 0, 1, "alpha")) {
assert(format == null || _space == ColorSpace.rgb);
assert(space != ColorSpace.lms);

_checkChannel(channel0OrNull, space.channels[0].name);
_checkChannel(channel1OrNull, space.channels[1].name);
_checkChannel(channel2OrNull, space.channels[2].name);
}

/// Throws a [RangeError] if [channel] isn't a finite number.
void _checkChannel(double? channel, String name) {
switch (channel) {
case null:
return;
case double(isNaN: true):
throw RangeError.value(channel, name, 'must be a number.');
case double(isFinite: false):
throw RangeError.value(channel, name, 'must be finite.');
}
}

/// If [hue] isn't null, normalizes it to the range `[0, 360)`.
Expand Down
3 changes: 2 additions & 1 deletion lib/src/value/color/gamut_map_method/clip.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import 'package:meta/meta.dart';

import '../../../util/number.dart';
import '../../color.dart';

/// Gamut mapping by clipping individual channels.
Expand All @@ -24,7 +25,7 @@ final class ClipGamutMap extends GamutMapMethod {
double? _clampChannel(double? value, ColorChannel channel) => value == null
? null
: switch (channel) {
LinearChannel(:var min, :var max) => value.clamp(min, max),
LinearChannel(:var min, :var max) => clampLikeCss(value, min, max),
_ => value
};
}
35 changes: 13 additions & 22 deletions lib/src/visitor/serialize.dart
Original file line number Diff line number Diff line change
Expand Up @@ -597,14 +597,11 @@ final class _SerializeVisitor
_buffer
..write(value.space)
..writeCharCode($lparen);
_writeChannel(value.channel0OrNull);
if (!_isCompressed && !value.isChannel0Missing) _buffer.write('deg');
_writeChannel(value.channel0OrNull, _isCompressed ? null : 'deg');
_buffer.writeCharCode($space);
_writeChannel(value.channel1OrNull);
if (!value.isChannel1Missing) _buffer.writeCharCode($percent);
_writeChannel(value.channel1OrNull, '%');
_buffer.writeCharCode($space);
_writeChannel(value.channel2OrNull);
if (!value.isChannel2Missing) _buffer.writeCharCode($percent);
_writeChannel(value.channel2OrNull, '%');
_maybeWriteSlashAlpha(value);
_buffer.writeCharCode($rparen);

Expand Down Expand Up @@ -672,10 +669,7 @@ final class _SerializeVisitor
_buffer.writeCharCode($space);
_writeChannel(value.channel1OrNull);
_buffer.writeCharCode($space);
_writeChannel(value.channel2OrNull);
if (!_isCompressed && !value.isChannel2Missing && polar) {
_buffer.write('deg');
}
_writeChannel(value.channel2OrNull, polar && !_isCompressed? 'deg' : null);
_maybeWriteSlashAlpha(value);
_buffer.writeCharCode($rparen);

Expand All @@ -685,11 +679,14 @@ final class _SerializeVisitor
}

/// Writes a [channel] which may be missing.
void _writeChannel(double? channel) {
void _writeChannel(double? channel, [String? unit]) {
if (channel == null) {
_buffer.write('none');
} else {
} else if (channel.isFinite) {
_writeNumber(channel);
if (unit != null) _buffer.write(unit);
} else {
visitNumber(SassNumber(channel, unit));
}
}

Expand Down Expand Up @@ -866,13 +863,11 @@ final class _SerializeVisitor
var opaque = fuzzyEquals(color.alpha, 1);
var hsl = color.toSpace(ColorSpace.hsl);
_buffer.write(opaque ? "hsl(" : "hsla(");
_writeNumber(hsl.channel('hue'));
_writeChannel(hsl.channel('hue'));
_buffer.write(_commaSeparator);
_writeNumber(hsl.channel('saturation'));
_buffer.writeCharCode($percent);
_writeChannel(hsl.channel('saturation'), '%');
_buffer.write(_commaSeparator);
_writeNumber(hsl.channel('lightness'));
_buffer.writeCharCode($percent);
_writeChannel(hsl.channel('lightness'), '%');

if (!opaque) {
_buffer.write(_commaSeparator);
Expand Down Expand Up @@ -948,11 +943,7 @@ final class _SerializeVisitor
_writeOptionalSpace();
_buffer.writeCharCode($slash);
_writeOptionalSpace();
if (color.isAlphaMissing) {
_buffer.write('none');
} else {
_writeNumber(color.alpha);
}
_writeChannel(color.alphaOrNull);
}

void visitFunction(SassFunction function) {
Expand Down

0 comments on commit 3d7eace

Please sign in to comment.