Lightpanda: the headless browser designed for AI and automation
webapi: id query selector with duplicate ids
Karl Seguindda4ed8c0a6e
diff --git a/src/SemanticTree.zig b/src/SemanticTree.zigindex 2b5a50def..247c60a45 100644--- a/src/SemanticTree.zig+++ b/src/SemanticTree.zig@@ -687,7 +687,7 @@ fn extractSelectOptions(node: *Node, frame: *Frame, arena: std.mem.Allocator) ![}fn extractDataListOptions(list_id: []const u8, frame: *Frame, arena: std.mem.Allocator) !?[]OptionData {- if (frame.document.getElementById(list_id, frame)) |referenced_el| {+ if (frame.document.getElementById(list_id)) |referenced_el| {if (referenced_el.getTag() == .datalist) {return try extractSelectOptions(referenced_el.asNode(), frame, arena);}diff --git a/src/browser/EventManager.zig b/src/browser/EventManager.zigindex 78dbe0563..0738330e1 100644--- a/src/browser/EventManager.zig+++ b/src/browser/EventManager.zig@@ -758,7 +758,7 @@ const ActivationState = struct {// For radio buttons, find the currently checked radio in the groupif (input._input_type == .radio and !old_checked) {- previously_checked_radio = try findCheckedRadioInGroup(input, frame);+ previously_checked_radio = try findCheckedRadioInGroup(input);}// Toggle checkbox or check radio (which unchecks others in group)@@ -802,7 +802,7 @@ const ActivationState = struct {}}- fn findCheckedRadioInGroup(input: *Input, frame: *Frame) !?*Input {+ fn findCheckedRadioInGroup(input: *Input) !?*Input {const elem = input.asElement();const name = elem.getName() orelse return null;@@ -810,7 +810,7 @@ const ActivationState = struct {return null;}- const form = input.getForm(frame);+ const form = input.getForm();// Walk from the root of the tree containing this element// This handles both document-attached and orphaned elements@@ -838,7 +838,7 @@ const ActivationState = struct {}// Check if same form context- const other_form = other_input.getForm(frame);+ const other_form = other_input.getForm();if (form) |f| {const of = other_form orelse continue;if (f != of) {diff --git a/src/browser/Frame.zig b/src/browser/Frame.zigindex 4c3c846b1..b3afa60da 100644--- a/src/browser/Frame.zig+++ b/src/browser/Frame.zig@@ -35,6 +35,7 @@ const h5e = @import("parser/html5ever.zig");const CustomElementReactions = @import("CustomElementReactions.zig");const URL = @import("URL.zig");+const IdMap = @import("IdMap.zig");const css_charset = @import("css/charset.zig");const referrer = @import("referrer.zig");const Blob = @import("webapi/Blob.zig");@@ -2511,36 +2512,24 @@ pub fn styleChanged(self: *Frame) void {self.page.style_version += 1;}-const ElementIdMaps = struct { lookup: *std.StringHashMapUnmanaged(*Element), removed_ids: *std.StringHashMapUnmanaged(void) };--fn getElementIdMap(frame: *Frame, node: *Node) ElementIdMaps {- return idMapsForRoot(node.getRootNode(.{})) orelse {+fn getIdMap(frame: *Frame, node: *Node) *IdMap {+ return idMapForRoot(node.getRootNode(.{})) orelse {// Detached nodes should not have IDs registeredif (lp.IS_DEBUG) {std.debug.assert(false);}- return .{- .lookup = &frame.document._elements_by_id,- .removed_ids = &frame.document._removed_ids,- };+ return &frame.document._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 {+fn idMapForRoot(root: *Node) ?*IdMap {if (root.is(ShadowRoot)) |shadow_root| {- return .{- .lookup = &shadow_root._elements_by_id,- .removed_ids = &shadow_root._removed_ids,- };+ return &shadow_root._ids;}if (root._type == .document) {- const doc = root.subtype(Document);- return .{- .lookup = &doc._elements_by_id,- .removed_ids = &doc._removed_ids,- };+ return &root.subtype(Document)._ids;}return null;}@@ -2556,50 +2545,31 @@ fn rootIsConnected(root: *Node) bool {}pub fn addElementId(self: *Frame, parent: *Node, element: *Element, id: []const u8) !void {- 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.page_arena, id);- if (!gop.found_existing) {- gop.value_ptr.* = element;- return;- }-- const existing = gop.value_ptr.*.asNode();- switch (element.asNode().compareDocumentPosition(existing)) {- 0x04 => gop.value_ptr.* = element,- else => {},- }+ return self.getIdMap(parent).add(self.page_arena, element, id);}pub fn removeElementId(self: *Frame, element: *Element, id: []const u8) void {- const node = element.asNode();- self.removeElementIdWithMaps(self.getElementIdMap(node), id);+ self.getIdMap(element.asNode()).remove(element, id);}-pub fn removeElementIdWithMaps(self: *Frame, id_maps: ElementIdMaps, id: []const u8) void {- if (id_maps.lookup.remove(id)) {- const gop = id_maps.removed_ids.getOrPut(self.page_arena, id) catch |err| {- log.warn(.frame, "removeElementIdWithMaps", .{ .err = err });- return;- };- if (gop.found_existing == false) {- gop.key_ptr.* = self.dupeString(id) catch return;- gop.value_ptr.* = {};- }- }+// The element with `id` in `node`'s tree scope, when only one element there+// has it. That element is then the only possible match below any search root,+// which is what the selector and XPath id fast paths need.+pub fn getUniqueElementByIdFromNode(node: *Node, id: []const u8) IdMap.Unique {+ const root = node.getRootNode(.{});+ const map = idMapForRoot(root) orelse return .many;+ return map.getUnique(root, id);}-pub fn getElementByIdFromNode(self: *Frame, node: *Node, id: []const u8) ?*Element {+pub fn getElementByIdFromNode(node: *Node, id: []const u8) ?*Element {// The id map lives on the node's root: a Document, or a ShadowRoot for// shadow DOM. Walk to the root once and consult the matching map.const root = node.getRootNode(.{});if (root._type == .document) {- return root.subtype(Document).getElementById(id, self);+ return root.subtype(Document).getElementById(id);}if (root.is(ShadowRoot)) |shadow_root| {- return shadow_root.getElementById(id, self);+ return shadow_root.getElementById(id);}// Detached subtree (root is neither a Document nor a ShadowRoot): no id map// exists, so scan it.@@ -3056,7 +3026,7 @@ pub fn removeNode(self: *Frame, parent: *Node, child: *Node, opts: RemoveNodeOptconst old_root = child.getRootNode(.{});const was_connected = rootIsConnected(old_root);- const old_id_maps = idMapsForRoot(old_root);+ const old_id_map = idMapForRoot(old_root);child._parent = null;@@ -3083,15 +3053,18 @@ pub fn removeNode(self: *Frame, parent: *Node, child: *Node, opts: RemoveNodeOptif (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)+ // Reconnected under the same root: its ids stay registered, but+ // the move can reorder duplicates.+ if (old_id_map) |id_map| {+ id_map.moved(child);+ }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);+ if (old_id_map) |id_map| {+ unregisterSubtreeIds(child, id_map);}// but it isn't a REAL disconnect (more like a move), so there's// nothing else to do, e.g. no disconnectedCallback@@ -3103,8 +3076,8 @@ pub fn removeNode(self: *Frame, parent: *Node, child: *Node, opts: RemoveNodeOptif (was_connected == false) {// 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);+ if (old_id_map) |id_map| {+ unregisterSubtreeIds(child, id_map);}// and because it wasn't disconnected, there's nothing else to do.return;@@ -3125,7 +3098,7 @@ pub fn removeNode(self: *Frame, parent: *Node, child: *Node, opts: RemoveNodeOptvar tw = TreeWalker.Full.Elements.init(child, .{});while (tw.next()) |el| {if (el.getId()) |id| {- self.removeElementIdWithMaps(old_id_maps.?, id);+ old_id_map.?.remove(el, id);}Element.Html.Custom.enqueueDisconnectedCallbackOnElement(el, self);@@ -3180,11 +3153,11 @@ fn removeStyleSheet(owner: ?*Frame, sheet: *CSSStyleSheet) void {// 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 {+fn unregisterSubtreeIds(node: *Node, id_map: *IdMap) void {var tw = TreeWalker.Full.Elements.init(node, .{});while (tw.next()) |el| {if (el.getId()) |id| {- self.removeElementIdWithMaps(id_maps, id);+ id_map.remove(el, id);}}}@@ -3371,9 +3344,20 @@ fn _insertNodeRelative(self: *Frame, comptime from_parser: bool, parent: *Node,if (child.is(Element)) |el| {const root = opts.parser_root orelse parent.getRootNode(.{});- if (idMapsForRoot(root)) |id_maps| {- if (el.getId()) |id| {- try self.addElementIdWithMaps(id_maps, el, id);+ if (idMapForRoot(root)) |id_map| {+ if (child.firstChild() == null) {+ if (el.getId()) |id| {+ try id_map.add(self.page_arena, el, id);+ }+ } else {+ // The adoption agency inserts a fresh element holding+ // children it took out of the tree: their ids come back.+ var tw = TreeWalker.Full.Elements.init(child, .{});+ while (tw.next()) |sub| {+ if (sub.getId()) |id| {+ try id_map.add(self.page_arena, sub, id);+ }+ }}if (rootIsConnected(root)) {// Build.connected, parser side (JS side is in nodeIsReady).@@ -3416,7 +3400,7 @@ fn _insertNodeRelative(self: *Frame, comptime from_parser: bool, parent: *Node,}// nothing to register, and nothing can become connected.- const new_id_maps = idMapsForRoot(parent_root) orelse {+ const new_id_map = idMapForRoot(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;@@ -3435,7 +3419,7 @@ fn _insertNodeRelative(self: *Frame, comptime from_parser: bool, parent: *Node,var tw = TreeWalker.Full.Elements.init(child, .{});while (tw.next()) |el| {if (el.getId()) |id| {- try self.addElementIdWithMaps(new_id_maps, el, id);+ try new_id_map.add(self.page_arena, el, id);}}// but beause it was and stays connected, we don't trigger@@ -3455,7 +3439,7 @@ fn _insertNodeRelative(self: *Frame, comptime from_parser: bool, parent: *Node,var tw = TreeWalker.Full.Elements.init(child, .{});while (tw.next()) |el| {if (el.getId()) |id| {- try self.addElementIdWithMaps(new_id_maps, el, id);+ try new_id_map.add(self.page_arena, el, id);}if (should_invoke_connected) {@@ -4540,7 +4524,7 @@ test "Frame: an onload handler does not dispatch load to other elements" {try testing.expectString("attr;prop;", (try frame.getTitle()).?);try testing.expectEqual(false, frame._event_manager.has_dom_load_listener);- const none = frame.document.getElementById("none", frame).?;+ const none = frame.document.getElementById("none").?;try testing.expectEqual(false, frame._event_manager.hasHandler(none.asEventTarget(), "load"));}diff --git a/src/browser/IdMap.zig b/src/browser/IdMap.zignew file mode 100644index 000000000..9f9c927b7--- /dev/null+++ b/src/browser/IdMap.zig@@ -0,0 +1,159 @@+// Copyright (C) 2023-2026 Lightpanda (Selecy SAS)+//+// Francis Bouvier <[email protected]>+// Pierre Tachoire <[email protected]>+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as+// published by the Free Software Foundation, either version 3 of the+// License, or (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++const std = @import("std");+const lp = @import("lightpanda");++const Node = @import("webapi/Node.zig");+const Element = @import("webapi/Element.zig");+const TreeWalker = @import("webapi/TreeWalker.zig");++const Allocator = std.mem.Allocator;++// The ids of one tree scope (a Document or a ShadowRoot).+const IdMap = @This();++// key is the element's attribute name, which lives in page.arena+_lookup: std.StringHashMapUnmanaged(Entry) = .empty,++// number of ids carried by more than 1 element+_duplicated: u32 = 0,++const Entry = struct {+ // ids aren't necessarily unique, and that impacts querySelectorAll and what+ // happens when a duplicate is added or removed from the tree+ count: u32,++ // first element (in tree order) with the id. null means it needs to be+ // recomputed (the first was removed, or duplicates were moved), which+ // get() does lazily, if ever requested+ first: ?*Element,+};++pub fn add(self: *IdMap, allocator: Allocator, element: *Element, id: []const u8) !void {+ const gop = try self._lookup.getOrPut(allocator, id);+ if (gop.found_existing == false) {+ gop.value_ptr.* = .{ .count = 1, .first = element };+ return;+ }++ const entry = gop.value_ptr;+ entry.count += 1;+ if (entry.count == 2) {+ self._duplicated += 1;+ }+ const first = entry.first orelse return;+ if (element.asNode().compareDocumentPosition(first.asNode()) & 0x04 != 0) {+ // new element comes before our first and thus becomes the new first+ entry.first = element;+ }+}++pub fn remove(self: *IdMap, element: *Element, id: []const u8) void {+ const kv = self._lookup.getEntry(id) orelse {+ if (comptime lp.IS_DEBUG) {+ // every remove should have a corresponding add+ std.debug.assert(false);+ }+ return;+ };++ const entry = kv.value_ptr;+ if (entry.count == 1) {+ self._lookup.removeByPtr(kv.key_ptr);+ return;+ }+ if (entry.count == 2) {+ self._duplicated -= 1;+ }+ entry.count -= 1;+ if (entry.first == element) {+ entry.first = null;+ }+}++// The subtree moved to another position within the same scope. The ids are+// still in this scope, but things could be re-ordered and `first` could change.+pub fn moved(self: *IdMap, subtree: *Node) void {+ if (self._duplicated == 0) {+ // fast-path, we have no duplicates, moving things around can't change+ // which is first+ return;+ }+ var tw = TreeWalker.Full.Elements.init(subtree, .{});+ while (tw.next()) |el| {+ const id = el.getId() orelse continue;+ const entry = self._lookup.getPtr(id) orelse continue;+ if (entry.count > 1) {+ // it may or may not still be first, but setting it as null is simplest+ // and signals for a lazy-resolution. This is the most efficient+ // option: we could do it now, but if we delay we might never have+ // to do it (or things might change again which will just invalidate+ // anything we do now)+ entry.first = null;+ }+ }+}++pub fn clear(self: *IdMap, allocator: Allocator) void {+ self._lookup.clearAndFree(allocator);+ self._duplicated = 0;+}++// first element with this id (in tree-order). `scope` is the Document or+// ShadowRoot that owns self.+pub fn get(self: *IdMap, scope: *Node, id: []const u8) ?*Element {+ const entry = self._lookup.getPtr(id) orelse return null;+ if (entry.first) |first| {+ return first;+ }+ return getInTree(entry, scope, id);+}++pub const Unique = union(enum) {+ none,+ one: *Element,+ many,+};++pub fn getUnique(self: *IdMap, scope: *Node, id: []const u8) Unique {+ const entry = self._lookup.getPtr(id) orelse return .none;+ if (entry.count > 1) {+ return .many;+ }+ const el = entry.first orelse getInTree(entry, scope, id) orelse return .none;+ return .{ .one = el };+}++fn getInTree(entry: *Entry, scope: *Node, id: []const u8) ?*Element {+ var tw = TreeWalker.Full.Elements.init(scope, .{});+ while (tw.next()) |el| {+ const element_id = el.getId() orelse continue;+ if (std.mem.eql(u8, element_id, id)) {+ entry.first = el;+ return el;+ }+ }++ if (comptime lp.IS_DEBUG) {+ // there *was* an entry for this id in _lookup, if we didn't find it+ // in the tree (the walk above), we haven't kept _lookup in sync correctly+ std.debug.assert(false);+ }+ return null;+}diff --git a/src/browser/frame/user_input.zig b/src/browser/frame/user_input.zigindex 4bce6647d..b0427d210 100644--- a/src/browser/frame/user_input.zig+++ b/src/browser/frame/user_input.zig@@ -1315,13 +1315,13 @@ pub fn handleClick(frame: *Frame, target: *Node, event_target: *Node) !void {if (element.isDisabled()) {return;}- return frame.submitForm(element, input.getForm(frame), .{});+ return frame.submitForm(element, input.getForm(), .{});}if (input._input_type == .reset) {if (element.isDisabled()) {return;}- const form = input.getForm(frame) orelse return;+ const form = input.getForm() orelse return;return form.reset(frame);}},@@ -1331,13 +1331,13 @@ pub fn handleClick(frame: *Frame, target: *Node, event_target: *Node) !void {if (element.isDisabled()) {return;}- return frame.submitForm(element, button.getForm(frame), .{});+ return frame.submitForm(element, button.getForm(), .{});}if (std.mem.eql(u8, button.getType(), "reset")) {if (element.isDisabled()) {return;}- const form = button.getForm(frame) orelse return;+ const form = button.getForm() orelse return;return form.reset(frame);}},@@ -1346,7 +1346,7 @@ pub fn handleClick(frame: *Frame, target: *Node, event_target: *Node) !void {// Per HTML §4.10.4 "The label element", a label's activation// behavior is to run the synthetic click activation steps on the// labeled control. Mirrors Chrome's HTMLLabelElement::DefaultEventHandler.- const control = label.getControl(frame) orelse return;+ const control = label.getControl() orelse return;if (control.asNode().contains(event_target)) {// label is the only control that synthesizes another click, so// we need to guard against that activation re-triggering the@@ -1519,7 +1519,7 @@ pub fn typeChar(frame: *Frame, target: *Element, keypress: *KeyboardEvent, text:/// form submits itself (SubmitEvent.submitter is null)./// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#implicit-submissionfn implicitFormSubmission(frame: *Frame, input: *Element.Html.Input) !void {- const form = input.getForm(frame) orelse return;+ const form = input.getForm() orelse return;if (form.getDefaultButton(frame)) |button| {if (button.isDisabled()) {return;@@ -1975,7 +1975,7 @@ test "user_input: mouse hit testing descends nested iframe viewports" {const main = page.frame().?;const child = main.child_frames.items[0];const nested = child.child_frames.items[0];- const target = nested.document.getElementById("inner", nested).?;+ const target = nested.document.getElementById("inner").?;const rect = target.boundingClientRectValues(nested);const child_rect = child.iframe.?.asElement().boundingClientRectValues(main);const nested_rect = nested.iframe.?.asElement().boundingClientRectValues(child);@@ -2012,8 +2012,8 @@ test "user_input: mouse release in another document does not click" {const main = page.frame().?;const child = main.child_frames.items[0];const nested = child.child_frames.items[0];- const inner = nested.document.getElementById("inner", nested).?;- const outer = main.document.getElementById("outer", main).?;+ const inner = nested.document.getElementById("inner").?;+ const outer = main.document.getElementById("outer").?;const inner_rect = inner.boundingClientRectValues(nested);const child_rect = child.iframe.?.asElement().boundingClientRectValues(main);const nested_rect = nested.iframe.?.asElement().boundingClientRectValues(child);@@ -2034,7 +2034,7 @@ test "user_input: a blank viewport point hovers the root; only leaving the viewpconst page = try testing.pageTest("input_mouse_frames.html", .{});defer page.close();const main = page.frame().?;- const outer = main.document.getElementById("outer", main).?;+ const outer = main.document.getElementById("outer").?;const rect = outer.boundingClientRectValues(main);const viewport = main.page.getViewport();const blank_y: f64 = @floatFromInt(viewport.height - 1);@@ -2071,7 +2071,7 @@ test "user_input: removing hit iframe in pointerdown stops its mouse sequence" {defer page.close();const main = page.frame().?;const child = main.child_frames.items[0];- const target = child.document.getElementById("middle", child).?;+ const target = child.document.getElementById("middle").?;const rect = target.boundingClientRectValues(child);const iframe_rect = child.iframe.?.asElement().boundingClientRectValues(main);var ls: js.Local.Scope = undefined;@@ -2187,7 +2187,7 @@ test "user_input: excluded child roots clear hover without releasing held buttonconst main = page.frame().?;const child = main.child_frames.items[0];const owner = if (from_child) child else main;- const target = owner.document.getElementById(if (from_child) "middle" else "outer", owner).?;+ const target = owner.document.getElementById(if (from_child) "middle" else "outer").?;const rect = target.boundingClientRectValues(owner);const iframe_rect = child.iframe.?.asElement().boundingClientRectValues(main);const x = rect.x + (if (from_child) iframe_rect.x else @as(f64, 0)) + 1;@@ -2232,8 +2232,8 @@ test "user_input: removing a pressed iframe between messages clears pointer statdefer page.close();const main = page.frame().?;const child = main.child_frames.items[0];- const target = child.document.getElementById("middle", child).?;- const outer = main.document.getElementById("outer", main).?;+ const target = child.document.getElementById("middle").?;+ const outer = main.document.getElementById("outer").?;const target_rect = target.boundingClientRectValues(child);const iframe_rect = child.iframe.?.asElement().boundingClientRectValues(main);const outer_rect = outer.boundingClientRectValues(main);@@ -2316,7 +2316,7 @@ test "user_input: wheel listener removing its iframe prevents the scroll default, null);}- const box = child.document.getElementById("wheelBox", child).?;+ const box = child.document.getElementById("wheelBox").?;const box_rect = box.boundingClientRectValues(child);const iframe_rect = child.iframe.?.asElement().boundingClientRectValues(main);const x = box_rect.x + iframe_rect.x + 1;@@ -2341,11 +2341,11 @@ test "user_input: mouse hover transitions cross nested iframe documents" {const child = main.child_frames.items[0];const nested = child.child_frames.items[0];- const outer = main.document.getElementById("outer", main).?;+ const outer = main.document.getElementById("outer").?;const child_iframe = child.iframe.?.asElement();- const middle = child.document.getElementById("middle", child).?;+ const middle = child.document.getElementById("middle").?;const nested_iframe = nested.iframe.?.asElement();- const inner = nested.document.getElementById("inner", nested).?;+ const inner = nested.document.getElementById("inner").?;const outer_rect = outer.boundingClientRectValues(main);const child_rect = child_iframe.boundingClientRectValues(main);const middle_rect = middle.boundingClientRectValues(child);@@ -2467,7 +2467,7 @@ test "user_input: mouse blank iframe takes document focus" {defer page.close();const main = page.frame().?;const child = main.child_frames.items[0];- const outer = main.document.getElementById("outer", main).?;+ const outer = main.document.getElementById("outer").?;var ls: js.Local.Scope = undefined;child.js.localScope(&ls);defer ls.deinit();@@ -2495,7 +2495,7 @@ test "user_input: mouse static nested iframe takes document focus" {nested.js.localScope(&ls);defer ls.deinit();_ = try ls.local.compileAndRun("document.body.innerHTML = '<div style=width:150px;height:150px>static</div>';", null);- try main.document.getElementById("outer", main).?.focus(main);+ try main.document.getElementById("outer").?.focus(main);const child_rect = child.iframe.?.asElement().boundingClientRectValues(main);const nested_rect = nested.iframe.?.asElement().boundingClientRectValues(child);const x = child_rect.x + nested_rect.x + 10;@@ -2513,7 +2513,7 @@ test "user_input: mouse blank iframe cancelled press preserves focus" {defer page.close();const main = page.frame().?;const child = main.child_frames.items[0];- const outer = main.document.getElementById("outer", main).?;+ const outer = main.document.getElementById("outer").?;var ls: js.Local.Scope = undefined;child.js.localScope(&ls);defer ls.deinit();@@ -2536,7 +2536,7 @@ test "user_input: mouse removed blank iframe does not take focus" {defer page.close();const main = page.frame().?;const child = main.child_frames.items[0];- const outer = main.document.getElementById("outer", main).?;+ const outer = main.document.getElementById("outer").?;var ls: js.Local.Scope = undefined;main.js.localScope(&ls);defer ls.deinit();@@ -2563,7 +2563,7 @@ test "user_input: mouse blank sibling iframe clears old focus chain" {const main = page.frame().?;const child = main.child_frames.items[0];const sibling = main.child_frames.items[1];- const middle = child.document.getElementById("middle", child).?;+ const middle = child.document.getElementById("middle").?;var ls: js.Local.Scope = undefined;main.js.localScope(&ls);defer ls.deinit();@@ -2591,7 +2591,7 @@ test "user_input: synthetic blank iframe click preserves focus" {const page = try testing.pageTest("input_mouse_frames.html", .{});defer page.close();const main = page.frame().?;- const outer = main.document.getElementById("outer", main).?;+ const outer = main.document.getElementById("outer").?;try outer.focus(main);var ls: js.Local.Scope = undefined;main.js.localScope(&ls);@@ -2608,7 +2608,7 @@ test "user_input: shadow mouse rects are viewport relative and native clicks reavar ls: js.Local.Scope = undefined;frame.js.localScope(&ls);defer ls.deinit();- const host = frame.document.getElementById("host", frame).?;+ const host = frame.document.getElementById("host").?;const inner = try ls.local.jsValueToZig(*Element, try ls.local.compileAndRun("inner", null));const host_rect = host.boundingClientRectValues(frame);const rect = inner.boundingClientRectValues(frame);@@ -2633,7 +2633,7 @@ test "user_input: shadow mouse hit testing respects bounds and hidden descendantvar ls: js.Local.Scope = undefined;frame.js.localScope(&ls);defer ls.deinit();- const host = frame.document.getElementById("host", frame).?;+ const host = frame.document.getElementById("host").?;const inner = try ls.local.jsValueToZig(*Element, try ls.local.compileAndRun("inner", null));const rect = inner.boundingClientRectValues(frame);try testing.expect((try mouseHitTest(frame, rect.x, rect.y)).target == inner);@@ -2667,7 +2667,7 @@ test "user_input: shadow mouse nested closed roots and window scroll share coord\\deep.addEventListener('click', e => { if (e.isTrusted && e.target === deep) deepClicks++; });\\deep;, null));- const host = frame.document.getElementById("host", frame).?;+ const host = frame.document.getElementById("host").?;const host_rect = host.boundingClientRectValues(frame);const before = target.boundingClientRectValues(frame);try testing.expectEqual(host_rect.x + 25, before.x);@@ -2723,7 +2723,7 @@ test "user_input: shadow mouse keeps host boundary path and common click target"\\boundaryHost.addEventListener('click', e => clicks.push({where:'host', target:e.target.id, trusted:e.isTrusted, inner:e.composedPath().includes(boundaryInner)}));\\boundaryInner;, null));- const host = frame.document.getElementById("boundaryHost", frame).?;+ const host = frame.document.getElementById("boundaryHost").?;const rect = inner.boundingClientRectValues(frame);const host_rect = host.boundingClientRectValues(frame);try triggerMouseMove(frame, rect.x + 1, rect.y + 1);@@ -2762,7 +2762,7 @@ test "user_input: shadow mouse wheel preserves outer scroll container" {\\inner;, null));const rect = inner.boundingClientRectValues(frame);- const scroller = frame.document.getElementById("scroller", frame).?;+ const scroller = frame.document.getElementById("scroller").?;try testing.expect(scroller.getScrollHeight(frame) > scroller.getClientHeight(frame));try triggerMouseWheel(frame, rect.x + 1, rect.y + 1, 0, 20);try testing.expectEqual(@as(u32, 20), scroller.getScrollTop(frame));diff --git a/src/browser/js/bridge.zig b/src/browser/js/bridge.zigindex da946210d..b612438f7 100644--- a/src/browser/js/bridge.zig+++ b/src/browser/js/bridge.zig@@ -733,7 +733,7 @@ pub fn unknownWindowPropertyCallback(c_name: ?*const v8.Name, handle: ?*const v8switch (local.ctx.global) {.frame => |frame| {const document = frame.document;- if (document.getElementById(property, frame)) |el| {+ if (document.getElementById(property)) |el| {const js_val = local.zigValueToJs(el, .{}) catch return js.Intercepted.no;var pc = Caller.PropertyCallbackInfo{ .handle = handle.? };pc.getReturnValue().set(js_val);diff --git a/src/browser/parser/Parser.zig b/src/browser/parser/Parser.zigindex 5faf7c536..23f0a0f6b 100644--- a/src/browser/parser/Parser.zig+++ b/src/browser/parser/Parser.zig@@ -690,6 +690,9 @@ fn _addAttrsIfMissingCallback(self: *Parser, node: *Node, attributes: h5e.Attribconst value = attr.value.slice();if (try attr_list.putNew(name, value, frame)) {// attribute didn't previously exist+ if (std.mem.eql(u8, name, "id") and node.isConnected()) {+ try frame.addElementId(node._parent.?, element, element.getId().?);+ }if (element.is(Element.Html)) |html| {try html.eventHandlerAttributeChanged(name, element.getAttributeSafe(.wrap(name)), frame);}diff --git a/src/browser/tests/element/duplicate_ids.html b/src/browser/tests/element/duplicate_ids.htmlindex 2e8b58948..339cd0d25 100644--- a/src/browser/tests/element/duplicate_ids.html+++ b/src/browser/tests/element/duplicate_ids.html@@ -13,9 +13,9 @@const second = document.getElementById('test');testing.expectEqual('second', second.textContent);- // second.remove();-- // testing.expectEqual(null, document.getElementById('test'));+ second.remove();+ testing.expectEqual(null, document.getElementById('test'));+ testing.expectEqual(null, document.querySelector('#test'));</script><div id="qs-test">first</div>@@ -23,10 +23,8 @@<script id=duplicateIdsQuerySelector>{- // Regression test: querySelector('#id') must agree with getElementById('id')- // when the first duplicate is removed. Selector engine fast path goes through- // Frame.getElementByIdFromNode, which previously only checked the lookup map- // and missed the _removed_ids recovery, so it returned null.+ // querySelector('#id') must agree with getElementById('id') when the+ // first duplicate is removed.const first = document.querySelector('#qs-test');testing.expectEqual('first', first.textContent);@@ -38,3 +36,135 @@testing.expectEqual('second', document.getElementById('qs-test').textContent);}</script>++<!-- adds an id to the existing body -->+<body id="late-body">++<script>+ function texts(list) {+ return Array.from(list).map((e) => e.textContent).join(',');+ }+</script>++<script id=parserBodyId>+{+ testing.expectEqual(document.body, document.getElementById('late-body'));+ testing.expectEqual(document.body, document.querySelector('#late-body'));+ document.body.removeAttribute('id');+ testing.expectEqual(null, document.getElementById('late-body'));+}+</script>++<div id="flow-one"><div id="dup">one</div></div>+<div id="flow-two"><div id="dup">two</div></div>++<script id=duplicateIdsScoped>+{+ const one = document.getElementById('flow-one');+ const two = document.getElementById('flow-two');+ testing.expectEqual('one', one.querySelector('#dup').textContent);+ testing.expectEqual('two', two.querySelector('#dup').textContent);+ testing.expectEqual('one,two', texts(document.querySelectorAll('#dup')));+ testing.expectEqual('two', texts(two.querySelectorAll('#dup')));+ testing.expectEqual('two', texts(two.querySelectorAll('div#dup')));+ testing.expectEqual(2, document.evaluate('//*[@id="dup"]', document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE).snapshotLength);++ // the root never matches itself+ const first = one.firstChild;+ testing.expectEqual(null, first.querySelector('#dup'));++ // id-anchored descendant selectors under a later duplicate+ const p = document.createElement('p');+ p.textContent = 'p-two';+ two.firstChild.appendChild(p);+ testing.expectEqual('p-two', texts(document.querySelectorAll('#dup p')));+ testing.expectEqual('p-two', document.querySelector('#dup p').textContent);+ p.remove();++ // a duplicate goes away: back to unique+ first.id = 'not-dup';+ testing.expectEqual('two', document.querySelector('#dup').textContent);+ testing.expectEqual('two', texts(document.querySelectorAll('#dup')));+ testing.expectEqual(null, one.querySelector('#dup'));+ first.id = 'dup';+ testing.expectEqual('one', document.getElementById('dup').textContent);+}+</script>++<div id="move-root"><div id="move-a"><span id="mv">A</span></div><div id="move-b"><span id="mv">B</span></div></div>++<script id=duplicateIdsMoved>+{+ // moving the first duplicate after the second, inside the document+ const root = document.getElementById('move-root');+ testing.expectEqual('A', document.getElementById('mv').textContent);+ root.appendChild(document.getElementById('move-a'));+ testing.expectEqual('B', document.getElementById('mv').textContent);+ testing.expectEqual('B', document.querySelector('#mv').textContent);+ testing.expectEqual('B', root.querySelector('#mv').textContent);+ testing.expectEqual('B,A', texts(document.querySelectorAll('#mv')));++ // and back, through moveBefore+ root.moveBefore(document.getElementById('move-a'), document.getElementById('move-b'));+ testing.expectEqual('A', document.getElementById('mv').textContent);+ testing.expectEqual('A', document.querySelector('#mv').textContent);+}+</script>++<div id="outer"><section id="inner"><p>p1</p></section></div>++<script id=idAnchorAboveRoot>+{+ // the anchor is an ancestor of the queried root+ const inner = document.getElementById('inner');+ testing.expectEqual('p1', inner.querySelector('#outer p').textContent);+ testing.expectEqual('p1', texts(inner.querySelectorAll('#outer p')));+ testing.expectEqual('p1', texts(inner.querySelectorAll('#inner p')));+ testing.expectEqual(null, inner.querySelector('#inner'));++ // the id is the subject, but its element isn't below the root+ testing.expectEqual(0, inner.querySelectorAll('#inner').length);+ testing.expectEqual(0, inner.querySelectorAll('#outer').length);+ testing.expectEqual(0, inner.querySelectorAll('div > #outer').length);+ testing.expectEqual(0, document.getElementById('flow-two').querySelectorAll('#outer').length);+ testing.expectEqual(null, inner.querySelector('body #outer'));+}+</script>++<div id="shadow-host"></div>++<script id=duplicateIdsShadow>+{+ const shadow = document.getElementById('shadow-host').attachShadow({ mode: 'open' });+ shadow.innerHTML = '<div id="s1"><b id="sd">x</b></div><div id="s2"><b id="sd">y</b></div>';+ testing.expectEqual('x', shadow.getElementById('sd').textContent);+ testing.expectEqual('y', shadow.getElementById('s2').querySelector('#sd').textContent);+ testing.expectEqual('x,y', texts(shadow.querySelectorAll('#sd')));+ shadow.getElementById('s1').remove();+ testing.expectEqual('y', shadow.getElementById('sd').textContent);+ testing.expectEqual('y', texts(shadow.querySelectorAll('#sd')));++ // moving out of the shadow root and into the document+ const b = shadow.getElementById('sd');+ document.body.appendChild(b);+ testing.expectEqual(null, shadow.getElementById('sd'));+ testing.expectEqual(b, document.getElementById('sd'));+ b.remove();+ testing.expectEqual(null, document.getElementById('sd'));+}+</script>++<!-- misnested: the adoption agency moves #aaa under a fresh <b> -->+<div id="aaa-root"><b><p><i id="aaa">aaa</i></b></p></div>++<script id=adoptionAgencyIds>+{+ const i = document.getElementById('aaa');+ testing.expectEqual('aaa', i.textContent);+ testing.expectEqual(i, document.querySelector('#aaa'));+ testing.expectEqual(i, document.getElementById('aaa-root').querySelector('#aaa'));+ i.remove();+ testing.expectEqual(null, document.getElementById('aaa'));+ testing.expectEqual(null, document.querySelector('#aaa'));+}+</script>diff --git a/src/browser/webapi/Document.zig b/src/browser/webapi/Document.zigindex 7a7dc0dca..f5945cd42 100644--- a/src/browser/webapi/Document.zig+++ b/src/browser/webapi/Document.zig@@ -24,6 +24,7 @@ const public_suffix_list = @import("../../data/public_suffix_list.zig");const EventTarget = @import("EventTarget.zig");const URL = @import("../URL.zig");+const IdMap = @import("../IdMap.zig");const js = @import("../js/js.zig");const Page = @import("../Page.zig");const Frame = @import("../Frame.zig");@@ -79,9 +80,7 @@ _navigated_away: bool = false,_iframe_load_in_progress: bool = false,_mute_iframe_load: bool = false,_current_script: ?*Element.Html.Script = null,-_elements_by_id: std.StringHashMapUnmanaged(*Element) = .empty,-// Track IDs that were removed from the map - they might have duplicates in the tree-_removed_ids: std.StringHashMapUnmanaged(void) = .empty,+_ids: IdMap = .{},_active_element: ?*Element = null,_style_sheets: ?*StyleSheetList = null,_implementation: ?*DOMImplementation = null,@@ -427,32 +426,11 @@ pub fn createAttributeNS(self: *const Document, namespace: []const u8, name: Str});}-pub fn getElementById(self: *Document, id: []const u8, frame: *Frame) ?*Element {+pub fn getElementById(self: *Document, id: []const u8) ?*Element {if (id.len == 0) {return null;}-- if (self._elements_by_id.get(id)) |element| {- return element;- }-- //ID was removed but might have duplicates- if (self._removed_ids.remove(id)) {- var tw = TreeWalker.Full.Elements.init(self.asNode(), .{});- while (tw.next()) |el| {- const element_id = el.getId() orelse continue;- if (std.mem.eql(u8, element_id, id)) {- // we ignore this error to keep getElementById easy to call- // if it really failed, then we're out of memory and nothing's- // going to work like it should anyways.- const owned_id = frame.dupeString(id) catch return null;- self._elements_by_id.put(frame.page_arena, owned_id, el) catch return null;- return el;- }- }- }-- return null;+ return self._ids.get(self.asNode(), id);}pub fn getElementsByTagName(self: *Document, tag_name: []const u8, frame: *Frame) !Node.GetElementsByTagNameResult {@@ -1285,7 +1263,7 @@ pub fn open(self: *Document, call_frame: *Frame) !*Document {}// reset the document- self._elements_by_id.clearAndFree(frame.page_arena);+ self._ids.clear(frame.page_arena);self.setActiveElement(null, frame);self._open_popovers = .empty;self._modal_dialogs = .empty;@@ -1826,15 +1804,15 @@ pub const JsApi = struct {pub const createExpression = bridge.function(Document.createExpression, .{});pub const createNSResolver = bridge.function(Document.createNSResolver, .{});pub const getElementById = bridge.function(_getElementById, .{});- fn _getElementById(self: *Document, value_: ?js.Value, frame: *Frame) !?*Element {+ fn _getElementById(self: *Document, value_: ?js.Value) !?*Element {const value = value_ orelse return null;if (value.isNull()) {- return self.getElementById("null", frame);+ return self.getElementById("null");}if (value.isUndefined()) {- return self.getElementById("undefined", frame);+ return self.getElementById("undefined");}- return self.getElementById(try value.toZig([]const u8), frame);+ return self.getElementById(try value.toZig([]const u8));}pub const querySelector = bridge.function(Document.querySelector, .{});pub const querySelectorAll = bridge.function(Document.querySelectorAll, .{});diff --git a/src/browser/webapi/ElementInternals.zig b/src/browser/webapi/ElementInternals.zigindex dfed35e55..fbbebc7da 100644--- a/src/browser/webapi/ElementInternals.zig+++ b/src/browser/webapi/ElementInternals.zig@@ -196,9 +196,9 @@ fn replaceFiles(self: *ElementInternals, files: []const *File, frame: *Frame) !vfl._files = dupe;}-fn getForm(self: *const ElementInternals, frame: *Frame) !?*Form {+fn getForm(self: *const ElementInternals) !?*Form {try self.assertFormAssociated();- return Form.ownerOf(self.asElement(), frame);+ return Form.ownerOf(self.asElement());}fn getLabels(self: *const ElementInternals, frame: *Frame) !js.Array {diff --git a/src/browser/webapi/ShadowRoot.zig b/src/browser/webapi/ShadowRoot.zigindex a28ec6d69..348dff903 100644--- a/src/browser/webapi/ShadowRoot.zig+++ b/src/browser/webapi/ShadowRoot.zig@@ -22,6 +22,7 @@ const js = @import("../js/js.zig");const dump = @import("../dump.zig");const EventTarget = @import("EventTarget.zig");const Frame = @import("../Frame.zig");+const IdMap = @import("../IdMap.zig");const Node = @import("Node.zig");const Element = @import("Element.zig");@@ -60,8 +61,7 @@ _clonable: bool,_serializable: bool,_declarative: bool,_available_to_internals: bool = false,-_elements_by_id: std.StringHashMapUnmanaged(*Element) = .{},-_removed_ids: std.StringHashMapUnmanaged(void) = .{},+_ids: IdMap = .{},_adopted_style_sheets: ?js.Object.Global = null,pub fn init(host: *Element, opts: AttachOptions, frame: *Frame) !*ShadowRoot {@@ -142,34 +142,11 @@ pub fn getActiveElement(self: *ShadowRoot, frame: *Frame) ?*Element {return candidate;}-pub fn getElementById(self: *ShadowRoot, id: []const u8, frame: *Frame) ?*Element {+pub fn getElementById(self: *ShadowRoot, id: []const u8) ?*Element {if (id.len == 0) {return null;}-- // Fast path: ID is in the map- if (self._elements_by_id.get(id)) |element| {- return element;- }-- // Slow path: ID was removed but might have duplicates- if (self._removed_ids.remove(id)) {- // Do a tree walk to find another element with this ID- var tw = @import("TreeWalker.zig").Full.Elements.init(self.asNode(), .{});- while (tw.next()) |el| {- const element_id = el.getId() orelse continue;- if (std.mem.eql(u8, element_id, id)) {- // we ignore this error to keep getElementById easy to call- // if it really failed, then we're out of memory and nothing's- // going to work like it should anyways.- const owned_id = frame.dupeString(id) catch return null;- self._elements_by_id.put(frame.page_arena, owned_id, el) catch return null;- return el;- }- }- }-- return null;+ return self._ids.get(self.asNode(), id);}fn getAdoptedStyleSheets(self: *ShadowRoot, frame: *Frame) !js.Object.Global {@@ -202,15 +179,15 @@ pub const JsApi = struct {pub const clonable = bridge.accessor(ShadowRoot.getClonable, null, .{});pub const serializable = bridge.accessor(ShadowRoot.getSerializable, null, .{});pub const getElementById = bridge.function(_getElementById, .{});- fn _getElementById(self: *ShadowRoot, value_: ?js.Value, frame: *Frame) !?*Element {+ fn _getElementById(self: *ShadowRoot, value_: ?js.Value) !?*Element {const value = value_ orelse return null;if (value.isNull()) {- return self.getElementById("null", frame);+ return self.getElementById("null");}if (value.isUndefined()) {- return self.getElementById("undefined", frame);+ return self.getElementById("undefined");}- return self.getElementById(try value.toZig([]const u8), frame);+ return self.getElementById(try value.toZig([]const u8));}pub const adoptedStyleSheets = bridge.accessor(ShadowRoot.getAdoptedStyleSheets, ShadowRoot.setAdoptedStyleSheets, .{});pub const setHTML = bridge.function(ShadowRoot.setHTML, .{ .ce_reactions = true });diff --git a/src/browser/webapi/collections/HTMLAllCollection.zig b/src/browser/webapi/collections/HTMLAllCollection.zigindex 8872fad06..f84d21650 100644--- a/src/browser/webapi/collections/HTMLAllCollection.zig+++ b/src/browser/webapi/collections/HTMLAllCollection.zig@@ -44,8 +44,8 @@ pub fn getAtIndex(self: *HTMLAllCollection, index: usize, frame: *const Frame) ?return self._nodes.getAtIndex(index, frame);}-pub fn getByName(self: *HTMLAllCollection, name: []const u8, frame: *Frame) ?*Element {- if (frame.getElementByIdFromNode(self._nodes._tw._root, name)) |el| {+pub fn getByName(self: *HTMLAllCollection, name: []const u8) ?*Element {+ if (Frame.getElementByIdFromNode(self._nodes._tw._root, name)) |el| {return el;}@@ -88,7 +88,7 @@ const CAllAsFunctionArg = union(enum) {pub fn callable(self: *HTMLAllCollection, arg: CAllAsFunctionArg, frame: *Frame) ?*Element {return switch (arg) {.index => |i| self.getAtIndex(i, frame),- .id => |id| self.getByName(id, frame),+ .id => |id| self.getByName(id),};}@@ -125,8 +125,8 @@ pub const JsApi = struct {pub const length = bridge.accessor(HTMLAllCollection.length, null, .{});pub const @"[int]" = bridge.indexed(HTMLAllCollection.getAtIndex, null, .{ .null_as_undefined = true });pub const @"[str]" = bridge.namedIndexed(HTMLAllCollection.getByName, null, null, null, struct {- fn wrap(self: *HTMLAllCollection, name: []const u8, frame: *Frame) !u32 {- if (self.getByName(name, frame) != null) {+ fn wrap(self: *HTMLAllCollection, name: []const u8) !u32 {+ if (self.getByName(name) != null) {// Named properties are [LegacyUnenumerableNamedProperties]return js.v8.DontEnum;}diff --git a/src/browser/webapi/collections/HTMLCollection.zig b/src/browser/webapi/collections/HTMLCollection.zigindex 494cc7684..e0accf402 100644--- a/src/browser/webapi/collections/HTMLCollection.zig+++ b/src/browser/webapi/collections/HTMLCollection.zig@@ -111,14 +111,14 @@ pub fn getAtIndex(self: *HTMLCollection, index: usize, frame: *const Frame) ?*El};}-pub fn getByName(self: *HTMLCollection, name: []const u8, frame: *Frame) ?*Element {+pub fn getByName(self: *HTMLCollection, name: []const u8) ?*Element {if (name.len == 0) {return null;}return switch (self._data) {.empty => null,- inline else => |*impl| impl.getByName(name, frame),+ inline else => |*impl| impl.getByName(name),};}@@ -209,20 +209,20 @@ pub const JsApi = struct {pub const length = bridge.accessor(HTMLCollection.length, null, .{});pub const @"[int]" = bridge.indexedFull(HTMLCollection.getAtIndex, setAtIndex, deleteAtIndex, queryAtIndex, defineAtIndex, getIndexes, .{ .null_as_undefined = true });pub const @"[str]" = bridge.namedIndexedFull(struct {- pub fn wrap(self: *HTMLCollection, name: []const u8, frame: *Frame) !?*Element {+ pub fn wrap(self: *HTMLCollection, name: []const u8) !?*Element {if (name.len == 0) {return error.NotHandled;}- return self.getByName(name, frame) orelse error.NotHandled;+ return self.getByName(name) orelse error.NotHandled;}}.wrap, null, deleteByName, getNames, queryByName, defineByName, describeByName, .{ .null_as_undefined = true });// Named properties are [LegacyUnenumerableNamedProperties]: the query// reports them non-enumerable, so for-in skips them while// Object.getOwnPropertyNames still lists them via the enumerator.- fn queryByName(self: *HTMLCollection, name: []const u8, frame: *Frame) !u32 {- if (name.len > 0 and self.getByName(name, frame) != null) {+ fn queryByName(self: *HTMLCollection, name: []const u8) !u32 {+ if (name.len > 0 and self.getByName(name) != null) {return js.v8.DontEnum;}return error.NotHandled;@@ -252,8 +252,8 @@ pub const JsApi = struct {// ordinary [[Set]] which ends up in defineByName, while an assignment// through a derived object (the collection as prototype) must ignore the// named property entirely and create an expando on the receiver.- fn defineByName(self: *HTMLCollection, name: []const u8, frame: *Frame) !bool {- if (name.len > 0 and self.getByName(name, frame) != null) {+ fn defineByName(self: *HTMLCollection, name: []const u8) !bool {+ if (name.len > 0 and self.getByName(name) != null) {return false;}return error.NotHandled;@@ -261,9 +261,9 @@ pub const JsApi = struct {// Named properties are [LegacyUnenumerableNamedProperties]: not// enumerable, configurable, read-only.- fn describeByName(self: *HTMLCollection, name: []const u8, frame: *Frame) !Descriptor {+ fn describeByName(self: *HTMLCollection, name: []const u8) !Descriptor {if (name.len > 0) {- if (self.getByName(name, frame)) |element| {+ if (self.getByName(name)) |element| {return .{.value = element,.writable = false,@@ -339,8 +339,8 @@ pub const JsApi = struct {return error.NotHandled;}- fn deleteByName(self: *HTMLCollection, name: []const u8, frame: *Frame) !bool {- if (self.getByName(name, frame) != null) {+ fn deleteByName(self: *HTMLCollection, name: []const u8) !bool {+ if (self.getByName(name) != null) {return false;}return error.NotHandled;diff --git a/src/browser/webapi/collections/HTMLOptionsCollection.zig b/src/browser/webapi/collections/HTMLOptionsCollection.zigindex 9a1e16239..e0ac64259 100644--- a/src/browser/webapi/collections/HTMLOptionsCollection.zig+++ b/src/browser/webapi/collections/HTMLOptionsCollection.zig@@ -63,8 +63,8 @@ pub fn getAtIndex(self: *HTMLOptionsCollection, index: usize, frame: *Frame) ?*Ereturn self._proto.getAtIndex(index, frame);}-pub fn getByName(self: *HTMLOptionsCollection, name: []const u8, frame: *Frame) ?*Element {- return self._proto.getByName(name, frame);+pub fn getByName(self: *HTMLOptionsCollection, name: []const u8) ?*Element {+ return self._proto.getByName(name);}// Forward selectedIndex to the owning select element@@ -166,8 +166,8 @@ pub const JsApi = struct {// Indexed accesspub const @"[int]" = bridge.indexedReadWrite(HTMLOptionsCollection.getAtIndex, setAtIndex, null, null, null, .{ .null_as_undefined = true, .ce_reactions = true });pub const @"[str]" = bridge.namedIndexed(HTMLOptionsCollection.getByName, null, null, null, struct {- fn wrap(self: *HTMLOptionsCollection, name: []const u8, frame: *Frame) !u32 {- if (self.getByName(name, frame) != null) {+ fn wrap(self: *HTMLOptionsCollection, name: []const u8) !u32 {+ if (self.getByName(name) != null) {// Named properties are [LegacyUnenumerableNamedProperties]: the queryreturn js.v8.DontEnum;}diff --git a/src/browser/webapi/collections/node_live.zig b/src/browser/webapi/collections/node_live.zigindex a52af7fa1..519f90aba 100644--- a/src/browser/webapi/collections/node_live.zig+++ b/src/browser/webapi/collections/node_live.zig@@ -212,8 +212,8 @@ pub fn NodeLive(comptime mode: Mode) type {return null;}- pub fn getByName(self: *Self, name: []const u8, frame: *Frame) ?*Element {- if (frame.getElementByIdFromNode(self._tw._root, name)) |element| {+ pub fn getByName(self: *Self, name: []const u8) ?*Element {+ if (Frame.getElementByIdFromNode(self._tw._root, name)) |element| {const node = element.asNode();if (self._tw.contains(node) and self.matches(node)) {return element;diff --git a/src/browser/webapi/element/html/Button.zig b/src/browser/webapi/element/html/Button.zigindex 0d9fba198..1378c8d2b 100644--- a/src/browser/webapi/element/html/Button.zig+++ b/src/browser/webapi/element/html/Button.zig@@ -62,8 +62,8 @@ pub fn getType(self: *const Button) []const u8 {return "submit";}-pub fn getForm(self: *Button, frame: *Frame) ?*Form {- return Form.ownerOf(self.asElement(), frame);+pub fn getForm(self: *Button) ?*Form {+ return Form.ownerOf(self.asElement());}fn getLabels(self: *Button, frame: *Frame) !js.Array {@@ -166,8 +166,8 @@ pub fn hasCustomValidity(self: *const Button) bool {return self._custom_validity != null;}-fn getPopoverTargetElement(self: *Button, frame: *Frame) ?*Element {- return popover.invokerTarget(self.asNode(), self._popover_target, frame);+fn getPopoverTargetElement(self: *Button) ?*Element {+ return popover.invokerTarget(self.asNode(), self._popover_target);}fn setPopoverTargetElement(self: *Button, value: ?*Element, frame: *Frame) !void {diff --git a/src/browser/webapi/element/html/Custom.zig b/src/browser/webapi/element/html/Custom.zigindex 6571f4672..1ccb0baf8 100644--- a/src/browser/webapi/element/html/Custom.zig+++ b/src/browser/webapi/element/html/Custom.zig@@ -94,7 +94,7 @@ pub fn formStateChanged(self: *Custom, frame: *Frame) void {}const element = self.asElement();- const owner = Form.ownerOf(element, frame);+ const owner = Form.ownerOf(element);if (owner != self._form_owner) {// new ownerself._form_owner = owner;diff --git a/src/browser/webapi/element/html/Form.zig b/src/browser/webapi/element/html/Form.zigindex 084135ab5..463942038 100644--- a/src/browser/webapi/element/html/Form.zig+++ b/src/browser/webapi/element/html/Form.zig@@ -208,7 +208,7 @@ pub fn requestSubmit(self: *Form, submitter: ?*Element, frame: *Frame) !void {}// The submitter's form owner must be this form element.- const submitter_form = ownerOf(s, frame);+ const submitter_form = ownerOf(s);if (submitter_form == null or submitter_form.? != self) return error.NotFound;break :blk s;@@ -266,14 +266,14 @@ pub fn isSubmitButton(element: *Element) bool {}// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#form-owner-pub fn ownerOf(element: *Element, frame: *Frame) ?*Form {+pub fn ownerOf(element: *Element) ?*Form {// A form attribute is authoritative, even when it names nothing. It// resolves in the control's own tree (shadow root or document), not the// calling realm's.const element_node = element.asNode();if (element_node.isConnected()) {if (element.getAttributeSafe(comptime .wrap("form"))) |form_id| {- const form_element = frame.getElementByIdFromNode(element_node, form_id) orelse return null;+ const form_element = Frame.getElementByIdFromNode(element_node, form_id) orelse return null;return form_element.is(Form);}}diff --git a/src/browser/webapi/element/html/Input.zig b/src/browser/webapi/element/html/Input.zigindex c1a79c550..14c653ce2 100644--- a/src/browser/webapi/element/html/Input.zig+++ b/src/browser/webapi/element/html/Input.zig@@ -220,7 +220,7 @@ pub fn getChecked(self: *const Input) bool {pub fn setChecked(self: *Input, checked: bool, frame: *Frame) !void {// If checking a radio button, uncheck others in the group firstif (checked and self._input_type == .radio) {- self.uncheckRadioGroup(frame);+ self.uncheckRadioGroup();}// This should _not_ call setAttribute. It updates the current state onlyself._checked = checked;@@ -366,7 +366,7 @@ fn getValueForJS(self: *const Input, frame: *Frame) ![]const u8 {fn getValidationMessage(self: *Input, frame: *Frame) []const u8 {if (!self.getWillValidate()) return "";if (self._custom_validity) |msg| return msg;- if (self.suffersValueMissing(frame)) return "Please fill out this field.";+ if (self.suffersValueMissing()) return "Please fill out this field.";if (self.suffersTypeMismatch()) return switch (self._input_type) {.email => "Please enter an email address.",.url => "Please enter a URL.",@@ -401,12 +401,12 @@ pub fn hasCustomValidity(self: *const Input) bool {return self._custom_validity != null;}-pub fn suffersValueMissing(self: *Input, frame: *Frame) bool {+pub fn suffersValueMissing(self: *Input) bool {if (!self.getWillValidate()) return false;if (!self.getRequired()) return false;return switch (self._input_type) {.checkbox => !self._checked,- .radio => !self.radioGroupHasChecked(frame),+ .radio => !self.radioGroupHasChecked(),.file => if (self._files) |fl| fl._files.len == 0 else true,.text, .password, .email, .url, .tel, .search, .number, .date, .time, .@"datetime-local", .month, .week, .color => blk: {const v = self._value orelse self._default_value orelse "";@@ -497,14 +497,14 @@ fn numericRangeBreach(self: *const Input, comptime kind: enum { underflow, overf};}-fn radioGroupHasChecked(self: *Input, frame: *Frame) bool {+fn radioGroupHasChecked(self: *Input) bool {if (self._checked) return true;var iter = self.radioGroupIterator() orelse return false;- const my_form = self.getForm(frame);+ const my_form = self.getForm();while (iter.next()) |other| {if (other == self) continue;if (!other._checked) continue;- if (sameFormOwner(my_form, other, frame)) return true;+ if (sameFormOwner(my_form, other)) return true;}return false;}@@ -543,8 +543,8 @@ fn radioGroupIterator(self: *const Input) ?RadioGroupIterator {};}-fn sameFormOwner(self_form: ?*Form, other: *Input, frame: *Frame) bool {- const other_form = other.getForm(frame);+fn sameFormOwner(self_form: ?*Form, other: *Input) bool {+ const other_form = other.getForm();// Check if same form contextif (self_form == null and other_form == null) {@@ -688,7 +688,7 @@ fn getLabels(self: *Input, frame: *Frame) !js.Array {return @import("Label.zig").getControlLabels(self.asElement(), frame);}-fn getList(self: *Input, frame: *Frame) ?*HtmlElement.DataList {+fn getList(self: *Input) ?*HtmlElement.DataList {switch (self._input_type) {.hidden, .password, .checkbox, .radio, .file, .submit, .image, .reset, .button => return null,else => {},@@ -698,12 +698,12 @@ fn getList(self: *Input, frame: *Frame) ?*HtmlElement.DataList {const list_id = element.getAttributeSafe(comptime .wrap("list")) orelse return null;// list= resolves in the input's own tree (shadow root or document).- const target = frame.getElementByIdFromNode(element.asNode(), list_id) orelse return null;+ const target = Frame.getElementByIdFromNode(element.asNode(), list_id) orelse return null;return target.is(HtmlElement.DataList);}-pub fn getForm(self: *Input, frame: *Frame) ?*Form {- return Form.ownerOf(self.asElement(), frame);+pub fn getForm(self: *Input) ?*Form {+ return Form.ownerOf(self.asElement());}// Form submission attribute overrides@@ -1469,18 +1469,18 @@ fn maxWeeksInYear(year: u32) u32 {return 52;}-fn uncheckRadioGroup(self: *Input, frame: *Frame) void {+fn uncheckRadioGroup(self: *Input) void {var iter = self.radioGroupIterator() orelse return;- const my_form = self.getForm(frame);+ const my_form = self.getForm();while (iter.next()) |other| {if (other == self) continue;- if (!sameFormOwner(my_form, other, frame)) continue;+ if (!sameFormOwner(my_form, other)) continue;other._checked = false;}}-fn getPopoverTargetElement(self: *Input, frame: *Frame) ?*Element {- return popover.invokerTarget(self.asNode(), self._popover_target, frame);+fn getPopoverTargetElement(self: *Input) ?*Element {+ return popover.invokerTarget(self.asNode(), self._popover_target);}fn setPopoverTargetElement(self: *Input, value: ?*Element, frame: *Frame) !void {@@ -1615,7 +1615,7 @@ pub const Build = struct {// If this is a checked radio button, uncheck others in its groupif (self._checked and self._input_type == .radio) {- self.uncheckRadioGroup(frame);+ self.uncheckRadioGroup();}}@@ -1638,7 +1638,7 @@ pub const Build = struct {self._checked = true;// If setting a radio button to checked, uncheck others in the groupif (self._input_type == .radio) {- self.uncheckRadioGroup(frame);+ self.uncheckRadioGroup();}}},diff --git a/src/browser/webapi/element/html/Label.zig b/src/browser/webapi/element/html/Label.zigindex f8c318a7c..7161be74e 100644--- a/src/browser/webapi/element/html/Label.zig+++ b/src/browser/webapi/element/html/Label.zig@@ -42,7 +42,7 @@ pub fn asNode(self: *Label) *Node {return self.asElement().asNode();}-pub fn getControl(self: *Label, frame: *Frame) ?*Element {+pub fn getControl(self: *Label) ?*Element {if (self.asElement().getAttributeInterned("for")) |id| {// Like Chrome: `for` only resolves in a document or shadow tree, so a// detached label has no control by id.@@ -50,7 +50,7 @@ pub fn getControl(self: *Label, frame: *Frame) ?*Element {if (!node.isConnected() and !node.isInShadowTree()) {return null;}- const el = frame.getElementByIdFromNode(node, id) orelse return null;+ const el = Frame.getElementByIdFromNode(node, id) orelse return null;if (!isLabelable(el)) {return null;}@@ -128,7 +128,7 @@ pub fn getControlLabels(control: *Element, frame: *Frame) !js.Array {// Only an id can pull in a `for` label from elsewhere in the tree, and only// if this control is the first element with it. Then walk the whole tree.const by_id = if (control.getId()) |id|- id.len > 0 and frame.getElementByIdFromNode(root, id) == control+ id.len > 0 and Frame.getElementByIdFromNode(root, id) == controlelsefalse;@@ -136,7 +136,7 @@ pub fn getControlLabels(control: *Element, frame: *Frame) !js.Array {var it = TreeWalker.Full.Elements.init(root, .{});while (it.next()) |el| {const label = el.is(Label) orelse continue;- if (label.getControl(frame) != control) {+ if (label.getControl() != control) {continue;}_ = try arr.set(idx, el, .{});@@ -151,7 +151,7 @@ pub fn getControlLabels(control: *Element, frame: *Frame) !js.Array {var current: ?*Node = node._parent;while (current) |n| : (current = n._parent) {const label = n.is(Label) orelse continue;- if (label.getControl(frame) == control) {+ if (label.getControl() == control) {count += 1;}}@@ -160,7 +160,7 @@ pub fn getControlLabels(control: *Element, frame: *Frame) !js.Array {current = node._parent;while (current) |n| : (current = n._parent) {const label = n.is(Label) orelse continue;- if (label.getControl(frame) != control) {+ if (label.getControl() != control) {continue;}idx -= 1;diff --git a/src/browser/webapi/element/html/Select.zig b/src/browser/webapi/element/html/Select.zigindex e2f15607d..2b543c618 100644--- a/src/browser/webapi/element/html/Select.zig+++ b/src/browser/webapi/element/html/Select.zig@@ -454,8 +454,8 @@ pub fn getSelectedOptions(self: *Select, frame: *Frame) !collections.NodeLive(.sreturn collections.NodeLive(.selected_options).init(self.asNode(), {}, frame);}-pub fn getForm(self: *Select, frame: *Frame) ?*Form {- return Form.ownerOf(self.asElement(), frame);+pub fn getForm(self: *Select) ?*Form {+ return Form.ownerOf(self.asElement());}fn getLabels(self: *Select, frame: *Frame) !js.Array {diff --git a/src/browser/webapi/element/html/TextArea.zig b/src/browser/webapi/element/html/TextArea.zigindex 45726358a..159677dfd 100644--- a/src/browser/webapi/element/html/TextArea.zig+++ b/src/browser/webapi/element/html/TextArea.zig@@ -187,8 +187,8 @@ fn getSelectionEnd(self: *const TextArea) u32 {return entry.selectionOffsetToJs(self, self._selection_end);}-pub fn getForm(self: *TextArea, frame: *Frame) ?*Form {- return Form.ownerOf(self.asElement(), frame);+pub fn getForm(self: *TextArea) ?*Form {+ return Form.ownerOf(self.asElement());}fn getLabels(self: *TextArea, frame: *Frame) !js.Array {diff --git a/src/browser/webapi/element/html/ValidityState.zig b/src/browser/webapi/element/html/ValidityState.zigindex d5ab072a0..956b0d5cc 100644--- a/src/browser/webapi/element/html/ValidityState.zig+++ b/src/browser/webapi/element/html/ValidityState.zig@@ -38,9 +38,9 @@ const ValidityState = @This();// because the flag definitions are per-type in the HTML spec._owner: *Element,-fn getValueMissing(self: *const ValidityState, frame: *Frame) bool {+fn getValueMissing(self: *const ValidityState) bool {if (self.customFlags()) |flags| return flags.valueMissing;- if (self._owner.is(Input)) |input| return input.suffersValueMissing(frame);+ if (self._owner.is(Input)) |input| return input.suffersValueMissing();if (self._owner.is(Select)) |select| return select.suffersValueMissing();if (self._owner.is(TextArea)) |textarea| return textarea.suffersValueMissing();return false;@@ -111,7 +111,7 @@ fn getCustomError(self: *const ValidityState) bool {pub fn getValid(self: *const ValidityState, frame: *Frame) bool {if (self.customFlags()) |flags| return !flags.any();- return !self.getValueMissing(frame) and+ return !self.getValueMissing() and!self.getTypeMismatch() and!self.getPatternMismatch(frame) and!self.getTooLong() anddiff --git a/src/browser/webapi/element/popover.zig b/src/browser/webapi/element/popover.zigindex 3a7474cf0..52df6e8a1 100644--- a/src/browser/webapi/element/popover.zig+++ b/src/browser/webapi/element/popover.zig@@ -191,7 +191,7 @@ pub fn removeFromOpen(el: *Element, frame: *Frame) void {// The popover targeted by an invoker (a <button>, or input button), resolving// the explicitly IDL-set element or the `popovertarget` IDREF content attribute.-pub fn invokerTarget(invoker: *Node, explicit: ?*Element, frame: *Frame) ?*Element {+pub fn invokerTarget(invoker: *Node, explicit: ?*Element) ?*Element {if (explicit) |target| {if (target.asNode().getRootNode(.{}) == invoker.getRootNode(.{})) {// The invoker and target must share the same root@@ -201,7 +201,7 @@ pub fn invokerTarget(invoker: *Node, explicit: ?*Element, frame: *Frame) ?*Eleme}const el = invoker.is(Element) orelse return null;const id = el.getAttributeSafe(.wrap("popovertarget")) orelse return null;- return frame.getElementByIdFromNode(el.asNode(), id);+ return Frame.getElementByIdFromNode(el.asNode(), id);}pub fn runInvokerActivation(invoker: *HtmlElement, explicit: ?*Element, frame: *Frame) !void {@@ -216,7 +216,7 @@ pub fn runInvokerActivation(invoker: *HtmlElement, explicit: ?*Element, frame: *const invoker_elem = invoker.asElement();const invoker_node = invoker_elem.asNode();- const target = invokerTarget(invoker_node, explicit, frame) orelse return;+ const target = invokerTarget(invoker_node, explicit) orelse return;if (getState(target) == null) {return;diff --git a/src/browser/webapi/selector/List.zig b/src/browser/webapi/selector/List.zigindex 2e14a8df7..4a470c0f2 100644--- a/src/browser/webapi/selector/List.zig+++ b/src/browser/webapi/selector/List.zig@@ -104,12 +104,37 @@ fn optimizeSelector(root: *Node, selector: *const Selector.Selector, nth: *NthCaconst id = anchor.id;const segment_index = anchor.segment_index;- // Look up the element by ID (O(1) hash map lookup)- const id_element = frame.getElementByIdFromNode(root, id) orelse return null;+ // id fast-path (O(1) hash map lookup). That's the common case, but+ // if the id actually isn't unique (it happens) or isn't under the root,+ // we need to walk+ const id_element = switch (Frame.getUniqueElementByIdFromNode(root, id)) {+ .none => return null,+ .one => |el| el,+ .many => {+ // multiple elements with the same id, can't be optimized+ return .{+ .root = root,+ .selector = selector.*,+ .exclude_root = true,+ };+ },+ };const id_node = id_element.asNode();- if (!root.contains(id_node)) {- return null;+ if (id_node == root or !root.contains(id_node)) {+ // When the id is in the rightmost compound, the only possible match+ // is id_node itself, and it isn't a descendant of root.+ const id_is_subject = if (segment_index) |i| i + 1 == selector.segments.len else selector.segments.len == 0;+ if (id_is_subject) {+ return null;+ }+ // Otherwise matches can still be below root (`#outer p` with #outer+ // an ancestor of root), so walk it.+ return .{+ .root = root,+ .selector = selector.*,+ .exclude_root = true,+ };}// If the ID is in the first compounddiff --git a/src/browser/webapi/selector/Selector.zig b/src/browser/webapi/selector/Selector.zigindex 477b86b50..b2d4d8a61 100644--- a/src/browser/webapi/selector/Selector.zig+++ b/src/browser/webapi/selector/Selector.zig@@ -451,17 +451,22 @@ pub fn query(selectors: []const Selector, root: *Node, frame: *Frame) !?*Node.Eldefer nth.deinit();for (selectors) |selector| {- // Fast path: single compound with only an ID selector+ // Fast path: single compound with only an ID selector. With+ // duplicate ids, the general walk below finds the first one under root.if (selector.segments.len == 0 and selector.first.parts.len == 1) {const first = selector.first.parts[0];if (first == .id) {- const el = frame.getElementByIdFromNode(root, first.id) orelse continue;- // Check if the element is within the root subtree- const node = el.asNode();- if (node != root and root.contains(node)) {- return el;+ switch (Frame.getUniqueElementByIdFromNode(root, first.id)) {+ .none => continue,+ .one => |el| {+ const node = el.asNode();+ if (node != root and root.contains(node)) {+ return el;+ }+ continue;+ },+ .many => {},}- continue;}}diff --git a/src/browser/xpath/Evaluator.zig b/src/browser/xpath/Evaluator.zigindex 88884dec0..15ce1ff48 100644--- a/src/browser/xpath/Evaluator.zig+++ b/src/browser/xpath/Evaluator.zig@@ -128,19 +128,12 @@ fn evalPath(self: *Evaluator, path: ast.Path, ctx: *Node) Error!result.Result {// Recognize the very common `//tag[@id='x']` and `.//tag[@id='x']`// shapes (and their wildcard `//*[@id='x']` variants) and serve them-// directly from `frame.getElementByIdFromNode`. Accepts the literal on-// either side of `=`.+// directly from the id map when the id is unique in its tree scope.+// Accepts the literal on either side of `=`.//-// Mirrors the same tradeoff `webapi/selector/List.zig:optimizeSelector`-// already makes for `querySelector(All)`: the id-map only stores the-// first element per ID in document order, so duplicate IDs (invalid-// HTML, but possible) yield one match here where a strict tree walk-// would find all. Acceptable because Capybara/Selenium hot paths-// assume unique IDs and CSS has shipped this compromise for years.-//-// Falls through to the general path for any deviation: extra steps,-// extra predicates, non-eq predicate, non-literal RHS, or the-// inability to resolve a search root.+// Falls through to the general path for duplicate ids (invalid HTML, but+// common) and for any deviation: extra steps, extra predicates, non-eq+// predicate, non-literal RHS, or the inability to resolve a search root.fn tryIdLookupFastPath(self: *Evaluator, path: ast.Path, ctx: *Node) Error!?result.Result {// Two acceptable AST shapes:// //tag[@id='x'] parses to: ds::node() / child::tag[pred]@@ -167,13 +160,15 @@ fn tryIdLookupFastPath(self: *Evaluator, path: ast.Path, ctx: *Node) Error!?resubreak :blk owner.asNode();} else ctx;- const id_element = self.frame.getElementByIdFromNode(search_root, id_value) orelse {- return .{ .node_set = &.{} };+ const id_element = switch (Frame.getUniqueElementByIdFromNode(search_root, id_value)) {+ .none => return .{ .node_set = &.{} },+ .one => |el| el,+ .many => return null,};const id_node = id_element.asNode();- // Relative paths must filter to descendants of the context.- // getElementByIdFromNode is doc-wide.+ // Relative paths must filter to descendants of the context. The id map+ // covers the whole tree scope.if (search_root != id_node and !search_root.contains(id_node)) {return .{ .node_set = &.{} };}diff --git a/src/browser/xpath/functions.zig b/src/browser/xpath/functions.zigindex 54d81e1f5..066cda27a 100644--- a/src/browser/xpath/functions.zig+++ b/src/browser/xpath/functions.zig@@ -135,7 +135,7 @@ fn idFn(arena: Allocator, args: []const result.Result, ctx: *Node, frame: *Framevar seen: std.AutoArrayHashMapUnmanaged(*Node, void) = .empty;var it = std.mem.tokenizeAny(u8, id_str, &std.ascii.whitespace);while (it.next()) |tok| {- if (doc.getElementById(tok, frame)) |el| {+ if (doc.getElementById(tok)) |el| {try seen.put(arena, el.asNode(), {});}}diff --git a/src/mcp/tools.zig b/src/mcp/tools.zigindex 54bf0bf67..559b0d57b 100644--- a/src/mcp/tools.zig+++ b/src/mcp/tools.zig@@ -1249,7 +1249,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setCheckedconst frame = server.active_session.session.currentFrame().?;{- const btn = frame.document.getElementById("btn", frame).?.asNode();+ const btn = frame.document.getElementById("btn").?.asNode();const btn_id = (try server.active_session.registry.register(btn)).id;var btn_id_buf: [12]u8 = undefined;const btn_id_str = std.mem.print(&btn_id_buf, "{d}", .{btn_id}) catch unreachable;@@ -1268,7 +1268,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked}{- const inp = frame.document.getElementById("inp", frame).?.asNode();+ const inp = frame.document.getElementById("inp").?.asNode();const inp_id = (try server.active_session.registry.register(inp)).id;var inp_id_buf: [12]u8 = undefined;const inp_id_str = std.mem.print(&inp_id_buf, "{d}", .{inp_id}) catch unreachable;@@ -1280,7 +1280,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked}{- const sel = frame.document.getElementById("sel", frame).?.asNode();+ const sel = frame.document.getElementById("sel").?.asNode();const sel_id = (try server.active_session.registry.register(sel)).id;var sel_id_buf: [12]u8 = undefined;const sel_id_str = std.mem.print(&sel_id_buf, "{d}", .{sel_id}) catch unreachable;@@ -1293,9 +1293,9 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked// A scroll container, and a node with no scroll-container ancestor, are// scrolled themselves.- const scrollbox = frame.document.getElementById("scrollbox", frame).?.asNode();+ const scrollbox = frame.document.getElementById("scrollbox").?.asNode();const scrollbox_id = (try server.active_session.registry.register(scrollbox)).id;- const plain = frame.document.getElementById("plain", frame).?.asNode();+ const plain = frame.document.getElementById("plain").?.asNode();const plain_id = (try server.active_session.registry.register(plain)).id;for ([_]struct { id: lp.NodeRegistry.Id, y: i32 }{ .{ .id = scrollbox_id, .y = 50 }, .{ .id = plain_id, .y = 7 } }) |c| {const msg = try aa.print("{{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"tools/call\",\"params\":{{\"name\":\"scroll\",\"arguments\":{{\"backendNodeId\":{d},\"y\":{d}}}}}}}", .{ c.id, c.y });@@ -1307,9 +1307,9 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked// A leaf inside a scroll container scrolls the container, not the leaf.{- const leaf = frame.document.getElementById("innerleaf", frame).?.asNode();+ const leaf = frame.document.getElementById("innerleaf").?.asNode();const leaf_id = (try server.active_session.registry.register(leaf)).id;- const outer = frame.document.getElementById("outerscroll", frame).?.asNode();+ const outer = frame.document.getElementById("outerscroll").?.asNode();const outer_id = (try server.active_session.registry.register(outer)).id;const msg = try aa.print("{{\"jsonrpc\":\"2.0\",\"id\":40,\"method\":\"tools/call\",\"params\":{{\"name\":\"scroll\",\"arguments\":{{\"backendNodeId\":{d},\"y\":30}}}}}}", .{leaf_id});try router.handleMessage(server, aa, msg);@@ -1320,7 +1320,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked// A selector targets the element as a backendNodeId does.{- const outer = frame.document.getElementById("outerscroll", frame).?.asNode();+ const outer = frame.document.getElementById("outerscroll").?.asNode();const outer_id = (try server.active_session.registry.register(outer)).id;try router.handleMessage(server, aa,\\{"jsonrpc":"2.0","id":41,"method":"tools/call","params":{"name":"scroll","arguments":{"selector":"#innerleaf","y":30}}}@@ -1332,9 +1332,9 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked// The container may be declared in a stylesheet rather than inline.{- const leaf = frame.document.getElementById("sheetleaf", frame).?.asNode();+ const leaf = frame.document.getElementById("sheetleaf").?.asNode();const leaf_id = (try server.active_session.registry.register(leaf)).id;- const outer = frame.document.getElementById("sheetscroll", frame).?.asNode();+ const outer = frame.document.getElementById("sheetscroll").?.asNode();const outer_id = (try server.active_session.registry.register(outer)).id;const msg = try aa.print("{{\"jsonrpc\":\"2.0\",\"id\":44,\"method\":\"tools/call\",\"params\":{{\"name\":\"scroll\",\"arguments\":{{\"backendNodeId\":{d},\"y\":30}}}}}}", .{leaf_id});try router.handleMessage(server, aa, msg);@@ -1358,7 +1358,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked}{- const el = frame.document.getElementById("hoverTarget", frame).?.asNode();+ const el = frame.document.getElementById("hoverTarget").?.asNode();const el_id = (try server.active_session.registry.register(el)).id;var id_buf: [12]u8 = undefined;const id_str = std.mem.print(&id_buf, "{d}", .{el_id}) catch unreachable;@@ -1369,7 +1369,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked}{- const el = frame.document.getElementById("keyTarget", frame).?.asNode();+ const el = frame.document.getElementById("keyTarget").?.asNode();const el_id = (try server.active_session.registry.register(el)).id;var id_buf: [12]u8 = undefined;const id_str = std.mem.print(&id_buf, "{d}", .{el_id}) catch unreachable;@@ -1380,7 +1380,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked}{- const el = frame.document.getElementById("sel2", frame).?.asNode();+ const el = frame.document.getElementById("sel2").?.asNode();const el_id = (try server.active_session.registry.register(el)).id;var id_buf: [12]u8 = undefined;const id_str = std.mem.print(&id_buf, "{d}", .{el_id}) catch unreachable;@@ -1391,7 +1391,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked}{- const el = frame.document.getElementById("chk", frame).?.asNode();+ const el = frame.document.getElementById("chk").?.asNode();const el_id = (try server.active_session.registry.register(el)).id;var id_buf: [12]u8 = undefined;const id_str = std.mem.print(&id_buf, "{d}", .{el_id}) catch unreachable;@@ -1402,7 +1402,7 @@ test "MCP - Actions: click, fill, scroll, hover, press, selectOption, setChecked}{- const el = frame.document.getElementById("rad", frame).?.asNode();+ const el = frame.document.getElementById("rad").?.asNode();const el_id = (try server.active_session.registry.register(el)).id;var id_buf: [12]u8 = undefined;const id_str = std.mem.print(&id_buf, "{d}", .{el_id}) catch unreachable;@@ -1465,7 +1465,7 @@ test "MCP - click that navigates clears node registry" {defer server.active_session.exitIsolate();const before_frame = server.active_session.session.currentFrame().?;- const link = before_frame.document.getElementById("navlink", before_frame).?.asNode();+ const link = before_frame.document.getElementById("navlink").?.asNode();const link_id = (try server.active_session.registry.register(link)).id;try testing.expect(server.active_session.registry.lookup_by_id.contains(link_id));diff --git a/src/server/cdp/AXNode.zig b/src/server/cdp/AXNode.zigindex 928fef1ec..911dd6cb5 100644--- a/src/server/cdp/AXNode.zig+++ b/src/server/cdp/AXNode.zig@@ -992,7 +992,7 @@ fn writeName(const trimmed_id = std.mem.trim(u8, id, &std.ascii.whitespace);if (trimmed_id.len == 0) continue;- if (doc.getElementById(trimmed_id, frame)) |referenced_el| {+ if (doc.getElementById(trimmed_id)) |referenced_el| {// Get the text content of the referenced elementtry referenced_el.getInnerText(&buf.writer, frame);try buf.writer.writeByte(' ');@@ -1243,7 +1243,7 @@ fn labelPromotionTarget(if (el.getTag() != .label) return null;const label = el.as(DOMNode.Element.Html.Label);- const control = label.getControl(frame) orelse return null;+ const control = label.getControl() orelse return null;if (control.getTag() != .input) return null;const input = control.as(DOMNode.Element.Html.Input);switch (input._input_type) {@@ -1990,7 +1990,7 @@ test "AXNode: Writer query and subtree root see a hiding ancestor" {const button = (try frame.window._document.querySelector(.wrap("#under-inert"), frame)).?;const host = (try frame.window._document.querySelector(.wrap("#inert-host"), frame)).?;- const shadow_button = host.getShadowRoot(frame).?.getElementById("in-inert-shadow", frame).?;+ const shadow_button = host.getShadowRoot(frame).?.getElementById("in-inert-shadow").?;writer.filter = null;for ([_]*DOMNode.Element{ button, shadow_button }) |root| {diff --git a/src/server/cdp/domains/dom.zig b/src/server/cdp/domains/dom.zigindex 8f83e821c..c4d2578db 100644--- a/src/server/cdp/domains/dom.zig+++ b/src/server/cdp/domains/dom.zig@@ -1216,8 +1216,8 @@ test "cdp.dom: focus and setFileInputFiles fire in the node's own frame" {const bc = try ctx.loadBrowserContext(.{ .id = "BID-A", .url = "cdp/input_iframe.html" });const child = bc.mainFrame().?.child_frames.items[0];- const text = child.document.getElementById("text", child) orelse unreachable;- const upload = child.document.getElementById("upload", child) orelse unreachable;+ const text = child.document.getElementById("text") orelse unreachable;+ const upload = child.document.getElementById("upload") orelse unreachable;const text_node = try bc.node_registry.register(text.asNode());const upload_node = try bc.node_registry.register(upload.asNode());@@ -1529,7 +1529,7 @@ test "cdp.dom: getContentQuads of a node in a nested iframe is in the top-levelconst main = bc.mainFrame().?;const child = main.child_frames.items[0];const nested = child.child_frames.items[0];- const inner = nested.document.getElementById("inner", nested).?;+ const inner = nested.document.getElementById("inner").?;const inner_rect = inner.boundingClientRectValues(nested);const child_rect = child.iframe.?.asElement().boundingClientRectValues(main);const nested_rect = nested.iframe.?.asElement().boundingClientRectValues(child);diff --git a/src/server/cdp/domains/input.zig b/src/server/cdp/domains/input.zigindex 418940bde..e46f14133 100644--- a/src/server/cdp/domains/input.zig+++ b/src/server/cdp/domains/input.zig@@ -3222,7 +3222,7 @@ test "cdp.input: re-navigating an iframe drops the pointer state on its elementsconst main = bc.mainFrame().?;const page = main.page;const child = main.child_frames.items[0];- const text = child.document.getElementById("text", child) orelse unreachable;+ const text = child.document.getElementById("text") orelse unreachable;try lp.actions.click(text.asNode(), child);try page.input_pointer.press(child, text, .{});@@ -3288,7 +3288,7 @@ test "cdp.input: navigating an iframe clears a touch contact on its child documeconst bc = try ctx.loadBrowserContext(.{ .url = "cdp/input_iframe.html" });const main = bc.mainFrame().?;const child = main.child_frames.items[0];- const target = child.document.getElementById("text", child) orelse unreachable;+ const target = child.document.getElementById("text") orelse unreachable;// CDP currently hit-tests only the main frame; seed the child contact// directly to exercise frame teardown independently of iframe routing.// Chrome keeps such a contact alive across the navigation (a laterdiff --git a/src/server/cdp/domains/lp.zig b/src/server/cdp/domains/lp.zigindex d0a627b66..2f2b6bcac 100644--- a/src/server/cdp/domains/lp.zig+++ b/src/server/cdp/domains/lp.zig@@ -822,7 +822,7 @@ test "cdp.lp: action tools" {try testing.waitForPage(bc);// Test Click- const btn = frame.document.getElementById("btn", frame).?.asNode();+ const btn = frame.document.getElementById("btn").?.asNode();const btn_id = (try bc.node_registry.register(btn)).id;try ctx.processMessage(.{.id = 1,@@ -831,7 +831,7 @@ test "cdp.lp: action tools" {});// Test Fill Input- const inp = frame.document.getElementById("inp", frame).?.asNode();+ const inp = frame.document.getElementById("inp").?.asNode();const inp_id = (try bc.node_registry.register(inp)).id;try ctx.processMessage(.{.id = 2,@@ -840,7 +840,7 @@ test "cdp.lp: action tools" {});// Test Fill Select- const sel = frame.document.getElementById("sel", frame).?.asNode();+ const sel = frame.document.getElementById("sel").?.asNode();const sel_id = (try bc.node_registry.register(sel)).id;try ctx.processMessage(.{.id = 3,@@ -849,7 +849,7 @@ test "cdp.lp: action tools" {});// Test Scroll- const scrollbox = frame.document.getElementById("scrollbox", frame).?.asNode();+ const scrollbox = frame.document.getElementById("scrollbox").?.asNode();const scrollbox_id = (try bc.node_registry.register(scrollbox)).id;try ctx.processMessage(.{.id = 4,@@ -859,9 +859,9 @@ test "cdp.lp: action tools" {try ctx.expectSentResult(.{ .backendNodeId = scrollbox_id, .x = 0, .y = 50 }, .{ .id = 4 });// A leaf inside a scroll container scrolls the container, not the leaf.- const leaf = frame.document.getElementById("innerleaf", frame).?.asNode();+ const leaf = frame.document.getElementById("innerleaf").?.asNode();const leaf_id = (try bc.node_registry.register(leaf)).id;- const outer = frame.document.getElementById("outerscroll", frame).?.asNode();+ const outer = frame.document.getElementById("outerscroll").?.asNode();const outer_id = (try bc.node_registry.register(outer)).id;try ctx.processMessage(.{.id = 5,