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
79 changes: 37 additions & 42 deletions pkgs/csslib/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,56 +1,51 @@
## 1.0.3-wip

- Correct `Font.hashCode` for partial/empty font styles and distribute hashes
across font families and other properties, avoiding hash-table collisions.
- `Font.scale` keeps the line height (scaling pixel heights and keeping
relative ratios), copies the font-family list, and no longer throws when
the font size is unspecified.
- 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 `Rgba.fromArgbValue`, `Rgba.argbValue` and `Hsla.color`, and preserve
alpha for grayscale colors in `Hsla.fromRgba`.
- Speed up named CSS color lookups by indexing the color table.
- Avoid recursive tokenizer calls when skipping CSS comments and whitespace,
preventing stack overflow on comment-heavy stylesheets.
- End HTML comments at the first `-->` even when more dashes precede it, and
don't end comments at a NUL character.
- Deep-clone declaration style payloads and preserve Dart style priorities;
detach mutable font-family lists in cloned font expressions.
- Fix `TokenKind.decimalToHex` hanging on negative input.
- Preserve nested group terms, IE7-prefixed declaration flags, and variable
usage state when cloning CSS expression/declaration nodes.
- Serialize partial font styles without bogus family names, `nullpx` sizes or
trailing spaces; preserve explicit line heights without font weight and
keep the `px` unit on pixel line heights (a unitless value is a multiplier);
include the font style and variant.
- Correct `Font.hashCode` for partial/empty font styles.
- `Font.scale` keeps the line height (scaling pixel heights and keeping
relative ratios) and no longer throws when the font size is unspecified.
- `Color.css` now reads the `hsl()`/`hsla()` hue as degrees (optional `deg`)
instead of a 0..1 fraction, and accepts percentages for saturation, lightness
and alpha. Functional colors with the wrong number of components or invalid
or non-finite values now throw a `FormatException`.
- Reduce allocations when tokenizing identifiers.
- Speed up tokenizing by indexing unit and directive keywords by length.
- Recognize the `@left-bottom` page-margin directive, and stop parsing
`@right-bottom` as `@left-bottom`.
- Fix `@namespace` serialization: quote bare URIs in pretty output and stop
doubling already-quoted URIs.
- Flatten nested top-level selectors with a single ordered pass instead of
repeated linear searches and list insertions on large stylesheets.
- Recognize the `rebeccapurple` color keyword.
- Deep-clone selector groups, selector sequences, identifiers, functional
pseudo-selector arguments, and legacy pseudo-element flags instead of
sharing mutable AST nodes between the original and its clone.
- Preserve nested group terms, IE7-prefixed declaration flags, and variable
usage state when cloning CSS expression/declaration nodes.
- Deep-clone declaration style payloads and preserve Dart style priorities;
detach mutable font-family lists in cloned font expressions.
- Fix `Rgba.fromArgbValue`, `Rgba.argbValue` and `Hsla.color`, preserve alpha
for grayscale colors in `Hsla.fromRgba`, and keep the exact 8-bit alpha in
`Color.rgba`, `Color.hsla` and `Hsla.fromArgbValue` instead of rounding it to
two digits. `Rgba.fromString` and `Hsla.fromString` parse the CSS color once,
and `Color.css` throws a `FormatException` for unsupported colors.
- Correct CSS namespace URI serialization in pretty-printed stylesheets while
preserving compact `url()` representation.
- 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.
`Color.css` also accepts named colors and `transparent`, and
`Rgba.fromString`/`Hsla.fromString` now parse their argument only once.
- `Color.css` now reads the `hsl()`/`hsla()` hue as a CSS angle (degrees by
default, or `deg`, `grad`, `rad` and `turn`) instead of a 0..1 fraction, and
accepts percentages for saturation, lightness, RGB channels and alpha.
Functional colors with the wrong number of components or invalid or
non-finite values now throw a `FormatException` whose source is the color.
- Correctly parse unit-like type selectors (`rem`, `vw`, `dpi`, etc.) at the
start of `selector()` and `parseSelectorGroup()` input and of style rules.
- Use native integer hexadecimal formatting for named CSS colors, reducing
temporary allocations and avoiding hangs on negative conversion inputs.
- Speed up named CSS color lookups by indexing the color table.
- Recognize the `@left-bottom` page-margin directive, and stop parsing
`@right-bottom` as `@left-bottom`.
- Recognize the `rebeccapurple` color keyword and add `Color.rebeccaPurple`.
- Reduce repeated CSS unit, directive, and media keyword scans by indexing
keyword tables by length while retaining allocation-free token matching.
- Reduce allocations when tokenizing ordinary CSS identifiers; add a parsing
benchmark and regression coverage for Unicode and escaped identifiers.
- Flatten nested top-level selectors with a single ordered pass instead of
repeated linear searches and list insertions on large stylesheets.
- Avoid recursive tokenizer calls when skipping CSS comments and whitespace,
preventing stack overflow on comment-heavy stylesheets.
- End HTML comments at the first `-->` even when more dashes precede it, and
don't end comments at a NUL character.
- Fix the values of the `aliceblue` color keyword and the `Color.aliceBlue`,
`Color.antiqueWhite` and `Color.peru` constants.
- Fix unhandled exceptions (`RangeError`, `FormatException`, `StateError`,
Expand Down
45 changes: 0 additions & 45 deletions pkgs/csslib/benchmark/font_hash_benchmark.dart

This file was deleted.

39 changes: 0 additions & 39 deletions pkgs/csslib/benchmark/tokenizer_benchmark.dart

This file was deleted.

36 changes: 9 additions & 27 deletions pkgs/csslib/lib/src/property.dart
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ class Color implements _StyleProperty, ColorBase {
// Get alpha blending value 0..255
var alpha = Color.hexToInt(_argb.substring(nextIndex, nextIndex + 2));
// Convert to value from 0..1
a = alpha / 255;
a = double.parse((alpha / 255).toStringAsPrecision(2));
nextIndex += 2;
}
var r = Color.hexToInt(_argb.substring(nextIndex, nextIndex + 2));
Expand Down Expand Up @@ -266,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 @@ -293,30 +293,13 @@ class Color implements _StyleProperty, ColorBase {
return parseNumber(trimmed);
}

int parseRgbChannel(String text) {
final trimmed = text.trim();
if (trimmed.endsWith('%')) {
return (parseFraction(trimmed) * 255).round();
}
return parseNumber(trimmed).toInt();
}
int parseRgbChannel(String text) => parseNumber(text).toInt();

double parseHue(String text) {
final trimmed = text.trim().toLowerCase();
double degrees;
if (trimmed.endsWith('turn')) {
degrees = parseNumber(trimmed.substring(0, trimmed.length - 4)) * 360;
} else if (trimmed.endsWith('grad')) {
degrees = parseNumber(trimmed.substring(0, trimmed.length - 4)) * 0.9;
} else if (trimmed.endsWith('rad')) {
degrees = parseNumber(trimmed.substring(0, trimmed.length - 3)) *
180 /
math.pi;
} else if (trimmed.endsWith('deg')) {
degrees = parseNumber(trimmed.substring(0, trimmed.length - 3));
} else {
degrees = parseNumber(trimmed);
}
final degrees = trimmed.endsWith('deg')
? parseNumber(trimmed.substring(0, trimmed.length - 3))
: parseNumber(trimmed);
// CSS hue is an angle, not the 0..1 fraction expected by Hsla.
// Dart's `%` is never negative here, so -120 wraps to 240 too.
return degrees % 360 / 360;
Expand Down Expand Up @@ -540,7 +523,6 @@ class Color implements _StyleProperty, ColorBase {
static final Color plum = const Color.hex('dda0dd');
static final Color powderBlue = const Color.hex('b0e0e6');
static final Color purple = const Color.hex('800080');
static final Color rebeccaPurple = const Color.hex('663399');
static final Color red = const Color.hex('ff0000');
static final Color rosyBrown = const Color.hex('bc8f8f');
static final Color royalBlue = const Color.hex('4169e1');
Expand Down Expand Up @@ -725,8 +707,8 @@ class Hsla implements _StyleProperty, ColorBase {
var g = (value.toInt() & 0xff00) >> 8;
var b = value.toInt() & 0xff;

// Keep the full 8-bit alpha precision for lossless ARGB round-trips.
a /= 255;
// Convert alpha to 0..1 from (0..255).
a = double.parse((a / 255).toStringAsPrecision(2));

return _createFromRgba(r, g, b, a);
}
Expand Down Expand Up @@ -1136,7 +1118,7 @@ class Font implements _StyleProperty {
);
return Font(
size: size == null ? null : size! * ratio,
family: family?.toList(),
family: family,
weight: weight,
style: style,
variant: variant,
Expand Down
2 changes: 0 additions & 2 deletions pkgs/csslib/lib/src/tokenizer.dart
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,6 @@ class Tokenizer extends TokenizerBase {
return _finishToken(TokenKind.INCOMPLETE_COMMENT);
}
_index = end + 3;
if (_inString) return next();
return _finishToken(TokenKind.HTML_COMMENT);
}

Expand All @@ -470,7 +469,6 @@ class Tokenizer extends TokenizerBase {
return _finishToken(TokenKind.INCOMPLETE_COMMENT);
}
_index = end + 2;
if (_inString) return next();
return _finishToken(TokenKind.COMMENT);
}
}
Expand Down
12 changes: 0 additions & 12 deletions pkgs/csslib/test/color_conversion_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,6 @@ void main() {
expect(Rgba(0xff, 0, 0, 1).argbValue, 0xffff0000);
});

test(
'ARGB round-trips retain each alpha byte, including 0x7f and >= 0x80',
() {
expect(const Color.hex('7f112233').rgba.toHexArgbString(), '7f112233');
expect(Hsla.fromArgbValue(0x7f808080).toHexArgbString(), '7f808080');
expect(Hsla.fromArgbValue(0x80808080).toHexArgbString(), '80808080');
expect(Hsla.fromArgbValue(0xff808080).toHexArgbString(), 'ff808080');
expect(Rgba.fromArgbValue(0xff808080).argbValue, 0xff808080);
expect(Rgba.fromArgbValue(0x80808080).argbValue, 0x80808080);
},
);

test('color string factories decode CSS colors only once', () {
expect(Rgba.fromString('rgba(255,0,0,0.5)').toHexArgbString(), '80ff0000');
expect(
Expand Down
19 changes: 0 additions & 19 deletions pkgs/csslib/test/color_function_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,6 @@ void main() {
test('HSL hue wraps and respects CSS angle units', () {
expect(Color.css('hsl(480deg,100%,50%)'), Color(0x00ff00));
expect(Color.css('hsl(-120deg,100%,50%)'), Color(0x0000ff));
expect(Color.css('hsl(0.5turn,100%,50%)'), Color(0x00ffff));
expect(Color.css('hsl(100grad,100%,50%)'), Color(0x80ff00));
expect(Color.css('hsl(1.5707963267948966rad,100%,50%)'), Color(0x80ff00));
expect(Color.css('HSL(120DEG,100%,50%)'), Color(0x00ff00));
});

Expand All @@ -32,24 +29,8 @@ void main() {
);
});

test('RGB and RGBA accept percentages', () {
expect(Color.css('rgb(100%,0%,0%)'), Color(0xff0000));
expect(
Color.css('rgba(100%,0%,0%,50%)').toHexArgbString(),
'80ff0000',
);
});

test('invalid color arity and nonfinite components fail cleanly', () {
expect(() => Color.css('rgba(10,20,30)'), throwsFormatException);
expect(() => Color.css('rgb(NaN,20,30)'), throwsFormatException);
});

test('component errors report the whole color as their source', () {
expect(
() => Color.css('rgb(1x,20,30)'),
throwsA(isA<FormatException>()
.having((e) => e.source, 'source', 'rgb(1x,20,30)')),
);
});
}
22 changes: 22 additions & 0 deletions pkgs/csslib/test/color_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ void main() {
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 All @@ -74,4 +78,22 @@ void main() {
expect(prettyPrint(stylesheet), 'a {\n color: #f0f8ff;\n}');
});
});

group('named color lookup', () {
test('remains case insensitive', () {
expect(TokenKind.colorValue(TokenKind.matchColorName('RED')!), 0xFF0000);
expect(
TokenKind.colorValue(TokenKind.matchColorName('aliceblue')!),
0xF0F8FF,
);
expect(TokenKind.matchColorName('not-a-color'), isNull);
});

test('reverse lookups preserve first canonical aliases', () {
expect(TokenKind.hexToColorName(0x00FFFF), 'aqua');
expect(TokenKind.hexToColorName(0xFF00FF), 'fuchsia');
expect(TokenKind.hexToColorName(0xF0F8FF), 'aliceblue');
expect(TokenKind.hexToColorName(0x010203), isNull);
});
});
}
Loading
Loading