Lightpanda: the headless browser designed for AI and automation
webapi: replaceChildren adopts nodes from another document
Adrià Arrufat3b93b9bb602c
diff --git a/src/browser/tests/element/replace_children.html b/src/browser/tests/element/replace_children.htmlindex fdadcb774..fd2c6d97f 100644--- a/src/browser/tests/element/replace_children.html+++ b/src/browser/tests/element/replace_children.html@@ -137,3 +137,21 @@testing.expectEqual(0, div1.childNodes.length);}</script>++<script id=replace_children_adopts>+ {+ // Nodes from another document are adopted, as appendChild does.+ const other = document.implementation.createHTMLDocument("other");+ const node = other.createElement('div');+ const frag = other.createDocumentFragment();+ const fragChild = other.createElement('span');+ frag.appendChild(fragChild);+ const host = document.getElementById('test');++ host.replaceChildren(node, frag);++ testing.expectEqual(document, node.ownerDocument);+ testing.expectEqual(document, fragChild.ownerDocument);+ testing.expectEqual(true, document.documentElement.scrollWidth > 0);+ }+</script>diff --git a/src/browser/webapi/Node.zig b/src/browser/webapi/Node.zigindex b57c63640..2ae59ec32 100644--- a/src/browser/webapi/Node.zig+++ b/src/browser/webapi/Node.zig@@ -1557,14 +1557,26 @@ pub fn replaceChildren(self: *Node, nodes: []const NodeOrText, frame: *Frame) !vconst notify = Frame.observers.hasMutationObservers(frame);const removed = try self.removeAllChildrenCollecting(notify, frame);- // Append new children+ const parent_owner = self.ownerDocument(frame) orelse self.as(Document);for (children_to_add.items) |child| {+ const child_owner = child.ownerDocument(frame);+ const adopting_to_new_document = child_owner != null and child_owner.? != parent_owner;+var previous_root: ?*Node = null;if (child._parent) |previous_parent| {previous_root = child.getRootNode(.{});- frame.removeNode(previous_parent, child, .{ .reconnect_to = self });+ frame.removeNode(previous_parent, child, .{+ .reconnect_to = if (adopting_to_new_document) null else self,+ });+ }+ if (adopting_to_new_document) {+ try frame.adoptNodeTree(child, child_owner.?, parent_owner);}- try frame.appendNode(self, child, .{ .previous_root = previous_root, .notify_observers = false });+ try frame.appendNode(self, child, .{+ .previous_root = previous_root,+ .adopting_to_new_document = adopting_to_new_document,+ .notify_observers = false,+ });}if (notify and (removed.items.len > 0 or children_to_add.items.len > 0)) {