Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

fix(accessibility): include shadow controls in AX snapshots

ldm037e8bf746c2d
diff --git a/moli-dom/src/accessibility/ax_dom.rs b/moli-dom/src/accessibility/ax_dom.rs
new file mode 100644
index 000000000..818379251
--- /dev/null
+++ b/moli-dom/src/accessibility/ax_dom.rs
@@ -0,0 +1,62 @@
+use crate::{NodeData, NodeId, native::DomHost};
+
+pub(super) fn ax_child_ids(
+ document: &DomHost,
+ node_id: NodeId,
+) -> impl Iterator<Item = NodeId> + '_ {
+ let composed = composed_child_ids(document, node_id);
+ let ordinary = composed.is_none().then(|| document.child_ids(node_id));
+ composed
+ .into_iter()
+ .flatten()
+ .chain(ordinary.into_iter().flatten())
+}
+
+pub(super) fn ax_child_ids_reversed(
+ document: &DomHost,
+ node_id: NodeId,
+) -> impl Iterator<Item = NodeId> + '_ {
+ let composed = composed_child_ids(document, node_id);
+ let ordinary = composed
+ .is_none()
+ .then(|| document.child_ids_reversed(node_id));
+ composed
+ .into_iter()
+ .flat_map(|children| children.into_iter().rev())
+ .chain(ordinary.into_iter().flatten())
+}
+
+fn composed_child_ids(document: &DomHost, node_id: NodeId) -> Option<Vec<NodeId>> {
+ // Shadow trees replace the host's light children; slots reinsert assigned
+ // nodes in their rendered order, using fallback children when unassigned.
+ if let Some(root) = document.shadow_root_handle(node_id) {
+ return Some(vec![root]);
+ }
+ if document
+ .element(node_id)
+ .is_some_and(|element| element.is_html_element("slot"))
+ && document.containing_shadow_root(node_id).is_some()
+ {
+ let assigned = document.assigned_nodes_for_slot_with_options(node_id, false);
+ if !assigned.is_empty() {
+ return Some(assigned);
+ }
+ }
+ None
+}
+
+pub(super) fn ax_content_text(document: &DomHost, node_id: NodeId) -> String {
+ let mut text = String::new();
+ let mut pending = ax_child_ids_reversed(document, node_id).collect::<Vec<_>>();
+ while let Some(node_id) = pending.pop() {
+ let Some(node) = document.node(node_id) else {
+ continue;
+ };
+ match node.kind() {
+ NodeData::Text(value) => text.push_str(value.data()),
+ NodeData::CDataSection(value) => text.push_str(value.data()),
+ _ => pending.extend(ax_child_ids_reversed(document, node_id)),
+ }
+ }
+ text
+}
diff --git a/moli-dom/src/accessibility/ax_projection.rs b/moli-dom/src/accessibility/ax_projection.rs
index 81e0c733a..c3b53d580 100644
--- a/moli-dom/src/accessibility/ax_projection.rs
+++ b/moli-dom/src/accessibility/ax_projection.rs
@@ -1,9 +1,11 @@
use crate::{
NodeData, NodeId,
forms::InputType,
- native::{Element, NativeDom, Node},
+ native::{DomHost, Element, NativeDom, Node},
};
+use super::ax_dom::{ax_child_ids, ax_child_ids_reversed};
+
/// A command-local projection of the DOM into the accessibility tree.
///
/// Blink keeps this distinction on `AXObject`: an object may be ignored but
@@ -34,12 +36,12 @@ enum AxNodeInclusion {
}
impl AxTreeProjection {
- pub(super) fn build_for_node(document: &NativeDom, node_id: NodeId) -> Self {
+ pub(super) fn build_for_node(document: &DomHost, node_id: NodeId) -> Self {
let root = accessibility_root_for_node(document, node_id);
Self::build_from_root(document, root)
}
- fn build_from_root(document: &NativeDom, root: NodeId) -> Self {
+ fn build_from_root(document: &DomHost, root: NodeId) -> Self {
let mut nodes = Vec::with_capacity(document.len());
nodes.resize_with(document.len(), || None);
let mut projection = Self { nodes };
@@ -79,7 +81,7 @@ impl AxTreeProjection {
}
}
- fn visit(&mut self, document: &NativeDom, root: NodeId) {
+ fn visit(&mut self, document: &DomHost, root: NodeId) {
let mut pending = vec![(root, None, None)];
while let Some((node_id, projected_parent, inherited_aria_hidden_root)) = pending.pop() {
let Some(node) = document.node(node_id) else {
@@ -90,7 +92,7 @@ impl AxTreeProjection {
AxNodeInclusion::ExcludeSubtree => continue,
AxNodeInclusion::ExcludeNode => {
pending.extend(
- document.child_ids_reversed(node_id).map(|child_id| {
+ ax_child_ids_reversed(document, node_id).map(|child_id| {
(child_id, projected_parent, inherited_aria_hidden_root)
}),
);
@@ -126,8 +128,7 @@ impl AxTreeProjection {
}
pending.extend(
- document
- .child_ids_reversed(node_id)
+ ax_child_ids_reversed(document, node_id)
.map(|child_id| (child_id, Some(node_id), aria_hidden_root)),
);
}
@@ -204,7 +205,7 @@ fn ax_aria_hidden(element: &Element) -> bool {
.is_some_and(|value| value.trim().eq_ignore_ascii_case("true"))
}
-fn ax_is_uninteresting_container(document: &NativeDom, node_id: NodeId, element: &Element) -> bool {
+fn ax_is_uninteresting_container(document: &DomHost, node_id: NodeId, element: &Element) -> bool {
if element.is_html_element("html") {
return true;
}
@@ -215,7 +216,7 @@ fn ax_is_uninteresting_container(document: &NativeDom, node_id: NodeId, element:
// Blink leaves a body with inline children in the tree as a generic
// container, but ignores a block-flow body and exposes its semantic block
// children through the ignored chain.
- document.child_ids(node_id).any(|child_id| {
+ ax_child_ids(document, node_id).any(|child_id| {
document
.node(child_id)
.and_then(Node::as_element)
@@ -275,6 +276,7 @@ mod tests {
parent = child;
}
+ let document = DomHost::from_dom(document);
let projection = AxTreeProjection::build_for_node(&document, document.document_node_id());
assert_eq!(
projection.node(parent).and_then(|node| node.parent),
diff --git a/moli-dom/src/accessibility/ax_properties.rs b/moli-dom/src/accessibility/ax_properties.rs
index 2c73447d3..3665d4836 100644
--- a/moli-dom/src/accessibility/ax_properties.rs
+++ b/moli-dom/src/accessibility/ax_properties.rs
@@ -1,12 +1,13 @@
use crate::{
NodeData, NodeId,
forms::InputType,
- native::{Element, NativeDom, Node},
+ native::{DomHost, Element, NativeDom, Node},
};
use serde_json::{Value, json};
use std::collections::HashSet;
use url::Url;
+use super::ax_dom::ax_content_text;
use super::ax_roles::{ax_role, heading_level};
// Blink bounds text-alternative traversal with
@@ -32,7 +33,7 @@ impl AxNameTraversal {
}
}
-pub(super) fn ax_name(document: &NativeDom, node: &Node) -> String {
+pub(super) fn ax_name(document: &DomHost, node: &Node) -> String {
match node.kind() {
NodeData::Document(_) => ax_document_name(document),
NodeData::Element(_) => ax_node_name(
@@ -55,7 +56,7 @@ pub(super) fn ax_name(document: &NativeDom, node: &Node) -> String {
/// `aria-labelledby`, `aria-label`, native HTML alternatives, contents, then
/// tooltip-style fallbacks.
fn ax_node_name(
- document: &NativeDom,
+ document: &DomHost,
node_id: NodeId,
traversal: AxNameTraversal,
visited: &mut HashSet<NodeId>,
@@ -85,7 +86,7 @@ fn ax_node_name(
}
fn ax_element_name(
- document: &NativeDom,
+ document: &DomHost,
node_id: NodeId,
node: &Node,
element: &Element,
@@ -131,7 +132,7 @@ fn ax_element_name(
// text controls expose that text through children or AXValue instead.
let content =
if traversal.includes_contents() || ax_name_comes_from_contents(document, node, element) {
- normalize_ax_whitespace(&node.text_content(document))
+ normalize_ax_whitespace(&ax_content_text(document, node_id))
} else {
String::new()
};
@@ -157,7 +158,7 @@ fn ax_element_name(
}
fn ax_native_element_name(
- document: &NativeDom,
+ document: &DomHost,
node_id: NodeId,
element: &Element,
visited: &mut HashSet<NodeId>,
@@ -857,7 +858,8 @@ mod tests {
}
fn node_name(document: &NativeDom, node_id: NodeId) -> String {
- ax_name(document, document.node(node_id).expect("named node"))
+ let host = DomHost::from_dom(document.clone());
+ ax_name(&host, host.node(node_id).expect("named node"))
}
#[test]
diff --git a/moli-dom/src/accessibility/ax_tree.rs b/moli-dom/src/accessibility/ax_tree.rs
index af7ddd8e8..6b148ed4c 100644
--- a/moli-dom/src/accessibility/ax_tree.rs
+++ b/moli-dom/src/accessibility/ax_tree.rs
@@ -1,6 +1,6 @@
use crate::{
NodeId,
- native::{NativeDom, Node},
+ native::{DomHost, Node},
};
use serde_json::{Value, json};
use std::collections::VecDeque;
@@ -14,7 +14,7 @@ use super::ax_roles::{ax_role, cdp_node_id, ordered_list_item_index};
// ---------------------------------------------------------------------------
pub fn accessibility_tree_payloads_for_document(
- document: &NativeDom,
+ document: &DomHost,
root: NodeId,
max_depth: Option<i32>,
) -> Vec<Value> {
@@ -29,11 +29,14 @@ pub fn accessibility_tree_payloads_for_document(
}
pub fn accessibility_tree_payloads_for_document_with_backend_node_ids(
- document: &NativeDom,
+ document: &DomHost,
root: NodeId,
max_depth: Option<i32>,
backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,
) -> Option<Vec<Value>> {
+ // Blink's queryAXTree starts at the host when given a ShadowRoot, which
+ // contributes descendants but has no AX node of its own.
+ let root = document.shadow_root_host(root).unwrap_or(root);
let projection = AxTreeProjection::build_for_node(document, root);
if !projection.contains(root) {
return Some(Vec::new());
@@ -76,7 +79,7 @@ pub fn accessibility_tree_payloads_for_document_with_backend_node_ids(
}
pub fn accessibility_node_payload_for_document(
- document: &NativeDom,
+ document: &DomHost,
node_id: NodeId,
) -> Option<Value> {
let mut backend_node_id_for_node = |node_id| Some(cdp_node_id(node_id));
@@ -88,7 +91,7 @@ pub fn accessibility_node_payload_for_document(
}
pub fn accessibility_node_payload_for_document_with_backend_node_ids(
- document: &NativeDom,
+ document: &DomHost,
node_id: NodeId,
backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,
) -> Option<Value> {
@@ -99,7 +102,7 @@ pub fn accessibility_node_payload_for_document_with_backend_node_ids(
}
pub fn accessibility_child_node_payloads_for_document(
- document: &NativeDom,
+ document: &DomHost,
node_id: NodeId,
) -> Vec<Value> {
let mut backend_node_id_for_node = |node_id| Some(cdp_node_id(node_id));
@@ -112,7 +115,7 @@ pub fn accessibility_child_node_payloads_for_document(
}
pub fn accessibility_child_node_payloads_for_document_with_backend_node_ids(
- document: &NativeDom,
+ document: &DomHost,
node_id: NodeId,
backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,
) -> Option<Vec<Value>> {
@@ -132,7 +135,7 @@ pub fn accessibility_child_node_payloads_for_document_with_backend_node_ids(
}
pub fn accessibility_node_and_ancestor_payloads_for_document(
- document: &NativeDom,
+ document: &DomHost,
node_id: NodeId,
) -> Vec<Value> {
let mut backend_node_id_for_node = |node_id| Some(cdp_node_id(node_id));
@@ -145,7 +148,7 @@ pub fn accessibility_node_and_ancestor_payloads_for_document(
}
pub fn accessibility_node_and_ancestor_payloads_for_document_with_backend_node_ids(
- document: &NativeDom,
+ document: &DomHost,
node_id: NodeId,
backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,
) -> Option<Vec<Value>> {
@@ -172,7 +175,7 @@ pub fn accessibility_node_and_ancestor_payloads_for_document_with_backend_node_i
}
pub fn accessibility_partial_tree_payloads_for_document(
- document: &NativeDom,
+ document: &DomHost,
node_id: NodeId,
fetch_relatives: bool,
) -> Option<Vec<Value>> {
@@ -186,7 +189,7 @@ pub fn accessibility_partial_tree_payloads_for_document(
}
pub fn accessibility_partial_tree_payloads_for_document_with_backend_node_ids(
- document: &NativeDom,
+ document: &DomHost,
node_id: NodeId,
fetch_relatives: bool,
backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,
@@ -240,7 +243,7 @@ pub fn accessibility_partial_tree_payloads_for_document_with_backend_node_ids(
// ---------------------------------------------------------------------------
fn add_ax_children(
- document: &NativeDom,
+ document: &DomHost,
projection: &AxTreeProjection,
node_id: NodeId,
out: &mut Vec<Value>,
@@ -269,7 +272,7 @@ fn add_ax_children(
}
fn push_ax_node_payload(
- document: &NativeDom,
+ document: &DomHost,
projection: &AxTreeProjection,
node_id: NodeId,
out: &mut Vec<Value>,
@@ -297,7 +300,7 @@ fn push_ax_node_payload(
}
fn ax_node_payload(
- document: &NativeDom,
+ document: &DomHost,
node_id: NodeId,
node: &Node,
projected: &super::ax_projection::AxProjectedNode,
@@ -374,7 +377,7 @@ fn ax_node_payload(
}
fn ax_ignored_reasons_payload(
- document: &NativeDom,
+ document: &DomHost,
reason: AxIgnoredReason,
backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,
) -> Value {
@@ -410,7 +413,7 @@ fn ax_ignored_reasons_payload(
}
fn ax_list_marker_payload(
- document: &NativeDom,
+ document: &DomHost,
node_id: NodeId,
node: &Node,
backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,
diff --git a/moli-dom/src/accessibility/mod.rs b/moli-dom/src/accessibility/mod.rs
index 5d8c9f13e..e9505016f 100644
--- a/moli-dom/src/accessibility/mod.rs
+++ b/moli-dom/src/accessibility/mod.rs
@@ -1,3 +1,4 @@
+mod ax_dom;
mod ax_projection;
mod ax_properties;
mod ax_roles;
@@ -15,3 +16,6 @@ pub use ax_tree::{
accessibility_tree_payloads_for_document,
accessibility_tree_payloads_for_document_with_backend_node_ids,
};
+
+#[cfg(test)]
+mod tests;
diff --git a/moli-dom/src/accessibility/tests.rs b/moli-dom/src/accessibility/tests.rs
new file mode 100644
index 000000000..a53e3f2b8
--- /dev/null
+++ b/moli-dom/src/accessibility/tests.rs
@@ -0,0 +1,223 @@
+use serde_json::{Value, json};
+
+use super::*;
+use crate::{
+ NodeId,
+ native::{DomHost, NativeDom},
+};
+
+fn tree(document: &DomHost) -> Vec<Value> {
+ accessibility_tree_payloads_for_document(document, document.document_node_id(), None)
+}
+
+fn document_with_host() -> (DomHost, NodeId) {
+ let mut document = DomHost::from_dom(NativeDom::new_html(
+ url::Url::parse("https://example.test/").expect("valid document URL"),
+ ));
+ let host = append_element(&mut document, NodeId::new(0), "div");
+ (document, host)
+}
+
+fn append_element(document: &mut DomHost, parent: NodeId, tag: &str) -> NodeId {
+ let element = document.create_element(tag);
+ assert!(document.append_child(parent, element));
+ element
+}
+
+fn append_text(document: &mut DomHost, parent: NodeId, text: &str) {
+ let text = document.create_text_node(text);
+ assert!(document.append_child(parent, text));
+}
+
+fn node_by_id(nodes: &[Value], node_id: NodeId) -> &Value {
+ let backend_id = super::ax_roles::cdp_node_id(node_id);
+ nodes
+ .iter()
+ .find(|node| node["backendDOMNodeId"] == backend_id)
+ .unwrap_or_else(|| panic!("missing AX node for {node_id:?}: {nodes:?}"))
+}
+
+fn button_names(nodes: &[Value]) -> Vec<&str> {
+ nodes
+ .iter()
+ .filter(|node| node["role"]["value"] == "button")
+ .map(|node| node["name"]["value"].as_str().expect("button name"))
+ .collect()
+}
+
+#[test]
+fn ax_tree_queries_shadow_roots_from_hosts() {
+ for mode in ["open", "closed"] {
+ let (mut document, host) = document_with_host();
+ let root = document
+ .attach_shadow_root(host, mode)
+ .expect("shadow root");
+ let button = append_element(&mut document, root, "button");
+ append_text(&mut document, button, "Shadow action");
+ let document_id = document.document_node_id();
+ let outside = append_element(&mut document, document_id, "button");
+ append_text(&mut document, outside, "Outside action");
+
+ let nodes = accessibility_tree_payloads_for_document(&document, root, None);
+ assert_eq!(
+ nodes[0]["backendDOMNodeId"],
+ super::ax_roles::cdp_node_id(host)
+ );
+ assert_eq!(button_names(&nodes), ["Shadow action"]);
+ assert_eq!(
+ node_by_id(&nodes, button)["nodeId"],
+ node_by_id(&tree(&document), button)["nodeId"]
+ );
+ assert!(!nodes.iter().any(|node| {
+ node["backendDOMNodeId"] == super::ax_roles::cdp_node_id(root)
+ || node["backendDOMNodeId"] == super::ax_roles::cdp_node_id(outside)
+ }));
+ }
+}
+
+#[test]
+fn ax_tree_names_shadow_hosts_from_composed_contents() {
+ for mode in ["open", "closed"] {
+ let (mut document, host) = document_with_host();
+ assert!(document.set_attribute(host, "role", "button"));
+ append_text(&mut document, host, "host name");
+ let root = document
+ .attach_shadow_root(host, mode)
+ .expect("shadow root");
+ append_text(&mut document, root, "Shadow ");
+ append_element(&mut document, root, "slot");
+
+ assert_eq!(
+ node_by_id(&tree(&document), host)["name"]["value"],
+ "Shadow host name"
+ );
+ }
+}
+
+#[test]
+fn ax_tree_includes_nested_shadow_controls_and_host_ancestors() {
+ for mode in ["open", "closed"] {
+ let (mut document, host) = document_with_host();
+ let root = document
+ .attach_shadow_root(host, mode)
+ .expect("shadow root");
+ let nested_host = append_element(&mut document, root, "div");
+ let nested_root = document
+ .attach_shadow_root(nested_host, mode)
+ .expect("nested shadow root");
+ let button = append_element(&mut document, nested_root, "button");
+ append_text(&mut document, button, "Shadow action");
+
+ let nodes = tree(&document);
+ let button_node = node_by_id(&nodes, button);
+ assert_eq!(button_node["role"]["value"], "button");
+ assert_eq!(button_node["name"]["value"], "Shadow action");
+ assert_eq!(button_node["ignored"], false);
+ assert_eq!(
+ button_node["parentId"],
+ node_by_id(&nodes, nested_host)["nodeId"]
+ );
+ assert_eq!(
+ node_by_id(&nodes, nested_host)["parentId"],
+ node_by_id(&nodes, host)["nodeId"]
+ );
+
+ let ancestors = accessibility_node_and_ancestor_payloads_for_document(&document, button);
+ let backend_ids = ancestors
+ .iter()
+ .map(|node| node["backendDOMNodeId"].clone())
+ .collect::<Vec<_>>();
+ assert_eq!(
+ backend_ids,
+ [button, nested_host, host, document.document_node_id()]
+ .map(|id| json!(super::ax_roles::cdp_node_id(id)))
+ );
+ }
+}
+
+#[test]
+fn ax_tree_uses_slot_order_and_replaces_fallback_after_assignment_changes() {
+ let (mut document, host) = document_with_host();
+ let first = append_element(&mut document, host, "button");
+ assert!(document.set_attribute(first, "slot", "second"));
+ append_text(&mut document, first, "First");
+ let second = append_element(&mut document, host, "button");
+ assert!(document.set_attribute(second, "slot", "first"));
+ append_text(&mut document, second, "Second");
+ let unassigned = append_element(&mut document, host, "button");
+ append_text(&mut document, unassigned, "Unassigned");
+
+ let root = document
+ .attach_shadow_root(host, "open")
+ .expect("shadow root");
+ let first_slot = append_element(&mut document, root, "slot");
+ assert!(document.set_attribute(first_slot, "name", "first"));
+ let fallback = append_element(&mut document, first_slot, "button");
+ append_text(&mut document, fallback, "Fallback");
+ let second_slot = append_element(&mut document, root, "slot");
+ assert!(document.set_attribute(second_slot, "name", "second"));
+
+ let nodes = tree(&document);
+ assert_eq!(button_names(&nodes), ["Second", "First"]);
+ assert_eq!(
+ node_by_id(&nodes, second)["parentId"],
+ node_by_id(&nodes, first_slot)["nodeId"]
+ );
+
+ assert!(document.set_attribute(second, "slot", "missing"));
+ let nodes = tree(&document);
+ assert_eq!(button_names(&nodes), ["Fallback", "First"]);
+}
+
+#[test]
+fn ax_tree_names_shadow_controls_from_assigned_text_and_scoped_labels() {
+ let (mut document, host) = document_with_host();
+ let assigned = append_element(&mut document, host, "span");
+ append_text(&mut document, assigned, "Assigned name");
+ let document_id = document.document_node_id();
+ let outside_label = append_element(&mut document, document_id, "span");
+ assert!(document.set_attribute(outside_label, "id", "label"));
+ append_text(&mut document, outside_label, "Outside label");
+
+ let root = document
+ .attach_shadow_root(host, "open")
+ .expect("shadow root");
+ let button = append_element(&mut document, root, "button");
+ let slot = append_element(&mut document, button, "slot");
+ append_text(&mut document, slot, "Fallback name");
+ let label = append_element(&mut document, root, "span");
+ assert!(document.set_attribute(label, "id", "label"));
+ append_text(&mut document, label, "Shadow label");
+ let labelled_button = append_element(&mut document, root, "button");
+ assert!(document.set_attribute(labelled_button, "aria-labelledby", "label"));
+
+ let nodes = tree(&document);
+ assert_eq!(node_by_id(&nodes, button)["name"]["value"], "Assigned name");
+ assert_eq!(
+ node_by_id(&nodes, labelled_button)["name"]["value"],
+ "Shadow label"
+ );
+}
+
+#[test]
+fn ax_tree_inherits_aria_hidden_from_shadow_host() {
+ let (mut document, host) = document_with_host();
+ assert!(document.set_attribute(host, "aria-hidden", "true"));
+ let root = document
+ .attach_shadow_root(host, "open")
+ .expect("shadow root");
+ let button = append_element(&mut document, root, "button");
+ append_text(&mut document, button, "Hidden action");
+
+ let nodes = tree(&document);
+ let button_node = node_by_id(&nodes, button);
+ assert_eq!(button_node["ignored"], true);
+ assert_eq!(
+ button_node["ignoredReasons"][0]["name"],
+ "ariaHiddenSubtree"
+ );
+ assert_eq!(
+ button_node["ignoredReasons"][0]["value"]["relatedNodes"][0]["backendDOMNodeId"],
+ super::ax_roles::cdp_node_id(host)
+ );
+}
diff --git a/moli-protocol/src/domains/accessibility/tests.rs b/moli-protocol/src/domains/accessibility/tests.rs
index a3b9af97b..dd2ab9312 100644
--- a/moli-protocol/src/domains/accessibility/tests.rs
+++ b/moli-protocol/src/domains/accessibility/tests.rs
@@ -58,6 +58,219 @@ async fn complete_child_frame_lifecycle(ctx: &mut TestContext) {
);
}
+#[tokio::test(flavor = "multi_thread")]
+async fn query_ax_tree_shadow_root_uses_all_node_reference_kinds() {
+ for mode in ["open", "closed"] {
+ let mut ctx = TestContext::new();
+ load_page_async(
+ &mut ctx,
+ &format!(
+ r#"<!doctype html><html><body>
+ <div id='host'><button slot='action'>Slotted action</button><button>Unassigned action</button></div>
+ <button>Outside action</button>
+ <script>
+ globalThis.axQueryRoot = document.getElementById('host').attachShadow({{mode:'{mode}'}});
+ axQueryRoot.innerHTML = '<slot name="action"><button>Fallback action</button></slot><button>Shadow action</button>';
+ </script></body></html>"#
+ ),
+ )
+ .await;
+
+ ctx.process_async(json!({"id": 1, "method": "Accessibility.getFullAXTree"}))
+ .await;
+ let tree = ctx.take_response_by_id(1);
+ let nodes = tree["result"]["nodes"].as_array().expect("full AX nodes");
+ let mut expected_ids = ["Shadow action", "Slotted action"]
+ .map(|name| renderer_backed_ax_node_id(find_ax_node(nodes, "button", name)))
+ .to_vec();
+ expected_ids.sort();
+
+ ctx.process_async(json!({
+ "id": 2, "method": "Runtime.evaluate", "params": {"expression": "axQueryRoot"}
+ }))
+ .await;
+ let evaluated = ctx.take_response_by_id(2);
+ let object_id = evaluated["result"]["result"]["objectId"]
+ .as_str()
+ .expect("live shadow root object")
+ .to_owned();
+
+ ctx.process_async(json!({
+ "id": 3, "method": "DOM.getDocument", "params": {"depth": -1, "pierce": true}
+ }))
+ .await;
+ assert!(ctx.take_response_by_id(3)["result"]["root"].is_object());
+ ctx.process_async(json!({
+ "id": 4, "method": "DOM.requestNode", "params": {"objectId": object_id}
+ }))
+ .await;
+ let node_id = ctx.take_response_by_id(4)["result"]["nodeId"]
+ .as_u64()
+ .expect("shadow root frontend ID");
+ ctx.process_async(json!({
+ "id": 5, "method": "DOM.describeNode", "params": {"nodeId": node_id}
+ }))
+ .await;
+ let described = ctx.take_response_by_id(5);
+ assert_eq!(described["result"]["node"]["shadowRootType"], mode);
+ let backend_id = described["result"]["node"]["backendNodeId"]
+ .as_u64()
+ .expect("shadow root backend ID");
+
+ for (id, reference) in [
+ (6, json!({"objectId": object_id, "role": "button"})),
+ (7, json!({"nodeId": node_id, "role": "button"})),
+ (8, json!({"backendNodeId": backend_id, "role": "button"})),
+ ] {
+ ctx.process_async(json!({
+ "id": id, "method": "Accessibility.queryAXTree", "params": reference
+ }))
+ .await;
+ let response = ctx.take_response_by_id(id);
+ let queried = response["result"]["nodes"]
+ .as_array()
+ .unwrap_or_else(|| panic!("{mode} shadow root query: {response}"));
+ let mut names = queried
+ .iter()
+ .map(|node| node["name"]["value"].as_str().expect("button name"))
+ .collect::<Vec<_>>();
+ names.sort_unstable();
+ assert_eq!(
+ names,
+ ["Shadow action", "Slotted action"],
+ "{mode}: {response}"
+ );
+ let mut queried_ids = queried
+ .iter()
+ .map(renderer_backed_ax_node_id)
+ .collect::<Vec<_>>();
+ queried_ids.sort();
+ assert_eq!(queried_ids, expected_ids, "{mode}: {response}");
+ }
+ }
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn get_full_ax_tree_shadow_button_ref_supports_mouse_click() {
+ let mut ctx = TestContext::new();
+ load_page_async(
+ &mut ctx,
+ r#"<!doctype html><html><body style='margin:0'>
+ <div id='host'></div>
+ <script>
+ const root = document.getElementById('host').attachShadow({mode:'open'});
+ root.innerHTML = '<button style="width:160px;height:40px">Shadow action</button>';
+ globalThis.shadowClicks = 0;
+ root.querySelector('button').addEventListener('click', function() {
+ globalThis.shadowClicks++;
+ this.textContent = 'Clicked';
+ });
+ </script></body></html>"#,
+ )
+ .await;
+
+ ctx.process_async(json!({"id": 1, "method": "Accessibility.getFullAXTree"}))
+ .await;
+ let tree = ctx.take_response_by_id(1);
+ let nodes = tree["result"]["nodes"].as_array().expect("AX nodes");
+ let button = find_ax_node(nodes, "button", "Shadow action");
+ assert_eq!(button["ignored"], false);
+ let button_ax_id = renderer_backed_ax_node_id(button);
+ let button_backend_id = renderer_backend_dom_node_id(button);
+
+ ctx.process_async(json!({
+ "id": 2, "method": "DOM.resolveNode",
+ "params": {"backendNodeId": button_backend_id}
+ }))
+ .await;
+ let resolved = ctx.take_response_by_id(2);
+ let object_id = resolved["result"]["object"]["objectId"]
+ .as_str()
+ .expect("AX backend ID must resolve to the live button")
+ .to_owned();
+
+ for (id, method, params) in [
+ (
+ 3,
+ "Accessibility.getPartialAXTree",
+ json!({"objectId": object_id, "fetchRelatives": true}),
+ ),
+ (
+ 4,
+ "Accessibility.getAXNodeAndAncestors",
+ json!({"backendNodeId": button_backend_id}),
+ ),
+ (
+ 5,
+ "Accessibility.queryAXTree",
+ json!({"objectId": object_id, "role": "button", "accessibleName": "Shadow action"}),
+ ),
+ ] {
+ ctx.process_async(json!({"id": id, "method": method, "params": params}))
+ .await;
+ let response = ctx.take_response_by_id(id);
+ assert_eq!(
+ response["result"]["nodes"][0]["nodeId"], button_ax_id,
+ "{method}: {response}"
+ );
+ }
+
+ ctx.process_async(json!({
+ "id": 6, "method": "DOM.getBoxModel",
+ "params": {"backendNodeId": button_backend_id}
+ }))
+ .await;
+ let geometry = ctx.take_response_by_id(6);
+ let border = geometry["result"]["model"]["border"]
+ .as_array()
+ .expect("button border quad");
+ assert!(
+ geometry["result"]["model"]["width"]
+ .as_f64()
+ .expect("button width")
+ > 0.0
+ );
+ assert!(
+ geometry["result"]["model"]["height"]
+ .as_f64()
+ .expect("button height")
+ > 0.0
+ );
+ let x = (border[0].as_f64().expect("left") + border[4].as_f64().expect("right")) / 2.0;
+ let y = (border[1].as_f64().expect("top") + border[5].as_f64().expect("bottom")) / 2.0;
+ for (id, event, buttons) in [
+ (7, "mouseMoved", 0),
+ (8, "mousePressed", 1),
+ (9, "mouseReleased", 0),
+ ] {
+ ctx.process_async(json!({
+ "id": id, "method": "Input.dispatchMouseEvent",
+ "params": {"type": event, "x": x, "y": y, "button": "left", "buttons": buttons, "clickCount": 1}
+ })).await;
+ ctx.expect_result(id, json!({}), None);
+ }
+
+ ctx.process_async(json!({
+ "id": 10, "method": "Runtime.evaluate",
+ "params": {"expression": "globalThis.shadowClicks", "returnByValue": true}
+ }))
+ .await;
+ assert_eq!(ctx.take_response_by_id(10)["result"]["result"]["value"], 1);
+
+ ctx.process_async(json!({"id": 11, "method": "Accessibility.getFullAXTree"}))
+ .await;
+ let updated_tree = ctx.take_response_by_id(11);
+ let updated_nodes = updated_tree["result"]["nodes"]
+ .as_array()
+ .expect("updated AX nodes");
+ let updated_button = find_ax_node(updated_nodes, "button", "Clicked");
+ assert_eq!(updated_button["nodeId"], button_ax_id);
+ assert_eq!(
+ renderer_backend_dom_node_id(updated_button),
+ button_backend_id
+ );
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn accessibility_top_frame_snapshot_commands_use_explicit_dispatch() {
let mut ctx = TestContext::new();
diff --git a/moli-renderer-v8/src/runtime/page_dom.rs b/moli-renderer-v8/src/runtime/page_dom.rs
index d947a0638..f562fe719 100644
--- a/moli-renderer-v8/src/runtime/page_dom.rs
+++ b/moli-renderer-v8/src/runtime/page_dom.rs
@@ -2974,7 +2974,7 @@ impl PageVm {
let backend_node_ids = self.renderer_backend_node_id_map_for_owner_document(root_handle)?;
let payloads = {
let mut backend_node_id_for_node = |node_id| backend_node_ids.get(&node_id).copied();
- let document = self.vm().document_runtime.dom_host().dom();
+ let document = self.vm().document_runtime.dom_host();
document.node(root_handle)?;
moli_dom::accessibility::accessibility_tree_payloads_for_document_with_backend_node_ids(
document,
@@ -3006,7 +3006,7 @@ impl PageVm {
let backend_node_ids = self.renderer_backend_node_id_map_for_owner_document(handle)?;
let payload = {
let mut backend_node_id_for_node = |node_id| backend_node_ids.get(&node_id).copied();
- let document = self.vm().document_runtime.dom_host().dom();
+ let document = self.vm().document_runtime.dom_host();
moli_dom::accessibility::accessibility_node_payload_for_document_with_backend_node_ids(
document,
handle,
@@ -3120,7 +3120,7 @@ impl PageVm {
&mut self,
reference: RendererDomNodeReference,
build_payloads: impl FnOnce(
- &crate::dom::native::NativeDom,
+ &DomHost,
DomHandle,
&HashMap<DomHandle, u32>,
) -> Option<Vec<serde_json::Value>>,
@@ -3141,7 +3141,7 @@ impl PageVm {
self.renderer_backend_node_id_map_for_document_handle(document_handle)?;
let payloads = {
let mut backend_node_id_for_node = |node_id| backend_node_ids.get(&node_id).copied();
- let document = self.vm().document_runtime.dom_host().dom();
+ let document = self.vm().document_runtime.dom_host();
document.node(document_handle)?;
moli_dom::accessibility::accessibility_tree_payloads_for_document_with_backend_node_ids(
document,
@@ -3167,7 +3167,7 @@ impl PageVm {
self.renderer_backend_node_id_map_for_document_handle(document_handle)?;
let payload = {
let mut backend_node_id_for_node = |node_id| backend_node_ids.get(&node_id).copied();
- let document = self.vm().document_runtime.dom_host().dom();
+ let document = self.vm().document_runtime.dom_host();
moli_dom::accessibility::accessibility_node_payload_for_document_with_backend_node_ids(
document,
document_handle,
@@ -3185,7 +3185,7 @@ impl PageVm {
&mut self,
handle: DomHandle,
build_payloads: impl FnOnce(
- &crate::dom::native::NativeDom,
+ &DomHost,
DomHandle,
&HashMap<DomHandle, u32>,
) -> Option<Vec<serde_json::Value>>,
@@ -3193,7 +3193,7 @@ impl PageVm {
let frame_id = self.vm().child_frame_id_for_live_node_handle(handle);
let backend_node_ids = self.renderer_backend_node_id_map_for_owner_document(handle)?;
let payloads = {
- let document = self.vm().document_runtime.dom_host().dom();
+ let document = self.vm().document_runtime.dom_host();
build_payloads(document, handle, &backend_node_ids)?
};
Some(RendererAccessibilityPayloadsForObjectId {
@@ -3272,7 +3272,7 @@ impl PageVm {
inspector_session_id: Option<&str>,
object_id: &str,
build_payloads: impl FnOnce(
- &crate::dom::native::NativeDom,
+ &DomHost,
DomHandle,
&HashMap<DomHandle, u32>,
) -> Option<Vec<serde_json::Value>>,