nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
Documentation
//! Pure, zero-allocation focusability, modal-overlay, and subtree query helpers over `&NodeStore`.

use nativeview_abi::NodeId;
use nativeview_store::NodeStore;
use nativeview_tables::semantics::{SemanticStyleOracle, resolve_effective_visibility_hidden};
pub use nativeview_tables::semantics::{
    is_open_modal, is_subtree_closed_overlay, is_within_subtree, topmost_open_modal,
};
use nativeview_tables::tables::{Accessibility, AriaRole, Interaction, Overlay, OverlayFlags};

pub(crate) use nativeview_store::MAX_TREE_DEPTH;

/// Returns `true` when `id` is a live text-entry / text-key-capturing control
/// (`Interaction::captures_text_keys`).
#[inline]
pub fn is_text_entry_node(store: &NodeStore, id: NodeId) -> bool {
    store.is_live(id)
        && store
            .try_row::<Interaction>(id)
            .is_some_and(|i| i.captures_text_keys())
}

/// Returns `true` when `id` or any ancestor has `Interaction::disabled == true`.
#[inline]
pub fn is_subtree_disabled(store: &NodeStore, id: NodeId) -> bool {
    let mut cur = Some(id);
    for _ in 0..MAX_TREE_DEPTH {
        let Some(nid) = cur else {
            break;
        };
        if store
            .try_row::<Interaction>(nid)
            .is_some_and(|i| i.disabled())
        {
            return true;
        }
        cur = store.parent(nid).filter(|&p| p != nid);
    }
    false
}

/// Focus target of a primary press on `hit` for every host that moves focus on press: the
/// nearest focusable ancestor-or-self (`None` blurs), or `current` unchanged when the press lands
/// inside an `Interaction::keep_focus_on_press` node first (HTML `mousedown` `preventDefault`).
pub fn press_focus_target<O: SemanticStyleOracle + ?Sized>(
    store: &NodeStore,
    oracle: &O,
    hit: Option<NodeId>,
    current: Option<NodeId>,
) -> Option<NodeId> {
    let mut cur = hit?;
    for _ in 0..MAX_TREE_DEPTH {
        if is_focusable_node(store, oracle, cur) {
            return Some(cur);
        }
        if store
            .try_row::<Interaction>(cur)
            .is_some_and(|i| i.keep_focus_on_press())
        {
            return current;
        }
        match store.parent(cur) {
            Some(p) if p != cur => cur = p,
            _ => return None,
        }
    }
    None
}

/// Returns `true` when `id` is live and focusable itself ([`is_focusable_self`], tested first: it
/// is O(1) and rejects almost every node), displayed (per `oracle`: cascaded `@media` /
/// `@container` / state `display` on native scenes, static rows where the platform applies CSS),
/// enabled, inside no closed overlay, not `visibility: hidden` (CSS-inherited) and not inert under
/// the topmost modal ([`SemanticStyleOracle::is_inert`]). The one focusability rule: engine focus
/// moves and the runtime's `focusable` scene fact both read it.
#[inline]
pub fn is_focusable_node<O: SemanticStyleOracle + ?Sized>(
    store: &NodeStore,
    oracle: &O,
    id: NodeId,
) -> bool {
    store.is_connected(id)
        && is_focusable_self(store, id)
        && !oracle.is_subtree_display_none(store, id)
        && !is_subtree_closed_overlay(store, id)
        && !is_subtree_disabled(store, id)
        && !resolve_effective_visibility_hidden(store, oracle, id)
        && !oracle.is_inert(store, id)
}

/// Whether live `id` is itself a focus target (text entry, `focusable`, a `tab_index` or
/// focus listeners), without the O(depth) ancestor checks of [`is_focusable_node`]: for callers
/// that already pruned `display: none`, closed-overlay and disabled nodes and their subtrees
/// (the [`first_matching_in_subtree`] DFS, tab-order walks).
#[inline]
pub fn is_focusable_self(store: &NodeStore, id: NodeId) -> bool {
    if !store.is_live(id) {
        return false;
    }
    if is_text_entry_node(store, id) {
        return true;
    }
    store.try_row::<Interaction>(id).is_some_and(|i| {
        let l = i.listeners();
        i.focusable()
            || i.tab_index().is_some()
            || l.contains(nativeview_abi::InteractionEvent::Focus)
            || l.contains(nativeview_abi::InteractionEvent::Blur)
    })
}

/// Returns `true` when `id` is a composite roving-focus group (`Interaction::roving_focus_group`
/// or a composite ARIA widget role).
#[inline]
pub fn is_composite_aria_group(store: &NodeStore, id: NodeId) -> bool {
    store
        .try_row::<Interaction>(id)
        .is_some_and(|i| i.roving_focus_group())
        || store
            .try_row::<Accessibility>(id)
            .and_then(|a| a.role())
            .is_some_and(|r| {
                matches!(
                    r,
                    AriaRole::TabList
                        | AriaRole::Menu
                        | AriaRole::RadioGroup
                        | AriaRole::ListBox
                        | AriaRole::Grid
                )
            })
}

/// Finds the first node inside `root`'s subtree matching `predicate` in document pre-order,
/// pruning dead, `display: none` (per `oracle`), closed-overlay and disabled subtrees, so the
/// predicate only judges the node itself (e.g. [`is_focusable_self`]).
pub fn first_matching_in_subtree<O: SemanticStyleOracle + ?Sized>(
    store: &NodeStore,
    oracle: &O,
    root: NodeId,
    dfs_scratch: &mut Vec<NodeId>,
    mut predicate: impl FnMut(&NodeStore, NodeId) -> bool,
) -> Option<NodeId> {
    if !store.is_live(root)
        || oracle.is_subtree_display_none(store, root)
        || is_subtree_closed_overlay(store, root)
        || is_subtree_disabled(store, root)
    {
        return None;
    }
    dfs_scratch.clear();
    dfs_scratch.push(root);
    while let Some(cur) = dfs_scratch.pop() {
        if !store.is_live(cur) {
            continue;
        }
        if cur != root
            && (oracle.is_display_none(store, cur)
                || store
                    .try_row::<Overlay>(cur)
                    .is_some_and(|ov| !ov.options().contains(OverlayFlags::OPEN))
                || store
                    .try_row::<Interaction>(cur)
                    .is_some_and(|i| i.disabled()))
        {
            continue;
        }
        if predicate(store, cur) {
            return Some(cur);
        }
        for &child in store.children(cur).iter().rev() {
            dfs_scratch.push(child);
        }
    }
    None
}

#[inline]
pub fn first_focusable_in_subtree<O: SemanticStyleOracle + ?Sized>(
    store: &NodeStore,
    oracle: &O,
    root: NodeId,
    dfs_scratch: &mut Vec<NodeId>,
) -> Option<NodeId> {
    first_matching_in_subtree(store, oracle, root, dfs_scratch, is_focusable_self)
}

/// [`is_focusable_self`] without a negative `tab_index` (same pruned-DFS contract).
#[inline]
pub fn is_tabbable_self(store: &NodeStore, id: NodeId) -> bool {
    is_focusable_self(store, id)
        && store
            .try_row::<Interaction>(id)
            .and_then(|i| i.tab_index())
            .is_none_or(|ti| ti >= 0)
}

pub(crate) fn pick_modal_initial_focus<O: SemanticStyleOracle + ?Sized>(
    store: &NodeStore,
    oracle: &O,
    modal_root: NodeId,
    dfs_scratch: &mut Vec<NodeId>,
) -> Option<NodeId> {
    first_matching_in_subtree(store, oracle, modal_root, dfs_scratch, |s, id| {
        is_focusable_self(s, id) && s.try_row::<Interaction>(id).is_some_and(|i| i.autofocus())
    })
    .or_else(|| first_matching_in_subtree(store, oracle, modal_root, dfs_scratch, is_tabbable_self))
    .or_else(|| first_focusable_in_subtree(store, oracle, modal_root, dfs_scratch))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn interaction_flags_drive_text_entry_and_roving_group_without_capability_tables() {
        let mut store = NodeStore::new();
        let mut changes = nativeview_store::ChangeSet::default();
        let mut tx = store.tx();
        let plain = tx.create();
        let text_host = tx.create();
        let roving = tx.create();
        tx.edit::<Interaction>(text_host).captures_text_keys(true);
        tx.edit::<Interaction>(roving).roving_focus_group(true);
        tx.commit_into(&mut changes);

        assert!(store.try_row::<Interaction>(text_host).is_some_and(|i| i.captures_text_keys()));
        assert!(!store.has::<Accessibility>(roving));

        assert!(!is_text_entry_node(&store, plain));
        assert!(is_text_entry_node(&store, text_host));
        assert!(is_focusable_self(&store, text_host));

        assert!(!is_composite_aria_group(&store, plain));
        assert!(is_composite_aria_group(&store, roving));

        // Dead nodes must return false even if they previously carried the flags.
        let mut tx = store.tx();
        tx.remove(text_host);
        tx.remove(roving);
        tx.commit_into(&mut changes);
        assert!(!is_text_entry_node(&store, text_host));
        assert!(!is_composite_aria_group(&store, roving));
    }

    #[test]
    fn detached_live_node_is_not_focusable_until_connected() {
        use nativeview_tables::semantics::StaticSemanticOracle;

        let mut store = NodeStore::new();
        let mut changes = nativeview_store::ChangeSet::default();
        let btn = {
            let mut tx = store.tx();
            let b = tx.create();
            tx.edit::<Interaction>(b).focusable(true).tab_index(Some(0));
            tx.commit_into(&mut changes);
            b
        };
        assert!(store.is_live(btn) && !store.is_connected(btn));
        assert!(!is_focusable_node(&store, &StaticSemanticOracle, btn));

        {
            let mut tx = store.tx();
            tx.set_children(NodeId::ROOT, &[btn]);
            tx.commit_into(&mut changes);
        }
        assert!(is_focusable_node(&store, &StaticSemanticOracle, btn));

        {
            let mut tx = store.tx();
            tx.detach_child(btn);
            tx.commit_into(&mut changes);
        }
        assert!(store.is_live(btn) && !store.is_connected(btn));
        assert!(!is_focusable_node(&store, &StaticSemanticOracle, btn));
    }
}