Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: adopt nodes from another document in replaceWith

Adrià Arrufate3dde66f79e6
diff --git a/src/browser/tests/element/replace_with.html b/src/browser/tests/element/replace_with.html
index 23172fb93..a5524aef0 100644
--- a/src/browser/tests/element/replace_with.html
+++ b/src/browser/tests/element/replace_with.html
@@ -425,3 +425,28 @@
testing.expectEqual(1, seenParentNodeType16); // ELEMENT_NODE
testing.expectEqual(parent16, seenParentElement16);
</script>
+
+<!-- Test 17: Nodes from another document are adopted, as insertBefore does -->
+<script id=test17-adopts>
+ const other17 = document.implementation.createHTMLDocument('other');
+ const node17 = other17.createElement('div');
+ const nested17 = other17.createElement('span');
+ node17.appendChild(nested17);
+ const moved17 = other17.createElement('div');
+ other17.body.appendChild(moved17);
+
+ const parent17 = document.createElement('div');
+ const old17 = document.createElement('div');
+ parent17.appendChild(old17);
+ document.body.appendChild(parent17);
+
+ old17.replaceWith(node17, moved17);
+
+ testing.expectEqual(parent17, node17.parentNode);
+ testing.expectEqual(document, node17.ownerDocument);
+ testing.expectEqual(document, nested17.ownerDocument);
+ testing.expectEqual(document, moved17.ownerDocument);
+ testing.expectEqual(0, other17.body.childNodes.length);
+ // Layout walks the document's elements, asserting each is its own.
+ testing.expectEqual(true, document.documentElement.scrollWidth > 0);
+</script>
diff --git a/src/browser/webapi/Element.zig b/src/browser/webapi/Element.zig
index d3a25023d..e30302b14 100644
--- a/src/browser/webapi/Element.zig
+++ b/src/browser/webapi/Element.zig
@@ -1212,17 +1212,26 @@ pub fn replaceWith(self: *Element, nodes: []const Node.NodeOrText, frame: *Frame
continue;
}
+ // A node from another document is adopted, as insertBefore does
+ const child_owner = child.ownerDocument(frame);
+ const parent_owner = parent.ownerDocument(frame) orelse parent.as(Node.Document);
+ const adopting = child_owner != null and child_owner.? != parent_owner;
+
var previous_root: ?*Node = null;
if (child._parent) |current_parent| {
previous_root = child.getRootNode(.{});
- frame.removeNode(current_parent, child, .{ .reconnect_to = parent });
+ frame.removeNode(current_parent, child, .{ .reconnect_to = if (adopting) null else parent });
+ }
+
+ if (adopting) {
+ try frame.adoptNodeTree(child, child_owner.?, parent_owner);
}
try frame.insertNodeRelative(
parent,
child,
.{ .before = ref_node },
- .{ .previous_root = previous_root },
+ .{ .previous_root = previous_root, .adopting_to_new_document = adopting },
);
}