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 (``, ``) now exit foreign content before reprocessing in HTML mode, matching the WHATWG HTML standard. - `<` and `>` are now escaped as `<` and `>` when serializing attribute values in `htmlSerializeEscape`, `innerHtml`, and `outerHtml`, matching the WHATWG HTML standard. - Fix `Node.attributeSpans` and `Node.attributeValueSpans` throwing a `TypeError` when a start tag emits tokenizer parse errors, and preserve the first occurrence's span on duplicate attributes. @@ -10,12 +22,6 @@ - Fix `querySelector` and `querySelectorAll` throwing a null-check `TypeError` instead of `FormatException` on empty `:not()` selectors. - Fix `TreeBuilder` not updating `Text.sourceSpan` when merging consecutive foster-parented text nodes before a ``. - Fix `ParseError.message` throwing a null-check `TypeError` on `unexpected-EOF-after-attribute-value` tokenizer errors, and align tokenizer error codes `this-closing-flag-on-end-tag` -> `self-closing-flag-on-end-tag` and `expected-end-of-tag-but-got-eof` -> `expected-end-of-tag-name-but-got-eof` with `errorMessages`. -- 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. -- `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. -- Reduce allocations when decoding numeric and named character references and when sniffing `` declarations. -- Fix `querySelector` and `querySelectorAll` matching of `:root` (now the element whose parent is the `Document`), `:empty` and `:blank` (previously inverted), 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, and class selectors no longer allocate a class set per candidate element. -- Fix `Element.text`, `DocumentFragment.text` and `Node.textContent` throwing a `StackOverflowError` on very deeply nested elements; text is now extracted iteratively. ## 0.15.7 diff --git a/pkgs/html/lib/src/css_class_set.dart b/pkgs/html/lib/src/css_class_set.dart index dfbb893d00..65fc184144 100644 --- a/pkgs/html/lib/src/css_class_set.dart +++ b/pkgs/html/lib/src/css_class_set.dart @@ -7,6 +7,7 @@ import 'dart:collection'; import '../dom.dart'; +import 'constants.dart' show isWhitespaceCC; // Scans class tokens without creating an ElementCssClassSet or temporary set. // HTML's class separator is ASCII whitespace (not arbitrary Unicode space). @@ -14,11 +15,11 @@ bool hasHtmlClassToken(String classes, String value) { if (value.isEmpty) return false; var i = 0; while (i < classes.length) { - while (i < classes.length && _isWhitespace(classes.codeUnitAt(i))) { + while (i < classes.length && isWhitespaceCC(classes.codeUnitAt(i))) { i++; } final start = i; - while (i < classes.length && !_isWhitespace(classes.codeUnitAt(i))) { + while (i < classes.length && !isWhitespaceCC(classes.codeUnitAt(i))) { i++; } if (i - start == value.length && classes.startsWith(value, start)) { @@ -28,13 +29,6 @@ bool hasHtmlClassToken(String classes, String value) { return false; } -bool _isWhitespace(int char) => - char == 0x20 || - char == 0x09 || - char == 0x0A || - char == 0x0C || - char == 0x0D; - class ElementCssClassSet extends _CssClassSetImpl { final Element _element; @@ -44,11 +38,6 @@ class ElementCssClassSet extends _CssClassSetImpl { ElementCssClassSet(this._element); - // Selectors use the direct helper to avoid allocating a set wrapper. - @override - bool contains(Object? value) => - value is String && hasHtmlClassToken(_element.className, value); - @override Set readClasses() { final s = LinkedHashSet(); diff --git a/pkgs/html/lib/src/query_selector.dart b/pkgs/html/lib/src/query_selector.dart index cedf3fb309..61a485d938 100644 --- a/pkgs/html/lib/src/query_selector.dart +++ b/pkgs/html/lib/src/query_selector.dart @@ -247,22 +247,14 @@ class SelectorEvaluator extends Visitor { final numericLiteral = literal.value as num; final parent = _element!.parentNode; - if (parent == null || - !numericLiteral.isFinite || - numericLiteral <= 0 || - numericLiteral != numericLiteral.toInt()) { - return false; - } - var index = 0; - for (final sibling in parent.nodes) { - if (sibling is Element) { - index++; - if (identical(sibling, _element)) { - return index == numericLiteral; - } - } + if (parent == null) return false; + var index = 1; + for (var e = _element!.previousElementSibling; + e != null; + e = e.previousElementSibling) { + index++; } - return false; + return index == numericLiteral; } break; diff --git a/pkgs/html/test/dom_text_extraction_regression_test.dart b/pkgs/html/test/dom_text_extraction_regression_test.dart index ea6f6cdf5c..0e94cd7846 100644 --- a/pkgs/html/test/dom_text_extraction_regression_test.dart +++ b/pkgs/html/test/dom_text_extraction_regression_test.dart @@ -3,23 +3,9 @@ // See LICENSE file in the project root for details. import 'package:html/dom.dart'; -import 'package:html/parser.dart'; import 'package:test/test.dart'; void main() { - test('text and textContent agree for mixed Hebrew markup', () { - final fragment = parseFragment( - '
אבגדהו' - '
זח' - '

ט

', - ); - final section = fragment.children.single; - expect(section.text, 'אבגדהוזחט'); - expect(section.textContent(convertBRsToNewlines: false), 'אבגדהוזחט'); - expect(section.textContent(convertBRsToNewlines: true), 'אבגדהו\nזחט'); - expect(fragment.text, 'אבגדהוזחט'); - }); - test('ordinary BR is a line break but SVG BR is not', () { final svgBr = Document().createElementNS('http://www.w3.org/2000/svg', 'br') ..append(Text('inside')); @@ -35,23 +21,6 @@ void main() { ); }); - test('BR element itself converts to a newline', () { - final br = Element.tag('br'); - expect(br.text, ''); - expect(br.textContent(convertBRsToNewlines: true), '\n'); - final svgBr = - Document().createElementNS('http://www.w3.org/2000/svg', 'br'); - expect(svgBr.textContent(convertBRsToNewlines: true), ''); - }); - - test('comments and doctype are not included in concatenated text', () { - final fragment = DocumentFragment() - ..append(Comment('skip')) - ..append(Text('א')) - ..append(Element.tag('span')..append(Text('ב'))); - expect(fragment.text, 'אב'); - }); - test('5000-deep book text extraction does not recurse', () { final root = Element.tag('div'); var child = root; @@ -64,9 +33,4 @@ void main() { expect(root.text, 'שלום עולם'); expect(root.textContent(convertBRsToNewlines: true), 'שלום עולם'); }); - - test('empty elements and fragments produce empty text', () { - expect(Element.tag('div').text, ''); - expect(DocumentFragment().text, ''); - }); } diff --git a/pkgs/html/test/query_selector_regression_test.dart b/pkgs/html/test/query_selector_regression_test.dart index 665b439e46..9421849e29 100644 --- a/pkgs/html/test/query_selector_regression_test.dart +++ b/pkgs/html/test/query_selector_regression_test.dart @@ -61,7 +61,7 @@ void main() { test('deep descendant queries retain preorder without recursion', () { final root = Element.tag('main'); var current = root; - for (var i = 0; i < 100000; i++) { + for (var i = 0; i < 20000; i++) { final child = Element.tag('section'); current.append(child); current = child; diff --git a/pkgs/markdown/lib/src/inline_syntaxes/autolink_extension_syntax.dart b/pkgs/markdown/lib/src/inline_syntaxes/autolink_extension_syntax.dart index 6afa9e20e4..0ccdc419a0 100644 --- a/pkgs/markdown/lib/src/inline_syntaxes/autolink_extension_syntax.dart +++ b/pkgs/markdown/lib/src/inline_syntaxes/autolink_extension_syntax.dart @@ -135,7 +135,6 @@ class AutolinkExtensionSyntax extends InlineSyntax { /// Preserve existing percent escapes. Encoding the whole URI would turn /// an already escaped percent sign into a double-encoded URL. static String _encodeHref(String destination) { - if (!destination.contains('%')) return Uri.encodeFull(destination); return destination.splitMapJoin( _percentEscapePattern, onMatch: (match) => match.match, diff --git a/pkgs/markdown/test/document_test.dart b/pkgs/markdown/test/document_test.dart index ab320542c0..ac9a561e9c 100644 --- a/pkgs/markdown/test/document_test.dart +++ b/pkgs/markdown/test/document_test.dart @@ -151,23 +151,6 @@ void main() { expect(second, contains('href="#fn-b"')); }); - test('orders Unicode footnotes by first reference, not definition', () { - const firstLabel = 'שני'; - const secondLabel = 'ראשון'; - final html = markdownToHtml( - 'ראה[^$firstLabel] ואחר כך[^$secondLabel].\n\n' - '[^$secondLabel]: הערה ראשונה\n' - '[^$firstLabel]: הערה שנייה', - extensionSet: ExtensionSet.gitHubWeb, - ); - final firstId = Uri.encodeComponent(firstLabel); - final secondId = Uri.encodeComponent(secondLabel); - final firstDefinition = html.indexOf('
  • '); - final secondDefinition = html.indexOf('
  • '); - expect(firstDefinition, greaterThanOrEqualTo(0)); - expect(secondDefinition, greaterThan(firstDefinition)); - }); - test('orders escaped punctuation footnotes by first reference', () { const firstLabel = 'one'; const secondLabel = r'\['; diff --git a/pkgs/markdown/test/html_renderer_test.dart b/pkgs/markdown/test/html_renderer_test.dart index 8ddea918ea..1de989a527 100644 --- a/pkgs/markdown/test/html_renderer_test.dart +++ b/pkgs/markdown/test/html_renderer_test.dart @@ -102,13 +102,6 @@ void main() { expect(renderer.render([Element.text('p', 'first')]), '

    first

    '); expect(renderer.render([Text(' preserve spaces')]), ' preserve spaces'); }); - - test('resets generated ID uniqueness for every render', () { - final renderer = HtmlRenderer(); - final heading = Element.text('h2', 'Heading')..generatedId = 'heading'; - expect(renderer.render([heading]), '

    Heading

    '); - expect(renderer.render([heading]), '

    Heading

    '); - }); }); group('HtmlRenderer text fast path', () {