Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust
Rust ai-agentsai-toolsbrowserbrowser-automationcloud-browserheadlessheadless-browserkitesurfplaywrightpuppeteerrustservoweb-crawlerweb-crawlingweb-scraperweb-scraping
perf(accessibility): build request projections on demand
ldm0ae20434893ff
diff --git a/moli-cdp-smoke/README.md b/moli-cdp-smoke/README.mdindex afdb6cf85..0b38c339c 100644--- a/moli-cdp-smoke/README.md+++ b/moli-cdp-smoke/README.md@@ -173,7 +173,10 @@ passed one run against each engine; use `--endpoint URL` for the Chromium run.The Puppeteer accessibility visibility workflow was calibrated on 2026-10-09with the same client and Chromium executable, then run unchanged against Moli.`puppeteer_accessibility_visibility.mjs` starts with a fresh Document and checks-both snapshot modes for computed display, visibility overrides, HTML inert,+an objectId partial AX request before the first full snapshot. It resolves an+external hidden label, observes label text changes, and preserves AX and backend+refs. Both snapshot modes then check computed display, visibility overrides,+HTML inert,explicit content-visibility:hidden, hidden/until-found CSS overrides, andhidden ARIA reference names.Closed shadow styles, :host rules, and assigned-slot visibility participate indiff --git a/moli-cdp-smoke/moli_cdp_smoke/puppeteer_accessibility_visibility.mjs b/moli-cdp-smoke/moli_cdp_smoke/puppeteer_accessibility_visibility.mjsindex fa58d1a24..ab83ca83a 100644--- a/moli-cdp-smoke/moli_cdp_smoke/puppeteer_accessibility_visibility.mjs+++ b/moli-cdp-smoke/moli_cdp_smoke/puppeteer_accessibility_visibility.mjs@@ -51,11 +51,37 @@ export async function runPuppeteerAccessibilityVisibilitySmoke(page) {'Slotted visible action', 'Transparent action', 'Until found override action','Visibility override action', 'Visible action',];- for (const interestingOnly of [true, false]) {- assert.deepEqual(buttonNames(await page.accessibility.snapshot({interestingOnly})), expected);- }const client = await page.createCDPSession();try {+ // Resolve an AX-external hidden label before any full AX snapshot. A local+ // request must observe its dependencies and discard them between commands.+ const remote = (await client.send('Runtime.evaluate', {+ expression: 'document.querySelector("button[aria-labelledby]")',+ })).result;+ assert.ok(remote.objectId);+ try {+ const partial = async () => (await client.send('Accessibility.getPartialAXTree', {+ objectId: remote.objectId, fetchRelatives: false,+ })).nodes[0];+ const first = await partial();+ assert.equal(first.ignored, false);+ assert.equal(first.name.value, 'Hidden root hidden aria child');+ await page.evaluate(() => {+ document.getElementById('hidden-label').firstChild.nodeValue = 'Updated root';+ });+ const updated = await partial();+ assert.equal(updated.name.value, 'Updated root hidden aria child');+ assert.equal(updated.nodeId, first.nodeId);+ assert.equal(updated.backendDOMNodeId, first.backendDOMNodeId);+ await page.evaluate(() => {+ document.getElementById('hidden-label').firstChild.nodeValue = 'Hidden root';+ });+ } finally {+ await client.send('Runtime.releaseObject', {objectId: remote.objectId});+ }+ for (const interestingOnly of [true, false]) {+ assert.deepEqual(buttonNames(await page.accessibility.snapshot({interestingOnly})), expected);+ }const initial = (await client.send('Accessibility.getFullAXTree')).nodes.find(node => !node.ignored && node.name?.value === 'Visible action');assert.ok(initial?.backendDOMNodeId);@@ -93,7 +119,7 @@ export async function runPuppeteerAccessibilityVisibilitySmoke(page) {assert.ok(changed.includes('Stylesheet hidden action'));assert.ok(changed.includes('Shadow hidden action'));assert.ok(!changed.includes('Hidden action'));- return {trustedClicks: 2, stableReference: true, shadowMode: 'closed', cssomRuleChanges: 2};+ return {trustedClicks: 2, stableReference: true, shadowMode: 'closed', cssomRuleChanges: 2, coldPartial: true};} finally {await client.detach();}diff --git a/moli-dom/src/accessibility/ax_dom.rs b/moli-dom/src/accessibility/ax_dom.rsindex 443e81337..cf2debe6e 100644--- a/moli-dom/src/accessibility/ax_dom.rs+++ b/moli-dom/src/accessibility/ax_dom.rs@@ -1,6 +1,6 @@use crate::{NodeData, NodeId, native::DomHost};-use super::ax_projection::AxTreeProjection;+use super::ax_projection::{AxTreeProjection, AxUnavailable};pub(super) const MAX_AX_NAME_VISITED_OBJECTS: usize = 100;@@ -51,16 +51,12 @@ fn composed_child_ids(document: &DomHost, node_id: NodeId) -> Option<Vec<NodeId>pub(super) fn ax_content_text(document: &DomHost,- projection: &AxTreeProjection,+ projection: &mut AxTreeProjection<'_, '_>,node_id: NodeId,include_hidden: bool,-) -> String {- if projection- .state(node_id)- .is_some_and(|state| state.hides_contents)- && !include_hidden- {- return String::new();+) -> Result<String, AxUnavailable> {+ if projection.state(node_id)?.hides_contents && !include_hidden {+ return Ok(String::new());}let mut text = String::new();let mut pending = ax_child_ids_reversed(document, node_id)@@ -79,9 +75,7 @@ pub(super) fn ax_content_text(let Some(node) = document.node(node_id) else {continue;};- let Some(state) = projection.state(node_id) else {- continue;- };+ let state = projection.state(node_id)?;if state.inert_reason.is_some()|| (!include_hidden && (state.not_rendered || state.aria_hidden_root.is_some())){@@ -105,5 +99,5 @@ pub(super) fn ax_content_text(_ => pending.extend(ax_child_ids_reversed(document, node_id).map(Some)),}}- text+ Ok(text)}diff --git a/moli-dom/src/accessibility/ax_projection.rs b/moli-dom/src/accessibility/ax_projection.rsindex 07c3eb8da..89520d103 100644--- a/moli-dom/src/accessibility/ax_projection.rs+++ b/moli-dom/src/accessibility/ax_projection.rs@@ -1,3 +1,5 @@+use std::collections::HashMap;+use crate::{NodeData, NodeId,forms::InputType,@@ -5,21 +7,28 @@ use crate::{};use super::{- AccessibilityFrameState, AccessibilityInput,+ AccessibilityFrameState, AccessibilityInput, AccessibilityStyleSource,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-/// still included in the inspector tree, while DOM-only nodes may have no AX-/// object at all. Moli builds the same semantic boundary on demand so-/// the CDP serializer never has to treat the DOM tree as an AX tree.-pub(super) struct AxTreeProjection {- nodes: Vec<Option<AxProjectedNode>>,- states: Vec<Option<AxNodeState>>,+/// Request-local memoization. Resolving a parent never expands its children,+/// and expanding children never computes their names or grandchildren.+pub(super) struct AxTreeProjection<'dom, 'styles> {+ pub(super) document: &'dom DomHost,+ styles: &'styles mut dyn AccessibilityStyleSource,+ root: NodeId,+ modal: Option<NodeId>,+ frame_inert: bool,+ states: HashMap<NodeId, AxNodeState>,+ entries: HashMap<NodeId, AxProjectionEntry>,+ children: HashMap<NodeId, Vec<NodeId>>,}+/// Required DOM/style input is unavailable. This is distinct from a valid DOM+/// node that has no AX object.+#[derive(Debug)]+pub(super) struct AxUnavailable;+#[derive(Clone, Copy)]pub(super) struct AxNodeState {pub(super) not_rendered: bool,@@ -36,12 +45,19 @@ impl AxNodeState {}}+#[derive(Clone, Copy)]pub(super) struct AxProjectedNode {pub(super) parent: Option<NodeId>,- pub(super) children: Vec<NodeId>,pub(super) ignored_reason: Option<AxIgnoredReason>,}+#[derive(Clone, Copy)]+enum AxProjectionEntry {+ Included(AxProjectedNode),+ Transparent { parent: Option<NodeId> },+ Excluded,+}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub(super) enum AxIgnoredReason {Uninteresting,@@ -60,11 +76,11 @@ enum AxNodeInclusion {ExcludeSubtree,}-impl AxTreeProjection {- pub(super) fn build_for_node(- document: &DomHost,+impl<'dom, 'styles> AxTreeProjection<'dom, 'styles> {+ pub(super) fn new(+ document: &'dom DomHost,node_id: NodeId,- styles: &AccessibilityInput,+ input: &'styles mut AccessibilityInput<'_>,) -> Option<Self> {let node_id = document.shadow_root_host(node_id).unwrap_or(node_id);let node = document.node(node_id)?;@@ -73,189 +89,197 @@ impl AxTreeProjection {} else {node.owner_document()?};- let mut nodes = Vec::with_capacity(document.len());- nodes.resize_with(document.len(), || None);- let mut projection = Self {- nodes,- states: vec![None; document.len()],- };- projection.observe_states(document, root, styles)?;- projection.visit(document, root);- Some(projection)- }-- pub(super) fn state(&self, node_id: NodeId) -> Option<AxNodeState> {- self.states.get(node_id.index()).copied().flatten()- }-- pub(super) fn is_rendered(&self, node_id: NodeId) -> bool {- self.node(node_id)- .is_some_and(|node| node.ignored_reason != Some(AxIgnoredReason::NotRendered))+ Some(Self {+ document,+ styles: &mut *input.styles,+ root,+ modal: document.active_modal_dialog_for_document(root),+ frame_inert: input.frame_state == AccessibilityFrameState::Inert,+ states: HashMap::new(),+ entries: HashMap::new(),+ children: HashMap::new(),+ })}- fn observe_states(- &mut self,- document: &DomHost,- root: NodeId,- styles: &AccessibilityInput,- ) -> Option<()> {- let modal = document.active_modal_dialog_for_document(root);- let frame_inert = styles.frame_state == AccessibilityFrameState::Inert;- let mut pending = vec![root];+ pub(super) fn state(&mut self, node_id: NodeId) -> Result<AxNodeState, AxUnavailable> {let mut ancestors = Vec::new();- while let Some(node_id) = pending.pop() {- // Also classify DOM-only label roots and unassigned light content.- // Memoized ancestry observes each node once, including slot links.- let mut current = Some(node_id);- while let Some(id) = current {- if self.state(id).is_some() {- break;- }- ancestors.push(id);- current = document.composed_parent(id);+ let mut current = Some(node_id);+ while let Some(id) = current {+ if self.states.contains_key(&id) {+ break;}- while let Some(id) = ancestors.pop() {- let node = document.node(id)?;- let parent = document- .composed_parent(id)- .and_then(|parent| self.state(parent));- let mut state = AxNodeState {- not_rendered: id != root- && parent.is_none_or(|parent| parent.not_rendered || parent.hides_contents),- visibility_visible: parent.is_none_or(|parent| parent.visibility_visible),- hides_contents: false,- block_level: false,- aria_hidden_root: parent.and_then(|parent| parent.aria_hidden_root),- inert_reason: parent.and_then(|parent| parent.inert_reason).or_else(|| {- if id != root {- None- } else if frame_inert {- Some(AxIgnoredReason::InertFrame)- } else {- modal.map(|root| AxIgnoredReason::ActiveModalDialog { root })- }- }),- };- if Some(id) == modal {- state.inert_reason = frame_inert.then_some(AxIgnoredReason::InertFrame);- }- if let Some(element) = node.as_element() {- let style = styles.element(id)?;- state.not_rendered |= style.display_none;- state.visibility_visible = style.visibility_visible;- state.hides_contents = style.hides_contents;- state.block_level = style.block_level;- if ax_aria_hidden(element) {- state.aria_hidden_root = state.aria_hidden_root.or(Some(id));- }- if element.namespace() == "http://www.w3.org/1999/xhtml"- && element.has_attribute("inert")- {- state.inert_reason = Some(AxIgnoredReason::InertSubtree { root: id });+ ancestors.push(id);+ current = self.document.composed_parent(id);+ }+ while let Some(id) = ancestors.pop() {+ let node = self.document.node(id).ok_or(AxUnavailable)?;+ let parent = self+ .document+ .composed_parent(id)+ .and_then(|id| self.states.get(&id));+ let mut state = AxNodeState {+ not_rendered: id != self.root+ && parent.is_none_or(|parent| parent.not_rendered || parent.hides_contents),+ visibility_visible: parent.is_none_or(|parent| parent.visibility_visible),+ hides_contents: false,+ block_level: false,+ aria_hidden_root: parent.and_then(|parent| parent.aria_hidden_root),+ inert_reason: parent.and_then(|parent| parent.inert_reason).or_else(|| {+ if id != self.root {+ None+ } else if self.frame_inert {+ Some(AxIgnoredReason::InertFrame)+ } else {+ self.modal+ .map(|root| AxIgnoredReason::ActiveModalDialog { root })}+ }),+ };+ if Some(id) == self.modal {+ state.inert_reason = self.frame_inert.then_some(AxIgnoredReason::InertFrame);+ }+ if let Some(element) = node.as_element() {+ let style = self.styles.element_style(id).ok_or(AxUnavailable)?;+ state.not_rendered |= style.display_none;+ state.visibility_visible = style.visibility_visible;+ state.hides_contents = style.hides_contents;+ state.block_level = style.block_level;+ if ax_aria_hidden(element) {+ state.aria_hidden_root = state.aria_hidden_root.or(Some(id));+ }+ if element.namespace() == "http://www.w3.org/1999/xhtml"+ && element.has_attribute("inert")+ {+ state.inert_reason = Some(AxIgnoredReason::InertSubtree { root: id });}- self.states[id.index()] = Some(state);}- pending.extend(document.child_ids_reversed(node_id));- if let Some(shadow) = document.shadow_root_handle(node_id) {- pending.push(shadow);+ self.states.insert(id, state);+ }+ self.states.get(&node_id).copied().ok_or(AxUnavailable)+ }++ fn entry(&mut self, node_id: NodeId) -> Result<AxProjectionEntry, AxUnavailable> {+ let mut ancestors = Vec::new();+ let mut current = Some(node_id);+ while let Some(id) = current {+ if self.entries.contains_key(&id) {+ break;}+ ancestors.push(id);+ current = self.document.composed_parent(id);}- Some(())+ while let Some(id) = ancestors.pop() {+ let node = self.document.node(id).ok_or(AxUnavailable)?;+ let parent = self+ .document+ .composed_parent(id)+ .and_then(|id| self.entries.get(&id).copied().map(|entry| (id, entry)));+ let projected_parent = match parent {+ Some((id, AxProjectionEntry::Included(_))) => Some(id),+ Some((_, AxProjectionEntry::Transparent { parent })) => parent,+ _ if id == self.root => None,+ _ => {+ self.entries.insert(id, AxProjectionEntry::Excluded);+ continue;+ }+ };+ let entry = match ax_node_inclusion(node) {+ AxNodeInclusion::ExcludeSubtree => AxProjectionEntry::Excluded,+ AxNodeInclusion::ExcludeNode => AxProjectionEntry::Transparent {+ parent: projected_parent,+ },+ AxNodeInclusion::Include => {+ let state = self.state(id)?;+ let ignored_reason = if node.is_document() {+ None+ } else {+ state+ .not_rendered+ .then_some(AxIgnoredReason::NotRendered)+ .or(state.inert_reason)+ .or_else(|| {+ (!state.visibility_visible).then_some(AxIgnoredReason::NotVisible)+ })+ .or_else(|| {+ state+ .aria_hidden_root+ .map(|root| AxIgnoredReason::AriaHiddenSubtree { root })+ })+ .or_else(|| {+ node.as_element()+ .is_some_and(|element| {+ ax_is_uninteresting_container(self.document, id, element)+ })+ .then_some(AxIgnoredReason::Uninteresting)+ })+ };+ AxProjectionEntry::Included(AxProjectedNode {+ parent: projected_parent,+ ignored_reason,+ })+ }+ };+ self.entries.insert(id, entry);+ }+ self.entries.get(&node_id).copied().ok_or(AxUnavailable)}- pub(super) fn node(&self, node_id: NodeId) -> Option<&AxProjectedNode> {- self.nodes.get(node_id.index())?.as_ref()+ pub(super) fn node(+ &mut self,+ node_id: NodeId,+ ) -> Result<Option<AxProjectedNode>, AxUnavailable> {+ Ok(match self.entry(node_id)? {+ AxProjectionEntry::Included(node) => Some(node),+ _ => None,+ })}- pub(super) fn contains(&self, node_id: NodeId) -> bool {- self.node(node_id).is_some()+ pub(super) fn is_rendered(&mut self, node_id: NodeId) -> Result<bool, AxUnavailable> {+ Ok(self+ .node(node_id)?+ .is_some_and(|node| node.ignored_reason != Some(AxIgnoredReason::NotRendered)))}- pub(super) fn unignored_children(&self, node_id: NodeId) -> Vec<NodeId> {+ pub(super) fn children(&mut self, node_id: NodeId) -> Result<Vec<NodeId>, AxUnavailable> {+ if let Some(children) = self.children.get(&node_id) {+ return Ok(children.clone());+ }let mut children = Vec::new();- self.collect_unignored_children(node_id, &mut children);- children+ if self.node(node_id)?.is_some() {+ let mut pending = ax_child_ids_reversed(self.document, node_id).collect::<Vec<_>>();+ while let Some(child_id) = pending.pop() {+ match self.entry(child_id)? {+ AxProjectionEntry::Included(_) => children.push(child_id),+ AxProjectionEntry::Transparent { .. } => {+ pending.extend(ax_child_ids_reversed(self.document, child_id));+ }+ AxProjectionEntry::Excluded => {}+ }+ }+ }+ self.children.insert(node_id, children.clone());+ Ok(children)}- fn collect_unignored_children(&self, node_id: NodeId, out: &mut Vec<NodeId>) {- let Some(node) = self.node(node_id) else {- return;- };-- let mut pending = node.children.iter().rev().copied().collect::<Vec<_>>();+ pub(super) fn unignored_children(+ &mut self,+ node_id: NodeId,+ ) -> Result<Vec<NodeId>, AxUnavailable> {+ let mut children = Vec::new();+ let mut pending = self.children(node_id)?;+ pending.reverse();while let Some(child_id) = pending.pop() {- let Some(child) = self.node(child_id) else {- continue;- };- if !self.is_rendered(child_id) {+ let child = self.node(child_id)?.ok_or(AxUnavailable)?;+ if child.ignored_reason == Some(AxIgnoredReason::NotRendered) {continue;}if child.ignored_reason.is_some() {- pending.extend(child.children.iter().rev().copied());+ pending.extend(self.children(child_id)?.into_iter().rev());} else {- out.push(child_id);+ children.push(child_id);}}- }-- fn visit(&mut self, document: &DomHost, root: NodeId) {- let mut pending = vec![(root, None)];- while let Some((node_id, projected_parent)) = pending.pop() {- let Some(node) = document.node(node_id) else {- continue;- };-- match ax_node_inclusion(node) {- AxNodeInclusion::ExcludeSubtree => continue,- AxNodeInclusion::ExcludeNode => {- pending.extend(- ax_child_ids_reversed(document, node_id)- .map(|child_id| (child_id, projected_parent)),- );- continue;- }- AxNodeInclusion::Include => {}- }-- let state = self.state(node_id).expect("observed composed node");- let ignored_reason = state- .not_rendered- .then_some(AxIgnoredReason::NotRendered)- .or(state.inert_reason)- .or_else(|| (!state.visibility_visible).then_some(AxIgnoredReason::NotVisible))- .or_else(|| {- state- .aria_hidden_root- .map(|root| AxIgnoredReason::AriaHiddenSubtree { root })- })- .or_else(|| {- node.as_element()- .is_some_and(|element| {- ax_is_uninteresting_container(document, node_id, element)- })- .then_some(AxIgnoredReason::Uninteresting)- });-- self.nodes[node_id.index()] = Some(AxProjectedNode {- parent: projected_parent,- children: Vec::new(),- ignored_reason: if node.is_document() {- None- } else {- ignored_reason- },- });- if let Some(parent_id) = projected_parent- && let Some(parent) = self.nodes[parent_id.index()].as_mut()- {- parent.children.push(node_id);- }-- pending.extend(- ax_child_ids_reversed(document, node_id).map(|child_id| (child_id, Some(node_id))),- );- }+ Ok(children)}}@@ -380,7 +404,7 @@ mod tests {use crate::native::NativeDom;#[test]- fn build_handles_deep_dom_without_call_stack_growth() {+ fn parent_resolution_handles_deep_dom_without_expanding_children() {const DEPTH: usize = 20_000;let mut document = NativeDom::new_html(@@ -397,16 +421,22 @@ mod tests {}let document = DomHost::from_dom(document);- let projection = AxTreeProjection::build_for_node(- &document,- document.document_node_id(),- &AccessibilityInput::visible_fixture(&document),- )- .expect("fixture projection");+ let mut styles = super::super::tests::FixtureStyles::visible(&document);+ let mut input = AccessibilityInput::new(&mut styles, AccessibilityFrameState::Active);+ let mut projection =+ AxTreeProjection::new(&document, document.document_node_id(), &mut input)+ .expect("fixture projection");assert_eq!(- projection.node(parent).and_then(|node| node.parent),+ projection+ .node(parent)+ .expect("fixture state")+ .and_then(|node| node.parent),document.node(parent).and_then(Node::parent_node_id));+ assert!(+ projection.children.is_empty(),+ "resolving ancestors must not expand children"+ );}#[test]@@ -416,7 +446,13 @@ mod tests {let root = NodeId::new(0);let chain_leaf = NodeId::new(DEPTH);let sibling = NodeId::new(DEPTH + 1);- let mut nodes = Vec::with_capacity(DEPTH + 2);+ let document = DomHost::from_dom(NativeDom::new_html(+ url::Url::parse("https://example.test/").expect("document URL"),+ ));+ let mut styles = super::super::tests::FixtureStyles::visible(&document);+ let mut input = AccessibilityInput::new(&mut styles, AccessibilityFrameState::Active);+ let mut projection =+ AxTreeProjection::new(&document, root, &mut input).expect("projection");for index in 0..=DEPTH + 1 {let children = if index == 0 {@@ -434,20 +470,21 @@ mod tests {Some(NodeId::new(index - 1))};- nodes.push(Some(AxProjectedNode {- parent,- children,- ignored_reason: (index > 0 && index < DEPTH)- .then_some(AxIgnoredReason::Uninteresting),- }));+ projection.children.insert(NodeId::new(index), children);+ projection.entries.insert(+ NodeId::new(index),+ AxProjectionEntry::Included(AxProjectedNode {+ parent,+ ignored_reason: (index > 0 && index < DEPTH)+ .then_some(AxIgnoredReason::Uninteresting),+ }),+ );}- let projection = AxTreeProjection {- nodes,- states: Vec::new(),- };assert_eq!(- projection.unignored_children(root),+ projection+ .unignored_children(root)+ .expect("fixture children"),vec![chain_leaf, sibling]);}diff --git a/moli-dom/src/accessibility/ax_properties.rs b/moli-dom/src/accessibility/ax_properties.rsindex cd5b16d31..8da671480 100644--- a/moli-dom/src/accessibility/ax_properties.rs+++ b/moli-dom/src/accessibility/ax_properties.rs@@ -8,13 +8,10 @@ use std::collections::HashSet;use url::Url;use super::ax_dom::{MAX_AX_NAME_VISITED_OBJECTS, ax_content_text};-use super::ax_projection::AxTreeProjection;+use super::ax_projection::{AxTreeProjection, AxUnavailable};use super::ax_roles::{ax_role, heading_level};-// Blink bounds text-alternative traversal with-// `kMaxDescendantsForTextAlternativeComputation`. Keep relation recursion-// within the same visited-object budget so hostile ARIA graphs cannot grow the-// native call stack without bound.+// Keep relation recursion within Blink's text-alternative object budget.#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum AxNameTraversal {Direct,@@ -41,9 +38,13 @@ impl AxNameTraversal {}}-pub(super) fn ax_name(document: &DomHost, projection: &AxTreeProjection, node: &Node) -> String {+pub(super) fn ax_name(+ document: &DomHost,+ projection: &mut AxTreeProjection<'_, '_>,+ node: &Node,+) -> Result<String, AxUnavailable> {match node.kind() {- NodeData::Document(_) => ax_document_name(document),+ NodeData::Document(_) => Ok(ax_document_name(document)),NodeData::Element(_) => ax_node_name(document,projection,@@ -51,65 +52,53 @@ pub(super) fn ax_name(document: &DomHost, projection: &AxTreeProjection, node: &AxNameTraversal::Direct,&mut HashSet::new(),),- NodeData::Text(text) => normalize_ax_whitespace(text.data()),- NodeData::CDataSection(cdata) => normalize_ax_whitespace(cdata.data()),- NodeData::Comment(_)- | NodeData::ProcessingInstruction(_)- | NodeData::DocumentType(_)- | NodeData::DocumentFragment(_) => String::new(),+ NodeData::Text(text) => Ok(normalize_ax_whitespace(text.data())),+ NodeData::CDataSection(cdata) => Ok(normalize_ax_whitespace(cdata.data())),+ _ => Ok(String::new()),}}-/// Computes the subset of the accessible-name algorithm that is observable in-/// the CDP AX tree. The source order mirrors Blink's `TextAlternative`:-/// `aria-labelledby`, `aria-label`, native HTML alternatives, contents, then-/// tooltip-style fallbacks.+/// Source order follows Blink's TextAlternative: ARIA relations, aria-label,+/// native HTML alternatives, contents, then tooltip-style fallbacks.fn ax_node_name(document: &DomHost,- projection: &AxTreeProjection,+ projection: &mut AxTreeProjection<'_, '_>,node_id: NodeId,traversal: AxNameTraversal,visited: &mut HashSet<NodeId>,-) -> String {- let Some(state) = projection.state(node_id) else {- return String::new();- };+) -> Result<String, AxUnavailable> {+ let state = projection.state(node_id)?;if state.inert_reason.is_some() || (!traversal.includes_hidden() && state.hidden_for_name()) {- return String::new();+ return Ok(String::new());}if visited.len() >= MAX_AX_NAME_VISITED_OBJECTS || !visited.insert(node_id) {- return String::new();+ return Ok(String::new());}- let name = match document.node(node_id) {- Some(node) => match node.kind() {- NodeData::Element(element) => ax_element_name(- document, projection, node_id, node, element, traversal, visited,- ),- NodeData::Text(text) => normalize_ax_whitespace(text.data()),- NodeData::CDataSection(cdata) => normalize_ax_whitespace(cdata.data()),- NodeData::Document(_) => ax_document_name(document),- NodeData::Comment(_)- | NodeData::ProcessingInstruction(_)- | NodeData::DocumentType(_)- | NodeData::DocumentFragment(_) => String::new(),- },- None => String::new(),+ let node = document.node(node_id).ok_or(AxUnavailable)?;+ let name = match node.kind() {+ NodeData::Element(element) => ax_element_name(+ document, projection, node_id, node, element, traversal, visited,+ )?,+ NodeData::Text(text) => normalize_ax_whitespace(text.data()),+ NodeData::CDataSection(cdata) => normalize_ax_whitespace(cdata.data()),+ NodeData::Document(_) => ax_document_name(document),+ _ => String::new(),};visited.remove(&node_id);- name+ Ok(name)}fn ax_element_name(document: &DomHost,- projection: &AxTreeProjection,+ projection: &mut AxTreeProjection<'_, '_>,node_id: NodeId,node: &Node,element: &Element,traversal: AxNameTraversal,visited: &mut HashSet<NodeId>,-) -> String {+) -> Result<String, AxUnavailable> {if traversal.follows_aria_labelledby()&& let Some(labelled_by) = element.attribute("aria-labelledby")@@ -121,43 +110,39 @@ fn ax_element_name(.filter_map(|id| ax_element_by_id(document, tree_scope, id)).collect::<Vec<_>>();if !label_ids.is_empty() {- return label_ids- .into_iter()- .map(|label_id| {- let include_hidden = projection- .state(label_id)- .is_some_and(|state| state.hidden_for_name());- ax_node_name(- document,- projection,- label_id,- AxNameTraversal::AriaReference { include_hidden },- visited,- )- })- .filter(|part| !part.is_empty())- .collect::<Vec<_>>()- .join(" ");+ let mut parts = Vec::new();+ for label_id in label_ids {+ let include_hidden = projection.state(label_id)?.hidden_for_name();+ let part = ax_node_name(+ document,+ projection,+ label_id,+ AxNameTraversal::AriaReference { include_hidden },+ visited,+ )?;+ if !part.is_empty() {+ parts.push(part);+ }+ }+ return Ok(parts.join(" "));}}if let Some(aria_label) = element.attribute("aria-label") {let aria_label = normalize_ax_whitespace(aria_label);if !aria_label.is_empty() {- return aria_label;+ return Ok(aria_label);}}if let Some(native_name) =- ax_native_element_name(document, projection, node_id, element, visited)+ ax_native_element_name(document, projection, node_id, element, visited)?{- return native_name;+ return Ok(native_name);}- // A node reached through aria-labelledby or a native <label> contributes- // its whole subtree. Outside that recursive context, only roles whose name- // comes from contents may consume descendant text; generic containers and- // text controls expose that text through children or AXValue instead.+ // Relation targets contribute contents independently of their AX inclusion.+ // Direct traversal retains the role's name-from-content restrictions.let content =if traversal.includes_contents() || ax_name_comes_from_contents(document, node, element) {normalize_ax_whitespace(&ax_content_text(@@ -165,15 +150,15 @@ fn ax_element_name(projection,node_id,traversal.includes_hidden(),- ))+ )?)} else {String::new()};if !content.is_empty() {- return content;+ return Ok(content);}- element+ Ok(element.attribute("title").map(normalize_ax_whitespace).filter(|title| !title.is_empty())@@ -187,39 +172,37 @@ fn ax_element_name(.flatten().filter(|placeholder| !placeholder.is_empty())})- .unwrap_or_default()+ .unwrap_or_default())}fn ax_native_element_name(document: &DomHost,- projection: &AxTreeProjection,+ projection: &mut AxTreeProjection<'_, '_>,node_id: NodeId,element: &Element,visited: &mut HashSet<NodeId>,-) -> Option<String> {+) -> Result<Option<String>, AxUnavailable> {if ax_is_labelable(element) {let labels = ax_labels_for_control(document, node_id);if !labels.is_empty() {- return Some(- labels- .into_iter()- .map(|label_id| {- ax_node_name(- document,- projection,- label_id,- AxNameTraversal::NativeLabel,- visited,- )- })- .filter(|part| !part.is_empty())- .collect::<Vec<_>>()- .join(" "),- );+ let mut parts = Vec::new();+ for label_id in labels {+ let part = ax_node_name(+ document,+ projection,+ label_id,+ AxNameTraversal::NativeLabel,+ visited,+ )?;+ if !part.is_empty() {+ parts.push(part);+ }+ }+ return Ok(Some(parts.join(" ")));}}- match element.local_name() {+ Ok(match element.local_name() {"input" => match element.input_type() {InputType::Button => Some(normalize_ax_whitespace(&element.input_value())),InputType::Submit => Some(ax_input_button_name(element, "Submit")),@@ -236,7 +219,7 @@ fn ax_native_element_name(},"img" | "area" => element.attribute("alt").map(normalize_ax_whitespace),_ => None,- }+ })}fn ax_input_button_name(element: &Element, default_name: &str) -> String {@@ -899,10 +882,19 @@ mod tests {fn node_name(document: &NativeDom, node_id: NodeId) -> String {let host = DomHost::from_dom(document.clone());- let styles = super::super::AccessibilityInput::visible_fixture(&host);- let projection =- AxTreeProjection::build_for_node(&host, node_id, &styles).expect("fixture projection");- ax_name(&host, &projection, host.node(node_id).expect("named node"))+ let mut styles = super::super::tests::FixtureStyles::visible(&host);+ let mut input = super::super::AccessibilityInput::new(+ &mut styles,+ super::super::AccessibilityFrameState::Active,+ );+ let mut projection =+ AxTreeProjection::new(&host, node_id, &mut input).expect("fixture projection");+ ax_name(+ &host,+ &mut projection,+ host.node(node_id).expect("named node"),+ )+ .expect("fixture name")}#[test]diff --git a/moli-dom/src/accessibility/ax_roles.rs b/moli-dom/src/accessibility/ax_roles.rsindex c8016d712..f4e22928c 100644--- a/moli-dom/src/accessibility/ax_roles.rs+++ b/moli-dom/src/accessibility/ax_roles.rs@@ -302,10 +302,6 @@ pub(super) fn ordered_list_item_index(None}-pub(super) fn cdp_node_id(node_id: NodeId) -> u32 {- (node_id.index() + 1) as u32-}-#[cfg(test)]mod tests {use super::*;diff --git a/moli-dom/src/accessibility/ax_styles.rs b/moli-dom/src/accessibility/ax_styles.rsindex a6d5986e3..4d6e979ae 100644--- a/moli-dom/src/accessibility/ax_styles.rs+++ b/moli-dom/src/accessibility/ax_styles.rs@@ -10,8 +10,14 @@ pub struct AccessibilityStyle {pub block_level: bool,}-pub struct AccessibilityInput {- elements: Vec<Option<AccessibilityStyle>>,+/// Reads from one synchronous style observation. A missing required style+/// makes the AX request unavailable; it must not become a visible default.+pub trait AccessibilityStyleSource {+ fn element_style(&mut self, node_id: NodeId) -> Option<AccessibilityStyle>;+}++pub struct AccessibilityInput<'a> {+ pub(super) styles: &'a mut dyn AccessibilityStyleSource,pub(super) frame_state: AccessibilityFrameState,}@@ -21,38 +27,14 @@ pub enum AccessibilityFrameState {Inert,}-impl AccessibilityInput {- pub fn new(node_count: usize, frame_state: AccessibilityFrameState) -> Self {+impl<'a> AccessibilityInput<'a> {+ pub fn new(+ styles: &'a mut dyn AccessibilityStyleSource,+ frame_state: AccessibilityFrameState,+ ) -> Self {Self {- elements: vec![None; node_count],+ styles,frame_state,}}-- pub fn insert(&mut self, node_id: NodeId, style: AccessibilityStyle) {- self.elements[node_id.index()] = Some(style);- }-- pub(super) fn element(&self, node_id: NodeId) -> Option<AccessibilityStyle> {- self.elements.get(node_id.index()).copied().flatten()- }-- #[cfg(test)]- pub(super) fn visible_fixture(document: &crate::native::DomHost) -> Self {- let mut styles = Self::new(document.len(), AccessibilityFrameState::Active);- for node in document.nodes() {- if node.is_element() {- styles.insert(- node.id(),- AccessibilityStyle {- display_none: false,- visibility_visible: true,- hides_contents: false,- block_level: false,- },- );- }- }- styles- }}diff --git a/moli-dom/src/accessibility/ax_tree.rs b/moli-dom/src/accessibility/ax_tree.rsindex 36bbac905..4dcf75635 100644--- a/moli-dom/src/accessibility/ax_tree.rs+++ b/moli-dom/src/accessibility/ax_tree.rs@@ -5,73 +5,138 @@ use crate::{use serde_json::{Value, json};use std::collections::VecDeque;+use super::AccessibilityInput;use super::ax_projection::{AxIgnoredReason, AxTreeProjection};use super::ax_properties::{ax_name, ax_properties, ax_value};-use super::ax_roles::{ax_role, cdp_node_id, ordered_list_item_index};--// ----------------------------------------------------------------------------// Public (pub(crate)) tree-building entry points-// ---------------------------------------------------------------------------+use super::ax_roles::{ax_role, ordered_list_item_index};++/// The semantic traversal requested by one synchronous AX command.+#[derive(Clone, Copy, Debug)]+pub enum AccessibilityRequest {+ Tree { max_depth: Option<i32> },+ Node,+ Children,+ Ancestors,+ Partial { fetch_relatives: bool },+}-pub fn accessibility_tree_payloads_for_document(+pub fn accessibility_payloads_for_document(document: &DomHost,- styles: &super::AccessibilityInput,- root: NodeId,- max_depth: Option<i32>,+ input: &mut AccessibilityInput<'_>,+ node_id: NodeId,+ request: AccessibilityRequest,+ backend_node_id_for_node: &mut dyn FnMut(NodeId) -> Option<u32>,) -> Option<Vec<Value>> {- let mut backend_node_id_for_node = |node_id| Some(cdp_node_id(node_id));- accessibility_tree_payloads_for_document_with_backend_node_ids(- document,- styles,- root,- max_depth,- &mut backend_node_id_for_node,- )+ // A ShadowRoot contributes children but has no AX object of its own.+ let node_id = if matches!(request, AccessibilityRequest::Tree { .. }) {+ document.shadow_root_host(node_id).unwrap_or(node_id)+ } else {+ node_id+ };+ let mut projection = AxTreeProjection::new(document, node_id, input)?;+ match request {+ AccessibilityRequest::Tree { max_depth } => tree_payloads(+ &mut projection,+ node_id,+ max_depth,+ backend_node_id_for_node,+ ),+ AccessibilityRequest::Node => Some(vec![node_payload(+ &mut projection,+ node_id,+ backend_node_id_for_node,+ )?]),+ AccessibilityRequest::Children => {+ let mut nodes = Vec::new();+ if projection.is_rendered(node_id).ok()? {+ add_ax_children(+ &mut projection,+ node_id,+ &mut nodes,+ backend_node_id_for_node,+ )?;+ }+ Some(nodes)+ }+ AccessibilityRequest::Ancestors => {+ if projection.node(node_id).ok()?.is_none() {+ return Some(vec![ax_dom_node_without_object_payload(+ node_id,+ backend_node_id_for_node,+ )?]);+ }+ let mut nodes = Vec::new();+ add_ax_ancestors(+ &mut projection,+ Some(node_id),+ &mut nodes,+ backend_node_id_for_node,+ )?;+ Some(nodes)+ }+ AccessibilityRequest::Partial { fetch_relatives } => {+ let projected = projection.node(node_id).ok()?;+ let mut nodes = vec![node_payload(+ &mut projection,+ node_id,+ backend_node_id_for_node,+ )?];+ if fetch_relatives {+ if projected.is_some_and(|node| node.ignored_reason.is_none()) {+ add_ax_children(+ &mut projection,+ node_id,+ &mut nodes,+ backend_node_id_for_node,+ )?;+ }+ let parent = if let Some(projected) = projected {+ projected.parent+ } else {+ let mut parent = document.composed_parent(node_id);+ while let Some(id) = parent {+ if projection.node(id).ok()?.is_some() {+ break;+ }+ parent = document.composed_parent(id);+ }+ parent+ };+ add_ax_ancestors(+ &mut projection,+ parent,+ &mut nodes,+ backend_node_id_for_node,+ )?;+ }+ Some(nodes)+ }+ }}-pub fn accessibility_tree_payloads_for_document_with_backend_node_ids(- document: &DomHost,- styles: &super::AccessibilityInput,+fn tree_payloads(+ projection: &mut AxTreeProjection<'_, '_>,root: NodeId,max_depth: Option<i32>,- backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,+ backend_node_id_for_node: &mut dyn 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, styles)?;- if !projection.is_rendered(root) {+ if !projection.is_rendered(root).ok()? {return Some(Vec::new());}-let mut nodes = Vec::new();- if !push_ax_node_payload(- document,- &projection,- root,- &mut nodes,- backend_node_id_for_node,- ) {- return None;- }+ push_ax_node_payload(projection, root, &mut nodes, backend_node_id_for_node)?;// Match Blink's WalkAXNodesToDepth: ignored nodes remain observable, but- // only unignored nodes consume depth. Each queued node exposes its direct- // children plus any ignored chains between it and the next semantic layer.+ // only unignored nodes consume depth.let max_depth = max_depth.unwrap_or(-1);let mut pending = VecDeque::from([(root, 1)]);while let Some((node_id, depth)) = pending.pop_front() {- add_ax_children(- document,- &projection,- node_id,- &mut nodes,- backend_node_id_for_node,- );+ add_ax_children(projection, node_id, &mut nodes, backend_node_id_for_node)?;if max_depth < 0 || depth < max_depth {pending.extend(projection.unignored_children(node_id)+ .ok()?.into_iter().map(|child_id| (child_id, depth + 1)),);@@ -80,218 +145,39 @@ pub fn accessibility_tree_payloads_for_document_with_backend_node_ids(Some(nodes)}-pub fn accessibility_node_payload_for_document(- document: &DomHost,- styles: &super::AccessibilityInput,- node_id: NodeId,-) -> Option<Value> {- let mut backend_node_id_for_node = |node_id| Some(cdp_node_id(node_id));- accessibility_node_payload_for_document_with_backend_node_ids(- document,- styles,- node_id,- &mut backend_node_id_for_node,- )-}--pub fn accessibility_node_payload_for_document_with_backend_node_ids(- document: &DomHost,- styles: &super::AccessibilityInput,+fn node_payload(+ projection: &mut AxTreeProjection<'_, '_>,node_id: NodeId,- backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,+ backend_node_id_for_node: &mut dyn FnMut(NodeId) -> Option<u32>,) -> Option<Value> {- let projection = AxTreeProjection::build_for_node(document, node_id, styles)?;- let node = document.node(node_id)?;- let Some(projected) = projection.node(node_id) else {- return ax_dom_node_without_object_payload(node_id, backend_node_id_for_node);- };- ax_node_payload(- document,- &projection,- node_id,- node,- projected,- backend_node_id_for_node,- )-}--pub fn accessibility_child_node_payloads_for_document(- document: &DomHost,- styles: &super::AccessibilityInput,- node_id: NodeId,-) -> Option<Vec<Value>> {- let mut backend_node_id_for_node = |node_id| Some(cdp_node_id(node_id));- accessibility_child_node_payloads_for_document_with_backend_node_ids(- document,- styles,- node_id,- &mut backend_node_id_for_node,- )-}--pub fn accessibility_child_node_payloads_for_document_with_backend_node_ids(- document: &DomHost,- styles: &super::AccessibilityInput,- node_id: NodeId,- backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,-) -> Option<Vec<Value>> {- let projection = AxTreeProjection::build_for_node(document, node_id, styles)?;- document.node(node_id)?;- if !projection.is_rendered(node_id) {- return Some(Vec::new());+ if projection.node(node_id).ok()?.is_none() {+ ax_dom_node_without_object_payload(node_id, backend_node_id_for_node)+ } else {+ ax_node_payload(projection, node_id, backend_node_id_for_node)}- let mut nodes = Vec::new();- add_ax_children(- document,- &projection,- node_id,- &mut nodes,- backend_node_id_for_node,- );- Some(nodes)-}--pub fn accessibility_node_and_ancestor_payloads_for_document(- document: &DomHost,- styles: &super::AccessibilityInput,- node_id: NodeId,-) -> Option<Vec<Value>> {- let mut backend_node_id_for_node = |node_id| Some(cdp_node_id(node_id));- accessibility_node_and_ancestor_payloads_for_document_with_backend_node_ids(- document,- styles,- node_id,- &mut backend_node_id_for_node,- )}-pub fn accessibility_node_and_ancestor_payloads_for_document_with_backend_node_ids(- document: &DomHost,- styles: &super::AccessibilityInput,- node_id: NodeId,- backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,-) -> Option<Vec<Value>> {- let projection = AxTreeProjection::build_for_node(document, node_id, styles)?;- document.node(node_id)?;- if !projection.contains(node_id) {- return Some(vec![ax_dom_node_without_object_payload(+fn add_ax_ancestors(+ projection: &mut AxTreeProjection<'_, '_>,+ mut current: Option<NodeId>,+ out: &mut Vec<Value>,+ backend_node_id_for_node: &mut dyn FnMut(NodeId) -> Option<u32>,+) -> Option<()> {+ while let Some(node_id) = current {+ let projected = projection.node(node_id).ok()??;+ out.push(ax_node_payload(+ projection,node_id,backend_node_id_for_node,- )?]);- }- let mut chain = Vec::new();- let mut current = Some(node_id);- while let Some(current_id) = current {- let Some(node) = document.node(current_id) else {- break;- };- let Some(projected) = projection.node(current_id) else {- break;- };- chain.push(ax_node_payload(- document,- &projection,- current_id,- node,- projected,- backend_node_id_for_node,)?);current = projected.parent;}- Some(chain)-}--pub fn accessibility_partial_tree_payloads_for_document(- document: &DomHost,- styles: &super::AccessibilityInput,- node_id: NodeId,- fetch_relatives: bool,-) -> Option<Vec<Value>> {- let mut backend_node_id_for_node = |node_id| Some(cdp_node_id(node_id));- accessibility_partial_tree_payloads_for_document_with_backend_node_ids(- document,- styles,- node_id,- fetch_relatives,- &mut backend_node_id_for_node,- )-}--pub fn accessibility_partial_tree_payloads_for_document_with_backend_node_ids(- document: &DomHost,- styles: &super::AccessibilityInput,- node_id: NodeId,- fetch_relatives: bool,- backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,-) -> Option<Vec<Value>> {- let projection = AxTreeProjection::build_for_node(document, node_id, styles)?;- let node = document.node(node_id)?;- let projected = projection.node(node_id);- let mut nodes = vec![if let Some(projected) = projected {- ax_node_payload(- document,- &projection,- node_id,- node,- projected,- backend_node_id_for_node,- )?- } else {- ax_dom_node_without_object_payload(node_id, backend_node_id_for_node)?- }];-- if fetch_relatives {- if projected.is_some_and(|projected| projected.ignored_reason.is_none()) {- add_ax_children(- document,- &projection,- node_id,- &mut nodes,- backend_node_id_for_node,- );- }-- let mut current = projected- .and_then(|projected| projected.parent)- .or_else(|| {- let mut parent = document.composed_parent(node_id);- while let Some(id) = parent {- if projection.contains(id) {- return Some(id);- }- parent = document.composed_parent(id);- }- None- });- while let Some(current_id) = current {- let Some(current_node) = document.node(current_id) else {- break;- };- let Some(current_projected) = projection.node(current_id) else {- break;- };- nodes.push(ax_node_payload(- document,- &projection,- current_id,- current_node,- current_projected,- backend_node_id_for_node,- )?);- current = current_projected.parent;- }- }-- Some(nodes)+ Some(())}-// ----------------------------------------------------------------------------// Private helpers-// ----------------------------------------------------------------------------fn ax_dom_node_without_object_payload(node_id: NodeId,- backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,+ backend_node_id_for_node: &mut dyn FnMut(NodeId) -> Option<u32>,) -> Option<Value> {let backend_node_id = backend_node_id_for_node(node_id)?;Some(json!({@@ -304,78 +190,59 @@ fn ax_dom_node_without_object_payload(}fn add_ax_children(- document: &DomHost,- projection: &AxTreeProjection,+ projection: &mut AxTreeProjection<'_, '_>,node_id: NodeId,out: &mut Vec<Value>,- backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,-) {- let Some(projected) = projection.node(node_id) else {- return;- };-- let mut reachable = projected.children.iter().rev().copied().collect::<Vec<_>>();+ backend_node_id_for_node: &mut dyn FnMut(NodeId) -> Option<u32>,+) -> Option<()> {+ let mut reachable = projection.children(node_id).ok()?;+ reachable.reverse();while let Some(child_id) = reachable.pop() {- let Some(child) = projection.node(child_id) else {- continue;- };- if !projection.is_rendered(child_id) {+ let child = projection.node(child_id).ok()??;+ if child.ignored_reason == Some(AxIgnoredReason::NotRendered) {continue;}- push_ax_node_payload(- document,- projection,- child_id,- out,- backend_node_id_for_node,- );+ push_ax_node_payload(projection, child_id, out, backend_node_id_for_node)?;if child.ignored_reason.is_some() {- reachable.extend(child.children.iter().rev().copied());+ reachable.extend(projection.children(child_id).ok()?.into_iter().rev());}}+ Some(())}fn push_ax_node_payload(- document: &DomHost,- projection: &AxTreeProjection,+ projection: &mut AxTreeProjection<'_, '_>,node_id: NodeId,out: &mut Vec<Value>,- backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,-) -> bool {- let Some(node) = document.node(node_id) else {- return false;- };- let Some(projected) = projection.node(node_id) else {- return false;- };- let Some(payload) = ax_node_payload(- document,+ backend_node_id_for_node: &mut dyn FnMut(NodeId) -> Option<u32>,+) -> Option<()> {+ let projected = projection.node(node_id).ok()??;+ out.push(ax_node_payload(projection,node_id,- node,- projected,backend_node_id_for_node,- ) else {- return false;- };- out.push(payload);+ )?);if projected.ignored_reason.is_none()- && let Some(marker) =- ax_list_marker_payload(document, node_id, node, backend_node_id_for_node)+ && let Some(marker) = ax_list_marker_payload(+ projection.document,+ node_id,+ projection.document.node(node_id)?,+ backend_node_id_for_node,+ ){out.push(marker);}- true+ Some(())}fn ax_node_payload(- document: &DomHost,- projection: &AxTreeProjection,+ projection: &mut AxTreeProjection<'_, '_>,node_id: NodeId,- node: &Node,- projected: &super::ax_projection::AxProjectedNode,- backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,+ backend_node_id_for_node: &mut dyn FnMut(NodeId) -> Option<u32>,) -> Option<Value> {+ let document = projection.document;+ let node = document.node(node_id)?;+ let projected = projection.node(node_id).ok()??;let backend_node_id = backend_node_id_for_node(node_id)?;let mut payload = serde_json::Map::new();payload.insert("nodeId".to_owned(), json!(format!("AX-{backend_node_id}")));@@ -397,22 +264,17 @@ fn ax_node_payload();if !ignored {- let name = ax_name(document, projection, node);+ let name = ax_name(document, projection, node).ok()?;if !name.is_empty() {payload.insert("name".to_owned(),- json!({- "type": "computedString",- "value": name,- }),+ json!({"type": "computedString", "value": name}),);}-if let Some(value) = ax_value(document, node_id, node) {payload.insert("value".to_owned(), value);}}-payload.insert("properties".to_owned(),Value::Array(if ignored {@@ -422,28 +284,24 @@ fn ax_node_payload(}),);- if let Some(parent_id) = projected.parent- && let Some(parent_backend_node_id) = backend_node_id_for_node(parent_id)- {+ if let Some(parent_id) = projected.parent {+ let parent_backend_node_id = backend_node_id_for_node(parent_id)?;payload.insert("parentId".to_owned(),json!(format!("AX-{parent_backend_node_id}")),);}-- if !projected.children.is_empty() {- let child_ids = projected- .children- .iter()- .filter(|child_id| projection.is_rendered(**child_id))- .filter_map(|child_id| {- backend_node_id_for_node(*child_id)- .map(|backend_node_id| format!("AX-{backend_node_id}"))- })- .collect::<Vec<_>>();+ let children = projection.children(node_id).ok()?;+ if !children.is_empty() {+ let mut child_ids = Vec::new();+ for child_id in children {+ if projection.is_rendered(child_id).ok()? {+ let backend_node_id = backend_node_id_for_node(child_id)?;+ child_ids.push(format!("AX-{backend_node_id}"));+ }+ }payload.insert("childIds".to_owned(), json!(child_ids));}-Some(Value::Object(payload))}@@ -451,7 +309,7 @@ fn ax_ignored_reasons_payload(document: &DomHost,node_id: NodeId,reason: AxIgnoredReason,- backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,+ backend_node_id_for_node: &mut dyn FnMut(NodeId) -> Option<u32>,) -> Value {match reason {AxIgnoredReason::Uninteresting@@ -503,7 +361,7 @@ fn ax_list_marker_payload(document: &DomHost,node_id: NodeId,node: &Node,- backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,+ backend_node_id_for_node: &mut dyn FnMut(NodeId) -> Option<u32>,) -> Option<Value> {let element = node.as_element()?;if !element.is_html_element("li") {diff --git a/moli-dom/src/accessibility/mod.rs b/moli-dom/src/accessibility/mod.rsindex 4059cb761..fb8c7fb71 100644--- a/moli-dom/src/accessibility/mod.rs+++ b/moli-dom/src/accessibility/mod.rs@@ -5,20 +5,11 @@ mod ax_roles;mod ax_styles;mod ax_tree;-pub use ax_styles::{AccessibilityFrameState, AccessibilityInput, AccessibilityStyle};--pub use ax_tree::{- accessibility_child_node_payloads_for_document,- accessibility_child_node_payloads_for_document_with_backend_node_ids,- accessibility_node_and_ancestor_payloads_for_document,- accessibility_node_and_ancestor_payloads_for_document_with_backend_node_ids,- accessibility_node_payload_for_document,- accessibility_node_payload_for_document_with_backend_node_ids,- accessibility_partial_tree_payloads_for_document,- accessibility_partial_tree_payloads_for_document_with_backend_node_ids,- accessibility_tree_payloads_for_document,- accessibility_tree_payloads_for_document_with_backend_node_ids,+pub use ax_styles::{+ AccessibilityFrameState, AccessibilityInput, AccessibilityStyle, AccessibilityStyleSource,};+pub use ax_tree::{AccessibilityRequest, accessibility_payloads_for_document};+#[cfg(test)]mod tests;diff --git a/moli-dom/src/accessibility/tests.rs b/moli-dom/src/accessibility/tests.rsindex 987369c4d..5798dc7a7 100644--- a/moli-dom/src/accessibility/tests.rs+++ b/moli-dom/src/accessibility/tests.rs@@ -1,4 +1,5 @@use serde_json::{Value, json};+use std::collections::{HashMap, HashSet};use super::*;use crate::{@@ -6,16 +7,71 @@ use crate::{native::{DomHost, NativeDom},};+#[derive(Default)]+pub(super) struct FixtureStyles(std::collections::HashMap<NodeId, AccessibilityStyle>);++impl FixtureStyles {+ pub(super) fn visible(document: &crate::native::DomHost) -> Self {+ Self(+ document+ .nodes()+ .iter()+ .filter(|node| node.is_element())+ .map(|node| {+ (+ node.id(),+ AccessibilityStyle {+ display_none: false,+ visibility_visible: true,+ hides_contents: false,+ block_level: false,+ },+ )+ })+ .collect(),+ )+ }++ pub(super) fn insert(&mut self, node: NodeId, style: AccessibilityStyle) {+ self.0.insert(node, style);+ }+}++impl AccessibilityStyleSource for FixtureStyles {+ fn element_style(&mut self, node: NodeId) -> Option<AccessibilityStyle> {+ self.0.get(&node).copied()+ }+}++fn backend_node_id(node: NodeId) -> u32 {+ u32::try_from(node.index() + 1).expect("fixture backend id")+}+fn tree(document: &DomHost) -> Vec<Value> {- accessibility_tree_payloads_for_document(+ request(document,- &AccessibilityInput::visible_fixture(document),+ &mut FixtureStyles::visible(document),document.document_node_id(),- None,+ AccessibilityRequest::Tree { max_depth: None },).expect("fixture AX tree")}+fn request(+ document: &DomHost,+ styles: &mut dyn AccessibilityStyleSource,+ node: NodeId,+ request: AccessibilityRequest,+) -> Option<Vec<Value>> {+ accessibility_payloads_for_document(+ document,+ &mut AccessibilityInput::new(styles, AccessibilityFrameState::Active),+ node,+ request,+ &mut |node| Some(backend_node_id(node)),+ )+}+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"),@@ -36,7 +92,7 @@ fn append_text(document: &mut DomHost, parent: NodeId, text: &str) {}fn node_by_id(nodes: &[Value], node_id: NodeId) -> &Value {- let backend_id = super::ax_roles::cdp_node_id(node_id);+ let backend_id = backend_node_id(node_id);nodes.iter().find(|node| node["backendDOMNodeId"] == backend_id)@@ -55,11 +111,11 @@ fn button_names(nodes: &[Value]) -> Vec<&str> {fn ax_requires_styles_for_connected_elements() {let (document, _) = document_with_host();assert!(- accessibility_tree_payloads_for_document(+ request(&document,- &AccessibilityInput::new(document.len(), AccessibilityFrameState::Active),+ &mut FixtureStyles::default(),document.document_node_id(),- None,+ AccessibilityRequest::Tree { max_depth: None },).is_none(),"missing computed style must not become a visible default"@@ -80,7 +136,7 @@ fn ax_hidden_reference_names_cross_transparent_shadow_roots() {let document_id = document.document_node_id();let button = append_element(&mut document, document_id, "button");assert!(document.set_attribute(button, "aria-labelledby", "label"));- let mut styles = AccessibilityInput::visible_fixture(&document);+ let mut styles = FixtureStyles::visible(&document);styles.insert(host,AccessibilityStyle {@@ -90,8 +146,13 @@ fn ax_hidden_reference_names_cross_transparent_shadow_roots() {block_level: true,},);- let nodes = accessibility_tree_payloads_for_document(&document, &styles, document_id, None)- .expect("AX tree");+ let nodes = request(+ &document,+ &mut styles,+ document_id,+ AccessibilityRequest::Tree { max_depth: None },+ )+ .expect("AX tree");assert_eq!(node_by_id(&nodes, button)["name"]["value"],"Shadow assigned"@@ -99,7 +160,7 @@ fn ax_hidden_reference_names_cross_transparent_shadow_roots() {assert!(!nodes.iter()- .any(|node| node["backendDOMNodeId"] == super::ax_roles::cdp_node_id(host))+ .any(|node| node["backendDOMNodeId"] == backend_node_id(host)));}}@@ -117,25 +178,22 @@ fn ax_tree_queries_shadow_roots_from_hosts() {let outside = append_element(&mut document, document_id, "button");append_text(&mut document, outside, "Outside action");- let nodes = accessibility_tree_payloads_for_document(+ let nodes = request(&document,- &AccessibilityInput::visible_fixture(&document),+ &mut FixtureStyles::visible(&document),root,- None,+ AccessibilityRequest::Tree { max_depth: None },).expect("fixture AX tree");- assert_eq!(- nodes[0]["backendDOMNodeId"],- super::ax_roles::cdp_node_id(host)- );+ assert_eq!(nodes[0]["backendDOMNodeId"], backend_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)+ node["backendDOMNodeId"] == backend_node_id(root)+ || node["backendDOMNodeId"] == backend_node_id(outside)}));}}@@ -187,10 +245,11 @@ fn ax_tree_includes_nested_shadow_controls_and_host_ancestors() {node_by_id(&nodes, host)["nodeId"]);- let ancestors = accessibility_node_and_ancestor_payloads_for_document(+ let ancestors = request(&document,- &AccessibilityInput::visible_fixture(&document),+ &mut FixtureStyles::visible(&document),button,+ AccessibilityRequest::Ancestors,).expect("fixture AX ancestors");let backend_ids = ancestors@@ -200,7 +259,7 @@ fn ax_tree_includes_nested_shadow_controls_and_host_ancestors() {assert_eq!(backend_ids,[button, nested_host, host, document.document_node_id()]- .map(|id| json!(super::ax_roles::cdp_node_id(id)))+ .map(|id| json!(backend_node_id(id))));}}@@ -288,6 +347,219 @@ fn ax_tree_inherits_aria_hidden_from_shadow_host() {);assert_eq!(button_node["ignoredReasons"][0]["value"]["relatedNodes"][0]["backendDOMNodeId"],- super::ax_roles::cdp_node_id(host)+ backend_node_id(host)+ );+}++struct RecordingStyles {+ facts: FixtureStyles,+ missing: HashSet<NodeId>,+ reads: Vec<NodeId>,+}++impl RecordingStyles {+ fn new(document: &DomHost) -> Self {+ Self {+ facts: FixtureStyles::visible(document),+ missing: HashSet::new(),+ reads: Vec::new(),+ }+ }++ fn assert_read_once(&self) {+ assert_eq!(+ self.reads.len(),+ self.reads.iter().collect::<HashSet<_>>().len(),+ "each required element style must be read once: {:?}",+ self.reads+ );+ }+}++impl AccessibilityStyleSource for RecordingStyles {+ fn element_style(&mut self, node: NodeId) -> Option<AccessibilityStyle> {+ self.reads.push(node);+ if self.missing.contains(&node) {+ None+ } else {+ self.facts.element_style(node)+ }+ }+}++#[test]+fn local_requests_only_read_their_dependencies_as_unrelated_subtrees_grow() {+ for size in [0, 2048] {+ let (mut document, host) = document_with_host();+ let target = append_element(&mut document, host, "button");+ document.set_attribute(target, "aria-label", "Target");+ let child = append_element(&mut document, target, "span");+ append_text(&mut document, child, "Contents");+ let unrelated = append_element(&mut document, host, "div");+ let untouched = (0..size)+ .map(|_| {+ let node = append_element(&mut document, unrelated, "span");+ append_text(&mut document, node, "Unrelated");+ node+ })+ .collect::<HashSet<_>>();++ for (query, reads_sibling) in [+ (AccessibilityRequest::Node, false),+ (+ AccessibilityRequest::Partial {+ fetch_relatives: false,+ },+ false,+ ),+ (+ AccessibilityRequest::Partial {+ fetch_relatives: true,+ },+ true,+ ),+ (AccessibilityRequest::Ancestors, true),+ (AccessibilityRequest::Tree { max_depth: None }, false),+ ] {+ let mut styles = RecordingStyles::new(&document);+ styles.missing = untouched.clone();+ if !reads_sibling {+ styles.missing.insert(unrelated);+ }+ let mut refs = HashMap::new();+ let nodes = accessibility_payloads_for_document(+ &document,+ &mut AccessibilityInput::new(&mut styles, AccessibilityFrameState::Active),+ target,+ query,+ &mut |node| Some(*refs.entry(node).or_insert(backend_node_id(node))),+ )+ .expect("unrelated missing styles must not affect a local AX request");+ assert_eq!(node_by_id(&nodes, target)["name"]["value"], "Target");+ let mut expected = HashSet::from([host, target, child]);+ if reads_sibling {+ expected.insert(unrelated);+ }+ assert_eq!(+ styles.reads.iter().copied().collect::<HashSet<_>>(),+ expected,+ "{query:?}, unrelated size {size}"+ );+ styles.assert_read_once();+ assert!(+ refs.keys().all(|id| !untouched.contains(id)),+ "unrelated descendants must not receive backend refs"+ );+ }+ }+}++#[test]+fn local_names_can_read_hidden_shadow_labels_outside_the_projected_subtree() {+ for mode in ["open", "closed"] {+ let (mut document, host) = document_with_host();+ let target = append_element(&mut document, host, "button");+ document.set_attribute(target, "aria-labelledby", "external-label");+ let root = document.document_node_id();+ let label = append_element(&mut document, root, "div");+ document.set_attribute(label, "id", "external-label");+ let assigned = append_element(&mut document, label, "span");+ append_text(&mut document, assigned, "assigned");+ let shadow = document+ .attach_shadow_root(label, mode)+ .expect("shadow root");+ append_text(&mut document, shadow, "Shadow");+ let slot = append_element(&mut document, shadow, "slot");+ let unrelated = append_element(&mut document, root, "div");+ for query in [+ AccessibilityRequest::Node,+ AccessibilityRequest::Partial {+ fetch_relatives: false,+ },+ AccessibilityRequest::Tree { max_depth: None },+ ] {+ let mut styles = RecordingStyles::new(&document);+ let hidden = AccessibilityStyle {+ display_none: true,+ visibility_visible: true,+ hides_contents: false,+ block_level: true,+ };+ styles.facts.insert(label, hidden);+ styles.missing.insert(unrelated);+ let nodes =+ request(&document, &mut styles, target, query).expect("local named AX node");+ assert_eq!(+ node_by_id(&nodes, target)["name"]["value"],+ "Shadow assigned"+ );+ assert!(+ nodes+ .iter()+ .all(|node| node["backendDOMNodeId"] != backend_node_id(label))+ );+ assert_eq!(+ styles.reads.iter().copied().collect::<HashSet<_>>(),+ HashSet::from([host, target, label, assigned, slot])+ );+ styles.assert_read_once();++ styles.missing.insert(label);+ assert!(+ request(&document, &mut styles, target, query).is_none(),+ "a required external label style must not become an empty name"+ );+ }+ }+}++#[test]+fn required_content_and_child_id_styles_fail_the_whole_request() {+ let (mut document, host) = document_with_host();+ let target = append_element(&mut document, host, "button");+ let child = append_element(&mut document, target, "span");+ append_text(&mut document, child, "Action");+ for explicit_name in [false, true] {+ if explicit_name {+ document.set_attribute(target, "aria-label", "Explicit");+ }+ let mut styles = RecordingStyles::new(&document);+ styles.missing.insert(child);+ assert!(+ request(&document, &mut styles, target, AccessibilityRequest::Node).is_none(),+ "required name contents and childIds must propagate missing styles"+ );+ }+}++#[test]+fn full_tree_does_not_read_styles_below_a_not_rendered_branch() {+ let (mut document, host) = document_with_host();+ let hidden = append_element(&mut document, host, "div");+ let child = append_element(&mut document, hidden, "button");+ append_text(&mut document, child, "Hidden action");+ let mut styles = RecordingStyles::new(&document);+ styles.facts.insert(+ hidden,+ AccessibilityStyle {+ display_none: true,+ visibility_visible: true,+ hides_contents: false,+ block_level: true,+ },+ );+ styles.missing.insert(child);+ let nodes = request(+ &document,+ &mut styles,+ document.document_node_id(),+ AccessibilityRequest::Tree { max_depth: None },+ )+ .expect("hidden descendants need no AX styles");+ assert!(button_names(&nodes).is_empty());+ assert_eq!(+ styles.reads.iter().copied().collect::<HashSet<_>>(),+ HashSet::from([host, hidden]));+ styles.assert_read_once();}diff --git a/moli-renderer-v8/src/runtime/page_dom.rs b/moli-renderer-v8/src/runtime/page_dom.rsindex d00355d06..8260c949d 100644--- a/moli-renderer-v8/src/runtime/page_dom.rs+++ b/moli-renderer-v8/src/runtime/page_dom.rs@@ -27,6 +27,7 @@ use crate::script_vm::{DomInspectorEdit, DomInspectorEditOutcome, PendingRuntimeEvaluateCall,RuntimeEvaluateCodeGenerationPolicy, RuntimeEvaluateOutcome, RuntimeEvaluateResultMode,};+use moli_dom::accessibility::AccessibilityRequest;use moli_page_types::{DocumentNodeAssociatedSnapshot, DocumentNodeAttributeSnapshot, DocumentNodeInspectorIdentity,DocumentNodeObjectSnapshot, DocumentNodeSnapshot, MAX_DOM_OUTPUT_TREE_DEPTH,@@ -36,9 +37,7 @@ use moli_page_types::{use moli_selector::QueryEngine;mod child_frame_nodes;-use child_frame_nodes::{- child_frame_document_contains_live_handle, collect_shadow_including_document_handles,-};+use child_frame_nodes::child_frame_document_contains_live_handle;fn script_truthy_sleep_for(ms_to_next: Option<u64>,@@ -2935,114 +2934,44 @@ impl PageVm {self.document_node_property_for_live_handle(handle, name)}- fn renderer_backend_node_id_map_for_document_handle(- &mut self,- document_handle: DomHandle,- ) -> Option<HashMap<DomHandle, u32>> {- let handles = {- let dom_host = self.vm().document_runtime.dom_host();- collect_shadow_including_document_handles(dom_host, document_handle)- };- Some(- handles- .into_iter()- .filter_map(|handle| {- self.renderer_backend_node_id_for_live_handle(handle)- .map(|backend_node_id| (handle, backend_node_id))- })- .collect(),- )- }-- fn renderer_backend_node_id_map_for_owner_document(- &mut self,- handle: DomHandle,- ) -> Option<HashMap<DomHandle, u32>> {- let document_handle = {- let dom_host = self.vm().document_runtime.dom_host();- let handle = live_shadow_root_host_for_handle(dom_host, handle).unwrap_or(handle);- dom_host.owner_document_handle(handle)?- };- let mut ids = self.renderer_backend_node_id_map_for_document_handle(document_handle)?;- // Retained detached DOM objects also need a stable ignored ref.- ids.insert(- handle,- self.renderer_backend_node_id_for_live_handle(handle)?,- );- Some(ids)- }-- fn renderer_accessibility_input(+ fn build_accessibility_payloads(&self,- backend_node_ids: &HashMap<DomHandle, u32>,- ) -> Option<moli_dom::accessibility::AccessibilityInput> {- let mut handles = backend_node_ids.keys().copied().collect::<Vec<_>>();- handles.sort_unstable_by_key(|handle| handle.index());- self.vm().accessibility_input(&handles)+ handle: DomHandle,+ request: AccessibilityRequest,+ ) -> Option<Vec<Value>> {+ let mut backend_node_id_for_node =+ |node_id| self.renderer_backend_node_id_for_live_handle(node_id);+ self.vm()+ .accessibility_payloads(handle, request, &mut backend_node_id_for_node)}pub(crate) fn accessibility_tree_payloads_for_live_handle(&mut self,root_handle: DomHandle,max_depth: Option<i32>,- ) -> Option<Vec<serde_json::Value>> {- let backend_node_ids = self.renderer_backend_node_id_map_for_owner_document(root_handle)?;- let styles = self.renderer_accessibility_input(&backend_node_ids)?;- 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();- document.node(root_handle)?;- moli_dom::accessibility::accessibility_tree_payloads_for_document_with_backend_node_ids(- document,- &styles,- root_handle,- max_depth,- &mut backend_node_id_for_node,- )- }?;- Some(payloads)+ ) -> Option<Vec<Value>> {+ self.build_accessibility_payloads(root_handle, AccessibilityRequest::Tree { max_depth })}pub(crate) fn accessibility_tree_payloads_for_document(&mut self,max_depth: Option<i32>,- ) -> Option<Vec<serde_json::Value>> {- let root_node_id = self- .vm()- .document_runtime- .dom_host()- .dom()- .document_node_id();- self.accessibility_tree_payloads_for_live_handle(root_node_id, max_depth)+ ) -> Option<Vec<Value>> {+ let root = self.vm().document_runtime.dom_host().document_node_id();+ self.accessibility_tree_payloads_for_live_handle(root, max_depth)}pub(crate) fn accessibility_node_payload_for_live_handle(&mut self,handle: DomHandle,- ) -> Option<serde_json::Value> {- let backend_node_ids = self.renderer_backend_node_id_map_for_owner_document(handle)?;- let styles = self.renderer_accessibility_input(&backend_node_ids)?;- 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();- moli_dom::accessibility::accessibility_node_payload_for_document_with_backend_node_ids(- document,- &styles,- handle,- &mut backend_node_id_for_node,- )?- };- Some(payload)+ ) -> Option<Value> {+ self.build_accessibility_payloads(handle, AccessibilityRequest::Node)?+ .pop()}- pub(crate) fn accessibility_node_payload_for_document(&mut self) -> Option<serde_json::Value> {- let node_id = self- .vm()- .document_runtime- .dom_host()- .dom()- .document_node_id();- self.accessibility_node_payload_for_live_handle(node_id)+ pub(crate) fn accessibility_node_payload_for_document(&mut self) -> Option<Value> {+ let root = self.vm().document_runtime.dom_host().document_node_id();+ self.accessibility_node_payload_for_live_handle(root)}pub(crate) fn accessibility_tree_payloads_for_node(@@ -3050,73 +2979,28 @@ impl PageVm {reference: RendererDomNodeReference,max_depth: Option<i32>,) -> Option<RendererAccessibilityPayloadsForObjectId> {- self.accessibility_payloads_for_node(reference, |document, styles, node_id, backend_node_ids| {- document.node(node_id)?;- let mut backend_node_id_for_node = |node_id| backend_node_ids.get(&node_id).copied();- moli_dom::accessibility::accessibility_tree_payloads_for_document_with_backend_node_ids(- document,- styles,- node_id,- max_depth,- &mut backend_node_id_for_node,- )- })+ self.accessibility_payloads_for_node(reference, AccessibilityRequest::Tree { max_depth })}pub(crate) fn accessibility_node_payload_for_node(&mut self,reference: RendererDomNodeReference,) -> Option<RendererAccessibilityPayloadsForObjectId> {- self.accessibility_payloads_for_node(reference, |document, styles, node_id, backend_node_ids| {- let mut backend_node_id_for_node = |node_id| backend_node_ids.get(&node_id).copied();- moli_dom::accessibility::accessibility_node_payload_for_document_with_backend_node_ids(- document,- styles,- node_id,- &mut backend_node_id_for_node,- )- .map(|payload| vec![payload])- })+ self.accessibility_payloads_for_node(reference, AccessibilityRequest::Node)}pub(crate) fn accessibility_node_and_ancestor_payloads_for_node(&mut self,reference: RendererDomNodeReference,) -> Option<RendererAccessibilityPayloadsForObjectId> {- self.accessibility_payloads_for_node(- reference,- |document, styles, node_id, backend_node_ids| {- document.node(node_id)?;- let mut backend_node_id_for_node =- |node_id| backend_node_ids.get(&node_id).copied();- moli_dom::accessibility::accessibility_node_and_ancestor_payloads_for_document_with_backend_node_ids(- document,- styles,- node_id,- &mut backend_node_id_for_node,- )- },- )+ self.accessibility_payloads_for_node(reference, AccessibilityRequest::Ancestors)}pub(crate) fn accessibility_child_node_payloads_for_node(&mut self,reference: RendererDomNodeReference,) -> Option<RendererAccessibilityPayloadsForObjectId> {- self.accessibility_payloads_for_node(- reference,- |document, styles, node_id, backend_node_ids| {- document.node(node_id)?;- let mut backend_node_id_for_node =- |node_id| backend_node_ids.get(&node_id).copied();- moli_dom::accessibility::accessibility_child_node_payloads_for_document_with_backend_node_ids(- document,- styles,- node_id,- &mut backend_node_id_for_node,- )- },- )+ self.accessibility_payloads_for_node(reference, AccessibilityRequest::Children)}pub(crate) fn accessibility_partial_tree_payloads_for_node(@@ -3126,32 +3010,17 @@ impl PageVm {) -> Option<RendererAccessibilityPayloadsForObjectId> {self.accessibility_payloads_for_node(reference,- |document, styles, node_id, backend_node_ids| {- let mut backend_node_id_for_node =- |node_id| backend_node_ids.get(&node_id).copied();- moli_dom::accessibility::accessibility_partial_tree_payloads_for_document_with_backend_node_ids(- document,- styles,- node_id,- fetch_relatives,- &mut backend_node_id_for_node,- )- },+ AccessibilityRequest::Partial { fetch_relatives },)}fn accessibility_payloads_for_node(&mut self,reference: RendererDomNodeReference,- build_payloads: impl FnOnce(- &DomHost,- &moli_dom::accessibility::AccessibilityInput,- DomHandle,- &HashMap<DomHandle, u32>,- ) -> Option<Vec<serde_json::Value>>,+ request: AccessibilityRequest,) -> Option<RendererAccessibilityPayloadsForObjectId> {let handle = self.live_handle_for_document_node_reference(reference)?;- self.accessibility_payloads_for_live_handle(handle, build_payloads)+ self.accessibility_payloads_for_live_handle(handle, request)}pub(crate) fn accessibility_tree_payloads_for_child_frame(@@ -3159,74 +3028,40 @@ impl PageVm {frame_id: &str,max_depth: Option<i32>,) -> Option<RendererAccessibilityPayloadsForObjectId> {- let document_handle = self- .vm()- .child_browsing_context_document_handle_by_frame_id(frame_id)?;- let backend_node_ids =- self.renderer_backend_node_id_map_for_document_handle(document_handle)?;- let styles = self.renderer_accessibility_input(&backend_node_ids)?;- 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();- document.node(document_handle)?;- moli_dom::accessibility::accessibility_tree_payloads_for_document_with_backend_node_ids(- document,- &styles,- document_handle,- max_depth,- &mut backend_node_id_for_node,- )- };- Some(RendererAccessibilityPayloadsForObjectId {- frame_id: Some(frame_id.to_owned()),- payloads,- })+ self.accessibility_payloads_for_child_frame(+ frame_id,+ AccessibilityRequest::Tree { max_depth },+ )}pub(crate) fn accessibility_node_payload_for_child_frame(&mut self,frame_id: &str,) -> Option<RendererAccessibilityPayloadsForObjectId> {- let document_handle = self+ self.accessibility_payloads_for_child_frame(frame_id, AccessibilityRequest::Node)+ }++ fn accessibility_payloads_for_child_frame(+ &self,+ frame_id: &str,+ request: AccessibilityRequest,+ ) -> Option<RendererAccessibilityPayloadsForObjectId> {+ let document = self.vm().child_browsing_context_document_handle_by_frame_id(frame_id)?;- let backend_node_ids =- self.renderer_backend_node_id_map_for_document_handle(document_handle)?;- let styles = self.renderer_accessibility_input(&backend_node_ids)?;- 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();- moli_dom::accessibility::accessibility_node_payload_for_document_with_backend_node_ids(- document,- &styles,- document_handle,- &mut backend_node_id_for_node,- )- };- let payloads = payload.map(|payload| vec![payload]);Some(RendererAccessibilityPayloadsForObjectId {frame_id: Some(frame_id.to_owned()),- payloads,+ payloads: self.build_accessibility_payloads(document, request),})}fn accessibility_payloads_for_live_handle(&mut self,handle: DomHandle,- build_payloads: impl FnOnce(- &DomHost,- &moli_dom::accessibility::AccessibilityInput,- DomHandle,- &HashMap<DomHandle, u32>,- ) -> Option<Vec<serde_json::Value>>,+ request: AccessibilityRequest,) -> Option<RendererAccessibilityPayloadsForObjectId> {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 styles = self.renderer_accessibility_input(&backend_node_ids)?;- let payloads = {- let document = self.vm().document_runtime.dom_host();- build_payloads(document, &styles, handle, &backend_node_ids)?- };+ let payloads = self.build_accessibility_payloads(handle, request)?;Some(RendererAccessibilityPayloadsForObjectId {frame_id,payloads: Some(payloads),@@ -3241,18 +3076,7 @@ impl PageVm {self.accessibility_payloads_for_object_id(inspector_session_id,object_id,- |document, styles, node_id, backend_node_ids| {- document.node(node_id)?;- let mut backend_node_id_for_node =- |node_id| backend_node_ids.get(&node_id).copied();- moli_dom::accessibility::accessibility_tree_payloads_for_document_with_backend_node_ids(- document,- styles,- node_id,- None,- &mut backend_node_id_for_node,- )- },+ AccessibilityRequest::Tree { max_depth: None },)}@@ -3264,17 +3088,7 @@ impl PageVm {self.accessibility_payloads_for_object_id(inspector_session_id,object_id,- |document, styles, node_id, backend_node_ids| {- document.node(node_id)?;- let mut backend_node_id_for_node =- |node_id| backend_node_ids.get(&node_id).copied();- moli_dom::accessibility::accessibility_node_and_ancestor_payloads_for_document_with_backend_node_ids(- document,- styles,- node_id,- &mut backend_node_id_for_node,- )- },+ AccessibilityRequest::Ancestors,)}@@ -3287,17 +3101,7 @@ impl PageVm {self.accessibility_payloads_for_object_id(inspector_session_id,object_id,- |document, styles, node_id, backend_node_ids| {- let mut backend_node_id_for_node =- |node_id| backend_node_ids.get(&node_id).copied();- moli_dom::accessibility::accessibility_partial_tree_payloads_for_document_with_backend_node_ids(- document,- styles,- node_id,- fetch_relatives,- &mut backend_node_id_for_node,- )- },+ AccessibilityRequest::Partial { fetch_relatives },)}@@ -3305,12 +3109,7 @@ impl PageVm {&mut self,inspector_session_id: Option<&str>,object_id: &str,- build_payloads: impl FnOnce(- &DomHost,- &moli_dom::accessibility::AccessibilityInput,- DomHandle,- &HashMap<DomHandle, u32>,- ) -> Option<Vec<serde_json::Value>>,+ request: AccessibilityRequest,) -> Result<Option<RendererAccessibilityPayloadsForObjectId>> {let Some(handle) = self.vm_mut()@@ -3318,7 +3117,7 @@ impl PageVm {else {return Ok(None);};- Ok(self.accessibility_payloads_for_live_handle(handle, build_payloads))+ Ok(self.accessibility_payloads_for_live_handle(handle, request))}pub(crate) fn outer_html_for_object_id(diff --git a/moli-renderer-v8/src/runtime/page_vm/mod.rs b/moli-renderer-v8/src/runtime/page_vm/mod.rsindex ed0c8d20d..371014fe0 100644--- a/moli-renderer-v8/src/runtime/page_vm/mod.rs+++ b/moli-renderer-v8/src/runtime/page_vm/mod.rs@@ -4810,7 +4810,7 @@ impl PageVm {}pub(super) fn renderer_backend_node_id_for_live_handle(- &mut self,+ &self,handle: DomHandle,) -> Option<u32> {let document_id = self.vm().document_id_for_live_node_handle(handle)?;@@ -4831,7 +4831,7 @@ impl PageVm {}fn renderer_backend_node_id_for_node_key(- &mut self,+ &self,document_id: DocumentId,handle: DomHandle,) -> u32 {diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/accessibility.rs b/moli-renderer-v8/src/runtime/page_vm/tests/accessibility.rsindex c3a74ca04..3ab8197ab 100644--- a/moli-renderer-v8/src/runtime/page_vm/tests/accessibility.rs+++ b/moli-renderer-v8/src/runtime/page_vm/tests/accessibility.rs@@ -1,5 +1,58 @@use super::*;+#[tokio::test(flavor = "current_thread")]+async fn local_accessibility_requests_only_allocate_backend_ids_used_by_the_payload() {+ run_page_vm_async_test(async move {+ let loader = crate::network::ResourceRequestClient::new(&FetchConfig::default())?;+ let mut page = test_page_vm_with_loader_and_document_url(+ &loader,+ Vec::new(),+ Url::parse("https://example.test/ax-lazy.html")?,+ );+ page.vm_mut().eval(r#"+ document.body.innerHTML = '<span id=before></span><div id=local><button id=target aria-label=Action><span>Contents</span></button></div><div id=unrelated></div><span id=after></span>';+ unrelated.innerHTML = '<div><button>Unrelated</button></div>'.repeat(512);+ "#)?;+ let handle = |id| {+ page.vm().document_runtime.dom_host()+ .element_handle_by_id(id).expect("fixture element")+ };+ let (before, target, after) = (handle("before"), handle("target"), handle("after"));+ let before_id = page.renderer_backend_node_id_for_live_handle(before)+ .expect("before marker");+ let payload = page.accessibility_node_payload_for_live_handle(target)+ .expect("local AX node");+ assert_eq!(payload["name"]["value"], "Action");+ let after_id = page.renderer_backend_node_id_for_live_handle(after)+ .expect("after marker");+ let mut referenced = std::collections::HashSet::from([+ payload["backendDOMNodeId"].as_u64().expect("backend id") as u32,+ ]);+ referenced.insert(+ payload["parentId"].as_str().expect("parent ref")+ .strip_prefix("AX-").expect("AX ref").parse::<u32>()?,+ );+ for child in payload["childIds"].as_array().expect("direct child refs") {+ referenced.insert(+ child.as_str().expect("child ref")+ .strip_prefix("AX-").expect("AX ref").parse::<u32>()?,+ );+ }+ assert_eq!(+ (before_id + 1..after_id).collect::<std::collections::HashSet<_>>(),+ referenced.into_iter().filter(|id| *id > before_id).collect(),+ "AX must not allocate ids for the unrelated Document subtree",+ );+ assert_eq!(+ page.accessibility_node_payload_for_live_handle(target)+ .expect("repeated AX node"),+ payload,+ "request-local caching must preserve stable refs",+ );+ Ok::<_, anyhow::Error>(())+ }).await.expect("local AX requests must allocate refs on demand");+}+#[tokio::test(flavor = "current_thread")]async fn accessibility_style_reads_never_publish_cold_or_warm_layout() {run_page_vm_async_test(async move {diff --git a/moli-renderer-v8/src/script_vm/layout.rs b/moli-renderer-v8/src/script_vm/layout.rsindex da563c1eb..62094cf42 100644--- a/moli-renderer-v8/src/script_vm/layout.rs+++ b/moli-renderer-v8/src/script_vm/layout.rs@@ -1,12 +1,25 @@use super::*;+impl moli_dom::accessibility::AccessibilityStyleSource+ for crate::native_bridge::element::StyleObservation<'_>+{+ fn element_style(+ &mut self,+ node_id: DomHandle,+ ) -> Option<moli_dom::accessibility::AccessibilityStyle> {+ self.read(node_id).accessibility_style()+ }+}+impl ScriptVm {- pub(crate) fn accessibility_input(+ pub(crate) fn accessibility_payloads(&self,- handles: &[DomHandle],- ) -> Option<moli_dom::accessibility::AccessibilityInput> {+ handle: DomHandle,+ request: moli_dom::accessibility::AccessibilityRequest,+ backend_node_id_for_node: &mut dyn FnMut(DomHandle) -> Option<u32>,+ ) -> Option<Vec<serde_json::Value>> {let host = self._context_host.borrow();- let mut document = host.dom_host().owner_document_handle(*handles.first()?)?;+ let mut document = host.dom_host().owner_document_handle(handle)?;let mut frame_state = moli_dom::accessibility::AccessibilityFrameState::Active;while let Some(owner) = host.child_browsing_context_host_for_document_handle(document) {if host.dom_host().is_inert_in_document(owner) {@@ -15,15 +28,16 @@ impl ScriptVm {}document = host.dom_host().owner_document_handle(owner)?;}- let mut styles =- moli_dom::accessibility::AccessibilityInput::new(host.dom_host().len(), frame_state);let mut observation = crate::native_bridge::element::StyleObservation::new(&host);- for &handle in handles {- if host.dom_host().is_connected(handle) && host.dom_host().element(handle).is_some() {- styles.insert(handle, observation.read(handle).accessibility_style()?);- }- }- Some(styles)+ let mut input =+ moli_dom::accessibility::AccessibilityInput::new(&mut observation, frame_state);+ moli_dom::accessibility::accessibility_payloads_for_document(+ host.dom_host(),+ &mut input,+ handle,+ request,+ backend_node_id_for_node,+ )}pub(crate) fn sync_live_document_style_sources(&mut self) {diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/content_and_invalidation.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/content_and_invalidation.rsindex c235e1267..53a98f901 100644--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/content_and_invalidation.rs+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/content_and_invalidation.rs@@ -672,28 +672,30 @@ fn style_observation_reuses_current_world_without_materializing_an_update() {}#[test]-fn accessibility_style_batches_reuse_the_retained_world() {+fn accessibility_requests_reuse_the_retained_style_world() {let mut vm = new_parsed_test_vm(- "https://ax-style-batch.test/",+ "https://ax-style-request.test/","<!doctype html><div id=host><button>Action</button></div>",);vm.eval("host.attachShadow({mode:'closed'}).innerHTML='<button>Shadow action</button>'").expect("closed shadow fixture");- let handles = vm- .document_runtime- .dom_host()- .nodes()- .iter()- .map(|node| node.id())- .collect::<Vec<_>>();- vm.accessibility_input(&handles).expect("initial AX styles");+ let root = vm.document_runtime.dom_host().document_node_id();+ let ax = || {+ vm.accessibility_payloads(+ root,+ moli_dom::accessibility::AccessibilityRequest::Tree { max_depth: None },+ &mut |node| u32::try_from(node.index() + 1).ok(),+ )+ .expect("AX request")+ };+ ax();let host = vm._context_host.borrow();let updates = host.style_world_update_materializations_for_test();let full = host.style_world_full_snapshots_for_test();let environments = host.style_observation_environment_resolutions_for_test();drop(host);for _ in 0..2 {- vm.accessibility_input(&handles).expect("warm AX styles");+ ax();}let host = vm._context_host.borrow();assert_eq!(host.style_world_update_materializations_for_test(), updates);@@ -701,7 +703,7 @@ fn accessibility_style_batches_reuse_the_retained_world() {assert_eq!(host.style_observation_environment_resolutions_for_test(),environments + 2,- "each synchronous AX batch resolves its document environment once"+ "each synchronous AX request resolves its document environment once");}