From a8ec68921a23e6191aa24674e7cdf1d0ff250a76 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Tue, 10 Nov 2026 20:52:35 +0200 Subject: [PATCH 1/5] perf(html): make DOM ID, tag and class lookups selector-free --- pkgs/html/lib/dom.dart | 62 +++++++++++++++++++++++++++++++++++------- 1 file changed, 52 insertions(+), 10 deletions(-) diff --git a/pkgs/html/lib/dom.dart b/pkgs/html/lib/dom.dart index cf909796b1..588784b298 100644 --- a/pkgs/html/lib/dom.dart +++ b/pkgs/html/lib/dom.dart @@ -106,10 +106,39 @@ 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]+'); + // 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 +146,27 @@ 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(element.classes.contains)) element, + ]; + } } /// Really basic implementation of a DOM-core like Node. From e6306a15b3f5d1fe69d70e59d7a2c6e7cd31d71c Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Tue, 10 Nov 2026 20:52:37 +0200 Subject: [PATCH 2/5] test(html): cover direct DOM lookup semantics and nested books --- .../html/test/dom_lookup_regression_test.dart | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 pkgs/html/test/dom_lookup_regression_test.dart 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..437be5e25f --- /dev/null +++ b/pkgs/html/test/dom_lookup_regression_test.dart @@ -0,0 +1,80 @@ +// 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 document = DocumentFragment(); + var current = Element.tag('div'); + document.append(current); + for (var i = 0; i < 5000; i++) { + final child = Element.tag('div'); + current.append(child); + current = child; + } + current.append(Element.tag('span') + ..id = 'found:123' + ..className = 'book heading'); + expect(document.getElementById('found:123')?.localName, 'span'); + expect(document.getElementsByTagName('span'), hasLength(1)); + expect(document.getElementsByClassName('book heading'), hasLength(1)); + }); + }); +} From 375d9dc343c08e34ec07957afa301755fcbd3fa2 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Tue, 10 Nov 2026 20:53:03 +0200 Subject: [PATCH 3/5] fix(html): scan ASCII-whitespace class tokens without per-element sets --- pkgs/html/lib/dom.dart | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/pkgs/html/lib/dom.dart b/pkgs/html/lib/dom.dart index 588784b298..b17c390977 100644 --- a/pkgs/html/lib/dom.dart +++ b/pkgs/html/lib/dom.dart @@ -127,6 +127,23 @@ Iterable _descendantElements(Node root) sync* { final RegExp _htmlClassWhitespace = RegExp(r'[ \t\n\f\r]+'); +bool _hasHtmlClassToken(String source, String token) { + var start = 0; + for (var i = 0; i <= source.length; i++) { + final separator = i == source.length || + switch (source.codeUnitAt(i)) { + 0x09 || 0x0A || 0x0C || 0x0D || 0x20 => true, + _ => false, + }; + 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 { /// Return the first descendant whose ID exactly matches [id]. @@ -164,7 +181,8 @@ abstract mixin class _ElementAndDocument implements _ParentNode { if (wanted.isEmpty) return []; return [ for (final element in _descendantElements(this)) - if (wanted.every(element.classes.contains)) element, + if (wanted.every((token) => _hasHtmlClassToken(element.className, token))) + element, ]; } } From 6a2c9c69427dccc0ef9b9c6d7270bcf0dd2fea11 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Tue, 10 Nov 2026 20:53:52 +0200 Subject: [PATCH 4/5] refactor(html): simplify ASCII class separator scan --- pkgs/html/lib/dom.dart | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/pkgs/html/lib/dom.dart b/pkgs/html/lib/dom.dart index b17c390977..351ee18d99 100644 --- a/pkgs/html/lib/dom.dart +++ b/pkgs/html/lib/dom.dart @@ -127,14 +127,18 @@ Iterable _descendantElements(Node root) sync* { 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 || - switch (source.codeUnitAt(i)) { - 0x09 || 0x0A || 0x0C || 0x0D || 0x20 => true, - _ => false, - }; + final separator = + i == source.length || _isHtmlClassWhitespace(source.codeUnitAt(i)); if (!separator) continue; if (i - start == token.length && source.startsWith(token, start)) { return true; From 06cfe5a7db8be13312ec320c1979aadebe76e86d Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Tue, 10 Nov 2026 21:41:07 +0200 Subject: [PATCH 5/5] Fix the DOM lookup test, format, and add a changelog entry The deep-nesting test called getElementsByTagName and getElementsByClassName on a DocumentFragment, which does not have them, so the file did not compile. Query through the root element instead and nest 100000 levels so the test overflows the stack with the old recursive selector walk. --- pkgs/html/CHANGELOG.md | 1 + pkgs/html/lib/dom.dart | 3 +- .../html/test/dom_lookup_regression_test.dart | 28 +++++++++---------- 3 files changed, 16 insertions(+), 16 deletions(-) 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 351ee18d99..0b0d2fa44a 100644 --- a/pkgs/html/lib/dom.dart +++ b/pkgs/html/lib/dom.dart @@ -185,7 +185,8 @@ abstract mixin class _ElementAndDocument implements _ParentNode { if (wanted.isEmpty) return []; return [ for (final element in _descendantElements(this)) - if (wanted.every((token) => _hasHtmlClassToken(element.className, token))) + if (wanted + .every((token) => _hasHtmlClassToken(element.className, token))) element, ]; } diff --git a/pkgs/html/test/dom_lookup_regression_test.dart b/pkgs/html/test/dom_lookup_regression_test.dart index 437be5e25f..48d7d9efdc 100644 --- a/pkgs/html/test/dom_lookup_regression_test.dart +++ b/pkgs/html/test/dom_lookup_regression_test.dart @@ -24,10 +24,9 @@ void main() { '' '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.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), @@ -42,11 +41,9 @@ void main() { '
' '
', ); - expect( - document.getElementsByClassName('alpha\tbeta').map((e) => e.id), + expect(document.getElementsByClassName('alpha\tbeta').map((e) => e.id), ['one', 'two']); - expect( - document.getElementsByClassName('gamma\nalpha').map((e) => e.id), + expect(document.getElementsByClassName('gamma\nalpha').map((e) => e.id), ['one']); expect(document.getElementsByClassName(' \n\t '), isEmpty); expect(document.getElementsByClassName(''), isEmpty); @@ -61,10 +58,11 @@ void main() { }); test('deep ID, class and tag lookups do not recurse', () { - final document = DocumentFragment(); - var current = Element.tag('div'); - document.append(current); - for (var i = 0; i < 5000; i++) { + 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; @@ -72,9 +70,9 @@ void main() { current.append(Element.tag('span') ..id = 'found:123' ..className = 'book heading'); - expect(document.getElementById('found:123')?.localName, 'span'); - expect(document.getElementsByTagName('span'), hasLength(1)); - expect(document.getElementsByClassName('book heading'), hasLength(1)); + expect(fragment.getElementById('found:123')?.localName, 'span'); + expect(root.getElementsByTagName('span'), hasLength(1)); + expect(root.getElementsByClassName('book heading'), hasLength(1)); }); }); }