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): project computed visibility and composed names

ldm04997e6d0d3f5
diff --git a/moli-dom/src/accessibility/ax_dom.rs b/moli-dom/src/accessibility/ax_dom.rs
index 818379251..443e81337 100644
--- a/moli-dom/src/accessibility/ax_dom.rs
+++ b/moli-dom/src/accessibility/ax_dom.rs
@@ -1,5 +1,9 @@
use crate::{NodeData, NodeId, native::DomHost};
+use super::ax_projection::AxTreeProjection;
+
+pub(super) const MAX_AX_NAME_VISITED_OBJECTS: usize = 100;
+
pub(super) fn ax_child_ids(
document: &DomHost,
node_id: NodeId,
@@ -45,17 +49,60 @@ fn composed_child_ids(document: &DomHost, node_id: NodeId) -> Option<Vec<NodeId>
None
}
-pub(super) fn ax_content_text(document: &DomHost, node_id: NodeId) -> String {
+pub(super) fn ax_content_text(
+ document: &DomHost,
+ projection: &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();
+ }
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 mut pending = ax_child_ids_reversed(document, node_id)
+ .map(Some)
+ .collect::<Vec<_>>();
+ let mut remaining = MAX_AX_NAME_VISITED_OBJECTS;
+ while let Some(entry) = pending.pop() {
+ let Some(node_id) = entry else {
+ text.push(' ');
+ continue;
+ };
+ if remaining == 0 {
+ break;
+ }
+ remaining -= 1;
let Some(node) = document.node(node_id) else {
continue;
};
+ let Some(state) = projection.state(node_id) else {
+ continue;
+ };
+ if state.inert_reason.is_some()
+ || (!include_hidden && (state.not_rendered || state.aria_hidden_root.is_some()))
+ {
+ continue;
+ }
+ // Unrendered ARIA references have no shared inline formatting context.
+ if state.block_level || (include_hidden && state.not_rendered) {
+ text.push(' ');
+ pending.push(None);
+ }
+ if state.hides_contents && !include_hidden {
+ 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)),
+ NodeData::Text(value) if include_hidden || state.visibility_visible => {
+ text.push_str(value.data())
+ }
+ NodeData::CDataSection(value) if include_hidden || state.visibility_visible => {
+ text.push_str(value.data())
+ }
+ _ => pending.extend(ax_child_ids_reversed(document, node_id).map(Some)),
}
}
text
diff --git a/moli-dom/src/accessibility/ax_projection.rs b/moli-dom/src/accessibility/ax_projection.rs
index c3b53d580..07c3eb8da 100644
--- a/moli-dom/src/accessibility/ax_projection.rs
+++ b/moli-dom/src/accessibility/ax_projection.rs
@@ -1,10 +1,13 @@
use crate::{
NodeData, NodeId,
forms::InputType,
- native::{DomHost, Element, NativeDom, Node},
+ native::{DomHost, Element, Node},
};
-use super::ax_dom::{ax_child_ids, ax_child_ids_reversed};
+use super::{
+ AccessibilityFrameState, AccessibilityInput,
+ ax_dom::{ax_child_ids, ax_child_ids_reversed},
+};
/// A command-local projection of the DOM into the accessibility tree.
///
@@ -14,6 +17,23 @@ use super::ax_dom::{ax_child_ids, ax_child_ids_reversed};
/// 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>>,
+}
+
+#[derive(Clone, Copy)]
+pub(super) struct AxNodeState {
+ pub(super) not_rendered: bool,
+ pub(super) visibility_visible: bool,
+ pub(super) hides_contents: bool,
+ pub(super) block_level: bool,
+ pub(super) aria_hidden_root: Option<NodeId>,
+ pub(super) inert_reason: Option<AxIgnoredReason>,
+}
+
+impl AxNodeState {
+ pub(super) fn hidden_for_name(self) -> bool {
+ self.not_rendered || !self.visibility_visible || self.aria_hidden_root.is_some()
+ }
}
pub(super) struct AxProjectedNode {
@@ -26,6 +46,11 @@ pub(super) struct AxProjectedNode {
pub(super) enum AxIgnoredReason {
Uninteresting,
AriaHiddenSubtree { root: NodeId },
+ NotRendered,
+ NotVisible,
+ InertSubtree { root: NodeId },
+ ActiveModalDialog { root: NodeId },
+ InertFrame,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -36,17 +61,107 @@ enum AxNodeInclusion {
}
impl AxTreeProjection {
- 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: &DomHost, root: NodeId) -> Self {
+ pub(super) fn build_for_node(
+ document: &DomHost,
+ node_id: NodeId,
+ styles: &AccessibilityInput,
+ ) -> Option<Self> {
+ let node_id = document.shadow_root_host(node_id).unwrap_or(node_id);
+ let node = document.node(node_id)?;
+ let root = if node.is_document() {
+ node_id
+ } else {
+ node.owner_document()?
+ };
let mut nodes = Vec::with_capacity(document.len());
nodes.resize_with(document.len(), || None);
- let mut projection = Self { nodes };
+ let mut projection = Self {
+ nodes,
+ states: vec![None; document.len()],
+ };
+ projection.observe_states(document, root, styles)?;
projection.visit(document, root);
- projection
+ 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))
+ }
+
+ 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];
+ 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);
+ }
+ 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 });
+ }
+ }
+ 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);
+ }
+ }
+ Some(())
}
pub(super) fn node(&self, node_id: NodeId) -> Option<&AxProjectedNode> {
@@ -73,6 +188,9 @@ impl AxTreeProjection {
let Some(child) = self.node(child_id) else {
continue;
};
+ if !self.is_rendered(child_id) {
+ continue;
+ }
if child.ignored_reason.is_some() {
pending.extend(child.children.iter().rev().copied());
} else {
@@ -82,8 +200,8 @@ impl AxTreeProjection {
}
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 mut pending = vec![(root, None)];
+ while let Some((node_id, projected_parent)) = pending.pop() {
let Some(node) = document.node(node_id) else {
continue;
};
@@ -92,22 +210,25 @@ impl AxTreeProjection {
AxNodeInclusion::ExcludeSubtree => continue,
AxNodeInclusion::ExcludeNode => {
pending.extend(
- ax_child_ids_reversed(document, node_id).map(|child_id| {
- (child_id, projected_parent, inherited_aria_hidden_root)
- }),
+ ax_child_ids_reversed(document, node_id)
+ .map(|child_id| (child_id, projected_parent)),
);
continue;
}
AxNodeInclusion::Include => {}
}
- let aria_hidden_root = inherited_aria_hidden_root.or_else(|| {
- node.as_element()
- .filter(|element| ax_aria_hidden(element))
- .map(|_| node_id)
- });
- let ignored_reason = aria_hidden_root
- .map(|root| AxIgnoredReason::AriaHiddenSubtree { root })
+ 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| {
@@ -119,7 +240,11 @@ impl AxTreeProjection {
self.nodes[node_id.index()] = Some(AxProjectedNode {
parent: projected_parent,
children: Vec::new(),
- ignored_reason,
+ 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()
@@ -128,24 +253,12 @@ impl AxTreeProjection {
}
pending.extend(
- ax_child_ids_reversed(document, node_id)
- .map(|child_id| (child_id, Some(node_id), aria_hidden_root)),
+ ax_child_ids_reversed(document, node_id).map(|child_id| (child_id, Some(node_id))),
);
}
}
}
-fn accessibility_root_for_node(document: &NativeDom, node_id: NodeId) -> NodeId {
- let Some(node) = document.node(node_id) else {
- return document.document_node_id();
- };
- if node.is_document() {
- return node_id;
- }
- node.owner_document()
- .unwrap_or_else(|| document.document_node_id())
-}
-
fn ax_node_inclusion(node: &Node) -> AxNodeInclusion {
match node.kind() {
NodeData::Document(_) => AxNodeInclusion::Include,
@@ -200,6 +313,12 @@ fn ax_element_inclusion(element: &Element) -> AxNodeInclusion {
}
fn ax_aria_hidden(element: &Element) -> bool {
+ if element.is_html_element("html")
+ || element.is_html_element("body")
+ || element.is_html_option()
+ {
+ return false;
+ }
element
.attribute("aria-hidden")
.is_some_and(|value| value.trim().eq_ignore_ascii_case("true"))
@@ -258,6 +377,7 @@ fn ax_is_uninteresting_container(document: &DomHost, node_id: NodeId, element: &
#[cfg(test)]
mod tests {
use super::*;
+ use crate::native::NativeDom;
#[test]
fn build_handles_deep_dom_without_call_stack_growth() {
@@ -277,7 +397,12 @@ mod tests {
}
let document = DomHost::from_dom(document);
- let projection = AxTreeProjection::build_for_node(&document, document.document_node_id());
+ let projection = AxTreeProjection::build_for_node(
+ &document,
+ document.document_node_id(),
+ &AccessibilityInput::visible_fixture(&document),
+ )
+ .expect("fixture projection");
assert_eq!(
projection.node(parent).and_then(|node| node.parent),
document.node(parent).and_then(Node::parent_node_id)
@@ -317,7 +442,10 @@ mod tests {
}));
}
- let projection = AxTreeProjection { nodes };
+ let projection = AxTreeProjection {
+ nodes,
+ states: Vec::new(),
+ };
assert_eq!(
projection.unignored_children(root),
vec![chain_leaf, sibling]
diff --git a/moli-dom/src/accessibility/ax_properties.rs b/moli-dom/src/accessibility/ax_properties.rs
index 3665d4836..cd5b16d31 100644
--- a/moli-dom/src/accessibility/ax_properties.rs
+++ b/moli-dom/src/accessibility/ax_properties.rs
@@ -7,37 +7,46 @@ use serde_json::{Value, json};
use std::collections::HashSet;
use url::Url;
-use super::ax_dom::ax_content_text;
+use super::ax_dom::{MAX_AX_NAME_VISITED_OBJECTS, ax_content_text};
+use super::ax_projection::AxTreeProjection;
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.
-const MAX_AX_NAME_VISITED_OBJECTS: usize = 100;
-
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AxNameTraversal {
Direct,
- AriaReference,
+ AriaReference { include_hidden: bool },
NativeLabel,
}
impl AxNameTraversal {
fn follows_aria_labelledby(self) -> bool {
- !matches!(self, Self::AriaReference)
+ !matches!(self, Self::AriaReference { .. })
}
fn includes_contents(self) -> bool {
!matches!(self, Self::Direct)
}
+
+ fn includes_hidden(self) -> bool {
+ matches!(
+ self,
+ Self::AriaReference {
+ include_hidden: true
+ }
+ )
+ }
}
-pub(super) fn ax_name(document: &DomHost, node: &Node) -> String {
+pub(super) fn ax_name(document: &DomHost, projection: &AxTreeProjection, node: &Node) -> String {
match node.kind() {
NodeData::Document(_) => ax_document_name(document),
NodeData::Element(_) => ax_node_name(
document,
+ projection,
node.id(),
AxNameTraversal::Direct,
&mut HashSet::new(),
@@ -57,19 +66,26 @@ pub(super) fn ax_name(document: &DomHost, node: &Node) -> String {
/// tooltip-style fallbacks.
fn ax_node_name(
document: &DomHost,
+ projection: &AxTreeProjection,
node_id: NodeId,
traversal: AxNameTraversal,
visited: &mut HashSet<NodeId>,
) -> String {
+ let Some(state) = projection.state(node_id) else {
+ return String::new();
+ };
+ if state.inert_reason.is_some() || (!traversal.includes_hidden() && state.hidden_for_name()) {
+ return String::new();
+ }
if visited.len() >= MAX_AX_NAME_VISITED_OBJECTS || !visited.insert(node_id) {
return String::new();
}
let name = match document.node(node_id) {
Some(node) => match node.kind() {
- NodeData::Element(element) => {
- ax_element_name(document, node_id, node, element, traversal, visited)
- }
+ 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),
@@ -87,6 +103,7 @@ fn ax_node_name(
fn ax_element_name(
document: &DomHost,
+ projection: &AxTreeProjection,
node_id: NodeId,
node: &Node,
element: &Element,
@@ -107,7 +124,16 @@ fn ax_element_name(
return label_ids
.into_iter()
.map(|label_id| {
- ax_node_name(document, label_id, AxNameTraversal::AriaReference, visited)
+ 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<_>>()
@@ -122,7 +148,9 @@ fn ax_element_name(
}
}
- if let Some(native_name) = ax_native_element_name(document, node_id, element, visited) {
+ if let Some(native_name) =
+ ax_native_element_name(document, projection, node_id, element, visited)
+ {
return native_name;
}
@@ -132,7 +160,12 @@ 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(&ax_content_text(document, node_id))
+ normalize_ax_whitespace(&ax_content_text(
+ document,
+ projection,
+ node_id,
+ traversal.includes_hidden(),
+ ))
} else {
String::new()
};
@@ -159,6 +192,7 @@ fn ax_element_name(
fn ax_native_element_name(
document: &DomHost,
+ projection: &AxTreeProjection,
node_id: NodeId,
element: &Element,
visited: &mut HashSet<NodeId>,
@@ -170,7 +204,13 @@ fn ax_native_element_name(
labels
.into_iter()
.map(|label_id| {
- ax_node_name(document, label_id, AxNameTraversal::NativeLabel, visited)
+ ax_node_name(
+ document,
+ projection,
+ label_id,
+ AxNameTraversal::NativeLabel,
+ visited,
+ )
})
.filter(|part| !part.is_empty())
.collect::<Vec<_>>()
@@ -859,7 +899,10 @@ mod tests {
fn node_name(document: &NativeDom, node_id: NodeId) -> String {
let host = DomHost::from_dom(document.clone());
- ax_name(&host, host.node(node_id).expect("named node"))
+ 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"))
}
#[test]
diff --git a/moli-dom/src/accessibility/ax_styles.rs b/moli-dom/src/accessibility/ax_styles.rs
new file mode 100644
index 000000000..a6d5986e3
--- /dev/null
+++ b/moli-dom/src/accessibility/ax_styles.rs
@@ -0,0 +1,58 @@
+use crate::NodeId;
+
+/// Final computed facts needed by AX. The renderer owns style observation;
+/// accessibility never reads CSS declarations or published layout boxes.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct AccessibilityStyle {
+ pub display_none: bool,
+ pub visibility_visible: bool,
+ pub hides_contents: bool,
+ pub block_level: bool,
+}
+
+pub struct AccessibilityInput {
+ elements: Vec<Option<AccessibilityStyle>>,
+ pub(super) frame_state: AccessibilityFrameState,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum AccessibilityFrameState {
+ Active,
+ Inert,
+}
+
+impl AccessibilityInput {
+ pub fn new(node_count: usize, frame_state: AccessibilityFrameState) -> Self {
+ Self {
+ elements: vec![None; node_count],
+ 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.rs
index 6b148ed4c..36bbac905 100644
--- a/moli-dom/src/accessibility/ax_tree.rs
+++ b/moli-dom/src/accessibility/ax_tree.rs
@@ -15,21 +15,23 @@ use super::ax_roles::{ax_role, cdp_node_id, ordered_list_item_index};
pub fn accessibility_tree_payloads_for_document(
document: &DomHost,
+ styles: &super::AccessibilityInput,
root: NodeId,
max_depth: Option<i32>,
-) -> Vec<Value> {
+) -> 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,
)
- .unwrap_or_default()
}
pub fn accessibility_tree_payloads_for_document_with_backend_node_ids(
document: &DomHost,
+ styles: &super::AccessibilityInput,
root: NodeId,
max_depth: Option<i32>,
backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,
@@ -37,8 +39,8 @@ pub fn accessibility_tree_payloads_for_document_with_backend_node_ids(
// 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) {
+ let projection = AxTreeProjection::build_for_node(document, root, styles)?;
+ if !projection.is_rendered(root) {
return Some(Vec::new());
}
@@ -80,11 +82,13 @@ pub fn accessibility_tree_payloads_for_document_with_backend_node_ids(
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,
)
@@ -92,35 +96,48 @@ pub fn accessibility_node_payload_for_document(
pub fn accessibility_node_payload_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<Value> {
- let projection = AxTreeProjection::build_for_node(document, node_id);
- let projected = projection.node(node_id)?;
+ let projection = AxTreeProjection::build_for_node(document, node_id, styles)?;
let node = document.node(node_id)?;
- ax_node_payload(document, node_id, node, projected, backend_node_id_for_node)
+ 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,
-) -> Vec<Value> {
+) -> 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,
)
- .unwrap_or_default()
}
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);
- if !projection.contains(node_id) {
+ let projection = AxTreeProjection::build_for_node(document, node_id, styles)?;
+ document.node(node_id)?;
+ if !projection.is_rendered(node_id) {
return Some(Vec::new());
}
let mut nodes = Vec::new();
@@ -136,23 +153,32 @@ pub fn accessibility_child_node_payloads_for_document_with_backend_node_ids(
pub fn accessibility_node_and_ancestor_payloads_for_document(
document: &DomHost,
+ styles: &super::AccessibilityInput,
node_id: NodeId,
-) -> Vec<Value> {
+) -> 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,
)
- .unwrap_or_default()
}
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);
+ 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(
+ node_id,
+ backend_node_id_for_node,
+ )?]);
+ }
let mut chain = Vec::new();
let mut current = Some(node_id);
while let Some(current_id) = current {
@@ -164,6 +190,7 @@ pub fn accessibility_node_and_ancestor_payloads_for_document_with_backend_node_i
};
chain.push(ax_node_payload(
document,
+ &projection,
current_id,
node,
projected,
@@ -176,12 +203,14 @@ pub fn accessibility_node_and_ancestor_payloads_for_document_with_backend_node_i
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,
@@ -190,23 +219,29 @@ pub fn accessibility_partial_tree_payloads_for_document(
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);
+ 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![ax_node_payload(
- document,
- node_id,
- node,
- projected,
- backend_node_id_for_node,
- )?];
+ 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.ignored_reason.is_none() {
+ if projected.is_some_and(|projected| projected.ignored_reason.is_none()) {
add_ax_children(
document,
&projection,
@@ -216,7 +251,18 @@ pub fn accessibility_partial_tree_payloads_for_document_with_backend_node_ids(
);
}
- let mut current = projected.parent;
+ 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;
@@ -226,6 +272,7 @@ pub fn accessibility_partial_tree_payloads_for_document_with_backend_node_ids(
};
nodes.push(ax_node_payload(
document,
+ &projection,
current_id,
current_node,
current_projected,
@@ -242,6 +289,20 @@ pub fn accessibility_partial_tree_payloads_for_document_with_backend_node_ids(
// Private helpers
// ---------------------------------------------------------------------------
+fn ax_dom_node_without_object_payload(
+ node_id: NodeId,
+ backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,
+) -> Option<Value> {
+ let backend_node_id = backend_node_id_for_node(node_id)?;
+ Some(json!({
+ "nodeId": format!("AX-{backend_node_id}"),
+ "backendDOMNodeId": backend_node_id,
+ "ignored": true,
+ "role": {"type": "role", "value": "none"},
+ "ignoredReasons": [{"name": "notRendered", "value": {"type": "boolean", "value": true}}],
+ }))
+}
+
fn add_ax_children(
document: &DomHost,
projection: &AxTreeProjection,
@@ -258,6 +319,9 @@ fn add_ax_children(
let Some(child) = projection.node(child_id) else {
continue;
};
+ if !projection.is_rendered(child_id) {
+ continue;
+ }
push_ax_node_payload(
document,
projection,
@@ -284,9 +348,14 @@ fn push_ax_node_payload(
let Some(projected) = projection.node(node_id) else {
return false;
};
- let Some(payload) =
- ax_node_payload(document, node_id, node, projected, backend_node_id_for_node)
- else {
+ let Some(payload) = ax_node_payload(
+ document,
+ projection,
+ node_id,
+ node,
+ projected,
+ backend_node_id_for_node,
+ ) else {
return false;
};
out.push(payload);
@@ -301,6 +370,7 @@ fn push_ax_node_payload(
fn ax_node_payload(
document: &DomHost,
+ projection: &AxTreeProjection,
node_id: NodeId,
node: &Node,
projected: &super::ax_projection::AxProjectedNode,
@@ -315,7 +385,7 @@ fn ax_node_payload(
if let Some(reason) = projected.ignored_reason {
payload.insert(
"ignoredReasons".to_owned(),
- ax_ignored_reasons_payload(document, reason, backend_node_id_for_node),
+ ax_ignored_reasons_payload(document, node_id, reason, backend_node_id_for_node),
);
}
payload.insert(
@@ -327,7 +397,7 @@ fn ax_node_payload(
);
if !ignored {
- let name = ax_name(document, node);
+ let name = ax_name(document, projection, node);
if !name.is_empty() {
payload.insert(
"name".to_owned(),
@@ -365,6 +435,7 @@ fn ax_node_payload(
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}"))
@@ -378,18 +449,29 @@ fn ax_node_payload(
fn ax_ignored_reasons_payload(
document: &DomHost,
+ node_id: NodeId,
reason: AxIgnoredReason,
backend_node_id_for_node: &mut impl FnMut(NodeId) -> Option<u32>,
) -> Value {
match reason {
- AxIgnoredReason::Uninteresting => json!([{
- "name": "uninteresting",
+ AxIgnoredReason::Uninteresting
+ | AxIgnoredReason::NotRendered
+ | AxIgnoredReason::InertFrame
+ | AxIgnoredReason::NotVisible => json!([{
+ "name": match reason {
+ AxIgnoredReason::NotRendered => "notRendered",
+ AxIgnoredReason::InertFrame => "inertSubtree",
+ AxIgnoredReason::NotVisible => "notVisible",
+ _ => "uninteresting",
+ },
"value": {
"type": "boolean",
"value": true,
}
}]),
- AxIgnoredReason::AriaHiddenSubtree { root } => {
+ AxIgnoredReason::AriaHiddenSubtree { root }
+ | AxIgnoredReason::InertSubtree { root }
+ | AxIgnoredReason::ActiveModalDialog { root } => {
let mut related_node = serde_json::Map::new();
if let Some(backend_node_id) = backend_node_id_for_node(root) {
related_node.insert("backendDOMNodeId".to_owned(), json!(backend_node_id));
@@ -402,7 +484,12 @@ fn ax_ignored_reasons_payload(
related_node.insert("idref".to_owned(), json!(idref));
}
json!([{
- "name": "ariaHiddenSubtree",
+ "name": match reason {
+ AxIgnoredReason::InertSubtree { .. } if root == node_id => "inertElement",
+ AxIgnoredReason::InertSubtree { .. } => "inertSubtree",
+ AxIgnoredReason::ActiveModalDialog { .. } => "activeModalDialog",
+ _ => "ariaHiddenSubtree",
+ },
"value": {
"type": "idref",
"relatedNodes": [Value::Object(related_node)],
diff --git a/moli-dom/src/accessibility/mod.rs b/moli-dom/src/accessibility/mod.rs
index e9505016f..4059cb761 100644
--- a/moli-dom/src/accessibility/mod.rs
+++ b/moli-dom/src/accessibility/mod.rs
@@ -2,8 +2,11 @@ mod ax_dom;
mod ax_projection;
mod ax_properties;
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,
diff --git a/moli-dom/src/accessibility/tests.rs b/moli-dom/src/accessibility/tests.rs
index a53e3f2b8..987369c4d 100644
--- a/moli-dom/src/accessibility/tests.rs
+++ b/moli-dom/src/accessibility/tests.rs
@@ -7,7 +7,13 @@ use crate::{
};
fn tree(document: &DomHost) -> Vec<Value> {
- accessibility_tree_payloads_for_document(document, document.document_node_id(), None)
+ accessibility_tree_payloads_for_document(
+ document,
+ &AccessibilityInput::visible_fixture(document),
+ document.document_node_id(),
+ None,
+ )
+ .expect("fixture AX tree")
}
fn document_with_host() -> (DomHost, NodeId) {
@@ -45,6 +51,59 @@ fn button_names(nodes: &[Value]) -> Vec<&str> {
.collect()
}
+#[test]
+fn ax_requires_styles_for_connected_elements() {
+ let (document, _) = document_with_host();
+ assert!(
+ accessibility_tree_payloads_for_document(
+ &document,
+ &AccessibilityInput::new(document.len(), AccessibilityFrameState::Active),
+ document.document_node_id(),
+ None,
+ )
+ .is_none(),
+ "missing computed style must not become a visible default"
+ );
+}
+
+#[test]
+fn ax_hidden_reference_names_cross_transparent_shadow_roots() {
+ for mode in ["open", "closed"] {
+ let (mut document, host) = document_with_host();
+ assert!(document.set_attribute(host, "id", "label"));
+ append_text(&mut document, host, "assigned");
+ let root = document
+ .attach_shadow_root(host, mode)
+ .expect("shadow root");
+ append_text(&mut document, root, "Shadow ");
+ append_element(&mut document, root, "slot");
+ 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);
+ styles.insert(
+ host,
+ AccessibilityStyle {
+ display_none: true,
+ visibility_visible: true,
+ hides_contents: false,
+ block_level: true,
+ },
+ );
+ let nodes = accessibility_tree_payloads_for_document(&document, &styles, document_id, None)
+ .expect("AX tree");
+ assert_eq!(
+ node_by_id(&nodes, button)["name"]["value"],
+ "Shadow assigned"
+ );
+ assert!(
+ !nodes
+ .iter()
+ .any(|node| node["backendDOMNodeId"] == super::ax_roles::cdp_node_id(host))
+ );
+ }
+}
+
#[test]
fn ax_tree_queries_shadow_roots_from_hosts() {
for mode in ["open", "closed"] {
@@ -58,7 +117,13 @@ 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(&document, root, None);
+ let nodes = accessibility_tree_payloads_for_document(
+ &document,
+ &AccessibilityInput::visible_fixture(&document),
+ root,
+ None,
+ )
+ .expect("fixture AX tree");
assert_eq!(
nodes[0]["backendDOMNodeId"],
super::ax_roles::cdp_node_id(host)
@@ -122,7 +187,12 @@ 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(&document, button);
+ let ancestors = accessibility_node_and_ancestor_payloads_for_document(
+ &document,
+ &AccessibilityInput::visible_fixture(&document),
+ button,
+ )
+ .expect("fixture AX ancestors");
let backend_ids = ancestors
.iter()
.map(|node| node["backendDOMNodeId"].clone())
diff --git a/moli-dom/src/native/host.rs b/moli-dom/src/native/host.rs
index b83f3adae..f2847fa75 100644
--- a/moli-dom/src/native/host.rs
+++ b/moli-dom/src/native/host.rs
@@ -14,6 +14,7 @@ use super::{Element, LiveDomNodeMetadata, NativeDom, NativeNodeId, Node, NodeTyp
mod clone;
mod collections;
mod document;
+mod flat_tree;
mod html_serialization;
mod mutation;
mod parser;
diff --git a/moli-dom/src/native/host/flat_tree.rs b/moli-dom/src/native/host/flat_tree.rs
new file mode 100644
index 000000000..0e185eb66
--- /dev/null
+++ b/moli-dom/src/native/host/flat_tree.rs
@@ -0,0 +1,58 @@
+use super::*;
+
+impl DomHost {
+ /// Includes the ShadowRoot as a transparent link. Unassigned light nodes
+ /// and replaced slot fallback have no parent in the composed tree.
+ pub fn composed_parent(&self, node: DomHandle) -> Option<DomHandle> {
+ if let Some(host) = self.shadow_root_host(node) {
+ return Some(host);
+ }
+ if let Some(slot) = self.assigned_slot_for_node(node) {
+ return Some(slot);
+ }
+ let parent = self.parent_node(node)?;
+ if self.shadow_root_handle(parent).is_some()
+ || (self.is_html_element_named(parent, "slot")
+ && self.containing_shadow_root(parent).is_some()
+ && !self
+ .assigned_nodes_for_slot_with_options(parent, false)
+ .is_empty())
+ {
+ return None;
+ }
+ Some(parent)
+ }
+
+ pub fn active_modal_dialog_for_document(&self, document: DomHandle) -> Option<DomHandle> {
+ self.nodes().iter().rev().find_map(|node| {
+ if !node.is_connected() || self.owner_document_handle(node.id()) != Some(document) {
+ return None;
+ }
+ let element = node.as_element()?;
+ (element.is_html_element("dialog")
+ && element.dialog_modal()
+ && element.has_attribute("open"))
+ .then_some(node.id())
+ })
+ }
+
+ pub fn is_inert_in_document(&self, node: DomHandle) -> bool {
+ let modal = self
+ .owner_document_handle(node)
+ .and_then(|document| self.active_modal_dialog_for_document(document));
+ let mut current = Some(node);
+ while let Some(id) = current {
+ if self.element(id).is_some_and(|element| {
+ element.namespace() == "http://www.w3.org/1999/xhtml"
+ && element.has_attribute("inert")
+ }) {
+ return true;
+ }
+ if Some(id) == modal {
+ return false;
+ }
+ current = self.composed_parent(id);
+ }
+ modal.is_some()
+ }
+}
diff --git a/moli-protocol/src/domains/accessibility/tests.rs b/moli-protocol/src/domains/accessibility/tests.rs
index dd2ab9312..3bc33da04 100644
--- a/moli-protocol/src/domains/accessibility/tests.rs
+++ b/moli-protocol/src/domains/accessibility/tests.rs
@@ -58,6 +58,103 @@ async fn complete_child_frame_lifecycle(ctx: &mut TestContext) {
);
}
+#[tokio::test(flavor = "multi_thread")]
+async fn ax_snapshot_filters_computed_visibility_without_losing_visible_overrides() {
+ let mut ctx = TestContext::new();
+ load_page_async(&mut ctx, r#"<!doctype html><style>
+ .none { display:none } .shown { display:block }
+ </style><body>
+ <button>Visible</button><button class=none>Display none</button>
+ <button style='visibility:collapse'>Collapsed</button>
+ <button style='position:absolute;left:100000px'>Offscreen</button>
+ <button hidden>Hidden</button><button hidden class=shown>Hidden override</button>
+ <div style='visibility:hidden'><button>Invisible</button>
+ <button style='visibility:visible'>Visibility override</button></div>
+ <div inert><button>Inert</button></div>
+ <div role=button style='content-visibility:hidden'>Hidden contents<button>CV child</button></div>
+ <div hidden=until-found><button>Until found child</button></div>
+ <div hidden=until-found style='content-visibility:visible'><button>Until found override</button></div>
+ <div style='content-visibility:hidden;display:contents'><button>CV contents</button></div>
+ <div style='content-visibility:hidden;display:inline'><button>CV inline</button></div>
+ <button style='opacity:0'>Transparent</button>
+ <button style='width:0;height:0;padding:0;border:0'>Zero size</button>
+ <div role=button style='display:contents'>Contents host</div>
+ </body>"#).await;
+ ctx.process_async(json!({"id":1,"method":"Accessibility.getFullAXTree"}))
+ .await;
+ let response = ctx.take_response_by_id(1);
+ let nodes = response["result"]["nodes"].as_array().expect("AX nodes");
+ let mut names = nodes
+ .iter()
+ .filter(|node| node["role"]["value"] == "button")
+ .map(|node| node["name"]["value"].as_str().unwrap_or_default())
+ .collect::<Vec<_>>();
+ names.sort_unstable();
+ assert_eq!(
+ names,
+ [
+ "",
+ "CV contents",
+ "CV inline",
+ "Contents host",
+ "Hidden override",
+ "Offscreen",
+ "Transparent",
+ "Until found override",
+ "Visibility override",
+ "Visible",
+ "Zero size"
+ ]
+ );
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn ax_names_filter_hidden_contents_and_preserve_hidden_aria_reference_roots() {
+ let mut ctx = TestContext::new();
+ load_page_async(&mut ctx, r#"<!doctype html><body>
+ <button>Direct<span style='display:none'> hidden</span><span aria-hidden=true> aria</span></button>
+ <button>Before<span style='content-visibility:hidden;display:block'>CV hidden</span>After</button>
+ <button>Before<span inert>Inert hidden</span>After</button>
+ <span id=visible>Visible label<span style='display:none'> hidden</span></span>
+ <button aria-labelledby=visible></button>
+ <span id=hidden style='display:none'>Hidden root<span aria-hidden=true>hidden aria child</span></span>
+ <button aria-labelledby=hidden></button>
+ <label for=native>Native label<span style='display:none'> hidden</span></label><input id=native>
+ <label for=nativeHidden style='display:none'>Hidden native label</label><input id=nativeHidden>
+ <span id=inert inert>Inert label</span><button aria-labelledby=inert></button>
+ <div id=host role=button>assigned text</div>
+ <script>host.attachShadow({mode:'closed'}).innerHTML='Shadow <slot></slot>';</script>
+ </body>"#).await;
+ ctx.process_async(json!({"id":1,"method":"Accessibility.getFullAXTree"}))
+ .await;
+ let response = ctx.take_response_by_id(1);
+ let nodes = response["result"]["nodes"].as_array().expect("AX nodes");
+ let mut names = nodes
+ .iter()
+ .filter(|node| node["role"]["value"] == "button")
+ .map(|node| node["name"]["value"].as_str().unwrap_or_default())
+ .collect::<Vec<_>>();
+ names.sort_unstable();
+ assert_eq!(
+ names,
+ [
+ "",
+ "Before After",
+ "BeforeAfter",
+ "Direct",
+ "Hidden root hidden aria child",
+ "Shadow assigned text",
+ "Visible label"
+ ]
+ );
+ let input_names = nodes
+ .iter()
+ .filter(|node| node["role"]["value"] == "textbox")
+ .map(|node| node["name"]["value"].as_str().unwrap_or_default())
+ .collect::<Vec<_>>();
+ assert_eq!(input_names, ["Native label", ""]);
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn query_ax_tree_shadow_root_uses_all_node_reference_kinds() {
for mode in ["open", "closed"] {
@@ -150,6 +247,314 @@ async fn query_ax_tree_shadow_root_uses_all_node_reference_kinds() {
}
}
+#[tokio::test(flavor = "multi_thread")]
+async fn ax_style_mutations_preserve_refs_and_hidden_node_queries() {
+ let mut ctx = TestContext::new();
+ load_page_async(
+ &mut ctx,
+ r#"<!doctype html><html><body><div id=host>
+ <button id=target>Live action</button></div><script>
+ globalThis.axRoot = host.attachShadow({mode:'closed'});
+ axRoot.innerHTML = '<slot></slot>';
+ </script></body></html>"#,
+ )
+ .await;
+ ctx.process_async(json!({"id":1,"method":"Accessibility.enable"}))
+ .await;
+ assert!(ctx.take_response_by_id(1).get("result").is_some());
+ ctx.process_async(json!({"id":2,"method":"Accessibility.getFullAXTree"}))
+ .await;
+ let full = ctx.take_response_by_id(2);
+ let initial = find_ax_node(
+ full["result"]["nodes"].as_array().expect("AX nodes"),
+ "button",
+ "Live action",
+ )
+ .clone();
+ let backend = renderer_backend_dom_node_id(&initial);
+ let ax_id = renderer_backed_ax_node_id(&initial);
+ dom_document_node_id_async(&mut ctx, None, 3).await;
+ ctx.process_async(json!({"id":4,"method":"Runtime.evaluate","params":{"expression":"document.getElementById('target')"}})).await;
+ let object = ctx.take_response_by_id(4)["result"]["result"]["objectId"]
+ .as_str()
+ .expect("target object")
+ .to_owned();
+ ctx.process_async(json!({"id":5,"method":"DOM.requestNode","params":{"objectId":object}}))
+ .await;
+ let frontend = ctx.take_response_by_id(5)["result"]["nodeId"]
+ .as_u64()
+ .expect("frontend node");
+ for (mutation, reason) in [
+ ("target.style.display='none'", "notRendered"),
+ (
+ "target.style.display='';target.style.visibility='hidden'",
+ "notVisible",
+ ),
+ (
+ "target.style.visibility='';target.inert=true",
+ "inertElement",
+ ),
+ ] {
+ ctx.process_async(
+ json!({"id":10,"method":"Runtime.evaluate","params":{"expression":mutation}}),
+ )
+ .await;
+ assert!(
+ ctx.take_response_by_id(10)["result"]
+ .get("exceptionDetails")
+ .is_none()
+ );
+ for reference in [
+ json!({"nodeId":frontend}),
+ json!({"backendNodeId":backend}),
+ json!({"objectId":object}),
+ ] {
+ let mut params = reference.clone();
+ params["fetchRelatives"] = json!(false);
+ ctx.process_async(
+ json!({"id":11,"method":"Accessibility.getPartialAXTree","params":params}),
+ )
+ .await;
+ let partial = ctx.take_response_by_id(11);
+ let nodes = partial["result"]["nodes"]
+ .as_array()
+ .expect("partial AX nodes");
+ assert_eq!(nodes.len(), 1);
+ assert_eq!(nodes[0]["ignored"], true);
+ assert_eq!(nodes[0]["backendDOMNodeId"], backend);
+ assert_eq!(nodes[0]["nodeId"], ax_id);
+ assert_eq!(nodes[0]["ignoredReasons"][0]["name"], reason);
+ ctx.process_async(
+ json!({"id":12,"method":"Accessibility.queryAXTree","params":reference}),
+ )
+ .await;
+ assert!(
+ ctx.take_response_by_id(12)["result"]["nodes"]
+ .as_array()
+ .expect("query nodes")
+ .iter()
+ .all(|node| node["ignored"] == true)
+ );
+ }
+ ctx.process_async(json!({"id":13,"method":"Accessibility.getAXNodeAndAncestors","params":{"backendNodeId":backend}})).await;
+ let ancestors = ctx.take_response_by_id(13);
+ let nodes = ancestors["result"]["nodes"].as_array().expect("ancestors");
+ assert_eq!(nodes[0]["ignored"], true);
+ assert_eq!(
+ nodes.last().expect("root ancestor")["role"]["value"],
+ "RootWebArea"
+ );
+ ctx.process_async(
+ json!({"id":14,"method":"Accessibility.getChildAXNodes","params":{"id":ax_id}}),
+ )
+ .await;
+ let children = ctx.take_response_by_id(14);
+ assert!(
+ children["result"]["nodes"]
+ .as_array()
+ .expect("AX children")
+ .iter()
+ .all(|node| node["ignored"] == true)
+ );
+ }
+ ctx.process_async(
+ json!({"id":20,"method":"Runtime.evaluate","params":{"expression":"target.inert=false"}}),
+ )
+ .await;
+ ctx.take_response_by_id(20);
+ ctx.process_async(json!({"id":21,"method":"Accessibility.getFullAXTree"}))
+ .await;
+ let restored = ctx.take_response_by_id(21);
+ let button = find_ax_node(
+ restored["result"]["nodes"].as_array().expect("AX nodes"),
+ "button",
+ "Live action",
+ );
+ assert_eq!(button["nodeId"], initial["nodeId"]);
+ assert_eq!(button["backendDOMNodeId"], initial["backendDOMNodeId"]);
+
+ ctx.process_async(
+ json!({"id":22,"method":"Runtime.evaluate","params":{"expression":"axRoot"}}),
+ )
+ .await;
+ let root_object = ctx.take_response_by_id(22)["result"]["result"]["objectId"]
+ .as_str()
+ .expect("shadow object")
+ .to_owned();
+ ctx.process_async(json!({"id":23,"method":"Accessibility.getAXNodeAndAncestors","params":{"objectId":root_object}})).await;
+ let no_object = ctx.take_response_by_id(23);
+ let nodes = no_object["result"]["nodes"]
+ .as_array()
+ .expect("transparent root placeholder");
+ assert_eq!(nodes.len(), 1);
+ assert_eq!(nodes[0]["ignoredReasons"][0]["name"], "notRendered");
+ ctx.process_async(json!({"id":24,"method":"Accessibility.getPartialAXTree","params":{"objectId":root_object}})).await;
+ let relatives = ctx.take_response_by_id(24);
+ assert!(
+ relatives["result"]["nodes"]
+ .as_array()
+ .expect("transparent root relatives")
+ .len()
+ > 1
+ );
+ ctx.process_async(json!({"id":25,"method":"Runtime.evaluate","params":{"expression":"globalThis.detachedControl=document.createElement('button');detachedControl"}})).await;
+ let detached = ctx.take_response_by_id(25)["result"]["result"]["objectId"]
+ .as_str()
+ .expect("detached object")
+ .to_owned();
+ ctx.process_async(
+ json!({"id":26,"method":"Accessibility.getPartialAXTree","params":{"objectId":detached}}),
+ )
+ .await;
+ let placeholder = ctx.take_response_by_id(26);
+ let nodes = placeholder["result"]["nodes"]
+ .as_array()
+ .expect("detached placeholder");
+ assert_eq!(nodes.len(), 1);
+ assert_eq!(nodes[0]["ignored"], true);
+ assert!(nodes[0]["backendDOMNodeId"].as_u64().is_some());
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn ax_styles_use_child_and_nested_document_cascades() {
+ let mut ctx = TestContext::new();
+ load_page_async(&mut ctx, r#"<!doctype html><html><body><style>button{display:none}</style>
+ <iframe srcdoc="<!doctype html><html><body><button hidden>Child hidden</button><button hidden style='display:block'>Child visible</button><iframe srcdoc='<!doctype html><html><body><button hidden>Nested hidden</button><button>Nested visible</button></body></html>'></iframe></body></html>"></iframe>
+ </body></html>"#).await;
+ complete_child_frame_lifecycle(&mut ctx).await;
+ let child = child_frame_id_for_single_iframe_async(&mut ctx).await;
+ let nested = nested_child_frame_id_for_single_nested_iframe_async(&mut ctx).await;
+ for (frame, name) in [(child, "Child visible"), (nested, "Nested visible")] {
+ ctx.process_async(
+ json!({"id":30,"method":"Accessibility.getFullAXTree","params":{"frameId":frame}}),
+ )
+ .await;
+ let response = ctx.take_response_by_id(30);
+ let nodes = response["result"]["nodes"]
+ .as_array()
+ .expect("frame AX nodes");
+ let buttons = nodes
+ .iter()
+ .filter(|node| node["role"]["value"] == "button")
+ .collect::<Vec<_>>();
+ assert_eq!(buttons.len(), 1);
+ assert_eq!(buttons[0]["name"]["value"], name);
+ let hidden = child_frame_renderer_backend_node_id_for_selector_async(
+ &mut ctx,
+ &frame,
+ "button[hidden]",
+ 40,
+ )
+ .await;
+ ctx.process_async(json!({"id":44,"method":"Accessibility.getPartialAXTree","params":{"backendNodeId":hidden,"frameId":frame,"fetchRelatives":false}})).await;
+ let partial = ctx.take_response_by_id(44);
+ assert_eq!(
+ partial["result"]["nodes"][0]["ignored"], true,
+ "frame partial: {partial}"
+ );
+ assert_eq!(
+ partial["result"]["nodes"][0]["ignoredReasons"][0]["name"],
+ "notRendered"
+ );
+ }
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn ax_modal_dialog_escapes_ancestor_inertness_but_not_its_own() {
+ let mut ctx = TestContext::new();
+ load_page_async(
+ &mut ctx,
+ r#"<!doctype html><html><body><button>Outside</button>
+ <div inert><dialog id=modal><button>Modal action</button></dialog></div>
+ <script>modal.showModal()</script></body></html>"#,
+ )
+ .await;
+ ctx.process_async(json!({"id":50,"method":"Accessibility.getFullAXTree"}))
+ .await;
+ let response = ctx.take_response_by_id(50);
+ let buttons = response["result"]["nodes"]
+ .as_array()
+ .expect("AX nodes")
+ .iter()
+ .filter(|node| node["role"]["value"] == "button")
+ .collect::<Vec<_>>();
+ assert_eq!(buttons.len(), 1);
+ assert_eq!(buttons[0]["name"]["value"], "Modal action");
+ ctx.process_async(
+ json!({"id":51,"method":"Runtime.evaluate","params":{"expression":"modal.inert=true"}}),
+ )
+ .await;
+ ctx.take_response_by_id(51);
+ ctx.process_async(json!({"id":52,"method":"Accessibility.getFullAXTree"}))
+ .await;
+ let response = ctx.take_response_by_id(52);
+ assert!(
+ !response["result"]["nodes"]
+ .as_array()
+ .expect("AX nodes")
+ .iter()
+ .any(|node| node["role"]["value"] == "button")
+ );
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn ax_inert_frames_block_modal_escape_and_update_nested_documents() {
+ let mut ctx = TestContext::new();
+ load_page_async(&mut ctx, r#"<!doctype html><html><body><iframe id=outer inert srcdoc="<!doctype html><html><body><dialog id=modal><button>Modal action</button></dialog><iframe srcdoc='<!doctype html><html><body><button>Nested action</button></body></html>'></iframe><script>modal.showModal()</script></body></html>"></iframe></body></html>"#).await;
+ complete_child_frame_lifecycle(&mut ctx).await;
+ let child = child_frame_id_for_single_iframe_async(&mut ctx).await;
+ let nested = nested_child_frame_id_for_single_nested_iframe_async(&mut ctx).await;
+ for frame in [&child, &nested] {
+ ctx.process_async(
+ json!({"id":60,"method":"Accessibility.getFullAXTree","params":{"frameId":frame}}),
+ )
+ .await;
+ let response = ctx.take_response_by_id(60);
+ assert!(
+ !response["result"]["nodes"]
+ .as_array()
+ .expect("inert frame AX tree")
+ .iter()
+ .any(|node| node["role"]["value"] == "button")
+ );
+ }
+ ctx.process_async(
+ json!({"id":61,"method":"Runtime.evaluate","params":{"expression":"outer.inert=false"}}),
+ )
+ .await;
+ ctx.take_response_by_id(61);
+ ctx.process_async(
+ json!({"id":62,"method":"Accessibility.getFullAXTree","params":{"frameId":child}}),
+ )
+ .await;
+ let response = ctx.take_response_by_id(62);
+ find_ax_node(
+ response["result"]["nodes"]
+ .as_array()
+ .expect("active frame AX tree"),
+ "button",
+ "Modal action",
+ );
+ ctx.process_async(json!({"id":63,"method":"Page.createIsolatedWorld","params":{"frameId":child,"worldName":"modal-close"}})).await;
+ let context = ctx.take_response_by_id(63)["result"]["executionContextId"]
+ .as_i64()
+ .expect("child world");
+ ctx.process_async(json!({"id":64,"method":"Runtime.evaluate","params":{"contextId":context,"expression":"document.getElementById('modal').close()"}})).await;
+ ctx.take_response_by_id(64);
+ ctx.process_async(
+ json!({"id":65,"method":"Accessibility.getFullAXTree","params":{"frameId":nested}}),
+ )
+ .await;
+ let response = ctx.take_response_by_id(65);
+ find_ax_node(
+ response["result"]["nodes"]
+ .as_array()
+ .expect("nested frame AX tree"),
+ "button",
+ "Nested action",
+ );
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn get_full_ax_tree_shadow_button_ref_supports_mouse_click() {
let mut ctx = TestContext::new();
diff --git a/moli-renderer-v8/src/context_bootstrap/range_algorithms/text.rs b/moli-renderer-v8/src/context_bootstrap/range_algorithms/text.rs
index 5a53e3620..b0c6d2778 100644
--- a/moli-renderer-v8/src/context_bootstrap/range_algorithms/text.rs
+++ b/moli-renderer-v8/src/context_bootstrap/range_algorithms/text.rs
@@ -392,22 +392,7 @@ fn selection_text_active_modal_dialog(
) -> Option<DomHandle> {
runtime
.dom_host()
- .dom()
- .nodes()
- .iter()
- .rev()
- .find_map(|node| {
- if !node.is_connected()
- || runtime.dom_host().owner_document_handle(node.id()) != Some(document)
- {
- return None;
- }
- let element = node.as_element()?;
- (element.is_html_element("dialog")
- && element.dialog_modal()
- && element.attribute("open").is_some())
- .then_some(node.id())
- })
+ .active_modal_dialog_for_document(document)
}
fn selection_text_is_inert(
@@ -442,10 +427,7 @@ fn selection_text_flat_tree_parent(
runtime: &crate::native_bridge::JsContextHost,
handle: DomHandle,
) -> Option<DomHandle> {
- if let Some(slot) = runtime.dom_host().assigned_slot_for_node(handle) {
- return Some(slot);
- }
- let parent = runtime.dom_host().parent_node(handle)?;
+ let parent = runtime.dom_host().composed_parent(handle)?;
if runtime.dom_host().is_shadow_root(parent) {
return runtime.dom_host().shadow_root_host(parent);
}
diff --git a/moli-renderer-v8/src/layout_renderer/style_resolver.rs b/moli-renderer-v8/src/layout_renderer/style_resolver.rs
index 4c14be7dc..cbadd94fa 100644
--- a/moli-renderer-v8/src/layout_renderer/style_resolver.rs
+++ b/moli-renderer-v8/src/layout_renderer/style_resolver.rs
@@ -151,14 +151,6 @@ impl LayoutStyleResolver<DomHandle> for NativeLayoutStyleResolver<'_> {
);
}
let phase_started = self.profile.as_ref().map(|_| Instant::now());
- if self
- .runtime
- .dom_host()
- .get_attribute(node, "hidden")
- .is_some()
- {
- resolved.force_display_none();
- }
if self.scripting_enabled
&& self
.runtime
diff --git a/moli-renderer-v8/src/native_bridge/element/geometry.rs b/moli-renderer-v8/src/native_bridge/element/geometry.rs
index 135fb54ca..d9e888f09 100644
--- a/moli-renderer-v8/src/native_bridge/element/geometry.rs
+++ b/moli-renderer-v8/src/native_bridge/element/geometry.rs
@@ -25,7 +25,6 @@ pub(in crate::native_bridge) use metrics::{
node_scroll_top_getter_function, node_scroll_top_setter_function,
node_scroll_width_getter_function,
};
-pub(super) use mock::element_has_hidden_attribute;
pub(crate) use mock::{
compute_mock_client_rect, compute_mock_intersection_client_rect,
compute_mock_intersection_scrollport_client_rect,
diff --git a/moli-renderer-v8/src/native_bridge/element/geometry/mock/layout.rs b/moli-renderer-v8/src/native_bridge/element/geometry/mock/layout.rs
index 682f85b42..07de5a98f 100644
--- a/moli-renderer-v8/src/native_bridge/element/geometry/mock/layout.rs
+++ b/moli-renderer-v8/src/native_bridge/element/geometry/mock/layout.rs
@@ -160,13 +160,6 @@ fn element_attribute(runtime: &JsContextHost, handle: DomHandle, name: &str) ->
runtime.dom_host().get_attribute(handle, name)
}
-pub(in crate::native_bridge::element) fn element_has_hidden_attribute(
- runtime: &JsContextHost,
- handle: DomHandle,
-) -> bool {
- element_attribute(runtime, handle, "hidden").is_some()
-}
-
fn element_is_hidden_input(runtime: &JsContextHost, handle: DomHandle) -> bool {
runtime
.dom_host()
@@ -181,9 +174,7 @@ fn element_is_hidden_input(runtime: &JsContextHost, handle: DomHandle) -> bool {
}
fn element_suppresses_mock_layout_subtree(runtime: &JsContextHost, handle: DomHandle) -> bool {
- element_has_hidden_attribute(runtime, handle)
- || element_is_hidden_input(runtime, handle)
- || scroll_layout_display(runtime, handle) == "none"
+ element_is_hidden_input(runtime, handle) || scroll_layout_display(runtime, handle) == "none"
}
fn scroll_layout_display(runtime: &JsContextHost, handle: DomHandle) -> String {
@@ -411,13 +402,11 @@ fn mock_client_rect(runtime: &JsContextHost, handle: DomHandle) -> ClientRect {
if !is_mock_rendered_element(runtime, handle) {
return zero_client_rect();
}
- if element_has_hidden_attribute(runtime, handle) || element_is_hidden_input(runtime, handle) {
+ if element_is_hidden_input(runtime, handle) {
return zero_client_rect();
}
if matches!(
- raw_inline_style_property_value(runtime, handle, "display")
- .unwrap_or_default()
- .as_str(),
+ scroll_layout_display(runtime, handle).as_str(),
"none" | "contents"
) {
return zero_client_rect();
diff --git a/moli-renderer-v8/src/native_bridge/element/geometry/mock/mod.rs b/moli-renderer-v8/src/native_bridge/element/geometry/mock/mod.rs
index 8da2e80be..58ee29bab 100644
--- a/moli-renderer-v8/src/native_bridge/element/geometry/mock/mod.rs
+++ b/moli-renderer-v8/src/native_bridge/element/geometry/mock/mod.rs
@@ -1,7 +1,6 @@
mod layout;
mod queries;
-pub(in crate::native_bridge::element) use layout::element_has_hidden_attribute;
pub(crate) use layout::{
compute_mock_client_rect, compute_mock_intersection_client_rect,
compute_mock_intersection_scrollport_client_rect,
diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs
index 79cfa9b91..28594b709 100644
--- a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs
+++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values.rs
@@ -12,11 +12,11 @@ use crate::{
},
document_runtime::DomHandle,
native_bridge::element::geometry::{
- ClientRect, element_has_hidden_attribute, observable_bounding_client_rects,
- observable_used_grid_tracks, read_bounding_client_rect,
+ ClientRect, observable_bounding_client_rects, observable_used_grid_tracks,
+ read_bounding_client_rect,
},
style_engine::{
- ComputedDisplayKind, ComputedRenderedStyleFacts, FullStyleWorldSnapshot, StyleViewport,
+ ComputedRenderedStyleFacts, FullStyleWorldSnapshot, StyleViewport,
StylesheetResourceSnapshot, StyloAnonymousBoxKind, StyloComputedStyleSnapshot,
StyloStylesheetSource, computed_property_is_queryable,
},
@@ -217,11 +217,7 @@ impl<'a> ComputedStyleRead<'a> {
pub(in crate::native_bridge::element) fn rendered_style_facts(
&self,
) -> Option<ComputedRenderedStyleFacts> {
- let mut facts = self.stylo_style.as_ref()?.rendered_style_facts();
- if element_has_hidden_attribute(self.runtime, self.handle) {
- facts.display = ComputedDisplayKind::None;
- }
- Some(facts)
+ Some(self.stylo_style.as_ref()?.rendered_style_facts())
}
pub(crate) fn computed_values(&self) -> Option<ServoArc<ComputedValues>> {
@@ -230,6 +226,12 @@ impl<'a> ComputedStyleRead<'a> {
.map(StyloComputedStyleSnapshot::computed_values)
}
+ pub(crate) fn accessibility_style(
+ &self,
+ ) -> Option<moli_dom::accessibility::AccessibilityStyle> {
+ Some(self.stylo_style.as_ref()?.accessibility_style())
+ }
+
/// Transfers the observation's owned Stylo handles into box construction.
/// The only reference-count increments happened when the canonical
/// `ElementStyles` crossed the renderer borrow boundary.
diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values/computed_properties.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values/computed_properties.rs
index f4f386df9..4a4634958 100644
--- a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values/computed_properties.rs
+++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values/computed_properties.rs
@@ -43,11 +43,6 @@ pub(super) fn computed_style_property_value_after_style_update(
if !computed_style_applies(runtime, handle) {
return String::new();
}
- if property == "display"
- && element_hidden_attribute_state(runtime, handle) == HiddenAttributeState::Hidden
- {
- return "none".to_owned();
- }
let inputs = prepared_inputs;
let resolution = if let Some(observation) = observation {
StyleResolutionContext::observed(context, inputs, observation, handle, prepared_style)
diff --git a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values/custom_functions.rs b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values/custom_functions.rs
index 49c6c4b20..8ac3c3451 100644
--- a/moli-renderer-v8/src/native_bridge/element/styles/declaration/values/custom_functions.rs
+++ b/moli-renderer-v8/src/native_bridge/element/styles/declaration/values/custom_functions.rs
@@ -500,28 +500,3 @@ pub(super) fn inline_width_px_with_resolution(
fn css_px_values_equal(left: f64, right: f64) -> bool {
(left - right).abs() < 0.001
}
-
-#[derive(Clone, Copy, Debug, Eq, PartialEq)]
-pub(super) enum HiddenAttributeState {
- Missing,
- Hidden,
- UntilFound,
-}
-
-pub(super) fn element_hidden_attribute_state(
- runtime: &JsContextHost,
- handle: DomHandle,
-) -> HiddenAttributeState {
- let value = runtime
- .dom_host()
- .node(handle)
- .and_then(Node::as_element)
- .and_then(|element| element.attribute("hidden"));
- match value {
- None => HiddenAttributeState::Missing,
- Some(value) if value.eq_ignore_ascii_case("until-found") => {
- HiddenAttributeState::UntilFound
- }
- Some(_) => HiddenAttributeState::Hidden,
- }
-}
diff --git a/moli-renderer-v8/src/runtime/page_dom.rs b/moli-renderer-v8/src/runtime/page_dom.rs
index f562fe719..d00355d06 100644
--- a/moli-renderer-v8/src/runtime/page_dom.rs
+++ b/moli-renderer-v8/src/runtime/page_dom.rs
@@ -2963,7 +2963,22 @@ impl PageVm {
let handle = live_shadow_root_host_for_handle(dom_host, handle).unwrap_or(handle);
dom_host.owner_document_handle(handle)?
};
- self.renderer_backend_node_id_map_for_document_handle(document_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(
+ &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)
}
pub(crate) fn accessibility_tree_payloads_for_live_handle(
@@ -2972,12 +2987,14 @@ impl PageVm {
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,
@@ -3004,11 +3021,13 @@ impl PageVm {
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,
)?
@@ -3031,11 +3050,12 @@ impl PageVm {
reference: RendererDomNodeReference,
max_depth: Option<i32>,
) -> Option<RendererAccessibilityPayloadsForObjectId> {
- self.accessibility_payloads_for_node(reference, |document, node_id, backend_node_ids| {
+ 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,
@@ -3047,10 +3067,11 @@ impl PageVm {
&mut self,
reference: RendererDomNodeReference,
) -> Option<RendererAccessibilityPayloadsForObjectId> {
- self.accessibility_payloads_for_node(reference, |document, node_id, backend_node_ids| {
+ 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,
)
@@ -3064,12 +3085,13 @@ impl PageVm {
) -> Option<RendererAccessibilityPayloadsForObjectId> {
self.accessibility_payloads_for_node(
reference,
- |document, node_id, backend_node_ids| {
+ |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,
)
@@ -3083,12 +3105,13 @@ impl PageVm {
) -> Option<RendererAccessibilityPayloadsForObjectId> {
self.accessibility_payloads_for_node(
reference,
- |document, node_id, backend_node_ids| {
+ |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,
)
@@ -3103,11 +3126,12 @@ impl PageVm {
) -> Option<RendererAccessibilityPayloadsForObjectId> {
self.accessibility_payloads_for_node(
reference,
- |document, node_id, backend_node_ids| {
+ |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,
@@ -3121,6 +3145,7 @@ impl PageVm {
reference: RendererDomNodeReference,
build_payloads: impl FnOnce(
&DomHost,
+ &moli_dom::accessibility::AccessibilityInput,
DomHandle,
&HashMap<DomHandle, u32>,
) -> Option<Vec<serde_json::Value>>,
@@ -3139,12 +3164,14 @@ impl PageVm {
.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,
@@ -3165,11 +3192,13 @@ impl PageVm {
.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,
)
@@ -3186,15 +3215,17 @@ impl PageVm {
handle: DomHandle,
build_payloads: impl FnOnce(
&DomHost,
+ &moli_dom::accessibility::AccessibilityInput,
DomHandle,
&HashMap<DomHandle, u32>,
) -> Option<Vec<serde_json::Value>>,
) -> 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, handle, &backend_node_ids)?
+ build_payloads(document, &styles, handle, &backend_node_ids)?
};
Some(RendererAccessibilityPayloadsForObjectId {
frame_id,
@@ -3210,12 +3241,13 @@ impl PageVm {
self.accessibility_payloads_for_object_id(
inspector_session_id,
object_id,
- |document, node_id, backend_node_ids| {
+ |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,
@@ -3232,12 +3264,13 @@ impl PageVm {
self.accessibility_payloads_for_object_id(
inspector_session_id,
object_id,
- |document, node_id, backend_node_ids| {
+ |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,
)
@@ -3254,11 +3287,12 @@ impl PageVm {
self.accessibility_payloads_for_object_id(
inspector_session_id,
object_id,
- |document, node_id, backend_node_ids| {
+ |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,
@@ -3273,6 +3307,7 @@ impl PageVm {
object_id: &str,
build_payloads: impl FnOnce(
&DomHost,
+ &moli_dom::accessibility::AccessibilityInput,
DomHandle,
&HashMap<DomHandle, u32>,
) -> Option<Vec<serde_json::Value>>,
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/accessibility.rs b/moli-renderer-v8/src/runtime/page_vm/tests/accessibility.rs
new file mode 100644
index 000000000..c3a74ca04
--- /dev/null
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/accessibility.rs
@@ -0,0 +1,36 @@
+use super::*;
+
+#[tokio::test(flavor = "current_thread")]
+async fn accessibility_style_reads_never_publish_cold_or_warm_layout() {
+ 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-style.html")?,
+ );
+ page.vm_mut().set_layout_policy(crate::real_layout_test_policy());
+ page.vm_mut().eval(r#"
+ document.body.innerHTML = '<button id=target>Live action</button><div id=host role=button></div>';
+ const root = host.attachShadow({mode:'closed'});
+ root.innerHTML = '<span>Shadow name</span>';
+ "#)?;
+ let cache = page.vm().layout_snapshot_cache_observability_for_test();
+ assert!(cache.3.is_none());
+ let passes = page.vm().layout_pass_observability_for_test().1;
+ let nodes = page.accessibility_tree_payloads_for_document(None).expect("cold AX tree");
+ assert!(nodes.iter().any(|node| node["name"]["value"] == "Live action"));
+ assert!(nodes.iter().any(|node| node["name"]["value"] == "Shadow name"));
+ assert_eq!(page.vm().layout_pass_observability_for_test().1, passes);
+ assert_eq!(page.vm().layout_snapshot_cache_observability_for_test(), cache);
+
+ page.vm_mut().publish_layout_for_test()?;
+ let passes = page.vm().layout_pass_observability_for_test().1;
+ let cache = page.vm().layout_snapshot_cache_observability_for_test();
+ page.vm_mut().eval("target.style.display='none';root.querySelector('span').style.display='none'")?;
+ let nodes = page.accessibility_tree_payloads_for_document(None).expect("warm AX tree");
+ assert!(!nodes.iter().any(|node| node["name"]["value"] == "Live action" || node["name"]["value"] == "Shadow name"));
+ assert_eq!(page.vm().layout_pass_observability_for_test().1, passes);
+ let after = page.vm().layout_snapshot_cache_observability_for_test();
+ assert_eq!((after.2, after.3), (cache.2, cache.3), "AX must preserve the published geometry after a style mutation");
+ Ok::<_, anyhow::Error>(())
+ }).await.expect("AX style observation must stay independent of layout");
+}
diff --git a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
index 8125bc3b6..8dac9e8b8 100644
--- a/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
+++ b/moli-renderer-v8/src/runtime/page_vm/tests/mod.rs
@@ -96,6 +96,7 @@ use crate::frame_owner_model::{
};
use crate::native_bridge::PendingWindowMessageEndpoint;
+mod accessibility;
mod async_subresource_completion;
mod broadcast_channel_delivery;
mod child_classic_source_load_completion;
diff --git a/moli-renderer-v8/src/runtime/tests/extracted/visual_output.rs b/moli-renderer-v8/src/runtime/tests/extracted/visual_output.rs
index c207f5243..486275adf 100644
--- a/moli-renderer-v8/src/runtime/tests/extracted/visual_output.rs
+++ b/moli-renderer-v8/src/runtime/tests/extracted/visual_output.rs
@@ -291,8 +291,8 @@ async fn capture_screenshot_consumes_the_shadow_flat_tree_without_light_dom_leak
);
assert_eq!(
decoded_png_pixel(&screenshot.bytes, 5, 45),
- [255, 255, 255, 255],
- "unassigned light DOM, suppressed slot fallback, and hidden content must not leak into layout"
+ [255, 0, 255, 255],
+ "CSS must override hidden without exposing unassigned nodes or replaced slot fallback"
);
}
#[tokio::test(flavor = "multi_thread")]
diff --git a/moli-renderer-v8/src/script_vm/layout.rs b/moli-renderer-v8/src/script_vm/layout.rs
index 64feab510..da563c1eb 100644
--- a/moli-renderer-v8/src/script_vm/layout.rs
+++ b/moli-renderer-v8/src/script_vm/layout.rs
@@ -1,6 +1,31 @@
use super::*;
impl ScriptVm {
+ pub(crate) fn accessibility_input(
+ &self,
+ handles: &[DomHandle],
+ ) -> Option<moli_dom::accessibility::AccessibilityInput> {
+ let host = self._context_host.borrow();
+ let mut document = host.dom_host().owner_document_handle(*handles.first()?)?;
+ 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) {
+ frame_state = moli_dom::accessibility::AccessibilityFrameState::Inert;
+ break;
+ }
+ 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)
+ }
+
pub(crate) fn sync_live_document_style_sources(&mut self) {
let document = self.document_runtime.document_handle();
self._context_host
diff --git a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/computed_style_access.rs b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/computed_style_access.rs
index b7271babb..3c1f9df56 100644
--- a/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/computed_style_access.rs
+++ b/moli-renderer-v8/src/script_vm/tests/dom_xhr/computed_style/computed_style_access.rs
@@ -1017,7 +1017,7 @@ setTimeout(() => { document.getElementById('before').style.display = 'block'; },
}
#[test]
-fn computed_display_treats_hidden_attribute_as_none() {
+fn computed_display_allows_css_to_override_hidden_attribute() {
let mut vm = new_storage_test_vm("https://hidden-computed-display.test/");
let result = vm
@@ -1035,16 +1035,53 @@ fn computed_display_treats_hidden_attribute_as_none() {
return [
host.hidden,
getComputedStyle(host).display,
- getComputedStyle(child).display,
- host.getClientRects().length,
- host.offsetWidth
+ getComputedStyle(child).display
].join('|');
})()
"#,
)
.expect("hidden attribute should influence computed display");
- assert_eq!(result, "true|none|inline|0|0");
+ assert_eq!(result, "true|block|inline");
+}
+
+#[test]
+fn hidden_presentation_hint_updates_through_cssom_and_shadow_scopes() {
+ let mut vm = new_storage_test_vm("https://hidden-cascade.test/");
+ let result = vm.eval(r#"
+(() => {
+ document.open();
+ document.write('<!doctype html><html><head></head><body></body></html>');
+ document.close();
+ const host = document.createElement('div');
+ document.body.appendChild(host);
+ const values = [];
+ const read = () => values.push(getComputedStyle(host).display);
+ host.hidden = true;
+ read();
+ host.style.display = 'block';
+ read();
+ host.style.removeProperty('display');
+ read();
+ const sheet = document.createElement('style');
+ sheet.textContent = 'div[hidden] { display: flex }';
+ document.head.appendChild(sheet);
+ read();
+ sheet.sheet.cssRules[0].style.display = 'grid';
+ read();
+ sheet.remove();
+ read();
+ host.removeAttribute('hidden');
+ read();
+ const root = host.attachShadow({mode: 'closed'});
+ root.innerHTML = '<style>:host([hidden]) { display: block }</style><button hidden>Hidden</button>';
+ host.hidden = true;
+ read();
+ values.push(getComputedStyle(root.querySelector('button')).display);
+ return values.join('|');
+})()
+"#).expect("hidden hints must participate in the live cascade");
+ assert_eq!(result, "none|block|none|flex|grid|none|block|block|none");
}
#[test]
@@ -1088,6 +1125,24 @@ fn computed_style_distinguishes_hidden_and_until_found_states() {
);
}
+#[test]
+fn hidden_presentation_hints_only_apply_to_html_elements() {
+ let mut vm = new_parsed_test_vm(
+ "https://hidden-namespace.test/",
+ "<!doctype html><body></body>",
+ );
+ let result = vm.eval(r#"
+ ['http://www.w3.org/2000/svg', 'http://www.w3.org/1998/Math/MathML'].map(namespace => {
+ const element = document.createElementNS(namespace, namespace.endsWith('svg') ? 'g' : 'mrow');
+ document.body.append(element);
+ const before = getComputedStyle(element).display;
+ element.setAttribute('hidden', '');
+ return before === getComputedStyle(element).display;
+ }).join('|')
+ "#).expect("foreign hidden attributes must not become HTML hints");
+ assert_eq!(result, "true|true");
+}
+
#[test]
fn detached_nested_iframe_window_get_computed_style_uses_iframe_width() {
let mut vm = new_storage_test_vm("https://nested-computed-width.test/");
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.rs
index 8be55835f..c235e1267 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
@@ -671,6 +671,40 @@ fn style_observation_reuses_current_world_without_materializing_an_update() {
assert_eq!(host.style_world_full_snapshots_for_test(), full_snapshots);
}
+#[test]
+fn accessibility_style_batches_reuse_the_retained_world() {
+ let mut vm = new_parsed_test_vm(
+ "https://ax-style-batch.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 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");
+ }
+ let host = vm._context_host.borrow();
+ assert_eq!(host.style_world_update_materializations_for_test(), updates);
+ assert_eq!(host.style_world_full_snapshots_for_test(), full);
+ assert_eq!(
+ host.style_observation_environment_resolutions_for_test(),
+ environments + 2,
+ "each synchronous AX batch resolves its document environment once"
+ );
+}
+
#[test]
fn style_observation_resolves_page_environment_once_for_all_element_reads() {
let mut vm = new_parsed_test_vm(
diff --git a/moli-renderer-v8/src/style_engine/computed.rs b/moli-renderer-v8/src/style_engine/computed.rs
index 7161ee441..4d27f9b3f 100644
--- a/moli-renderer-v8/src/style_engine/computed.rs
+++ b/moli-renderer-v8/src/style_engine/computed.rs
@@ -30,7 +30,7 @@ use style::{
values::{
AtomIdent, resolved,
specified::{
- box_::{DisplayInside, DisplayOutside},
+ box_::{ContentVisibility, Display, DisplayInside, DisplayOutside},
text::TextTransformCase,
},
},
@@ -186,20 +186,7 @@ impl StyloComputedStyleSnapshot {
pub(crate) fn rendered_style_facts(&self) -> ComputedRenderedStyleFacts {
let display = self.primary.clone_display();
- let content_visibility_applicable = !display.is_none()
- && !display.is_contents()
- && !display.is_inline_flow()
- && display.outside() != DisplayOutside::TableCaption
- && !matches!(
- display.inside(),
- DisplayInside::Table
- | DisplayInside::TableRowGroup
- | DisplayInside::TableColumn
- | DisplayInside::TableColumnGroup
- | DisplayInside::TableHeaderGroup
- | DisplayInside::TableFooterGroup
- | DisplayInside::TableRow
- );
+ let content_visibility_applicable = content_visibility_applies(display);
let display = if display.is_none() {
ComputedDisplayKind::None
} else if display.is_contents() {
@@ -274,6 +261,20 @@ impl StyloComputedStyleSnapshot {
}
}
+ pub(crate) fn accessibility_style(&self) -> moli_dom::accessibility::AccessibilityStyle {
+ let display = self.primary.clone_display();
+ moli_dom::accessibility::AccessibilityStyle {
+ display_none: display.is_none(),
+ visibility_visible: self.primary.clone_visibility() == ComputedVisibility::Visible,
+ hides_contents: content_visibility_applies(display)
+ && self.primary.clone_content_visibility() == ContentVisibility::Hidden,
+ block_level: matches!(
+ display.outside(),
+ DisplayOutside::Block | DisplayOutside::TableCaption
+ ),
+ }
+ }
+
pub(crate) fn property_value(&self, property: &str) -> Option<String> {
if property.starts_with("--") {
return serialize_computed_custom_property(&self.primary, property);
@@ -295,6 +296,23 @@ impl StyloComputedStyleSnapshot {
}
}
+fn content_visibility_applies(display: Display) -> bool {
+ !display.is_none()
+ && !display.is_contents()
+ && !display.is_inline_flow()
+ && display.outside() != DisplayOutside::TableCaption
+ && !matches!(
+ display.inside(),
+ DisplayInside::Table
+ | DisplayInside::TableRowGroup
+ | DisplayInside::TableColumn
+ | DisplayInside::TableColumnGroup
+ | DisplayInside::TableHeaderGroup
+ | DisplayInside::TableFooterGroup
+ | DisplayInside::TableRow
+ )
+}
+
pub(super) fn retained_current_element_state(
engine: &MoliStyleEngine,
host: &DomHost,
diff --git a/moli-renderer-v8/src/style_engine/mutation_effect.rs b/moli-renderer-v8/src/style_engine/mutation_effect.rs
index 7f9186193..2e58900c9 100644
--- a/moli-renderer-v8/src/style_engine/mutation_effect.rs
+++ b/moli-renderer-v8/src/style_engine/mutation_effect.rs
@@ -225,9 +225,9 @@ impl StyleAttributeImpact {
pub(crate) fn for_attribute_name(name: &str) -> Self {
let name = name.to_ascii_lowercase();
match name.as_str() {
- "style" | "class" | "id" => Self::ComputedStyle,
- "hidden" | "width" | "height" | "cols" | "rows" | "size" | "value" | "border"
- | "slot" | "align" => Self::LayoutMetric,
+ "style" | "class" | "id" | "hidden" => Self::ComputedStyle,
+ "width" | "height" | "cols" | "rows" | "size" | "value" | "border" | "slot"
+ | "align" => Self::LayoutMetric,
"cellpadding" => Self::DescendantComputedStyle,
"href" | "rel" | "media" | "blocking" | "disabled" => Self::StylesheetLinkage,
"type" => Self::LayoutMetricAndStylesheetLinkage,
diff --git a/moli-renderer-v8/src/style_engine/tests/lifecycle.rs b/moli-renderer-v8/src/style_engine/tests/lifecycle.rs
index 91ad74ed8..ac94b4534 100644
--- a/moli-renderer-v8/src/style_engine/tests/lifecycle.rs
+++ b/moli-renderer-v8/src/style_engine/tests/lifecycle.rs
@@ -75,6 +75,7 @@ fn disabled_author_styles_use_stylo_author_origin_gate() {
let body = host.document_body_handle().expect("test body");
let target = host.create_element("div");
assert!(host.set_attribute(target, "class", "styled"));
+ assert!(host.set_attribute(target, "hidden", ""));
assert!(host.set_attribute(target, "style", "color: rgb(1, 2, 3); display: none"));
assert!(host.append_child(body, target));
diff --git a/moli-selector/src/stylo/presentation.rs b/moli-selector/src/stylo/presentation.rs
index ec298c85f..3c9228353 100644
--- a/moli-selector/src/stylo/presentation.rs
+++ b/moli-selector/src/stylo/presentation.rs
@@ -26,9 +26,7 @@ use style_traits::{ParsingMode, ToCss};
use crate::dom::native::Element;
-use super::{
- presentational_hints::synthesize_hidden_until_found_presentational_hint, query::QueryElement,
-};
+use super::{presentational_hints::synthesize_hidden_presentational_hint, query::QueryElement};
const HTML_NAMESPACE: &str = "http://www.w3.org/1999/xhtml";
const SVG_NAMESPACE: &str = "http://www.w3.org/2000/svg";
@@ -177,7 +175,7 @@ impl QueryElement<'_> {
LayerOrder::root(),
));
}
- synthesize_hidden_until_found_presentational_hint(
+ synthesize_hidden_presentational_hint(
self.host(),
self.handle(),
self.shared_lock(),
diff --git a/moli-selector/src/stylo/presentational_hints.rs b/moli-selector/src/stylo/presentational_hints.rs
index 3a13ad982..16d82b65f 100644
--- a/moli-selector/src/stylo/presentational_hints.rs
+++ b/moli-selector/src/stylo/presentational_hints.rs
@@ -9,6 +9,7 @@ use style::{
servo_arc::Arc,
shared_lock::SharedRwLock,
stylesheets::layer_rule::LayerOrder,
+ values::specified::box_::Display,
};
use crate::dom::{
@@ -18,7 +19,7 @@ use crate::dom::{
const HTML_NAMESPACE: &str = "http://www.w3.org/1999/xhtml";
-pub(super) fn synthesize_hidden_until_found_presentational_hint<V>(
+pub(super) fn synthesize_hidden_presentational_hint<V>(
host: &DomHost,
handle: NodeId,
shared_lock: &SharedRwLock,
@@ -29,18 +30,19 @@ pub(super) fn synthesize_hidden_until_found_presentational_hint<V>(
let Some(element) = host.node(handle).and_then(Node::as_element) else {
return;
};
- if element.namespace() != HTML_NAMESPACE
- || !element
- .attribute("hidden")
- .is_some_and(|value| value.eq_ignore_ascii_case("until-found"))
- {
+ if element.namespace() != HTML_NAMESPACE {
return;
}
+ let Some(hidden) = element.attribute("hidden") else {
+ return;
+ };
+ let declaration = if hidden.eq_ignore_ascii_case("until-found") {
+ PropertyDeclaration::ContentVisibility(ContentVisibility::Hidden)
+ } else {
+ PropertyDeclaration::Display(Display::None)
+ };
- let declarations = PropertyDeclarationBlock::with_one(
- PropertyDeclaration::ContentVisibility(ContentVisibility::Hidden),
- Importance::Normal,
- );
+ let declarations = PropertyDeclarationBlock::with_one(declaration, Importance::Normal);
hints.push(ApplicableDeclarationBlock::from_declarations(
Arc::new(shared_lock.wrap(declarations)),
CascadeLevel::new(CascadeOrigin::PresHints),