Skip to main content

nativeview_layout/scene/focus_traversal/
mod.rs

1//! Pluggable, zero-allocation focus traversal policy seam on [`LaidOutScene`].
2//!
3//! [`TabOrderPolicy`] is the default zero-sized policy implementing HTML sequential focus
4//! navigation (global positive `tab_index` across the active scope before natural document order,
5//! CSS-inherited `visibility: hidden` with `visibility: visible` descendant restoration, pruned
6//! `display: none` / closed-overlay / disabled subtrees, and unconditional modal focus trapping).
7//! Capability modules such as `nativeview-tv` wrap it via [`FocusTraversalPolicy`] decorators to
8//! add 2D spatial D-Pad / remote navigation without duplicating tab-order or modal logic.
9
10mod tab_order;
11
12use std::ops::{BitAnd, BitOr, BitOrAssign};
13
14use nativeview_abi::{
15    FocusMove, NV_FOCUS_TRAVERSE_MASK, NV_FOCUS_TRAVERSE_NONE, NV_FOCUS_TRAVERSE_NO_WRAP,
16    NV_FOCUS_TRAVERSE_OUT_SCROLLED, NV_FOCUS_TRAVERSE_OUT_TRAPPED, NV_FOCUS_TRAVERSE_OUT_WRAPPED,
17    NV_FOCUS_TRAVERSE_SCROLL_INTO_VIEW,
18};
19use nativeview_engine::{
20    LayoutRect, Viewport, is_focusable_node, is_focusable_self, is_subtree_closed_overlay,
21    is_tabbable_self,
22};
23use nativeview_store::{NodeId, NodeStore};
24use nativeview_tables::semantics::{
25    SemanticStyleOracle, resolve_effective_disabled, resolve_effective_visibility_hidden,
26};
27use nativeview_tables::tables::{Overlay, OverlayFlags, Visibility};
28
29use crate::StoreLayoutEngine;
30
31use super::overlay::resolved::ResolvedOverlay;
32use super::overlay::scene::OverlayState;
33use super::style_cascade::{ResponsivePatches, StyleCascade};
34use super::LaidOutScene;
35
36pub use tab_order::TabOrderPolicy;
37
38/// Input flags controlling [`LaidOutScene::traverse_focus`] and [`FocusTraversalPolicy::traverse`].
39#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
40pub struct FocusTraverseFlags(u32);
41
42impl FocusTraverseFlags {
43    pub const NONE: Self = Self(NV_FOCUS_TRAVERSE_NONE);
44    /// Do not wrap at the start/end boundary outside modals (for embedded native surfaces).
45    /// Ignored while a modal is active so modals always trap focus.
46    pub const NO_WRAP: Self = Self(NV_FOCUS_TRAVERSE_NO_WRAP);
47    /// Scroll the resolved focus target into view via
48    /// [`LaidOutScene::scroll_into_view_box_with_transform`].
49    pub const SCROLL_INTO_VIEW: Self = Self(NV_FOCUS_TRAVERSE_SCROLL_INTO_VIEW);
50    /// Bitmask of all valid input flags.
51    pub const ALL: Self = Self(NV_FOCUS_TRAVERSE_MASK);
52
53    /// Validates a raw C ABI bitmask, rejecting unknown bits.
54    #[inline]
55    pub const fn from_bits(raw: u32) -> Option<Self> {
56        if (raw & !NV_FOCUS_TRAVERSE_MASK) != 0 {
57            None
58        } else {
59            Some(Self(raw))
60        }
61    }
62
63    #[inline]
64    pub const fn bits(self) -> u32 {
65        self.0
66    }
67
68    #[inline]
69    pub const fn is_empty(self) -> bool {
70        self.0 == 0
71    }
72
73    #[inline]
74    pub const fn contains(self, other: Self) -> bool {
75        (self.0 & other.0) == other.0
76    }
77
78    #[inline]
79    pub const fn union(self, other: Self) -> Self {
80        Self(self.0 | other.0)
81    }
82
83    #[inline]
84    pub const fn without(self, other: Self) -> Self {
85        Self(self.0 & !other.0)
86    }
87}
88
89impl BitOr for FocusTraverseFlags {
90    type Output = Self;
91
92    #[inline]
93    fn bitor(self, rhs: Self) -> Self::Output {
94        Self(self.0 | rhs.0)
95    }
96}
97
98impl BitOrAssign for FocusTraverseFlags {
99    #[inline]
100    fn bitor_assign(&mut self, rhs: Self) {
101        self.0 |= rhs.0;
102    }
103}
104
105impl BitAnd for FocusTraverseFlags {
106    type Output = Self;
107
108    #[inline]
109    fn bitand(self, rhs: Self) -> Self::Output {
110        Self(self.0 & rhs.0)
111    }
112}
113
114/// Output flags bitset corresponding to `NV_FOCUS_TRAVERSE_OUT_*`.
115#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
116pub struct FocusTraverseOutFlags(u32);
117
118impl FocusTraverseOutFlags {
119    pub const NONE: Self = Self(0);
120    pub const TRAPPED: Self = Self(NV_FOCUS_TRAVERSE_OUT_TRAPPED);
121    pub const SCROLLED: Self = Self(NV_FOCUS_TRAVERSE_OUT_SCROLLED);
122    pub const WRAPPED: Self = Self(NV_FOCUS_TRAVERSE_OUT_WRAPPED);
123
124    #[inline]
125    pub const fn bits(self) -> u32 {
126        self.0
127    }
128
129    #[inline]
130    pub const fn contains(self, other: Self) -> bool {
131        (self.0 & other.0) == other.0
132    }
133
134    #[inline]
135    pub const fn from_outcome(outcome: FocusTraversalOutcome) -> Self {
136        let mut bits = 0u32;
137        if outcome.trapped {
138            bits |= NV_FOCUS_TRAVERSE_OUT_TRAPPED;
139        }
140        if outcome.scrolled {
141            bits |= NV_FOCUS_TRAVERSE_OUT_SCROLLED;
142        }
143        if outcome.wrapped {
144            bits |= NV_FOCUS_TRAVERSE_OUT_WRAPPED;
145        }
146        Self(bits)
147    }
148}
149
150/// Result of one [`FocusTraversalPolicy::traverse`] / [`LaidOutScene::traverse_focus`] call.
151#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
152pub struct FocusTraversalOutcome {
153    pub target: Option<NodeId>,
154    /// `true` when an active modal owns focus even if `target` is `None`.
155    pub trapped: bool,
156    /// `true` when one or more ancestor scroll containers moved to reveal `target`.
157    pub scrolled: bool,
158    /// `true` when traversal wrapped across the start/end boundary.
159    pub wrapped: bool,
160}
161
162impl FocusTraversalOutcome {
163    #[inline]
164    pub const fn out_flags(self) -> FocusTraverseOutFlags {
165        FocusTraverseOutFlags::from_outcome(self)
166    }
167}
168
169/// Reusable scratch buffers owned by [`LaidOutScene`] so warm focus traversal runs with 0 heap
170/// allocations.
171#[derive(Debug, Default)]
172pub struct FocusTraversalScratch {
173    pub dfs_stack: Vec<(NodeId, bool)>,
174    pub positive_buf: Vec<(i16, NodeId)>,
175    pub positive_sort_buf: Vec<(i16, NodeId)>,
176    pub natural_buf: Vec<NodeId>,
177    pub scroll_dirty: Vec<NodeId>,
178}
179
180impl FocusTraversalScratch {
181    #[inline]
182    pub fn clear(&mut self) {
183        self.dfs_stack.clear();
184        self.positive_buf.clear();
185        self.positive_sort_buf.clear();
186        self.natural_buf.clear();
187        self.scroll_dirty.clear();
188    }
189}
190
191pub(crate) trait FocusLayoutLookup {
192    fn layout_of(&self, id: NodeId) -> Option<LayoutRect>;
193    fn visual_rect_of(&self, store: &NodeStore, id: NodeId) -> Option<LayoutRect>;
194}
195
196impl<L: StoreLayoutEngine> FocusLayoutLookup for LaidOutScene<L> {
197    #[inline]
198    fn layout_of(&self, id: NodeId) -> Option<LayoutRect> {
199        LaidOutScene::layout_of(self, id)
200    }
201
202    #[inline]
203    fn visual_rect_of(&self, store: &NodeStore, id: NodeId) -> Option<LayoutRect> {
204        LaidOutScene::visual_rect_of(self, store, id)
205    }
206}
207
208/// Read-only scene view plus reusable scratch buffers passed to [`FocusTraversalPolicy::traverse`].
209pub struct FocusTraversalCtx<'a> {
210    pub(super) store: &'a NodeStore,
211    pub(super) cascade: StyleCascade<'a, dyn ResponsivePatches + 'a>,
212    pub(super) overlays: &'a OverlayState,
213    layout: &'a (dyn FocusLayoutLookup + 'a),
214    viewport: Viewport,
215    pub(super) scratch: &'a mut FocusTraversalScratch,
216}
217
218impl<'a> FocusTraversalCtx<'a> {
219    #[inline]
220    pub fn store(&self) -> &'a NodeStore {
221        self.store
222    }
223
224    #[inline]
225    pub fn style_cascade(&self) -> &StyleCascade<'a, dyn ResponsivePatches + 'a> {
226        &self.cascade
227    }
228
229    #[inline]
230    pub fn open_overlays(&self) -> &'a [ResolvedOverlay] {
231        self.overlays.open_overlays()
232    }
233
234    #[inline]
235    pub fn resolved_overlay(&self, id: NodeId) -> Option<ResolvedOverlay> {
236        self.overlays.get(id)
237    }
238
239    #[inline]
240    pub fn is_open_overlay(&self, id: NodeId) -> bool {
241        self.overlays.is_open_overlay(id)
242    }
243
244    #[inline]
245    pub fn topmost_modal(&self) -> Option<NodeId> {
246        self.overlays.topmost_modal()
247    }
248
249    #[inline]
250    pub fn topmost_modal_index(&self) -> Option<usize> {
251        self.overlays.topmost_modal_index()
252    }
253
254    #[inline]
255    pub fn layout_of(&self, id: NodeId) -> Option<LayoutRect> {
256        self.layout.layout_of(id)
257    }
258
259    /// Viewport-space visual rectangle of `id` accounting for ancestor scroll offsets, sticky
260    /// clamping, 2D transforms, and hoisted open-overlay positioning.
261    #[inline]
262    pub fn visual_rect_of(&self, id: NodeId) -> Option<LayoutRect> {
263        self.layout.visual_rect_of(self.store, id)
264    }
265
266    #[inline]
267    pub fn viewport(&self) -> (f32, f32) {
268        (self.viewport.width, self.viewport.height)
269    }
270
271    /// Canonical focusability check matching `nativeview_engine::is_focusable_node`.
272    #[inline]
273    pub fn is_focusable(&self, id: NodeId) -> bool {
274        is_focusable_node(self.store, &self.cascade, id)
275    }
276
277    /// Canonical tabbability check: focusable and `tab_index` is absent or `>= 0`.
278    #[inline]
279    pub fn is_tabbable(&self, id: NodeId) -> bool {
280        self.is_focusable(id) && is_tabbable_self(self.store, id)
281    }
282
283    /// Returns `true` when `id` is connected and not inert under the topmost open modal.
284    #[inline]
285    pub fn is_in_active_scope(&self, id: NodeId) -> bool {
286        self.store.is_connected(id) && !self.cascade.is_inert(self.store, id)
287    }
288
289    #[inline]
290    pub fn scratch(&mut self) -> &mut FocusTraversalScratch {
291        self.scratch
292    }
293
294    /// Walks every non-pruned node in the active focus scope in document pre-order, deduplicating
295    /// open overlay subtrees and propagating CSS-inherited `visibility: hidden` without pruning
296    /// `visibility: hidden` subtrees (so `visibility: visible` descendants remain reachable).
297    ///
298    /// Passes `(store, node_id, effectively_hidden, containing_open_overlay)` to `visit`.
299    pub fn visit_active_scope(
300        &mut self,
301        mut visit: impl FnMut(&NodeStore, NodeId, bool, Option<ResolvedOverlay>),
302    ) {
303        walk_active_scope(
304            self.store,
305            &self.cascade,
306            self.overlays,
307            &mut self.scratch.dfs_stack,
308            &mut visit,
309        );
310    }
311
312    /// Walks every focusable, non-hidden node in the active focus scope in document pre-order,
313    /// passing `(node_id, viewport_rect)` resolved via [`LaidOutScene::visual_rect_of`] (scroll
314    /// offsets, sticky clamping, 2D transforms, and hoisted open overlays). Zero heap allocations
315    /// once scratch buffers are warm.
316    pub fn visit_active_scope_focusables(
317        &mut self,
318        mut visit: impl FnMut(NodeId, Option<LayoutRect>),
319    ) {
320        let store = self.store;
321        let cascade = &self.cascade;
322        let overlays = self.overlays;
323        let layout = self.layout;
324        walk_active_scope(
325            store,
326            cascade,
327            overlays,
328            &mut self.scratch.dfs_stack,
329            &mut |s, id, eff_hidden, _active_ov| {
330                if eff_hidden || !is_focusable_self(s, id) {
331                    return;
332                }
333                visit(id, layout.visual_rect_of(s, id));
334            },
335        );
336    }
337}
338
339/// Pluggable focus-traversal policy installed on [`LaidOutScene`] (default [`TabOrderPolicy`]).
340pub trait FocusTraversalPolicy: Send {
341    fn traverse(
342        &mut self,
343        ctx: &mut FocusTraversalCtx<'_>,
344        current: Option<NodeId>,
345        direction: FocusMove,
346        flags: FocusTraverseFlags,
347    ) -> FocusTraversalOutcome;
348
349    /// Called after each scene commit so stateful policies can prune unmounted node state.
350    fn on_scene_commit(&mut self, _store: &NodeStore) {}
351}
352
353pub(super) fn walk_active_scope<'a>(
354    store: &NodeStore,
355    cascade: &StyleCascade<'a, dyn ResponsivePatches + 'a>,
356    overlays: &OverlayState,
357    dfs_stack: &mut Vec<(NodeId, bool)>,
358    visit: &mut impl FnMut(&NodeStore, NodeId, bool, Option<ResolvedOverlay>),
359) {
360    let open = overlays.open_overlays();
361    if let Some(modal_idx) = overlays.topmost_modal_index() {
362        for &ov in &open[modal_idx..] {
363            walk_root(store, cascade, overlays, dfs_stack, ov.node, Some(ov), visit);
364        }
365    } else {
366        walk_root(store, cascade, overlays, dfs_stack, NodeId::ROOT, None, visit);
367        for &ov in open {
368            walk_root(store, cascade, overlays, dfs_stack, ov.node, Some(ov), visit);
369        }
370    }
371}
372
373fn walk_root<'a>(
374    store: &NodeStore,
375    cascade: &StyleCascade<'a, dyn ResponsivePatches + 'a>,
376    overlays: &OverlayState,
377    dfs_stack: &mut Vec<(NodeId, bool)>,
378    root: NodeId,
379    active_overlay: Option<ResolvedOverlay>,
380    visit: &mut impl FnMut(&NodeStore, NodeId, bool, Option<ResolvedOverlay>),
381) {
382    if !store.is_connected(root)
383        || cascade.is_subtree_display_none(store, root)
384        || is_subtree_closed_overlay(store, root)
385        || resolve_effective_disabled(store, cascade, root)
386    {
387        return;
388    }
389    let root_parent_hidden = store
390        .parent(root)
391        .filter(|&p| p != root)
392        .is_some_and(|p| resolve_effective_visibility_hidden(store, cascade, p));
393
394    dfs_stack.clear();
395    dfs_stack.push((root, root_parent_hidden));
396    while let Some((id, parent_hidden)) = dfs_stack.pop() {
397        if !store.is_live(id) {
398            continue;
399        }
400        if id != root
401            && (overlays.is_open_overlay(id)
402                || cascade.is_display_none(store, id)
403                || cascade.is_node_disabled(store, id)
404                || store
405                    .try_row::<Overlay>(id)
406                    .is_some_and(|ov| !ov.options().contains(OverlayFlags::OPEN)))
407        {
408            continue;
409        }
410        let eff_hidden = match cascade.visibility(store, id) {
411            Visibility::Hidden => true,
412            Visibility::Visible => false,
413            Visibility::Inherit => parent_hidden,
414        };
415        visit(store, id, eff_hidden, active_overlay);
416        for &child in store.children(id).iter().rev() {
417            if !overlays.is_open_overlay(child) {
418                dfs_stack.push((child, eff_hidden));
419            }
420        }
421    }
422}
423
424impl<L: StoreLayoutEngine> LaidOutScene<L> {
425    /// Installs a custom [`FocusTraversalPolicy`] on this scene (replacing [`TabOrderPolicy`]).
426    #[inline]
427    pub fn set_focus_traversal_policy(&mut self, policy: Box<dyn FocusTraversalPolicy>) {
428        self.focus_policy = policy;
429    }
430
431    /// Computes the next focus target in `direction` from `current` under the installed
432    /// [`FocusTraversalPolicy`], optionally scrolling the resolved target into view.
433    ///
434    /// Zero heap allocations once the scene's internal scratch buffers are warm.
435    pub fn traverse_focus(
436        &mut self,
437        store: &NodeStore,
438        current: Option<NodeId>,
439        direction: FocusMove,
440        flags: FocusTraverseFlags,
441    ) -> FocusTraversalOutcome {
442        self.focus_scratch.scroll_dirty.clear();
443
444        // Zero-alloc swaps: `TabOrderPolicy` is a ZST (`Box::new` does not allocate) and
445        // `FocusTraversalScratch` moves only Vec headers, letting `&*self` serve `visual_rect_of`.
446        let mut policy = std::mem::replace(&mut self.focus_policy, Box::new(TabOrderPolicy));
447        let mut scratch = std::mem::take(&mut self.focus_scratch);
448        let mut outcome = {
449            let cascade: StyleCascade<'_, dyn ResponsivePatches + '_> = StyleCascade {
450                responsive: &self.layout,
451                interaction: Some(&self.interaction),
452                inert: Some(&self.overlays),
453            };
454            let mut ctx = FocusTraversalCtx {
455                store,
456                cascade,
457                overlays: &self.overlays,
458                layout: &*self,
459                viewport: self.viewport,
460                scratch: &mut scratch,
461            };
462            policy.traverse(&mut ctx, current, direction, flags)
463        };
464        self.focus_policy = policy;
465        self.focus_scratch = scratch;
466
467        if flags.contains(FocusTraverseFlags::SCROLL_INTO_VIEW)
468            && let Some(target) = outcome.target
469            && let Some(rect) = self.layout_of(target)
470        {
471            let mut dirty = std::mem::take(&mut self.focus_scratch.scroll_dirty);
472            let scrolled = self.scroll_into_view_box_with_transform(
473                store,
474                target,
475                rect,
476                rect,
477                |_, tf| tf,
478                |scene, sid, tx, ty| {
479                    let (cx, cy, _) = scene.set_scroll_offset_clamped(store, sid, tx, ty);
480                    (cx, cy)
481                },
482                Some(&mut dirty),
483            );
484            outcome.scrolled = scrolled || !dirty.is_empty();
485            self.focus_scratch.scroll_dirty = dirty;
486        }
487
488        outcome
489    }
490
491    /// Scroll containers adjusted during the most recent [`Self::traverse_focus`] call when
492    /// [`FocusTraverseFlags::SCROLL_INTO_VIEW`] was requested.
493    #[inline]
494    pub fn last_focus_scroll_dirty(&self) -> &[NodeId] {
495        &self.focus_scratch.scroll_dirty
496    }
497}