From 142342a3d98df2e568bc7ce6fcde050f5a381150 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Tue, 10 Nov 2026 20:44:10 +0200 Subject: [PATCH 1/5] fix(html): preserve parent pointers and move DOM fragments in linear time --- pkgs/html/lib/dom.dart | 109 ++++++++++++++++++++++++++++++++--------- 1 file changed, 86 insertions(+), 23 deletions(-) diff --git a/pkgs/html/lib/dom.dart b/pkgs/html/lib/dom.dart index 3e021e6244..e7675302b5 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,14 @@ 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 +841,16 @@ 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 +903,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,7 +967,9 @@ class FilteredElementList extends IterableBase @override void forEach(void Function(Element) action) { - _filtered.forEach(action); + for (final node in _childNodes) { + if (node is Element) action(node); + } } @override @@ -946,7 +990,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) { @@ -966,7 +1011,7 @@ class FilteredElementList extends IterableBase } @override - Iterable get reversed => _filtered.reversed; + Iterable get reversed => _childNodes.reversed.whereType(); @override void sort([int Function(Element, Element)? compare]) { @@ -1007,13 +1052,16 @@ class FilteredElementList extends IterableBase } @override - Iterable map(T Function(Element) f) => _filtered.map(f); + Iterable map(T Function(Element) f) => + _childNodes.whereType().map(f); @override - Iterable where(bool Function(Element) test) => _filtered.where(test); + Iterable where(bool Function(Element) test) => + _childNodes.whereType().where(test); @override - Iterable expand(Iterable Function(Element) f) => _filtered.expand(f); + Iterable expand(Iterable Function(Element) f) => + _childNodes.whereType().expand(f); @override void insert(int index, Element element) { @@ -1093,16 +1141,31 @@ 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; + Iterator get iterator => _childNodes.whereType().iterator; @override List sublist(int start, [int? end]) => _filtered.sublist(start, end); @@ -1124,13 +1187,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 From f1ef0b49c46bf100faa0682c8731987aca2614d5 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Tue, 10 Nov 2026 20:44:14 +0200 Subject: [PATCH 2/5] test(html): verify DOM parent links, fragment moves and live children --- ..._mutation_performance_regression_test.dart | 130 ++++++++++++++++++ 1 file changed, 130 insertions(+) create mode 100644 pkgs/html/test/dom_mutation_performance_regression_test.dart diff --git a/pkgs/html/test/dom_mutation_performance_regression_test.dart b/pkgs/html/test/dom_mutation_performance_regression_test.dart new file mode 100644 index 0000000000..31e4ce4fdf --- /dev/null +++ b/pkgs/html/test/dom_mutation_performance_regression_test.dart @@ -0,0 +1,130 @@ +// 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('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('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(','), ','); + }); +} From 0a694d7da4d5e387e77de5eb713ae69de65bf229 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Tue, 10 Nov 2026 20:59:10 +0200 Subject: [PATCH 3/5] fix(html): preserve mutation-safe children snapshot traversal --- pkgs/html/lib/dom.dart | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/pkgs/html/lib/dom.dart b/pkgs/html/lib/dom.dart index e7675302b5..0e317b9278 100644 --- a/pkgs/html/lib/dom.dart +++ b/pkgs/html/lib/dom.dart @@ -967,9 +967,8 @@ class FilteredElementList extends IterableBase @override void forEach(void Function(Element) action) { - for (final node in _childNodes) { - if (node is Element) action(node); - } + // Preserve snapshot iteration when callbacks mutate the DOM. + _filtered.forEach(action); } @override @@ -1011,7 +1010,7 @@ class FilteredElementList extends IterableBase } @override - Iterable get reversed => _childNodes.reversed.whereType(); + Iterable get reversed => _filtered.reversed; @override void sort([int Function(Element, Element)? compare]) { @@ -1052,16 +1051,13 @@ class FilteredElementList extends IterableBase } @override - Iterable map(T Function(Element) f) => - _childNodes.whereType().map(f); + Iterable map(T Function(Element) f) => _filtered.map(f); @override - Iterable where(bool Function(Element) test) => - _childNodes.whereType().where(test); + Iterable where(bool Function(Element) test) => _filtered.where(test); @override - Iterable expand(Iterable Function(Element) f) => - _childNodes.whereType().expand(f); + Iterable expand(Iterable Function(Element) f) => _filtered.expand(f); @override void insert(int index, Element element) { @@ -1165,7 +1161,7 @@ class FilteredElementList extends IterableBase } @override - Iterator get iterator => _childNodes.whereType().iterator; + Iterator get iterator => _filtered.iterator; @override List sublist(int start, [int? end]) => _filtered.sublist(start, end); From 5285d051dd58a50f91a8d84ab90c0b87f3ed079d Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Tue, 10 Nov 2026 20:59:22 +0200 Subject: [PATCH 4/5] test(html): cover mutation-safe children iteration --- ...dom_mutation_performance_regression_test.dart | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/pkgs/html/test/dom_mutation_performance_regression_test.dart b/pkgs/html/test/dom_mutation_performance_regression_test.dart index 31e4ce4fdf..833f40a60f 100644 --- a/pkgs/html/test/dom_mutation_performance_regression_test.dart +++ b/pkgs/html/test/dom_mutation_performance_regression_test.dart @@ -111,6 +111,22 @@ void main() { }); }); + 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 = []; + parent.children.forEach((child) { + visited.add(child); + child.remove(); + }); + 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')) From 3098a08bd0ed06067fc2fa8bc4f656ae04b79e01 Mon Sep 17 00:00:00 2001 From: palmoni5 Date: Tue, 10 Nov 2026 21:43:41 +0200 Subject: [PATCH 5/5] fix(html): format DOM mutation fix, correct join test and add changelog Rename the test to dom_mutation_test.dart, fix the children.join expectation (Element.toString is ''), cover insertBefore with an earlier sibling and avoid a lint on the forEach callback. --- pkgs/html/CHANGELOG.md | 1 + pkgs/html/lib/dom.dart | 6 ++---- ...ssion_test.dart => dom_mutation_test.dart} | 21 ++++++++++++++++--- 3 files changed, 21 insertions(+), 7 deletions(-) rename pkgs/html/test/{dom_mutation_performance_regression_test.dart => dom_mutation_test.dart} (89%) 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 0e317b9278..cf909796b1 100644 --- a/pkgs/html/lib/dom.dart +++ b/pkgs/html/lib/dom.dart @@ -813,8 +813,7 @@ class NodeList extends ListProxy { if (element is DocumentFragment) { insertAll(index, element.nodes); } else { - if (identical(element.parentNode, _parent) && - indexOf(element) < index) { + if (identical(element.parentNode, _parent) && indexOf(element) < index) { index--; } super.insert(index, _setParent(element)); @@ -844,8 +843,7 @@ class NodeList extends ListProxy { 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) { + if (identical(value.parentNode, _parent) && indexOf(value) < index) { index--; } value.remove(); diff --git a/pkgs/html/test/dom_mutation_performance_regression_test.dart b/pkgs/html/test/dom_mutation_test.dart similarity index 89% rename from pkgs/html/test/dom_mutation_performance_regression_test.dart rename to pkgs/html/test/dom_mutation_test.dart index 833f40a60f..23f9ef004f 100644 --- a/pkgs/html/test/dom_mutation_performance_regression_test.dart +++ b/pkgs/html/test/dom_mutation_test.dart @@ -58,6 +58,19 @@ void main() { } }); + 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'); @@ -117,10 +130,12 @@ void main() { final two = Element.tag('i'); parent.nodes.addAll([one, Text('text'), two]); final visited = []; - parent.children.forEach((child) { + 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); @@ -141,6 +156,6 @@ void main() { 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(','), ','); + expect(parent.children.join(','), ','); }); }