diff --git a/pkgs/html/CHANGELOG.md b/pkgs/html/CHANGELOG.md index 49551962fe..47cc50eb35 100644 --- a/pkgs/html/CHANGELOG.md +++ b/pkgs/html/CHANGELOG.md @@ -13,6 +13,8 @@ - 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. ## 0.15.7 diff --git a/pkgs/html/lib/src/css_class_set.dart b/pkgs/html/lib/src/css_class_set.dart index 04553d676b..dfbb893d00 100644 --- a/pkgs/html/lib/src/css_class_set.dart +++ b/pkgs/html/lib/src/css_class_set.dart @@ -8,21 +8,54 @@ import 'dart:collection'; import '../dom.dart'; +// Scans class tokens without creating an ElementCssClassSet or temporary set. +// HTML's class separator is ASCII whitespace (not arbitrary Unicode space). +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))) { + i++; + } + final start = i; + while (i < classes.length && !_isWhitespace(classes.codeUnitAt(i))) { + i++; + } + if (i - start == value.length && classes.startsWith(value, start)) { + return true; + } + } + return false; +} + +bool _isWhitespace(int char) => + char == 0x20 || + char == 0x09 || + char == 0x0A || + char == 0x0C || + char == 0x0D; + class ElementCssClassSet extends _CssClassSetImpl { final Element _element; + // HTML class tokens are separated by ASCII whitespace, not every Unicode + // whitespace character. Reuse the pattern when enumerating classes. + static final RegExp _classWhitespace = RegExp(r'[ \t\n\f\r]+'); + 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(); final classname = _element.className; - for (var name in classname.split(' ')) { - final trimmed = name.trim(); - if (trimmed.isNotEmpty) { - s.add(trimmed); - } + for (final name in classname.split(_classWhitespace)) { + if (name.isNotEmpty) s.add(name); } return s; } diff --git a/pkgs/html/lib/src/query_selector.dart b/pkgs/html/lib/src/query_selector.dart index 38cbcbcce1..cedf3fb309 100644 --- a/pkgs/html/lib/src/query_selector.dart +++ b/pkgs/html/lib/src/query_selector.dart @@ -10,6 +10,7 @@ import 'package:csslib/visitor.dart'; import '../dom.dart'; import 'constants.dart' show isWhitespaceCC; +import 'css_class_set.dart' show hasHtmlClassToken; Element? querySelector(Node node, String selector) => SelectorEvaluator().querySelector(node, _parseSelectorList(selector)); @@ -40,20 +41,39 @@ class SelectorEvaluator extends Visitor { return visitSelectorGroup(selector); } + // Explicit DFS preserves document order without recursive calls, which + // could overflow on deeply nested HTML documents. Element? querySelector(Node root, SelectorGroup selector) { - for (var element in root.nodes.whereType()) { - if (matches(element, selector)) return element; - final result = querySelector(element, selector); - if (result != null) return result; + final stack = >[root.nodes.iterator]; + while (stack.isNotEmpty) { + final cursor = stack.last; + if (!cursor.moveNext()) { + stack.removeLast(); + continue; + } + final node = cursor.current; + if (node is Element) { + if (matches(node, selector)) return node; + if (node.nodes.isNotEmpty) stack.add(node.nodes.iterator); + } } return null; } void querySelectorAll( Node root, SelectorGroup selector, List results) { - for (var element in root.nodes.whereType()) { - if (matches(element, selector)) results.add(element); - querySelectorAll(element, selector, results); + final stack = >[root.nodes.iterator]; + while (stack.isNotEmpty) { + final cursor = stack.last; + if (!cursor.moveNext()) { + stack.removeLast(); + continue; + } + final node = cursor.current; + if (node is Element) { + if (matches(node, selector)) results.add(node); + if (node.nodes.isNotEmpty) stack.add(node.nodes.iterator); + } } } @@ -142,19 +162,18 @@ class SelectorEvaluator extends Visitor { // http://dev.w3.org/csswg/selectors-4/#the-root-pseudo case 'root': - // TODO(jmesserly): fix when we have a .ownerDocument pointer - // return _element == _element.ownerDocument.rootElement; - return _element!.localName == 'html' && _element!.parentNode == null; + return _element!.parentNode is Document; // http://dev.w3.org/csswg/selectors-4/#the-empty-pseudo case 'empty': - return _element!.nodes - .any((n) => !(n is Element || n is Text && n.text.isNotEmpty)); + return !_element!.nodes + .any((n) => n is Element || n is Text && n.data.isNotEmpty); // http://dev.w3.org/csswg/selectors-4/#the-blank-pseudo case 'blank': - return _element!.nodes.any((n) => !(n is Element || - n is Text && n.text.runes.any((r) => !isWhitespaceCC(r)))); + return !_element!.nodes.any((n) => + n is Element || + n is Text && n.data.runes.any((r) => !isWhitespaceCC(r))); // http://dev.w3.org/csswg/selectors-4/#the-first-child-pseudo case 'first-child': @@ -228,9 +247,22 @@ class SelectorEvaluator extends Visitor { final numericLiteral = literal.value as num; final parent = _element!.parentNode; - return parent != null && - numericLiteral > 0 && - parent.nodes.indexOf(_element) == numericLiteral; + 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; + } + } + } + return false; } break; @@ -278,7 +310,7 @@ class SelectorEvaluator extends Visitor { @override bool visitClassSelector(ClassSelector node) => - _element!.classes.contains(node.name); + hasHtmlClassToken(_element!.className, node.name); // TODO(jmesserly): negation should support any selectors in level 4, // not just simple selectors. @@ -301,8 +333,7 @@ class SelectorEvaluator extends Visitor { final select = '${node.value}'; return switch (node.operatorKind) { TokenKind.EQUALS => value == select, - TokenKind.INCLUDES => - value.split(' ').any((v) => v.isNotEmpty && v == select), + TokenKind.INCLUDES => hasHtmlClassToken(value, select), TokenKind.DASH_MATCH => value.startsWith(select) && (value.length == select.length || value[select.length] == '-'), TokenKind.PREFIX_MATCH => value.startsWith(select), diff --git a/pkgs/html/test/query_selector_regression_test.dart b/pkgs/html/test/query_selector_regression_test.dart new file mode 100644 index 0000000000..665b439e46 --- /dev/null +++ b/pkgs/html/test/query_selector_regression_test.dart @@ -0,0 +1,84 @@ +// Copyright (c) project authors. All rights reserved. +// Licensed under the MIT license. +// 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() { + group('structural selectors', () { + test(':root matches the document element, not detached elements', () { + final document = parse('
'); + expect(document.querySelector(':root'), same(document.documentElement)); + expect(document.body!.querySelector(':root'), isNull); + expect(parseFragment('
').querySelector(':root'), isNull); + }); + + test(':empty ignores comments but not text or elements', () { + final document = parse( + '
' + '
שלום
' + '
', + ); + expect( + document.querySelectorAll('div:empty').map((e) => e.id).toList(), + ['empty', 'comment'], + ); + expect( + document.querySelectorAll('div:blank').map((e) => e.id).toList(), + ['empty', 'comment', 'space'], + ); + }); + + test(':nth-child counts element siblings starting with one', () { + final document = parse( + '
    text
  • ' + '\n
', + ); + expect(document.querySelector('li:nth-child(1)')?.id, 'first'); + expect(document.querySelector('li:nth-child(2)')?.id, 'second'); + expect(document.querySelector('li:nth-child(3)')?.id, 'third'); + expect(document.querySelector('li:nth-child(4)'), isNull); + }); + }); + + test('class tokens are separated by ASCII whitespace only', () { + final element = Element.tag('span')..className = 'foo\tbar\nbaz\rqux\fquux'; + expect(element.classes.contains('bar'), isTrue); + expect(element.classes.contains('qux'), isTrue); + expect(element.classes.contains('foo bar'), isFalse); + expect(element.classes, {'foo', 'bar', 'baz', 'qux', 'quux'}); + final parent = Element.tag('div')..append(element); + expect(parent.querySelector('.baz'), same(element)); + expect(parent.querySelector('[class~=qux]'), same(element)); + expect(parent.querySelector('[class~="bar baz"]'), isNull); + element.className = 'foo\u00a0bar'; + expect(element.classes.contains('foo'), isFalse); + expect(element.classes.contains('foo\u00a0bar'), isTrue); + }); + + test('deep descendant queries retain preorder without recursion', () { + final root = Element.tag('main'); + var current = root; + for (var i = 0; i < 100000; i++) { + final child = Element.tag('section'); + current.append(child); + current = child; + } + current.append(Element.tag('span')..id = 'target'); + expect(root.querySelector('span')?.id, 'target'); + expect(root.querySelectorAll('span').single.id, 'target'); + }); + + test('iterative querySelectorAll preserves preorder', () { + final root = parseFragment( + '

' + '', + ); + expect( + root.querySelectorAll('span').map((e) => e.id).toList(), + ['one', 'two', 'three'], + ); + }); +}