From 9af72ed9d247335e1bfc70540bbcbeb06257d0b4 Mon Sep 17 00:00:00 2001
From: palmoni5
Date: Sat, 14 Nov 2026 18:46:43 +0200
Subject: [PATCH] chore: apply upstream maintainer review to csslib, html and
markdown
Replays the review fixes pushed to the dart-lang/tools topic branches
(#2826-#2836, #2838, #2842, #2843, #2845, #2846, #2850, #2852, #2853,
#2857, #2862, #2863) onto the integration branch:
- csslib: round converted alpha to two digits again, drop rgb()
percentages and non-degree hue units, drop the Color.rebeccaPurple
constant, keep sharing the family list in Font.scale, throw
FormatException for unknown color functions, remove unreachable
comment branches, and trim tests and benchmarks.
- html: reuse isWhitespaceCC, drop the classes.contains override,
simplify :nth-child, and trim tests. The :empty/:blank fix stays here
until dart-lang/tools#2734 lands.
- markdown: drop the redundant autolink early return and two tests.
CHANGELOG sections are rebuilt from the topic branches' entries.
---
pkgs/csslib/CHANGELOG.md | 79 ++++++++--------
.../csslib/benchmark/font_hash_benchmark.dart | 45 ----------
.../csslib/benchmark/tokenizer_benchmark.dart | 39 --------
pkgs/csslib/lib/src/property.dart | 36 ++------
pkgs/csslib/lib/src/tokenizer.dart | 2 -
pkgs/csslib/test/color_conversion_test.dart | 12 ---
pkgs/csslib/test/color_function_test.dart | 19 ----
pkgs/csslib/test/color_test.dart | 22 +++++
.../test/declaration_group_clone_test.dart | 44 ---------
pkgs/csslib/test/font_hash_test.dart | 9 --
pkgs/csslib/test/font_scale_test.dart | 14 ---
pkgs/csslib/test/hex_formatting_test.dart | 9 --
pkgs/csslib/test/keyword_index_test.dart | 16 ----
pkgs/csslib/test/selector_clone_test.dart | 90 -------------------
.../test/selector_first_token_test.dart | 7 --
pkgs/csslib/test/token_lookup_test.dart | 46 +---------
.../csslib/test/tokenizer_fast_path_test.dart | 11 ---
pkgs/html/CHANGELOG.md | 18 ++--
pkgs/html/lib/src/css_class_set.dart | 17 +---
pkgs/html/lib/src/query_selector.dart | 22 ++---
.../dom_text_extraction_regression_test.dart | 36 --------
.../test/query_selector_regression_test.dart | 2 +-
.../autolink_extension_syntax.dart | 1 -
pkgs/markdown/test/document_test.dart | 17 ----
pkgs/markdown/test/html_renderer_test.dart | 7 --
25 files changed, 94 insertions(+), 526 deletions(-)
delete mode 100644 pkgs/csslib/benchmark/font_hash_benchmark.dart
delete mode 100644 pkgs/csslib/benchmark/tokenizer_benchmark.dart
diff --git a/pkgs/csslib/CHANGELOG.md b/pkgs/csslib/CHANGELOG.md
index 49998e90f8..2329efc656 100644
--- a/pkgs/csslib/CHANGELOG.md
+++ b/pkgs/csslib/CHANGELOG.md
@@ -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`,
diff --git a/pkgs/csslib/benchmark/font_hash_benchmark.dart b/pkgs/csslib/benchmark/font_hash_benchmark.dart
deleted file mode 100644
index eff2de73fd..0000000000
--- a/pkgs/csslib/benchmark/font_hash_benchmark.dart
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-// ignore_for_file: avoid_print
-
-import 'package:csslib/parser.dart';
-
-/// Compare baseline and optimized branches:
-/// dart run benchmark/font_hash_benchmark.dart
-///
-/// Many font styles share the same size, as they do in document rendering.
-/// The old hash function collapsed most of them into the same bucket.
-void main() {
- const count = 2000;
- const passes = 3;
- final fonts = List.generate(
- count,
- (i) => Font(size: 16, family: ['font-$i']),
- );
-
- // Warm up compilation and the hash-table implementation.
- for (var i = 0; i < 2; i++) {
- final warmup = {};
- for (var j = 0; j < fonts.length; j++) {
- warmup[fonts[j]] = j;
- }
- }
-
- final stopwatch = Stopwatch()..start();
- var sum = 0;
- for (var pass = 0; pass < passes; pass++) {
- final map = {};
- for (var i = 0; i < fonts.length; i++) {
- map[fonts[i]] = i;
- }
- for (final font in fonts) {
- sum += map[font]!;
- }
- }
- stopwatch.stop();
- final elapsed = stopwatch.elapsedMicroseconds;
- print('Hash insert/lookup: $count fonts x $passes passes, '
- 'sum=$sum, elapsed=$elapsed us');
-}
diff --git a/pkgs/csslib/benchmark/tokenizer_benchmark.dart b/pkgs/csslib/benchmark/tokenizer_benchmark.dart
deleted file mode 100644
index 434584cec9..0000000000
--- a/pkgs/csslib/benchmark/tokenizer_benchmark.dart
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file
-// for details. All rights reserved. Use of this source code is governed by a
-// BSD-style license that can be found in the LICENSE file.
-
-// ignore_for_file: avoid_print
-
-import 'package:csslib/parser.dart';
-
-/// Run with: dart run benchmark/tokenizer_benchmark.dart
-///
-/// Compare identical inputs, SDKs and modes across revisions. This exercises
-/// the repeated short style declarations common to inline HTML rendering.
-void main() {
- const stylesheet = '''
-.entry-שלום {
- font-family: FrankRuhl;
- font-size: 18px;
- line-height: 1.4;
- color: #334455;
- background-color: rgba(25, 30, 35, 0.5);
- margin-right: 0.5em;
- padding: 2px 4px;
-}
-''';
- const iterations = 20000;
- // Warm up the parser/JIT before measuring.
- for (var i = 0; i < 1000; i++) {
- parse(stylesheet);
- }
- final stopwatch = Stopwatch()..start();
- var rules = 0;
- for (var i = 0; i < iterations; i++) {
- rules += parse(stylesheet).topLevels.length;
- }
- stopwatch.stop();
- final elapsed = stopwatch.elapsedMicroseconds;
- final perParse = elapsed / iterations;
- print('Parsed $rules rules in $elapsed us ($perParse us/parse)');
-}
diff --git a/pkgs/csslib/lib/src/property.dart b/pkgs/csslib/lib/src/property.dart
index bd8371ab9d..d4e4692da0 100644
--- a/pkgs/csslib/lib/src/property.dart
+++ b/pkgs/csslib/lib/src/property.dart
@@ -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));
@@ -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.
@@ -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;
@@ -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');
@@ -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);
}
@@ -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,
diff --git a/pkgs/csslib/lib/src/tokenizer.dart b/pkgs/csslib/lib/src/tokenizer.dart
index 27b5abe120..62df68a2bd 100644
--- a/pkgs/csslib/lib/src/tokenizer.dart
+++ b/pkgs/csslib/lib/src/tokenizer.dart
@@ -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);
}
@@ -470,7 +469,6 @@ class Tokenizer extends TokenizerBase {
return _finishToken(TokenKind.INCOMPLETE_COMMENT);
}
_index = end + 2;
- if (_inString) return next();
return _finishToken(TokenKind.COMMENT);
}
}
diff --git a/pkgs/csslib/test/color_conversion_test.dart b/pkgs/csslib/test/color_conversion_test.dart
index b573fd3fe5..bf6b1041a4 100644
--- a/pkgs/csslib/test/color_conversion_test.dart
+++ b/pkgs/csslib/test/color_conversion_test.dart
@@ -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(
diff --git a/pkgs/csslib/test/color_function_test.dart b/pkgs/csslib/test/color_function_test.dart
index d4a41efad0..f932687329 100644
--- a/pkgs/csslib/test/color_function_test.dart
+++ b/pkgs/csslib/test/color_function_test.dart
@@ -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));
});
@@ -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()
- .having((e) => e.source, 'source', 'rgb(1x,20,30)')),
- );
- });
}
diff --git a/pkgs/csslib/test/color_test.dart b/pkgs/csslib/test/color_test.dart
index 94f41f99df..3222957cc6 100644
--- a/pkgs/csslib/test/color_test.dart
+++ b/pkgs/csslib/test/color_test.dart
@@ -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', () {
@@ -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);
+ });
+ });
}
diff --git a/pkgs/csslib/test/declaration_group_clone_test.dart b/pkgs/csslib/test/declaration_group_clone_test.dart
index 73a9fafdd7..62485e453b 100644
--- a/pkgs/csslib/test/declaration_group_clone_test.dart
+++ b/pkgs/csslib/test/declaration_group_clone_test.dart
@@ -3,55 +3,11 @@
// BSD-style license that can be found in the LICENSE file.
import 'package:csslib/parser.dart';
-import 'package:csslib/visitor.dart';
-import 'package:source_span/source_span.dart';
import 'package:test/test.dart';
import 'testing.dart';
void main() {
- test('cloning a group preserves terms and detaches its list', () {
- final group = GroupTerm(null)
- ..add(NumberTerm(2, '2', null))
- ..add(NumberTerm(5, '5', null));
- final copy = group.clone();
-
- expect((CssPrinter()..visitGroupTerm(copy)).toString(), '(2 5)');
- copy.add(NumberTerm(7, '7', null));
- expect((CssPrinter()..visitGroupTerm(copy)).toString(), '(2 5 7)');
- expect((CssPrinter()..visitGroupTerm(group)).toString(), '(2 5)');
- });
-
- test('IE7-prefixed declarations retain their flag on clone', () {
- final errors = [];
- final sheet = parse('a { *zoom: 1 !important; }', errors: errors);
- expect(errors, isEmpty);
- final rule = sheet.topLevels.single as RuleSet;
- final decl = rule.declarationGroup.declarations.single as Declaration;
- final copy = decl.clone();
-
- expect(decl.property, '*zoom');
- expect(copy.property, '*zoom');
- expect(copy.isIE7, isTrue);
- expect(copy.important, isTrue);
-
- final originalExpr = decl.expression as Expressions;
- final clonedExpr = copy.expression as Expressions;
- clonedExpr.expressions.clear();
- expect(originalExpr.expressions, hasLength(1));
- });
-
- test('cloned variable declarations preserve invalid-usage state', () {
- final span = SourceFile.fromString('var-foo').span(0, 7);
- final original = VarDefinition(Identifier('foo', span), null, span)
- ..badUsage = true;
- final copy = original.clone();
-
- expect(copy.badUsage, isTrue);
- copy.badUsage = false;
- expect(original.badUsage, isTrue);
- });
-
test('included mixin declarations keep groups and IE7 flags', () {
final errors = [];
final sheet = compileCss('''
diff --git a/pkgs/csslib/test/font_hash_test.dart b/pkgs/csslib/test/font_hash_test.dart
index 46070d1599..5648b8eb52 100644
--- a/pkgs/csslib/test/font_hash_test.dart
+++ b/pkgs/csslib/test/font_hash_test.dart
@@ -36,13 +36,4 @@ void main() {
expect(first.hashCode, second.hashCode);
expect({first: 'found'}[second], 'found');
});
-
- test('font hashes distinguish many equal-size distinct families', () {
- final fonts = List.generate(
- 256,
- (i) => Font(size: 16, family: ['family-$i']),
- );
- final distinctHashes = fonts.map((font) => font.hashCode).toSet();
- expect(distinctHashes.length, greaterThan(200));
- });
}
diff --git a/pkgs/csslib/test/font_scale_test.dart b/pkgs/csslib/test/font_scale_test.dart
index 7f72bb54a4..681d1cb6c8 100644
--- a/pkgs/csslib/test/font_scale_test.dart
+++ b/pkgs/csslib/test/font_scale_test.dart
@@ -21,11 +21,6 @@ void main() {
expect(doubled.lineHeight!.inPixels, isTrue);
expect(doubled.lineHeightInPixels, 36);
expect(doubled.weight, FontWeight.bold);
-
- families[0] = 'Changed';
- expect(doubled.family, ['Frank Ruhl', 'serif']);
- doubled.family!.add('Custom');
- expect(original.family, ['Changed', 'serif']);
});
test('relative line height remains a ratio when the font scales', () {
@@ -49,19 +44,10 @@ void main() {
expect(scaled.size, isNull);
expect(scaled.family, ['Alef']);
- family.add('serif');
- expect(scaled.family, ['Alef']);
const withLineHeight = Font(lineHeight: LineHeight(18));
final scaledHeight = withLineHeight.scale(2);
expect(scaledHeight.size, isNull);
expect(scaledHeight.lineHeight!.height, 36);
});
-
- test('font without explicit line height retains its default', () {
- final scaled = const Font(size: 10).scale(3);
- expect(scaled.size, 30);
- expect(scaled.lineHeight, isNull);
- expect(scaled.lineHeightInPixels, closeTo(36, 0.000001));
- });
}
diff --git a/pkgs/csslib/test/hex_formatting_test.dart b/pkgs/csslib/test/hex_formatting_test.dart
index 030e4ad9d0..80270da176 100644
--- a/pkgs/csslib/test/hex_formatting_test.dart
+++ b/pkgs/csslib/test/hex_formatting_test.dart
@@ -3,7 +3,6 @@
// BSD-style license that can be found in the LICENSE file.
import 'package:csslib/parser.dart';
-import 'package:csslib/visitor.dart';
import 'package:test/test.dart';
void main() {
@@ -19,12 +18,4 @@ void main() {
expect(TokenKind.decimalToHex(-1), '-1');
expect(TokenKind.decimalToHex(-255, 4), '-00ff');
});
-
- test('named CSS colors still roundtrip through the parser and printer', () {
- final errors = [];
- final sheet = parse('a { color: aliceblue; }', errors: errors);
- expect(errors, isEmpty);
- expect((CssPrinter()..visitTree(sheet, pretty: true)).toString(),
- 'a {\n color: #f0f8ff;\n}');
- });
}
diff --git a/pkgs/csslib/test/keyword_index_test.dart b/pkgs/csslib/test/keyword_index_test.dart
index a7a44fb667..fdee6cc8d9 100644
--- a/pkgs/csslib/test/keyword_index_test.dart
+++ b/pkgs/csslib/test/keyword_index_test.dart
@@ -6,22 +6,6 @@ import 'package:csslib/parser.dart';
import 'package:test/test.dart';
void main() {
- test('indexed CSS keywords remain ASCII case-insensitive', () {
- expect(TokenKind.matchUnits('PX', 0, 2), TokenKind.UNIT_LENGTH_PX);
- expect(TokenKind.matchUnits('10ReM', 2, 3), TokenKind.UNIT_REM);
- expect(TokenKind.matchDirectives('MEDiA', 0, 5), TokenKind.DIRECTIVE_MEDIA);
- expect(TokenKind.matchMediaOperator('AND', 0, 3), TokenKind.MEDIA_OP_AND);
- });
-
- test('offsets and unknown keywords are unchanged', () {
- expect(TokenKind.matchUnits('font', 0, 4), -1);
- expect(TokenKind.matchUnits('foopx', 0, 5), -1);
- expect(TokenKind.matchDirectives('my-import', 3, 6),
- TokenKind.DIRECTIVE_IMPORT);
- expect(TokenKind.matchMarginDirectives('right-top', 0, 9),
- TokenKind.MARGIN_DIRECTIVE_RIGHTTOP);
- });
-
test('indexed matching agrees with the linear matcher on full tables', () {
for (var unit = TokenKind.UNIT_EM; unit < 700; unit++) {
final name = TokenKind.unitToString(unit)!;
diff --git a/pkgs/csslib/test/selector_clone_test.dart b/pkgs/csslib/test/selector_clone_test.dart
index f261c6ff92..a1e9cd112d 100644
--- a/pkgs/csslib/test/selector_clone_test.dart
+++ b/pkgs/csslib/test/selector_clone_test.dart
@@ -4,99 +4,9 @@
import 'package:csslib/parser.dart';
import 'package:csslib/visitor.dart';
-import 'package:source_span/source_span.dart';
import 'package:test/test.dart';
void main() {
- test('selector group clones isolate list and combinator changes', () {
- final sheet = parse('div, span { color: red; }');
- final original = (sheet.topLevels.single as RuleSet).selectorGroup!;
- final copy = original.clone();
-
- expect(identical(original.selectors, copy.selectors), isFalse);
- copy.selectors.removeLast();
- expect(original.selectors, hasLength(2));
-
- final originalSequence =
- original.selectors.first.simpleSelectorSequences.first;
- final clonedSequence = copy.selectors.first.simpleSelectorSequences.first;
- clonedSequence.combinator = TokenKind.COMBINATOR_GREATER;
- expect(originalSequence.combinator, TokenKind.COMBINATOR_NONE);
- });
-
- test('selector names and attributes are not aliased', () {
- final name = Identifier('original', null);
- final original = ClassSelector(name, null);
- final copy = original.clone();
- name.name = 'changed';
- expect(copy.name, 'original');
-
- final attributeName = Identifier('title', null);
- final attributeValue = Identifier('hello', null);
- final attribute = AttributeSelector(
- attributeName,
- TokenKind.EQUALS,
- attributeValue,
- null,
- ).clone();
- attributeName.name = 'other';
- attributeValue.name = 'world';
- expect(attribute.name, 'title');
- expect(attribute.valueToString(), 'hello');
-
- final namespaceName = Identifier('svg', null);
- final elementName = Identifier('rect', null);
- final namespace = NamespaceSelector(
- namespaceName,
- ElementSelector(elementName, null),
- null,
- ).clone();
- namespaceName.name = 'other';
- elementName.name = 'circle';
- expect(namespace.toString(), 'svg|rect');
- });
-
- test('legacy pseudo elements retain single-colon syntax when cloned', () {
- final name = Identifier('before', null);
- final original = PseudoElementSelector(name, null, isLegacy: true);
- final copy = original.clone();
- name.name = 'after';
- expect(copy.isLegacy, isTrue);
- expect(copy.toString(), ':before');
- });
-
- test('functional pseudo-selector arguments are deeply cloned', () {
- final innerName = Identifier('item', null);
- final nested = Selector(
- [SimpleSelectorSequence(ClassSelector(innerName, null), null)],
- null,
- );
- final original =
- PseudoClassFunctionSelector(Identifier('host', null), nested, null);
- final copy = original.clone();
- innerName.name = 'changed';
- final clonedArgument = copy.argument as Selector;
- final firstSequence = clonedArgument.simpleSelectorSequences.single;
- expect(firstSequence.simpleSelector.name, 'item');
-
- final span = SourceFile.fromString('2').span(0, 1);
- final expr = SelectorExpression([NumberTerm(2, '2', span)], span);
- final pseudo = PseudoElementFunctionSelector(
- Identifier('part', null),
- expr,
- null,
- ).clone();
- expr.expressions.clear();
- expect(pseudo.expression.expressions, hasLength(1));
- });
-
- test('negation argument is detached from original', () {
- final name = Identifier('className', null);
- final negative = NegationSelector(ClassSelector(name, null), null).clone();
- name.name = 'mutated';
- expect(negative.negationArg!.name, 'className');
- });
-
test('parsed style sheet clones print identically and share no names', () {
final sheet = parse('a:before, p::after, svg|rect, [lang|=he], '
'li:nth-child(2n+1):not(.x) > b ~ #i + u, :host(.a) { color: red; }');
diff --git a/pkgs/csslib/test/selector_first_token_test.dart b/pkgs/csslib/test/selector_first_token_test.dart
index 22f0b2b982..29f79bdb86 100644
--- a/pkgs/csslib/test/selector_first_token_test.dart
+++ b/pkgs/csslib/test/selector_first_token_test.dart
@@ -37,11 +37,4 @@ void main() {
expect(compactOutput(sheet), input, reason: input);
}
});
-
- test('ordinary stylesheet value units still parse as units', () {
- final errors = [];
- final sheet = parse('.entry { width: 10px; }', errors: errors);
- expect(errors, isEmpty);
- expect(sheet.topLevels, hasLength(1));
- });
}
diff --git a/pkgs/csslib/test/token_lookup_test.dart b/pkgs/csslib/test/token_lookup_test.dart
index 12bc7b94d7..db78ed75ea 100644
--- a/pkgs/csslib/test/token_lookup_test.dart
+++ b/pkgs/csslib/test/token_lookup_test.dart
@@ -3,29 +3,14 @@
// BSD-style license that can be found in the LICENSE file.
import 'package:csslib/parser.dart';
-import 'package:csslib/visitor.dart';
import 'package:test/test.dart';
-import 'testing.dart';
-
void main() {
- test('named color lookup remains case insensitive', () {
- expect(TokenKind.colorValue(TokenKind.matchColorName('RED')!), 0xFF0000);
+ test('rebeccapurple is a named color keyword', () {
expect(
- TokenKind.colorValue(TokenKind.matchColorName('aliceblue')!),
- 0xF0F8FF,
+ TokenKind.colorValue(TokenKind.matchColorName('rebeccapurple')!),
+ 0x663399,
);
- expect(TokenKind.colorValue(TokenKind.matchColorName('rebeccapurple')!),
- 0x663399);
- expect(Color.rebeccaPurple.argbValue, 0x663399);
- expect(TokenKind.matchColorName('not-a-color'), isNull);
- });
-
- test('reverse color 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);
});
test('left and right bottom page-margin names are distinct', () {
@@ -39,30 +24,5 @@ void main() {
TokenKind.matchMarginDirectives(right, 0, right.length),
TokenKind.MARGIN_DIRECTIVE_RIGHTBOTTOM,
);
-
- final errors = [];
- final parsed = parse(
- '@page { @left-bottom { content: "L"; } '
- '@right-bottom { content: "R"; } }',
- errors: errors,
- );
- expect(errors, isEmpty);
- expect(parsed.topLevels.single, isA());
- expect((_MarginSymbols()..visitTree(parsed)).symbols, [
- TokenKind.MARGIN_DIRECTIVE_LEFTBOTTOM,
- TokenKind.MARGIN_DIRECTIVE_RIGHTBOTTOM,
- ]);
- expect(compactOutput(parsed), contains('@left-bottom'));
- expect(compactOutput(parsed), contains('@right-bottom'));
});
}
-
-class _MarginSymbols extends Visitor {
- final symbols = [];
-
- @override
- void visitMarginGroup(MarginGroup node) {
- symbols.add(node.margin_sym);
- super.visitMarginGroup(node);
- }
-}
diff --git a/pkgs/csslib/test/tokenizer_fast_path_test.dart b/pkgs/csslib/test/tokenizer_fast_path_test.dart
index c4088eac1b..4a1765e397 100644
--- a/pkgs/csslib/test/tokenizer_fast_path_test.dart
+++ b/pkgs/csslib/test/tokenizer_fast_path_test.dart
@@ -7,8 +7,6 @@ import 'package:csslib/visitor.dart';
import 'package:source_span/source_span.dart';
import 'package:test/test.dart';
-import 'testing.dart';
-
void main() {
test('unescaped identifiers preserve names and !important', () {
final errors = [];
@@ -43,13 +41,4 @@ void main() {
expect(decode(r'x\110000'), 'x�');
expect(decode(r'שלום\5d'), 'שלום]');
});
-
- test('long plain identifiers do not change parsed output', () {
- final errors = [];
- final identifier = 'hebrew' * 100;
- final css = '.$identifier { --my-property: some-long-value; }';
- final parsed = parse(css, errors: errors);
- expect(errors, isEmpty);
- expect(compactOutput(parsed), contains(identifier));
- });
}
diff --git a/pkgs/html/CHANGELOG.md b/pkgs/html/CHANGELOG.md
index cfff74bc97..298a31a188 100644
--- a/pkgs/html/CHANGELOG.md
+++ b/pkgs/html/CHANGELOG.md
@@ -1,6 +1,18 @@
## 0.15.8-wip
+- Reduce allocations when decoding numeric and named character references and when sniffing `` declarations.
+- `getElementById`, `getElementsByTagName` and `getElementsByClassName` no longer parse a CSS selector. IDs and class names that are not valid CSS identifiers (such as `a:b`, `a.b` or `1`) now match exactly instead of throwing or matching the wrong element, `getElementById('')` returns `null`, class names are split on HTML ASCII whitespace, and deeply nested documents no longer overflow the stack. **Breaking:** `getElementsByTagName` now matches a single tag name, as in the DOM spec, so selector lists or combinators such as `'h1, h2'` return an empty list, and `''` returns an empty list instead of throwing.
+- Fix `Node.remove` and `NodeList.remove` leaving a stale `parentNode`, `Node.insertBefore`, `NodeList.insert`, `insertAll` and `operator []=` using a shifted index when moving an earlier sibling, and `reparentChildren` emptying a node reparented to itself. Moving all children of another node (`append` of a `DocumentFragment`, `reparentChildren`, `innerHtml`) now runs in linear time.
+- Fix `Element.text`, `DocumentFragment.text` and `Node.textContent` throwing a `StackOverflowError` on very deeply nested elements; text is now extracted iteratively.
- Reduce allocations when parsing and serializing: `HtmlInputStream` no longer copies the input when it needs no newline or surrogate normalization, and `htmlSerializeEscape` copies unescaped runs at once and returns the input unchanged when nothing needs escaping.
+- Fix `querySelector` and `querySelectorAll` matching of `:root` (now the
+ element whose parent is the `Document`) and numeric `:nth-child(n)` (now
+ counts element siblings from 1), and traverse descendants iteratively so
+ deeply nested documents no longer overflow the stack.
+- Class selectors, `[attr~=value]` selectors and `Element.classes` now split
+ their values on ASCII whitespace (space, tab, LF, FF, CR) as the HTML
+ standard requires.
+- Fix `:empty` and `:blank` selector matching (previously inverted).
- `` and `
` end tags in foreign content (`