Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions pkgs/csslib/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
## 1.0.3-wip

- Fix fractional alpha in the numeric `Color` constructor and normalize CSS
short and eight-digit hex colors, with validation of malformed input and
unknown color names. Eight-digit hex colors are now read as `#rrggbbaa`
(CSS order), e.g. `Color.css('#ff000080')` is 50% red; previously the first
byte was treated as alpha.
`Color.css` also accepts named colors and `transparent`, throws a
`FormatException` instead of an `UnsupportedError` for unknown color
functions, and `Rgba.fromString`/`Hsla.fromString` now parse their argument
only once.
- Fix `TokenKind.decimalToHex` hanging on negative input.
- Speed up named CSS color lookups by indexing the color table.
- Recognize the `rebeccapurple` color keyword.
Expand Down
69 changes: 48 additions & 21 deletions pkgs/csslib/lib/src/property.dart
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,11 @@ class Color implements _StyleProperty, ColorBase {

/// Creates a new color from a CSS color string. For more information, see
/// <https://developer.mozilla.org/en/CSS/color>.
Color.css(String color) : _argb = Color._convertCssToArgb(color)!;
///
/// Throws a [FormatException] if [color] is not a supported CSS color.
Comment thread
palmoni5 marked this conversation as resolved.
Resolved
Color.css(String color)
: _argb = Color._convertCssToArgb(color) ??
(throw FormatException('Unsupported CSS color', color));

// TODO(jmesserly): I found the use of percents a bit suprising.
/// HSL takes three values. The [hueDegree] degree on the color wheel; '0' is
Expand Down Expand Up @@ -201,36 +205,53 @@ class Color implements _StyleProperty, ColorBase {
// Conversion routines:

static String _rgbToArgbString(int rgba, num? alpha) {
num? a;
// If alpha is defined then adjust from 0..1 to 0..255 value, if not set
// then a is left as undefined and passed to convertToHexString.
if (alpha != null) {
a = (Color._clamp(alpha, 0, 1) * 255).round();
}

// convertToHexString already takes alpha in the range 0..1 and converts it
// to an 8-bit channel. Multiplying here made every nonzero alpha opaque.
var r = (rgba & 0xff0000) >> 0x10;
var g = (rgba & 0xff00) >> 8;
var b = rgba & 0xff;

return Color.convertToHexString(r, g, b, a);
return Color.convertToHexString(r, g, b, alpha);
}

static const int _rgbCss = 1;
static const int _rgbaCss = 2;
static const int _hslCss = 3;
static const int _hslaCss = 4;

static final _hexDigits = RegExp(r'^[0-9a-fA-F]+$');

/// Parse CSS expressions of the from #rgb, rgb(r,g,b), rgba(r,g,b,a),
/// hsl(h,s,l), hsla(h,s,l,a) and SVG colors (e.g., darkSlateblue, etc.) and
/// convert to argb.
static String? _convertCssToArgb(String value) {
// TODO(terry): Better parser/regex for converting CSS properties.
var color = value.trim().replaceAll('\\s', '');
if (color[0] == '#') {
var v = color.substring(1);
Color.hexToInt(v); // Valid hexadecimal, throws if not.
return v;
} else if (color.isNotEmpty && color[color.length - 1] == ')') {
var color = value.trim();
if (color.isEmpty) {
throw FormatException('Empty CSS color', value);
}
if (color.startsWith('#')) {
var digits = color.substring(1);
if (digits.length == 3 || digits.length == 4) {
final expanded = StringBuffer();
for (var i = 0; i < digits.length; i++) {
expanded
..write(digits[i])
..write(digits[i]);
}
digits = expanded.toString();
}
// int.parse also accepts a sign and surrounding whitespace.
if ((digits.length != 6 && digits.length != 8) ||
!_hexDigits.hasMatch(digits)) {
throw FormatException('Invalid CSS hexadecimal color', value);
}
if (digits.length == 8) {
// CSS #rrggbbaa is stored internally as aarrggbb.
return (digits.substring(6) + digits.substring(0, 6)).toLowerCase();
}
return digits.toLowerCase();
} else if (color.endsWith(')')) {
int type;
if (color.indexOf('rgb(') == 0 || color.indexOf('RGB(') == 0) {
color = color.substring(4);
Expand All @@ -245,7 +266,7 @@ class Color implements _StyleProperty, ColorBase {
type = _hslaCss;
color = color.substring(5);
} else {
throw UnsupportedError('CSS property not implemented');
throw FormatException('Unsupported CSS color', value);
}

color = color.substring(0, color.length - 1); // Strip close paren.
Expand All @@ -272,7 +293,14 @@ class Color implements _StyleProperty, ColorBase {
break;
}
}
return null;

// Color.css should accept the same standard named colors as the CSS
// parser, including the transparent keyword with zero alpha.
if (color.toLowerCase() == 'transparent') return '00000000';
final named = TokenKind.matchColorName(color);
return named == null
? null
: TokenKind.decimalToHex(TokenKind.colorValue(named), 6);
Comment thread
palmoni5 marked this conversation as resolved.
Resolved
}

static int hexToInt(String hex) => int.parse(hex, radix: 16);
Expand Down Expand Up @@ -499,8 +527,7 @@ class Rgba implements _StyleProperty, ColorBase {
b = Color._clamp(blue, 0, 255),
a = (alpha != null) ? Color._clamp(alpha, 0, 1) : alpha;

factory Rgba.fromString(String hexValue) =>
Color.css('#${Color._convertCssToArgb(hexValue)}').rgba;
factory Rgba.fromString(String cssColor) => Color.css(cssColor).rgba;

factory Rgba.fromColor(Color color) => color.rgba;

Expand Down Expand Up @@ -628,8 +655,8 @@ class Hsla implements _StyleProperty, ColorBase {
_l = Color._clamp(lightness, 0, 1),
_a = (alpha != null) ? Color._clamp(alpha, 0, 1) : alpha;

factory Hsla.fromString(String hexValue) {
var rgba = Color.css('#${Color._convertCssToArgb(hexValue)}').rgba;
factory Hsla.fromString(String cssColor) {
final rgba = Color.css(cssColor).rgba;
return _createFromRgba(rgba.r, rgba.g, rgba.b, rgba.a);
}

Expand Down
46 changes: 46 additions & 0 deletions pkgs/csslib/test/color_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,52 @@ void main() {
final color = Color.css('rgba(0, 0, 255, 1.0)');
expect(color, equals(Color.createRgba(0, 0, 255, 1.0)));
});

test('numeric Color constructor preserves fractional alpha', () {
expect(Color(0xff0000, 0).toHexArgbString(), '00ff0000');
expect(Color(0xff0000, 0.5).toHexArgbString(), '80ff0000');
expect(Color(0xff0000, 1).toHexArgbString(), 'ffff0000');
});

test('CSS short hex colors are expanded', () {
expect(Color.css('#F00'), Color(0xff0000));
expect(Color.css('#f008').toHexArgbString(), '88ff0000');
});

test('CSS eight-digit hex uses rrggbbaa order', () {
expect(Color.css('#ff000080').toHexArgbString(), '80ff0000');
expect(Color.css(' #FF0000 '), Color(0xff0000));
});

test('Color.css accepts named color keywords and transparent', () {
expect(Color.css('red'), Color(0xff0000));
expect(Color.css('ALICEBLUE'), Color(0xf0f8ff));
expect(Color.css('transparent').toHexArgbString(), '00000000');
expect(Color.css('Transparent').toHexArgbString(), '00000000');
});

test('Rgba and Hsla fromString keep the alpha channel in place', () {
expect(Rgba.fromString('rgba(255, 0, 0, 0.5)').toHexArgbString(),
'80ff0000');
expect(Rgba.fromString('#ff000080').toHexArgbString(), '80ff0000');
expect(Hsla.fromString('#ff000080').toHexArgbString(), '80ff0000');
});

test('empty and malformed CSS hex is rejected predictably', () {
expect(() => Color.css(''), throwsFormatException);
expect(() => Color.css(' '), throwsFormatException);
expect(() => Color.css('#12'), throwsFormatException);
expect(() => Color.css('#-12345'), throwsFormatException);
expect(() => Color.css('# 12345'), throwsFormatException);
});

test('unknown color names throw a FormatException', () {
expect(() => Color.css('notacolor'), throwsFormatException);
});

test('unknown color functions throw a FormatException', () {
expect(() => Color.css('foo(1,2,3)'), throwsFormatException);
});
});

group('named colors', () {
Expand Down
Loading