Lightpanda: the headless browser designed for AI and automation
webapi: Track node relocation across shadow roots
Karl Seguin59be69b1f824
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zigindex a5ed00a7c..aa0c2ece0 100644--- a/src/browser/Frame.zig+++ b/src/browser/Frame.zig@@ -52,6 +52,7 @@ const VisualViewport = @import("webapi/VisualViewport.zig");const AbstractRange = @import("webapi/AbstractRange.zig");const DOMNodeIterator = @import("webapi/DOMNodeIterator.zig");const Worker = @import("webapi/Worker.zig");+const TreeWalker = @import("webapi/TreeWalker.zig");const MessagePort = @import("webapi/MessagePort.zig");const CSSStyleSheet = @import("webapi/css/CSSStyleSheet.zig");const CustomElementDefinition = @import("webapi/CustomElementDefinition.zig");@@ -2079,40 +2080,52 @@ pub fn domChanged(self: *Frame) void {const ElementIdMaps = struct { lookup: *std.StringHashMapUnmanaged(*Element), removed_ids: *std.StringHashMapUnmanaged(void) };fn getElementIdMap(frame: *Frame, node: *Node) ElementIdMaps {- // Walk up the tree checking for ShadowRoot and tracking the root- var current = node;- while (true) {- if (current.is(ShadowRoot)) |shadow_root| {- return .{- .lookup = &shadow_root._elements_by_id,- .removed_ids = &shadow_root._removed_ids,- };+ return idMapsForRoot(node.getRootNode(.{})) orelse {+ // Detached nodes should not have IDs registered+ if (lp.IS_DEBUG) {+ std.debug.assert(false);}+ return .{+ .lookup = &frame.document._elements_by_id,+ .removed_ids = &frame.document._removed_ids,+ };+ };+}- const parent = current._parent orelse {- if (current._type == .document) {- const doc = current.subtype(Document);- return .{- .lookup = &doc._elements_by_id,- .removed_ids = &doc._removed_ids,- };- }- // Detached nodes should not have IDs registered- if (lp.IS_DEBUG) {- std.debug.assert(false);- }- return .{- .lookup = &frame.document._elements_by_id,- .removed_ids = &frame.document._removed_ids,- };+// Ids are registered per tree scope: a ShadowRoot or a Document each own a+// map. A root that is neither (a detached tree) has none.+fn idMapsForRoot(root: *Node) ?ElementIdMaps {+ if (root.is(ShadowRoot)) |shadow_root| {+ return .{+ .lookup = &shadow_root._elements_by_id,+ .removed_ids = &shadow_root._removed_ids,+ };+ }+ if (root._type == .document) {+ const doc = root.subtype(Document);+ return .{+ .lookup = &doc._elements_by_id,+ .removed_ids = &doc._removed_ids,};+ }+ return null;+}- current = parent;+// Node.isConnected re-walks the ancestor chain; callers here already have the+// root in hand.+fn rootIsConnected(root: *Node) bool {+ if (root._type == .document) {+ return true;}+ const shadow_root = root.is(ShadowRoot) orelse return false;+ return shadow_root._host.asNode().isConnected();}pub fn addElementId(self: *Frame, parent: *Node, element: *Element, id: []const u8) !void {- var id_maps = self.getElementIdMap(parent);+ return self.addElementIdWithMaps(self.getElementIdMap(parent), element, id);+}++fn addElementIdWithMaps(self: *Frame, id_maps: ElementIdMaps, element: *Element, id: []const u8) !void {const gop = try id_maps.lookup.getOrPut(self.arena, id);if (!gop.found_existing) {gop.value_ptr.* = element;@@ -2152,7 +2165,7 @@ pub fn getElementByIdFromNode(self: *Frame, node: *Node, id: []const u8) ?*Eleme}// Detached subtree (root is neither a Document nor a ShadowRoot): no id map// exists, so scan it.- var tw = @import("webapi/TreeWalker.zig").Full.Elements.init(node, .{});+ var tw = TreeWalker.Full.Elements.init(node, .{});while (tw.next()) |el| {const element_id = el.getAttributeSafe(comptime .wrap("id")) orelse continue;if (std.mem.eql(u8, element_id, id)) {@@ -2461,12 +2474,8 @@ pub fn notifyNetworkAlmostIdle(self: *Frame) void {// "insert this fully-formed node as a new last child of parent" entry point.pub fn appendNew(self: *Frame, parent: *Node, child: *Node) !void {lp.assert(child._parent == null, "Frame.appendNew", .{});- try self._insertNodeRelative(true, parent, child, .append, .{- // this opts has no meaning since we're passing `true` as the first- // parameter, which indicates this comes from the parser, and has its- // own special processing. Still, set it to be clear.- .child_already_connected = false,- });+ // opts is meaningless when from_parser (the first param) is true.+ try self._insertNodeRelative(true, parent, child, .append, .{});}// called from the parser when the node and all its children have been added@@ -2533,7 +2542,12 @@ pub fn dupeSSO(self: *Frame, value: []const u8) !String {}const RemoveNodeOpts = struct {- will_be_reconnected: bool,+ // The parent the child is going to be attached to after it is removed. null+ // if it isn't AND null if the parent is cross-document. Why cross-document?+ // because a remove + add-to-another-document behaves like a distinct remove+ // + add. Where as a remove+add-to-the-same-document behaves more like a+ // "move", e.g. it doesn't require idmap changes NOR disconnectedCallbacks.+ reconnect_to: ?*Node,// Set to false when the caller queues its own combined mutation recordnotify_observers: bool = true,};@@ -2558,10 +2572,10 @@ pub fn removeNode(self: *Frame, parent: *Node, child: *Node, opts: RemoveNodeOptnull;parent.unlink(child);- // grab this before we null the parent- const was_connected = child.isConnected();- // Capture the ID map before disconnecting, so we can remove IDs from the correct document- const id_maps = if (was_connected) self.getElementIdMap(child) else null;++ const old_root = child.getRootNode(.{});+ const was_connected = rootIsConnected(old_root);+ const old_id_maps = idMapsForRoot(old_root);child._parent = null;@@ -2577,16 +2591,33 @@ pub fn removeNode(self: *Frame, parent: *Node, child: *Node, opts: RemoveNodeOptobservers.notifyChildListChange(self, parent, &.{}, &removed, previous_sibling, next_sibling);}- if (opts.will_be_reconnected) {- // We might be removing the node only to re-insert it. If the node will- // remain connected, we can skip the expensive process of fully- // disconnecting it.- return;+ if (opts.reconnect_to) |dest| {+ const dest_root = dest.getRootNode(.{});+ if (dest_root == old_root) {+ // reconnected under the same root, nothing to do (e.g. if it WAS in the+ // idmap, it'll stay there)+ return;+ }+ if (rootIsConnected(dest_root)) {+ // The node is going to be reconnected to a different root which IS+ // connected, we need to remove it from the old root's idmap.+ if (old_id_maps) |id_maps| {+ self.unregisterSubtreeIds(child, id_maps);+ }+ // but it isn't a REAL disconnect (more like a move), so there's+ // nothing else to do, e.g. no disconnectedCallback+ return;+ }+ // The destination is detached: this is a real disconnect.}if (was_connected == false) {- // If the child wasn't connected, then there should be nothing left for- // us to do+ // the node wasn't connected, but it could still have lived in a shadow+ // root's id map+ if (old_id_maps) |id_maps| {+ self.unregisterSubtreeIds(child, id_maps);+ }+ // and because it wasn't disconnected, there's nothing else to do.return;}@@ -2602,10 +2633,10 @@ pub fn removeNode(self: *Frame, parent: *Node, child: *Node, opts: RemoveNodeOpt// The child was connected and now it no longer is. We need to "disconnect"// it and all of its descendants. For now "disconnect" just means updating// the ID map and invoking disconnectedCallback for custom elements- var tw = @import("webapi/TreeWalker.zig").Full.Elements.init(child, .{});+ var tw = TreeWalker.Full.Elements.init(child, .{});while (tw.next()) |el| {if (el.getAttributeSafe(comptime .wrap("id"))) |id| {- self.removeElementIdWithMaps(id_maps.?, id);+ self.removeElementIdWithMaps(old_id_maps.?, id);}Element.Html.Custom.enqueueDisconnectedCallbackOnElement(el, self);@@ -2639,6 +2670,17 @@ pub fn removeNode(self: *Frame, parent: *Node, child: *Node, opts: RemoveNodeOpt}}+// The TreeWalker isn't shadow DOM aware, so this is correctly scoped to direct+// descendants (ids nested under a shadow DOM are owned by that shadow DOM).+fn unregisterSubtreeIds(self: *Frame, node: *Node, id_maps: ElementIdMaps) void {+ var tw = TreeWalker.Full.Elements.init(node, .{});+ while (tw.next()) |el| {+ if (el.getAttributeSafe(comptime .wrap("id"))) |id| {+ self.removeElementIdWithMaps(id_maps, id);+ }+ }+}+pub fn appendNode(self: *Frame, parent: *Node, child: *Node, opts: InsertNodeOpts) !void {return self._insertNodeRelative(false, parent, child, .append, opts);}@@ -2662,26 +2704,27 @@ pub const MoveChildrenNotify = enum { records, silent_parent };// pay attention to suppressObservers".pub fn moveAllChildren(self: *Frame, source: *Node, parent: *Node, ref_node: ?*Node, notify_mode: MoveChildrenNotify) !void {self.domChanged();- const dest_connected = parent.isConnected();const notify = observers.hasMutationObservers(self);var moved: std.ArrayList(*Node) = .empty;const previous_sibling = if (ref_node) |ref| ref.previousSibling() else parent.lastChild();+ // Every child shares source's root, and source itself doesn't move.+ const previous_root = source.getRootNode(.{});+var it = source.childrenIterator();while (it.next()) |child| {try moved.append(self.call_arena, child);- const child_was_connected = child.isConnected();- self.removeNode(source, child, .{ .will_be_reconnected = dest_connected, .notify_observers = false });+ self.removeNode(source, child, .{ .reconnect_to = parent, .notify_observers = false });if (ref_node) |ref| {try self.insertNodeRelative(parent,child,.{ .before = ref },- .{ .child_already_connected = child_was_connected, .notify_observers = false, .run_ready = false },+ .{ .previous_root = previous_root, .notify_observers = false, .run_ready = false },);} else {- try self.appendNode(parent, child, .{ .child_already_connected = child_was_connected, .notify_observers = false, .run_ready = false });+ try self.appendNode(parent, child, .{ .previous_root = previous_root, .notify_observers = false, .run_ready = false });}}@@ -2715,7 +2758,10 @@ const InsertNodeRelative = union(enum) {before: *Node,};const InsertNodeOpts = struct {- child_already_connected: bool = false,+ // The other half of RemoveNodeOpts.reconnect_to. This is the root (not+ // parent) of the node before it was moved. This is null when the operation+ // isn't part of a "move" (remove+add) but was a new/cloned child.+ previous_root: ?*Node = null,adopting_to_new_document: bool = false,// Set to false when the caller queues its own combined mutation recordnotify_observers: bool = true,@@ -2797,7 +2843,8 @@ pub fn _insertNodeRelative(self: *Frame, comptime from_parser: bool, parent: *Noreturn;}- const parent_is_connected = parent.isConnected();+ const parent_root = parent.getRootNode(.{});+ const parent_is_connected = rootIsConnected(parent_root);// Mutation records queue synchronously at insertion, before any script// runs: an inserted script can observe its own record via takeRecords.@@ -2822,37 +2869,47 @@ pub fn _insertNodeRelative(self: *Frame, comptime from_parser: bool, parent: *Notry self.nodeIsReadySubtree(child);}- if (opts.child_already_connected and !opts.adopting_to_new_document) {- // The child is already connected in the same document, we don't have to reconnect it.- // On cross-document adoption the child has already fired- // disconnectedCallback against the old tree and must re-fire- // connectedCallback for the new tree, so we fall through.+ // nothing to register, and nothing can become connected.+ const new_id_maps = idMapsForRoot(parent_root) orelse {+ // The destination has no id scope, it's detached and outside of a+ // shadow root. There's nothing left to do.return;- }-- const parent_in_shadow = parent.containingShadowRoot() != null;+ };- if (!parent_in_shadow and !parent_is_connected) {- return;+ if (!opts.adopting_to_new_document) {+ if (opts.previous_root) |previous_root| {+ if (previous_root == parent_root) {+ // The child already belongs to this scope; nothing to do.+ return;+ }+ if (rootIsConnected(previous_root)) {+ // The child is being moved to a different scope, but was and+ // remains connected. We need to move it (and any children)'s+ // id to the new parent...+ var tw = TreeWalker.Full.Elements.init(child, .{});+ while (tw.next()) |el| {+ if (el.getAttributeSafe(comptime .wrap("id"))) |id| {+ try self.addElementIdWithMaps(new_id_maps, el, id);+ }+ }+ // but beause it was and stays connected, we don't trigger+ // a connectedCallback.+ return;+ }+ // The child was in a detached tree (removeNode already cleaned a+ // detached-host shadow map, if any): a fresh connect, below.+ }}- // If we're here, it means either:- // 1. A disconnected child became connected (parent.isConnected() == true)- // 2. Child is being added to a shadow tree (parent_in_shadow == true)- // In both cases, we need to update ID maps and invoke callbacks-- // Only invoke connectedCallback if the root child is transitioning from- // disconnected to connected. When that happens, all descendants should also- // get connectedCallback invoked (they're becoming connected as a group).- // Cross-document adoption also counts as a transition: the element fired- // disconnectedCallback against the old tree during removeNode and must- // now fire connectedCallback against the new tree.- const should_invoke_connected = parent_is_connected and (!opts.child_already_connected or opts.adopting_to_new_document);+ // The child was not connected or is being adopted. We need to move the id+ // (of it and its chidlren) and if it is newly becoming connected, invoke+ // connectedCallback.+ const should_invoke_connected = parent_is_connected;- var tw = @import("webapi/TreeWalker.zig").Full.Elements.init(child, .{});+ var tw = TreeWalker.Full.Elements.init(child, .{});while (tw.next()) |el| {if (el.getAttributeSafe(comptime .wrap("id"))) |id| {- try self.addElementId(el.asNode()._parent.?, el, id);+ try self.addElementIdWithMaps(new_id_maps, el, id);}if (should_invoke_connected) {@@ -2994,7 +3051,7 @@ fn nodeIsReadySubtree(self: *Frame, node: *Node) !void {// Scripts can mutate the tree. Safe to do this since nodeIsReady re-checks// connectivity.var elements: std.ArrayList(*Node) = .empty;- var tw = @import("webapi/TreeWalker.zig").Full.Elements.init(node, .{});+ var tw = TreeWalker.Full.Elements.init(node, .{});while (tw.next()) |el| {try elements.append(self.call_arena, el.asNode());}diff --git a/src/browser/parser/Parser.zig b/src/browser/parser/Parser.zigindex 370f65a5f..2bbe994cb 100644--- a/src/browser/parser/Parser.zig+++ b/src/browser/parser/Parser.zig@@ -684,7 +684,7 @@ fn _appendCallback(self: *Parser, parent: *Node, node_or_text: h5e.NodeOrText) !if (comptime lp.IS_DEBUG) {unreachable;}- self.frame.removeNode(previous_parent, child, .{ .will_be_reconnected = parent.isConnected() });+ self.frame.removeNode(previous_parent, child, .{ .reconnect_to = parent });}try self.frame.appendNew(parent, child);},@@ -757,7 +757,7 @@ fn _appendBeforeSiblingCallback(self: *Parser, sibling: *Node, node_or_text: h5e// A custom element constructor may have inserted the node into the// DOM before the parser officially places it (e.g. via foster// parenting). Detach it first so insertNodeRelative's assertion holds.- self.frame.removeNode(previous_parent, child, .{ .will_be_reconnected = parent.isConnected() });+ self.frame.removeNode(previous_parent, child, .{ .reconnect_to = parent });}break :blk child;},diff --git a/src/browser/tests/shadowroot/id_scope_moves.html b/src/browser/tests/shadowroot/id_scope_moves.htmlnew file mode 100644index 000000000..be2999d12--- /dev/null+++ b/src/browser/tests/shadowroot/id_scope_moves.html@@ -0,0 +1,250 @@+<!DOCTYPE html>+<script src="../testing.js"></script>+<body></body>++<script id="connected_move_document_to_shadow">+{+ const host = document.createElement('div');+ const shadow = host.attachShadow({ mode: 'open' });+ document.body.appendChild(host);++ const div = document.createElement('div');+ div.id = 'mover';+ div.textContent = 'Content';+ document.body.appendChild(div);++ testing.expectEqual('Content', document.getElementById('mover').textContent);++ // Both host and div are connected, so this move never disconnects div.+ shadow.appendChild(div);++ testing.expectEqual(null, document.getElementById('mover'));+ testing.expectEqual(null, document.querySelector('#mover'));+ testing.expectEqual('Content', shadow.getElementById('mover').textContent);+ testing.expectEqual('Content', shadow.querySelector('#mover').textContent);++ host.remove();+}+</script>++<script id="connected_move_shadow_to_document">+{+ const host = document.createElement('div');+ const shadow = host.attachShadow({ mode: 'open' });+ document.body.appendChild(host);+ shadow.innerHTML = '<div id="escapee">Content</div>';++ testing.expectEqual('Content', shadow.getElementById('escapee').textContent);++ const div = shadow.getElementById('escapee');+ document.body.appendChild(div);++ testing.expectEqual(null, shadow.getElementById('escapee'));+ testing.expectEqual(null, shadow.querySelector('#escapee'));+ testing.expectEqual('Content', document.getElementById('escapee').textContent);+ testing.expectEqual('Content', document.querySelector('#escapee').textContent);++ div.remove();+ host.remove();+}+</script>++<script id="connected_move_shadow_to_shadow">+{+ const host1 = document.createElement('div');+ const shadow1 = host1.attachShadow({ mode: 'open' });+ const host2 = document.createElement('div');+ const shadow2 = host2.attachShadow({ mode: 'open' });+ document.body.appendChild(host1);+ document.body.appendChild(host2);++ shadow1.innerHTML = '<p id="hopper">Content</p>';+ const p = shadow1.getElementById('hopper');++ shadow2.appendChild(p);++ testing.expectEqual(null, shadow1.getElementById('hopper'));+ testing.expectEqual('Content', shadow2.getElementById('hopper').textContent);+ testing.expectEqual('Content', shadow2.querySelector('#hopper').textContent);+ testing.expectEqual(null, document.getElementById('hopper'));++ host1.remove();+ host2.remove();+}+</script>++<script id="subtree_ids_move_together">+{+ const host = document.createElement('div');+ const shadow = host.attachShadow({ mode: 'open' });+ document.body.appendChild(host);++ const wrap = document.createElement('div');+ wrap.innerHTML = '<span id="inner-a">A</span><span><b id="inner-b">B</b></span>';+ document.body.appendChild(wrap);++ testing.expectEqual('A', document.getElementById('inner-a').textContent);++ // Moving the wrapper migrates every descendant id, not just the root's.+ shadow.appendChild(wrap);++ testing.expectEqual(null, document.getElementById('inner-a'));+ testing.expectEqual(null, document.getElementById('inner-b'));+ testing.expectEqual('A', shadow.getElementById('inner-a').textContent);+ testing.expectEqual('B', shadow.getElementById('inner-b').textContent);++ host.remove();+}+</script>++<script id="insert_before_across_scopes">+{+ const host = document.createElement('div');+ const shadow = host.attachShadow({ mode: 'open' });+ document.body.appendChild(host);+ shadow.innerHTML = '<p>anchor</p>';++ const div = document.createElement('div');+ div.id = 'before-mover';+ document.body.appendChild(div);++ shadow.insertBefore(div, shadow.firstChild);++ testing.expectEqual(null, document.getElementById('before-mover'));+ testing.expectEqual(div, shadow.getElementById('before-mover'));++ host.remove();+}+</script>++<script id="move_before_across_scopes">+{+ const host = document.createElement('div');+ const shadow = host.attachShadow({ mode: 'open' });+ document.body.appendChild(host);+ shadow.innerHTML = '<p>anchor</p>';++ const div = document.createElement('div');+ div.id = 'atomic-mover';+ document.body.appendChild(div);++ // moveBefore allows moves anywhere within the same shadow-including root.+ shadow.moveBefore(div, shadow.firstChild);++ testing.expectEqual(null, document.getElementById('atomic-mover'));+ testing.expectEqual(div, shadow.getElementById('atomic-mover'));+ testing.expectEqual(div, shadow.querySelector('#atomic-mover'));++ // and back out again+ document.body.moveBefore(div, null);++ testing.expectEqual(null, shadow.getElementById('atomic-mover'));+ testing.expectEqual(div, document.getElementById('atomic-mover'));++ div.remove();+ host.remove();+}+</script>++<script id="duplicate_id_left_behind_still_found">+{+ const host = document.createElement('div');+ const shadow = host.attachShadow({ mode: 'open' });+ document.body.appendChild(host);++ const first = document.createElement('div');+ first.id = 'dupe';+ first.textContent = 'First';+ const second = document.createElement('div');+ second.id = 'dupe';+ second.textContent = 'Second';+ document.body.appendChild(first);+ document.body.appendChild(second);++ testing.expectEqual('First', document.getElementById('dupe').textContent);++ // Moving the mapped element out must let the remaining duplicate surface.+ shadow.appendChild(first);++ testing.expectEqual('Second', document.getElementById('dupe').textContent);+ testing.expectEqual('First', shadow.getElementById('dupe').textContent);++ second.remove();+ host.remove();+}+</script>++<script id="clonable_shadow_root_clone_ids">+{+ const host = document.createElement('div');+ const shadow = host.attachShadow({ mode: 'open', clonable: true });+ shadow.innerHTML = '<span id="cloned-id">Original</span>';+ document.body.appendChild(host);++ const clone = host.cloneNode(true);++ testing.expectEqual('Original', clone.shadowRoot.getElementById('cloned-id').textContent);+ testing.expectEqual('Original', clone.shadowRoot.querySelector('#cloned-id').textContent);++ // The clone's map is its own: changing the original doesn't affect it.+ shadow.getElementById('cloned-id').remove();+ testing.expectEqual(null, shadow.getElementById('cloned-id'));+ testing.expectEqual('Original', clone.shadowRoot.getElementById('cloned-id').textContent);++ host.remove();+}+</script>++<script id="detached_host_shadow_removal">+{+ // A shadow tree keeps its id map even while its host is detached; removal+ // must still unregister.+ const host = document.createElement('div');+ const shadow = host.attachShadow({ mode: 'open' });+ shadow.innerHTML = '<div id="ghost">Boo</div>';++ const div = shadow.getElementById('ghost');+ testing.expectEqual('Boo', div.textContent);++ div.remove();++ testing.expectEqual(null, shadow.getElementById('ghost'));+ testing.expectEqual(null, shadow.querySelector('#ghost'));+}+</script>++<script id="detached_host_shadow_to_document">+{+ const host = document.createElement('div');+ const shadow = host.attachShadow({ mode: 'open' });+ shadow.innerHTML = '<div id="riser">Content</div>';++ const div = shadow.getElementById('riser');+ document.body.appendChild(div);++ testing.expectEqual(null, shadow.getElementById('riser'));+ testing.expectEqual('Content', document.getElementById('riser').textContent);++ div.remove();+}+</script>++<script id="replace_children_across_scopes">+{+ const host = document.createElement('div');+ const shadow = host.attachShadow({ mode: 'open' });+ document.body.appendChild(host);++ const div = document.createElement('div');+ div.id = 'replaced-in';+ div.textContent = 'Content';+ document.body.appendChild(div);++ shadow.replaceChildren(div);++ testing.expectEqual(null, document.getElementById('replaced-in'));+ testing.expectEqual('Content', shadow.getElementById('replaced-in').textContent);++ host.remove();+}+</script>diff --git a/src/browser/webapi/Document.zig b/src/browser/webapi/Document.zigindex f3b2e75f3..a1e4364be 100644--- a/src/browser/webapi/Document.zig+++ b/src/browser/webapi/Document.zig@@ -780,7 +780,7 @@ pub fn adoptNode(self: *Document, node: *Node, frame: *Frame) !*Node {const old_owner = node.ownerDocument(frame) orelse frame.document;if (node._parent) |parent| {- frame.removeNode(parent, node, .{ .will_be_reconnected = false });+ frame.removeNode(parent, node, .{ .reconnect_to = null });}if (old_owner != self) {@@ -803,7 +803,6 @@ pub fn append(self: *Document, nodes: []const Node.NodeOrText, frame: *Frame) !vconst parent = self.asNode();frame.domChanged();- const parent_is_connected = parent.isConnected();for (nodes) |node_or_text| {const child = try node_or_text.toNode(frame);@@ -814,12 +813,12 @@ pub fn append(self: *Document, nodes: []const Node.NodeOrText, frame: *Frame) !vcontinue;}- var child_connected = false;+ var previous_root: ?*Node = null;if (child._parent) |previous_parent| {- child_connected = child.isConnected();- frame.removeNode(previous_parent, child, .{ .will_be_reconnected = parent_is_connected });+ previous_root = child.getRootNode(.{});+ frame.removeNode(previous_parent, child, .{ .reconnect_to = parent });}- try frame.appendNode(parent, child, .{ .child_already_connected = child_connected });+ try frame.appendNode(parent, child, .{ .previous_root = previous_root });}}@@ -828,7 +827,6 @@ pub fn prepend(self: *Document, nodes: []const Node.NodeOrText, frame: *Frame) !const parent = self.asNode();frame.domChanged();- const parent_is_connected = parent.isConnected();var i = nodes.len;while (i > 0) {@@ -841,7 +839,7 @@ pub fn prepend(self: *Document, nodes: []const Node.NodeOrText, frame: *Frame) !var frag_child = frag.asNode().lastChild();while (frag_child) |fc| {const prev = fc.previousSibling();- frame.removeNode(frag.asNode(), fc, .{ .will_be_reconnected = parent_is_connected });+ frame.removeNode(frag.asNode(), fc, .{ .reconnect_to = parent });if (first_child) |before| {try frame.insertNodeRelative(parent, fc, .{ .before = before }, .{});} else {@@ -852,17 +850,17 @@ pub fn prepend(self: *Document, nodes: []const Node.NodeOrText, frame: *Frame) !continue;}- var child_connected = false;+ var previous_root: ?*Node = null;if (child._parent) |previous_parent| {- child_connected = child.isConnected();- frame.removeNode(previous_parent, child, .{ .will_be_reconnected = parent_is_connected });+ previous_root = child.getRootNode(.{});+ frame.removeNode(previous_parent, child, .{ .reconnect_to = parent });}const first_child = parent.firstChild();if (first_child) |before| {- try frame.insertNodeRelative(parent, child, .{ .before = before }, .{ .child_already_connected = child_connected });+ try frame.insertNodeRelative(parent, child, .{ .before = before }, .{ .previous_root = previous_root });} else {- try frame.appendNode(parent, child, .{ .child_already_connected = child_connected });+ try frame.appendNode(parent, child, .{ .previous_root = previous_root });}}}@@ -1146,7 +1144,7 @@ pub fn open(self: *Document, call_frame: *Frame) !*Document {// Remove all children from documentvar it = doc_node.childrenIterator();while (it.next()) |child| {- frame.removeNode(doc_node, child, .{ .will_be_reconnected = false });+ frame.removeNode(doc_node, child, .{ .reconnect_to = null });}}diff --git a/src/browser/webapi/DocumentFragment.zig b/src/browser/webapi/DocumentFragment.zigindex 2580ca815..01a5aa4a3 100644--- a/src/browser/webapi/DocumentFragment.zig+++ b/src/browser/webapi/DocumentFragment.zig@@ -173,13 +173,10 @@ pub fn cloneFragment(self: *DocumentFragment, deep: bool, frame: *Frame) !*Nodeconst fragment_node = fragment.asNode();if (deep) {- const node = self.asNode();- const self_is_connected = node.isConnected();-- var child_it = node.childrenIterator();+ var child_it = self.asNode().childrenIterator();while (child_it.next()) |child| {if (try child.cloneNodeForAppending(true, frame)) |cloned_child| {- try frame.appendNode(fragment_node, cloned_child, .{ .child_already_connected = self_is_connected });+ try frame.appendNode(fragment_node, cloned_child, .{});}}}diff --git a/src/browser/webapi/Element.zig b/src/browser/webapi/Element.zigindex 497ea81c4..b94294999 100644--- a/src/browser/webapi/Element.zig+++ b/src/browser/webapi/Element.zig@@ -557,7 +557,6 @@ pub fn setOuterHTML(self: *Element, html: []const u8, frame: *Frame) !void {const next_sibling = node.nextSibling();if (fragment) |frag| {- const dest_connected = parent.isConnected();var it = frag.childrenIterator();while (it.next()) |child| {if (node._parent != parent) {@@ -566,7 +565,7 @@ pub fn setOuterHTML(self: *Element, html: []const u8, frame: *Frame) !void {if (notify) {try added.append(frame.call_arena, child);}- frame.removeNode(frag, child, .{ .will_be_reconnected = dest_connected, .notify_observers = false });+ frame.removeNode(frag, child, .{ .reconnect_to = parent, .notify_observers = false });try frame.insertNodeRelative(parent, child, .{ .before = node }, .{ .notify_observers = false });}}@@ -574,7 +573,7 @@ pub fn setOuterHTML(self: *Element, html: []const u8, frame: *Frame) !void {if (node._parent != parent) {return error.NotFound;}- frame.removeNode(parent, node, .{ .will_be_reconnected = false, .notify_observers = false });+ frame.removeNode(parent, node, .{ .reconnect_to = null, .notify_observers = false });if (notify) {const removed = [_]*Node{node};@@ -1035,8 +1034,6 @@ pub fn replaceWith(self: *Element, nodes: []const Node.NodeOrText, frame: *Frameconst parent = ref_node._parent orelse return;frame.domChanged();- const parent_is_connected = parent.isConnected();-// Detect if the ref_node must be removed (by default) or kept.// We kept it when ref_node is present into the nodes list.var rm_ref_node = true;@@ -1056,22 +1053,24 @@ pub fn replaceWith(self: *Element, nodes: []const Node.NodeOrText, frame: *Framecontinue;}+ var previous_root: ?*Node = null;if (child._parent) |current_parent| {- frame.removeNode(current_parent, child, .{ .will_be_reconnected = parent_is_connected });+ previous_root = child.getRootNode(.{});+ frame.removeNode(current_parent, child, .{ .reconnect_to = parent });}try frame.insertNodeRelative(parent,child,.{ .before = ref_node },- .{ .child_already_connected = child.isConnected() },+ .{ .previous_root = previous_root },);}// Re-check parent after insertNodeRelative since callbacks (e.g. connectedCallback)// could have already removed ref_node from parent.if (rm_ref_node and ref_node._parent == parent) {- frame.removeNode(parent, ref_node, .{ .will_be_reconnected = false });+ frame.removeNode(parent, ref_node, .{ .reconnect_to = null });}}@@ -1079,7 +1078,7 @@ pub fn remove(self: *Element, frame: *Frame) void {const node = self.asNode();const parent = node._parent orelse return;frame.domChanged();- frame.removeNode(parent, node, .{ .will_be_reconnected = false });+ frame.removeNode(parent, node, .{ .reconnect_to = null });}pub fn focus(self: *Element, frame: *Frame) !void {@@ -1802,7 +1801,7 @@ pub fn clone(self: *Element, deep: bool, frame: *Frame) !*Node {var shadow_child_it = shadow.asNode().childrenIterator();while (shadow_child_it.next()) |child| {if (try child.cloneNodeForAppending(true, frame)) |cloned_child| {- try frame.appendNode(cloned_shadow_node, cloned_child, .{ .child_already_connected = true });+ try frame.appendNode(cloned_shadow_node, cloned_child, .{});}}}@@ -1812,10 +1811,7 @@ pub fn clone(self: *Element, deep: bool, frame: *Frame) !*Node {var child_it = self.asNode().childrenIterator();while (child_it.next()) |child| {if (try child.cloneNodeForAppending(true, frame)) |cloned_child| {- // We pass `true` to `child_already_connected` as a hacky optimization- // We _know_ this child isn't connected (Because the parent isn't connected)- // setting this to `true` skips all connection checks.- try frame.appendNode(node, cloned_child, .{ .child_already_connected = true });+ try frame.appendNode(node, cloned_child, .{});}}}diff --git a/src/browser/webapi/Node.zig b/src/browser/webapi/Node.zigindex 03b84fa8d..a0c9d5f4d 100644--- a/src/browser/webapi/Node.zig+++ b/src/browser/webapi/Node.zig@@ -393,10 +393,7 @@ pub fn appendChild(self: *Node, child: *Node, frame: *Frame) !*Node {frame.domChanged();- // If the child is currently connected, and if its new parent is connected,- // then we can remove + add a bit more efficiently (we don't have to fully- // disconnect then reconnect)- const child_connected = child.isConnected();+ const previous_root = child.getRootNode(.{});// Check if we're adopting the node to a different documentconst child_owner = child.ownerDocument(frame);@@ -404,12 +401,8 @@ pub fn appendChild(self: *Node, child: *Node, frame: *Frame) !*Node {const adopting_to_new_document = child_owner != null and child_owner.? != parent_owner;if (child._parent) |parent| {- // we can signal removeNode that the child will remain connected- // (when it's appended to self) so that it can be a bit more efficient.- // But on cross-document moves the child must fully disconnect from the- // source document (firing disconnectedCallback) before adoption.frame.removeNode(parent, child, .{- .will_be_reconnected = self.isConnected() and !adopting_to_new_document,+ .reconnect_to = if (adopting_to_new_document) null else self,});}@@ -419,7 +412,7 @@ pub fn appendChild(self: *Node, child: *Node, frame: *Frame) !*Node {}try frame.appendNode(self, child, .{- .child_already_connected = child_connected,+ .previous_root = previous_root,.adopting_to_new_document = adopting_to_new_document,});return child;@@ -811,7 +804,7 @@ pub fn removeChild(self: *Node, child: *Node, frame: *Frame) !*Node {while (it.next()) |n| {if (n == child) {frame.domChanged();- frame.removeNode(self, child, .{ .will_be_reconnected = false });+ frame.removeNode(self, child, .{ .reconnect_to = null });return child;}}@@ -850,7 +843,7 @@ fn insertBeforeInner(self: *Node, new_node: *Node, ref_node_: ?*Node, frame: *Frreturn new_node;}- const child_already_connected = new_node.isConnected();+ const previous_root = new_node.getRootNode(.{});// Check if we're adopting the node to a different documentconst child_owner = new_node.ownerDocument(frame);@@ -858,9 +851,10 @@ fn insertBeforeInner(self: *Node, new_node: *Node, ref_node_: ?*Node, frame: *Frconst adopting_to_new_document = child_owner != null and child_owner.? != parent_owner;frame.domChanged();- const will_be_reconnected = self.isConnected() and !adopting_to_new_document;if (new_node._parent) |parent| {- frame.removeNode(parent, new_node, .{ .will_be_reconnected = will_be_reconnected });+ frame.removeNode(parent, new_node, .{+ .reconnect_to = if (adopting_to_new_document) null else self,+ });}// Adopt the node tree if moving between documents@@ -873,7 +867,7 @@ fn insertBeforeInner(self: *Node, new_node: *Node, ref_node_: ?*Node, frame: *Frnew_node,.{ .before = ref_node },.{- .child_already_connected = child_already_connected,+ .previous_root = previous_root,.adopting_to_new_document = adopting_to_new_document,},);@@ -894,16 +888,16 @@ pub fn replaceChild(self: *Node, new_child: *Node, old_child: *Node, frame: *Fra// followed by an addition record.const prev = old_child.previousSibling();const next = old_child.nextSibling();- const was_connected = old_child.isConnected();- frame.removeNode(self, old_child, .{ .will_be_reconnected = was_connected, .notify_observers = false });+ const previous_root = old_child.getRootNode(.{});+ frame.removeNode(self, old_child, .{ .reconnect_to = self, .notify_observers = false });if (next) |reference| {try frame.insertNodeRelative(self, old_child, .{ .before = reference }, .{- .child_already_connected = was_connected,+ .previous_root = previous_root,.notify_observers = false,});} else {try frame.appendNode(self, old_child, .{- .child_already_connected = was_connected,+ .previous_root = previous_root,.notify_observers = false,});}@@ -926,15 +920,16 @@ pub fn replaceChild(self: *Node, new_child: *Node, old_child: *Node, frame: *Frareference = new_child.nextSibling();}- const child_already_connected = new_child.isConnected();+ const previous_root = new_child.getRootNode(.{});const child_owner = new_child.ownerDocument(frame);const parent_owner = self.ownerDocument(frame) orelse self.as(Document);const adopting = child_owner != null and child_owner.? != parent_owner;- const will_be_reconnected = self.isConnected() and !adopting;if (new_child.is(DocumentFragment) == null) {if (new_child._parent) |previous_parent| {- frame.removeNode(previous_parent, new_child, .{ .will_be_reconnected = will_be_reconnected });+ frame.removeNode(previous_parent, new_child, .{+ .reconnect_to = if (adopting) null else self,+ });}if (adopting) {try frame.adoptNodeTree(new_child, child_owner.?, parent_owner);@@ -953,7 +948,7 @@ pub fn replaceChild(self: *Node, new_child: *Node, old_child: *Node, frame: *Fra}}- frame.removeNode(self, old_child, .{ .will_be_reconnected = false, .notify_observers = false });+ frame.removeNode(self, old_child, .{ .reconnect_to = null, .notify_observers = false });if (new_child.is(DocumentFragment)) |_| {try frame.moveAllChildren(new_child, self, reference, .silent_parent);@@ -963,14 +958,14 @@ pub fn replaceChild(self: *Node, new_child: *Node, old_child: *Node, frame: *Franew_child,.{ .before = ref },.{- .child_already_connected = child_already_connected,+ .previous_root = previous_root,.adopting_to_new_document = adopting,.notify_observers = false,},);} else {try frame.appendNode(self, new_child, .{- .child_already_connected = child_already_connected,+ .previous_root = previous_root,.adopting_to_new_document = adopting,.notify_observers = false,});@@ -1049,21 +1044,23 @@ pub fn moveBefore(self: *Node, node_val: js.Value, child_val: js.Value, frame: *frame.domChanged();- // selfand node share a root, so the connectedness won't change. This API- // should appear atomic as much as possible. We can skip the id-map- // management (because it won't change) and custom elements shouldn't fire- // disconnect/connected callbacks. But MutationObservers and ranges still- // fire+ // self and node share a *composed* root, so the connectedness won't+ // change — but the move can still cross tree scopes (document <->+ // shadow), moving ids between maps. This API should appear atomic as much+ // as possible: custom elements don't fire disconnected/connected+ // callbacks (they get connectedMoveCallback below). But MutationObservers+ // and ranges still fire.const connected = node.isConnected();+ const previous_root = node.getRootNode(.{});if (node._parent) |old_parent| {- frame.removeNode(old_parent, node, .{ .will_be_reconnected = connected });+ frame.removeNode(old_parent, node, .{ .reconnect_to = self });}if (ref) |r| {- try frame.insertNodeRelative(self, node, .{ .before = r }, .{ .child_already_connected = connected });+ try frame.insertNodeRelative(self, node, .{ .before = r }, .{ .previous_root = previous_root });} else {- try frame.appendNode(self, node, .{ .child_already_connected = connected });+ try frame.appendNode(self, node, .{ .previous_root = previous_root });}if (connected) {@@ -1394,7 +1391,7 @@ fn _normalize(self: *Node, allocator: Allocator, buffer: *std.ArrayList(u8), fra};if (text_node.asCData().getData().len == 0) {- frame.removeNode(self, current_node, .{ .will_be_reconnected = false });+ frame.removeNode(self, current_node, .{ .reconnect_to = null });child = next_node;continue;}@@ -1409,7 +1406,7 @@ fn _normalize(self: *Node, allocator: Allocator, buffer: *std.ArrayList(u8), fraconst to_remove = node_to_merge;next_node = node_to_merge.nextSibling();- frame.removeNode(self, to_remove, .{ .will_be_reconnected = false });+ frame.removeNode(self, to_remove, .{ .reconnect_to = null });}text_node.asCData()._data = try frame.dupeSSO(buffer.items);buffer.clearRetainingCapacity();@@ -1560,14 +1557,13 @@ pub fn replaceChildren(self: *Node, nodes: []const NodeOrText, frame: *Frame) !vconst removed = try self.removeAllChildrenCollecting(notify, frame);// Append new children- const parent_is_connected = self.isConnected();for (children_to_add.items) |child| {- var child_connected = false;+ var previous_root: ?*Node = null;if (child._parent) |previous_parent| {- child_connected = child.isConnected();- frame.removeNode(previous_parent, child, .{ .will_be_reconnected = parent_is_connected });+ previous_root = child.getRootNode(.{});+ frame.removeNode(previous_parent, child, .{ .reconnect_to = self });}- try frame.appendNode(self, child, .{ .child_already_connected = child_connected, .notify_observers = false });+ try frame.appendNode(self, child, .{ .previous_root = previous_root, .notify_observers = false });}if (notify and (removed.items.len > 0 or children_to_add.items.len > 0)) {@@ -1585,7 +1581,7 @@ fn removeAllChildrenCollecting(self: *Node, notify: bool, frame: *Frame) !std.Arif (notify) {try removed.append(frame.call_arena, child);}- frame.removeNode(self, child, .{ .will_be_reconnected = false, .notify_observers = false });+ frame.removeNode(self, child, .{ .reconnect_to = null, .notify_observers = false });}return removed;}diff --git a/src/browser/webapi/Range.zig b/src/browser/webapi/Range.zigindex 6b6978ded..dcdafd8ec 100644--- a/src/browser/webapi/Range.zig+++ b/src/browser/webapi/Range.zig@@ -708,8 +708,8 @@ pub fn createContextualFragment(self: *const Range, html: []const u8, frame: *Fr// Keep removing first child until temp element is emptyconst fragment_node = fragment.asNode();while (temp_node.firstChild()) |child| {- frame.removeNode(temp_node, child, .{ .will_be_reconnected = true });- try frame.appendNode(fragment_node, child, .{ .child_already_connected = false });+ frame.removeNode(temp_node, child, .{ .reconnect_to = fragment_node });+ try frame.appendNode(fragment_node, child, .{});}return fragment;diff --git a/src/browser/webapi/element/Html.zig b/src/browser/webapi/element/Html.zigindex 1dc08f973..c426b1f53 100644--- a/src/browser/webapi/element/Html.zig+++ b/src/browser/webapi/element/Html.zig@@ -1781,7 +1781,7 @@ fn mergeTextNodes(left_node: *Node, right_node: *Node, frame: *Frame) !bool {if (right_node.parentNode()) |p| {// remove right node- frame.removeNode(p, right_node, .{ .will_be_reconnected = false });+ frame.removeNode(p, right_node, .{ .reconnect_to = null });}return true;}diff --git a/src/browser/webapi/element/html/Template.zig b/src/browser/webapi/element/html/Template.zigindex d84550fb9..e264a8316 100644--- a/src/browser/webapi/element/html/Template.zig+++ b/src/browser/webapi/element/html/Template.zig@@ -174,7 +174,7 @@ pub const Build = struct {var child_it = source._content.asNode().childrenIterator();while (child_it.next()) |child| {if (try child.cloneNodeForAppending(true, frame)) |cloned_child| {- try frame.appendNode(clone_content, cloned_child, .{ .child_already_connected = true });+ try frame.appendNode(clone_content, cloned_child, .{});}}}