nativeview-engine 0.1.0-rc.1

Framework-agnostic scene engine traits, hot-reload cdylib loader, and Frame-0 snapshot codecs.
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
//! Unified, zero-allocation focusability, modal tracking, and deterministic unmount focus recovery
//! over `&NodeStore`, shared across `LaidOutScene` (Skia/Headless) and `WebBackend`.

use nativeview_abi::NodeId;
use nativeview_store::NodeStore;
use nativeview_tables::interaction::{resolve_focus_visible, FocusModality};
use nativeview_tables::semantics::SemanticStyleOracle;
use nativeview_tables::tables::Interaction;

pub use crate::focus_query::{
    first_focusable_in_subtree, first_matching_in_subtree, is_composite_aria_group,
    is_focusable_node, is_focusable_self, is_subtree_closed_overlay, is_subtree_disabled,
    is_tabbable_self, is_text_entry_node, is_within_subtree, topmost_open_modal,
};
use crate::focus_query::{is_open_modal, pick_modal_initial_focus, MAX_TREE_DEPTH};

const PRE_MODAL_STACK_CAP: usize = 8;

/// Paired `(modal, saved_return_focus)` entry in [`FocusAnchor`]'s inline modal stack.
/// Empty slots use `modal == NodeId::NULL` so no separate length field is needed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct ModalStackEntry {
    modal: NodeId,
    return_focus: NodeId,
}

impl Default for ModalStackEntry {
    #[inline]
    fn default() -> Self {
        Self {
            modal: NodeId::NULL,
            return_focus: NodeId::NULL,
        }
    }
}

/// Snapshot of the currently focused node's structural context used to recover focus deterministically
/// when the focused node (or any ancestor wrapper) unmounts, hides, disables, or exits a modal.
#[derive(Debug, Clone, Default)]
pub struct FocusAnchor {
    pub focused: Option<NodeId>,
    pub prev_sibling: Option<NodeId>,
    pub next_sibling: Option<NodeId>,
    /// Ancestor chain `(ancestor, child_index)` from immediate parent up to `NodeId::ROOT`.
    pub trail: Vec<(NodeId, usize)>,
    /// Bounded stack of open modals paired with their pre-modal return focus (up to 8 levels).
    modal_stack: [ModalStackEntry; PRE_MODAL_STACK_CAP],
    /// Topmost open modal overlay observed on the last commit/snapshot.
    pub active_modal: Option<NodeId>,
    /// Nearest enclosing composite ARIA group (`tablist`, `menu`, `radiogroup`, `listbox`, `grid`).
    pub composite_group: Option<NodeId>,
    /// Whether `focused` had `tab_index == Some(0)` inside `composite_group`.
    pub was_roving_active: bool,
    pub was_text_entry: bool,
    pub modality: FocusModality,
}

impl FocusAnchor {
    #[inline]
    pub fn clear(&mut self) {
        self.focused = None;
        self.prev_sibling = None;
        self.next_sibling = None;
        self.trail.clear();
        self.modal_stack = [ModalStackEntry::default(); PRE_MODAL_STACK_CAP];
        self.active_modal = None;
        self.composite_group = None;
        self.was_roving_active = false;
        self.was_text_entry = false;
        self.modality = FocusModality::Pointer;
    }

    #[inline]
    fn modal_stack_index(&self, modal: NodeId) -> Option<usize> {
        if modal.is_null() {
            return None;
        }
        self.modal_stack.iter().position(|e| e.modal == modal)
    }

    #[inline]
    fn push_modal(&mut self, modal: NodeId, return_focus: Option<NodeId>) {
        if modal.is_null() || self.modal_stack_index(modal).is_some() {
            return;
        }
        let entry = ModalStackEntry {
            modal,
            return_focus: return_focus.unwrap_or(NodeId::NULL),
        };
        if let Some(slot) = self.modal_stack.iter_mut().find(|e| e.modal.is_null()) {
            *slot = entry;
        } else {
            self.modal_stack.copy_within(1..PRE_MODAL_STACK_CAP, 0);
            self.modal_stack[PRE_MODAL_STACK_CAP - 1] = entry;
        }
    }

    #[inline]
    fn unwind_modals_above<O: SemanticStyleOracle + ?Sized>(
        &mut self,
        target_modal: Option<NodeId>,
        store: &NodeStore,
        oracle: &O,
        scope_root: NodeId,
    ) -> Option<NodeId> {
        let stop_len = target_modal
            .and_then(|m| self.modal_stack_index(m))
            .map_or(0, |idx| idx + 1);
        let mut returned = None;
        for idx in (stop_len..PRE_MODAL_STACK_CAP).rev() {
            let entry = self.modal_stack[idx];
            if entry.modal.is_null() {
                continue;
            }
            self.modal_stack[idx] = ModalStackEntry::default();
            if returned.is_none()
                && !entry.return_focus.is_null()
                && is_focusable_node(store, oracle, entry.return_focus)
                && is_within_subtree(store, entry.return_focus, scope_root)
            {
                returned = Some(entry.return_focus);
            }
        }
        returned
    }

    #[inline]
    fn prune_closed_top_modals<O: SemanticStyleOracle + ?Sized>(
        &mut self,
        store: &NodeStore,
        oracle: &O,
        exclude_subtree: NodeId,
    ) -> Option<NodeId> {
        let mut carried = None;
        for idx in (0..PRE_MODAL_STACK_CAP).rev() {
            let entry = self.modal_stack[idx];
            if entry.modal.is_null() {
                continue;
            }
            if is_open_modal(store, oracle, entry.modal) {
                break;
            }
            self.modal_stack[idx] = ModalStackEntry::default();
            if carried.is_none()
                && !entry.return_focus.is_null()
                && is_focusable_node(store, oracle, entry.return_focus)
                && !is_within_subtree(store, entry.return_focus, exclude_subtree)
            {
                carried = Some(entry.return_focus);
            }
        }
        carried
    }
}

/// Outcome of post-commit focus reconciliation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FocusRecoveryResult {
    /// Focused node (or lack of focus) remains valid; no focus move required.
    Unchanged,
    /// Focus moved deterministically to a surviving target node.
    Moved {
        previous: Option<NodeId>,
        next: NodeId,
        modality: FocusModality,
        focus_visible: bool,
    },
    /// Previous focused node became invalid and no focusable target exists in the active scope.
    Cleared { previous: NodeId },
}


/// Captures `focused`'s sibling handles, ancestor `(parent, child_index)` trail, composite ARIA
/// group, and active modal into `anchor` (zero steady-state allocations).
pub fn snapshot_focus_anchor<O: SemanticStyleOracle + ?Sized>(
    store: &NodeStore,
    oracle: &O,
    anchor: &mut FocusAnchor,
    focused: Option<NodeId>,
    modality: FocusModality,
    dfs_scratch: &mut Vec<NodeId>,
) {
    anchor.focused = focused;
    anchor.modality = modality;
    anchor.prev_sibling = None;
    anchor.next_sibling = None;
    anchor.trail.clear();
    anchor.composite_group = None;
    anchor.was_roving_active = false;
    anchor.was_text_entry = focused.is_some_and(|id| is_text_entry_node(store, id));
    let topmost = topmost_open_modal(store, oracle, dfs_scratch);
    anchor.active_modal = topmost;
    if let Some(m) = topmost {
        anchor.push_modal(m, None);
    }

    let Some(id) = focused else {
        return;
    };
    if !store.is_live(id) {
        return;
    }

    let mut cur = id;
    for depth in 0..MAX_TREE_DEPTH {
        let Some(parent) = store.parent(cur) else {
            break;
        };
        if parent == cur {
            break;
        }
        let children = store.children(parent);
        let idx = children.iter().position(|&c| c == cur).unwrap_or(0);
        if depth == 0 {
            anchor.next_sibling = children[idx.saturating_add(1).min(children.len())..]
                .iter()
                .copied()
                .find(|&c| is_focusable_node(store, oracle, c));
            anchor.prev_sibling = children[..idx]
                .iter()
                .rev()
                .copied()
                .find(|&c| is_focusable_node(store, oracle, c));
        }
        anchor.trail.push((parent, idx));
        if anchor.composite_group.is_none() && is_composite_aria_group(store, parent) {
            anchor.composite_group = Some(parent);
        }
        cur = parent;
    }
    anchor.was_roving_active = anchor.composite_group.is_some()
        && store
            .try_row::<Interaction>(id)
            .and_then(|i| i.tab_index())
            == Some(0);
}

fn recover_from_trail<O: SemanticStyleOracle + ?Sized>(
    store: &NodeStore,
    oracle: &O,
    anchor: &FocusAnchor,
    scope_root: NodeId,
    dfs_scratch: &mut Vec<NodeId>,
) -> Option<NodeId> {
    if let Some(next) = anchor.next_sibling
        && is_focusable_node(store, oracle, next)
        && is_within_subtree(store, next, scope_root)
    {
        return Some(next);
    }
    if let Some(prev) = anchor.prev_sibling
        && is_focusable_node(store, oracle, prev)
        && is_within_subtree(store, prev, scope_root)
    {
        return Some(prev);
    }
    for &(anc, old_idx) in &anchor.trail {
        if !store.is_live(anc)
            || oracle.is_subtree_display_none(store, anc)
            || is_subtree_closed_overlay(store, anc)
            || is_subtree_disabled(store, anc)
            || !is_within_subtree(store, anc, scope_root)
        {
            continue;
        }
        let children = store.children(anc);
        let split = old_idx.min(children.len());
        for &child in &children[split..] {
            if let Some(found) = first_focusable_in_subtree(store, oracle, child, dfs_scratch) {
                return Some(found);
            }
        }
        for &child in children[..split].iter().rev() {
            if let Some(found) = first_focusable_in_subtree(store, oracle, child, dfs_scratch) {
                return Some(found);
            }
        }
        // `anc`'s own subtree checks ran above.
        if is_focusable_self(store, anc) {
            return Some(anc);
        }
    }
    first_matching_in_subtree(store, oracle, scope_root, dfs_scratch, is_tabbable_self)
        .or_else(|| first_focusable_in_subtree(store, oracle, scope_root, dfs_scratch))
}

/// Resolves deterministic focus recovery after a committed `NodeStore` mutation (zero allocs).
///
/// Handles:
/// - modal open (`pre_modal_focus` push + `autofocus`/first focusable entry),
/// - modal close (`explicit_return_focus` -> `pre_modal_focus.pop()` -> trail fallback),
/// - roving `tab_index: 0 -> -1` demotion inside composite ARIA groups, and
/// - focused node/ancestor unmount, `display: none`, closed overlay, or disablement.
///
/// `oracle` resolves effective `display` for the top-layer / modal predicate
/// (`[INV:top-layer-single-definition]`): `LaidOutScene` passes its `DisplayEnv`, store-only
/// callers `StaticSemanticOracle`.
pub fn resolve_focus_recovery<O: SemanticStyleOracle + ?Sized>(
    store: &NodeStore,
    oracle: &O,
    anchor: &mut FocusAnchor,
    last_input: FocusModality,
    current_focused: Option<NodeId>,
    explicit_return_focus: Option<NodeId>,
    dfs_scratch: &mut Vec<NodeId>,
) -> FocusRecoveryResult {
    let prev_modal = anchor.active_modal;
    let new_modal = topmost_open_modal(store, oracle, dfs_scratch);
    let prev_focus = current_focused.or(anchor.focused);
    let prev_modal_closed =
        prev_modal.is_some_and(|pm| {
            new_modal != Some(pm) && !is_open_modal(store, oracle, pm)
        });
    let closing_to_underlying = prev_modal_closed
        && (new_modal.is_none()
            || new_modal.is_some_and(|nm| anchor.modal_stack_index(nm).is_some()));

    // 1. Topmost modal closed (to document root or downward to an already-open underlying modal).
    if let Some(closed_modal) = prev_modal
        && closing_to_underlying
    {
        anchor.active_modal = new_modal;
        let scope_root = new_modal.unwrap_or(NodeId::ROOT);
        let popped_return = anchor.unwind_modals_above(new_modal, store, oracle, scope_root);
        let needs_return = prev_focus.is_none_or(|p| {
            !is_focusable_node(store, oracle, p)
                || !is_within_subtree(store, p, scope_root)
                || is_within_subtree(store, p, closed_modal)
        });
        if needs_return {
            let target = explicit_return_focus
                .filter(|&id| is_focusable_node(store, oracle, id) && is_within_subtree(store, id, scope_root))
                .or(popped_return)
                .or_else(|| recover_from_trail(store, oracle, anchor, scope_root, dfs_scratch));
            if let Some(next) = target {
                let fv = resolve_focus_visible(
                    FocusModality::Programmatic,
                    last_input,
                    is_text_entry_node(store, next),
                );
                snapshot_focus_anchor(store, oracle,
                    anchor,
                    Some(next),
                    FocusModality::Programmatic,
                    dfs_scratch,
                );
                return FocusRecoveryResult::Moved {
                    previous: prev_focus,
                    next,
                    modality: FocusModality::Programmatic,
                    focus_visible: fv,
                };
            }
            anchor.focused = None;
            return match prev_focus {
                Some(previous) => FocusRecoveryResult::Cleared { previous },
                None => FocusRecoveryResult::Unchanged,
            };
        }
    } else if let Some(modal_id) = new_modal
        && new_modal != prev_modal
    {
        // 2. A brand-new modal opened (either atop the current scope or via atomic swap `B -> C`).
        let carried_return = anchor.prune_closed_top_modals(store, oracle, modal_id);
        let saved_return = if prev_modal_closed {
            // Atomic swap (`prev_modal` closed while `modal_id` opened): carry forward the closed
            // modal's return focus instead of pushing a dead/closed-modal button onto the stack.
            carried_return.or_else(|| {
                prev_focus.filter(|&id| {
                    is_focusable_node(store, oracle, id)
                        && !is_within_subtree(store, id, modal_id)
                        && prev_modal.is_none_or(|pm| !is_within_subtree(store, id, pm))
                })
            })
        } else {
            // Normal open: prefer live `current_focused` outside `modal_id`, falling back to
            // `anchor.focused` when imperative `autofocus`/`showModal()` already moved DOM focus
            // inside `modal_id` before `resolve_focus_recovery` ran.
            current_focused
                .filter(|&id| store.is_live(id) && !is_within_subtree(store, id, modal_id))
                .or_else(|| {
                    anchor
                        .focused
                        .filter(|&id| store.is_live(id) && !is_within_subtree(store, id, modal_id))
                })
        };
        anchor.push_modal(modal_id, saved_return);
        anchor.active_modal = Some(modal_id);
        if let Some(cur) = current_focused
            && is_focusable_node(store, oracle, cur)
            && is_within_subtree(store, cur, modal_id)
        {
            snapshot_focus_anchor(store, oracle, anchor, Some(cur), anchor.modality, dfs_scratch);
            return FocusRecoveryResult::Unchanged;
        }
        if let Some(next) = pick_modal_initial_focus(store, oracle, modal_id, dfs_scratch) {
            let fv = resolve_focus_visible(
                FocusModality::Programmatic,
                last_input,
                is_text_entry_node(store, next),
            );
            snapshot_focus_anchor(store, oracle,
                anchor,
                Some(next),
                FocusModality::Programmatic,
                dfs_scratch,
            );
            return FocusRecoveryResult::Moved {
                previous: prev_focus,
                next,
                modality: FocusModality::Programmatic,
                focus_visible: fv,
            };
        }
        anchor.focused = None;
        return match prev_focus {
            Some(previous) => FocusRecoveryResult::Cleared { previous },
            None => FocusRecoveryResult::Unchanged,
        };
    }

    anchor.active_modal = new_modal;
    let scope_root = new_modal.unwrap_or(NodeId::ROOT);

    let Some(prev_id) = prev_focus else {
        return FocusRecoveryResult::Unchanged;
    };

    // 3. Focused node still live & focusable inside active scope: check roving tabindex demotion.
    if is_focusable_node(store, oracle, prev_id) && is_within_subtree(store, prev_id, scope_root) {
        if anchor.was_roving_active
            && let Some(group) = anchor.composite_group
            && store.is_live(group)
            && is_within_subtree(store, group, scope_root)
            && store
                .try_row::<Interaction>(prev_id)
                .and_then(|i| i.tab_index())
                == Some(-1)
            && let Some(next) = first_matching_in_subtree(store, oracle, group, dfs_scratch, |s, id| {
                id != prev_id
                    && is_focusable_self(s, id)
                    && s.try_row::<Interaction>(id).and_then(|i| i.tab_index()) == Some(0)
            })
        {
            let fv = resolve_focus_visible(
                FocusModality::Programmatic,
                last_input,
                is_text_entry_node(store, next),
            );
            snapshot_focus_anchor(store, oracle,
                anchor,
                Some(next),
                FocusModality::Programmatic,
                dfs_scratch,
            );
            return FocusRecoveryResult::Moved {
                previous: Some(prev_id),
                next,
                modality: FocusModality::Programmatic,
                focus_visible: fv,
            };
        }
        snapshot_focus_anchor(store, oracle, anchor, Some(prev_id), anchor.modality, dfs_scratch);
        return FocusRecoveryResult::Unchanged;
    }

    // 4. Focused node became invalid (unmounted / display:none / closed overlay / disabled / out of scope).
    if let Some(next) = recover_from_trail(store, oracle, anchor, scope_root, dfs_scratch) {
        let fv = resolve_focus_visible(
            FocusModality::Programmatic,
            last_input,
            is_text_entry_node(store, next),
        );
        snapshot_focus_anchor(store, oracle,
            anchor,
            Some(next),
            FocusModality::Programmatic,
            dfs_scratch,
        );
        FocusRecoveryResult::Moved {
            previous: Some(prev_id),
            next,
            modality: FocusModality::Programmatic,
            focus_visible: fv,
        }
    } else {
        anchor.focused = None;
        anchor.prev_sibling = None;
        anchor.next_sibling = None;
        anchor.trail.clear();
        FocusRecoveryResult::Cleared { previous: prev_id }
    }
}