Skip to main content

nativeview_tables/semantics/
mod.rs

1//! Pure, zero-allocation semantic role resolution, tree exclusion, modal inertness, and W3C
2//! AccName 1.2 accessible-name computation directly over `&NodeStore`.
3//!
4//! Single source of truth consumed by `nativeview-accessibility`, `nativeview-engine`, `nativeview-backend-headless`,
5//! `nativeview-backend-web`, and `nativeview-view` with zero `accesskit` or backend dependencies.
6
7use nativeview_abi::NodeId;
8use nativeview_store::{MAX_TREE_DEPTH, NodeStore, NvTable, TableStorage};
9
10mod accname;
11pub mod query;
12mod role;
13mod types;
14
15pub use accname::{SemanticScratch, compute_accessible_name_into};
16pub(crate) use accname::{
17    append_normalized, compute_accessible_name_cached_into, has_non_ascii_whitespace,
18};
19pub use role::{
20    NativeRole, ResolvedRole, has_semantic_inline_descendant, is_presentational_conflict_focusable,
21    is_semantic_inline_node, node_matches_role, resolve_node_role, resolve_semantic_role,
22    walk_inline_descendants,
23};
24
25use crate::tables::{
26    Accessibility, Interaction, Overlay, OverlayFlags, OverlayLayer, Visibility, Visual,
27    is_display_contents, is_node_display_none, is_open_overlay,
28};
29
30/// Iterates `id` and its ancestors (bounded by [`MAX_TREE_DEPTH`], cycle-safe) and
31/// returns `true` as soon as `pred` holds for one of them.
32#[inline]
33pub(crate) fn any_ancestor_or_self(
34    store: &NodeStore,
35    id: NodeId,
36    mut pred: impl FnMut(NodeId) -> bool,
37) -> bool {
38    let mut cur = Some(id);
39    for _ in 0..MAX_TREE_DEPTH {
40        let Some(nid) = cur else {
41            break;
42        };
43        if pred(nid) {
44            return true;
45        }
46        cur = store.parent(nid).filter(|&p| p != nid);
47    }
48    false
49}
50
51/// Returns `true` when `id` or any ancestor owns a closed [`Overlay`] row.
52#[inline]
53pub fn is_subtree_closed_overlay(store: &NodeStore, id: NodeId) -> bool {
54    any_ancestor_or_self(store, id, |nid| {
55        store
56            .try_row::<Overlay>(nid)
57            .is_some_and(|ov| !ov.options().contains(OverlayFlags::OPEN))
58    })
59}
60
61/// Returns `true` when `node` equals `ancestor` or descends from `ancestor`.
62#[inline]
63pub fn is_within_subtree(store: &NodeStore, node: NodeId, ancestor: NodeId) -> bool {
64    any_ancestor_or_self(store, node, |nid| nid == ancestor)
65}
66
67/// Writes the ancestor-or-self chain of `id` (self first, bounded by
68/// [`MAX_TREE_DEPTH`]) into `chain` and returns its length.
69fn ancestor_chain(store: &NodeStore, id: NodeId, chain: &mut [NodeId; MAX_TREE_DEPTH]) -> usize {
70    let mut len = 0;
71    any_ancestor_or_self(store, id, |nid| {
72        chain[len] = nid;
73        len += 1;
74        false
75    });
76    len
77}
78
79/// Returns `true` when connected node `a` comes strictly before `b` in document pre-order:
80/// O(depth + siblings of the divergence parent), zero heap allocations (two
81/// `MAX_TREE_DEPTH` ancestor arrays, 2 KiB of stack). Nodes deeper than the bound
82/// compare by their bounded chains.
83pub(crate) fn precedes_in_document(store: &NodeStore, a: NodeId, b: NodeId) -> bool {
84    let mut chain_a = [NodeId::NULL; MAX_TREE_DEPTH];
85    let mut chain_b = [NodeId::NULL; MAX_TREE_DEPTH];
86    let len_a = ancestor_chain(store, a, &mut chain_a);
87    let len_b = ancestor_chain(store, b, &mut chain_b);
88    // Walk both chains from the root side until they diverge.
89    let mut shared = 0;
90    while shared < len_a.min(len_b) && chain_a[len_a - 1 - shared] == chain_b[len_b - 1 - shared] {
91        shared += 1;
92    }
93    if shared == len_a || shared == len_b {
94        // One is an ancestor-or-self of the other: the ancestor comes first.
95        return len_a < len_b;
96    }
97    if shared == 0 {
98        return false;
99    }
100    let (branch_a, branch_b) = (chain_a[len_a - 1 - shared], chain_b[len_b - 1 - shared]);
101    let siblings = store.children(chain_a[len_a - shared]);
102    siblings.iter().position(|&c| c == branch_a) < siblings.iter().position(|&c| c == branch_b)
103}
104
105#[inline]
106fn is_open_modal_row(store: &NodeStore, id: NodeId) -> bool {
107    store.try_row::<Overlay>(id).is_some_and(|ov| {
108        ov.layer() == OverlayLayer::Modal && ov.options().contains(OverlayFlags::OPEN)
109    })
110}
111
112/// The one top-layer predicate (`[INV:top-layer-single-definition]`), shared by layout hoisting
113/// (`nativeview_layout::TopLayerIndex`, with the engine's effective-display cascade as `oracle`), focus
114/// management (`nativeview-engine`, `nativeview-backend-web`), semantic queries and accessibility.
115///
116/// `id` belongs to the top layer of `root` when it is live, not `root`, not inline, effectively
117/// neither `display: none` nor `display: contents`, connected to `root`, and no ancestor (`root`
118/// included) is effectively `display: none` or a paragraph root. Whether its `Overlay` row is
119/// open is the caller's check. `on_ancestor` sees every ancestor up to `root`, leaf first, while
120/// the walk succeeds (the index records the chain to sort roots into document order).
121/// `aria-hidden` deliberately does not matter: like a browser's top-layer `<dialog>`, an open
122/// modal keeps the document inert even when it is hidden from the accessibility tree (which
123/// hides an `aria-hidden` ancestor's modal scope instead).
124pub fn walk_top_layer_chain<O: SemanticStyleOracle + ?Sized>(
125    store: &NodeStore,
126    oracle: &O,
127    root: NodeId,
128    id: NodeId,
129    mut on_ancestor: impl FnMut(NodeId),
130) -> bool {
131    if id.is_null()
132        || id == root
133        || !store.is_live(id)
134        || store.is_inline(id)
135        || oracle.is_display_none(store, id)
136        || oracle.is_display_contents(store, id)
137    {
138        return false;
139    }
140    let mut cur = id;
141    for _ in 0..MAX_TREE_DEPTH {
142        let Some(parent) = store.parent(cur).filter(|&p| p != cur) else {
143            return false;
144        };
145        if !store.is_live(parent)
146            || store.is_inline_context_root(parent)
147            || oracle.is_display_none(store, parent)
148        {
149            return false;
150        }
151        on_ancestor(parent);
152        if parent == root {
153            return true;
154        }
155        cur = parent;
156    }
157    false
158}
159
160/// Whether `id` is an open `Overlay` root in the document's top layer
161/// ([`walk_top_layer_chain`] against `NodeId::ROOT`).
162#[inline]
163pub fn is_top_layer_root<O: SemanticStyleOracle + ?Sized>(
164    store: &NodeStore,
165    oracle: &O,
166    id: NodeId,
167) -> bool {
168    is_open_overlay(store, id) && walk_top_layer_chain(store, oracle, NodeId::ROOT, id, |_| {})
169}
170
171/// Whether `id` is an open modal [`Overlay`] in the top layer ([`is_top_layer_root`]).
172#[inline]
173pub fn is_open_modal<O: SemanticStyleOracle + ?Sized>(
174    store: &NodeStore,
175    oracle: &O,
176    id: NodeId,
177) -> bool {
178    is_open_modal_row(store, id) && is_top_layer_root(store, oracle, id)
179}
180
181/// Finds the topmost (last in document order) open modal [`Overlay`] in the top layer (zero
182/// allocs on a warm `dfs_scratch`). The single definition (`[INV:top-layer-single-definition]`)
183/// shared by focus management, semantic queries, and — through `TopLayerIndex`, which applies
184/// [`walk_top_layer_chain`] with the same oracle and document order — layout, hit-testing,
185/// scroll latching and accessibility.
186pub fn topmost_open_modal<O: SemanticStyleOracle + ?Sized>(
187    store: &NodeStore,
188    oracle: &O,
189    dfs_scratch: &mut Vec<NodeId>,
190) -> Option<NodeId> {
191    let TableStorage {
192        owners, row_count, ..
193    } = store.table_storage(Overlay::slot())?;
194    let mut candidate: Option<NodeId> = None;
195    let mut count = 0usize;
196    for &nid in owners.iter().take(row_count) {
197        if is_open_modal(store, oracle, nid) {
198            candidate = Some(nid);
199            count += 1;
200        }
201    }
202    if count <= 1 {
203        return candidate;
204    }
205    // Several open modals: the last one in document pre-order wins. Top-down DFS prunes
206    // display-none subtrees in O(1) per node.
207    dfs_scratch.clear();
208    dfs_scratch.push(NodeId::ROOT);
209    let mut last_modal = candidate;
210    while let Some(cur) = dfs_scratch.pop() {
211        if !store.is_live(cur) || oracle.is_display_none(store, cur) {
212            continue;
213        }
214        if is_open_modal(store, oracle, cur) {
215            last_modal = Some(cur);
216        }
217        for &child in store.children(cur).iter().rev() {
218            dfs_scratch.push(child);
219        }
220    }
221    last_modal
222}
223
224/// Style/visibility oracle letting backends with live `InteractionTracker` + `StateRules`
225/// (`HeadlessBackend`) supply dynamic `Display` / `Visibility` / `disabled` overrides, while
226/// pure-store callers (`ReactiveSurface`, focus management) use zero-cost static table reads via
227/// [`StaticSemanticOracle`].
228pub trait SemanticStyleOracle {
229    #[inline]
230    fn is_display_none(&self, store: &NodeStore, id: NodeId) -> bool {
231        is_node_display_none(store, id)
232    }
233
234    /// Effectively `display: contents` (non-root).
235    #[inline]
236    fn is_display_contents(&self, store: &NodeStore, id: NodeId) -> bool {
237        id != NodeId::ROOT && is_display_contents(store, id)
238    }
239
240    #[inline]
241    fn visibility(&self, store: &NodeStore, id: NodeId) -> Visibility {
242        store
243            .try_row::<Visual>(id)
244            .map_or(Visibility::Inherit, |v| v.visibility())
245    }
246
247    #[inline]
248    fn is_node_disabled(&self, store: &NodeStore, id: NodeId) -> bool {
249        store
250            .try_row::<Interaction>(id)
251            .is_some_and(|i| i.disabled())
252    }
253
254    /// Inert under the topmost modal (HTML modal-dialog `inert`: neither focusable nor
255    /// targetable). Oracles without the scene's overlay resolution answer `false`.
256    #[inline]
257    fn is_inert(&self, _store: &NodeStore, _id: NodeId) -> bool {
258        false
259    }
260
261    /// Whether `id` or any ancestor is [`Self::is_display_none`].
262    #[inline]
263    fn is_subtree_display_none(&self, store: &NodeStore, id: NodeId) -> bool {
264        let mut cur = Some(id);
265        for _ in 0..nativeview_store::MAX_TREE_DEPTH {
266            let Some(n) = cur else { break };
267            if self.is_display_none(store, n) {
268                return true;
269            }
270            cur = store.parent(n).filter(|&p| p != n);
271        }
272        false
273    }
274}
275
276/// Zero-sized static [`SemanticStyleOracle`] reading directly from `&NodeStore` core tables.
277#[derive(Debug, Clone, Copy, Default)]
278pub struct StaticSemanticOracle;
279
280impl SemanticStyleOracle for StaticSemanticOracle {}
281
282/// Returns `true` when `id` and its entire subtree must be pruned from semantic traversal
283/// (`!live`, `display: none` incl. hidden inputs and closed overlays, or `aria-hidden="true"`
284/// when `!include_hidden`). CSS `Visibility::Hidden` does **not** prune subtrees because a
285/// descendant with explicit `Visibility::Visible` remains visible.
286#[inline]
287pub fn is_subtree_pruned<O: SemanticStyleOracle>(
288    store: &NodeStore,
289    oracle: &O,
290    id: NodeId,
291    include_hidden: bool,
292) -> bool {
293    if !store.is_live(id) {
294        return true;
295    }
296    if id == NodeId::ROOT || include_hidden {
297        return false;
298    }
299    if oracle.is_display_none(store, id) {
300        return true;
301    }
302    store
303        .try_row::<Accessibility>(id)
304        .is_some_and(|a| a.hidden())
305}
306
307/// Resolves CSS-inherited [`Visibility`] for `id` in O(depth) with zero allocations.
308#[inline]
309pub fn resolve_effective_visibility_hidden<O: SemanticStyleOracle + ?Sized>(
310    store: &NodeStore,
311    oracle: &O,
312    id: NodeId,
313) -> bool {
314    let mut hidden = false;
315    any_ancestor_or_self(store, id, |nid| match oracle.visibility(store, nid) {
316        Visibility::Hidden => {
317            hidden = true;
318            true
319        }
320        Visibility::Visible => true,
321        Visibility::Inherit => false,
322    });
323    hidden
324}
325
326/// Resolves inherited disabled state (`id` or any ancestor disabled) in O(depth) with zero allocs.
327#[inline]
328pub fn resolve_effective_disabled<O: SemanticStyleOracle>(
329    store: &NodeStore,
330    oracle: &O,
331    id: NodeId,
332) -> bool {
333    any_ancestor_or_self(store, id, |nid| oracle.is_node_disabled(store, nid))
334}