nativeview-layout 0.1.0-rc.1

Shared NodeStore layout layer: StoreLayoutEngine / TextMeasurer traits and the default direct Taffy engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! Pluggable, zero-allocation focus traversal policy seam on [`LaidOutScene`].
//!
//! [`TabOrderPolicy`] is the default zero-sized policy implementing HTML sequential focus
//! navigation (global positive `tab_index` across the active scope before natural document order,
//! CSS-inherited `visibility: hidden` with `visibility: visible` descendant restoration, pruned
//! `display: none` / closed-overlay / disabled subtrees, and unconditional modal focus trapping).
//! Capability modules such as `nativeview-tv` wrap it via [`FocusTraversalPolicy`] decorators to
//! add 2D spatial D-Pad / remote navigation without duplicating tab-order or modal logic.

mod tab_order;

use std::ops::{BitAnd, BitOr, BitOrAssign};

use nativeview_abi::{
    FocusMove, NV_FOCUS_TRAVERSE_MASK, NV_FOCUS_TRAVERSE_NONE, NV_FOCUS_TRAVERSE_NO_WRAP,
    NV_FOCUS_TRAVERSE_OUT_SCROLLED, NV_FOCUS_TRAVERSE_OUT_TRAPPED, NV_FOCUS_TRAVERSE_OUT_WRAPPED,
    NV_FOCUS_TRAVERSE_SCROLL_INTO_VIEW,
};
use nativeview_engine::{
    LayoutRect, Viewport, is_focusable_node, is_focusable_self, is_subtree_closed_overlay,
    is_tabbable_self,
};
use nativeview_store::{NodeId, NodeStore};
use nativeview_tables::semantics::{
    SemanticStyleOracle, resolve_effective_disabled, resolve_effective_visibility_hidden,
};
use nativeview_tables::tables::{Overlay, OverlayFlags, Visibility};

use crate::StoreLayoutEngine;

use super::overlay::resolved::ResolvedOverlay;
use super::overlay::scene::OverlayState;
use super::style_cascade::{ResponsivePatches, StyleCascade};
use super::LaidOutScene;

pub use tab_order::TabOrderPolicy;

/// Input flags controlling [`LaidOutScene::traverse_focus`] and [`FocusTraversalPolicy::traverse`].
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct FocusTraverseFlags(u32);

impl FocusTraverseFlags {
    pub const NONE: Self = Self(NV_FOCUS_TRAVERSE_NONE);
    /// Do not wrap at the start/end boundary outside modals (for embedded native surfaces).
    /// Ignored while a modal is active so modals always trap focus.
    pub const NO_WRAP: Self = Self(NV_FOCUS_TRAVERSE_NO_WRAP);
    /// Scroll the resolved focus target into view via
    /// [`LaidOutScene::scroll_into_view_box_with_transform`].
    pub const SCROLL_INTO_VIEW: Self = Self(NV_FOCUS_TRAVERSE_SCROLL_INTO_VIEW);
    /// Bitmask of all valid input flags.
    pub const ALL: Self = Self(NV_FOCUS_TRAVERSE_MASK);

    /// Validates a raw C ABI bitmask, rejecting unknown bits.
    #[inline]
    pub const fn from_bits(raw: u32) -> Option<Self> {
        if (raw & !NV_FOCUS_TRAVERSE_MASK) != 0 {
            None
        } else {
            Some(Self(raw))
        }
    }

    #[inline]
    pub const fn bits(self) -> u32 {
        self.0
    }

    #[inline]
    pub const fn is_empty(self) -> bool {
        self.0 == 0
    }

    #[inline]
    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }

    #[inline]
    pub const fn union(self, other: Self) -> Self {
        Self(self.0 | other.0)
    }

    #[inline]
    pub const fn without(self, other: Self) -> Self {
        Self(self.0 & !other.0)
    }
}

impl BitOr for FocusTraverseFlags {
    type Output = Self;

    #[inline]
    fn bitor(self, rhs: Self) -> Self::Output {
        Self(self.0 | rhs.0)
    }
}

impl BitOrAssign for FocusTraverseFlags {
    #[inline]
    fn bitor_assign(&mut self, rhs: Self) {
        self.0 |= rhs.0;
    }
}

impl BitAnd for FocusTraverseFlags {
    type Output = Self;

    #[inline]
    fn bitand(self, rhs: Self) -> Self::Output {
        Self(self.0 & rhs.0)
    }
}

/// Output flags bitset corresponding to `NV_FOCUS_TRAVERSE_OUT_*`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct FocusTraverseOutFlags(u32);

impl FocusTraverseOutFlags {
    pub const NONE: Self = Self(0);
    pub const TRAPPED: Self = Self(NV_FOCUS_TRAVERSE_OUT_TRAPPED);
    pub const SCROLLED: Self = Self(NV_FOCUS_TRAVERSE_OUT_SCROLLED);
    pub const WRAPPED: Self = Self(NV_FOCUS_TRAVERSE_OUT_WRAPPED);

    #[inline]
    pub const fn bits(self) -> u32 {
        self.0
    }

    #[inline]
    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }

    #[inline]
    pub const fn from_outcome(outcome: FocusTraversalOutcome) -> Self {
        let mut bits = 0u32;
        if outcome.trapped {
            bits |= NV_FOCUS_TRAVERSE_OUT_TRAPPED;
        }
        if outcome.scrolled {
            bits |= NV_FOCUS_TRAVERSE_OUT_SCROLLED;
        }
        if outcome.wrapped {
            bits |= NV_FOCUS_TRAVERSE_OUT_WRAPPED;
        }
        Self(bits)
    }
}

/// Result of one [`FocusTraversalPolicy::traverse`] / [`LaidOutScene::traverse_focus`] call.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct FocusTraversalOutcome {
    pub target: Option<NodeId>,
    /// `true` when an active modal owns focus even if `target` is `None`.
    pub trapped: bool,
    /// `true` when one or more ancestor scroll containers moved to reveal `target`.
    pub scrolled: bool,
    /// `true` when traversal wrapped across the start/end boundary.
    pub wrapped: bool,
}

impl FocusTraversalOutcome {
    #[inline]
    pub const fn out_flags(self) -> FocusTraverseOutFlags {
        FocusTraverseOutFlags::from_outcome(self)
    }
}

/// Reusable scratch buffers owned by [`LaidOutScene`] so warm focus traversal runs with 0 heap
/// allocations.
#[derive(Debug, Default)]
pub struct FocusTraversalScratch {
    pub dfs_stack: Vec<(NodeId, bool)>,
    pub positive_buf: Vec<(i16, NodeId)>,
    pub positive_sort_buf: Vec<(i16, NodeId)>,
    pub natural_buf: Vec<NodeId>,
    pub scroll_dirty: Vec<NodeId>,
}

impl FocusTraversalScratch {
    #[inline]
    pub fn clear(&mut self) {
        self.dfs_stack.clear();
        self.positive_buf.clear();
        self.positive_sort_buf.clear();
        self.natural_buf.clear();
        self.scroll_dirty.clear();
    }
}

pub(crate) trait FocusLayoutLookup {
    fn layout_of(&self, id: NodeId) -> Option<LayoutRect>;
    fn visual_rect_of(&self, store: &NodeStore, id: NodeId) -> Option<LayoutRect>;
}

impl<L: StoreLayoutEngine> FocusLayoutLookup for LaidOutScene<L> {
    #[inline]
    fn layout_of(&self, id: NodeId) -> Option<LayoutRect> {
        LaidOutScene::layout_of(self, id)
    }

    #[inline]
    fn visual_rect_of(&self, store: &NodeStore, id: NodeId) -> Option<LayoutRect> {
        LaidOutScene::visual_rect_of(self, store, id)
    }
}

/// Read-only scene view plus reusable scratch buffers passed to [`FocusTraversalPolicy::traverse`].
pub struct FocusTraversalCtx<'a> {
    pub(super) store: &'a NodeStore,
    pub(super) cascade: StyleCascade<'a, dyn ResponsivePatches + 'a>,
    pub(super) overlays: &'a OverlayState,
    layout: &'a (dyn FocusLayoutLookup + 'a),
    viewport: Viewport,
    pub(super) scratch: &'a mut FocusTraversalScratch,
}

impl<'a> FocusTraversalCtx<'a> {
    #[inline]
    pub fn store(&self) -> &'a NodeStore {
        self.store
    }

    #[inline]
    pub fn style_cascade(&self) -> &StyleCascade<'a, dyn ResponsivePatches + 'a> {
        &self.cascade
    }

    #[inline]
    pub fn open_overlays(&self) -> &'a [ResolvedOverlay] {
        self.overlays.open_overlays()
    }

    #[inline]
    pub fn resolved_overlay(&self, id: NodeId) -> Option<ResolvedOverlay> {
        self.overlays.get(id)
    }

    #[inline]
    pub fn is_open_overlay(&self, id: NodeId) -> bool {
        self.overlays.is_open_overlay(id)
    }

    #[inline]
    pub fn topmost_modal(&self) -> Option<NodeId> {
        self.overlays.topmost_modal()
    }

    #[inline]
    pub fn topmost_modal_index(&self) -> Option<usize> {
        self.overlays.topmost_modal_index()
    }

    #[inline]
    pub fn layout_of(&self, id: NodeId) -> Option<LayoutRect> {
        self.layout.layout_of(id)
    }

    /// Viewport-space visual rectangle of `id` accounting for ancestor scroll offsets, sticky
    /// clamping, 2D transforms, and hoisted open-overlay positioning.
    #[inline]
    pub fn visual_rect_of(&self, id: NodeId) -> Option<LayoutRect> {
        self.layout.visual_rect_of(self.store, id)
    }

    #[inline]
    pub fn viewport(&self) -> (f32, f32) {
        (self.viewport.width, self.viewport.height)
    }

    /// Canonical focusability check matching `nativeview_engine::is_focusable_node`.
    #[inline]
    pub fn is_focusable(&self, id: NodeId) -> bool {
        is_focusable_node(self.store, &self.cascade, id)
    }

    /// Canonical tabbability check: focusable and `tab_index` is absent or `>= 0`.
    #[inline]
    pub fn is_tabbable(&self, id: NodeId) -> bool {
        self.is_focusable(id) && is_tabbable_self(self.store, id)
    }

    /// Returns `true` when `id` is connected and not inert under the topmost open modal.
    #[inline]
    pub fn is_in_active_scope(&self, id: NodeId) -> bool {
        self.store.is_connected(id) && !self.cascade.is_inert(self.store, id)
    }

    #[inline]
    pub fn scratch(&mut self) -> &mut FocusTraversalScratch {
        self.scratch
    }

    /// Walks every non-pruned node in the active focus scope in document pre-order, deduplicating
    /// open overlay subtrees and propagating CSS-inherited `visibility: hidden` without pruning
    /// `visibility: hidden` subtrees (so `visibility: visible` descendants remain reachable).
    ///
    /// Passes `(store, node_id, effectively_hidden, containing_open_overlay)` to `visit`.
    pub fn visit_active_scope(
        &mut self,
        mut visit: impl FnMut(&NodeStore, NodeId, bool, Option<ResolvedOverlay>),
    ) {
        walk_active_scope(
            self.store,
            &self.cascade,
            self.overlays,
            &mut self.scratch.dfs_stack,
            &mut visit,
        );
    }

    /// Walks every focusable, non-hidden node in the active focus scope in document pre-order,
    /// passing `(node_id, viewport_rect)` resolved via [`LaidOutScene::visual_rect_of`] (scroll
    /// offsets, sticky clamping, 2D transforms, and hoisted open overlays). Zero heap allocations
    /// once scratch buffers are warm.
    pub fn visit_active_scope_focusables(
        &mut self,
        mut visit: impl FnMut(NodeId, Option<LayoutRect>),
    ) {
        let store = self.store;
        let cascade = &self.cascade;
        let overlays = self.overlays;
        let layout = self.layout;
        walk_active_scope(
            store,
            cascade,
            overlays,
            &mut self.scratch.dfs_stack,
            &mut |s, id, eff_hidden, _active_ov| {
                if eff_hidden || !is_focusable_self(s, id) {
                    return;
                }
                visit(id, layout.visual_rect_of(s, id));
            },
        );
    }
}

/// Pluggable focus-traversal policy installed on [`LaidOutScene`] (default [`TabOrderPolicy`]).
pub trait FocusTraversalPolicy: Send {
    fn traverse(
        &mut self,
        ctx: &mut FocusTraversalCtx<'_>,
        current: Option<NodeId>,
        direction: FocusMove,
        flags: FocusTraverseFlags,
    ) -> FocusTraversalOutcome;

    /// Called after each scene commit so stateful policies can prune unmounted node state.
    fn on_scene_commit(&mut self, _store: &NodeStore) {}
}

pub(super) fn walk_active_scope<'a>(
    store: &NodeStore,
    cascade: &StyleCascade<'a, dyn ResponsivePatches + 'a>,
    overlays: &OverlayState,
    dfs_stack: &mut Vec<(NodeId, bool)>,
    visit: &mut impl FnMut(&NodeStore, NodeId, bool, Option<ResolvedOverlay>),
) {
    let open = overlays.open_overlays();
    if let Some(modal_idx) = overlays.topmost_modal_index() {
        for &ov in &open[modal_idx..] {
            walk_root(store, cascade, overlays, dfs_stack, ov.node, Some(ov), visit);
        }
    } else {
        walk_root(store, cascade, overlays, dfs_stack, NodeId::ROOT, None, visit);
        for &ov in open {
            walk_root(store, cascade, overlays, dfs_stack, ov.node, Some(ov), visit);
        }
    }
}

fn walk_root<'a>(
    store: &NodeStore,
    cascade: &StyleCascade<'a, dyn ResponsivePatches + 'a>,
    overlays: &OverlayState,
    dfs_stack: &mut Vec<(NodeId, bool)>,
    root: NodeId,
    active_overlay: Option<ResolvedOverlay>,
    visit: &mut impl FnMut(&NodeStore, NodeId, bool, Option<ResolvedOverlay>),
) {
    if !store.is_connected(root)
        || cascade.is_subtree_display_none(store, root)
        || is_subtree_closed_overlay(store, root)
        || resolve_effective_disabled(store, cascade, root)
    {
        return;
    }
    let root_parent_hidden = store
        .parent(root)
        .filter(|&p| p != root)
        .is_some_and(|p| resolve_effective_visibility_hidden(store, cascade, p));

    dfs_stack.clear();
    dfs_stack.push((root, root_parent_hidden));
    while let Some((id, parent_hidden)) = dfs_stack.pop() {
        if !store.is_live(id) {
            continue;
        }
        if id != root
            && (overlays.is_open_overlay(id)
                || cascade.is_display_none(store, id)
                || cascade.is_node_disabled(store, id)
                || store
                    .try_row::<Overlay>(id)
                    .is_some_and(|ov| !ov.options().contains(OverlayFlags::OPEN)))
        {
            continue;
        }
        let eff_hidden = match cascade.visibility(store, id) {
            Visibility::Hidden => true,
            Visibility::Visible => false,
            Visibility::Inherit => parent_hidden,
        };
        visit(store, id, eff_hidden, active_overlay);
        for &child in store.children(id).iter().rev() {
            if !overlays.is_open_overlay(child) {
                dfs_stack.push((child, eff_hidden));
            }
        }
    }
}

impl<L: StoreLayoutEngine> LaidOutScene<L> {
    /// Installs a custom [`FocusTraversalPolicy`] on this scene (replacing [`TabOrderPolicy`]).
    #[inline]
    pub fn set_focus_traversal_policy(&mut self, policy: Box<dyn FocusTraversalPolicy>) {
        self.focus_policy = policy;
    }

    /// Computes the next focus target in `direction` from `current` under the installed
    /// [`FocusTraversalPolicy`], optionally scrolling the resolved target into view.
    ///
    /// Zero heap allocations once the scene's internal scratch buffers are warm.
    pub fn traverse_focus(
        &mut self,
        store: &NodeStore,
        current: Option<NodeId>,
        direction: FocusMove,
        flags: FocusTraverseFlags,
    ) -> FocusTraversalOutcome {
        self.focus_scratch.scroll_dirty.clear();

        // Zero-alloc swaps: `TabOrderPolicy` is a ZST (`Box::new` does not allocate) and
        // `FocusTraversalScratch` moves only Vec headers, letting `&*self` serve `visual_rect_of`.
        let mut policy = std::mem::replace(&mut self.focus_policy, Box::new(TabOrderPolicy));
        let mut scratch = std::mem::take(&mut self.focus_scratch);
        let mut outcome = {
            let cascade: StyleCascade<'_, dyn ResponsivePatches + '_> = StyleCascade {
                responsive: &self.layout,
                interaction: Some(&self.interaction),
                inert: Some(&self.overlays),
            };
            let mut ctx = FocusTraversalCtx {
                store,
                cascade,
                overlays: &self.overlays,
                layout: &*self,
                viewport: self.viewport,
                scratch: &mut scratch,
            };
            policy.traverse(&mut ctx, current, direction, flags)
        };
        self.focus_policy = policy;
        self.focus_scratch = scratch;

        if flags.contains(FocusTraverseFlags::SCROLL_INTO_VIEW)
            && let Some(target) = outcome.target
            && let Some(rect) = self.layout_of(target)
        {
            let mut dirty = std::mem::take(&mut self.focus_scratch.scroll_dirty);
            let scrolled = self.scroll_into_view_box_with_transform(
                store,
                target,
                rect,
                rect,
                |_, tf| tf,
                |scene, sid, tx, ty| {
                    let (cx, cy, _) = scene.set_scroll_offset_clamped(store, sid, tx, ty);
                    (cx, cy)
                },
                Some(&mut dirty),
            );
            outcome.scrolled = scrolled || !dirty.is_empty();
            self.focus_scratch.scroll_dirty = dirty;
        }

        outcome
    }

    /// Scroll containers adjusted during the most recent [`Self::traverse_focus`] call when
    /// [`FocusTraverseFlags::SCROLL_INTO_VIEW`] was requested.
    #[inline]
    pub fn last_focus_scroll_dirty(&self) -> &[NodeId] {
        &self.focus_scratch.scroll_dirty
    }
}