Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions pkgs/html/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
- Fix `TreeBuilder` not updating `Text.sourceSpan` when merging consecutive foster-parented text nodes before a `<table>`.
- 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

Expand Down
85 changes: 75 additions & 10 deletions pkgs/html/lib/dom.dart
Original file line number Diff line number Diff line change
Expand Up @@ -106,25 +106,90 @@ 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<Element> _descendantElements(Node root) sync* {
final stack = <Iterator<Node>>[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
// common methods from these:
// 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<Element> getElementsByTagName(String localName) =>
querySelectorAll(localName);

List<Element> getElementsByClassName(String classNames) =>
querySelectorAll(classNames.splitMapJoin(' ',
onNonMatch: (m) => m.isNotEmpty ? '.$m' : m, onMatch: (m) => ''));
/// Return matching descendant elements without parsing a CSS selector.
List<Element> 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<Element> getElementsByClassName(String classNames) {
final wanted = classNames
.split(_htmlClassWhitespace)
.where((name) => name.isNotEmpty)
.toSet();
if (wanted.isEmpty) return <Element>[];
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.
Expand Down
78 changes: 78 additions & 0 deletions pkgs/html/test/dom_lookup_regression_test.dart
Original file line number Diff line number Diff line change
@@ -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('<div id="a:b"></div>'
'<div id="a b"></div><p id="123"></p>');
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('<div id="parent">'
'<span id="one" class="first common"></span>'
'text<span id="two" class="second common"></span></div>');
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(
'<div id="one" class="alpha&#9;beta&#10;gamma"></div>'
'<div id="two" class="alpha beta"></div>',
);
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(
'<section id="ab:cd"><b id="lead"></b></section>',
);
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));
});
});
}
Loading