Skip to content

Lightpanda: the headless browser designed for AI and automation

webapi: replaceChildren uses pre-insert validity and a fragment

Adrià Arrufatf90e89289a9d
diff --git a/src/browser/tests/element/replace_children.html b/src/browser/tests/element/replace_children.html
index fd2c6d97f..1a17a1e06 100644
--- a/src/browser/tests/element/replace_children.html
+++ b/src/browser/tests/element/replace_children.html
@@ -155,3 +155,69 @@
testing.expectEqual(true, document.documentElement.scrollWidth > 0);
}
</script>
+
+<script id=error_document_child>
+ {
+ const doc = document.implementation.createHTMLDocument("title");
+ testing.expectError('HierarchyRequest', () => {
+ document.getElementById('test').replaceChildren(doc);
+ });
+ testing.expectError('HierarchyRequest', () => {
+ document.getElementById('test').replaceChildren(doc, 'text');
+ });
+ }
+</script>
+
+<script id=document_replace_children>
+ {
+ const doc = document.implementation.createHTMLDocument("title");
+ doc.replaceChildren();
+ testing.expectEqual(0, doc.childNodes.length);
+
+ const el = doc.createElement('html');
+ doc.replaceChildren(el);
+ testing.expectEqual(el, doc.documentElement);
+
+ testing.expectError('HierarchyRequest', () => {
+ doc.replaceChildren('text');
+ });
+ testing.expectError('HierarchyRequest', () => {
+ doc.replaceChildren(doc.createElement('a'), doc.createElement('b'));
+ });
+ testing.expectEqual(el, doc.documentElement);
+ }
+</script>
+
+<script id=replace_children_mutation_records>
+ {
+ const parent = document.createElement('div');
+ const a = document.createElement('a');
+ const mo = new MutationObserver(() => {});
+ mo.observe(parent, {childList: true});
+
+ // A node passed twice is inserted once, in one record.
+ parent.replaceChildren(a, a);
+ let records = mo.takeRecords();
+ testing.expectEqual(1, records.length);
+ testing.expectEqual(1, records[0].addedNodes.length);
+ testing.expectEqual(a, records[0].addedNodes[0]);
+ testing.expectEqual(1, parent.childNodes.length);
+
+ // Nodes taken from this parent are removed one by one into the
+ // intermediate fragment, then the rest is replaced in one record.
+ const b = document.createElement('b');
+ const c = document.createElement('c');
+ parent.append(b, c);
+ mo.takeRecords();
+ parent.replaceChildren(c, a);
+ records = mo.takeRecords();
+ testing.expectEqual(3, records.length);
+ testing.expectEqual(c, records[0].removedNodes[0]);
+ testing.expectEqual(a, records[1].removedNodes[0]);
+ testing.expectEqual(1, records[2].removedNodes.length);
+ testing.expectEqual(b, records[2].removedNodes[0]);
+ testing.expectEqual(2, records[2].addedNodes.length);
+ testing.expectEqual(c, records[2].addedNodes[0]);
+ testing.expectEqual(a, records[2].addedNodes[1]);
+ }
+</script>
diff --git a/src/browser/webapi/Document.zig b/src/browser/webapi/Document.zig
index 421a75ac8..e53945467 100644
--- a/src/browser/webapi/Document.zig
+++ b/src/browser/webapi/Document.zig
@@ -899,7 +899,7 @@ fn importNode(self: *const Document, node: *Node, deep_: ?bool, frame: *Frame) !
}
pub fn append(self: *Document, nodes: []const Node.NodeOrText, frame: *Frame) !void {
- try validateDocumentNodes(self, nodes, false);
+ try validateDocumentNodes(self, nodes);
const parent = self.asNode();
frame.domChanged();
@@ -923,7 +923,7 @@ pub fn append(self: *Document, nodes: []const Node.NodeOrText, frame: *Frame) !v
}
pub fn prepend(self: *Document, nodes: []const Node.NodeOrText, frame: *Frame) !void {
- try validateDocumentNodes(self, nodes, false);
+ try validateDocumentNodes(self, nodes);
const parent = self.asNode();
frame.domChanged();
@@ -966,7 +966,6 @@ pub fn prepend(self: *Document, nodes: []const Node.NodeOrText, frame: *Frame) !
}
pub fn replaceChildren(self: *Document, nodes: []const Node.NodeOrText, frame: *Frame) !void {
- try validateDocumentNodes(self, nodes, false);
return self.asNode().replaceChildren(nodes, frame);
}
@@ -1397,22 +1396,17 @@ fn setAdoptedStyleSheets(self: *Document, sheets: js.Object) !void {
// - At most one DocumentType child
// - No Document, Attribute, or Text nodes
// - Only Element, DocumentType, Comment, and ProcessingInstruction are allowed
-// When replacing=true, existing children are not counted (for replaceChildren)
-fn validateDocumentNodes(self: *Document, nodes: []const Node.NodeOrText, comptime replacing: bool) !void {
+fn validateDocumentNodes(self: *Document, nodes: []const Node.NodeOrText) !void {
const parent = self.asNode();
- // Check existing elements and doctypes (unless we're replacing all children)
var has_element = false;
var has_doctype = false;
-
- if (!replacing) {
- var it = parent.childrenIterator();
- while (it.next()) |child| {
- if (child._type == .element) {
- has_element = true;
- } else if (child._type == .document_type) {
- has_doctype = true;
- }
+ var it = parent.childrenIterator();
+ while (it.next()) |child| {
+ if (child._type == .element) {
+ has_element = true;
+ } else if (child._type == .document_type) {
+ has_doctype = true;
}
}
diff --git a/src/browser/webapi/Node.zig b/src/browser/webapi/Node.zig
index 2ae59ec32..c447ea44c 100644
--- a/src/browser/webapi/Node.zig
+++ b/src/browser/webapi/Node.zig
@@ -241,28 +241,6 @@ pub fn parentElement(self: *const Node) ?*Element {
return parent.is(Element);
}
-// Validates that a node can be inserted as a child of parent.
-fn validateNodeInsertion(parent: *Node, node: *Node) !void {
- // Check if parent is a valid type to have children
- if (parent._type != .document and parent._type != .element and parent._type != .document_fragment) {
- return error.HierarchyError;
- }
-
- // Check if node contains parent (would create a cycle)
- if (node.isHostIncludingInclusiveAncestorOf(parent)) {
- return error.HierarchyError;
- }
-
- if (node._type == .attribute) {
- return error.HierarchyError;
- }
-
- // Doctype nodes can only be inserted into a Document
- if (node._type == .document_type and parent._type != .document) {
- return error.HierarchyError;
- }
-}
-
// DOM "ensure pre-insert validity" (and its replaceChild variant), with the
// checks in spec order: parent type, cycle, child-parent (NotFoundError),
// node type, then the document-parent structure rules.
@@ -1527,60 +1505,79 @@ pub fn prependNodes(self: *Node, nodes: []const NodeOrText, frame: *Frame) !void
}
/// Shared implementation of replaceChildren for Element, Document, and DocumentFragment.
-/// Validates all nodes, removes existing children, then appends new children.
pub fn replaceChildren(self: *Node, nodes: []const NodeOrText, frame: *Frame) !void {
- // First pass: validate all nodes and collect them
- // We need to collect because DocumentFragments contribute their children, not themselves
- var children_to_add: std.ArrayList(*Node) = .empty;
+ if (nodes.len > 1) {
+ // Several nodes are converted into a fragment first, as append and
+ // prepend do: a node passed twice is inserted once, and nodes taken
+ // from this parent don't leave a removal record behind.
+ const fragment = try DocumentFragment.init(self.getDocument(frame), frame);
+ const fragment_node = fragment.asNode();
+ defer if (fragment_node.firstChild() == null) frame._factory.destroy(fragment);
+ for (nodes) |node_or_text| {
+ const child = try node_or_text.toNode(self.getDocument(frame));
+ _ = try fragment_node.appendChild(child, frame);
+ }
+ return self.replaceAll(fragment_node, frame);
+ }
+ const node = if (nodes.len == 1) try nodes[0].toNode(self.getDocument(frame)) else null;
+ return self.replaceAll(node, frame);
+}
- for (nodes) |node_or_text| {
- const child = try node_or_text.toNode(self.getDocument(frame));
+// DOM "replace all": observers get one combined record with every removed
+// and added node, so per-node notification is suppressed.
+fn replaceAll(self: *Node, node_: ?*Node, frame: *Frame) !void {
+ if (node_) |node| {
+ try ensurePreInsertValidity(self, node, null, .insert);
+ }
+
+ frame.domChanged();
+ const notify = Frame.observers.hasMutationObservers(frame);
- // DocumentFragments contribute their children, not themselves
- if (child.is(DocumentFragment)) |frag| {
- var frag_it = frag.asNode().childrenIterator();
- while (frag_it.next()) |frag_child| {
- try validateNodeInsertion(self, frag_child);
- try children_to_add.append(frame.call_arena, frag_child);
+ var added: std.ArrayList(*Node) = .empty;
+ if (notify) {
+ if (node_) |node| {
+ if (node.is(DocumentFragment)) |_| {
+ var it = node.childrenIterator();
+ while (it.next()) |child| {
+ try added.append(frame.call_arena, child);
+ }
+ } else {
+ try added.append(frame.call_arena, node);
}
- } else {
- try validateNodeInsertion(self, child);
- try children_to_add.append(frame.call_arena, child);
}
}
- frame.domChanged();
-
- // Per the "replace all" algorithm, observers get one combined mutation
- // record with all removed and added nodes, so per-node notification is
- // suppressed here.
- const notify = Frame.observers.hasMutationObservers(frame);
const removed = try self.removeAllChildrenCollecting(notify, frame);
- 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 = if (adopting_to_new_document) null else self,
+ if (node_) |node| {
+ if (node.is(DocumentFragment)) |_| {
+ try frame.moveAllChildren(node, self, null, .silent_parent);
+ } else {
+ // A Document can't be inserted, so every other node has an owner.
+ const child_owner = node.ownerDocument(frame).?;
+ const parent_owner = self.ownerDocument(frame) orelse self.as(Document);
+ const adopting = child_owner != parent_owner;
+
+ var previous_root: ?*Node = null;
+ if (node._parent) |previous_parent| {
+ previous_root = node.getRootNode(.{});
+ frame.removeNode(previous_parent, node, .{
+ .reconnect_to = if (adopting) null else self,
+ });
+ }
+ if (adopting) {
+ try frame.adoptNodeTree(node, child_owner, parent_owner);
+ }
+ try frame.appendNode(self, node, .{
+ .previous_root = previous_root,
+ .adopting_to_new_document = adopting,
+ .notify_observers = false,
});
}
- if (adopting_to_new_document) {
- try frame.adoptNodeTree(child, child_owner.?, parent_owner);
- }
- 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)) {
- Frame.observers.notifyChildListChange(frame, self, children_to_add.items, removed.items, null, null);
+ if (notify and (removed.items.len > 0 or added.items.len > 0)) {
+ Frame.observers.notifyChildListChange(frame, self, added.items, removed.items, null, null);
}
}