diff --git a/pkgs/html/CHANGELOG.md b/pkgs/html/CHANGELOG.md
index e5f84d848a..79010ecfb2 100644
--- a/pkgs/html/CHANGELOG.md
+++ b/pkgs/html/CHANGELOG.md
@@ -11,6 +11,7 @@
- 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.
## 0.15.7
diff --git a/pkgs/html/lib/dom.dart b/pkgs/html/lib/dom.dart
index cf909796b1..0b0d2fa44a 100644
--- a/pkgs/html/lib/dom.dart
+++ b/pkgs/html/lib/dom.dart
@@ -106,10 +106,60 @@ mixin _ParentNode implements Node {
query.querySelectorAll(this, selector);
}
+// Shared traversal for DOM lookups that need no CSS selector parsing.
+// Descendants are visited in document order and deeply nested documents do not
+// consume the call stack.
+Iterable _descendantElements(Node root) sync* {
+ final stack = >[root.nodes.iterator];
+ while (stack.isNotEmpty) {
+ final cursor = stack.last;
+ if (!cursor.moveNext()) {
+ stack.removeLast();
+ continue;
+ }
+ final child = cursor.current;
+ if (child is Element) {
+ yield child;
+ if (child.nodes.isNotEmpty) stack.add(child.nodes.iterator);
+ }
+ }
+}
+
+final RegExp _htmlClassWhitespace = RegExp(r'[ \t\n\f\r]+');
+
+bool _isHtmlClassWhitespace(int code) =>
+ code == 0x09 ||
+ code == 0x0A ||
+ code == 0x0C ||
+ code == 0x0D ||
+ code == 0x20;
+
+bool _hasHtmlClassToken(String source, String token) {
+ var start = 0;
+ for (var i = 0; i <= source.length; i++) {
+ final separator =
+ i == source.length || _isHtmlClassWhitespace(source.codeUnitAt(i));
+ if (!separator) continue;
+ if (i - start == token.length && source.startsWith(token, start)) {
+ return true;
+ }
+ start = i + 1;
+ }
+ return false;
+}
+
// http://dom.spec.whatwg.org/#interface-nonelementparentnode
mixin _NonElementParentNode implements _ParentNode {
- // TODO(jmesserly): could be faster, should throw on invalid id.
- Element? getElementById(String id) => querySelector('#$id');
+ /// Return the first descendant whose ID exactly matches [id].
+ ///
+ /// IDs need not be valid CSS identifiers, so don't parse them as selectors.
+ Element? getElementById(String id) {
+ if (id.isEmpty) return null;
+ for (final element in _descendantElements(this)) {
+ if (element.id == id) return element;
+ }
+ return null;
+ }
}
// This doesn't exist as an interface in the spec, but it's useful to merge
@@ -117,14 +167,29 @@ mixin _NonElementParentNode implements _ParentNode {
// http://dom.spec.whatwg.org/#interface-document
// http://dom.spec.whatwg.org/#element
abstract mixin class _ElementAndDocument implements _ParentNode {
- // TODO(jmesserly): could be faster, should throw on invalid tag/class names.
-
- List getElementsByTagName(String localName) =>
- querySelectorAll(localName);
-
- List getElementsByClassName(String classNames) =>
- querySelectorAll(classNames.splitMapJoin(' ',
- onNonMatch: (m) => m.isNotEmpty ? '.$m' : m, onMatch: (m) => ''));
+ /// Return matching descendant elements without parsing a CSS selector.
+ List getElementsByTagName(String localName) {
+ final name = localName.toLowerCase();
+ return [
+ for (final element in _descendantElements(this))
+ if (name == '*' || element.localName == name) element,
+ ];
+ }
+
+ /// All whitespace-delimited class names must match on each element.
+ List getElementsByClassName(String classNames) {
+ final wanted = classNames
+ .split(_htmlClassWhitespace)
+ .where((name) => name.isNotEmpty)
+ .toSet();
+ if (wanted.isEmpty) return [];
+ return [
+ for (final element in _descendantElements(this))
+ if (wanted
+ .every((token) => _hasHtmlClassToken(element.className, token)))
+ element,
+ ];
+ }
}
/// Really basic implementation of a DOM-core like Node.
diff --git a/pkgs/html/test/dom_lookup_regression_test.dart b/pkgs/html/test/dom_lookup_regression_test.dart
new file mode 100644
index 0000000000..48d7d9efdc
--- /dev/null
+++ b/pkgs/html/test/dom_lookup_regression_test.dart
@@ -0,0 +1,78 @@
+// 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('direct DOM lookups', () {
+ test('IDs with punctuation, whitespace and digits match exactly', () {
+ final document = parse(''
+ '');
+ expect(document.getElementById('a:b')?.localName, 'div');
+ expect(document.getElementById('a b')?.localName, 'div');
+ expect(document.getElementById('123')?.localName, 'p');
+ expect(document.getElementById(''), isNull);
+ expect(document.getElementById('A:B'), isNull);
+ expect(document.getElementById('missing'), isNull);
+ });
+
+ test('lookups visit descendants in document order, not the root', () {
+ final root = Element.html(''
+ ''
+ 'text
');
+ expect(root.getElementsByTagName('div'), isEmpty);
+ expect(
+ root.getElementsByTagName('SPAN').map((e) => e.id), ['one', 'two']);
+ expect(root.getElementsByTagName('*').map((e) => e.id), ['one', 'two']);
+ expect(root.getElementsByClassName('common').map((e) => e.id),
+ ['one', 'two']);
+ expect(root.getElementsByClassName('common first').map((e) => e.id),
+ ['one']);
+ expect(root.getElementsByClassName('first common').map((e) => e.id),
+ ['one']);
+ expect(root.getElementsByClassName('common absent'), isEmpty);
+ });
+
+ test('class names handle all HTML whitespace and empty query', () {
+ final document = parse(
+ ''
+ '',
+ );
+ expect(document.getElementsByClassName('alpha\tbeta').map((e) => e.id),
+ ['one', 'two']);
+ expect(document.getElementsByClassName('gamma\nalpha').map((e) => e.id),
+ ['one']);
+ expect(document.getElementsByClassName(' \n\t '), isEmpty);
+ expect(document.getElementsByClassName(''), isEmpty);
+ });
+
+ test('fragment can find IDs regardless of CSS identifier syntax', () {
+ final fragment = parseFragment(
+ '',
+ );
+ expect(fragment.getElementById('ab:cd'), same(fragment.children.first));
+ expect(fragment.getElementById('lead')?.localName, 'b');
+ });
+
+ test('deep ID, class and tag lookups do not recurse', () {
+ final fragment = DocumentFragment();
+ final root = Element.tag('div');
+ fragment.append(root);
+ var current = root;
+ for (var i = 0; i < 100000; i++) {
+ final child = Element.tag('div');
+ current.append(child);
+ current = child;
+ }
+ current.append(Element.tag('span')
+ ..id = 'found:123'
+ ..className = 'book heading');
+ expect(fragment.getElementById('found:123')?.localName, 'span');
+ expect(root.getElementsByTagName('span'), hasLength(1));
+ expect(root.getElementsByClassName('book heading'), hasLength(1));
+ });
+ });
+}