crcbl-ui 0.2.1

Crucible immediate-mode GUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
//! Focus, keyboard and gamepad navigation, and the engaged state:
//! UI rung 6.
//!
//! # One focused node per tree
//!
//! A [`Ui`] is one UI context and holds at most one focused node. A node takes
//! part through the [`Behavior`] its builder declares
//! ([`Ui::block_with`]): a [`Role::Button`] or [`Role::Engage`] node is
//! focusable unless it opts out, a plain block is not unless it opts in, and a
//! `disabled` node never is. Like hover, focus is resolved when a frame begins,
//! against the tree the previous frame built — so a node built for the first
//! time is focusable from the frame after.
//!
//! # The frame's navigation input
//!
//! [`Ui::begin_frame_with`] takes a [`NavInput`]: one directional step, the
//! tree-order steps, accept, back, the context menu's key, a [`Jump`] inside
//! an open pop-up, and which kind of device spoke last. The
//! tree reads no device; the caller maps its own input to these, which is what
//! lets this rung land before `crcbl-input` has the context stack the plan's
//! reserved `ui_*` actions need.
//!
//! **The mixed-input rule**: in [`InputMode::Pointer`] the pointer's hover sets
//! `:hover` and focus sets nothing; in [`InputMode::Navigation`] focus sets
//! `:focus` and hover sets nothing — so a stylesheet's focus ring shows only
//! while the pad or the keyboard is driving. Focus itself is kept in both: a
//! click focuses what it clicked, so the pad continues from there. When the
//! pad speaks and nothing is focused, focus lands — on the most recently
//! focused node still in the tree, else the node under the pointer, else the
//! first focusable node in tree order, all inside an open modal and preferring
//! the modal's remembered node to the pointer's — and the press that landed it
//! moves nothing further.
//!
//! # Moves
//!
//! A direction goes, in order of precedence, where the focused node's
//! `nav-up`/`nav-right`/`nav-down`/`nav-left` names (`none` stays put), else
//! where the beam-first spatial search in `spatial.rs` lands. That search is
//! **clamped**: it looks first inside the innermost scope root, `overflow:
//! scroll` container or `nav-wrap` container around the focused node, and only
//! when nothing lies that way inside does it widen to the next one out — or,
//! for a `nav-wrap` container, wrap round to the far side of its content on
//! that axis — scrolled out of view or not. A [`Scope::Modal`] is never
//! widened past. [`NavInput::next`] and
//! [`NavInput::prev`] walk every focusable node in tree order, wrapping at the
//! ends, inside the modal when there is one: the always-works fallback.
//!
//! # Scopes
//!
//! **Each scope root remembers the last node focused inside it**, and a
//! directional move that enters a scope from outside resumes at that node
//! rather than at the geometric winner — provided the remembered node lies in
//! the direction pressed as well, so memory never sends focus backwards. The topmost [`Scope::Modal`] in paint
//! order traps focus: focus outside it is pulled in, a click outside it
//! focuses nothing, and no move leaves it. When the modal goes, the landing
//! rule's history returns focus to what was focused before it opened. A
//! pop-up's root is a modal in a layer above the tree, so it is the topmost
//! while it is open; `popup.rs` has how it hands focus back.
//!
//! **An `overflow: scroll` block scrolls the focused node into view**: its
//! offset moves the least that puts the node's border box inside the block's
//! content box — the block's padding is the margin a focus ring is drawn in —
//! clamped to how far its content reaches. A node [`Ui::set_focus`] asks for
//! is scrolled into view at that frame's [`Ui::layout`] already, so it is
//! drawn in view in the frame that asked rather than the frame after.
//!
//! # Focused and engaged (LOCKED)
//!
//! Focus never captures navigation. A [`Role::Engage`] node starts consuming it
//! only once engaged, by a click or by accept while focused. While it is
//! engaged every directional and tree-order step is handed to it
//! ([`Response::captured`]) instead of moving focus, and a [`Jump`] does
//! nothing; accept, or a click
//! anywhere outside it, **commits**; back **cancels**. One node per context is
//! engaged, and engaging another commits the first in the same frame. The
//! engaged node has `:engaged`. [`Ui::snapshot`] is the widget's half of the
//! contract: called every frame with the value the widget edits, it keeps a
//! copy when engagement begins and writes it back on a cancel. A
//! [`Role::Button`] has no engaged state: accept fires it through the same
//! [`Response::clicked`] a click does.
//!
//! **One exception: a drag-value being typed into takes no tree-order step.**
//! [`NavInput::next`] and [`NavInput::prev`] — Tab and Shift+Tab — commit it
//! and move focus in tree order as they would from a node not engaged, and
//! when focus lands on another drag-value, engage that one, which opens it for
//! typing (`widgets/number_entry.rs`): a vector row's axes are typed one after
//! another as a spreadsheet's cells are. Anywhere else the step only moves
//! focus, so Tab out of the last number of a run leaves it.
//!
//! # Tree nodes take left and right
//!
//! The one exception to moves going where the layout says: a focused
//! [`Ui::tree_node`] row answers left and right as the WAI-ARIA Authoring
//! Practices' tree view pattern does — right opens a closed node and moves to
//! an open one's first child, left closes an open node and moves from a child
//! to its parent. Where the pattern says a key "does nothing" — right on an
//! end node, left on a root that is closed or an end node, or right on an open
//! node with no child built — the move goes where the layout says instead, so
//! arrowing never stops dead on a tree.
//!
//! A context menu's items take them the same way: right on an item with a
//! submenu opens it, and left inside a submenu closes it, focus going back to
//! its item (`widgets/context_menu.rs`).

mod debug;
pub mod spatial;
#[cfg(test)]
mod tests;

use std::any::Any;
use std::collections::HashSet;

use glam::Vec2;

use super::store::NodeKey;
use super::style::{NavTarget, Overflow};
use super::{Response, Ui};

pub use debug::{NAV_DEBUG_BEAM, NAV_DEBUG_CHOSEN, NAV_DEBUG_OUTSIDE, NAV_DEBUG_PATH};
pub use spatial::Score;

/// How many recently focused nodes a tree keeps, for landing focus again when
/// the focused node goes and for the debug overlay's history.
pub const FOCUS_HISTORY: usize = 16;

/// A direction a move goes in, on screen: Y down.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Direction {
    /// Toward the top of the screen.
    Up,
    /// Toward the right.
    Right,
    /// Toward the bottom.
    Down,
    /// Toward the left.
    Left,
}

impl Direction {
    /// All four, clockwise from up.
    pub const ALL: [Self; 4] = [Self::Up, Self::Right, Self::Down, Self::Left];

    /// Whether the move runs along the horizontal axis.
    #[must_use]
    pub const fn is_horizontal(self) -> bool {
        matches!(self, Self::Left | Self::Right)
    }
}

/// Which kind of device spoke last: what decides whether hover or focus is
/// shown. See the module docs' mixed-input rule.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum InputMode {
    /// A mouse or a finger: `:hover` is set, `:focus` is not.
    #[default]
    Pointer,
    /// A keyboard or a pad: `:focus` is set, `:hover` is not.
    Navigation,
}

/// One frame's navigation input, in the vocabulary of the plan's reserved UI
/// actions. Every field is this frame's edge — a held key repeats by the caller
/// sending it again — so the default is no input at all, from a pointer.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct NavInput {
    /// Which kind of device spoke last.
    pub mode: InputMode,
    /// `ui_move`: one step in a direction.
    pub direction: Option<Direction>,
    /// `ui_next`: forward in tree order.
    pub next: bool,
    /// `ui_prev`: backward in tree order.
    pub prev: bool,
    /// `ui_accept`: fire a button, engage a widget, or commit the engaged one.
    pub accept: bool,
    /// `ui_back`: cancel the engaged widget, or else [`Ui::back_requested`].
    pub back: bool,
    /// `ui_menu`: open the focused widget's context menu
    /// ([`Ui::context_menu`]), as the keyboard's menu key and Shift+F10 do.
    pub menu: bool,
    /// The `list` context's Home, End, Page Up and Page Down: a jump inside
    /// the topmost open pop-up (`popup_nav.rs`).
    pub jump: Option<Jump>,
}

impl NavInput {
    /// A step in `direction`, from the pad or the keyboard.
    #[must_use]
    pub const fn toward(direction: Direction) -> Self {
        Self {
            direction: Some(direction),
            ..Self::NAVIGATION
        }
    }

    /// A jump inside the topmost open pop-up, from the keyboard.
    #[must_use]
    pub const fn jumping(jump: Jump) -> Self {
        Self {
            jump: Some(jump),
            ..Self::NAVIGATION
        }
    }

    /// No press, with the pad or the keyboard the last to speak.
    pub const NAVIGATION: Self = Self {
        mode: InputMode::Navigation,
        direction: None,
        next: false,
        prev: false,
        accept: false,
        back: false,
        menu: false,
        jump: None,
    };

    /// `ui_next`, from the pad or the keyboard.
    pub const NEXT: Self = Self {
        next: true,
        ..Self::NAVIGATION
    };

    /// `ui_prev`, from the pad or the keyboard.
    pub const PREV: Self = Self {
        prev: true,
        ..Self::NAVIGATION
    };

    /// `ui_accept`, from the pad or the keyboard.
    pub const ACCEPT: Self = Self {
        accept: true,
        ..Self::NAVIGATION
    };

    /// `ui_back`, from the pad or the keyboard.
    pub const BACK: Self = Self {
        back: true,
        ..Self::NAVIGATION
    };

    /// `ui_menu`, from the keyboard.
    pub const MENU: Self = Self {
        menu: true,
        ..Self::NAVIGATION
    };

    /// Whether a move, a step, a jump or accept was pressed: anything but
    /// `back` and `menu`, which act on focus where it is.
    const fn steers(self) -> bool {
        self.direction.is_some() || self.next || self.prev || self.accept || self.jump.is_some()
    }

    /// The step an engaged node would take from this input.
    const fn step(self) -> Option<NavStep> {
        match (self.direction, self.next, self.prev) {
            (Some(direction), _, _) => Some(NavStep::Move(direction)),
            (None, true, _) => Some(NavStep::Next),
            (None, false, true) => Some(NavStep::Prev),
            (None, false, false) => None,
        }
    }
}

/// Where a jump inside an open pop-up goes: the `list` context's keys. See
/// `popup_nav.rs`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Jump {
    /// Home: the first item focus can rest on.
    First,
    /// End: the last item focus can rest on.
    Last,
    /// Page Up: a view's height up.
    PageUp,
    /// Page Down: a view's height down.
    PageDown,
}

/// A navigation step an engaged node took instead of focus.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NavStep {
    /// A direction.
    Move(Direction),
    /// Forward in tree order.
    Next,
    /// Backward in tree order.
    Prev,
}

/// What a node is, to focus.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Role {
    /// A plain block: not focusable unless it opts in, and accept fires it as
    /// a click when it does.
    #[default]
    None,
    /// Instant activation: focusable, and accept fires it as a click.
    Button,
    /// A widget that edits a value: focusable, and engaged by a click or by
    /// accept before it takes navigation.
    Engage,
}

/// Whether a node is a focus scope root.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Scope {
    /// Not a scope.
    #[default]
    None,
    /// A pane or window: moves search inside it first, and it remembers the
    /// node last focused inside it.
    Root,
    /// As `Root`, and it traps focus while it is in the tree.
    Modal,
}

/// How a node takes part in focus; see the module docs.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Behavior {
    /// What it is.
    pub role: Role,
    /// `Some` to opt in or out of focus; `None` for its role's default.
    pub focusable: Option<bool>,
    /// Never focusable, never fired or engaged, and `:disabled`.
    pub disabled: bool,
    /// Whether it is a scope root.
    pub scope: Scope,
}

impl Behavior {
    /// A plain block.
    pub const NONE: Self = Self {
        role: Role::None,
        focusable: None,
        disabled: false,
        scope: Scope::None,
    };

    /// A button.
    pub const BUTTON: Self = Self {
        role: Role::Button,
        ..Self::NONE
    };

    /// A widget with an engaged state.
    pub const ENGAGE: Self = Self {
        role: Role::Engage,
        ..Self::NONE
    };

    /// A pane: a scope root.
    pub const SCOPE: Self = Self {
        scope: Scope::Root,
        ..Self::NONE
    };

    /// A modal: a scope root that traps focus.
    pub const MODAL: Self = Self {
        scope: Scope::Modal,
        ..Self::NONE
    };

    /// Whether focus can rest on the node.
    #[must_use]
    pub const fn is_focusable(self) -> bool {
        let wanted = match self.focusable {
            Some(wanted) => wanted,
            None => !matches!(self.role, Role::None),
        };
        wanted && !self.disabled
    }
}

/// Where a node's engagement is, this frame.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Engagement {
    /// Not engaged.
    #[default]
    Idle,
    /// Engaged from this frame: the moment to snapshot.
    Began,
    /// Engaged since an earlier frame.
    Engaged,
    /// Engagement ended this frame, keeping the value.
    Committed,
    /// Engagement ended this frame, and the value goes back to the snapshot.
    Cancelled,
}

impl Engagement {
    /// Whether the node is engaged this frame: `:engaged` is set.
    #[must_use]
    pub const fn is_engaged(self) -> bool {
        matches!(self, Self::Began | Self::Engaged)
    }
}

/// One candidate a directional move scored, for the debug overlay and for a
/// test asking why focus went where it did.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct NavScore {
    /// The candidate.
    pub key: NodeKey,
    /// Its score.
    pub score: Score,
    /// Whether the move landed on it.
    pub chosen: bool,
}

/// The value an engaged widget copied when it engaged.
struct Snapshot {
    key: NodeKey,
    value: Box<dyn Any + Send + Sync>,
}

impl std::fmt::Debug for Snapshot {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Snapshot")
            .field("key", &self.key)
            .finish_non_exhaustive()
    }
}

/// A tree's focus: what is focused and engaged, and what the last frame's
/// navigation did.
#[derive(Debug, Default)]
pub(crate) struct FocusState {
    focused: Option<NodeKey>,
    engaged: Option<NodeKey>,
    snapshot: Option<Snapshot>,
    pub mode: InputMode,
    back: bool,
    /// Newest last, at most [`FOCUS_HISTORY`] long, no key twice in a row.
    history: Vec<NodeKey>,
    scores: Vec<NavScore>,
    pub debug: bool,
    /// What [`Ui::set_focus`] asked for, applied when the next frame begins.
    requested: Option<NodeKey>,
    /// A node [`Ui::engage`] took the engagement from, for the next frame to
    /// report [`Engagement::Committed`] on.
    displaced: Option<NodeKey>,
    /// Nodes whose `nav-*` id was already reported as matching nothing.
    warned: HashSet<NodeKey>,
}

/// What one frame's resolution did to engagement, for writing into the nodes.
#[derive(Default)]
struct Events {
    ended: Option<(NodeKey, Engagement)>,
    began: Option<NodeKey>,
    captured: Option<NavStep>,
    activated: Option<NodeKey>,
}

impl Ui {
    /// Whether `key` is in last frame's tree, focusable, and drawn.
    pub(super) fn can_focus(&self, key: NodeKey) -> bool {
        self.store
            .by_key(key)
            .is_some_and(|node| node.hittable && node.behavior.is_focusable())
    }

    /// Whether `key` is `region` or inside it; everything is inside no region.
    pub(super) fn inside(&self, key: NodeKey, region: Option<NodeKey>) -> bool {
        region.is_none_or(|region| self.store.is_within(key, region))
    }

    /// The topmost modal scope in last frame's tree.
    pub(super) fn active_modal(&self) -> Option<NodeKey> {
        self.store
            .iter()
            .filter(|node| node.hittable && node.behavior.scope == Scope::Modal)
            .max_by_key(|node| node.stacking())
            .map(|node| node.key)
    }

    /// Every focusable node inside `region`, in tree order.
    pub(super) fn focusable_in(&self, region: Option<NodeKey>) -> Vec<NodeKey> {
        let mut nodes: Vec<_> = self
            .store
            .iter()
            .filter(|node| node.hittable && node.behavior.is_focusable())
            .filter(|node| self.inside(node.key, region))
            .map(|node| (node.paint_order, node.key))
            .collect();
        nodes.sort_unstable_by_key(|(order, _)| *order);
        nodes.into_iter().map(|(_, key)| key).collect()
    }

    /// Resolves this frame's focus and engagement from `nav` and the click the
    /// pointer made, then writes the result into every stored node. Runs after
    /// the pointer is resolved, before anything is built.
    ///
    /// A click that ended a drag — `dragged` — focuses what it clicked without
    /// engaging it: the drag already was the engagement. A text input is the
    /// exception, and engages: its drag selected text to type over or copy.
    pub(super) fn resolve_navigation(
        &mut self,
        nav: NavInput,
        clicked: Option<NodeKey>,
        dragged: bool,
    ) {
        self.focus.mode = nav.mode;
        self.focus.back = false;
        self.focus.scores.clear();
        // A snapshot outlives its engagement by the one frame that reported the
        // end, for the widget to read it back in.
        if self
            .focus
            .snapshot
            .as_ref()
            .is_some_and(|held| Some(held.key) != self.focus.engaged)
        {
            self.focus.snapshot = None;
        }
        if self.focus.engaged.is_some_and(|key| {
            !self.can_focus(key)
                || self.store.by_key(key).map(|node| node.behavior.role) != Some(Role::Engage)
        }) {
            self.focus.engaged = None;
        }
        // Back closes the topmost pop-up before anything reads the modal it
        // was or the focus it held; see `popup.rs`.
        let nav = self.back_out_of_popup(nav);
        if self.focus.focused.is_some_and(|key| !self.can_focus(key)) {
            self.focus.focused = None;
        }

        let modal = self.active_modal();
        let mut events = Events::default();

        // `Ui::engage` took the engagement between frames; the node it took it
        // from hears about it here, as a click elsewhere would have told it.
        if let Some(displaced) = self.focus.displaced.take()
            && self.focus.engaged != Some(displaced)
        {
            events.ended = Some((displaced, Engagement::Committed));
        }

        // A request stands in for a click on the node it names.
        if let Some(requested) = self.focus.requested.take()
            && self.can_focus(requested)
            && self.inside(requested, modal)
        {
            if let Some(engaged) = self.focus.engaged
                && engaged != requested
            {
                self.focus.engaged = None;
                events.ended = Some((engaged, Engagement::Committed));
            }
            self.move_focus(requested);
        }

        if let Some(clicked) = clicked {
            if let Some(engaged) = self.focus.engaged
                && !self.store.is_within(clicked, engaged)
            {
                self.focus.engaged = None;
                events.ended = Some((engaged, Engagement::Committed));
            }
            let target = self
                .store
                .ancestry(Some(clicked))
                .into_iter()
                .find(|&key| self.can_focus(key));
            if let Some(target) = target
                && self.inside(target, modal)
            {
                self.move_focus(target);
                let (engages, selects) = self.store.by_key(target).map_or((false, false), |node| {
                    (node.behavior.role == Role::Engage, node.widget.types())
                });
                if engages && (!dragged || selects) && self.focus.engaged != Some(target) {
                    self.focus.engaged = Some(target);
                    events.began = Some(target);
                }
            }
        }

        let outside_modal = modal.is_some()
            && self
                .focus
                .focused
                .is_none_or(|focused| !self.inside(focused, modal));
        let landing = outside_modal
            || (self.focus.focused.is_none()
                && (nav.mode == InputMode::Navigation || nav.steers()));
        let spent = landing && self.land(modal) && nav.steers();

        if let Some(engaged) = self.focus.engaged {
            if nav.accept && events.began != Some(engaged) {
                self.focus.engaged = None;
                events.ended = Some((engaged, Engagement::Committed));
            } else if nav.back {
                self.focus.engaged = None;
                events.ended = Some((engaged, Engagement::Cancelled));
            } else if let Some(forward) = tab(nav.step())
                && self
                    .store
                    .by_key(engaged)
                    .is_some_and(|node| node.widget.is_typed_number())
            {
                self.focus.engaged = None;
                events.ended = Some((engaged, Engagement::Committed));
                self.move_in_tree_order(forward, modal);
                if let Some(next) = self.focus.focused
                    && next != engaged
                    && self.store.by_key(next).is_some_and(|node| {
                        node.behavior.role == Role::Engage && node.widget.is_drag_value()
                    })
                {
                    self.focus.engaged = Some(next);
                    events.began = Some(next);
                }
            } else {
                events.captured = nav.step();
            }
        } else {
            if nav.back {
                self.focus.back = true;
            }
            if !spent {
                if let Some(direction) = nav.direction {
                    let before = self.focus.focused;
                    if !self.tree_item_step(direction) && !self.submenu_step(direction) {
                        self.move_spatially(direction, modal);
                    }
                    if !direction.is_horizontal() && before != self.focus.focused {
                        self.vertical_focus_move = before.zip(self.focus.focused);
                    }
                } else if nav.next || nav.prev {
                    self.move_in_tree_order(nav.next, modal);
                } else if let Some(jump) = nav.jump {
                    self.jump_in_popup(jump);
                }
                if nav.accept
                    && let Some(focused) = self.focus.focused
                {
                    let role = self.store.by_key(focused).map(|node| node.behavior.role);
                    if role == Some(Role::Engage) {
                        self.focus.engaged = Some(focused);
                        events.began = Some(focused);
                    } else {
                        events.activated = Some(focused);
                    }
                }
            }
        }

        let FocusState {
            focused, engaged, ..
        } = self.focus;
        for node in self.store.iter_mut() {
            let key = node.key;
            let interaction = &mut node.interaction;
            interaction.focused = focused == Some(key);
            interaction.engagement = match events.ended {
                Some((ended, how)) if ended == key => how,
                _ if events.began == Some(key) => Engagement::Began,
                _ if engaged == Some(key) => Engagement::Engaged,
                _ => Engagement::Idle,
            };
            interaction.captured = events.captured.filter(|_| engaged == Some(key));
            if events.activated == Some(key) {
                interaction.clicked = true;
            }
        }
    }

    /// Lands focus inside `region`: on the newest node in the history still
    /// there, else the scope's remembered node, else the focusable node under
    /// the pointer, else the first in tree order. Returns whether focus moved.
    fn land(&mut self, region: Option<NodeKey>) -> bool {
        let usable = |ui: &Self, key: NodeKey| ui.can_focus(key) && ui.inside(key, region);
        let from_history = self
            .focus
            .history
            .iter()
            .rev()
            .copied()
            .find(|&key| usable(self, key));
        let remembered = region
            .and_then(|region| self.store.by_key(region))
            .and_then(|node| node.remembered)
            .filter(|&key| usable(self, key));
        let hovered = self
            .store
            .iter()
            .filter(|node| node.interaction.hovered && node.behavior.is_focusable())
            .max_by_key(|node| node.stacking())
            .map(|node| node.key)
            .filter(|&key| usable(self, key));
        let target = from_history
            .or(remembered)
            .or(hovered)
            .or_else(|| self.focusable_in(region).first().copied());
        match target {
            Some(target) if self.focus.focused != Some(target) => {
                self.move_focus(target);
                true
            }
            _ => false,
        }
    }

    /// Focuses `key`: remembers it in every scope around it, records it in the
    /// history, and scrolls it into view.
    pub(super) fn move_focus(&mut self, key: NodeKey) {
        if self.focus.focused == Some(key) {
            return;
        }
        self.focus.focused = Some(key);
        for scope in self.store.ancestry(Some(key)) {
            if let Some(slot) = self.store.find(scope) {
                let node = self.store.get_mut(slot);
                if node.behavior.scope != Scope::None {
                    node.remembered = Some(key);
                }
            }
        }
        let history = &mut self.focus.history;
        history.retain(|&held| held != key);
        history.push(key);
        if history.len() > FOCUS_HISTORY {
            history.remove(0);
        }
        self.scroll_into_view(key);
    }

    /// Moves every `overflow: scroll` block around `key` the least that puts
    /// its border box inside the block's content box, clamped to the block's
    /// reach, and says whether any moved.
    pub(super) fn scroll_into_view(&mut self, key: NodeKey) -> bool {
        let Some(node) = self.store.by_key(key) else {
            return false;
        };
        let mut moved = false;
        let (mut min, mut max) = node.rect;
        for ancestor in self.store.ancestry(Some(key)).into_iter().skip(1) {
            let Some(slot) = self.store.find(ancestor) else {
                continue;
            };
            let container = self.store.get_mut(slot);
            if container.resolved.overflow != Overflow::Scroll {
                continue;
            }
            let view = container.content_box();
            let mut delta = Vec2::ZERO;
            for axis in 0..2 {
                if min[axis] < view.0[axis] {
                    delta[axis] = min[axis] - view.0[axis];
                } else if max[axis] > view.1[axis] {
                    // A node taller than the view keeps its start in sight.
                    delta[axis] = (max[axis] - view.1[axis]).min(min[axis] - view.0[axis]);
                }
            }
            let before = container.scroll_offset;
            let after = (before + delta).clamp(Vec2::ZERO, container.scroll_max.max(Vec2::ZERO));
            container.scroll_offset = after;
            let applied = after - before;
            moved |= applied != Vec2::ZERO;
            min -= applied;
            max -= applied;
        }
        moved
    }

    /// A directional move from the focused node; see the module docs.
    fn move_spatially(&mut self, direction: Direction, modal: Option<NodeKey>) {
        let Some(from) = self.focus.focused else {
            return;
        };
        let Some(current) = self.store.by_key(from) else {
            return;
        };
        match current.resolved.nav(direction) {
            NavTarget::Auto => {}
            NavTarget::None => return,
            NavTarget::Id(id) => {
                let target = self
                    .focusable_in(modal)
                    .into_iter()
                    .find(|&key| self.store.by_key(key).and_then(|node| node.id) == Some(id));
                if let Some(target) = target {
                    self.move_focus(target);
                    return;
                }
                if self.focus.warned.insert(from) {
                    let selector = current
                        .candidates
                        .as_ref()
                        .map_or("", |held| held.selector.as_str());
                    crcbl_core::warn!(
                        "ui tree: `{selector}`'s nav-{} names an id no focusable node has; the \
                         move searches instead",
                        match direction {
                            Direction::Up => "up",
                            Direction::Right => "right",
                            Direction::Down => "down",
                            Direction::Left => "left",
                        }
                    );
                }
            }
        }

        let origin = current.rect;
        let candidates: Vec<(NodeKey, (Vec2, Vec2))> = self
            .focusable_in(modal)
            .into_iter()
            .filter_map(|key| self.store.by_key(key).map(|node| (key, node.rect)))
            .collect();
        let mut scored: Vec<NavScore> = Vec::new();
        let mut record = |found: &[(NodeKey, Score)]| {
            for &(key, score) in found {
                if !scored.iter().any(|held| held.key == key) {
                    scored.push(NavScore {
                        key,
                        score,
                        chosen: false,
                    });
                }
            }
        };

        // Innermost first: every scope root, scroll container and wrapping
        // container around the focused node, then the whole tree.
        let mut target = None;
        let mut regions: Vec<Option<NodeKey>> = self
            .store
            .ancestry(Some(from))
            .into_iter()
            .skip(1)
            .filter(|&key| {
                self.store.by_key(key).is_some_and(|node| {
                    node.behavior.scope != Scope::None
                        || node.resolved.overflow == Overflow::Scroll
                        || node.resolved.nav_wrap.wraps(direction.is_horizontal())
                })
            })
            .map(Some)
            .collect();
        regions.push(None);
        for region in regions {
            let inside: Vec<_> = candidates
                .iter()
                .copied()
                .filter(|&(key, _)| key != from && self.inside(key, region))
                .collect();
            let (found, scores) = spatial::pick(origin, inside, direction);
            record(&scores);
            target = found;
            let node = region.and_then(|region| self.store.by_key(region));
            if target.is_none()
                && let Some(node) = node
                && node.resolved.nav_wrap.wraps(direction.is_horizontal())
            {
                // The content's extent, not the box's: a scrolled list wraps
                // to its first item, not to the first one in view.
                let content = (
                    node.rect.0 - node.scroll_offset,
                    node.rect.1 + (node.scroll_max - node.scroll_offset).max(Vec2::ZERO),
                );
                let shifted = wrapped(origin, content, direction);
                let around: Vec<_> = candidates
                    .iter()
                    .copied()
                    .filter(|&(key, _)| self.inside(key, region))
                    .collect();
                let (found, scores) = spatial::pick(shifted, around, direction);
                record(&scores);
                target = found.filter(|&key| key != from);
            }
            if target.is_some() || node.is_some_and(|node| node.behavior.scope == Scope::Modal) {
                break;
            }
        }

        if let Some(found) = target {
            let target = self.remembered_on_entry(from, found, origin, direction);
            for score in &mut scored {
                score.chosen = score.key == target;
            }
            self.focus.scores = scored;
            self.move_focus(target);
        } else {
            self.focus.scores = scored;
        }
    }

    /// `target`, or — when it lies in scopes `from` is not in — the node the
    /// outermost of those scopes remembers, if it is still focusable there and
    /// lies in `direction` from `origin` too, so a remembered node never pulls
    /// focus against the press.
    fn remembered_on_entry(
        &self,
        from: NodeKey,
        target: NodeKey,
        origin: (Vec2, Vec2),
        direction: Direction,
    ) -> NodeKey {
        let entered = self
            .store
            .ancestry(Some(target))
            .into_iter()
            .skip(1)
            .rfind(|&scope| {
                self.store
                    .by_key(scope)
                    .is_some_and(|node| node.behavior.scope != Scope::None)
                    && !self.store.is_within(from, scope)
            });
        entered
            .and_then(|scope| {
                let remembered = self.store.by_key(scope)?.remembered?;
                let ahead = self
                    .store
                    .by_key(remembered)
                    .is_some_and(|node| spatial::score(origin, node.rect, direction).is_some());
                (ahead && self.can_focus(remembered) && self.store.is_within(remembered, scope))
                    .then_some(remembered)
            })
            .unwrap_or(target)
    }

    /// A tree-order step: forward when `forward`, wrapping at the ends.
    fn move_in_tree_order(&mut self, forward: bool, modal: Option<NodeKey>) {
        let order = self.focusable_in(modal);
        if order.is_empty() {
            return;
        }
        let at = self
            .focus
            .focused
            .and_then(|focused| order.iter().position(|&key| key == focused));
        let next = match (at, forward) {
            (Some(at), true) => (at + 1) % order.len(),
            (Some(at), false) => (at + order.len() - 1) % order.len(),
            (None, true) => 0,
            (None, false) => order.len() - 1,
        };
        self.move_focus(order[next]);
    }

    // -- the public surface ---------------------------------------------------

    /// The focused node, in either input mode.
    #[must_use]
    pub fn focused(&self) -> Option<NodeKey> {
        self.focus.focused
    }

    /// Focuses `key` when the next frame begins, committing the engaged node
    /// there if it is another — unless `key` is not a focusable node of the
    /// tree that frame is resolved against, or lies outside an open modal,
    /// which leaves focus where it is.
    ///
    /// Asked for while a frame is built, `key` is scrolled into view at that
    /// frame's [`Ui::layout`], ahead of the focus: a drop-down opening on its
    /// chosen option draws it in view in the frame it opens.
    pub fn set_focus(&mut self, key: NodeKey) {
        self.focus.requested = Some(key);
    }

    /// Scrolls the node [`Ui::set_focus`] asked for into view, as last placed,
    /// and says whether anything moved — so the caller places the tree again.
    pub(super) fn reveal_requested(&mut self) -> bool {
        let Some(key) = self.focus.requested else {
            return false;
        };
        self.store.by_key(key).is_some_and(|node| node.hittable) && self.scroll_into_view(key)
    }

    /// Takes focus and engagement away from the tree entirely, leaving nothing
    /// focused: what a caller calls when input has gone somewhere the tree
    /// knows nothing about.
    ///
    /// **A click the tree cannot focus does not do this**, and cannot: the
    /// pointer resolution finds no focusable node in that click's ancestry, so
    /// focus stays where it was — which is right for a click on a panel's own
    /// background and wrong for one on an application's viewport, where the
    /// keyboard has genuinely left the panel. The application is the only thing
    /// that can tell those two apart, so it is the one that says so.
    ///
    /// The engaged node is **committed**, exactly as a click on another node
    /// commits it: the next frame reports it [`Engagement::Committed`], so a
    /// text input keeps what was typed rather than cancelling back.
    pub fn clear_focus(&mut self) {
        self.focus.focused = None;
        if let Some(engaged) = self.focus.engaged.take() {
            self.focus.displaced = Some(engaged);
        }
    }

    /// Focuses and engages `key` **now**, for the frames that follow: what a
    /// screen that is always editing calls, where a click would have done it.
    ///
    /// Engagement is taken immediately rather than requested for the next
    /// frame, unlike [`Ui::set_focus`], and that is the point of it: the next
    /// frame's resolution finds the node already engaged and reports
    /// [`Engagement::Engaged`] rather than [`Engagement::Began`], so
    /// [`Ui::text_input`] takes that frame's edits — an input engaged only on
    /// the `Began` frame deliberately takes none. The debug console's prompt is
    /// engaged for as long as the console is open, and a frame of typing
    /// swallowed each time a click landed elsewhere in the panel is what this
    /// avoids.
    ///
    /// **It engages nothing** unless `key` is a focusable, drawn node of the
    /// tree as last laid out whose [`Behavior`] role is [`Role::Engage`]:
    /// engagement is a contract a widget keeps, and a node that is not one has
    /// nothing to keep it. Whatever was engaged before is displaced, and
    /// reports [`Engagement::Committed`] when the next frame resolves, which is
    /// what a click elsewhere would have given it.
    pub fn engage(&mut self, key: NodeKey) {
        if !self.can_focus(key)
            || self.store.by_key(key).map(|node| node.behavior.role) != Some(Role::Engage)
        {
            return;
        }
        self.focus.requested = Some(key);
        if self.focus.engaged == Some(key) {
            return;
        }
        self.focus.displaced = self.focus.engaged;
        self.focus.engaged = Some(key);
    }

    /// The engaged node.
    #[must_use]
    pub fn engaged(&self) -> Option<NodeKey> {
        self.focus.engaged
    }

    /// Which kind of device this frame's input says spoke last.
    #[must_use]
    pub fn input_mode(&self) -> InputMode {
        self.focus.mode
    }

    /// Whether back was pressed this frame with nothing engaged to cancel: the
    /// caller's to close a modal or pop a screen with.
    #[must_use]
    pub fn back_requested(&self) -> bool {
        self.focus.back
    }

    /// The nodes focused most recently, oldest first; see [`FOCUS_HISTORY`].
    #[must_use]
    pub fn focus_history(&self) -> &[NodeKey] {
        &self.focus.history
    }

    /// Every candidate the frame's directional move scored, in tree order, the
    /// one it landed on marked. Empty on a frame with no directional move.
    #[must_use]
    pub fn nav_scores(&self) -> &[NavScore] {
        &self.focus.scores
    }

    /// The widget's half of the engaged contract, called every frame with the
    /// node's `response` and the value it edits: on [`Engagement::Began`] a copy
    /// of `value` is kept, on [`Engagement::Cancelled`] the copy is written back
    /// into `value`, and on [`Engagement::Committed`] it is dropped.
    ///
    /// A cancel that finds a copy of another type — the widget passed a
    /// different `T` from the one it engaged with — leaves `value` alone and
    /// logs a warning.
    pub fn snapshot<T: Clone + Send + Sync + 'static>(
        &mut self,
        response: &Response,
        value: &mut T,
    ) {
        self.snapshot_for(response.key, response.engagement, value);
    }

    /// The copy [`Ui::snapshot`] holds for `key`, if it holds one and it is a
    /// `T`: what a widget that changes how it edits partway through an
    /// engagement reads, to put back what the engagement began with.
    pub(super) fn snapshot_of<T: Clone + 'static>(&self, key: NodeKey) -> Option<T> {
        self.focus
            .snapshot
            .as_ref()
            .filter(|held| held.key == key)
            .and_then(|held| held.value.downcast_ref::<T>())
            .cloned()
    }

    /// [`Ui::snapshot`] for the node `key`, engaged as `engagement` says: for a
    /// widget that restores its value before it builds the node.
    pub(super) fn snapshot_for<T: Clone + Send + Sync + 'static>(
        &mut self,
        key: NodeKey,
        engagement: Engagement,
        value: &mut T,
    ) {
        match engagement {
            Engagement::Began => {
                self.focus.snapshot = Some(Snapshot {
                    key,
                    value: Box::new(value.clone()),
                });
            }
            Engagement::Cancelled | Engagement::Committed => {
                let Some(held) = self.focus.snapshot.take_if(|held| held.key == key) else {
                    return;
                };
                if engagement == Engagement::Committed {
                    return;
                }
                match held.value.downcast::<T>() {
                    Ok(copy) => *value = *copy,
                    Err(_) => crcbl_core::warn!(
                        "ui tree: an engaged widget cancelled with a value of another type than \
                         it engaged with; its value is left as it is"
                    ),
                }
            }
            Engagement::Idle | Engagement::Engaged => {}
        }
    }
}

/// Which way a tree-order step goes: forward for [`NavStep::Next`], back for
/// [`NavStep::Prev`]; none for any other step.
const fn tab(step: Option<NavStep>) -> Option<bool> {
    match step {
        Some(NavStep::Next) => Some(true),
        Some(NavStep::Prev) => Some(false),
        _ => None,
    }
}

/// `origin` moved to just before `container`'s start along a move in
/// `direction`, so that a search from it finds what lies first inside the
/// container that way.
fn wrapped(origin: (Vec2, Vec2), container: (Vec2, Vec2), direction: Direction) -> (Vec2, Vec2) {
    let (min, max) = origin;
    let shift = match direction {
        Direction::Right => Vec2::new(container.0.x - max.x, 0.0),
        Direction::Left => Vec2::new(container.1.x - min.x, 0.0),
        Direction::Down => Vec2::new(0.0, container.0.y - max.y),
        Direction::Up => Vec2::new(0.0, container.1.y - min.y),
    };
    (min + shift, max + shift)
}