diff --git a/pkgs/html/CHANGELOG.md b/pkgs/html/CHANGELOG.md
index c7caf3f444..e5f84d848a 100644
--- a/pkgs/html/CHANGELOG.md
+++ b/pkgs/html/CHANGELOG.md
@@ -10,6 +10,7 @@
- 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.
## 0.15.7
diff --git a/pkgs/html/lib/dom.dart b/pkgs/html/lib/dom.dart
index 3e021e6244..cf909796b1 100644
--- a/pkgs/html/lib/dom.dart
+++ b/pkgs/html/lib/dom.dart
@@ -269,8 +269,9 @@ abstract class Node {
/// This is needed so that trees that don't store text as nodes move the
/// text in the correct way.
void reparentChildren(Node newParent) {
+ if (identical(this, newParent)) return;
+ // NodeList.addAll detaches source children in one pass.
newParent.nodes.addAll(nodes);
- nodes.clear();
}
bool hasChildNodes() => nodes.isNotEmpty;
@@ -764,6 +765,14 @@ class NodeList extends ListProxy {
return node;
}
+ @override
+ bool remove(Object? element) {
+ final index = indexOf(element);
+ if (index < 0) return false;
+ removeAt(index);
+ return true;
+ }
+
@override
void add(Node element) {
if (element is DocumentFragment) {
@@ -777,13 +786,20 @@ class NodeList extends ListProxy {
@override
void addAll(Iterable iterable) {
- // Note: we need to be careful if collection is another NodeList.
- // In particular:
- // 1. we need to copy the items before updating their parent pointers,
- // _flattenDocFragments does a copy internally.
- // 2. we should update parent pointers in reverse order. That way they
- // are removed from the original NodeList (if any) from the end, which
- // is faster.
+ // Moving an entire node list is a common fragment insertion operation.
+ // Detach its children in one pass instead of repeatedly searching and
+ // removing from the source list (quadratic for large fragments).
+ if (iterable is NodeList && !identical(iterable, this)) {
+ final moving = iterable.toList(growable: false);
+ iterable.clear();
+ for (final node in moving) {
+ node.parentNode = _parent;
+ }
+ super.addAll(moving);
+ return;
+ }
+
+ // Snapshot the iterable, flatten fragments and detach in reverse order.
final list = _flattenDocFragments(iterable);
for (var node in list.reversed) {
_setParent(node);
@@ -793,9 +809,13 @@ class NodeList extends ListProxy {
@override
void insert(int index, Node element) {
+ RangeError.checkValueInInterval(index, 0, length, 'index');
if (element is DocumentFragment) {
insertAll(index, element.nodes);
} else {
+ if (identical(element.parentNode, _parent) && indexOf(element) < index) {
+ index--;
+ }
super.insert(index, _setParent(element));
}
}
@@ -820,8 +840,15 @@ class NodeList extends ListProxy {
removeAt(index);
insertAll(index, value.nodes);
} else {
+ if (identical(this[index], value)) return;
+ // Removing a sibling before the target shifts its index. Detach first,
+ // then replace the node at the adjusted position.
+ if (identical(value.parentNode, _parent) && indexOf(value) < index) {
+ index--;
+ }
+ value.remove();
this[index].parentNode = null;
- super[index] = _setParent(value);
+ super[index] = value..parentNode = _parent;
}
}
@@ -874,9 +901,22 @@ class NodeList extends ListProxy {
@override
void insertAll(int index, Iterable iterable) {
- // Note: we need to be careful how we copy nodes. See note in addAll.
+ RangeError.checkValueInInterval(index, 0, length, 'index');
+ if (iterable is NodeList && !identical(iterable, this)) {
+ final moving = iterable.toList(growable: false);
+ iterable.clear();
+ for (final node in moving) {
+ node.parentNode = _parent;
+ }
+ super.insertAll(index, moving);
+ return;
+ }
+
final list = _flattenDocFragments(iterable);
for (var node in list.reversed) {
+ if (identical(node.parentNode, _parent) && indexOf(node) < index) {
+ index--;
+ }
_setParent(node);
}
super.insertAll(index, list);
@@ -925,6 +965,7 @@ class FilteredElementList extends IterableBase
@override
void forEach(void Function(Element) action) {
+ // Preserve snapshot iteration when callbacks mutate the DOM.
_filtered.forEach(action);
}
@@ -946,7 +987,8 @@ class FilteredElementList extends IterableBase
}
@override
- String join([String separator = '']) => _filtered.join(separator);
+ String join([String separator = '']) =>
+ _childNodes.whereType().join(separator);
@override
void add(Element element) {
@@ -1093,13 +1135,28 @@ class FilteredElementList extends IterableBase
}
@override
- bool get isEmpty => _filtered.isEmpty;
+ bool get isEmpty => !_childNodes.any((node) => node is Element);
@override
- int get length => _filtered.length;
+ int get length {
+ var count = 0;
+ for (final node in _childNodes) {
+ if (node is Element) count++;
+ }
+ return count;
+ }
@override
- Element operator [](int index) => _filtered[index];
+ Element operator [](int index) {
+ var position = 0;
+ for (final node in _childNodes) {
+ if (node is Element) {
+ if (position == index) return node;
+ position++;
+ }
+ }
+ throw RangeError.index(index, this);
+ }
@override
Iterator get iterator => _filtered.iterator;
@@ -1124,13 +1181,13 @@ class FilteredElementList extends IterableBase
}
@override
- Element get first => _filtered.first;
+ Element get first => _childNodes.whereType().first;
@override
- Element get last => _filtered.last;
+ Element get last => _childNodes.whereType().last;
@override
- Element get single => _filtered.single;
+ Element get single => _childNodes.whereType().single;
}
// http://dom.spec.whatwg.org/#dom-node-textcontent
diff --git a/pkgs/html/test/dom_mutation_test.dart b/pkgs/html/test/dom_mutation_test.dart
new file mode 100644
index 0000000000..23f9ef004f
--- /dev/null
+++ b/pkgs/html/test/dom_mutation_test.dart
@@ -0,0 +1,161 @@
+// 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('parent pointer invariants', () {
+ test('nodes.remove detaches the removed node', () {
+ final parent = Element.tag('div');
+ final child = Element.tag('span');
+ parent.append(child);
+ expect(parent.nodes.remove(child), isTrue);
+ expect(child.parentNode, isNull);
+ expect(parent.nodes, isEmpty);
+ expect(parent.nodes.remove(child), isFalse);
+ });
+
+ test('replacing with an earlier sibling adjusts the index', () {
+ final parent = Element.tag('div');
+ final a = Element.tag('a');
+ final b = Element.tag('b');
+ final c = Element.tag('c');
+ parent.nodes.addAll([a, b, c]);
+ parent.nodes[2] = a;
+ expect(parent.nodes, [b, a]);
+ expect(c.parentNode, isNull);
+ expect(a.parentNode, same(parent));
+ expect(b.parentNode, same(parent));
+ parent.nodes[1] = a;
+ expect(parent.nodes, [b, a]);
+ });
+
+ test('replacing with a later sibling preserves other children', () {
+ final parent = Element.tag('div');
+ final a = Element.tag('a');
+ final b = Element.tag('b');
+ final c = Element.tag('c');
+ parent.nodes.addAll([a, b, c]);
+ parent.nodes[0] = c;
+ expect(parent.nodes, [c, b]);
+ expect(a.parentNode, isNull);
+ expect(c.parentNode, same(parent));
+ });
+
+ test('insert moves an earlier sibling to the end', () {
+ final parent = Element.tag('div');
+ final a = Element.tag('a');
+ final b = Element.tag('b');
+ final c = Element.tag('c');
+ parent.nodes.addAll([a, b, c]);
+ parent.nodes.insert(3, a);
+ expect(parent.nodes, [b, c, a]);
+ for (final child in parent.nodes) {
+ expect(child.parentNode, same(parent));
+ }
+ });
+
+ test('insertBefore moves an earlier sibling before the reference', () {
+ final parent = Element.tag('div');
+ final a = Element.tag('a');
+ final b = Element.tag('b');
+ final c = Element.tag('c');
+ parent.nodes.addAll([a, b, c]);
+ parent.insertBefore(a, c);
+ expect(parent.nodes, [b, a, c]);
+ a.remove();
+ expect(a.parentNode, isNull);
+ expect(parent.nodes, [b, c]);
+ });
+
+ test('insertAll moves siblings without duplicates', () {
+ final parent = Element.tag('div');
+ final a = Element.tag('a');
+ final b = Element.tag('b');
+ final c = Element.tag('c');
+ final d = Element.tag('d');
+ parent.nodes.addAll([a, b, c, d]);
+ parent.nodes.insertAll(3, [a, b]);
+ expect(parent.nodes, [c, a, b, d]);
+ for (final child in parent.nodes) {
+ expect(child.parentNode, same(parent));
+ }
+ });
+ });
+
+ group('bulk fragment insertion', () {
+ test('reparentChildren keeps order and empties the source', () {
+ final from = parseFragment('א
ב
');
+ final to = Element.tag('article');
+ from.reparentChildren(to);
+ expect(from.nodes, isEmpty);
+ expect(to.children.map((e) => e.localName), ['p', 'hr', 'p']);
+ for (final node in to.nodes) {
+ expect(node.parentNode, same(to));
+ }
+ to.reparentChildren(to);
+ expect(to.children, hasLength(3));
+ });
+
+ test('inserting a large fragment moves all nodes once', () {
+ final source = DocumentFragment();
+ for (var i = 0; i < 1000; i++) {
+ source.append(Element.tag('span')..id = '$i');
+ }
+ final destination = Element.tag('div');
+ destination.nodes.addAll(source.nodes);
+ expect(source.nodes, isEmpty);
+ expect(destination.children.length, 1000);
+ expect(destination.children.first.id, '0');
+ expect(destination.children.last.id, '999');
+ });
+
+ test('innerHtml replaces children without stale parent pointers', () {
+ final target = Element.tag('div');
+ final old = Element.tag('b');
+ target.append(old);
+ target.innerHtml = 'חדשטקסט';
+ expect(old.parentNode, isNull);
+ expect(target.children.map((e) => e.localName), ['i', 'span']);
+ expect(target.text, 'חדש' 'טקסט');
+ });
+ });
+
+ test('children.forEach is safe when callbacks remove children', () {
+ final parent = Element.tag('div');
+ final one = Element.tag('b');
+ final two = Element.tag('i');
+ parent.nodes.addAll([one, Text('text'), two]);
+ final visited = [];
+ void visitAndRemove(Element child) {
+ visited.add(child);
+ child.remove();
+ }
+
+ parent.children.forEach(visitAndRemove);
+ expect(visited, [one, two]);
+ expect(parent.children, isEmpty);
+ expect(one.parentNode, isNull);
+ expect(two.parentNode, isNull);
+ });
+
+ test('live children traversal ignores non-elements and preserves order', () {
+ final parent = Element.tag('div')
+ ..append(Text('before'))
+ ..append(Element.tag('b'))
+ ..append(Comment('comment'))
+ ..append(Element.tag('i'))
+ ..append(Text('after'));
+ expect(parent.children.length, 2);
+ expect(parent.children.first.localName, 'b');
+ expect(parent.children.last.localName, 'i');
+ expect(parent.children.map((e) => e.localName), ['b', 'i']);
+ expect(parent.children.reversed.map((e) => e.localName), ['i', 'b']);
+ expect(parent.children[0].localName, 'b');
+ expect(parent.children[1].localName, 'i');
+ expect(parent.children.join(','), ',');
+ });
+}