1
//! Focus and tab navigation management.
2
//!
3
//! Manages keyboard focus, tab navigation, and programmatic focus changes
4
//! with a recursive event system for focus/blur callbacks (max depth: 5).
5

            
6
use alloc::collections::{BTreeMap, BTreeSet};
7

            
8
use azul_core::{
9
    callbacks::{FocusTarget, FocusTargetPath},
10
    dom::{DomId, DomNodeId, NodeId},
11
    style::matches_html_element,
12
    styled_dom::NodeHierarchyItemId,
13
    window::UpdateFocusWarning,
14
};
15

            
16
use crate::window::DomLayoutResult;
17

            
18
/// Information about a pending contenteditable focus that needs cursor initialization
19
/// after layout is complete (W3C "flag and defer" pattern).
20
///
21
/// This is set during focus event handling and consumed after layout pass.
22
#[derive(Copy, Debug, Clone, PartialEq, Eq)]
23
pub struct PendingContentEditableFocus {
24
    /// The DOM where the contenteditable element is
25
    pub dom_id: DomId,
26
    /// The contenteditable container node that received focus
27
    pub container_node_id: NodeId,
28
    /// The text node where the cursor should be placed (often a child of the container)
29
    pub text_node_id: NodeId,
30
}
31

            
32
/// Manager for keyboard focus and tab navigation
33
///
34
/// Note: Text cursor management is now handled by the separate `CursorManager`.
35
///
36
/// The `FocusManager` only tracks which node has focus, while `CursorManager`
37
/// tracks the cursor position within that node (if it's contenteditable).
38
///
39
/// ## W3C Focus/Selection Model
40
///
41
/// The W3C model maintains a strict separation between **keyboard focus** and **selection**:
42
///
43
/// 1. **Focus** lands on the contenteditable container (`document.activeElement`)
44
/// 2. **Selection/Cursor** is placed in a descendant text node (`Selection.focusNode`)
45
///
46
/// This separation requires a "flag and defer" pattern:
47
/// - During focus event: Set `cursor_needs_initialization = true`
48
/// - After layout pass: Call `finalize_pending_focus_changes()` to actually initialize the cursor
49
///
50
/// This is necessary because cursor positioning requires text layout information,
51
/// which isn't available during the focus event handling phase.
52
#[derive(Debug, Clone, PartialEq, Eq)]
53
pub struct FocusManager {
54
    /// Currently focused node (if any)
55
    pub focused_node: Option<DomNodeId>,
56
    /// Pending focus request from callback
57
    pub pending_focus_request: Option<FocusTarget>,
58

            
59
    /// Whether the CURRENT focus should be indicated visually - the W3C
60
    /// `:focus-visible` rule.
61
    ///
62
    /// Focus and its INDICATION are different questions. A browser rings a
63
    /// control focused by Tab and does NOT ring one focused by a click or by
64
    /// `autofocus`: a form that opens with its first field ringed looks like
65
    /// the user pressed Tab when they did not. The focus ring reads this;
66
    /// hit-testing, activation and the a11y tree read `focused_node` and do
67
    /// not care how focus arrived.
68
    ///
69
    /// Set by the route that MOVES focus: keyboard navigation sets it, a
70
    /// pointer click and `autofocus` clear it.
71
    pub focus_is_visible: bool,
72

            
73
    // --- W3C "flag and defer" pattern fields ---
74
    /// Flag indicating that cursor initialization is pending (set during focus, consumed after
75
    /// layout)
76
    pub cursor_needs_initialization: bool,
77
    /// Information about the pending contenteditable focus
78
    pub pending_contenteditable_focus: Option<PendingContentEditableFocus>,
79

            
80
    // --- focus-before-first-layout retry queue ---
81
    /// A [`FocusTarget`] that could not be resolved because no layout existed
82
    /// yet, kept so it can be re-resolved as soon as one does.
83
    ///
84
    /// `resolve_focus_target` used to answer `Ok(None)` with empty
85
    /// `layout_results`, and every caller read that as "clear focus" — so a programmatic
86
    /// `set_focus` issued from a `create` callback (which runs BEFORE the first
87
    /// layout) vanished without a trace, and apps papered over it with a
88
    /// short timer. Drained by
89
    /// `LayoutWindow::finalize_pending_focus_changes`, which runs after the
90
    /// layout pass.
91
    pub deferred_focus_target: Option<FocusTarget>,
92
    /// How many times the pending contenteditable focus has been re-armed for
93
    /// want of a text layout. Bounded so a node that will never have an inline
94
    /// layout cannot re-arm forever.
95
    pub pending_focus_retries: u8,
96

            
97
    /// The OTHER seats' focused nodes (9b-ii-a-i-d): seat 0, the primary, IS
98
    /// `focused_node`; a second seat (X11 MPX master pair, a second Wayland
99
    /// `wl_seat`) keeps its own here, so two people can edit two fields of
100
    /// one window - the user's ruling. Absent = that seat focuses nothing.
101
    /// Key events of a seat target ITS node; click-to-focus and the Tab walk
102
    /// move ITS entry. The text-edit session, the `:focus` restyle and the
103
    /// a11y focus stay the primary's (follow-ups, see the ledger).
104
    pub seat_focus: BTreeMap<u64, DomNodeId>,
105
}
106

            
107
/// How many times [`FocusManager::pending_contenteditable_focus`] may be put
108
/// back because the text layout was not available yet.
109
pub const MAX_PENDING_FOCUS_RETRIES: u8 = 2;
110

            
111
/// Outcome of resolving a [`FocusTarget`] — the answer says WHY there is no
112
/// node, not just that there is none.
113
///
114
/// The old shape (`Resolved(Option<DomNodeId>)`) conflated three different
115
/// answers in `None`: "the app asked to clear focus", "the selector matched
116
/// nothing", and "the tab order is empty" — and every caller applied all of
117
/// them as a clear. A focus request that merely MISSED (a selector against a
118
/// `VirtualView` that had not materialized yet, a Tab press with nothing
119
/// tabbable) therefore DESTROYED the current focus/caret as a side effect.
120
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121
pub enum FocusResolution {
122
    /// The target resolved to this node — apply it.
123
    Resolved(DomNodeId),
124
    /// The app explicitly asked for no focus (`FocusTarget::NoFocus`) —
125
    /// apply the clear.
126
    ClearRequested,
127
    /// The target matched nothing (unmatched selector, empty tab order,
128
    /// no layout to search). NOT a clear: callers keep the current focus.
129
    NotFound,
130
    /// No layout existed yet, so the target was retained on the
131
    /// [`FocusManager`] and will be re-resolved after the first layout pass.
132
    /// Callers must leave the current focus alone.
133
    Deferred,
134
}
135

            
136
impl Default for FocusManager {
137
2
    fn default() -> Self {
138
2
        Self::new()
139
2
    }
140
}
141

            
142
impl FocusManager {
143
    /// Create a new focus manager
144
    #[must_use]
145
7789
    pub const fn new() -> Self {
146
7789
        Self {
147
7789
            focused_node: None,
148
7789
            pending_focus_request: None,
149
7789
            focus_is_visible: false,
150
7789
            cursor_needs_initialization: false,
151
7789
            pending_contenteditable_focus: None,
152
7789
            deferred_focus_target: None,
153
7789
            pending_focus_retries: 0,
154
7789
            seat_focus: BTreeMap::new(),
155
7789
        }
156
7789
    }
157

            
158
    /// The node seat `seat_id` focuses (9b-ii-a-i-d): the primary's is
159
    /// `focused_node`, every other seat's its own entry.
160
    #[must_use]
161
2964
    pub fn focused_node_for(&self, seat_id: u64) -> Option<DomNodeId> {
162
2964
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
163
2823
            self.focused_node
164
        } else {
165
141
            self.seat_focus.get(&seat_id).copied()
166
        }
167
2964
    }
168

            
169
    /// Move seat `seat_id`'s focus; `None` clears it. The primary seat is
170
    /// `set_focused_node`.
171
116
    pub fn set_focused_node_for(&mut self, seat_id: u64, node: Option<DomNodeId>) {
172
116
        if seat_id == azul_core::window::PRIMARY_POINTER_SEAT {
173
1
            self.focused_node = node;
174
1
        } else {
175
115
            match node {
176
110
                Some(n) => {
177
110
                    self.seat_focus.insert(seat_id, n);
178
110
                }
179
5
                None => {
180
5
                    self.seat_focus.remove(&seat_id);
181
5
                }
182
            }
183
        }
184
116
    }
185

            
186
    /// Whether seat `seat_id` focuses `node`.
187
    #[must_use]
188
2
    pub fn has_focus_for(&self, seat_id: u64, node: &DomNodeId) -> bool {
189
2
        self.focused_node_for(seat_id).as_ref() == Some(node)
190
2
    }
191

            
192
    /// Every seat focusing `node`, the primary as seat 0.
193
    #[must_use]
194
6
    pub fn seats_focusing(&self, node: &DomNodeId) -> Vec<u64> {
195
6
        let mut seats = Vec::new();
196
6
        if self.focused_node.as_ref() == Some(node) {
197
            seats.push(azul_core::window::PRIMARY_POINTER_SEAT);
198
6
        }
199
6
        seats.extend(
200
6
            self.seat_focus
201
6
                .iter()
202
6
                .filter(|(_, n)| *n == node)
203
6
                .map(|(seat, _)| *seat),
204
        );
205
6
        seats
206
6
    }
207

            
208
    /// Get the currently focused node
209
    #[must_use]
210
51194
    pub const fn get_focused_node(&self) -> Option<&DomNodeId> {
211
51194
        self.focused_node.as_ref()
212
51194
    }
213

            
214
    /// Set the focused node directly (used by event system)
215
    ///
216
    /// Note: Cursor initialization/clearing is now handled by `CursorManager`.
217
    /// The event system should check if the newly focused node is contenteditable
218
    /// and call `CursorManager::initialize_cursor_at_end()` if needed.
219
    /// Move focus and say whether it should be INDICATED (see
220
    /// [`Self::focus_is_visible`]): `true` for keyboard navigation, `false`
221
    /// for a pointer click or `autofocus`.
222
26
    pub const fn set_focused_node_with_visibility(
223
26
        &mut self,
224
26
        node: Option<DomNodeId>,
225
26
        visible: bool,
226
26
    ) {
227
26
        self.focused_node = node;
228
26
        self.focus_is_visible = visible;
229
26
    }
230

            
231
1351
    pub const fn set_focused_node(&mut self, node: Option<DomNodeId>) {
232
1351
        self.focused_node = node;
233
1351
    }
234

            
235
    /// Request a focus change (to be processed by event system)
236
12
    pub fn request_focus_change(&mut self, target: FocusTarget) {
237
12
        self.pending_focus_request = Some(target);
238
12
    }
239

            
240
    /// Take the pending focus request (one-shot)
241
14
    pub const fn take_focus_request(&mut self) -> Option<FocusTarget> {
242
14
        self.pending_focus_request.take()
243
14
    }
244

            
245
    /// Clear focus
246
5
    pub const fn clear_focus(&mut self) {
247
5
        self.focused_node = None;
248
5
    }
249

            
250
    /// Check if a specific node has focus
251
    #[must_use]
252
75
    pub fn has_focus(&self, node: &DomNodeId) -> bool {
253
75
        self.focused_node.as_ref() == Some(node)
254
75
    }
255

            
256
    // --- W3C "flag and defer" pattern methods ---
257

            
258
    /// Mark that cursor initialization is needed for a contenteditable element.
259
    ///
260
    /// This is called during focus event handling. The actual cursor initialization
261
    /// happens later in `finalize_pending_focus_changes()` after layout is complete.
262
    ///
263
    /// # W3C Conformance
264
    ///
265
    /// In the W3C model, when focus lands on a contenteditable element:
266
    /// 1. The focus event fires on the container element
267
    /// 2. The browser's editing engine modifies the Selection to place a caret
268
    /// 3. The Selection's anchorNode/focusNode point to the child text node
269
    ///
270
    /// Since we need layout information to position the cursor, we defer step 2+3.
271
110
    pub const fn set_pending_contenteditable_focus(
272
110
        &mut self,
273
110
        dom_id: DomId,
274
110
        container_node_id: NodeId,
275
110
        text_node_id: NodeId,
276
110
    ) {
277
110
        self.cursor_needs_initialization = true;
278
110
        self.pending_focus_retries = 0;
279
110
        self.pending_contenteditable_focus = Some(PendingContentEditableFocus {
280
110
            dom_id,
281
110
            container_node_id,
282
110
            text_node_id,
283
110
        });
284
110
    }
285

            
286
    /// Put a just-taken pending contenteditable focus BACK because the text
287
    /// layout it needs did not exist yet. Returns `false` once
288
    /// [`MAX_PENDING_FOCUS_RETRIES`] is exhausted, in which case the caller
289
    /// must seed the cursor with whatever it has.
290
33
    pub const fn rearm_pending_contenteditable_focus(
291
33
        &mut self,
292
33
        pending: PendingContentEditableFocus,
293
33
    ) -> bool {
294
33
        if self.pending_focus_retries >= MAX_PENDING_FOCUS_RETRIES {
295
11
            return false;
296
22
        }
297
22
        self.pending_focus_retries += 1;
298
22
        self.cursor_needs_initialization = true;
299
22
        self.pending_contenteditable_focus = Some(pending);
300
22
        true
301
33
    }
302

            
303
    /// Put a just-taken pending contenteditable focus BACK because the whole
304
    /// DOM's layout result is ABSENT - the funnel takes it out while the pass
305
    /// runs, the same transient absence `caret_editable_is_focused` tolerates.
306
    /// Unlike [`Self::rearm_pending_contenteditable_focus`] this does NOT
307
    /// spend a retry: mid-pass absence is not a failed attempt, and burning
308
    /// the bounded budget on it locked in the (0,0)+Trailing fallback - the
309
    /// device caret landing MID-TEXT ('4|2') when tabbing into a filled
310
    /// `NumberInput` (2026-08-31).
311
5
    pub const fn rearm_pending_contenteditable_focus_transient(
312
5
        &mut self,
313
5
        pending: PendingContentEditableFocus,
314
5
    ) {
315
5
        self.cursor_needs_initialization = true;
316
5
        self.pending_contenteditable_focus = Some(pending);
317
5
    }
318

            
319
    /// Clear the pending contenteditable focus (when focus moves away or is cleared).
320
36
    pub const fn clear_pending_contenteditable_focus(&mut self) {
321
36
        self.cursor_needs_initialization = false;
322
36
        self.pending_focus_retries = 0;
323
36
        self.pending_contenteditable_focus = None;
324
36
    }
325

            
326
    /// Take the pending contenteditable focus (consumes the flag).
327
    ///
328
    /// Returns `Some(info)` if cursor initialization is pending, `None` otherwise.
329
    /// After calling this, `cursor_needs_initialization` is set to `false`.
330
239
    pub const fn take_pending_contenteditable_focus(
331
239
        &mut self,
332
239
    ) -> Option<PendingContentEditableFocus> {
333
239
        if self.cursor_needs_initialization {
334
119
            self.cursor_needs_initialization = false;
335
119
            self.pending_contenteditable_focus.take()
336
        } else {
337
120
            None
338
        }
339
239
    }
340

            
341
    /// Check if cursor initialization is pending.
342
    #[must_use]
343
17
    pub const fn needs_cursor_initialization(&self) -> bool {
344
17
        self.cursor_needs_initialization
345
17
    }
346

            
347
    // --- focus-before-first-layout retry queue ---
348

            
349
    /// Retain a focus target that had no layout to resolve against.
350
    ///
351
    /// A later request replaces an earlier one: only the most recent
352
    /// programmatic focus can win once layout arrives, exactly as it would if
353
    /// both had been resolvable immediately.
354
11
    pub fn defer_focus_target(&mut self, target: FocusTarget) {
355
11
        self.deferred_focus_target = Some(target);
356
11
    }
357

            
358
    /// Whether a focus target is waiting for the first layout.
359
    #[must_use]
360
359
    pub const fn has_deferred_focus_target(&self) -> bool {
361
359
        self.deferred_focus_target.is_some()
362
359
    }
363

            
364
    /// Take the deferred focus target (one-shot).
365
11
    pub const fn take_deferred_focus_target(&mut self) -> Option<FocusTarget> {
366
11
        self.deferred_focus_target.take()
367
11
    }
368
}
369

            
370
impl crate::managers::NodeIdRemap for FocusManager {
371
    /// Remap the focused node AND the pending contenteditable focus.
372
    ///
373
    /// Focus on an unmounted node is CLEARED (not kept — the index now denotes a
374
    /// different element).
375
456
    fn remap_node_ids(&mut self, dom_id: DomId, map: &crate::managers::NodeIdMap) {
376
        // 0. the other seats' focus (9b-ii-a-i-d): the same rule as the
377
        // primary's - follow the node, clear on an unmounted one.
378
456
        self.seat_focus.retain(|_, focused| {
379
2
            if focused.dom != dom_id {
380
                return true;
381
2
            }
382
2
            match focused
383
2
                .node
384
2
                .into_crate_internal()
385
2
                .and_then(|old| map.resolve(old))
386
            {
387
1
                Some(new_id) => {
388
1
                    focused.node = NodeHierarchyItemId::from_crate_internal(Some(new_id));
389
1
                    true
390
                }
391
1
                None => false,
392
            }
393
2
        });
394
        // 1. currently focused node
395
456
        if let Some(focused) = self.focused_node {
396
67
            if focused.dom == dom_id {
397
66
                match focused
398
66
                    .node
399
66
                    .into_crate_internal()
400
66
                    .and_then(|old| map.resolve(old))
401
                {
402
64
                    Some(new_id) => {
403
64
                        self.focused_node = Some(DomNodeId {
404
64
                            dom: dom_id,
405
64
                            node: NodeHierarchyItemId::from_crate_internal(Some(new_id)),
406
64
                        });
407
64
                    }
408
2
                    None => self.focused_node = None,
409
                }
410
1
            }
411
389
        }
412

            
413
        // 2. pending contenteditable focus (set during focus handling, consumed after layout — a
414
        //    DOM rebuild can land in between).
415
456
        if let Some(ref mut pending) = self.pending_contenteditable_focus {
416
4
            if pending.dom_id != dom_id {
417
                return;
418
4
            }
419
1
            if let (Some(container), Some(text)) = (
420
4
                map.resolve(pending.container_node_id),
421
4
                map.resolve(pending.text_node_id),
422
1
            ) {
423
1
                pending.container_node_id = container;
424
1
                pending.text_node_id = text;
425
3
            } else {
426
3
                self.pending_contenteditable_focus = None;
427
3
                self.cursor_needs_initialization = false;
428
3
            }
429
452
        }
430
456
    }
431
}
432

            
433
/// MWA-C-focus_cursor: W3C sequential focus order over all DOMs.
434
///
435
/// Ordering: nodes with a positive `tabindex` (`TabIndex::OverrideInParent(n)`,
436
/// n >= 1) come first, ascending by n (stable sort, so document order breaks
437
/// ties); then all remaining keyboard-focusable nodes (`Auto`,
438
/// `OverrideInParent(0)`, implicit focusables) in document order.
439
/// `TabIndex::NoKeyboardFocus` (tabindex=-1) nodes stay focusable by click /
440
/// API but are NEVER part of the Tab order. The previous linear `NodeId` walk
441
/// both ignored positive-tabindex ordering and tabbed onto tabindex=-1 nodes.
442
410
fn collect_tab_order(
443
410
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
444
410
    out_of_scope: &BTreeSet<DomId>,
445
410
) -> Vec<DomNodeId> {
446
    use azul_core::dom::TabIndex;
447
410
    let mut positive: Vec<(u32, DomNodeId)> = Vec::new();
448
410
    let mut auto: Vec<DomNodeId> = Vec::new();
449
822
    for (dom_id, layout) in layout_results {
450
        // A DOM that is not part of THIS window's focus scope contributes no
451
        // tab stops. A transient popup is a separate OS window whose content
452
        // DOM the PARENT lays out, so without this the parent's Tab order
453
        // walked straight into the popup - and kept doing so after the popup
454
        // closed, which stranded the keyboard there (device report,
455
        // 2026-09-01). Inside the popup's own window that same content is the
456
        // ROOT dom and hosts no popups, so it stays fully tabbable there.
457
412
        if out_of_scope.contains(dom_id) {
458
1
            continue;
459
411
        }
460
        // A `<transient-window>`'s SUBTREE is not rendered by this window: it
461
        // is the template the popup's own window shows, extracted into its own
462
        // DOM when the popup opens. The parent's copy is never on screen, so
463
        // it can hold no tab stops - Tab landed on it anyway (a ColorInput has
464
        // ONE real stop, the swatch, and EIGHT under its transient node), and
465
        // then arrow keys did nothing because the focused node was the
466
        // parent's dead copy rather than the live control the popup displays
467
        // (device report, 2026-09-01).
468
411
        let node_data = layout.styled_dom.node_data.as_container();
469
411
        let hierarchy = layout.styled_dom.node_hierarchy.as_container();
470
411
        let transient_roots: Vec<NodeId> = (0..node_data.len())
471
411
            .map(NodeId::new)
472
3429
            .filter(|n| {
473
3429
                node_data.get(*n).is_some_and(|nd| {
474
3428
                    matches!(
475
3429
                        nd.get_node_type(),
476
                        azul_core::dom::NodeType::TransientWindow(_)
477
                    )
478
3429
                })
479
3429
            })
480
411
            .collect();
481
2002
        let under_transient = |mut n: NodeId| -> bool {
482
2002
            if transient_roots.is_empty() {
483
1999
                return false;
484
3
            }
485
3
            let mut guard = 0usize;
486
4
            while let Some(parent) = hierarchy
487
4
                .get(n)
488
4
                .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id)
489
            {
490
3
                guard += 1;
491
3
                if guard > 65_536 {
492
                    break;
493
3
                }
494
3
                if transient_roots.contains(&parent) {
495
2
                    return true;
496
1
                }
497
1
                n = parent;
498
            }
499
1
            false
500
2002
        };
501
3429
        for index in 0..node_data.len() {
502
3429
            let node_id = NodeId::new(index);
503
3429
            let Some(nd) = node_data.get(node_id) else {
504
                continue;
505
            };
506
3429
            if !nd.is_focusable() {
507
1427
                continue;
508
2002
            }
509
2002
            if under_transient(node_id) {
510
2
                continue;
511
2000
            }
512
2000
            let dom_node = FocusSearchContext::make_dom_node_id(*dom_id, node_id);
513
2000
            match nd.get_tab_index() {
514
19
                Some(TabIndex::NoKeyboardFocus) => {}
515
60
                Some(TabIndex::OverrideInParent(n)) if n > 0 => positive.push((n, dom_node)),
516
1941
                _ => auto.push(dom_node),
517
            }
518
        }
519
    }
520
410
    order_tab_entries(positive, auto)
521
410
}
522

            
523
/// Pure merge of the two tab-order sections (split out for unit testing).
524
416
fn order_tab_entries(mut positive: Vec<(u32, DomNodeId)>, auto: Vec<DomNodeId>) -> Vec<DomNodeId> {
525
416
    positive.sort_by_key(|(n, _)| *n); // stable: document order within equal n
526
416
    positive.into_iter().map(|(_, id)| id).chain(auto).collect()
527
416
}
528

            
529
/// Document-order key for a node (DOM index, then arena index) — used to
530
/// re-enter the tab order from a node that is not itself tab-focusable.
531
95
fn doc_order_key(id: &DomNodeId) -> (usize, usize) {
532
    (
533
95
        id.dom.inner,
534
95
        id.node.into_crate_internal().map_or(0, |n| n.index()),
535
    )
536
95
}
537

            
538
/// Pick the next / previous entry in `order` relative to `current`.
539
///
540
/// If `current` is a tab stop, steps with wrap-around. If it is not (no focus
541
/// yet, or focus sits on a tabindex=-1 / removed node), forward picks the
542
/// first tab stop after it in document order (wrapping to the first entry),
543
/// backward symmetrically.
544
51
fn next_in_tab_order(
545
51
    order: &[DomNodeId],
546
51
    current: Option<DomNodeId>,
547
51
    forward: bool,
548
51
) -> Option<DomNodeId> {
549
51
    if order.is_empty() {
550
8
        return None;
551
43
    }
552
43
    let Some(cur) = current else {
553
9
        return if forward {
554
8
            order.first().copied()
555
        } else {
556
1
            order.last().copied()
557
        };
558
    };
559
83
    if let Some(pos) = order.iter().position(|x| *x == cur) {
560
19
        let len = order.len();
561
19
        let next = if forward {
562
13
            (pos + 1) % len
563
        } else {
564
6
            (pos + len - 1) % len
565
        };
566
19
        return Some(order[next]);
567
15
    }
568
15
    let cur_key = doc_order_key(&cur);
569
15
    let candidate = if forward {
570
8
        order
571
8
            .iter()
572
27
            .filter(|x| doc_order_key(x) > cur_key)
573
9
            .min_by_key(|x| doc_order_key(x))
574
    } else {
575
7
        order
576
7
            .iter()
577
22
            .filter(|x| doc_order_key(x) < cur_key)
578
10
            .max_by_key(|x| doc_order_key(x))
579
    };
580
15
    candidate.copied().or_else(|| {
581
7
        if forward {
582
4
            order.first().copied()
583
        } else {
584
3
            order.last().copied()
585
        }
586
7
    })
587
51
}
588

            
589
/// Context for focus-target resolution (`Path` / `Id` lookups).
590
///
591
/// MWA-C-focus_cursor: the old linear-walk machinery (`SearchDirection`,
592
/// `search_focusable_node`, `get_*_start`) was replaced by the W3C tab order
593
/// built in `collect_tab_order`; only the layout lookup helpers remain.
594
struct FocusSearchContext<'a> {
595
    /// Reference to all DOM layouts in the window
596
    layout_results: &'a BTreeMap<DomId, DomLayoutResult>,
597
}
598

            
599
impl<'a> FocusSearchContext<'a> {
600
    /// Create a new search context from layout results.
601
430
    const fn new(layout_results: &'a BTreeMap<DomId, DomLayoutResult>) -> Self {
602
430
        Self { layout_results }
603
430
    }
604

            
605
    /// Get the layout for a DOM ID, or return an error if invalid.
606
    #[allow(clippy::trivially_copy_pass_by_ref)] // <=8B Copy param kept by-ref intentionally (hot
607
                                                 // pixel/coord path or to avoid churning call sites
608
                                                 // for a perf-neutral change)
609
31
    fn get_layout(&self, dom_id: &DomId) -> Result<&'a DomLayoutResult, UpdateFocusWarning> {
610
31
        self.layout_results
611
31
            .get(dom_id)
612
31
            .ok_or_else(|| UpdateFocusWarning::FocusInvalidDomId(*dom_id))
613
31
    }
614

            
615
    /// Construct a `DomNodeId` from DOM and node IDs.
616
2218
    const fn make_dom_node_id(dom_id: DomId, node_id: NodeId) -> DomNodeId {
617
2218
        DomNodeId {
618
2218
            dom: dom_id,
619
2218
            node: NodeHierarchyItemId::from_crate_internal(Some(node_id)),
620
2218
        }
621
2218
    }
622
}
623

            
624
/// Find the first focusable node matching a CSS path selector.
625
///
626
/// Iterates through all nodes in the DOM in document order (index 0..n),
627
/// and returns the first node that:
628
///
629
/// 1. Matches the CSS path selector
630
/// 2. Is focusable (has `tabindex` or is naturally focusable)
631
///
632
/// # Returns
633
///
634
/// * `Ok(Some(node))` - Found a matching focusable node
635
/// * `Ok(None)` - No matching focusable node exists
636
/// * `Err(_)` - CSS path could not be matched (malformed selector)
637
#[allow(clippy::trivially_copy_pass_by_ref)] // <=8B Copy param kept by-ref intentionally (hot
638
                                             // pixel/coord path or to avoid churning call sites for
639
                                             // a perf-neutral change)
640
9
fn find_first_matching_focusable_node(
641
9
    layout: &DomLayoutResult,
642
9
    dom_id: &DomId,
643
9
    css_path: &azul_css::css::CssPath,
644
9
) -> Option<DomNodeId> {
645
9
    let styled_dom = &layout.styled_dom;
646
9
    let node_hierarchy = styled_dom.node_hierarchy.as_container();
647
9
    let node_data = styled_dom.node_data.as_container();
648
9
    let cascade_info = styled_dom.cascade_info.as_container();
649

            
650
    // Iterate through all nodes in document order
651
9
    let matching_node = (0..node_data.len())
652
9
        .map(NodeId::new)
653
31
        .filter(|&node_id| {
654
            // Check if node matches the CSS path (no pseudo-selector requirement)
655
31
            matches_html_element(
656
31
                css_path,
657
31
                node_id,
658
31
                &node_hierarchy,
659
31
                &node_data,
660
31
                &cascade_info,
661
31
                None, // No expected pseudo-selector ending like :hover/:focus
662
            )
663
31
        })
664
9
        .find(|&node_id| {
665
            // Among matching nodes, find first that is focusable
666
5
            node_data[node_id].is_focusable()
667
5
        });
668

            
669
9
    matching_node.map(|node_id| DomNodeId {
670
4
        dom: *dom_id,
671
4
        node: NodeHierarchyItemId::from_crate_internal(Some(node_id)),
672
4
    })
673
9
}
674

            
675
/// The child DOMs `host` mounts through `VirtualView` items, transitively, in
676
/// display-list order.
677
///
678
/// Read off the host's display list — the same place
679
/// `headless::resolve_virtual_view_placements` reads it — because that is the
680
/// only host→child link available to a function that is handed nothing but
681
/// `layout_results`. Bounded by the number of layout results, so a cyclic or
682
/// self-referential item cannot spin.
683
2
fn nested_dom_ids(layout_results: &BTreeMap<DomId, DomLayoutResult>, host: DomId) -> Vec<DomId> {
684
    use crate::solver3::display_list::DisplayListItem;
685

            
686
2
    let mut out: Vec<DomId> = Vec::new();
687
2
    let mut queue: Vec<DomId> = vec![host];
688
2
    let mut head = 0usize;
689
2
    let limit = layout_results.len().saturating_add(1);
690
5
    while head < queue.len() && head < limit {
691
3
        let current = queue[head];
692
3
        head += 1;
693
3
        let Some(lr) = layout_results.get(&current) else {
694
            continue;
695
        };
696
3
        for item in &lr.display_list.items {
697
1
            if let DisplayListItem::VirtualView { child_dom_id, .. } = item {
698
1
                if *child_dom_id != host && !out.contains(child_dom_id) {
699
1
                    out.push(*child_dom_id);
700
1
                    queue.push(*child_dom_id);
701
1
                }
702
            }
703
        }
704
    }
705
2
    out
706
2
}
707

            
708
/// Resolve a `FocusTarget`, or QUEUE it when there is no layout to resolve
709
/// against yet.
710
///
711
/// This is the entry point every focus-changing caller should use.
712
/// [`resolve_focus_target`] used to be unable to tell "nothing matched" from "nothing exists
713
/// yet": both are `Ok(None)`, and callers apply that as "clear focus". A
714
/// `set_focus` issued from a `create` callback — which runs before the first
715
/// layout — was therefore dropped on the floor.
716
///
717
/// # Errors
718
///
719
/// Returns an `UpdateFocusWarning` if the focus target cannot be resolved.
720
14
pub fn resolve_focus_target_or_defer(
721
14
    focus_manager: &mut FocusManager,
722
14
    focus_target: &FocusTarget,
723
14
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
724
14
    out_of_scope: &BTreeSet<DomId>,
725
14
) -> Result<FocusResolution, UpdateFocusWarning> {
726
    // `NoFocus` means the app WANTS focus cleared; that is answerable without
727
    // any layout and must not be queued (it would then fire later, clearing a
728
    // focus the app had meanwhile set).
729
14
    if layout_results.is_empty() && !matches!(focus_target, FocusTarget::NoFocus) {
730
10
        focus_manager.defer_focus_target(focus_target.clone());
731
10
        return Ok(FocusResolution::Deferred);
732
4
    }
733

            
734
4
    let current_focus = focus_manager.get_focused_node().copied();
735
4
    resolve_focus_target(focus_target, layout_results, current_focus, out_of_scope)
736
14
}
737

            
738
/// Resolve a `FocusTarget` to a [`FocusResolution`] (never `Deferred` —
739
/// that variant belongs to [`resolve_focus_target_or_defer`], which parks
740
/// targets that arrive before the first layout).
741
///
742
/// # Errors
743
///
744
/// Returns an `UpdateFocusWarning` if the focus target names an invalid
745
/// dom/node.
746
437
pub fn resolve_focus_target(
747
437
    focus_target: &FocusTarget,
748
437
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
749
437
    current_focus: Option<DomNodeId>,
750
437
    out_of_scope: &BTreeSet<DomId>,
751
437
) -> Result<FocusResolution, UpdateFocusWarning> {
752
    use azul_core::callbacks::FocusTarget::{
753
        Directional, First, Id, Last, Next, NoFocus, Path, Previous,
754
    };
755

            
756
    // The explicit clear is answerable without any layout and must stay
757
    // distinguishable from every kind of miss below.
758
437
    if matches!(focus_target, NoFocus) {
759
2
        return Ok(FocusResolution::ClearRequested);
760
435
    }
761
435
    if layout_results.is_empty() {
762
7
        return Ok(FocusResolution::NotFound);
763
428
    }
764

            
765
428
    let ctx = FocusSearchContext::new(layout_results);
766

            
767
428
    match focus_target {
768
4
        Path(FocusTargetPath { dom, css_path }) => {
769
4
            let layout = ctx.get_layout(dom)?;
770
3
            if let Some(found) = find_first_matching_focusable_node(layout, dom, css_path) {
771
1
                return Ok(FocusResolution::Resolved(found));
772
2
            }
773
            // A `VirtualView` mounts its callback's DOM as a SEPARATE layout
774
            // result under its own DomId. To the app that subtree is part of
775
            // the same document — it wrote it, it gets its edit callbacks —
776
            // but a selector resolved against the HOST dom alone could never
777
            // see it, so `set_focus_to_path` matched nothing and the caller's
778
            // focus request was applied as "clear focus".
779
            //
780
            // That is why an app whose editable content lives in a VirtualView
781
            // (AzWriter's page canvas) opened with no caret at all: its
782
            // startup focus targeted `.mw-doc`, which is a class on the page
783
            // content root inside the nested dom.
784
2
            for nested in nested_dom_ids(layout_results, *dom) {
785
1
                let Some(nested_layout) = layout_results.get(&nested) else {
786
                    continue;
787
                };
788
1
                if let Some(found) =
789
1
                    find_first_matching_focusable_node(nested_layout, &nested, css_path)
790
                {
791
1
                    return Ok(FocusResolution::Resolved(found));
792
                }
793
            }
794
1
            Ok(FocusResolution::NotFound)
795
        }
796

            
797
23
        Id(dom_node_id) => {
798
23
            let layout = ctx.get_layout(&dom_node_id.dom)?;
799
22
            let is_valid = dom_node_id
800
22
                .node
801
22
                .into_crate_internal()
802
22
                .is_some_and(|n| layout.styled_dom.node_data.as_container().get(n).is_some());
803

            
804
22
            if is_valid {
805
17
                Ok(FocusResolution::Resolved(*dom_node_id))
806
            } else {
807
5
                Err(UpdateFocusWarning::FocusInvalidNodeId(dom_node_id.node))
808
            }
809
        }
810

            
811
        // MWA-C-focus_cursor: sequential navigation goes through the W3C tab
812
        // order (positive tabindex ascending, then document order; -1
813
        // excluded) instead of the old raw-NodeId walk.
814
6
        Previous => Ok(next_in_tab_order(
815
6
            &collect_tab_order(layout_results, out_of_scope),
816
6
            current_focus,
817
6
            false,
818
6
        )
819
6
        .map_or(FocusResolution::NotFound, FocusResolution::Resolved)),
820

            
821
        // Directional (spatial) navigation. Same candidate pool as Tab —
822
        // `collect_tab_order` already honours tabindex=-1, transient windows
823
        // and out-of-scope DOMs, and a node that cannot be tabbed to should
824
        // not be reachable with an arrow key either.
825
        //
826
        // Spatial navigation CONTAINERS (9a-i-b, 9a-i-b-i) narrow that pool:
827
        // the search runs in the innermost container first, then in each
828
        // container outward, and in the whole document last. That chain is
829
        // the spec's own shape, so an arrow at the edge of a scroll box or a
830
        // `contain` panel still escapes it rather than dying there - but a
831
        // candidate INSIDE the box wins over a nearer one outside.
832
370
        Directional(dir) => {
833
370
            let all = collect_tab_order(layout_results, out_of_scope);
834
370
            let chain = current_focus
835
370
                .map(|c| spatial_navigation_containers(layout_results, c))
836
370
                .unwrap_or_default();
837
370
            let found = chain
838
370
                .iter()
839
370
                .find_map(|container| {
840
5
                    let pool: Vec<DomNodeId> = all
841
5
                        .iter()
842
5
                        .copied()
843
16
                        .filter(|cand| is_within(layout_results, *cand, *container))
844
5
                        .collect();
845
5
                    next_in_direction(&pool, layout_results, current_focus, *dir)
846
5
                })
847
370
                .or_else(|| next_in_direction(&all, layout_results, current_focus, *dir));
848
370
            Ok(found.map_or(FocusResolution::NotFound, FocusResolution::Resolved))
849
        }
850

            
851
20
        Next => Ok(next_in_tab_order(
852
20
            &collect_tab_order(layout_results, out_of_scope),
853
20
            current_focus,
854
20
            true,
855
20
        )
856
20
        .map_or(FocusResolution::NotFound, FocusResolution::Resolved)),
857

            
858
3
        First => Ok(collect_tab_order(layout_results, out_of_scope)
859
3
            .first()
860
3
            .copied()
861
3
            .map_or(FocusResolution::NotFound, FocusResolution::Resolved)),
862

            
863
2
        Last => Ok(collect_tab_order(layout_results, out_of_scope)
864
2
            .last()
865
2
            .copied()
866
2
            .map_or(FocusResolution::NotFound, FocusResolution::Resolved)),
867

            
868
        // Handled by the early return above; kept for match exhaustiveness.
869
        NoFocus => Ok(FocusResolution::ClearRequested),
870
    }
871
437
}
872

            
873
// Trait Implementations for Event Filtering
874

            
875
impl azul_core::events::FocusManagerQuery for FocusManager {
876
4
    fn get_focused_node_for_seat(&self, seat_id: u64) -> Option<DomNodeId> {
877
4
        self.focused_node_for(seat_id)
878
4
    }
879

            
880
    fn get_focused_node_id(&self) -> Option<DomNodeId> {
881
        self.focused_node
882
    }
883
}
884

            
885
#[cfg(test)]
886
mod tab_order_tests {
887
    use super::*;
888

            
889
    #[test]
890
1
    fn a_transient_rearm_spends_no_retry_budget() {
891
1
        let mut fm = FocusManager::default();
892
1
        fm.set_pending_contenteditable_focus(DomId { inner: 0 }, NodeId::new(1), NodeId::new(2));
893
6
        for _ in 0..5 {
894
5
            let pending = fm.take_pending_contenteditable_focus().expect("armed");
895
5
            fm.rearm_pending_contenteditable_focus_transient(pending);
896
5
        }
897
        // The bounded rearm still has its FULL budget afterwards.
898
1
        let pending = fm.take_pending_contenteditable_focus().expect("armed");
899
1
        assert!(
900
1
            fm.rearm_pending_contenteditable_focus(pending),
901
            "retry 1 must be available"
902
        );
903
1
        let pending = fm.take_pending_contenteditable_focus().expect("armed");
904
1
        assert!(
905
1
            fm.rearm_pending_contenteditable_focus(pending),
906
            "retry 2 must be available"
907
        );
908
1
        let pending = fm.take_pending_contenteditable_focus().expect("armed");
909
1
        assert!(
910
1
            !fm.rearm_pending_contenteditable_focus(pending),
911
            "budget is 2"
912
        );
913
1
    }
914

            
915
37
    fn nid(dom: usize, node: usize) -> DomNodeId {
916
37
        FocusSearchContext::make_dom_node_id(DomId { inner: dom }, NodeId::new(node))
917
37
    }
918

            
919
    #[test]
920
1
    fn positive_tabindex_sorts_first_ascending_then_document_order() {
921
        // Document order: n3 (tabindex=2), n5 (auto), n7 (tabindex=1), n9 (auto)
922
1
        let order = order_tab_entries(
923
1
            vec![(2, nid(0, 3)), (1, nid(0, 7))],
924
1
            vec![nid(0, 5), nid(0, 9)],
925
        );
926
1
        assert_eq!(order, vec![nid(0, 7), nid(0, 3), nid(0, 5), nid(0, 9)]);
927
1
    }
928

            
929
    #[test]
930
1
    fn equal_positive_tabindex_keeps_document_order() {
931
1
        let order = order_tab_entries(vec![(1, nid(0, 2)), (1, nid(0, 8))], vec![]);
932
1
        assert_eq!(order, vec![nid(0, 2), nid(0, 8)]);
933
1
    }
934

            
935
    #[test]
936
1
    fn next_wraps_and_previous_wraps() {
937
1
        let order = vec![nid(0, 1), nid(0, 4), nid(0, 6)];
938
1
        assert_eq!(
939
1
            next_in_tab_order(&order, Some(nid(0, 6)), true),
940
1
            Some(nid(0, 1))
941
        );
942
1
        assert_eq!(
943
1
            next_in_tab_order(&order, Some(nid(0, 1)), false),
944
1
            Some(nid(0, 6))
945
        );
946
1
        assert_eq!(
947
1
            next_in_tab_order(&order, Some(nid(0, 4)), true),
948
1
            Some(nid(0, 6))
949
        );
950
1
    }
951

            
952
    #[test]
953
1
    fn no_focus_starts_at_ends() {
954
1
        let order = vec![nid(0, 1), nid(0, 4)];
955
1
        assert_eq!(next_in_tab_order(&order, None, true), Some(nid(0, 1)));
956
1
        assert_eq!(next_in_tab_order(&order, None, false), Some(nid(0, 4)));
957
1
    }
958

            
959
    #[test]
960
1
    fn non_tab_stop_focus_reenters_in_document_order() {
961
        // Focus sits on a tabindex=-1 node (0,5): Tab goes to the next tab
962
        // stop in document order (0,6); Shift+Tab to the previous one (0,4).
963
1
        let order = vec![nid(0, 1), nid(0, 4), nid(0, 6)];
964
1
        assert_eq!(
965
1
            next_in_tab_order(&order, Some(nid(0, 5)), true),
966
1
            Some(nid(0, 6))
967
        );
968
1
        assert_eq!(
969
1
            next_in_tab_order(&order, Some(nid(0, 5)), false),
970
1
            Some(nid(0, 4))
971
        );
972
        // Past the last stop: wraps to first / last respectively.
973
1
        assert_eq!(
974
1
            next_in_tab_order(&order, Some(nid(0, 9)), true),
975
1
            Some(nid(0, 1))
976
        );
977
1
        assert_eq!(
978
1
            next_in_tab_order(&order, Some(nid(0, 0)), false),
979
1
            Some(nid(0, 6))
980
        );
981
1
    }
982

            
983
    #[test]
984
1
    fn empty_order_yields_none() {
985
1
        assert_eq!(next_in_tab_order(&[], Some(nid(0, 1)), true), None);
986
1
        assert_eq!(next_in_tab_order(&[], None, false), None);
987
1
    }
988
}
989

            
990
#[cfg(test)]
991
mod autotest_generated {
992
    use std::collections::HashMap;
993

            
994
    use azul_core::{
995
        dom::{Dom, NodeType, TabIndex},
996
        geom::LogicalRect,
997
        styled_dom::StyledDom,
998
    };
999
    use azul_css::css::{CssPath, CssPathSelector};
    use super::*;
    use crate::{
        managers::{NodeIdMap, NodeIdRemap},
        solver3::{display_list::DisplayList, layout_tree::LayoutTree},
    };
    // ------------------------------------------------------------------
    // Fixtures
    // ------------------------------------------------------------------
    fn dom(inner: usize) -> DomId {
        DomId { inner }
    }
    fn nid(dom_idx: usize, node: usize) -> DomNodeId {
        FocusSearchContext::make_dom_node_id(dom(dom_idx), NodeId::new(node))
    }
    /// A `DomNodeId` whose node slot is the "no node" sentinel (`inner == 0`).
    fn null_nid(dom_idx: usize) -> DomNodeId {
        DomNodeId {
            dom: dom(dom_idx),
            node: NodeHierarchyItemId::from_crate_internal(None),
        }
    }
    /// `DomLayoutResult` with an empty layout tree — every function under test
    /// here reads only `styled_dom`, so no real layout (and no font) is needed.
    fn layout_result(styled_dom: StyledDom) -> DomLayoutResult {
        DomLayoutResult {
            styled_dom,
            layout_tree: LayoutTree {
                nodes: Vec::new(),
                warm: Vec::new(),
                cold: Vec::new(),
                root: 0,
                dom_to_layout: BTreeMap::new(),
                children_arena: Vec::new(),
                children_offsets: Vec::new(),
                subtree_needs_intrinsic: Vec::new(),
            },
            calculated_positions: Vec::new(),
            viewport: LogicalRect::zero(),
            display_list: std::sync::Arc::new(DisplayList::default()),
            scroll_ids: HashMap::new(),
            scroll_id_to_node_id: HashMap::new(),
        }
    }
    /// A host display list that mounts `child` through a `VirtualView` item —
    /// the only host→child link `resolve_focus_target` can read.
    fn virtual_view_display_list(child: DomId) -> DisplayList {
        use azul_core::geom::{LogicalPosition, LogicalSize};
        use crate::solver3::display_list::{DisplayListItem, WindowLogicalRect};
        let bounds =
            WindowLogicalRect::new(LogicalPosition::zero(), LogicalSize::new(100.0, 100.0));
        let mut dl = DisplayList::default();
        dl.items.push(DisplayListItem::VirtualView {
            child_dom_id: child,
            bounds,
            clip_rect: bounds,
            content_offset: LogicalPosition::zero(),
        });
        dl
    }
    fn window(entries: Vec<(DomId, StyledDom)>) -> BTreeMap<DomId, DomLayoutResult> {
        entries
            .into_iter()
            .map(|(id, sd)| (id, layout_result(sd)))
            .collect()
    }
    /// Flat (pre-order) indices of [`tab_fixture`]:
    ///
    /// | idx | node                    | focusable | tab bucket        |
    /// |-----|-------------------------|-----------|-------------------|
    /// | 0   | body                    | no        | —                 |
    /// | 1   | div (plain)             | no        | —                 |
    /// | 2   | button                  | yes       | auto              |
    /// | 3   | div `tabindex=2`        | yes       | positive (n=2)    |
    /// | 4   | div `tabindex=-1`       | yes       | EXCLUDED          |
    /// | 5   | div `tabindex=1`        | yes       | positive (n=1)    |
    /// | 6   | div `tabindex=0`        | yes       | auto              |
    /// | 7   | textarea                | yes       | auto              |
    ///
    /// => tab order `[5, 3, 2, 6, 7]`.
    fn tab_fixture() -> StyledDom {
        StyledDom::create_from_dom(
            Dom::create_body()
                .with_child(Dom::create_div())
                .with_child(Dom::create_node(NodeType::Button))
                .with_child(Dom::create_div().with_tab_index(TabIndex::OverrideInParent(2)))
                .with_child(Dom::create_div().with_tab_index(TabIndex::NoKeyboardFocus))
                .with_child(Dom::create_div().with_tab_index(TabIndex::OverrideInParent(1)))
                .with_child(Dom::create_div().with_tab_index(TabIndex::OverrideInParent(0)))
                .with_child(Dom::create_node(NodeType::TextArea)),
        )
    }
    /// A `<body>` with two buttons, then a contained panel holding two more.
    ///
    /// Flat pre-order indices: 0 body, 1 button, 2 button, 3 panel (the
    /// container), 4 button, 5 button.
    fn contain_fixture(contained: bool) -> StyledDom {
        use azul_css::{
            css::CssPropertyValue,
            props::{property::CssProperty, style::spatial_nav::StyleSpatialNavigationContain},
        };
        let mut panel = azul_core::dom::NodeData::create_div();
        if contained {
            panel.upsert_inline_css_property(CssProperty::SpatialNavigationContain(
                CssPropertyValue::Exact(StyleSpatialNavigationContain::Contain),
            ));
        }
        StyledDom::create_from_dom(
            Dom::create_body()
                .with_child(Dom::create_node(NodeType::Button))
                .with_child(Dom::create_node(NodeType::Button))
                .with_child(
                    Dom::create_from_data(panel)
                        .with_child(Dom::create_node(NodeType::Button))
                        .with_child(Dom::create_node(NodeType::Button)),
                ),
        )
    }
    /// `contain` marks the panel and nothing else, and it is found from a
    /// node INSIDE it - which is the lookup the resolver actually makes.
    #[test]
    fn contain_names_the_panel_and_only_when_declared() {
        let contained = window(vec![(dom(0), contain_fixture(true))]);
        let panel = nid(0, 3);
        let inside = nid(0, 4);
        assert_eq!(
            spatial_navigation_container(&contained, inside),
            Some(panel),
            "a node inside the panel must resolve to the panel",
        );
        // Self-inclusive: the panel is its own container.
        assert_eq!(spatial_navigation_container(&contained, panel), Some(panel));
        // A sibling OUTSIDE the panel is in no container.
        assert_eq!(spatial_navigation_container(&contained, nid(0, 1)), None);
        // Without the declaration a PLAIN div is still no container: `auto`
        // makes a container of a scroll container and of nothing else.
        let plain = window(vec![(dom(0), contain_fixture(false))]);
        assert_eq!(spatial_navigation_container(&plain, inside), None);
    }
    /// [`contain_fixture`]'s shape with `overflow-y` on the panel instead of
    /// `contain`, so the panel is a container under `auto` only if it is a
    /// scroll container.
    fn scroll_fixture(overflow: azul_css::props::layout::overflow::LayoutOverflow) -> StyledDom {
        use azul_css::{css::CssPropertyValue, props::property::CssProperty};
        let mut panel = azul_core::dom::NodeData::create_div();
        panel.upsert_inline_css_property(CssProperty::OverflowY(CssPropertyValue::Exact(overflow)));
        StyledDom::create_from_dom(
            Dom::create_body()
                .with_child(Dom::create_node(NodeType::Button))
                .with_child(Dom::create_node(NodeType::Button))
                .with_child(
                    Dom::create_from_data(panel)
                        .with_child(Dom::create_node(NodeType::Button))
                        .with_child(Dom::create_node(NodeType::Button)),
                ),
        )
    }
    /// `auto` (the initial value) makes a container of a SCROLL CONTAINER -
    /// `css-nav-1`, per the user's ruling (9a-i-b-i) - and `visible` does not.
    #[test]
    fn auto_makes_a_container_of_a_scroll_container_only() {
        use azul_css::props::layout::overflow::LayoutOverflow;
        let panel = nid(0, 3);
        let inside = nid(0, 4);
        for scrolling in [
            LayoutOverflow::Auto,
            LayoutOverflow::Scroll,
            LayoutOverflow::Hidden,
        ] {
            let w = window(vec![(dom(0), scroll_fixture(scrolling))]);
            assert_eq!(
                spatial_navigation_container(&w, inside),
                Some(panel),
                "overflow: {scrolling:?} is a scroll container, so a container under auto"
            );
        }
        let w = window(vec![(dom(0), scroll_fixture(LayoutOverflow::Visible))]);
        assert_eq!(spatial_navigation_container(&w, inside), None);
    }
    /// The CHAIN is innermost-first and lists every container on the way up:
    /// body > `contain` panel > scrolling inner box > button.
    ///
    /// Flat pre-order indices: 0 body, 1 outer (contain), 2 inner (overflow),
    /// 3 button.
    #[test]
    fn the_container_chain_runs_innermost_first_to_the_outermost() {
        use azul_css::{
            css::CssPropertyValue,
            props::{
                layout::overflow::LayoutOverflow, property::CssProperty,
                style::spatial_nav::StyleSpatialNavigationContain,
            },
        };
        let mut outer = azul_core::dom::NodeData::create_div();
        outer.upsert_inline_css_property(CssProperty::SpatialNavigationContain(
            CssPropertyValue::Exact(StyleSpatialNavigationContain::Contain),
        ));
        let mut inner = azul_core::dom::NodeData::create_div();
        inner.upsert_inline_css_property(CssProperty::OverflowY(CssPropertyValue::Exact(
            LayoutOverflow::Auto,
        )));
        let sd = StyledDom::create_from_dom(Dom::create_body().with_child(
            Dom::create_from_data(outer).with_child(
                Dom::create_from_data(inner).with_child(Dom::create_node(NodeType::Button)),
            ),
        ));
        let w = window(vec![(dom(0), sd)]);
        assert_eq!(
            spatial_navigation_containers(&w, nid(0, 3)),
            vec![nid(0, 2), nid(0, 1)],
            "innermost (the scroll box) first, then the contain panel; the body is implicit"
        );
        assert_eq!(spatial_navigation_containers(&w, nid(0, 0)), Vec::new());
    }
    /// Containment is a SUBTREE test, not a "same parent" test, and it must
    /// never say yes across DOMs.
    #[test]
    fn is_within_covers_self_descendants_and_rejects_other_trees() {
        let w = window(vec![
            (dom(0), contain_fixture(true)),
            (dom(1), contain_fixture(true)),
        ]);
        let panel = nid(0, 3);
        assert!(is_within(&w, panel, panel), "a container contains itself");
        assert!(is_within(&w, nid(0, 4), panel));
        assert!(is_within(&w, nid(0, 5), panel));
        assert!(!is_within(&w, nid(0, 1), panel), "a sibling is not inside");
        assert!(
            !is_within(&w, nid(0, 0), panel),
            "an ancestor is not inside"
        );
        // Same index, different DOM: a VirtualView page is a separate tree and
        // treating it as contained would let the filter admit everything.
        assert!(!is_within(&w, nid(1, 4), panel));
    }
    /// The pool an arrow searches narrows to the container, and WIDENS AGAIN
    /// when nothing inside answers - the spec's move-to-the-parent-container
    /// step. Without the widening, an arrow at the edge of a panel would die
    /// there instead of escaping.
    #[test]
    fn a_contained_arrow_prefers_the_panel_but_can_still_escape() {
        let w = window(vec![(dom(0), contain_fixture(true))]);
        let inside = nid(0, 4);
        let resolved = resolve_focus_target(
            &FocusTarget::Directional(azul_core::callbacks::FocusDirection::Down),
            &w,
            Some(inside),
            &BTreeSet::new(),
        );
        // This fixture has no laid-out boxes, so `next_in_direction` falls
        // back to "the first candidate in the pool" - which is exactly what
        // makes the POOL observable here.
        let Ok(FocusResolution::Resolved(target)) = resolved else {
            panic!("expected a resolution, got {resolved:?}");
        };
        assert!(
            is_within(&w, target, nid(0, 3)),
            "a contained search must land inside the panel, got {target:?}",
        );
        // From OUTSIDE the panel there is no container, so the whole document
        // is in scope and the first tab stop wins.
        let outside = nid(0, 1);
        let resolved = resolve_focus_target(
            &FocusTarget::Directional(azul_core::callbacks::FocusDirection::Down),
            &w,
            Some(outside),
            &BTreeSet::new(),
        );
        let Ok(FocusResolution::Resolved(target)) = resolved else {
            panic!("expected a resolution, got {resolved:?}");
        };
        assert!(
            !is_within(&w, target, nid(0, 3)) || target == nid(0, 3),
            "an uncontained search must not be confined to the panel, got {target:?}",
        );
    }
    fn tab_order_of(fixture: StyledDom) -> Vec<DomNodeId> {
        collect_tab_order(&window(vec![(dom(0), fixture)]), &BTreeSet::new())
    }
    fn class_path(class: &str) -> CssPath {
        CssPath {
            selectors: vec![CssPathSelector::Class(class.to_string().into())].into(),
        }
    }
    // ==================================================================
    // FocusManager — constructor / getters / predicates
    // ==================================================================
    #[test]
    fn focus_manager_new_matches_default_and_is_fully_empty() {
        let fm = FocusManager::new();
        assert_eq!(fm, FocusManager::default());
        assert_eq!(fm.get_focused_node(), None);
        assert!(!fm.needs_cursor_initialization());
        assert_eq!(fm.pending_focus_request, None);
        assert_eq!(fm.pending_contenteditable_focus, None);
        // A default instance must answer every query without panicking.
        assert!(!fm.has_focus(&nid(0, 0)));
        assert!(!fm.has_focus(&null_nid(0)));
    }
    #[test]
    fn seat_focus_is_independent_of_the_primary() {
        // 9b-ii-a-i-d: seat 0 IS `focused_node`; seat 7 keeps its own entry.
        let mut fm = FocusManager::new();
        fm.set_focused_node_for(azul_core::window::PRIMARY_POINTER_SEAT, Some(nid(0, 1)));
        fm.set_focused_node_for(7, Some(nid(0, 2)));
        assert_eq!(fm.get_focused_node(), Some(&nid(0, 1)));
        assert_eq!(fm.focused_node_for(0), Some(nid(0, 1)));
        assert_eq!(fm.focused_node_for(7), Some(nid(0, 2)));
        assert_eq!(
            fm.focused_node_for(8),
            None,
            "an unknown seat focuses nothing"
        );
        assert!(fm.has_focus_for(7, &nid(0, 2)));
        assert!(!fm.has_focus_for(7, &nid(0, 1)));
        assert_eq!(fm.seats_focusing(&nid(0, 2)), vec![7]);
        // Clearing the seat leaves the primary alone, and the other way round.
        fm.set_focused_node_for(7, None);
        assert_eq!(fm.focused_node_for(7), None);
        assert_eq!(fm.focused_node_for(0), Some(nid(0, 1)));
        fm.clear_focus();
        fm.set_focused_node_for(7, Some(nid(0, 3)));
        assert_eq!(fm.focused_node_for(0), None);
        assert_eq!(fm.focused_node_for(7), Some(nid(0, 3)));
    }
    #[test]
    fn seat_focus_follows_a_remap_and_clears_on_an_unmounted_node() {
        let mut fm = FocusManager::new();
        fm.set_focused_node_for(7, Some(nid(0, 5)));
        fm.set_focused_node_for(9, Some(nid(0, 6)));
        fm.remap_node_ids(
            dom(0),
            &NodeIdMap::from_pairs([(NodeId::new(5), NodeId::new(2))]),
        );
        assert_eq!(fm.focused_node_for(7), Some(nid(0, 2)), "followed the node");
        assert_eq!(fm.focused_node_for(9), None, "unmounted: cleared, not kept");
    }
    #[test]
    fn focus_manager_set_get_clear_focus_roundtrip() {
        let mut fm = FocusManager::new();
        fm.set_focused_node(Some(nid(0, 3)));
        assert_eq!(fm.get_focused_node(), Some(&nid(0, 3)));
        assert!(fm.has_focus(&nid(0, 3)));
        // Explicitly setting `None` is equivalent to clearing.
        fm.set_focused_node(None);
        assert_eq!(fm.get_focused_node(), None);
        fm.set_focused_node(Some(nid(0, 3)));
        fm.clear_focus();
        assert_eq!(fm.get_focused_node(), None);
        assert!(!fm.has_focus(&nid(0, 3)));
        // Clearing twice is idempotent, not a panic.
        fm.clear_focus();
        assert_eq!(fm.get_focused_node(), None);
    }
    #[test]
    fn focus_manager_has_focus_discriminates_both_dom_and_node() {
        let mut fm = FocusManager::new();
        fm.set_focused_node(Some(nid(1, 4)));
        assert!(fm.has_focus(&nid(1, 4)));
        // Same node index, different DOM — must NOT be treated as focused.
        assert!(!fm.has_focus(&nid(0, 4)));
        assert!(!fm.has_focus(&nid(2, 4)));
        // Same DOM, different node index.
        assert!(!fm.has_focus(&nid(1, 3)));
        assert!(!fm.has_focus(&nid(1, 5)));
        // The "no node" sentinel must not alias node 0.
        assert!(!fm.has_focus(&null_nid(1)));
    }
    #[test]
    fn focus_manager_has_focus_on_null_node_sentinel_is_exact() {
        // Focusing the sentinel itself: it matches only the sentinel, and in
        // particular is NOT confused with real node index 0 (whose encoded
        // `NodeHierarchyItemId` is 1, not 0).
        let mut fm = FocusManager::new();
        fm.set_focused_node(Some(null_nid(0)));
        assert!(fm.has_focus(&null_nid(0)));
        assert!(!fm.has_focus(&nid(0, 0)));
        assert!(!fm.has_focus(&null_nid(1)));
    }
    #[test]
    fn focus_manager_focus_survives_extreme_node_index() {
        // `NodeHierarchyItemId` encodes `Some(n)` as `n + 1`, so `usize::MAX`
        // itself would overflow the encoding. `usize::MAX - 1` is the largest
        // representable node and must round-trip cleanly.
        let extreme = nid(usize::MAX, usize::MAX - 1);
        let mut fm = FocusManager::new();
        fm.set_focused_node(Some(extreme));
        assert!(fm.has_focus(&extreme));
        assert_eq!(
            fm.get_focused_node()
                .and_then(|n| n.node.into_crate_internal())
                .map(|n| n.index()),
            Some(usize::MAX - 1)
        );
    }
    // ==================================================================
    // FocusManager — pending focus request (one-shot)
    // ==================================================================
    #[test]
    fn focus_manager_take_focus_request_is_one_shot() {
        let mut fm = FocusManager::new();
        // Taking from a fresh manager yields None rather than panicking.
        assert_eq!(fm.take_focus_request(), None);
        fm.request_focus_change(FocusTarget::Next);
        assert_eq!(fm.take_focus_request(), Some(FocusTarget::Next));
        // Consumed — a second take must not replay the request.
        assert_eq!(fm.take_focus_request(), None);
        assert_eq!(fm.take_focus_request(), None);
    }
    #[test]
    fn focus_manager_request_focus_change_overwrites_pending_request() {
        // The field holds a single slot: a second request silently REPLACES the
        // first (requests are not queued). Pin that, so a change to queueing
        // semantics is a deliberate, visible break.
        let mut fm = FocusManager::new();
        fm.request_focus_change(FocusTarget::First);
        fm.request_focus_change(FocusTarget::Last);
        fm.request_focus_change(FocusTarget::NoFocus);
        assert_eq!(fm.take_focus_request(), Some(FocusTarget::NoFocus));
        assert_eq!(fm.take_focus_request(), None);
    }
    #[test]
    fn focus_manager_request_focus_change_accepts_every_variant() {
        let path = FocusTarget::Path(FocusTargetPath {
            dom: dom(usize::MAX),
            css_path: class_path("nonexistent"),
        });
        let targets = vec![
            FocusTarget::Id(nid(0, 0)),
            FocusTarget::Id(null_nid(usize::MAX)),
            path,
            FocusTarget::Previous,
            FocusTarget::Next,
            FocusTarget::First,
            FocusTarget::Last,
            FocusTarget::NoFocus,
        ];
        for t in targets {
            let mut fm = FocusManager::new();
            fm.request_focus_change(t.clone());
            assert_eq!(fm.take_focus_request(), Some(t));
        }
    }
    // ==================================================================
    // FocusManager — W3C "flag and defer" contenteditable state
    // ==================================================================
    #[test]
    fn focus_manager_pending_contenteditable_set_then_take_is_one_shot() {
        let mut fm = FocusManager::new();
        assert!(!fm.needs_cursor_initialization());
        assert_eq!(fm.take_pending_contenteditable_focus(), None);
        fm.set_pending_contenteditable_focus(dom(2), NodeId::new(7), NodeId::new(9));
        assert!(fm.needs_cursor_initialization());
        assert_eq!(
            fm.take_pending_contenteditable_focus(),
            Some(PendingContentEditableFocus {
                dom_id: dom(2),
                container_node_id: NodeId::new(7),
                text_node_id: NodeId::new(9),
            })
        );
        // Flag consumed; a second take must not replay the pending focus.
        assert!(!fm.needs_cursor_initialization());
        assert_eq!(fm.take_pending_contenteditable_focus(), None);
    }
    #[test]
    fn focus_manager_set_pending_contenteditable_overwrites_and_accepts_extremes() {
        let mut fm = FocusManager::new();
        fm.set_pending_contenteditable_focus(dom(0), NodeId::new(1), NodeId::new(2));
        // Extreme ids (and container == text, i.e. a degenerate self-reference)
        // must be stored verbatim without panicking.
        fm.set_pending_contenteditable_focus(
            dom(usize::MAX),
            NodeId::new(usize::MAX),
            NodeId::new(usize::MAX),
        );
        assert_eq!(
            fm.take_pending_contenteditable_focus(),
            Some(PendingContentEditableFocus {
                dom_id: dom(usize::MAX),
                container_node_id: NodeId::new(usize::MAX),
                text_node_id: NodeId::new(usize::MAX),
            })
        );
    }
    #[test]
    fn focus_manager_clear_pending_contenteditable_clears_flag_and_value() {
        let mut fm = FocusManager::new();
        fm.set_pending_contenteditable_focus(dom(0), NodeId::new(1), NodeId::new(2));
        fm.clear_pending_contenteditable_focus();
        assert!(!fm.needs_cursor_initialization());
        assert_eq!(fm.pending_contenteditable_focus, None);
        assert_eq!(fm.take_pending_contenteditable_focus(), None);
        // Clearing an already-clear manager is idempotent.
        fm.clear_pending_contenteditable_focus();
        assert!(!fm.needs_cursor_initialization());
    }
    #[test]
    fn focus_manager_take_pending_without_flag_strands_the_value() {
        // Both fields are `pub`, so the flag and the value can be desynced by a
        // direct field write. `take_pending_contenteditable_focus` gates purely
        // on the FLAG, so a value written without the flag is never handed out
        // and is left stranded in the manager. Pin the (safe, non-panicking)
        // behaviour: no cursor is initialised, and the stale value survives.
        let mut fm = FocusManager::new();
        fm.pending_contenteditable_focus = Some(PendingContentEditableFocus {
            dom_id: dom(0),
            container_node_id: NodeId::new(1),
            text_node_id: NodeId::new(2),
        });
        assert!(!fm.needs_cursor_initialization());
        assert_eq!(fm.take_pending_contenteditable_focus(), None);
        assert!(fm.pending_contenteditable_focus.is_some());
    }
    #[test]
    fn focus_manager_flag_without_value_take_returns_none_and_clears_flag() {
        // The mirror-image desync: flag set, value absent. `take` must report
        // "nothing to do" AND drop the flag, so the caller cannot spin on a
        // permanently-pending initialisation.
        let mut fm = FocusManager::new();
        fm.cursor_needs_initialization = true;
        assert!(fm.needs_cursor_initialization());
        assert_eq!(fm.take_pending_contenteditable_focus(), None);
        assert!(!fm.needs_cursor_initialization());
    }
    #[test]
    fn focus_manager_clear_focus_does_not_clear_pending_cursor_state() {
        // `clear_focus` touches ONLY `focused_node`: the deferred contenteditable
        // cursor request deliberately survives it (callers must call
        // `clear_pending_contenteditable_focus` themselves). Pin this, since a
        // silent change would either leak a cursor into an unfocused node or
        // drop a legitimate deferred cursor.
        let mut fm = FocusManager::new();
        fm.set_focused_node(Some(nid(0, 4)));
        fm.set_pending_contenteditable_focus(dom(0), NodeId::new(4), NodeId::new(5));
        fm.clear_focus();
        assert_eq!(fm.get_focused_node(), None);
        assert!(fm.needs_cursor_initialization());
        assert!(fm.pending_contenteditable_focus.is_some());
    }
    // ==================================================================
    // order_tab_entries / doc_order_key
    // ==================================================================
    #[test]
    fn order_tab_entries_empty_inputs_yield_empty() {
        assert_eq!(order_tab_entries(Vec::new(), Vec::new()), Vec::new());
    }
    #[test]
    fn order_tab_entries_u32_max_sorts_after_smaller_positives() {
        // No overflow / wrap: u32::MAX is just a very large key and must land
        // last among the positives, never first.
        let order = order_tab_entries(
            vec![
                (u32::MAX, nid(0, 1)),
                (1, nid(0, 2)),
                (u32::MAX - 1, nid(0, 3)),
            ],
            vec![nid(0, 4)],
        );
        assert_eq!(
            order,
            vec![nid(0, 2), nid(0, 3), nid(0, 1), nid(0, 4)],
            "u32::MAX must sort last among positives, and all positives before auto"
        );
    }
    #[test]
    fn order_tab_entries_positive_always_precedes_auto() {
        // Even the largest possible positive tabindex outranks every auto entry.
        let order = order_tab_entries(vec![(u32::MAX, nid(9, 99))], vec![nid(0, 0), nid(0, 1)]);
        assert_eq!(order[0], nid(9, 99));
        assert_eq!(order.len(), 3);
    }
    #[test]
    fn order_tab_entries_does_not_deduplicate() {
        // Duplicates are preserved verbatim (the function is a pure merge, not a
        // set builder) — a duplicated entry must not silently vanish.
        let order = order_tab_entries(
            vec![(1, nid(0, 1)), (1, nid(0, 1))],
            vec![nid(0, 2), nid(0, 2)],
        );
        assert_eq!(order, vec![nid(0, 1), nid(0, 1), nid(0, 2), nid(0, 2)]);
    }
    #[test]
    fn doc_order_key_null_node_collides_with_node_index_zero() {
        // `doc_order_key` maps the "no node" sentinel to arena index 0, so it is
        // indistinguishable from real node 0 within the same DOM. Pin the
        // collision: `next_in_tab_order`'s re-entry search relies on this key,
        // and a focus sitting on the sentinel therefore re-enters as if it sat
        // on node 0.
        assert_eq!(doc_order_key(&null_nid(0)), (0, 0));
        assert_eq!(doc_order_key(&nid(0, 0)), (0, 0));
        assert_eq!(doc_order_key(&null_nid(0)), doc_order_key(&nid(0, 0)));
    }
    #[test]
    fn doc_order_key_is_dom_major_then_arena_index() {
        assert_eq!(doc_order_key(&nid(3, 7)), (3, 7));
        // DOM index dominates: a huge node index in DOM 0 still precedes node 0
        // of DOM 1.
        assert!(doc_order_key(&nid(0, usize::MAX - 1)) < doc_order_key(&nid(1, 0)));
        assert_eq!(
            doc_order_key(&nid(usize::MAX, usize::MAX - 1)),
            (usize::MAX, usize::MAX - 1)
        );
    }
    // ==================================================================
    // next_in_tab_order
    // ==================================================================
    #[test]
    fn next_in_tab_order_single_entry_wraps_onto_itself() {
        // `(0 + 1) % 1 == 0` — must terminate on itself, not loop or panic.
        let order = vec![nid(0, 1)];
        assert_eq!(
            next_in_tab_order(&order, Some(nid(0, 1)), true),
            Some(nid(0, 1))
        );
        assert_eq!(
            next_in_tab_order(&order, Some(nid(0, 1)), false),
            Some(nid(0, 1))
        );
    }
    #[test]
    fn next_in_tab_order_duplicate_entries_resolve_to_first_position() {
        // `position()` finds the FIRST occurrence, so a duplicated tab stop makes
        // the trailing copy unreachable by stepping. Pin it (a dedup in
        // `collect_tab_order` would change this).
        let order = vec![nid(0, 1), nid(0, 2), nid(0, 1)];
        assert_eq!(
            next_in_tab_order(&order, Some(nid(0, 1)), true),
            Some(nid(0, 2))
        );
        // Backward from index 0 wraps to the last element.
        assert_eq!(
            next_in_tab_order(&order, Some(nid(0, 1)), false),
            Some(nid(0, 1))
        );
    }
    #[test]
    fn next_in_tab_order_unknown_current_uses_cross_dom_document_order() {
        // Current node lives in DOM 1; the tab order is split across DOM 0 and 2.
        let order = vec![nid(0, 5), nid(2, 1)];
        assert_eq!(
            next_in_tab_order(&order, Some(nid(1, 0)), true),
            Some(nid(2, 1))
        );
        assert_eq!(
            next_in_tab_order(&order, Some(nid(1, 9)), false),
            Some(nid(0, 5))
        );
    }
    #[test]
    fn next_in_tab_order_unknown_current_past_both_ends_wraps() {
        let order = vec![nid(1, 2), nid(1, 4)];
        // Nothing greater -> wrap to first.
        assert_eq!(
            next_in_tab_order(&order, Some(nid(9, 9)), true),
            Some(nid(1, 2))
        );
        // Nothing smaller -> wrap to last.
        assert_eq!(
            next_in_tab_order(&order, Some(nid(0, 0)), false),
            Some(nid(1, 4))
        );
    }
    #[test]
    fn next_in_tab_order_null_current_node_is_deterministic() {
        // The sentinel keys as (dom, 0); it is not in the order, so the re-entry
        // path runs. It must produce a stable answer, not panic.
        let order = vec![nid(0, 1), nid(0, 3)];
        assert_eq!(
            next_in_tab_order(&order, Some(null_nid(0)), true),
            Some(nid(0, 1))
        );
        assert_eq!(
            next_in_tab_order(&order, Some(null_nid(0)), false),
            Some(nid(0, 3))
        );
    }
    #[test]
    fn next_in_tab_order_empty_order_is_none_for_every_input() {
        assert_eq!(next_in_tab_order(&[], None, true), None);
        assert_eq!(next_in_tab_order(&[], None, false), None);
        assert_eq!(next_in_tab_order(&[], Some(null_nid(0)), true), None);
        assert_eq!(
            next_in_tab_order(&[], Some(nid(usize::MAX, usize::MAX - 1)), false),
            None
        );
    }
    // ==================================================================
    // collect_tab_order
    // ==================================================================
    #[test]
    fn collect_tab_order_empty_window_is_empty() {
        assert_eq!(
            collect_tab_order(&BTreeMap::new(), &BTreeSet::new()),
            Vec::new()
        );
    }
    #[test]
    fn collect_tab_order_dom_without_focusables_is_empty() {
        let sd = StyledDom::create_from_dom(
            Dom::create_body()
                .with_child(Dom::create_div())
                .with_child(Dom::create_div()),
        );
        assert_eq!(tab_order_of(sd), Vec::new());
    }
    #[test]
    fn collect_tab_order_positives_first_then_document_order_minus_one_excluded() {
        // See `tab_fixture` doc comment for the expected layout.
        assert_eq!(
            tab_order_of(tab_fixture()),
            vec![nid(0, 5), nid(0, 3), nid(0, 2), nid(0, 6), nid(0, 7)],
            "tabindex=1 then tabindex=2, then auto nodes in document order"
        );
    }
    #[test]
    fn collect_tab_order_excludes_tabindex_minus_one_though_it_is_focusable() {
        // The tabindex=-1 node (index 4) is click/API focusable but must NEVER be
        // a tab stop.
        let order = tab_order_of(tab_fixture());
        assert!(
            !order.contains(&nid(0, 4)),
            "tabindex=-1 must not be a tab stop"
        );
        // ...and the plain, non-focusable div is absent too.
        assert!(!order.contains(&nid(0, 1)));
        // ...while the body itself is never a tab stop.
        assert!(!order.contains(&nid(0, 0)));
    }
    #[test]
    fn collect_tab_order_huge_tabindex_truncates_at_28_bits() {
        // `NodeFlags` packs the tabindex into 28 bits, so:
        //   * tabindex = u32::MAX  -> stored as 2^28-1  -> still POSITIVE
        //   * tabindex = 1 << 28   -> stored as 0       -> demoted to the AUTO bucket (0 is not >
        //     0)
        // The truncation is silent, so pin the observable ordering consequence.
        //
        // Document order: 1 = u32::MAX, 2 = 1<<28, 3 = tabindex 1, 4 = button.
        let sd = StyledDom::create_from_dom(
            Dom::create_body()
                .with_child(Dom::create_div().with_tab_index(TabIndex::OverrideInParent(u32::MAX)))
                .with_child(Dom::create_div().with_tab_index(TabIndex::OverrideInParent(1 << 28)))
                .with_child(Dom::create_div().with_tab_index(TabIndex::OverrideInParent(1)))
                .with_child(Dom::create_node(NodeType::Button)),
        );
        assert_eq!(
            tab_order_of(sd),
            vec![nid(0, 3), nid(0, 1), nid(0, 2), nid(0, 4)],
            "u32::MAX stays positive (sorts after tabindex=1); 1<<28 truncates to 0 and falls \
             back into the auto bucket behind every positive"
        );
    }
    /// A TRANSIENT POPUP's content DOM contributes NO tab stops to the
    /// parent window's order.
    ///
    /// The parent lays the popup's content out and keeps it in
    /// `layout_results`, so without an explicit scope the parent's Tab walked
    /// straight into the popup - and kept walking into it after the popup had
    /// CLOSED, which stranded the keyboard there: Tab appeared to stop
    /// working entirely (device report, 2026-09-01). Inside the popup's own
    /// window that same content is the ROOT dom and hosts no popups, so its
    /// scope is empty and it stays fully tabbable there.
    /// A `<transient-window>`'s SUBTREE holds no tab stops in the parent.
    ///
    /// The popup's controls live in the PARENT's DOM as children of the
    /// transient node - a ColorInput has ONE real stop (the swatch) and EIGHT
    /// under its transient node - and that copy is never rendered by the
    /// parent window. Tab landed on it anyway, and arrow keys then did
    /// nothing, because the focused node was the parent's dead copy rather
    /// than the live control the popup window shows (device report,
    /// 2026-09-01).
    #[test]
    fn collect_tab_order_skips_everything_under_a_transient_window() {
        use azul_core::dom::{Dom, NodeType, TabIndex};
        let stop = || {
            let mut d = Dom::create_div();
            d.set_tab_index(TabIndex::Auto);
            d
        };
        // body > [ real stop, transient-window > [ hidden stop, hidden stop ] ]
        let sd = StyledDom::create_from_dom(
            Dom::create_body().with_child(stop()).with_child(
                Dom::create_node(NodeType::TransientWindow(Default::default()))
                    .with_child(stop())
                    .with_child(stop()),
            ),
        );
        let order = collect_tab_order(&window(vec![(dom(0), sd)]), &BTreeSet::new());
        assert_eq!(
            order,
            vec![nid(0, 1)],
            "only the node OUTSIDE the transient subtree is a tab stop, got {order:?}",
        );
    }
    #[test]
    fn collect_tab_order_skips_doms_outside_this_windows_focus_scope() {
        let results = window(vec![(dom(0), tab_fixture()), (dom(1), tab_fixture())]);
        let both = collect_tab_order(&results, &BTreeSet::new());
        assert!(
            both.iter().any(|n| n.dom == dom(1)),
            "premise: with an empty scope BOTH doms contribute stops",
        );
        // Dom 1 is a popup hosted by this window.
        let popup: BTreeSet<DomId> = [dom(1)].into_iter().collect();
        let parent_only = collect_tab_order(&results, &popup);
        assert!(
            parent_only.iter().all(|n| n.dom == dom(0)),
            "the popup's dom must contribute no tab stops to its parent: {parent_only:?}",
        );
        assert!(
            !parent_only.is_empty(),
            "and the parent's own stops must survive",
        );
    }
    #[test]
    fn collect_tab_order_tab_order_is_global_across_doms() {
        // A positive-tabindex node in DOM 1 must outrank an auto node in DOM 0:
        // the tab order is a single sequence over all DOMs, not per-DOM chunks.
        let order = collect_tab_order(
            &window(vec![(dom(0), tab_fixture()), (dom(1), tab_fixture())]),
            &BTreeSet::new(),
        );
        assert_eq!(
            order,
            vec![
                // positives, ascending; ties broken by DOM then document order
                nid(0, 5),
                nid(1, 5),
                nid(0, 3),
                nid(1, 3),
                // autos, in DOM order then document order
                nid(0, 2),
                nid(0, 6),
                nid(0, 7),
                nid(1, 2),
                nid(1, 6),
                nid(1, 7),
            ]
        );
    }
    // ==================================================================
    // FocusSearchContext
    // ==================================================================
    #[test]
    fn focus_search_context_get_layout_hit_and_miss() {
        let results = window(vec![(dom(0), tab_fixture())]);
        let ctx = FocusSearchContext::new(&results);
        // `DomLayoutResult` is not `PartialEq`, so compare on the error side only.
        assert!(ctx.get_layout(&dom(0)).is_ok());
        assert_eq!(
            ctx.get_layout(&dom(1)).err(),
            Some(UpdateFocusWarning::FocusInvalidDomId(dom(1)))
        );
        assert_eq!(
            ctx.get_layout(&dom(usize::MAX)).err(),
            Some(UpdateFocusWarning::FocusInvalidDomId(dom(usize::MAX)))
        );
    }
    #[test]
    fn focus_search_context_new_on_empty_map_never_resolves() {
        let empty = BTreeMap::new();
        let ctx = FocusSearchContext::new(&empty);
        assert_eq!(
            ctx.get_layout(&dom(0)).err(),
            Some(UpdateFocusWarning::FocusInvalidDomId(dom(0)))
        );
    }
    #[test]
    fn make_dom_node_id_round_trips_including_boundary_index() {
        // encode == decode for 0, a mid value, and the largest encodable index
        // (`usize::MAX` itself would overflow `NodeHierarchyItemId`'s n+1 encoding).
        for idx in [0usize, 1, 42, usize::MAX - 1] {
            let d = FocusSearchContext::make_dom_node_id(dom(7), NodeId::new(idx));
            assert_eq!(d.dom, dom(7));
            assert_eq!(d.node.into_crate_internal(), Some(NodeId::new(idx)));
            assert_eq!(doc_order_key(&d), (7, idx));
        }
    }
    // ==================================================================
    // find_first_matching_focusable_node
    // ==================================================================
    #[test]
    fn find_first_matching_skips_matching_but_unfocusable_nodes() {
        // Node 1 matches `.target` but is NOT focusable; node 2 matches AND is
        // focusable. The first *focusable* match must win.
        let sd = StyledDom::create_from_dom(
            Dom::create_body()
                .with_child(Dom::create_div().with_class("target".to_string().into()))
                .with_child(
                    Dom::create_div()
                        .with_class("target".to_string().into())
                        .with_tab_index(TabIndex::Auto),
                ),
        );
        let results = window(vec![(dom(0), sd)]);
        let layout = results.get(&dom(0)).unwrap();
        assert_eq!(
            find_first_matching_focusable_node(layout, &dom(0), &class_path("target")),
            Some(nid(0, 2))
        );
    }
    #[test]
    fn find_first_matching_empty_css_path_matches_nothing() {
        // A `CssPath` with zero selectors must not vacuously match every node.
        let results = window(vec![(dom(0), tab_fixture())]);
        let layout = results.get(&dom(0)).unwrap();
        let empty = CssPath {
            selectors: Vec::<CssPathSelector>::new().into(),
        };
        assert_eq!(
            find_first_matching_focusable_node(layout, &dom(0), &empty),
            None
        );
    }
    #[test]
    fn find_first_matching_unicode_class_matches_and_misses_cleanly() {
        // Non-ASCII / astral-plane class names must compare by exact string, with
        // no panic and no byte-index slicing surprises.
        let class = "クラス-día-🎯";
        let sd = StyledDom::create_from_dom(
            Dom::create_body().with_child(
                Dom::create_div()
                    .with_class(class.to_string().into())
                    .with_tab_index(TabIndex::Auto),
            ),
        );
        let results = window(vec![(dom(0), sd)]);
        let layout = results.get(&dom(0)).unwrap();
        assert_eq!(
            find_first_matching_focusable_node(layout, &dom(0), &class_path(class)),
            Some(nid(0, 1))
        );
        // A near-miss (same prefix, different suffix) must NOT match.
        assert_eq!(
            find_first_matching_focusable_node(layout, &dom(0), &class_path("クラス-día-🎲")),
            None
        );
        // A huge class name that cannot exist in the DOM also just misses.
        let huge = "x".repeat(10_000);
        assert_eq!(
            find_first_matching_focusable_node(layout, &dom(0), &class_path(&huge)),
            None
        );
    }
    // ==================================================================
    // resolve_focus_target
    // ==================================================================
    #[test]
    fn resolve_focus_target_empty_window_short_circuits_every_variant() {
        // The `layout_results.is_empty()` guard runs BEFORE any validation, so
        // even a structurally invalid target resolves to `Ok(FocusResolution::NotFound)` — never
        // Err, never a panic.
        let empty = BTreeMap::new();
        let targets = vec![
            FocusTarget::Id(nid(usize::MAX, 0)),
            FocusTarget::Id(null_nid(0)),
            FocusTarget::Path(FocusTargetPath {
                dom: dom(usize::MAX),
                css_path: class_path("nope"),
            }),
            FocusTarget::Previous,
            FocusTarget::Next,
            FocusTarget::First,
            FocusTarget::Last,
        ];
        for t in targets {
            assert_eq!(
                resolve_focus_target(&t, &empty, Some(nid(0, 1)), &BTreeSet::new()),
                Ok(FocusResolution::NotFound),
                "empty window must short-circuit {t:?}"
            );
        }
        // The explicit clear stays answerable — and distinguishable — even
        // with no layout at all.
        assert_eq!(
            resolve_focus_target(
                &FocusTarget::NoFocus,
                &empty,
                Some(nid(0, 1)),
                &BTreeSet::new()
            ),
            Ok(FocusResolution::ClearRequested),
        );
    }
    #[test]
    fn resolve_focus_target_id_rejects_unknown_dom() {
        let results = window(vec![(dom(0), tab_fixture())]);
        assert_eq!(
            resolve_focus_target(
                &FocusTarget::Id(nid(1, 2)),
                &results,
                None,
                &BTreeSet::new()
            ),
            Err(UpdateFocusWarning::FocusInvalidDomId(dom(1)))
        );
    }
    #[test]
    fn resolve_focus_target_id_rejects_out_of_range_node() {
        // The fixture has 8 nodes (0..=7); anything past the end must be a
        // `FocusInvalidNodeId` error, not a panic and not a silent focus.
        let results = window(vec![(dom(0), tab_fixture())]);
        for idx in [8usize, 9, 1_000_000, usize::MAX - 1] {
            let target = nid(0, idx);
            assert_eq!(
                resolve_focus_target(&FocusTarget::Id(target), &results, None, &BTreeSet::new()),
                Err(UpdateFocusWarning::FocusInvalidNodeId(target.node)),
                "node {idx} is out of range and must be rejected"
            );
        }
    }
    #[test]
    fn resolve_focus_target_id_rejects_null_node_sentinel() {
        let results = window(vec![(dom(0), tab_fixture())]);
        let target = null_nid(0);
        assert_eq!(
            resolve_focus_target(&FocusTarget::Id(target), &results, None, &BTreeSet::new()),
            Err(UpdateFocusWarning::FocusInvalidNodeId(target.node))
        );
    }
    #[test]
    fn resolve_focus_target_id_accepts_valid_but_unfocusable_node() {
        // `Id` checks only that the node EXISTS — programmatic focus deliberately
        // bypasses the focusability check (unlike `Path` and the tab order).
        // Node 0 is the body and node 4 is tabindex=-1: both resolve.
        let results = window(vec![(dom(0), tab_fixture())]);
        assert_eq!(
            resolve_focus_target(
                &FocusTarget::Id(nid(0, 0)),
                &results,
                None,
                &BTreeSet::new()
            ),
            Ok(FocusResolution::Resolved(nid(0, 0)))
        );
        assert_eq!(
            resolve_focus_target(
                &FocusTarget::Id(nid(0, 4)),
                &results,
                None,
                &BTreeSet::new()
            ),
            Ok(FocusResolution::Resolved(nid(0, 4)))
        );
    }
    #[test]
    fn resolve_focus_target_path_rejects_unknown_dom() {
        let results = window(vec![(dom(0), tab_fixture())]);
        let target = FocusTarget::Path(FocusTargetPath {
            dom: dom(3),
            css_path: class_path("target"),
        });
        assert_eq!(
            resolve_focus_target(&target, &results, None, &BTreeSet::new()),
            Err(UpdateFocusWarning::FocusInvalidDomId(dom(3)))
        );
    }
    #[test]
    fn resolve_focus_target_path_with_no_match_is_ok_none_not_err() {
        // NOTE: the doc comment on `find_first_matching_focusable_node` advertises
        // `Err(_)` for an unmatchable path, but the implementation returns
        // `Ok(FocusResolution::NotFound)`. Pin the IMPLEMENTED behaviour (a miss is not an error);
        // the doc comment is what is wrong here.
        let results = window(vec![(dom(0), tab_fixture())]);
        let target = FocusTarget::Path(FocusTargetPath {
            dom: dom(0),
            css_path: class_path("no-such-class"),
        });
        assert_eq!(
            resolve_focus_target(&target, &results, None, &BTreeSet::new()),
            Ok(FocusResolution::NotFound)
        );
    }
    /// A `VirtualView` mounts its DOM under its OWN DomId, so a selector the
    /// app resolves against the host dom must still find it — otherwise an app
    /// whose editable content lives in a VirtualView can never focus it by
    /// path, and the request lands as "clear focus".
    ///
    /// This is AzWriter's startup caret: `set_focus_to_path(ROOT, ".mw-doc")`,
    /// where `.mw-doc` is on the page content root inside the nested dom.
    #[test]
    fn resolve_focus_target_path_reaches_into_a_virtual_views_nested_dom() {
        let host = StyledDom::create_from_dom(Dom::create_body().with_child(Dom::create_div()));
        let mut page = Dom::create_div();
        page.set_contenteditable(true);
        let nested =
            StyledDom::create_from_dom(Dom::create_body().with_child(page.with_ids_and_classes(
                vec![azul_core::dom::IdOrClass::Class("mw-doc".into())].into(),
            )));
        let mut results = window(vec![(dom(0), host), (dom(1), nested)]);
        results.get_mut(&dom(0)).unwrap().display_list =
            std::sync::Arc::new(virtual_view_display_list(dom(1)));
        let target = FocusTarget::Path(FocusTargetPath {
            dom: dom(0),
            css_path: class_path("mw-doc"),
        });
        assert_eq!(
            resolve_focus_target(&target, &results, None, &BTreeSet::new()),
            Ok(FocusResolution::Resolved(nid(1, 1))),
            "the selector must resolve into the dom the VirtualView mounted; answering None here \
             is applied by every caller as 'clear focus', which is why the editor opened with no \
             caret"
        );
    }
    #[test]
    fn resolve_focus_target_path_still_prefers_the_host_dom_over_a_nested_one() {
        // Both doms carry `.target`; the host's match wins, so adding the
        // nested search cannot steal a focus that already resolved.
        let host = StyledDom::create_from_dom(
            Dom::create_body().with_child(
                Dom::create_div()
                    .with_tab_index(TabIndex::Auto)
                    .with_ids_and_classes(
                        vec![azul_core::dom::IdOrClass::Class("target".into())].into(),
                    ),
            ),
        );
        let nested = StyledDom::create_from_dom(
            Dom::create_body().with_child(
                Dom::create_div()
                    .with_tab_index(TabIndex::Auto)
                    .with_ids_and_classes(
                        vec![azul_core::dom::IdOrClass::Class("target".into())].into(),
                    ),
            ),
        );
        let mut results = window(vec![(dom(0), host), (dom(1), nested)]);
        results.get_mut(&dom(0)).unwrap().display_list =
            std::sync::Arc::new(virtual_view_display_list(dom(1)));
        let target = FocusTarget::Path(FocusTargetPath {
            dom: dom(0),
            css_path: class_path("target"),
        });
        assert_eq!(
            resolve_focus_target(&target, &results, None, &BTreeSet::new()),
            Ok(FocusResolution::Resolved(nid(0, 1)))
        );
    }
    #[test]
    fn resolve_focus_target_no_focus_is_an_explicit_clear() {
        let results = window(vec![(dom(0), tab_fixture())]);
        assert_eq!(
            resolve_focus_target(
                &FocusTarget::NoFocus,
                &results,
                Some(nid(0, 5)),
                &BTreeSet::new()
            ),
            Ok(FocusResolution::ClearRequested),
            "the app's explicit clear must stay distinguishable from a miss"
        );
    }
    #[test]
    fn resolve_focus_target_first_and_last_are_the_tab_order_ends() {
        let results = window(vec![(dom(0), tab_fixture())]);
        // Tab order is [5, 3, 2, 6, 7].
        assert_eq!(
            resolve_focus_target(&FocusTarget::First, &results, None, &BTreeSet::new()),
            Ok(FocusResolution::Resolved(nid(0, 5))),
            "First must be the lowest positive tabindex, not document node 0"
        );
        assert_eq!(
            resolve_focus_target(&FocusTarget::Last, &results, None, &BTreeSet::new()),
            Ok(FocusResolution::Resolved(nid(0, 7)))
        );
        // `current_focus` must not influence First/Last.
        assert_eq!(
            resolve_focus_target(
                &FocusTarget::First,
                &results,
                Some(nid(0, 7)),
                &BTreeSet::new()
            ),
            Ok(FocusResolution::Resolved(nid(0, 5)))
        );
    }
    #[test]
    fn resolve_focus_target_first_and_last_on_unfocusable_dom_are_none() {
        let sd = StyledDom::create_from_dom(Dom::create_body().with_child(Dom::create_div()));
        let results = window(vec![(dom(0), sd)]);
        assert_eq!(
            resolve_focus_target(&FocusTarget::First, &results, None, &BTreeSet::new()),
            Ok(FocusResolution::NotFound)
        );
        assert_eq!(
            resolve_focus_target(&FocusTarget::Last, &results, None, &BTreeSet::new()),
            Ok(FocusResolution::NotFound)
        );
        assert_eq!(
            resolve_focus_target(&FocusTarget::Next, &results, None, &BTreeSet::new()),
            Ok(FocusResolution::NotFound)
        );
        assert_eq!(
            resolve_focus_target(
                &FocusTarget::Previous,
                &results,
                Some(nid(0, 0)),
                &BTreeSet::new()
            ),
            Ok(FocusResolution::NotFound)
        );
    }
    #[test]
    fn resolve_focus_target_next_and_previous_wrap_around_the_tab_order() {
        let results = window(vec![(dom(0), tab_fixture())]);
        // Tab order [5, 3, 2, 6, 7]: stepping off either end wraps.
        assert_eq!(
            resolve_focus_target(
                &FocusTarget::Next,
                &results,
                Some(nid(0, 7)),
                &BTreeSet::new()
            ),
            Ok(FocusResolution::Resolved(nid(0, 5)))
        );
        assert_eq!(
            resolve_focus_target(
                &FocusTarget::Previous,
                &results,
                Some(nid(0, 5)),
                &BTreeSet::new()
            ),
            Ok(FocusResolution::Resolved(nid(0, 7)))
        );
        // ...and step normally in the middle.
        assert_eq!(
            resolve_focus_target(
                &FocusTarget::Next,
                &results,
                Some(nid(0, 3)),
                &BTreeSet::new()
            ),
            Ok(FocusResolution::Resolved(nid(0, 2)))
        );
        assert_eq!(
            resolve_focus_target(
                &FocusTarget::Previous,
                &results,
                Some(nid(0, 2)),
                &BTreeSet::new()
            ),
            Ok(FocusResolution::Resolved(nid(0, 3)))
        );
    }
    #[test]
    fn resolve_focus_target_next_from_a_non_tab_stop_reenters_in_document_order() {
        let results = window(vec![(dom(0), tab_fixture())]);
        // Focus sits on the tabindex=-1 node (index 4), which is NOT in the tab
        // order. Shift+Tab must fall back to document order and land on node 3
        // (the nearest preceding tab stop by DOCUMENT position), NOT on the tab
        // order's neighbour of any element.
        assert_eq!(
            resolve_focus_target(
                &FocusTarget::Previous,
                &results,
                Some(nid(0, 4)),
                &BTreeSet::new()
            ),
            Ok(FocusResolution::Resolved(nid(0, 3)))
        );
        // Focus on the plain, non-focusable div (index 1): Tab goes to the next
        // tab stop in DOCUMENT order (node 2, the button) — not to the tab
        // order's first entry (node 5).
        assert_eq!(
            resolve_focus_target(
                &FocusTarget::Next,
                &results,
                Some(nid(0, 1)),
                &BTreeSet::new()
            ),
            Ok(FocusResolution::Resolved(nid(0, 2)))
        );
    }
    #[test]
    fn resolve_focus_target_next_from_a_stale_removed_node_never_panics() {
        // Focus left over from a previous DOM whose node index no longer exists:
        // resolution must still yield a valid tab stop rather than panic.
        let results = window(vec![(dom(0), tab_fixture())]);
        let stale = nid(0, 9_999);
        assert_eq!(
            resolve_focus_target(&FocusTarget::Next, &results, Some(stale), &BTreeSet::new()),
            Ok(FocusResolution::Resolved(nid(0, 5))),
            "no tab stop past node 9999 -> wrap to the first"
        );
        // A stale node in a DOM that isn't even mounted.
        let alien = nid(5, 1);
        assert_eq!(
            resolve_focus_target(&FocusTarget::Next, &results, Some(alien), &BTreeSet::new()),
            Ok(FocusResolution::Resolved(nid(0, 5)))
        );
        assert_eq!(
            resolve_focus_target(
                &FocusTarget::Previous,
                &results,
                Some(alien),
                &BTreeSet::new()
            ),
            Ok(FocusResolution::Resolved(nid(0, 7)))
        );
    }
    // ==================================================================
    // NodeIdRemap
    // ==================================================================
    #[test]
    fn remap_rewrites_the_focused_node() {
        let mut fm = FocusManager::new();
        fm.set_focused_node(Some(nid(0, 5)));
        fm.remap_node_ids(
            dom(0),
            &NodeIdMap::from_pairs([(NodeId::new(5), NodeId::new(2))]),
        );
        assert_eq!(fm.get_focused_node(), Some(&nid(0, 2)));
    }
    #[test]
    fn remap_clears_focus_on_an_unmounted_node() {
        // The node vanished from the rebuilt DOM: keeping the stale index would
        // silently focus a DIFFERENT element, so focus must be dropped.
        let mut fm = FocusManager::new();
        fm.set_focused_node(Some(nid(0, 5)));
        fm.remap_node_ids(
            dom(0),
            &NodeIdMap::from_pairs([(NodeId::new(1), NodeId::new(1))]),
        );
        assert_eq!(fm.get_focused_node(), None);
    }
    #[test]
    fn remap_leaves_other_doms_untouched() {
        let mut fm = FocusManager::new();
        fm.set_focused_node(Some(nid(1, 5)));
        // Remapping DOM 0 must not disturb focus that lives in DOM 1.
        fm.remap_node_ids(
            dom(0),
            &NodeIdMap::from_pairs([(NodeId::new(5), NodeId::new(2))]),
        );
        assert_eq!(fm.get_focused_node(), Some(&nid(1, 5)));
    }
    #[test]
    fn remap_rewrites_pending_contenteditable_focus() {
        let mut fm = FocusManager::new();
        fm.set_pending_contenteditable_focus(dom(0), NodeId::new(3), NodeId::new(4));
        fm.remap_node_ids(
            dom(0),
            &NodeIdMap::from_pairs([
                (NodeId::new(3), NodeId::new(10)),
                (NodeId::new(4), NodeId::new(11)),
            ]),
        );
        assert!(fm.needs_cursor_initialization());
        assert_eq!(
            fm.take_pending_contenteditable_focus(),
            Some(PendingContentEditableFocus {
                dom_id: dom(0),
                container_node_id: NodeId::new(10),
                text_node_id: NodeId::new(11),
            })
        );
    }
    #[test]
    fn remap_partially_resolvable_pending_focus_drops_it_entirely() {
        // Container survives the rebuild but the text node does not (or vice
        // versa): keeping half of the pair would place a cursor in the wrong
        // node, so BOTH the value and the flag must be dropped.
        for pairs in [
            vec![(NodeId::new(3), NodeId::new(10))], // text node unmapped
            vec![(NodeId::new(4), NodeId::new(11))], // container unmapped
            vec![],                                  // neither survives
        ] {
            let mut fm = FocusManager::new();
            fm.set_pending_contenteditable_focus(dom(0), NodeId::new(3), NodeId::new(4));
            fm.remap_node_ids(dom(0), &NodeIdMap::from_pairs(pairs));
            assert!(!fm.needs_cursor_initialization());
            assert_eq!(fm.pending_contenteditable_focus, None);
        }
    }
}
/// Every spatial navigation container on the way up from `from`, INNERMOST
/// FIRST - the chain `css-nav-1` searches outward through (9a-i-b-i).
///
/// A node is a container when it declares `spatial-navigation-contain:
/// contain`, or - under `auto`, the initial value - when it is a SCROLL
/// CONTAINER (`overflow` other than `visible`/`clip` on either axis). That is
/// the spec's rule, and the user's ruling (2026-09-03) after 9a-i-a had held
/// it back. The document itself is the outermost container and is not
/// listed: the caller falls back to the whole candidate pool after the chain,
/// so an arrow at the edge of the innermost box still escapes it.
///
/// Self-inclusive: `contain` on the focused node, or a focused scroll
/// container, counts as its own innermost container.
380
fn spatial_navigation_containers(
380
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
380
    from: DomNodeId,
380
) -> Vec<DomNodeId> {
    use azul_css::props::style::spatial_nav::StyleSpatialNavigationContain;
    use crate::solver3::getters::{
        get_overflow_x, get_overflow_y, get_spatial_navigation_contain, MultiValue,
    };
380
    let mut chain = Vec::new();
380
    let Some(lr) = layout_results.get(&from.dom) else {
        return chain;
    };
380
    let hierarchy = lr.styled_dom.node_hierarchy.as_container();
380
    let states = lr.styled_dom.styled_nodes.as_container();
380
    let Some(mut node) = from.node.into_crate_internal() else {
        return chain;
    };
    // Bounded by the node count: a corrupt hierarchy whose parent chain loops
    // must not hang the event loop, and a valid chain can never be longer.
380
    for _ in 0..hierarchy.internal.len().saturating_add(1) {
700
        if let Some(sn) = states.get(node) {
700
            let state = &sn.styled_node_state;
700
            let is_container = match get_spatial_navigation_contain(&lr.styled_dom, node, state) {
4
                MultiValue::Exact(StyleSpatialNavigationContain::Contain) => true,
                // `auto`, and unset (whose initial value is `auto`): a
                // container exactly when the box is a scroll container.
                _ => {
696
                    get_overflow_x(&lr.styled_dom, node, state).is_scroll_container()
692
                        || get_overflow_y(&lr.styled_dom, node, state).is_scroll_container()
                }
            };
700
            if is_container {
12
                chain.push(DomNodeId {
12
                    dom: from.dom,
12
                    node: NodeHierarchyItemId::from_crate_internal(Some(node)),
12
                });
688
            }
        }
700
        match hierarchy
700
            .get(node)
700
            .and_then(azul_core::styled_dom::NodeHierarchyItem::parent_id)
        {
320
            Some(parent) => node = parent,
380
            None => break,
        }
    }
380
    chain
380
}
/// The INNERMOST spatial navigation container of `from`, if any - the first
/// entry of [`spatial_navigation_containers`].
8
fn spatial_navigation_container(
8
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
8
    from: DomNodeId,
8
) -> Option<DomNodeId> {
8
    spatial_navigation_containers(layout_results, from)
8
        .first()
8
        .copied()
8
}
/// Is `candidate` inside `container` (or the container itself)?
///
/// Cross-DOM candidates are never inside: a containing panel and a
/// `VirtualView`'s child document are different trees, and treating a node in
/// another DOM as contained would let the filter admit everything.
24
fn is_within(
24
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
24
    candidate: DomNodeId,
24
    container: DomNodeId,
24
) -> bool {
24
    if candidate.dom != container.dom {
1
        return false;
23
    }
23
    let (Some(cand), Some(cont)) = (
23
        candidate.node.into_crate_internal(),
23
        container.node.into_crate_internal(),
    ) else {
        return false;
    };
23
    if cand == cont {
1
        return true;
22
    }
22
    let Some(lr) = layout_results.get(&candidate.dom) else {
        return false;
    };
22
    let hierarchy = lr.styled_dom.node_hierarchy.as_container();
30
    cand.get_nearest_matching_parent(&hierarchy, |n| n == cont)
22
        .is_some()
24
}
/// Find the focusable nearest to `current` in `dir`.
///
/// The rule is the one `css-nav-1` describes and every TV framework
/// re-implements: consider only candidates that lie in the requested
/// direction, then pick the closest — where "closest" weights movement ALONG
/// the axis you asked for much more heavily than drift across it.
///
/// That weighting is the whole algorithm. Plain Euclidean distance picks
/// diagonal neighbours over the obvious one directly to the side, so pressing
/// Right in a grid walks diagonally down the screen. Weighting the
/// cross-axis makes "straight ahead, further away" beat "off to one side,
/// nearer", which is what a person means by the arrow key.
372
fn next_in_direction(
372
    candidates: &[DomNodeId],
372
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
372
    current: Option<DomNodeId>,
372
    dir: azul_core::callbacks::FocusDirection,
372
) -> Option<DomNodeId> {
    use azul_core::callbacks::FocusDirection;
    /// How much harder cross-axis drift counts than along-axis distance.
    /// 3 is what the CSS spec's reference implementation uses and what feels
    /// right on a grid: a neighbour one row down has to be three times nearer
    /// to beat one straight ahead.
    const CROSS_AXIS_WEIGHT: f32 = 3.0;
    // Absolute position comes from `calculated_positions`, size from the
    // layout node — the same pair the a11y snapshot reads. There is no
    // single "rects" table: a DOM node can map to several layout nodes
    // (inline fragments), so `dom_to_layout` yields a list and the first
    // entry is the box a focus ring would be drawn around.
380
    let rect_of = |n: &DomNodeId| -> Option<azul_core::geom::LogicalRect> {
380
        let layout = layout_results.get(&n.dom)?;
380
        let node = n.node.into_crate_internal()?;
380
        let idx = *layout.layout_tree.dom_to_layout.get(&node)?.first()?;
14
        let hot = layout.layout_tree.get(idx)?;
14
        let origin = layout.calculated_positions.get(idx.index()).copied()?;
        // `used_size` is None for a node that was never laid out — an
        // unmounted subtree, or one still awaiting its first pass. Skipping
        // it is right: a node with no box cannot be navigated to.
        Some(azul_core::geom::LogicalRect {
14
            origin,
14
            size: hot.used_size?,
        })
380
    };
    // With nothing focused there is no "direction from", so an arrow key acts
    // as an entry point and takes the first tab stop — the same thing a TV
    // remote does when you wake a menu.
372
    let Some(current) = current else {
        return candidates.first().copied();
    };
372
    let Some(from) = rect_of(&current) else {
366
        return candidates.first().copied();
    };
6
    let from_c = (
6
        from.origin.x + from.size.width / 2.0,
6
        from.origin.y + from.size.height / 2.0,
6
    );
6
    let mut best: Option<(f32, DomNodeId)> = None;
20
    for cand in candidates {
14
        if *cand == current {
6
            continue;
8
        }
8
        let Some(r) = rect_of(cand) else { continue };
8
        let c = (
8
            r.origin.x + r.size.width / 2.0,
8
            r.origin.y + r.size.height / 2.0,
8
        );
8
        let (dx, dy) = (c.0 - from_c.0, c.1 - from_c.1);
        // "In the requested direction" is decided by the dominant axis, not
        // by the sign alone: a node that is 2px right and 400px down is below,
        // not beside, and offering it to a Right press would make the focus
        // ring jump across the screen.
8
        let (along, cross) = match dir {
            FocusDirection::Left => (-dx, dy.abs()),
            FocusDirection::Right => (dx, dy.abs()),
            FocusDirection::Up => (-dy, dx.abs()),
8
            FocusDirection::Down => (dy, dx.abs()),
        };
8
        if along <= 0.0 || cross > along {
4
            continue;
4
        }
4
        let score = along + cross * CROSS_AXIS_WEIGHT;
4
        if best.is_none_or(|(b, _)| score < b) {
4
            best = Some((score, *cand));
4
        }
    }
6
    best.map(|(_, n)| n)
372
}