1
//! Default Action Processing for Keyboard Events
2
//!
3
//! This module implements W3C-compliant default actions for keyboard events.
4
//! Default actions are built-in behaviors that occur after event dispatch,
5
//! unless `event.prevent_default()` was called.
6
//!
7
//! ## W3C Event Model
8
//!
9
//! Per DOM Level 2/3 and W3C UI Events:
10
//!
11
//! 1. Event is dispatched through capture → target → bubble phases
12
//! 2. Callbacks can call `event.prevent_default()` to cancel default action
13
//! 3. After dispatch, if not prevented, the default action is performed
14
//!
15
//! ## Keyboard Default Actions
16
//!
17
//! | Key | Modifiers | Default Action |
18
//! |-----|-----------|----------------|
19
//! | Tab | None | Focus next element |
20
//! | Tab | Shift | Focus previous element |
21
//! | Enter | None | Activate focused element (if activatable) |
22
//! | Space | None | Activate focused element (if activatable) |
23
//! | Escape | None | Clear focus |
24
//!
25
//! ## Activation Behavior (HTML5)
26
//!
27
//! Per HTML5 spec, elements with "activation behavior" can be activated via
28
//! Enter or Space. This generates a synthetic click event:
29
//!
30
//! - Button elements
31
//! - Anchor elements with href
32
//! - Input elements (submit, button, checkbox, radio)
33
//! - Any element with a click callback
34
//!
35
//! See: https://html.spec.whatwg.org/multipage/interaction.html#activation-behavior
36

            
37
use alloc::vec::Vec;
38
use std::collections::{BTreeMap, BTreeSet};
39

            
40
use azul_core::{
41
    callbacks::{FocusDirection, FocusTarget},
42
    dom::{DomId, DomNodeId, NodeId},
43
    events::{DefaultAction, DefaultActionResult, ScrollAmount, ScrollDirection},
44
    window::{KeyboardState, VirtualKeyCode},
45
};
46
use azul_css::props::style::spatial_nav::StyleSpatialNavigationAction;
47

            
48
use crate::window::DomLayoutResult;
49

            
50
/// Editing state of the focused node, as the caret sees it — built by the
51
/// caller (`LayoutWindow::build_editing_query_state`) because the decision
52
/// function itself deliberately cannot see cursors.
53
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
54
// Four independent facts about one caret position, not a state enum: any
55
// combination of them can hold at once.
56
#[allow(clippy::struct_excessive_bools)]
57
pub struct EditingQueryState {
58
    /// The focused node is inside a `contenteditable` host.
59
    pub is_contenteditable: bool,
60
    /// The caret sits at the very start of the block's text.
61
    pub cursor_at_block_start: bool,
62
    /// The caret sits at the very end of the block's text.
63
    pub cursor_at_block_end: bool,
64
    /// The editing HOST's computed `white-space` preserves newlines
65
    /// (pre / pre-wrap / break-spaces / pre-line). In such a host a literal
66
    /// `"\n"` is the native line separator, so Enter inserts one instead of
67
    /// recording a structural block split.
68
    pub host_preserves_newlines: bool,
69
}
70

            
71
#[must_use]
72
9350
pub fn determine_keyboard_default_action(
73
9350
    keyboard_state: &KeyboardState,
74
9350
    focused_node: Option<DomNodeId>,
75
9350
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
76
9350
    prevented: bool,
77
9350
) -> DefaultActionResult {
78
9350
    determine_keyboard_default_action_with_editing(
79
9350
        keyboard_state,
80
9350
        focused_node,
81
9350
        layout_results,
82
9350
        prevented,
83
9350
        None,
84
    )
85
9350
}
86

            
87
/// [`determine_keyboard_default_action`] with contenteditable awareness.
88
///
89
/// Enter on a contenteditable focus records a structural SPLIT (Shift+Enter
90
/// stays a soft line break through the text path); Backspace at block start /
91
/// Delete at block end record structural MERGES. `editing: None` behaves
92
/// exactly like the editing-blind variant.
93
#[allow(clippy::too_many_lines)] // large but cohesive: single-purpose layout/render/parse routine (one branch per case)
94
#[must_use]
95
9396
pub fn determine_keyboard_default_action_with_editing(
96
9396
    keyboard_state: &KeyboardState,
97
9396
    focused_node: Option<DomNodeId>,
98
9396
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
99
9396
    prevented: bool,
100
9396
    editing: Option<&EditingQueryState>,
101
9396
) -> DefaultActionResult {
102
    // If prevented, return early with no action
103
9396
    if prevented {
104
1081
        return DefaultActionResult::prevented();
105
8315
    }
106

            
107
    // Get the current key (if any)
108
8315
    let Some(current_key) = keyboard_state.current_virtual_keycode.into_option() else {
109
1
        return DefaultActionResult::default();
110
    };
111

            
112
    // Check modifier state
113
8314
    let shift_down = keyboard_state.shift_down();
114
8314
    let ctrl_down = keyboard_state.ctrl_down();
115
8314
    let alt_down = keyboard_state.alt_down();
116

            
117
    // Determine action based on key
118
8314
    let action = match current_key {
119
        // Tab navigation
120
        VirtualKeyCode::Tab => {
121
478
            if ctrl_down || alt_down {
122
                // Ctrl+Tab / Alt+Tab are typically handled by OS
123
321
                DefaultAction::None
124
157
            } else if shift_down {
125
95
                DefaultAction::FocusPrevious
126
            } else {
127
62
                DefaultAction::FocusNext
128
            }
129
        }
130

            
131
        // Activation (Enter key)
132
        VirtualKeyCode::Return | VirtualKeyCode::NumpadEnter => {
133
945
            focused_node.as_ref().map_or(DefaultAction::None, |focus| {
134
                // Enter in a contenteditable host: a STRUCTURAL block split
135
                // for the app to apply (the browser default) — unless the
136
                // host is a plain-text context (`white-space` preserves
137
                // newlines), where `"\n"` is the native separator and the
138
                // split has no app model to land in. Shift+Enter is the soft
139
                // break in either kind of host.
140
864
                if let Some(e) = editing.filter(|e| e.is_contenteditable) {
141
23
                    if shift_down || e.host_preserves_newlines {
142
2
                        return DefaultAction::InsertLineBreakAtCursor { target: *focus };
143
21
                    }
144
21
                    return DefaultAction::SplitBlockAtCursor { target: *focus };
145
841
                }
146
                // A RESET control is checked BEFORE the generic activation:
147
                // it IS activatable, so the arm below would swallow it and the
148
                // form would never reset. Same reason submit is checked after
149
                // activation and reset before it - the specific case has to
150
                // win over the general one.
151
841
                if is_reset_control(focus, layout_results) {
152
1
                    if let Some(form_node) = find_form_ancestor(focus, layout_results) {
153
1
                        return DefaultAction::ResetForm { form_node };
154
                    }
155
                    // A reset button outside a form resets nothing; fall
156
                    // through to ordinary activation so a click handler on it
157
                    // still runs.
158
840
                }
159
840
                if is_element_activatable(focus, layout_results) {
160
109
                    DefaultAction::ActivateFocusedElement { target: *focus }
161
731
                } else if let Some(form_node) = find_form_ancestor(focus, layout_results) {
162
                    // IMPLICIT SUBMISSION, the HTML rule: Enter in a control
163
                    // that does not activate submits the form it belongs to.
164
                    //
165
                    // `DefaultAction::SubmitForm` and its consumer both
166
                    // existed - the consumer even claims "Enter on a focused
167
                    // control produced this action" - but NOTHING ever
168
                    // constructed it, so `EventType::Submit` could not fire on
169
                    // any platform. This is the missing producer.
170
1
                    DefaultAction::SubmitForm { form_node }
171
                } else {
172
                    // Not in a form: there is no target to submit, and
173
                    // guessing one would fire Submit at an unrelated node.
174
730
                    DefaultAction::None
175
                }
176
864
            })
177
        }
178

            
179
        // Backspace at BLOCK START / Delete at BLOCK END in a contenteditable
180
        // host: structural block merges. Anywhere else these keys keep flowing
181
        // through the per-IFC text-edit path unchanged (this fn returns None).
182
2
        VirtualKeyCode::Back => match (focused_node.as_ref(), editing) {
183
2
            (Some(focus), Some(e)) if e.is_contenteditable && e.cursor_at_block_start => {
184
1
                DefaultAction::MergeWithPrevious { target: *focus }
185
            }
186
1
            _ => DefaultAction::None,
187
        },
188
2
        VirtualKeyCode::Delete => match (focused_node.as_ref(), editing) {
189
2
            (Some(focus), Some(e)) if e.is_contenteditable && e.cursor_at_block_end => {
190
1
                DefaultAction::MergeWithNext { target: *focus }
191
            }
192
1
            _ => DefaultAction::None,
193
        },
194

            
195
        // Activation (Space key) — or page-scroll when nothing activatable
196
        // has focus (MWA-C-scroll: the browser default; Shift+Space pages up).
197
        VirtualKeyCode::Space => {
198
467
            match focused_node.as_ref() {
199
31
                Some(focus)
200
425
                    if is_element_activatable(focus, layout_results)
201
52
                        && !is_text_input(focus, layout_results) =>
202
                {
203
31
                    DefaultAction::ActivateFocusedElement { target: *focus }
204
                }
205
                // Space in text input should insert space (handled by text input system)
206
394
                Some(focus) if is_text_input(focus, layout_results) => DefaultAction::None,
207
                _ => DefaultAction::ScrollFocusedContainer {
208
394
                    direction: if shift_down {
209
197
                        ScrollDirection::Up
210
                    } else {
211
197
                        ScrollDirection::Down
212
                    },
213
394
                    amount: ScrollAmount::Page,
214
                },
215
            }
216
        }
217

            
218
        // Escape - clear focus
219
        VirtualKeyCode::Escape => {
220
460
            if focused_node.is_some() {
221
419
                DefaultAction::ClearFocus
222
            } else {
223
                // Could close modal/dialog here if any is open
224
41
                DefaultAction::None
225
            }
226
        }
227

            
228
        // Arrow keys - scroll or navigate
229
        VirtualKeyCode::Up
230
        | VirtualKeyCode::Down
231
        | VirtualKeyCode::Left
232
        | VirtualKeyCode::Right => {
233
1822
            let direction = match current_key {
234
455
                VirtualKeyCode::Up => ScrollDirection::Up,
235
457
                VirtualKeyCode::Down => ScrollDirection::Down,
236
455
                VirtualKeyCode::Left => ScrollDirection::Left,
237
455
                _ => ScrollDirection::Right,
238
            };
239
1822
            let scroll = DefaultAction::ScrollFocusedContainer {
240
1822
                direction,
241
1822
                amount: ScrollAmount::Line,
242
1822
            };
243
            // MWA-C-scroll: arrows scroll with NO focused node too (the
244
            // consumer anchors on the hovered container then) — only a
245
            // focused text input claims the arrows for caret movement.
246
1822
            focused_node.as_ref().map_or(scroll, |focus| {
247
1658
                if is_text_input(focus, layout_results) {
248
164
                    return DefaultAction::None;
249
1494
                }
250
                // SPATIAL NAVIGATION, per CSS Spatial Navigation Level 1: an
251
                // arrow does not choose between focus and scroll, it tries them
252
                // IN ORDER. Look for a focusable in that direction first; only
253
                // if there is none does the arrow scroll.
254
                //
255
                // That ordering is the whole reason this was blocked: taking
256
                // the arrows outright would break every scroll container, and
257
                // leaving them on scroll means a keyboard user deep in one part
258
                // of a UI cannot reach a visually adjacent control without
259
                // tabbing through everything between.
260
                //
261
                // Resolution is asked HERE rather than left to the dll seam so
262
                // the fallback is one decision in one place, testable without a
263
                // window — the seam would have to undo an already-dispatched
264
                // focus action to scroll instead.
265
1494
                let dir = match direction {
266
373
                    ScrollDirection::Up => FocusDirection::Up,
267
375
                    ScrollDirection::Down => FocusDirection::Down,
268
373
                    ScrollDirection::Left => FocusDirection::Left,
269
373
                    ScrollDirection::Right => FocusDirection::Right,
270
                };
271
                // Spatial navigation needs a real ORIGIN: "what is above THIS"
272
                // is unanswerable from a focus that names no live node, and
273
                // the resolver is lenient there — handed an unresolvable
274
                // current focus it falls back to a first-focusable, which
275
                // would turn every arrow into a focus jump. Require the anchor
276
                // to exist before asking.
277
1494
                let anchor_is_live = focus.node.into_crate_internal().is_some_and(|n| {
278
1330
                    layout_results
279
1330
                        .get(&focus.dom)
280
1330
                        .is_some_and(|lr| n.index() < lr.styled_dom.node_data.as_container().len())
281
1330
                });
282
1494
                if !anchor_is_live {
283
1128
                    return scroll;
284
366
                }
285
366
                let focus_move = match dir {
286
91
                    FocusDirection::Up => DefaultAction::FocusUp,
287
93
                    FocusDirection::Down => DefaultAction::FocusDown,
288
91
                    FocusDirection::Left => DefaultAction::FocusLeft,
289
91
                    FocusDirection::Right => DefaultAction::FocusRight,
290
                };
291
                // `spatial-navigation-action` (9a-i-b) is how a container opts
292
                // OUT of the ordered fallback. `Scroll` answers BEFORE the
293
                // spatial search runs, so a map or a canvas also pays nothing
294
                // for a search whose answer it would discard.
295
366
                let action = spatial_navigation_action(layout_results, focus);
296
366
                if action == StyleSpatialNavigationAction::Scroll {
297
                    return resolve_arrow_action(action, focus_move, false, scroll);
298
366
                }
299
366
                let spatial = crate::managers::focus_cursor::resolve_focus_target(
300
366
                    &FocusTarget::Directional(dir),
301
366
                    layout_results,
302
366
                    Some(*focus),
303
366
                    &BTreeSet::new(),
304
                );
305
366
                let found = matches!(
306
366
                    spatial,
307
                    Ok(crate::managers::focus_cursor::FocusResolution::Resolved(_))
308
                );
309
366
                resolve_arrow_action(action, focus_move, found, scroll)
310
1658
            })
311
        }
312

            
313
        // Page Up/Down
314
480
        VirtualKeyCode::PageUp => DefaultAction::ScrollFocusedContainer {
315
480
            direction: ScrollDirection::Up,
316
480
            amount: ScrollAmount::Page,
317
480
        },
318
481
        VirtualKeyCode::PageDown => DefaultAction::ScrollFocusedContainer {
319
481
            direction: ScrollDirection::Down,
320
481
            amount: ScrollAmount::Page,
321
481
        },
322

            
323
        // Home/End
324
        VirtualKeyCode::Home => {
325
457
            if ctrl_down {
326
                // Ctrl+Home - go to start of document
327
185
                DefaultAction::FocusFirst
328
            } else {
329
272
                DefaultAction::ScrollFocusedContainer {
330
272
                    direction: ScrollDirection::Up,
331
272
                    amount: ScrollAmount::Document,
332
272
                }
333
            }
334
        }
335
        VirtualKeyCode::End => {
336
455
            if ctrl_down {
337
                // Ctrl+End - go to end of document
338
183
                DefaultAction::FocusLast
339
            } else {
340
272
                DefaultAction::ScrollFocusedContainer {
341
272
                    direction: ScrollDirection::Down,
342
272
                    amount: ScrollAmount::Document,
343
272
                }
344
            }
345
        }
346

            
347
        // All other keys - no default action
348
2265
        _ => DefaultAction::None,
349
    };
350

            
351
8314
    DefaultActionResult::new(action)
352
9396
}
353

            
354
/// Check if an element is activatable (can receive synthetic click from Enter/Space).
355
1282
fn is_element_activatable(
356
1282
    node_id: &DomNodeId,
357
1282
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
358
1282
) -> bool {
359
1282
    let Some(layout) = layout_results.get(&node_id.dom) else {
360
668
        return false;
361
    };
362
614
    let Some(internal_id) = node_id.node.into_crate_internal() else {
363
64
        return false;
364
    };
365
550
    layout
366
550
        .styled_dom
367
550
        .node_data
368
550
        .as_container()
369
550
        .get(internal_id)
370
550
        .is_some_and(azul_core::dom::NodeData::is_activatable)
371
1282
}
372

            
373
/// Whether this control is a form RESET button (`type="reset"`).
374
///
375
/// HTML distinguishes reset from submit by the `type` attribute alone - both
376
/// are `<button>` or `<input>` - so this is an attribute read rather than a
377
/// node-type check.
378
841
fn is_reset_control(
379
841
    node_id: &DomNodeId,
380
841
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
381
841
) -> bool {
382
    use azul_core::dom::AttributeType;
383

            
384
841
    let Some(layout) = layout_results.get(&node_id.dom) else {
385
443
        return false;
386
    };
387
398
    let Some(internal_id) = node_id.node.into_crate_internal() else {
388
41
        return false;
389
    };
390
357
    let node_data = layout.styled_dom.node_data.as_container();
391
357
    let Some(data) = node_data.get(internal_id) else {
392
82
        return false;
393
    };
394
275
    data.attributes().as_ref().iter().any(
395
1
        |a| matches!(a, AttributeType::InputType(t) if t.as_str().eq_ignore_ascii_case("reset")),
396
    )
397
841
}
398

            
399
/// The nearest `NodeType::Form` ancestor of `node_id`, including itself.
400
///
401
/// HTML's rule: a control belongs to the form it is nested in, and Enter in
402
/// that control submits THAT form - not the page, and not the innermost thing
403
/// that happens to be focusable. Nested forms are invalid HTML, so the first
404
/// one found walking up is unambiguous.
405
///
406
/// Returns `None` for a control that is not in a form, which is why Enter
407
/// there does nothing rather than guessing at a target.
408
736
fn find_form_ancestor(
409
736
    node_id: &DomNodeId,
410
736
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
411
736
) -> Option<DomNodeId> {
412
    use azul_core::dom::NodeType;
413

            
414
736
    let layout = layout_results.get(&node_id.dom)?;
415
293
    let mut current = node_id.node.into_crate_internal()?;
416
252
    let node_data = layout.styled_dom.node_data.as_container();
417
252
    let hierarchy = layout.styled_dom.node_hierarchy.as_container();
418

            
419
    loop {
420
379
        if matches!(node_data.get(current)?.get_node_type(), NodeType::Form) {
421
4
            return Some(DomNodeId {
422
4
                dom: node_id.dom,
423
4
                node: azul_core::styled_dom::NodeHierarchyItemId::from_crate_internal(Some(
424
4
                    current,
425
4
                )),
426
4
            });
427
293
        }
428
293
        current = hierarchy.get(current)?.parent_id()?;
429
    }
430
736
}
431

            
432
/// Check if an element is a text input (where Space should insert text, not activate).
433
2120
fn is_text_input(node_id: &DomNodeId, layout_results: &BTreeMap<DomId, DomLayoutResult>) -> bool {
434
    use azul_core::events::{EventFilter, FocusEventFilter};
435
2120
    let Some(layout) = layout_results.get(&node_id.dom) else {
436
1109
        return false;
437
    };
438
1011
    let Some(internal_id) = node_id.node.into_crate_internal() else {
439
107
        return false;
440
    };
441
904
    let node_data = layout.styled_dom.node_data.as_container();
442
904
    let Some(node) = node_data.get(internal_id) else {
443
204
        return false;
444
    };
445

            
446
    // Check if this node has a TextInput callback (FocusEventFilter::TextInput)
447
    // which indicates it's a text input field
448
700
    node.get_callbacks()
449
700
        .iter()
450
700
        .any(|cb| matches!(cb.event, EventFilter::Focus(FocusEventFilter::TextInput)))
451
2120
}
452

            
453
/// What an arrow key does, given the container's `spatial-navigation-action`
454
/// and whether spatial navigation found anywhere to go.
455
///
456
/// Split out as a pure function because it is the whole behaviour of 9a-i-b in
457
/// three lines, and the alternative - asserting it through
458
/// `determine_keyboard_default_action` - needs a fixture with a real layout
459
/// tree carrying `scrollbar_info`, which no test in this file has. The truth
460
/// table gets tested directly instead.
461
372
const fn resolve_arrow_action(
462
372
    action: StyleSpatialNavigationAction,
463
372
    focus_move: DefaultAction,
464
372
    found: bool,
465
372
    scroll: DefaultAction,
466
372
) -> DefaultAction {
467
372
    match action {
468
        // Always scroll, focusable children or not. `found` is not even
469
        // consulted, which is why the caller can skip the search.
470
2
        StyleSpatialNavigationAction::Scroll => scroll,
471
        // Always focus. Nothing found means NOTHING HAPPENS - not a scroll.
472
        // The spec's "continue the search outward" is already covered, because
473
        // `next_in_direction` searches the whole candidate pool rather than
474
        // just this container.
475
        StyleSpatialNavigationAction::Focus => {
476
2
            if found {
477
1
                focus_move
478
            } else {
479
1
                DefaultAction::None
480
            }
481
        }
482
        // The ordered fallback 9a-i-a shipped, and the initial value.
483
        StyleSpatialNavigationAction::Auto => {
484
368
            if found {
485
367
                focus_move
486
            } else {
487
1
                scroll
488
            }
489
        }
490
    }
491
372
}
492

            
493
/// The `spatial-navigation-action` in force for an arrow press from `focus`.
494
///
495
/// Read off the nearest SCROLL CONTAINER at or above the focused node, not off
496
/// the focused node itself: the property answers "what does an arrow do when
497
/// this element is the container being navigated", and the element an arrow
498
/// would scroll is the one `ScrollFocusedContainer` acts on.
499
///
500
/// "Scroll container" here is the layout's own answer - `scrollbar_info` is
501
/// present - and NOT "does it currently overflow". The stricter test lives on
502
/// `LayoutWindow::find_scrollable_ancestor` and needs the scroll manager,
503
/// which this decision function deliberately does not have; the looser one is
504
/// also the right question, because an author who wrote
505
/// `spatial-navigation-action: scroll` meant it whether or not the box happens
506
/// to overflow at this instant.
507
367
fn spatial_navigation_action(
508
367
    layout_results: &BTreeMap<DomId, DomLayoutResult>,
509
367
    focus: &DomNodeId,
510
367
) -> StyleSpatialNavigationAction {
511
367
    let Some(lr) = layout_results.get(&focus.dom) else {
512
        return StyleSpatialNavigationAction::Auto;
513
    };
514
367
    let Some(node) = focus.node.into_crate_internal() else {
515
        return StyleSpatialNavigationAction::Auto;
516
    };
517
367
    let Some(start) = lr
518
367
        .layout_tree
519
367
        .dom_to_layout
520
367
        .get(&node)
521
367
        .and_then(|v| v.first())
522
    else {
523
365
        return StyleSpatialNavigationAction::Auto;
524
    };
525
2
    let states = lr.styled_dom.styled_nodes.as_container();
526
    // SELF-inclusive, like `find_scrollable_ancestor`: a focused node can BE
527
    // the scroll container - a focusable list box is the common case.
528
2
    for idx in lr
529
2
        .layout_tree
530
2
        .ancestor_chain(*start, azul_core::spaces::Inclusivity::SelfAndAncestors)
531
    {
532
2
        let is_scroll_container = lr
533
2
            .layout_tree
534
2
            .warm(idx)
535
2
            .and_then(|w| w.scrollbar_info.as_ref())
536
2
            .is_some();
537
2
        if !is_scroll_container {
538
            continue;
539
2
        }
540
2
        let Some(dom_node) = lr.layout_tree.get(idx).and_then(|n| n.dom_node_id) else {
541
            continue;
542
        };
543
2
        let Some(sn) = states.get(dom_node) else {
544
            continue;
545
        };
546
        if let crate::solver3::getters::MultiValue::Exact(action) =
547
2
            crate::solver3::getters::get_spatial_navigation_action(
548
2
                &lr.styled_dom,
549
2
                dom_node,
550
2
                &sn.styled_node_state,
551
2
            )
552
        {
553
            return action;
554
2
        }
555
        // The NEAREST scroll container decides, even when it says nothing:
556
        // walking past it to an outer one would let a grandparent override a
557
        // panel the author scoped deliberately.
558
2
        return StyleSpatialNavigationAction::Auto;
559
    }
560
    StyleSpatialNavigationAction::Auto
561
367
}
562

            
563
/// The default action a gamepad button press asks for.
564
///
565
/// `pressed` is an EDGE mask — buttons that went down since the last pass, as
566
/// `GamepadManager::take_pending_pressed` reports them. A level mask would
567
/// move focus once per poll for as long as the D-pad is held.
568
///
569
/// Only the D-pad is bound, and deliberately: it is the one control whose
570
/// meaning is unambiguously "move in this direction" and which conflicts with
571
/// nothing. Arrow keys scroll, so binding THEM needs the CSS opt-out that item
572
/// 9a-i describes; a D-pad has no such conflict, which is why this half could
573
/// land first. The face buttons are not bound either — "A activates" is a
574
/// platform convention (it is B on Nintendo layouts), not something to
575
/// hardcode here.
576
///
577
/// Diagonals resolve to a single direction rather than none: pressing up and
578
/// right together in one pass is a real thing a thumb does, and answering
579
/// `None` would make the D-pad feel dead at exactly the moment the user is
580
/// moving fastest. Vertical wins, because a spatial-navigation grid is
581
/// conventionally row-major.
582
#[must_use]
583
11
pub const fn determine_gamepad_default_action(pressed: u32) -> DefaultAction {
584
    use azul_core::gamepad::GamepadButton;
585
11
    if (pressed & GamepadButton::DPadUp.bit()) != 0 {
586
2
        DefaultAction::FocusUp
587
9
    } else if (pressed & GamepadButton::DPadDown.bit()) != 0 {
588
2
        DefaultAction::FocusDown
589
7
    } else if (pressed & GamepadButton::DPadLeft.bit()) != 0 {
590
1
        DefaultAction::FocusLeft
591
6
    } else if (pressed & GamepadButton::DPadRight.bit()) != 0 {
592
1
        DefaultAction::FocusRight
593
    } else {
594
5
        DefaultAction::None
595
    }
596
11
}
597

            
598
/// Convert a `DefaultAction` to a `FocusTarget` for the focus manager.
599
///
600
/// This bridges the gap between the abstract `DefaultAction` and the
601
/// concrete `FocusTarget` that the `FocusManager` understands.
602
#[must_use]
603
265
pub const fn default_action_to_focus_target(action: &DefaultAction) -> Option<FocusTarget> {
604
265
    match action {
605
18
        DefaultAction::FocusNext => Some(FocusTarget::Next),
606
5
        DefaultAction::FocusPrevious => Some(FocusTarget::Previous),
607
4
        DefaultAction::FocusFirst => Some(FocusTarget::First),
608
4
        DefaultAction::FocusLast => Some(FocusTarget::Last),
609
        // Spatial navigation. `resolve_focus_target` has handled
610
        // `Directional` since it was written — the gap was that no
611
        // `DefaultAction` could ask for it.
612
3
        DefaultAction::FocusUp => Some(FocusTarget::Directional(FocusDirection::Up)),
613
5
        DefaultAction::FocusDown => Some(FocusTarget::Directional(FocusDirection::Down)),
614
3
        DefaultAction::FocusLeft => Some(FocusTarget::Directional(FocusDirection::Left)),
615
3
        DefaultAction::FocusRight => Some(FocusTarget::Directional(FocusDirection::Right)),
616
4
        DefaultAction::ClearFocus => Some(FocusTarget::NoFocus),
617
216
        _ => None,
618
    }
619
265
}
620

            
621
#[cfg(test)]
622
mod tests {
623
    use azul_core::styled_dom::NodeHierarchyItemId;
624

            
625
    use super::*;
626

            
627
    #[test]
628
    #[allow(clippy::field_reassign_with_default)] // struct built incrementally / test setup; a
629
                                                  // struct literal is not clearer here
630
1
    fn test_tab_focus_next() {
631
1
        let mut keyboard_state = KeyboardState::default();
632
1
        keyboard_state.current_virtual_keycode = Some(VirtualKeyCode::Tab).into();
633

            
634
1
        let result =
635
1
            determine_keyboard_default_action(&keyboard_state, None, &BTreeMap::new(), false);
636

            
637
1
        assert!(matches!(result.action, DefaultAction::FocusNext));
638
1
        assert!(!result.prevented);
639
1
    }
640

            
641
    #[test]
642
    #[allow(clippy::field_reassign_with_default)] // struct built incrementally / test setup; a
643
                                                  // struct literal is not clearer here
644
1
    fn test_shift_tab_focus_previous() {
645
1
        let mut keyboard_state = KeyboardState::default();
646
1
        keyboard_state.current_virtual_keycode = Some(VirtualKeyCode::Tab).into();
647
        // Add LShift to pressed keys to simulate Shift being held
648
1
        keyboard_state.pressed_virtual_keycodes =
649
1
            vec![VirtualKeyCode::LShift, VirtualKeyCode::Tab].into();
650

            
651
1
        let result =
652
1
            determine_keyboard_default_action(&keyboard_state, None, &BTreeMap::new(), false);
653

            
654
1
        assert!(matches!(result.action, DefaultAction::FocusPrevious));
655
1
    }
656

            
657
    #[test]
658
    #[allow(clippy::field_reassign_with_default)] // struct built incrementally / test setup; a
659
                                                  // struct literal is not clearer here
660
1
    fn test_escape_clears_focus() {
661
1
        let mut keyboard_state = KeyboardState::default();
662
1
        keyboard_state.current_virtual_keycode = Some(VirtualKeyCode::Escape).into();
663

            
664
1
        let focused = Some(DomNodeId {
665
1
            dom: DomId { inner: 0 },
666
1
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(1))),
667
1
        });
668

            
669
1
        let result =
670
1
            determine_keyboard_default_action(&keyboard_state, focused, &BTreeMap::new(), false);
671

            
672
1
        assert!(matches!(result.action, DefaultAction::ClearFocus));
673
1
    }
674

            
675
    #[test]
676
    #[allow(clippy::field_reassign_with_default)] // struct built incrementally / test setup; a
677
                                                  // struct literal is not clearer here
678
1
    fn test_prevented_returns_no_action() {
679
1
        let mut keyboard_state = KeyboardState::default();
680
1
        keyboard_state.current_virtual_keycode = Some(VirtualKeyCode::Tab).into();
681

            
682
1
        let result = determine_keyboard_default_action(
683
1
            &keyboard_state,
684
1
            None,
685
1
            &BTreeMap::new(),
686
            true, // prevented!
687
        );
688

            
689
1
        assert!(result.prevented);
690
1
        assert!(matches!(result.action, DefaultAction::None));
691
1
    }
692
}
693

            
694
#[cfg(test)]
695
#[allow(clippy::field_reassign_with_default)] // KeyboardState is built incrementally in the helpers
696
mod autotest_generated {
697
    // ==================================================================
698
    // Structural-edit arms (A2): Enter splits, Backspace/Delete merge —
699
    // ONLY with contenteditable editing state; the editing-blind wrapper
700
    // must behave exactly as before.
701
    // ==================================================================
702

            
703
    #[test]
704
    fn enter_on_contenteditable_records_a_split_not_activation() {
705
        let layouts = BTreeMap::new();
706
        let focus = Some(dom_node(3));
707
        let editing = EditingQueryState {
708
            is_contenteditable: true,
709
            cursor_at_block_start: false,
710
            cursor_at_block_end: false,
711
            host_preserves_newlines: false,
712
        };
713

            
714
        let with = determine_keyboard_default_action_with_editing(
715
            &kbd(VirtualKeyCode::Return, &[]),
716
            focus,
717
            &layouts,
718
            false,
719
            Some(&editing),
720
        );
721
        assert!(matches!(
722
            with.action,
723
            DefaultAction::SplitBlockAtCursor { .. }
724
        ));
725

            
726
        // Shift+Enter: the soft break — a literal "\n" through the text
727
        // pipeline, never structural. (This used to fall through to nothing;
728
        // the documented intent is now implemented.)
729
        let shift = determine_keyboard_default_action_with_editing(
730
            &kbd(VirtualKeyCode::Return, &[VirtualKeyCode::LShift]),
731
            focus,
732
            &layouts,
733
            false,
734
            Some(&editing),
735
        );
736
        assert!(matches!(
737
            shift.action,
738
            DefaultAction::InsertLineBreakAtCursor { .. }
739
        ));
740

            
741
        // A PLAIN-TEXT host (white-space preserves newlines, e.g. the
742
        // text_area widget): plain Enter inserts the newline instead of
743
        // splitting blocks — there is no app model for a split to land in.
744
        let plaintext = EditingQueryState {
745
            host_preserves_newlines: true,
746
            ..editing
747
        };
748
        let plain_enter = determine_keyboard_default_action_with_editing(
749
            &kbd(VirtualKeyCode::Return, &[]),
750
            focus,
751
            &layouts,
752
            false,
753
            Some(&plaintext),
754
        );
755
        assert!(matches!(
756
            plain_enter.action,
757
            DefaultAction::InsertLineBreakAtCursor { .. }
758
        ));
759

            
760
        // Editing-blind: the old behavior, byte for byte.
761
        let without = determine_keyboard_default_action(
762
            &kbd(VirtualKeyCode::Return, &[]),
763
            focus,
764
            &layouts,
765
            false,
766
        );
767
        assert!(!matches!(
768
            without.action,
769
            DefaultAction::SplitBlockAtCursor { .. }
770
        ));
771
    }
772

            
773
    #[test]
774
    fn backspace_and_delete_merge_only_at_block_boundaries() {
775
        let layouts = BTreeMap::new();
776
        let focus = Some(dom_node(3));
777

            
778
        let at_start = EditingQueryState {
779
            is_contenteditable: true,
780
            cursor_at_block_start: true,
781
            cursor_at_block_end: false,
782
            host_preserves_newlines: false,
783
        };
784
        let mid = EditingQueryState {
785
            is_contenteditable: true,
786
            cursor_at_block_start: false,
787
            cursor_at_block_end: false,
788
            host_preserves_newlines: false,
789
        };
790
        let at_end = EditingQueryState {
791
            is_contenteditable: true,
792
            cursor_at_block_start: false,
793
            cursor_at_block_end: true,
794
            host_preserves_newlines: false,
795
        };
796

            
797
        let r = |key, e: &EditingQueryState| {
798
            determine_keyboard_default_action_with_editing(
799
                &kbd(key, &[]),
800
                focus,
801
                &layouts,
802
                false,
803
                Some(e),
804
            )
805
            .action
806
        };
807

            
808
        assert!(matches!(
809
            r(VirtualKeyCode::Back, &at_start),
810
            DefaultAction::MergeWithPrevious { .. }
811
        ));
812
        assert!(matches!(r(VirtualKeyCode::Back, &mid), DefaultAction::None));
813
        assert!(matches!(
814
            r(VirtualKeyCode::Delete, &at_end),
815
            DefaultAction::MergeWithNext { .. }
816
        ));
817
        assert!(matches!(
818
            r(VirtualKeyCode::Delete, &mid),
819
            DefaultAction::None
820
        ));
821
    }
822

            
823
    use std::collections::HashMap;
824

            
825
    use azul_core::{
826
        a11y::{AccessibilityRole, AccessibilityState, SmallAriaInfo},
827
        dom::{Dom, NodeData, NodeType},
828
        events::{EventFilter, FocusEventFilter, HoverEventFilter},
829
        geom::LogicalRect,
830
        refany::RefAny,
831
        styled_dom::{NodeHierarchyItemId, StyledDom},
832
    };
833

            
834
    use super::*;
835
    use crate::solver3::{display_list::DisplayList, layout_tree::LayoutTree};
836

            
837
    // ------------------------------------------------------------------
838
    // Fixtures
839
    // ------------------------------------------------------------------
840

            
841
    /// A `NodeData` with a single callback attached. The callback pointer is a
842
    /// dummy `usize` — nothing in this module ever invokes it, both functions
843
    /// under test only look at `CoreCallbackData::event`.
844
    fn node_with_callback(node_type: NodeType, event: EventFilter) -> NodeData {
845
        let mut nd = NodeData::create_node(node_type);
846
        nd.add_callback(event, RefAny::new(0u32), 0usize);
847
        nd
848
    }
849

            
850
    fn node_with_role(node_type: NodeType, role: AccessibilityRole) -> NodeData {
851
        let mut nd = NodeData::create_node(node_type);
852
        nd.set_accessibility_info(SmallAriaInfo::label("label").with_role(role).to_full_info());
853
        nd
854
    }
855

            
856
    /// A control that *has* activation behaviour (role `PushButton`) but is
857
    /// explicitly disabled — `is_activatable` must reject it.
858
    fn disabled_control() -> NodeData {
859
        let mut nd = NodeData::create_node(NodeType::Input);
860
        let mut info = SmallAriaInfo::label("Save")
861
            .with_role(AccessibilityRole::PushButton)
862
            .to_full_info();
863
        info.states = vec![AccessibilityState::Unavailable].into();
864
        nd.set_accessibility_info(info);
865
        nd
866
    }
867

            
868
    /// One DOM whose children each have a *distinct* `NodeType`, so tests can
869
    /// look a node up by type without hardcoding flatten indices:
870
    ///
871
    /// - `Button`   — activatable (inherent), not a text input
872
    /// - `Div`      — neither
873
    /// - `TextArea` — text input (has a `Focus(TextInput)` callback), not activatable
874
    /// - `A`        — activatable (inherent) *and* a text input (pathological overlap)
875
    /// - `P`        — activatable via a `Hover(LeftMouseUp)` click callback
876
    /// - `Input`    — role `PushButton` but `Unavailable` → disabled
877
    /// - `Select`   — activatable purely via the `CheckButton` a11y role
878
    fn fixture() -> BTreeMap<DomId, DomLayoutResult> {
879
        let dom = Dom::create_body()
880
            .with_child(Dom::create_from_data(NodeData::create_button_no_a11y()))
881
            .with_child(Dom::create_from_data(NodeData::create_div()))
882
            .with_child(Dom::create_from_data(node_with_callback(
883
                NodeType::TextArea,
884
                EventFilter::Focus(FocusEventFilter::TextInput),
885
            )))
886
            .with_child(Dom::create_from_data(node_with_callback(
887
                NodeType::A,
888
                EventFilter::Focus(FocusEventFilter::TextInput),
889
            )))
890
            .with_child(Dom::create_from_data(node_with_callback(
891
                NodeType::P,
892
                EventFilter::Hover(HoverEventFilter::LeftMouseUp),
893
            )))
894
            .with_child(Dom::create_from_data(disabled_control()))
895
            .with_child(Dom::create_from_data(node_with_role(
896
                NodeType::Select,
897
                AccessibilityRole::CheckButton,
898
            )));
899

            
900
        let styled_dom = StyledDom::create_from_dom(dom);
901

            
902
        let mut map = BTreeMap::new();
903
        map.insert(
904
            DomId::ROOT_ID,
905
            DomLayoutResult {
906
                styled_dom,
907
                layout_tree: LayoutTree {
908
                    nodes: Vec::new(),
909
                    warm: Vec::new(),
910
                    cold: Vec::new(),
911
                    root: 0,
912
                    dom_to_layout: BTreeMap::new(),
913
                    children_arena: Vec::new(),
914
                    children_offsets: Vec::new(),
915
                    subtree_needs_intrinsic: Vec::new(),
916
                },
917
                calculated_positions: Vec::new(),
918
                viewport: LogicalRect::zero(),
919
                display_list: std::sync::Arc::new(DisplayList::default()),
920
                scroll_ids: HashMap::new(),
921
                scroll_id_to_node_id: HashMap::new(),
922
            },
923
        );
924
        map
925
    }
926

            
927
    /// A body containing a `Form` whose child is a plain, non-activatable
928
    /// control - the shape implicit submission is about.
929
    ///
930
    /// Node 0 = body, 1 = form, 2 = the control inside it, 3 = a control
931
    /// OUTSIDE any form.
932
    fn form_fixture() -> BTreeMap<DomId, DomLayoutResult> {
933
        let dom = Dom::create_body()
934
            .with_child(
935
                Dom::create_node(NodeType::Form).with_child(Dom::create_from_data(
936
                    node_with_callback(
937
                        NodeType::TextArea,
938
                        EventFilter::Focus(FocusEventFilter::TextInput),
939
                    ),
940
                )),
941
            )
942
            .with_child(Dom::create_from_data(node_with_callback(
943
                NodeType::TextArea,
944
                EventFilter::Focus(FocusEventFilter::TextInput),
945
            )));
946

            
947
        let styled_dom = StyledDom::create_from_dom(dom);
948
        let mut map = BTreeMap::new();
949
        map.insert(
950
            DomId::ROOT_ID,
951
            DomLayoutResult {
952
                styled_dom,
953
                layout_tree: LayoutTree {
954
                    nodes: Vec::new(),
955
                    warm: Vec::new(),
956
                    cold: Vec::new(),
957
                    root: 0,
958
                    dom_to_layout: BTreeMap::new(),
959
                    children_arena: Vec::new(),
960
                    children_offsets: Vec::new(),
961
                    subtree_needs_intrinsic: Vec::new(),
962
                },
963
                calculated_positions: Vec::new(),
964
                viewport: LogicalRect::zero(),
965
                display_list: std::sync::Arc::new(DisplayList::default()),
966
                scroll_ids: HashMap::new(),
967
                scroll_id_to_node_id: HashMap::new(),
968
            },
969
        );
970
        map
971
    }
972

            
973
    /// A control inside a form finds it; the walk is up the ANCESTOR chain,
974
    /// not a scan of the document.
975
    #[test]
976
    fn a_control_finds_the_form_it_is_nested_in() {
977
        let layouts = form_fixture();
978
        assert_eq!(
979
            find_form_ancestor(&dom_node(2), &layouts),
980
            Some(dom_node(1)),
981
            "the control's parent is the form"
982
        );
983
    }
984

            
985
    /// The form is its own ancestor - HTML's rule, and it keeps Enter on a
986
    /// focused form itself from walking past it to nothing.
987
    #[test]
988
    fn a_form_is_its_own_ancestor() {
989
        let layouts = form_fixture();
990
        assert_eq!(
991
            find_form_ancestor(&dom_node(1), &layouts),
992
            Some(dom_node(1))
993
        );
994
    }
995

            
996
    /// A control outside every form has NO target, and that must stay `None`:
997
    /// guessing one would fire Submit at an unrelated node.
998
    #[test]
999
    fn a_control_outside_a_form_has_no_target() {
        let layouts = form_fixture();
        assert_eq!(find_form_ancestor(&dom_node(3), &layouts), None);
        assert_eq!(
            find_form_ancestor(&dom_node(0), &layouts),
            None,
            "the body is not a form"
        );
    }
    /// THE PRODUCER THAT WAS MISSING. `DefaultAction::SubmitForm` and its
    /// consumer both existed - the consumer even claims Enter produces it -
    /// but nothing ever constructed it, so `EventType::Submit` could not fire
    /// on any platform.
    #[test]
    fn enter_in_a_form_control_submits_the_form() {
        let layouts = form_fixture();
        let result = determine_keyboard_default_action(
            &kbd(VirtualKeyCode::Return, &[]),
            Some(dom_node(2)),
            &layouts,
            false,
        );
        assert_eq!(
            result.action,
            DefaultAction::SubmitForm {
                form_node: dom_node(1)
            },
            "Enter in a non-activatable form control must submit its form"
        );
    }
    /// A reset button must produce `ResetForm`, NOT `ActivateFocusedElement`.
    /// A button IS activatable, so the generic arm would swallow it and the
    /// form would never reset - which is why the reset check runs first.
    #[test]
    fn activating_a_reset_button_resets_its_form() {
        use azul_core::dom::AttributeType;
        let mut button = NodeData::create_button_no_a11y();
        button.set_attributes(vec![AttributeType::InputType("reset".into())].into());
        let dom = Dom::create_body()
            .with_child(Dom::create_node(NodeType::Form).with_child(Dom::create_from_data(button)));
        let styled_dom = StyledDom::create_from_dom(dom);
        let mut layouts = BTreeMap::new();
        layouts.insert(
            DomId::ROOT_ID,
            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(),
            },
        );
        let result = determine_keyboard_default_action(
            &kbd(VirtualKeyCode::Return, &[]),
            Some(dom_node(2)),
            &layouts,
            false,
        );
        assert_eq!(
            result.action,
            DefaultAction::ResetForm {
                form_node: dom_node(1)
            },
            "a reset button must reset, not merely activate"
        );
    }
    /// Enter outside a form stays `None` rather than submitting something.
    #[test]
    fn enter_outside_a_form_does_nothing() {
        let layouts = form_fixture();
        let result = determine_keyboard_default_action(
            &kbd(VirtualKeyCode::Return, &[]),
            Some(dom_node(3)),
            &layouts,
            false,
        );
        assert_eq!(result.action, DefaultAction::None);
    }
    fn dom_node(index: usize) -> DomNodeId {
        DomNodeId {
            dom: DomId::ROOT_ID,
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(index))),
        }
    }
    /// Locate the fixture node with the given `NodeType`. Scanning (instead of
    /// assuming `child i == NodeId(i + 1)`) keeps the tests honest even if the
    /// flatten order or anonymous-box insertion ever changes.
    fn node_of(
        layouts: &BTreeMap<DomId, DomLayoutResult>,
        matcher: fn(&NodeType) -> bool,
    ) -> DomNodeId {
        let layout = layouts.get(&DomId::ROOT_ID).expect("fixture dom missing");
        let container = layout.styled_dom.node_data.as_container();
        for i in 0..container.len() {
            if container
                .get(NodeId::new(i))
                .is_some_and(|nd| matcher(&nd.node_type))
            {
                return dom_node(i);
            }
        }
        panic!("fixture node not found");
    }
    fn button(l: &BTreeMap<DomId, DomLayoutResult>) -> DomNodeId {
        node_of(l, |t| matches!(t, NodeType::Button))
    }
    fn div(l: &BTreeMap<DomId, DomLayoutResult>) -> DomNodeId {
        node_of(l, |t| matches!(t, NodeType::Div))
    }
    fn textarea(l: &BTreeMap<DomId, DomLayoutResult>) -> DomNodeId {
        node_of(l, |t| matches!(t, NodeType::TextArea))
    }
    fn anchor(l: &BTreeMap<DomId, DomLayoutResult>) -> DomNodeId {
        node_of(l, |t| matches!(t, NodeType::A))
    }
    fn clickable_p(l: &BTreeMap<DomId, DomLayoutResult>) -> DomNodeId {
        node_of(l, |t| matches!(t, NodeType::P))
    }
    fn disabled(l: &BTreeMap<DomId, DomLayoutResult>) -> DomNodeId {
        node_of(l, |t| matches!(t, NodeType::Input))
    }
    fn role_only(l: &BTreeMap<DomId, DomLayoutResult>) -> DomNodeId {
        node_of(l, |t| matches!(t, NodeType::Select))
    }
    fn body(l: &BTreeMap<DomId, DomLayoutResult>) -> DomNodeId {
        node_of(l, |t| matches!(t, NodeType::Body))
    }
    // --- Deliberately broken node ids ---------------------------------
    /// References a `DomId` that is not in the map at all.
    fn missing_dom() -> DomNodeId {
        DomNodeId {
            dom: DomId { inner: 9999 },
            node: NodeHierarchyItemId::from_crate_internal(Some(NodeId::new(0))),
        }
    }
    /// In-range DOM, node index far past the end of the container.
    fn out_of_bounds_node() -> DomNodeId {
        dom_node(9999)
    }
    /// The "no node" sentinel (`inner == 0` decodes to `None`).
    fn null_node() -> DomNodeId {
        DomNodeId {
            dom: DomId::ROOT_ID,
            node: NodeHierarchyItemId::NONE,
        }
    }
    /// Maximal raw encoding. Decodes to `NodeId(usize::MAX - 1)`; the container
    /// lookup must reject it rather than index out of bounds.
    fn max_node() -> DomNodeId {
        DomNodeId {
            dom: DomId::ROOT_ID,
            node: NodeHierarchyItemId::from_raw(usize::MAX),
        }
    }
    fn kbd(key: VirtualKeyCode, mods: &[VirtualKeyCode]) -> KeyboardState {
        let mut ks = KeyboardState::default();
        ks.current_virtual_keycode = Some(key).into();
        let mut pressed = mods.to_vec();
        pressed.push(key);
        ks.pressed_virtual_keycodes = pressed.into();
        ks
    }
    const ALL_KEYS: &[VirtualKeyCode] = &[
        VirtualKeyCode::Tab,
        VirtualKeyCode::Return,
        VirtualKeyCode::NumpadEnter,
        VirtualKeyCode::Space,
        VirtualKeyCode::Escape,
        VirtualKeyCode::Up,
        VirtualKeyCode::Down,
        VirtualKeyCode::Left,
        VirtualKeyCode::Right,
        VirtualKeyCode::PageUp,
        VirtualKeyCode::PageDown,
        VirtualKeyCode::Home,
        VirtualKeyCode::End,
        VirtualKeyCode::F1,
        VirtualKeyCode::Key1,
        VirtualKeyCode::LShift,
        VirtualKeyCode::LControl,
        VirtualKeyCode::LAlt,
    ];
    const MOD_SETS: &[&[VirtualKeyCode]] = &[
        &[],
        &[VirtualKeyCode::LShift],
        &[VirtualKeyCode::RShift],
        &[VirtualKeyCode::LControl],
        &[VirtualKeyCode::RControl],
        &[VirtualKeyCode::LAlt],
        &[VirtualKeyCode::RAlt],
        &[VirtualKeyCode::LControl, VirtualKeyCode::LShift],
        &[VirtualKeyCode::LAlt, VirtualKeyCode::LShift],
        &[
            VirtualKeyCode::LControl,
            VirtualKeyCode::LAlt,
            VirtualKeyCode::LShift,
        ],
    ];
    fn scroll(direction: ScrollDirection, amount: ScrollAmount) -> DefaultAction {
        DefaultAction::ScrollFocusedContainer { direction, amount }
    }
    // ==================================================================
    // determine_keyboard_default_action — prevention & missing key
    // ==================================================================
    #[test]
    fn prevented_beats_every_key_modifier_and_focus_combination() {
        let layouts = fixture();
        let focus_states = [
            None,
            Some(button(&layouts)),
            Some(textarea(&layouts)),
            Some(missing_dom()),
            Some(null_node()),
        ];
        for key in ALL_KEYS {
            for mods in MOD_SETS {
                for focus in focus_states {
                    let result =
                        determine_keyboard_default_action(&kbd(*key, mods), focus, &layouts, true);
                    assert!(
                        result.prevented,
                        "prevent_default() must be reported for {key:?}"
                    );
                    assert_eq!(
                        result.action,
                        DefaultAction::None,
                        "a prevented event must never carry an action ({key:?})"
                    );
                }
            }
        }
    }
    #[test]
    fn no_current_key_yields_the_default_result() {
        let layouts = fixture();
        // Modifiers held, keys "pressed", but no `current_virtual_keycode`.
        let mut ks = KeyboardState::default();
        ks.pressed_virtual_keycodes = vec![VirtualKeyCode::LShift, VirtualKeyCode::LControl].into();
        let result =
            determine_keyboard_default_action(&ks, Some(button(&layouts)), &layouts, false);
        assert_eq!(result.action, DefaultAction::None);
        assert!(!result.prevented);
    }
    #[test]
    fn never_reports_prevented_when_not_prevented() {
        let layouts = fixture();
        for key in ALL_KEYS {
            for mods in MOD_SETS {
                let result = determine_keyboard_default_action(
                    &kbd(*key, mods),
                    Some(button(&layouts)),
                    &layouts,
                    false,
                );
                assert!(!result.prevented, "{key:?} must not set `prevented`");
            }
        }
    }
    // ==================================================================
    // Tab
    // ==================================================================
    #[test]
    fn tab_with_ctrl_or_alt_yields_no_action() {
        let layouts = fixture();
        for mods in [
            &[VirtualKeyCode::LControl][..],
            &[VirtualKeyCode::RControl][..],
            &[VirtualKeyCode::LAlt][..],
            &[VirtualKeyCode::RAlt][..],
            // Ctrl/Alt must win even when Shift is also down.
            &[VirtualKeyCode::LControl, VirtualKeyCode::LShift][..],
            &[VirtualKeyCode::LAlt, VirtualKeyCode::RShift][..],
        ] {
            let result = determine_keyboard_default_action(
                &kbd(VirtualKeyCode::Tab, mods),
                None,
                &layouts,
                false,
            );
            assert_eq!(
                result.action,
                DefaultAction::None,
                "Ctrl/Alt+Tab belongs to the OS, not the app ({mods:?})"
            );
        }
    }
    #[test]
    fn tab_uses_either_shift_key_and_ignores_focus() {
        let layouts = fixture();
        for shift in [VirtualKeyCode::LShift, VirtualKeyCode::RShift] {
            let result = determine_keyboard_default_action(
                &kbd(VirtualKeyCode::Tab, &[shift]),
                Some(textarea(&layouts)),
                &layouts,
                false,
            );
            assert_eq!(result.action, DefaultAction::FocusPrevious);
        }
        let result = determine_keyboard_default_action(
            &kbd(VirtualKeyCode::Tab, &[]),
            Some(textarea(&layouts)),
            &layouts,
            false,
        );
        assert_eq!(result.action, DefaultAction::FocusNext);
    }
    // ==================================================================
    // Enter / NumpadEnter
    // ==================================================================
    #[test]
    fn enter_activates_every_kind_of_activatable_element() {
        let layouts = fixture();
        for target in [
            button(&layouts),
            anchor(&layouts),
            clickable_p(&layouts),
            role_only(&layouts),
        ] {
            for key in [VirtualKeyCode::Return, VirtualKeyCode::NumpadEnter] {
                let result = determine_keyboard_default_action(
                    &kbd(key, &[]),
                    Some(target),
                    &layouts,
                    false,
                );
                assert_eq!(
                    result.action,
                    DefaultAction::ActivateFocusedElement { target },
                    "{key:?} on an activatable element must activate exactly that element"
                );
            }
        }
    }
    #[test]
    fn enter_on_a_disabled_control_does_not_activate() {
        let layouts = fixture();
        let result = determine_keyboard_default_action(
            &kbd(VirtualKeyCode::Return, &[]),
            Some(disabled(&layouts)),
            &layouts,
            false,
        );
        assert_eq!(
            result.action,
            DefaultAction::None,
            "an Unavailable (disabled) control must never be activated"
        );
    }
    #[test]
    fn enter_on_non_activatable_or_unfocused_yields_no_action() {
        let layouts = fixture();
        for focus in [None, Some(div(&layouts)), Some(body(&layouts))] {
            let result = determine_keyboard_default_action(
                &kbd(VirtualKeyCode::Return, &[]),
                focus,
                &layouts,
                false,
            );
            assert_eq!(result.action, DefaultAction::None);
        }
    }
    #[test]
    fn enter_on_a_dangling_focus_target_does_not_panic() {
        let layouts = fixture();
        let empty: BTreeMap<DomId, DomLayoutResult> = BTreeMap::new();
        // Bogus node ids against a populated map.
        for focus in [missing_dom(), out_of_bounds_node(), null_node(), max_node()] {
            let result = determine_keyboard_default_action(
                &kbd(VirtualKeyCode::Return, &[]),
                Some(focus),
                &layouts,
                false,
            );
            assert_eq!(
                result.action,
                DefaultAction::None,
                "a focus target that cannot be resolved must not be activated"
            );
        }
        // A perfectly valid node id against an empty map.
        let result = determine_keyboard_default_action(
            &kbd(VirtualKeyCode::Return, &[]),
            Some(dom_node(1)),
            &empty,
            false,
        );
        assert_eq!(result.action, DefaultAction::None);
    }
    // ==================================================================
    // Space
    // ==================================================================
    #[test]
    fn space_activates_a_focused_button() {
        let layouts = fixture();
        let target = button(&layouts);
        let result = determine_keyboard_default_action(
            &kbd(VirtualKeyCode::Space, &[]),
            Some(target),
            &layouts,
            false,
        );
        assert_eq!(
            result.action,
            DefaultAction::ActivateFocusedElement { target }
        );
    }
    #[test]
    fn space_in_a_text_input_is_swallowed_even_when_the_element_is_activatable() {
        let layouts = fixture();
        // Plain text input: not activatable at all.
        let result = determine_keyboard_default_action(
            &kbd(VirtualKeyCode::Space, &[]),
            Some(textarea(&layouts)),
            &layouts,
            false,
        );
        assert_eq!(
            result.action,
            DefaultAction::None,
            "Space in a text input must insert text, not scroll or activate"
        );
        // Pathological overlap: an <a> (inherently activatable) that also has a
        // TextInput callback. Text-input behaviour must win over activation,
        // otherwise typing a space in it would fire a synthetic click.
        let result = determine_keyboard_default_action(
            &kbd(VirtualKeyCode::Space, &[]),
            Some(anchor(&layouts)),
            &layouts,
            false,
        );
        assert_eq!(
            result.action,
            DefaultAction::None,
            "text-input behaviour must take precedence over activation for Space"
        );
    }
    #[test]
    fn space_pages_the_scroll_container_when_nothing_activatable_has_focus() {
        let layouts = fixture();
        for focus in [
            None,
            Some(div(&layouts)),
            Some(body(&layouts)),
            Some(disabled(&layouts)),
            Some(missing_dom()),
            Some(null_node()),
            Some(out_of_bounds_node()),
        ] {
            let down = determine_keyboard_default_action(
                &kbd(VirtualKeyCode::Space, &[]),
                focus,
                &layouts,
                false,
            );
            assert_eq!(
                down.action,
                scroll(ScrollDirection::Down, ScrollAmount::Page)
            );
            let up = determine_keyboard_default_action(
                &kbd(VirtualKeyCode::Space, &[VirtualKeyCode::RShift]),
                focus,
                &layouts,
                false,
            );
            assert_eq!(
                up.action,
                scroll(ScrollDirection::Up, ScrollAmount::Page),
                "Shift+Space pages up"
            );
        }
    }
    // ==================================================================
    // Escape
    // ==================================================================
    #[test]
    fn escape_clears_focus_only_when_something_is_focused() {
        let layouts = fixture();
        // Even an unresolvable focus target counts as "focused" — Escape only
        // checks `is_some()`, and clearing a dangling focus is still correct.
        for focus in [
            button(&layouts),
            div(&layouts),
            null_node(),
            missing_dom(),
            max_node(),
        ] {
            let result = determine_keyboard_default_action(
                &kbd(VirtualKeyCode::Escape, &[]),
                Some(focus),
                &layouts,
                false,
            );
            assert_eq!(result.action, DefaultAction::ClearFocus);
        }
        let result = determine_keyboard_default_action(
            &kbd(VirtualKeyCode::Escape, &[]),
            None,
            &layouts,
            false,
        );
        assert_eq!(result.action, DefaultAction::None);
    }
    // ==================================================================
    // Arrows / PageUp / PageDown / Home / End
    // ==================================================================
    /// An arrow MOVES FOCUS when there is a focusable in that direction.
    ///
    /// This is the half that was blocked. Arrows used to scroll
    /// unconditionally, so a keyboard user deep in one part of a UI could not
    /// reach a visually adjacent control without tabbing through everything
    /// between it — the complaint that opened the item. Per CSS Spatial
    /// Navigation Level 1 the arrow tries focus FIRST and falls back to
    /// scrolling, which is what makes taking the arrows safe at all.
    ///
    /// THE WHOLE TRUTH TABLE of `spatial-navigation-action`, all six cases.
    ///
    /// The two overrides differ from the default in exactly one cell each, and
    /// both of those cells are the point of the property: `scroll` must not
    /// focus even when a target exists, and `focus` must not scroll even when
    /// none does.
    #[test]
    fn the_spatial_navigation_action_truth_table() {
        let up = DefaultAction::FocusUp;
        let scroll = DefaultAction::ScrollFocusedContainer {
            direction: ScrollDirection::Up,
            amount: ScrollAmount::Line,
        };
        for found in [true, false] {
            assert_eq!(
                resolve_arrow_action(StyleSpatialNavigationAction::Scroll, up, found, scroll),
                scroll,
                "`scroll` must scroll whether or not a focus target exists (found={found})",
            );
        }
        assert_eq!(
            resolve_arrow_action(StyleSpatialNavigationAction::Focus, up, true, scroll),
            up,
        );
        assert_eq!(
            resolve_arrow_action(StyleSpatialNavigationAction::Focus, up, false, scroll),
            DefaultAction::None,
            "`focus` must NOT fall back to scrolling - that is what it opts out of",
        );
        assert_eq!(
            resolve_arrow_action(StyleSpatialNavigationAction::Auto, up, true, scroll),
            up,
        );
        assert_eq!(
            resolve_arrow_action(StyleSpatialNavigationAction::Auto, up, false, scroll),
            scroll,
            "`auto` is the ordered fallback 9a-i-a shipped",
        );
    }
    /// The property is read off the nearest SCROLL CONTAINER, and this fixture
    /// has no layout tree at all - so every lookup must answer `Auto` rather
    /// than panicking or inventing an override. That is also what keeps this
    /// whole change a no-op for existing behaviour.
    #[test]
    fn a_node_with_no_layout_reports_the_initial_action() {
        let layouts = fixture();
        let focus = button(&layouts);
        assert_eq!(
            spatial_navigation_action(&layouts, &focus),
            StyleSpatialNavigationAction::Auto,
        );
    }
    #[test]
    fn an_arrow_moves_focus_when_something_is_there_to_focus() {
        let layouts = fixture();
        // A live, non-text anchor: the resolver has an origin to search from.
        let focus = button(&layouts);
        let mut moved = 0;
        for (key, focus_action) in [
            (VirtualKeyCode::Up, DefaultAction::FocusUp),
            (VirtualKeyCode::Down, DefaultAction::FocusDown),
            (VirtualKeyCode::Left, DefaultAction::FocusLeft),
            (VirtualKeyCode::Right, DefaultAction::FocusRight),
        ] {
            let action =
                determine_keyboard_default_action(&kbd(key, &[]), Some(focus), &layouts, false)
                    .action;
            // Whichever way this fixture actually has a neighbour, the answer
            // must be EITHER that direction's focus move OR the scroll
            // fallback — never a different direction, and never nothing.
            assert!(
                action == focus_action
                    || matches!(action, DefaultAction::ScrollFocusedContainer { .. }),
                "{key:?} must either move focus {focus_action:?} or fall back to a scroll, got \
                 {action:?}",
            );
            if action == focus_action {
                moved += 1;
            }
        }
        assert!(
            moved > 0,
            "at least one direction in this fixture has a neighbour to focus; if none does, the \
             ordering is untested and the fixture needs a second focusable",
        );
    }
    /// An arrow SCROLLS only when spatial navigation finds nothing.
    ///
    /// CSS Spatial Navigation Level 1 makes this an ORDER, not a choice: look
    /// for a focusable in that direction, and only if there is none does the
    /// arrow scroll. This asserts the fallback half — the cases where no
    /// candidate can resolve, so the scroll is what must happen.
    #[test]
    fn arrow_keys_map_to_their_own_direction_and_scroll_by_line() {
        let layouts = fixture();
        for (key, direction) in [
            (VirtualKeyCode::Up, ScrollDirection::Up),
            (VirtualKeyCode::Down, ScrollDirection::Down),
            (VirtualKeyCode::Left, ScrollDirection::Left),
            (VirtualKeyCode::Right, ScrollDirection::Right),
        ] {
            // No focus at all, and focus anchored in a dom/node that cannot be
            // resolved: spatial navigation has nowhere to search FROM, so the
            // fallback applies.
            for focus in [None, Some(missing_dom()), Some(null_node())] {
                let result =
                    determine_keyboard_default_action(&kbd(key, &[]), focus, &layouts, false);
                assert_eq!(
                    result.action,
                    scroll(direction, ScrollAmount::Line),
                    "{key:?} must scroll one line towards {direction:?} when spatial navigation \
                     finds no candidate"
                );
            }
            // A focused text input claims the arrows for caret movement.
            let result = determine_keyboard_default_action(
                &kbd(key, &[]),
                Some(textarea(&layouts)),
                &layouts,
                false,
            );
            assert_eq!(
                result.action,
                DefaultAction::None,
                "{key:?} in a text input must move the caret, not scroll"
            );
        }
    }
    #[test]
    fn page_keys_scroll_a_page_regardless_of_modifiers_and_focus() {
        let layouts = fixture();
        for (key, direction) in [
            (VirtualKeyCode::PageUp, ScrollDirection::Up),
            (VirtualKeyCode::PageDown, ScrollDirection::Down),
        ] {
            for mods in MOD_SETS {
                for focus in [None, Some(textarea(&layouts)), Some(button(&layouts))] {
                    let result =
                        determine_keyboard_default_action(&kbd(key, mods), focus, &layouts, false);
                    assert_eq!(result.action, scroll(direction, ScrollAmount::Page));
                }
            }
        }
    }
    #[test]
    fn home_and_end_switch_between_scrolling_and_focus_on_ctrl() {
        let layouts = fixture();
        for ctrl in [VirtualKeyCode::LControl, VirtualKeyCode::RControl] {
            let home = determine_keyboard_default_action(
                &kbd(VirtualKeyCode::Home, &[ctrl]),
                None,
                &layouts,
                false,
            );
            assert_eq!(home.action, DefaultAction::FocusFirst);
            let end = determine_keyboard_default_action(
                &kbd(VirtualKeyCode::End, &[ctrl]),
                None,
                &layouts,
                false,
            );
            assert_eq!(end.action, DefaultAction::FocusLast);
            // Ctrl still wins when Shift/Alt are also held.
            let home_shift = determine_keyboard_default_action(
                &kbd(
                    VirtualKeyCode::Home,
                    &[ctrl, VirtualKeyCode::LShift, VirtualKeyCode::LAlt],
                ),
                Some(textarea(&layouts)),
                &layouts,
                false,
            );
            assert_eq!(home_shift.action, DefaultAction::FocusFirst);
        }
        // Without Ctrl: scroll to the document start / end. Note this happens
        // even inside a focused text input (no Home/End caret handling here).
        for focus in [None, Some(textarea(&layouts))] {
            let home = determine_keyboard_default_action(
                &kbd(VirtualKeyCode::Home, &[VirtualKeyCode::LShift]),
                focus,
                &layouts,
                false,
            );
            assert_eq!(
                home.action,
                scroll(ScrollDirection::Up, ScrollAmount::Document)
            );
            let end = determine_keyboard_default_action(
                &kbd(VirtualKeyCode::End, &[]),
                focus,
                &layouts,
                false,
            );
            assert_eq!(
                end.action,
                scroll(ScrollDirection::Down, ScrollAmount::Document)
            );
        }
    }
    #[test]
    fn keys_without_a_default_action_yield_none() {
        let layouts = fixture();
        for key in [
            VirtualKeyCode::F1,
            VirtualKeyCode::Key1,
            VirtualKeyCode::LShift,
            VirtualKeyCode::LControl,
            VirtualKeyCode::LAlt,
        ] {
            for focus in [None, Some(button(&layouts)), Some(textarea(&layouts))] {
                let result =
                    determine_keyboard_default_action(&kbd(key, &[]), focus, &layouts, false);
                assert_eq!(
                    result.action,
                    DefaultAction::None,
                    "{key:?} has no default action"
                );
            }
        }
    }
    // ==================================================================
    // Whole-surface smoke: no panic, deterministic, self-consistent
    // ==================================================================
    #[test]
    fn every_key_modifier_and_focus_combination_is_panic_free_and_deterministic() {
        let layouts = fixture();
        let empty: BTreeMap<DomId, DomLayoutResult> = BTreeMap::new();
        let focus_states = [
            None,
            Some(button(&layouts)),
            Some(div(&layouts)),
            Some(textarea(&layouts)),
            Some(anchor(&layouts)),
            Some(disabled(&layouts)),
            Some(body(&layouts)),
            Some(missing_dom()),
            Some(out_of_bounds_node()),
            Some(null_node()),
            Some(max_node()),
        ];
        for key in ALL_KEYS {
            for mods in MOD_SETS {
                for focus in focus_states {
                    for maps in [&layouts, &empty] {
                        let ks = kbd(*key, mods);
                        let a = determine_keyboard_default_action(&ks, focus, maps, false);
                        let b = determine_keyboard_default_action(&ks, focus, maps, false);
                        assert_eq!(
                            a.action, b.action,
                            "{key:?} must be a pure function of its inputs"
                        );
                        assert_eq!(a.prevented, b.prevented);
                        // An activation can only ever target the focused node.
                        if let DefaultAction::ActivateFocusedElement { target } = a.action {
                            assert_eq!(
                                Some(target),
                                focus,
                                "activation must target the focused node, nothing else"
                            );
                        }
                    }
                }
            }
        }
    }
    // ==================================================================
    // is_element_activatable
    // ==================================================================
    #[test]
    fn is_element_activatable_true_and_false_cases() {
        let layouts = fixture();
        for (node, expected, why) in [
            (
                button(&layouts),
                true,
                "a <button> is inherently activatable",
            ),
            (anchor(&layouts), true, "an <a> is inherently activatable"),
            (
                clickable_p(&layouts),
                true,
                "a click callback grants activation behaviour",
            ),
            (
                role_only(&layouts),
                true,
                "the CheckButton a11y role grants activation behaviour",
            ),
            (
                div(&layouts),
                false,
                "a plain <div> has no activation behaviour",
            ),
            (body(&layouts), false, "the root <body> is not activatable"),
            (textarea(&layouts), false, "a text input is not activatable"),
            (
                disabled(&layouts),
                false,
                "an Unavailable control is not activatable",
            ),
        ] {
            assert_eq!(is_element_activatable(&node, &layouts), expected, "{why}");
        }
    }
    #[test]
    fn is_element_activatable_rejects_every_unresolvable_node_id() {
        let layouts = fixture();
        let empty: BTreeMap<DomId, DomLayoutResult> = BTreeMap::new();
        for node in [missing_dom(), out_of_bounds_node(), null_node(), max_node()] {
            assert!(!is_element_activatable(&node, &layouts));
        }
        // A valid id, but no layout results at all.
        assert!(!is_element_activatable(&button(&layouts), &empty));
        assert!(!is_element_activatable(&dom_node(0), &empty));
    }
    // ==================================================================
    // is_text_input
    // ==================================================================
    #[test]
    fn is_text_input_true_and_false_cases() {
        let layouts = fixture();
        for (node, expected, why) in [
            (
                textarea(&layouts),
                true,
                "a Focus(TextInput) callback marks a text input",
            ),
            (
                anchor(&layouts),
                true,
                "even an <a> counts if it has a TextInput callback",
            ),
            (button(&layouts), false, "a <button> is not a text input"),
            (div(&layouts), false, "a plain <div> is not a text input"),
            (body(&layouts), false, "the root <body> is not a text input"),
            (
                clickable_p(&layouts),
                false,
                "a non-TextInput callback must not be mistaken for a text input",
            ),
            (
                disabled(&layouts),
                false,
                "a disabled control is not a text input",
            ),
        ] {
            assert_eq!(is_text_input(&node, &layouts), expected, "{why}");
        }
    }
    #[test]
    fn is_text_input_rejects_every_unresolvable_node_id() {
        let layouts = fixture();
        let empty: BTreeMap<DomId, DomLayoutResult> = BTreeMap::new();
        for node in [missing_dom(), out_of_bounds_node(), null_node(), max_node()] {
            assert!(!is_text_input(&node, &layouts));
        }
        assert!(!is_text_input(&textarea(&layouts), &empty));
        assert!(!is_text_input(&dom_node(0), &empty));
    }
    #[test]
    fn predicates_are_pure_and_never_both_wrong_for_the_body_root() {
        let layouts = fixture();
        let root = body(&layouts);
        assert_eq!(
            is_element_activatable(&root, &layouts),
            is_element_activatable(&root, &layouts)
        );
        assert_eq!(
            is_text_input(&root, &layouts),
            is_text_input(&root, &layouts)
        );
        assert!(!is_element_activatable(&root, &layouts));
        assert!(!is_text_input(&root, &layouts));
    }
    // ==================================================================
    // default_action_to_focus_target
    // ==================================================================
    /// Every `DefaultAction` variant, so the mapping test cannot silently miss
    /// a newly added one.
    fn all_default_actions() -> Vec<DefaultAction> {
        let node = dom_node(1);
        let mut v = vec![
            DefaultAction::FocusNext,
            DefaultAction::FocusPrevious,
            DefaultAction::FocusFirst,
            DefaultAction::FocusLast,
            DefaultAction::FocusUp,
            DefaultAction::FocusDown,
            DefaultAction::FocusLeft,
            DefaultAction::FocusRight,
            DefaultAction::ClearFocus,
            DefaultAction::ActivateFocusedElement { target: node },
            DefaultAction::SubmitForm { form_node: node },
            DefaultAction::CloseModal { modal_node: node },
            DefaultAction::SelectAllText,
            DefaultAction::None,
        ];
        for direction in [
            ScrollDirection::Up,
            ScrollDirection::Down,
            ScrollDirection::Left,
            ScrollDirection::Right,
        ] {
            for amount in [
                ScrollAmount::Line,
                ScrollAmount::Page,
                ScrollAmount::Document,
            ] {
                v.push(scroll(direction, amount));
            }
        }
        v
    }
    #[test]
    fn focus_actions_map_to_their_focus_target() {
        for (action, target) in [
            (DefaultAction::FocusNext, FocusTarget::Next),
            (DefaultAction::FocusPrevious, FocusTarget::Previous),
            (DefaultAction::FocusFirst, FocusTarget::First),
            (DefaultAction::FocusLast, FocusTarget::Last),
            (
                DefaultAction::FocusUp,
                FocusTarget::Directional(FocusDirection::Up),
            ),
            (
                DefaultAction::FocusDown,
                FocusTarget::Directional(FocusDirection::Down),
            ),
            (
                DefaultAction::FocusLeft,
                FocusTarget::Directional(FocusDirection::Left),
            ),
            (
                DefaultAction::FocusRight,
                FocusTarget::Directional(FocusDirection::Right),
            ),
            (DefaultAction::ClearFocus, FocusTarget::NoFocus),
        ] {
            assert_eq!(default_action_to_focus_target(&action), Some(target));
        }
    }
    /// Each D-pad direction asks for the matching spatial move, and nothing
    /// else on the pad asks for anything.
    #[test]
    fn the_dpad_drives_spatial_focus_and_the_rest_of_the_pad_does_not() {
        use azul_core::gamepad::GamepadButton;
        for (button, want) in [
            (GamepadButton::DPadUp, DefaultAction::FocusUp),
            (GamepadButton::DPadDown, DefaultAction::FocusDown),
            (GamepadButton::DPadLeft, DefaultAction::FocusLeft),
            (GamepadButton::DPadRight, DefaultAction::FocusRight),
        ] {
            assert_eq!(determine_gamepad_default_action(button.bit()), want);
        }
        // Nothing pressed asks for nothing.
        assert_eq!(determine_gamepad_default_action(0), DefaultAction::None);
        // The face buttons are deliberately unbound: "A activates" is a
        // platform convention (it is B on Nintendo layouts), not a fact.
        for button in [
            GamepadButton::South,
            GamepadButton::East,
            GamepadButton::North,
            GamepadButton::West,
        ] {
            assert_eq!(
                determine_gamepad_default_action(button.bit()),
                DefaultAction::None,
                "{button:?} must not move focus",
            );
        }
    }
    /// A diagonal must still move, rather than answering "nothing" at the
    /// moment the user is moving fastest.
    #[test]
    fn a_diagonal_dpad_press_resolves_to_one_direction() {
        use azul_core::gamepad::GamepadButton;
        let up_right = GamepadButton::DPadUp.bit() | GamepadButton::DPadRight.bit();
        assert_eq!(
            determine_gamepad_default_action(up_right),
            DefaultAction::FocusUp,
        );
        let down_left = GamepadButton::DPadDown.bit() | GamepadButton::DPadLeft.bit();
        assert_eq!(
            determine_gamepad_default_action(down_left),
            DefaultAction::FocusDown,
        );
    }
    #[test]
    fn mapping_is_some_exactly_for_focus_actions() {
        for action in all_default_actions() {
            let is_focus_action = matches!(
                action,
                DefaultAction::FocusNext
                    | DefaultAction::FocusPrevious
                    | DefaultAction::FocusFirst
                    | DefaultAction::FocusLast
                    | DefaultAction::FocusUp
                    | DefaultAction::FocusDown
                    | DefaultAction::FocusLeft
                    | DefaultAction::FocusRight
                    | DefaultAction::ClearFocus
            );
            let mapped = default_action_to_focus_target(&action);
            assert_eq!(
                mapped.is_some(),
                is_focus_action,
                "{action:?} must map to a FocusTarget iff it is a focus action"
            );
            // Non-focus actions (activation, scrolling, ...) must never be
            // turned into a focus move.
            if !is_focus_action {
                assert_eq!(mapped, None);
            }
        }
    }
    #[test]
    fn mapping_is_injective_over_the_focus_actions() {
        let mapped: Vec<FocusTarget> = all_default_actions()
            .iter()
            .filter_map(default_action_to_focus_target)
            .collect();
        assert_eq!(
            mapped.len(),
            9,
            "nine actions move focus: next/previous/first/last, the four directional ones, and \
             clear",
        );
        let mut deduped = mapped.clone();
        deduped.sort();
        deduped.dedup();
        assert_eq!(
            deduped.len(),
            mapped.len(),
            "two different focus actions must not collapse onto the same FocusTarget"
        );
    }
    #[test]
    fn mapping_is_usable_in_a_const_context() {
        const NEXT: Option<FocusTarget> = default_action_to_focus_target(&DefaultAction::FocusNext);
        const NOTHING: Option<FocusTarget> =
            default_action_to_focus_target(&DefaultAction::SelectAllText);
        assert_eq!(NEXT, Some(FocusTarget::Next));
        assert_eq!(NOTHING, None);
    }
    // ==================================================================
    // Round trip: key press -> DefaultAction -> FocusTarget
    // ==================================================================
    #[test]
    fn key_presses_round_trip_through_to_the_focus_manager() {
        let layouts = fixture();
        let focus = Some(button(&layouts));
        for (key, mods, expected) in [
            (VirtualKeyCode::Tab, &[][..], Some(FocusTarget::Next)),
            (
                VirtualKeyCode::Tab,
                &[VirtualKeyCode::LShift][..],
                Some(FocusTarget::Previous),
            ),
            (
                VirtualKeyCode::Home,
                &[VirtualKeyCode::LControl][..],
                Some(FocusTarget::First),
            ),
            (
                VirtualKeyCode::End,
                &[VirtualKeyCode::LControl][..],
                Some(FocusTarget::Last),
            ),
            (VirtualKeyCode::Escape, &[][..], Some(FocusTarget::NoFocus)),
            // Not a focus action: activation must not reach the focus manager.
            (VirtualKeyCode::Return, &[][..], None),
            (VirtualKeyCode::PageDown, &[][..], None),
        ] {
            let action =
                determine_keyboard_default_action(&kbd(key, mods), focus, &layouts, false).action;
            assert_eq!(
                default_action_to_focus_target(&action),
                expected,
                "{key:?} + {mods:?} round-trips to the wrong FocusTarget"
            );
        }
    }
    #[test]
    fn a_prevented_key_press_never_reaches_the_focus_manager() {
        let layouts = fixture();
        for key in ALL_KEYS {
            for mods in MOD_SETS {
                let action = determine_keyboard_default_action(
                    &kbd(*key, mods),
                    Some(button(&layouts)),
                    &layouts,
                    true,
                )
                .action;
                assert_eq!(
                    default_action_to_focus_target(&action),
                    None,
                    "{key:?} was prevented, so focus must not move"
                );
            }
        }
    }
}