kui-core 0.1.0-alpha.45

kui contract: flat per-frame tree, clay-style flex layout, text stack, events as data, quad display list
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
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
//! Keyboard focus as data (`docs/adr/0002-keyboard-focus-as-data.md`): one
//! focus for every node, Tab walking every control in tree order, Enter /
//! Space pressing the focused one, arrows nudging a slider, a ring the
//! core draws for keyboard focus (or the node's `focus_bg`), `disabled`
//! nodes inert and skipped, and assistive technology landing on the same
//! focus a Tab press moves — and, on top of it,
//! `docs/adr/0003-modal-surfaces.md`: a modal surface containing focus,
//! making everything outside it inert, and asking to be dismissed.

use kui_core::testing::{click_at, tab};
use kui_core::{
    AccessAction, AccessRequest, Align, Color, Core, EditKey, EditOptions, FloatConfig, InputEvent,
    Key, Mods, NodeSpec, Role, Size, TextStyle, UiEvent, Value, Vec2, WindowButton,
};

const H: f32 = 20.0;

/// The keys of the frame's nodes, in tree order.
struct Keys {
    go: Key,
    save: Key,
    mute: Key,
    vol: Key,
    off: Key,
    hidden: Key,
    row: Key,
    name: Key,
    pane: Key,
    styled: Key,
}

const FOCUS_BG: Color = Color {
    r: 1.0,
    g: 0.0,
    b: 1.0,
    a: 1.0,
};

/// Thirteen rows of height `H`, so row `n` is centred at `y = n * H + 10`:
/// a titlebar with a close button (chrome), a heading, a button, an icon
/// button, a switch, a slider, a disabled button, a button inside
/// decoration, a plain box, a `focusable` row, an editor, a key sink and a
/// button with its own `focus_bg`. Repeating the frame repeats the
/// declaration on the sink when `declare_pane` says so.
fn frame(core: &mut Core, declare_pane: bool, autofocus_edit: bool) -> Keys {
    let mut ui = core.frame(Size::new(200.0, 300.0), 1.0);
    ui.window_title("Focus");
    ui.configure_root(NodeSpec::column().fill());
    let row = || NodeSpec::row().size(100.0, H);
    ui.with_keyed("titlebar", row().window_drag(), |ui| {
        ui.leaf_keyed(
            "close",
            NodeSpec::row()
                .size(H, H)
                .window_button(WindowButton::Close),
        );
    });
    ui.text_in_keyed(
        "heading",
        row().role(Role::Heading),
        "Controls",
        TextStyle::new(12.0),
    );
    let go = ui.text_in_keyed("go", row().on_click("go"), "Go", TextStyle::new(12.0));
    let save = ui.leaf_keyed("save", row().on_click("save").label("Save"));
    let mute = ui.leaf_keyed(
        "mute",
        row()
            .role(Role::Switch)
            .checked(true)
            .on_click("mute")
            .label("Mute"),
    );
    let vol = ui.leaf_keyed(
        "vol",
        row()
            .role(Role::Slider)
            .on_drag("vol")
            .label("Volume")
            .value_now(3.0)
            .value_min(0.0)
            .value_max(10.0),
    );
    let off = ui.leaf_keyed(
        "off",
        row()
            .on_click("nope")
            .disabled(true)
            .hover_bg(Color::WHITE)
            .label("Off"),
    );
    let mut hidden = Key::ROOT;
    ui.with_keyed("deco", row().role(Role::None), |ui| {
        hidden = ui.leaf_keyed("hidden", NodeSpec::row().size(H, H).on_click("hidden"));
    });
    ui.leaf_keyed("plain", row());
    let row_key = ui.leaf_keyed("row", row().focusable().label("Row"));
    let name = ui.text_edit(
        "name",
        "hi",
        &EditOptions {
            autofocus: autofocus_edit,
            ..Default::default()
        },
        row().label("Name"),
    );
    let pane = ui.leaf_keyed("pane", row().on_key("pane"));
    if declare_pane {
        ui.take_key_focus(pane);
    }
    let styled = ui.leaf_keyed(
        "styled",
        row().on_click("styled").bg(Color::BLACK).focus_bg(FOCUS_BG),
    );
    ui.finish();
    Keys {
        go,
        save,
        mute,
        vol,
        off,
        hidden,
        row: row_key,
        name,
        pane,
        styled,
    }
}

fn key(core: &mut Core, k: EditKey) -> Vec<UiEvent> {
    core.handle_input(InputEvent::Key(k, Mods::default()))
}

fn payloads(evs: &[UiEvent]) -> Vec<String> {
    evs.iter()
        .map(|e| match e.payload.as_str() {
            Some(s) => s.to_string(),
            None => format!(
                "{}:{}",
                e.kind().unwrap_or("?"),
                e.payload.get_str("action").unwrap_or("")
            ),
        })
        .collect()
}

/// The default focus ring: a transparent quad with a 2px border, on top.
fn ring_count(core: &mut Core) -> usize {
    core.output()
        .0
        .quads
        .iter()
        .filter(|q| q.color.a == 0.0 && q.border_w == 2.0 && q.border_color.a > 0.0)
        .count()
}

#[test]
fn tab_walks_every_control_in_tree_order_and_wraps() {
    let mut core = Core::new();
    let k = frame(&mut core, false, false);
    assert_eq!(core.focus(), None);
    let ring = [k.go, k.save, k.mute, k.vol, k.row, k.name, k.pane];
    let mut seen = Vec::new();
    for _ in 0..ring.len() {
        tab(&mut core, false);
        seen.push(core.focus().unwrap());
    }
    assert_eq!(
        seen, ring,
        "chrome, the heading, the disabled button, decoration and plain boxes are not stops"
    );
    assert!(core.focus_visible(), "keyboard focus shows");
    assert!(!seen.contains(&k.off) && !seen.contains(&k.hidden));

    // A sink owns Tab; the app hands focus on with focus_next.
    tab(&mut core, false);
    assert_eq!(core.focus(), Some(k.pane), "a key sink keeps Tab");
    core.focus_next(true);
    assert_eq!(core.focus(), Some(k.styled));
    assert!(core.is_focused(k.styled) && core.key_focus() == Some(k.styled));

    // Wrapping, both ways; the editor mirrors into the edit store.
    tab(&mut core, false);
    assert_eq!(core.focus(), Some(k.go));
    tab(&mut core, true);
    assert_eq!(core.focus(), Some(k.styled));
    core.set_focus(Some(k.name));
    assert_eq!(core.edit.focused(), Some(k.name));
    tab(&mut core, true);
    assert_eq!(core.focus(), Some(k.row));
    assert_eq!(core.edit.focused(), None);
}

/// `Ui::focus_next` / `focus_prev` defer to `finish`, because a view is
/// still declaring the tree the Tab ring is made of. So a view that has
/// never rendered can still step onto a control it is declaring — where
/// `Core::focus_next`, which walks the last finished tree, has nothing.
#[test]
fn a_view_steps_focus_onto_the_frame_it_is_declaring() {
    let build = |core: &mut Core, step: Option<bool>| {
        let mut ui = core.frame(Size::new(200.0, 200.0), 1.0);
        match step {
            Some(true) => ui.focus_next(),
            Some(false) => ui.focus_prev(),
            None => {}
        }
        for name in ["a", "b", "c"] {
            ui.leaf_keyed(name, NodeSpec::row().focusable().size(100.0, H));
        }
        ui.finish();
    };
    let root = Key::ROOT;
    let (a, c) = (root.str("a"), root.str("c"));

    // The very first frame: nothing has been laid out, so an immediate
    // step has no ring at all and the deferred one still lands.
    let mut immediate = Core::new();
    {
        let mut ui = immediate.frame(Size::new(200.0, 200.0), 1.0);
        ui.core().focus_next(true);
        for name in ["a", "b", "c"] {
            ui.leaf_keyed(name, NodeSpec::row().focusable().size(100.0, H));
        }
        ui.finish();
    }
    assert_eq!(immediate.focus(), None, "no ring to walk mid-build");

    let mut core = Core::new();
    build(&mut core, Some(true));
    assert_eq!(core.focus(), Some(a), "the deferred step found the ring");

    // And it beats a `set_focus` made in the same frame — the step is the
    // later word, applied once the frame it belongs to is whole.
    {
        let mut ui = core.frame(Size::new(200.0, 200.0), 1.0);
        ui.focus(a);
        ui.focus_prev();
        for name in ["a", "b", "c"] {
            ui.leaf_keyed(name, NodeSpec::row().focusable().size(100.0, H));
        }
        ui.finish();
    }
    assert_eq!(core.focus(), Some(c), "stepped back from a, wrapping");

    // Only the last request of a frame is kept, and it is not held for a
    // later frame once applied.
    build(&mut core, None);
    assert_eq!(core.focus(), Some(c), "no step, no move");
}

#[test]
fn enter_and_space_press_the_focused_control() {
    let mut core = Core::new();
    let k = frame(&mut core, false, false);
    core.set_focus(Some(k.go));
    assert_eq!(payloads(&key(&mut core, EditKey::Enter)), ["go"]);
    assert_eq!(
        payloads(&core.handle_input(InputEvent::Text(" ".into()))),
        ["go"]
    );
    core.set_focus(Some(k.mute));
    assert_eq!(
        payloads(&core.handle_input(InputEvent::Text(" ".into()))),
        ["mute"]
    );
    // The focusable row has no payload: reachable, nothing to press.
    core.set_focus(Some(k.row));
    assert!(key(&mut core, EditKey::Enter).is_empty());
    // An editor keeps Enter and Space as text; a sink takes every key as
    // data and is never "pressed".
    core.set_focus(Some(k.name));
    assert!(
        key(&mut core, EditKey::Enter)
            .iter()
            .all(|e| e.payload.get_str("kind") == Some("submit"))
    );
    core.set_focus(Some(k.pane));
    assert!(key(&mut core, EditKey::Enter).is_empty());
    assert!(core.handle_input(InputEvent::Text(" ".into())).is_empty());
    // Escape lets go of a control.
    core.set_focus(Some(k.go));
    key(&mut core, EditKey::Escape);
    assert_eq!(core.focus(), None);
}

#[test]
fn arrows_nudge_a_focused_slider_like_assistive_technology_does() {
    let mut core = Core::new();
    let k = frame(&mut core, false, false);
    core.set_focus(Some(k.vol));
    let up = key(&mut core, EditKey::Right);
    assert_eq!(payloads(&up), ["access:increment"]);
    assert_eq!(up[0].key, k.vol);
    assert_eq!(up[0].payload.get_str("tag"), Some("vol"));
    assert_eq!(payloads(&key(&mut core, EditKey::Up)), ["access:increment"]);
    assert_eq!(
        payloads(&key(&mut core, EditKey::Left)),
        ["access:decrement"]
    );
    assert_eq!(
        payloads(&key(&mut core, EditKey::Down)),
        ["access:decrement"]
    );
    // The same request from a reader yields the same event.
    let req = core.handle_input(InputEvent::Access(AccessRequest::new(
        k.vol,
        AccessAction::Increment,
    )));
    assert_eq!(payloads(&req), ["access:increment"]);
    // Arrows on a button are nothing.
    core.set_focus(Some(k.go));
    assert!(key(&mut core, EditKey::Right).is_empty());
}

#[test]
fn keyboard_focus_draws_a_ring_and_pointer_focus_does_not() {
    let mut core = Core::new();
    let k = frame(&mut core, false, false);
    assert_eq!(ring_count(&mut core), 0);
    tab(&mut core, false);
    assert_eq!(core.focus(), Some(k.go));
    frame(&mut core, false, false);
    assert_eq!(
        ring_count(&mut core),
        1,
        "Tab onto the button draws the ring"
    );
    let ring = core
        .output()
        .0
        .quads
        .iter()
        .find(|q| q.color.a == 0.0 && q.border_w == 2.0)
        .copied()
        .unwrap();
    // Two px outside the 100×20 button on row 2.
    assert_eq!(
        (ring.rect.x, ring.rect.y, ring.rect.w, ring.rect.h),
        (-2.0, 2.0 * H - 2.0, 104.0, H + 4.0)
    );

    // A click on the same button keeps focus there but hides the ring.
    click_at(&mut core, 50.0, 2.0 * H + 10.0);
    assert_eq!(core.focus(), Some(k.go));
    assert!(!core.focus_visible());
    frame(&mut core, false, false);
    assert_eq!(ring_count(&mut core), 0);

    // Editors and sinks draw no ring: the caret and the app show focus.
    core.set_focus(Some(k.name));
    tab(&mut core, false);
    assert_eq!(core.focus(), Some(k.pane));
    frame(&mut core, false, false);
    assert_eq!(ring_count(&mut core), 0);
    core.focus_next(false);
    assert_eq!(core.focus(), Some(k.name));
    frame(&mut core, false, false);
    assert_eq!(ring_count(&mut core), 0);
}

#[test]
fn focus_bg_swaps_the_background_instead_of_a_ring() {
    let mut core = Core::new();
    let k = frame(&mut core, false, false);
    let styled_quad = |core: &mut Core| {
        core.output()
            .0
            .quads
            .iter()
            .find(|q| q.rect.y == 12.0 * H && q.rect.h == H)
            .copied()
            .unwrap()
    };
    assert_eq!(styled_quad(&mut core).color, Color::BLACK);
    tab(&mut core, true);
    assert_eq!(core.focus(), Some(k.styled));
    frame(&mut core, false, false);
    assert_eq!(styled_quad(&mut core).color, FOCUS_BG);
    assert_eq!(ring_count(&mut core), 0, "a focus_bg node gets no ring");
    // Pointer focus is not keyboard-visible: plain bg again.
    click_at(&mut core, 50.0, 12.0 * H + 10.0);
    frame(&mut core, false, false);
    assert_eq!(styled_quad(&mut core).color, Color::BLACK);
}

#[test]
fn disabled_nodes_are_inert_and_say_so() {
    let mut core = Core::new();
    let k = frame(&mut core, false, false);
    // No click from the pointer, Enter, Space or a reader; no focus.
    assert!(click_at(&mut core, 50.0, 6.0 * H + 10.0).is_empty());
    assert_eq!(
        core.focus(),
        None,
        "a press on a disabled node takes no focus"
    );
    core.set_focus(Some(k.off));
    assert!(key(&mut core, EditKey::Enter).is_empty());
    assert!(core.handle_input(InputEvent::Text(" ".into())).is_empty());
    assert!(
        core.handle_input(InputEvent::Access(AccessRequest::new(
            k.off,
            AccessAction::Click
        )))
        .is_empty()
    );
    // Hover styling stays off; the hit region (for a tooltip) stays.
    core.handle_input(InputEvent::CursorMoved(Vec2::new(50.0, 6.0 * H + 10.0)));
    assert!(core.is_hovered(k.off));
    frame(&mut core, false, false);
    let off_quad = core
        .output()
        .0
        .quads
        .iter()
        .find(|q| q.rect.y == 6.0 * H && q.rect.h == H)
        .copied();
    assert!(
        off_quad.is_none(),
        "no hover_bg swap: the node stays unpainted"
    );
    // The access tree reports it, without click or focus actions.
    let tree = core.access_tree();
    let off = tree.get(k.off).unwrap();
    assert!(off.disabled);
    assert!(!off.supports(AccessAction::Click));
    assert!(!off.supports(AccessAction::Focus));
    let go = tree.get(k.go).unwrap();
    assert!(!go.disabled);
    assert!(go.supports(AccessAction::Click) && go.supports(AccessAction::Focus));
}

#[test]
fn assistive_technology_focuses_what_tab_would() {
    let mut core = Core::new();
    let k = frame(&mut core, false, false);
    // Every control advertises focus; structure does not.
    let tree = core.access_tree().clone();
    for key in [k.go, k.save, k.mute, k.vol, k.row, k.name, k.pane, k.styled] {
        let n = tree.get(key).unwrap();
        assert!(
            n.supports(AccessAction::Focus) && n.supports(AccessAction::Blur),
            "{:?} advertises focus",
            n.role
        );
        assert!(!n.focused);
    }
    assert_eq!(tree.focus, None);
    let close = tree.get(Key::ROOT.str("titlebar").str("close")).unwrap();
    assert!(
        !close.supports(AccessAction::Focus),
        "chrome is not a Tab stop"
    );

    core.handle_input(InputEvent::Access(AccessRequest::new(
        k.mute,
        AccessAction::Focus,
    )));
    assert_eq!(core.focus(), Some(k.mute));
    assert!(core.focus_visible(), "a reader's focus shows like Tab's");
    let tree = core.access_tree();
    assert_eq!(tree.focus, Some(k.mute));
    assert!(tree.get(k.mute).unwrap().focused);

    // Tab continues from there; the tree follows.
    tab(&mut core, false);
    assert_eq!(core.access_tree().focus, Some(k.vol));

    // Blur only when it is the focused node; a request on structure does
    // nothing.
    core.handle_input(InputEvent::Access(AccessRequest::new(
        k.go,
        AccessAction::Blur,
    )));
    assert_eq!(core.focus(), Some(k.vol));
    core.handle_input(InputEvent::Access(AccessRequest::new(
        k.hidden,
        AccessAction::Focus,
    )));
    assert_eq!(core.focus(), Some(k.vol));
    core.handle_input(InputEvent::Access(AccessRequest::new(
        k.vol,
        AccessAction::Blur,
    )));
    assert_eq!(core.focus(), None);
    assert_eq!(core.access_tree().focus, None);
}

#[test]
fn a_repeated_declaration_takes_focus_once() {
    let mut core = Core::new();
    let k = frame(&mut core, true, false);
    assert_eq!(core.focus(), Some(k.pane), "declared: focused");
    assert!(!core.focus_visible(), "programmatic focus shows no ring");
    // The app hands focus on; the next frame declares the sink again
    // and does not take it back.
    core.focus_next(true);
    assert_eq!(core.focus(), Some(k.styled));
    frame(&mut core, true, false);
    assert_eq!(core.focus(), Some(k.styled));
    // A frame that stops declaring, then one that declares again: an
    // edge, so the sink takes focus once more.
    frame(&mut core, false, false);
    assert_eq!(core.focus(), Some(k.styled));
    frame(&mut core, true, false);
    assert_eq!(core.focus(), Some(k.pane));
    // None blurs at once.
    core.set_key_focus(None);
    assert_eq!(core.focus(), None);
}

/// `autofocus` is an edge (`docs/adr/0022-focus-regions.md`, decision 9):
/// the editor takes focus on the frame its declaration starts, only while
/// nothing holds focus, and a blur afterwards stands — an app with an
/// autofocus field can have nothing focused. Turning the flag on for an
/// editor that already exists is an edge too, and so is coming back after
/// a frame without the editor.
#[test]
fn autofocus_is_an_edge_that_takes_the_keyboard_only_while_nothing_holds_it() {
    let mut core = Core::new();
    let k = frame(&mut core, false, true);
    assert_eq!(core.focus(), Some(k.name));
    assert_eq!(core.edit.focused(), Some(k.name));
    core.set_focus(Some(k.go));
    frame(&mut core, false, true);
    assert_eq!(core.focus(), Some(k.go), "a focused control keeps focus");
    assert_eq!(core.edit.focused(), None);
    core.set_focus(None);
    frame(&mut core, false, true);
    assert_eq!(core.focus(), None, "a blur stands: the flag asked once");
    // The flag turned off and on again is a new declaration.
    frame(&mut core, false, false);
    frame(&mut core, false, true);
    assert_eq!(core.focus(), Some(k.name), "an edge: autofocus takes it");
    // And it still never takes focus from something that holds it.
    core.set_focus(Some(k.go));
    frame(&mut core, false, false);
    frame(&mut core, false, true);
    assert_eq!(core.focus(), Some(k.go));
}

#[test]
fn a_press_moves_focus_to_what_it_hits() {
    let mut core = Core::new();
    let k = frame(&mut core, false, false);
    assert_eq!(payloads(&click_at(&mut core, 50.0, 2.0 * H + 10.0)), ["go"]);
    assert_eq!(core.focus(), Some(k.go));
    // The focusable row takes focus without emitting anything.
    assert!(click_at(&mut core, 50.0, 9.0 * H + 10.0).is_empty());
    assert_eq!(core.focus(), Some(k.row));
    // A plain box drops it.
    click_at(&mut core, 50.0, 8.0 * H + 10.0);
    assert_eq!(core.focus(), None);
    // An editor: focus and caret together.
    click_at(&mut core, 50.0, 10.0 * H + 10.0);
    assert_eq!(core.focus(), Some(k.name));
    assert_eq!(core.edit.focused(), Some(k.name));
    // Tab from the editor goes on to the sink, and the editor lets go.
    tab(&mut core, false);
    assert_eq!(core.focus(), Some(k.pane));
    assert_eq!(core.edit.focused(), None);
}

// -- Modal surfaces (docs/adr/0003-modal-surfaces.md) -----------------------

/// A window with chrome, a scrolling list of buttons behind, an editor,
/// and — when `dialog` says so — a floated modal holding a button and an
/// editor of its own. The viewport is 200x300; the background sits at the
/// top left, the modal at the bottom right.
struct Modal {
    open: Key,
    behind: Key,
    list: Key,
    note: Key,
    dialog: Key,
    ok: Key,
    reason: Key,
}

fn modal_frame(core: &mut Core, dialog: bool) -> Modal {
    let mut ui = core.frame(Size::new(200.0, 300.0), 1.0);
    ui.window_title("Modal");
    ui.configure_root(NodeSpec::column().fill());
    let row = || NodeSpec::row().size(100.0, H);
    ui.with_keyed("titlebar", row().window_drag(), |ui| {
        ui.leaf_keyed(
            "close",
            NodeSpec::row()
                .size(H, H)
                .window_button(WindowButton::Close),
        );
    });
    let open = ui.leaf_keyed("open", row().on_click("open").label("Open"));
    // A scroll container two rows tall holding four: it overflows, so it
    // has a scrollbar and somewhere for the wheel to go.
    let list = ui.with_keyed(
        "list",
        NodeSpec::column().size(100.0, 2.0 * H).scroll_y(),
        |ui| {
            for n in 0..4 {
                ui.leaf_keyed(["a", "b", "c", "d"][n], row().on_click("row").label("Row"));
            }
        },
    );
    let behind = Key::ROOT.str("list").str("a");
    let note = ui.text_edit("note", "hi", &EditOptions::default(), row().label("Note"));
    let mut ok = Key::ROOT;
    let mut reason = Key::ROOT;
    let mut dlg = Key::ROOT;
    if dialog {
        dlg = ui.with_keyed(
            "dialog",
            NodeSpec::column()
                .size(100.0, 3.0 * H)
                .float(FloatConfig::viewport().inside(Align::End, Align::End))
                .modal("dlg")
                .label("Settings"),
            |ui| {
                ok = ui.leaf_keyed("ok", row().on_click("ok").label("OK"));
                reason = ui.text_edit("reason", "", &EditOptions::default(), row().label("Reason"));
            },
        );
    }
    ui.finish();
    Modal {
        open,
        behind,
        list,
        note,
        dialog: dlg,
        ok,
        reason,
    }
}

/// The centre of the modal's OK button (bottom right, the modal's first
/// row), a point on the modal's own background under its two rows, and the
/// centre of the button behind it (top left).
const IN_MODAL: (f32, f32) = (150.0, 300.0 - 3.0 * H + H / 2.0);
const MODAL_BG: (f32, f32) = (150.0, 300.0 - H / 2.0);
const BEHIND: (f32, f32) = (50.0, H + H / 2.0);

#[test]
fn everything_outside_the_modal_is_inert() {
    let mut core = Core::new();
    let m = modal_frame(&mut core, true);
    assert_eq!(core.modal(), Some(m.dialog));

    // A press on the button behind emits its click payload no longer —
    // only the modal's dismiss — and does not move focus.
    let out = click_at(&mut core, BEHIND.0, BEHIND.1);
    assert_eq!(payloads(&out), ["dismiss:"], "no `open`, one dismiss");
    assert_eq!(out[0].payload.get_str("reason"), Some("outside"));
    assert_eq!(out[0].key, m.dialog);
    assert_eq!(core.focus(), Some(m.ok), "focus stays in the modal");

    // Hover and Enter / Space resolve against the same hit list, so both
    // are inert too.
    core.handle_input(InputEvent::CursorMoved(Vec2::new(BEHIND.0, BEHIND.1)));
    assert!(!core.is_hovered(m.open));
    core.set_focus(Some(m.open));
    assert!(key(&mut core, EditKey::Enter).is_empty());
    assert!(core.handle_input(InputEvent::Text(" ".into())).is_empty());
    // A reader's click on the button behind is the press outside: the
    // modal's dismiss and no `open`, as the pointer's above (backlog
    // RG13 — it used to be dropped).
    let out = core.handle_input(InputEvent::Access(AccessRequest::new(
        m.behind,
        AccessAction::Click,
    )));
    assert_eq!(payloads(&out), ["dismiss:"]);
    assert_eq!(out[0].key, m.dialog);

    // The wheel over the list behind does nothing; the modal's own
    // controls are live.
    let before = core.scroll.offset(m.list);
    core.handle_input(InputEvent::Scroll(Vec2::new(0.0, -30.0)));
    assert_eq!(core.scroll.offset(m.list), before, "the list stays put");
    assert_eq!(
        payloads(&click_at(&mut core, IN_MODAL.0, IN_MODAL.1)),
        ["ok"]
    );
    assert_eq!(core.focus(), Some(m.ok));

    // Without the modal, every one of those works again.
    let m = modal_frame(&mut core, false);
    assert_eq!(core.modal(), None);
    assert_eq!(payloads(&click_at(&mut core, BEHIND.0, BEHIND.1)), ["open"]);
    assert_eq!(core.focus(), Some(m.open));
    core.handle_input(InputEvent::CursorMoved(Vec2::new(50.0, 3.0 * H)));
    core.handle_input(InputEvent::Scroll(Vec2::new(0.0, -30.0)));
    assert!(core.scroll.offset(m.list).y > 0.0);
}

#[test]
fn window_chrome_stays_live_behind_a_modal() {
    let mut core = Core::new();
    let m = modal_frame(&mut core, true);
    // The close button is chrome: a press on it issues its window command
    // rather than a dismiss.
    let out = click_at(&mut core, H / 2.0, H / 2.0);
    assert!(payloads(&out).is_empty(), "chrome emits no app event");
    assert_eq!(core.take_window_commands().len(), 1, "the window closes");
    assert_eq!(core.focus(), Some(m.ok), "and focus stays in the modal");
}

#[test]
fn escape_asks_the_modal_to_go_away_and_does_nothing_else() {
    let mut core = Core::new();
    let m = modal_frame(&mut core, true);

    let out = key(&mut core, EditKey::Escape);
    assert_eq!(payloads(&out), ["dismiss:"]);
    assert_eq!(out[0].key, m.dialog);
    assert_eq!(out[0].payload.get_str("reason"), Some("escape"));
    assert_eq!(
        out[0].payload.get_str("tag"),
        Some("dlg"),
        "the modal's tag rides along"
    );
    assert_eq!(core.focus(), Some(m.ok), "Escape does not let go");

    // Not even from inside an editor in the dialog: the modal owns it.
    core.set_focus(Some(m.reason));
    let out = key(&mut core, EditKey::Escape);
    assert_eq!(payloads(&out), ["dismiss:"]);
    assert_eq!(core.focus(), Some(m.reason));
    assert_eq!(core.edit.focused(), Some(m.reason));

    // The core closed nothing — the app decides. Once it stops declaring
    // the dialog, Escape means what ADR 0002 gave it again.
    let m = modal_frame(&mut core, false);
    core.set_focus(Some(m.note));
    assert!(payloads(&key(&mut core, EditKey::Escape)).is_empty());
    assert_eq!(core.focus(), None);
}

#[test]
fn a_press_on_the_modal_itself_is_not_outside_it() {
    let mut core = Core::new();
    let m = modal_frame(&mut core, true);
    // The strip under the modal's two rows is its own background: a press
    // there is inside, so nothing is dismissed and nothing is emitted.
    let out = click_at(&mut core, MODAL_BG.0, MODAL_BG.1);
    assert!(payloads(&out).is_empty(), "{:?}", payloads(&out));
    assert_eq!(core.modal(), Some(m.dialog));
}

#[test]
fn a_modal_without_a_tag_still_dismisses() {
    let mut core = Core::new();
    let mut ui = core.frame(Size::new(200.0, 300.0), 1.0);
    ui.configure_root(NodeSpec::column().fill());
    let menu = ui.leaf_keyed(
        "menu",
        NodeSpec::column()
            .size(100.0, H)
            .float(FloatConfig::viewport())
            .modal(Value::Null)
            .label("Menu"),
    );
    ui.finish();
    let out = key(&mut core, EditKey::Escape);
    assert_eq!(out.len(), 1);
    assert_eq!(out[0].key, menu);
    assert_eq!(out[0].kind(), Some("dismiss"));
    assert_eq!(out[0].payload.get("tag"), None, "a null tag carries none");
}

#[test]
fn the_access_tree_reports_the_modal_and_derives_a_dialog() {
    let mut core = Core::new();
    let m = modal_frame(&mut core, true);
    let tree = core.access_tree().clone();
    let dlg = tree.get(m.dialog).unwrap();
    assert_eq!(dlg.role, Role::Dialog, "a modal box is a dialog");
    assert_eq!(dlg.name.as_deref(), Some("Settings"));
    assert!(dlg.modal, "aria-modal");
    assert_eq!(tree.focus, Some(m.ok), "the reader's cursor is inside it");
    // The background is still in the tree — the platform acts on the
    // modal flag — and nothing else claims to be modal.
    assert!(tree.get(m.open).is_some());
    assert_eq!(tree.nodes.iter().filter(|n| n.modal).count(), 1);
    let hash = tree.hash;

    // Without the modal, the flag is gone and the tree says so.
    modal_frame(&mut core, false);
    let tree = core.access_tree();
    assert!(!tree.nodes.iter().any(|n| n.modal));
    assert_ne!(tree.hash, hash);
}

/// A dialog is named by its `label` alone (it is not one of ARIA's
/// name-from-content roles), so an unlabelled one is announced as an
/// unnamed dialog — the `control-without-name` defect, on the node that
/// just took focus.
#[test]
fn a_modal_without_a_name_warns() {
    let dialog = |label: Option<&'static str>| {
        let mut core = Core::new();
        let mut ui = core.frame(Size::new(200.0, 300.0), 1.0);
        ui.configure_root(NodeSpec::column().fill());
        let mut spec = NodeSpec::column()
            .size(100.0, 2.0 * H)
            .float(FloatConfig::viewport())
            .modal("dlg");
        if let Some(label) = label {
            spec = spec.label(label);
        }
        let key = ui.with_keyed("dialog", spec, |ui| {
            // Text inside is not a name for a dialog, so it does not
            // silence the warning the way it would for a button.
            ui.text("Delete everything?", TextStyle::default());
        });
        ui.finish();
        (core.take_warnings(), key)
    };

    let (ws, key) = dialog(None);
    let named: Vec<_> = ws
        .iter()
        .filter(|w| w.code == kui_core::diag::MODAL_WITHOUT_NAME)
        .collect();
    assert_eq!(named.len(), 1);
    assert_eq!(named[0].key, key);
    assert!(named[0].message.contains("`label`"), "{}", named[0].message);

    let (ws, _) = dialog(Some("Confirm"));
    assert!(
        !ws.iter()
            .any(|w| w.code == kui_core::diag::MODAL_WITHOUT_NAME),
        "a labelled dialog says nothing: {ws:?}"
    );
}

#[test]
fn a_modal_that_is_not_floated_warns() {
    let mut core = Core::new();
    let mut ui = core.frame(Size::new(200.0, 300.0), 1.0);
    ui.configure_root(NodeSpec::column().fill());
    let sheet = ui.leaf_keyed(
        "sheet",
        NodeSpec::column()
            .size(100.0, H)
            .modal(Value::Null)
            .label("Sheet"),
    );
    ui.leaf_keyed("after", NodeSpec::row().height(H));
    ui.finish();
    let ws = core.take_warnings();
    let modal: Vec<_> = ws
        .iter()
        .filter(|w| w.code == kui_core::diag::MODAL_BEHIND_CONTENT)
        .collect();
    assert_eq!(modal.len(), 1);
    assert_eq!(modal[0].key, sheet);

    // Floated, it draws over everything and says nothing.
    let mut core = Core::new();
    modal_frame(&mut core, true);
    assert!(
        !core
            .take_warnings()
            .iter()
            .any(|w| w.code == kui_core::diag::MODAL_BEHIND_CONTENT)
    );
}

#[test]
fn a_scrollbar_behind_a_modal_is_drawn_but_not_grabbable() {
    let mut core = Core::new();
    let m = modal_frame(&mut core, true);
    // The list (x 0..100, y 2H..4H) overflows, so it has a vertical bar at
    // its right edge. A press low on the track would jump the offset there.
    let track = (99.0, 4.0 * H - 4.0);
    let out = click_at(&mut core, track.0, track.1);
    assert_eq!(
        core.scroll.offset(m.list).y,
        0.0,
        "the track press did nothing"
    );
    assert_eq!(
        payloads(&out),
        ["dismiss:"],
        "an inert bar is not a hit region: the press is outside the modal"
    );
    assert_eq!(core.focus(), Some(m.ok));

    // Without the modal the same press jumps the list.
    let m = modal_frame(&mut core, false);
    let out = click_at(&mut core, track.0, track.1);
    assert!(
        payloads(&out).is_empty(),
        "a scrollbar press is not a click"
    );
    assert!(
        core.scroll.offset(m.list).y > 0.0,
        "the track press scrolled"
    );
}

#[test]
fn a_float_declared_before_a_modal_paints_over_it_too() {
    // Floats paint after every in-flow node, so a float declared before
    // an in-flow modal still draws on top of it.
    let mut core = Core::new();
    let mut ui = core.frame(Size::new(200.0, 300.0), 1.0);
    ui.configure_root(NodeSpec::column().fill());
    ui.leaf_keyed(
        "hud",
        NodeSpec::row().size(50.0, H).float(FloatConfig::viewport()),
    );
    let sheet = ui.leaf_keyed(
        "sheet",
        NodeSpec::column()
            .size(100.0, H)
            .modal(Value::Null)
            .label("Sheet"),
    );
    ui.finish();
    let ws = core.take_warnings();
    let modal: Vec<_> = ws
        .iter()
        .filter(|w| w.code == kui_core::diag::MODAL_BEHIND_CONTENT)
        .collect();
    assert_eq!(modal.len(), 1);
    assert_eq!(modal[0].key, sheet);

    // A float inside the modal is the modal's own (a dropdown, a tooltip):
    // nothing paints over the modal, so nothing is said.
    let mut core = Core::new();
    let mut ui = core.frame(Size::new(200.0, 300.0), 1.0);
    ui.configure_root(NodeSpec::column().fill());
    ui.with_keyed(
        "sheet",
        NodeSpec::column()
            .size(100.0, H)
            .modal(Value::Null)
            .label("Sheet"),
        |ui| {
            ui.leaf_keyed(
                "menu",
                NodeSpec::row().size(50.0, H).float(FloatConfig::viewport()),
            );
        },
    );
    ui.finish();
    assert!(
        !core
            .take_warnings()
            .iter()
            .any(|w| w.code == kui_core::diag::MODAL_BEHIND_CONTENT)
    );
}

/// A draggable handle and a button at the top left, and — when `dialog`
/// says so — a floated modal at the bottom right.
fn drag_frame(core: &mut Core, dialog: bool) -> (Key, Key) {
    let mut ui = core.frame(Size::new(200.0, 300.0), 1.0);
    ui.configure_root(NodeSpec::column().fill());
    let row = || NodeSpec::row().size(100.0, H);
    let handle = ui.leaf_keyed("handle", row().on_drag("split"));
    let button = ui.leaf_keyed("button", row().on_click("go"));
    if dialog {
        ui.with_keyed(
            "dialog",
            NodeSpec::column()
                .size(100.0, H)
                .float(FloatConfig::viewport().inside(Align::End, Align::End))
                .modal(Value::Null)
                .label("Wait"),
            |ui| {
                ui.leaf_keyed("ok", row().on_click("ok"));
            },
        );
    }
    ui.finish();
    (handle, button)
}

fn drag_phases(evs: &[UiEvent]) -> Vec<String> {
    evs.iter()
        .filter(|e| e.kind() == Some("drag"))
        .map(|e| e.payload.get_str("phase").unwrap_or("?").to_string())
        .collect()
}

#[test]
fn a_drag_in_flight_when_a_modal_appears_still_ends() {
    // Pointer capture outlives the frame that raised the modal: the app
    // was told the drag started, so it is told the drag ended, and gets
    // the moves in between. Only a new press is inert.
    let mut core = Core::new();
    drag_frame(&mut core, false);
    let mut all = Vec::new();
    all.extend(core.handle_input(InputEvent::CursorMoved(Vec2::new(50.0, H / 2.0))));
    all.extend(core.handle_input(InputEvent::mouse_down(1)));
    all.extend(core.handle_input(InputEvent::CursorMoved(Vec2::new(60.0, H / 2.0))));
    assert_eq!(drag_phases(&all), ["start", "move"]);

    drag_frame(&mut core, true);
    let mut after = Vec::new();
    after.extend(core.handle_input(InputEvent::CursorMoved(Vec2::new(70.0, H / 2.0))));
    after.extend(core.handle_input(InputEvent::mouse_up()));
    assert_eq!(
        drag_phases(&after),
        ["move", "end"],
        "the capture runs to release"
    );
    assert!(
        !after.iter().any(|e| e.payload.as_str().is_some()),
        "and a release after a drag is not a click"
    );

    // The next press on the handle finds no region: no drag starts, the
    // modal is asked to go away instead.
    let out = click_at(&mut core, 50.0, H / 2.0);
    assert!(drag_phases(&out).is_empty());
    assert_eq!(payloads(&out), ["dismiss:"]);
}

#[test]
fn a_press_behind_released_after_a_modal_appears_is_not_a_click() {
    let mut core = Core::new();
    let (_, button) = drag_frame(&mut core, false);
    core.handle_input(InputEvent::CursorMoved(Vec2::new(50.0, H + H / 2.0)));
    core.handle_input(InputEvent::mouse_down(1));
    assert!(core.is_pressed(button));

    // The modal appears between press and release: the button behind is
    // no longer under the pointer as far as the hit list knows.
    drag_frame(&mut core, true);
    assert!(!core.is_hovered(button));
    let out = core.handle_input(InputEvent::mouse_up());
    assert!(payloads(&out).is_empty(), "{:?}", payloads(&out));
}

// -- The way out of a modal (backlog F4) -------------------------------------

/// The mind map's rename editor: a list of nodes, and — when `editing`
/// says so — a floated modal holding the editor. `focus_on` is the frame's
/// `keyFocus` declaration, the only way a data view has of saying where
/// the keyboard belongs.
fn rename_frame(
    core: &mut Core,
    nodes: &[&str],
    editing: bool,
    focus_on: Option<&str>,
) -> Vec<Key> {
    let mut ui = core.frame(Size::new(200.0, 300.0), 1.0);
    ui.configure_root(NodeSpec::column().fill());
    let row = || NodeSpec::row().size(100.0, H);
    let keys: Vec<Key> = nodes
        .iter()
        .map(|n| ui.leaf_keyed(n, row().focusable().label(*n)))
        .collect();
    if let Some(name) = focus_on {
        let i = nodes
            .iter()
            .position(|n| n == &name)
            .expect("a declared node");
        ui.take_key_focus(keys[i]);
    }
    if editing {
        ui.with_keyed(
            "rename",
            NodeSpec::column()
                .size(100.0, 2.0 * H)
                .float(FloatConfig::viewport().inside(Align::End, Align::End))
                .modal("rename")
                .label("Rename"),
            |ui| {
                ui.text_edit("field", "", &EditOptions::default(), row().label("Name"));
            },
        );
    }
    ui.finish();
    keys
}

#[test]
fn a_key_focus_edge_beats_the_focus_the_modal_gives_back() {
    // The report's case: a node is created and its rename editor opened in
    // one frame, so what the modal displaced is the node the user was on
    // *before* — and handing that back on the way out puts the next Enter
    // in the wrong place. The app says where focus lands by declaring it,
    // and the declaration wins (ADR 0003, decision 4).
    let mut core = Core::new();
    let k = rename_frame(&mut core, &["a"], false, Some("a"));
    let a = k[0];
    assert_eq!(core.focus(), Some(a));

    // `b` is created and the editor opened together: the modal remembers
    // `a`, and containment puts focus in the editor.
    let k = rename_frame(&mut core, &["a", "b"], true, None);
    let b = k[1];
    assert_eq!(core.focus(), Some(Key::ROOT.str("rename").str("field")));

    // The editor goes away and the app declares the new node focused.
    rename_frame(&mut core, &["a", "b"], false, Some("b"));
    assert_eq!(
        core.focus(),
        Some(b),
        "the edge stands, the restore is dropped"
    );
    assert_ne!(core.focus(), Some(a));
}

#[test]
fn a_modal_closing_over_no_edge_still_gives_the_focus_back() {
    // The other half, and the reason the rule is an *edge*: a view that
    // repeats `keyFocus` every frame — an app that owns its keyboard —
    // declares nothing new on the frame the modal drops, so decision 4 is
    // untouched and the focus the dialog displaced comes back.
    let mut core = Core::new();
    let k = rename_frame(&mut core, &["a", "b"], false, Some("a"));
    let a = k[0];
    core.set_focus(Some(k[1]));

    rename_frame(&mut core, &["a", "b"], true, Some("a"));
    assert_eq!(core.focus(), Some(Key::ROOT.str("rename").str("field")));
    rename_frame(&mut core, &["a", "b"], false, Some("a"));
    assert_eq!(core.focus(), Some(k[1]), "back where the editor found it");

    // And with no declaration at all, which is where it always landed.
    core.set_focus(Some(a));
    rename_frame(&mut core, &["a", "b"], true, None);
    rename_frame(&mut core, &["a", "b"], false, None);
    assert_eq!(core.focus(), Some(a));
}

/// AR17: F4's scenario through the door F4 did not cover. An app that
/// closes the dialog and *says* where focus lands — `set_focus` from the
/// dismissing handler, or `ui.focus` from the view that drops the modal
/// — got the pre-dialog node instead, because the restore yielded to a
/// `keyFocus` edge and a Tab step and nothing else. An imperative move
/// since the last frame is an edge too: three doors, one precedence.
#[test]
fn an_imperative_focus_beats_the_focus_the_modal_gives_back() {
    let mut core = Core::new();
    let k = rename_frame(&mut core, &["a", "b"], false, Some("a"));
    let (a, b) = (k[0], k[1]);
    rename_frame(&mut core, &["a", "b"], true, None);
    assert_eq!(core.focus(), Some(Key::ROOT.str("rename").str("field")));

    // The handler that closes the dialog names `b`, between frames.
    core.set_focus(Some(b));
    rename_frame(&mut core, &["a", "b"], false, None);
    assert_eq!(
        core.focus(),
        Some(b),
        "the app's move stands over the restore"
    );

    // The same from inside the view that drops the modal.
    core.set_focus(Some(a));
    rename_frame(&mut core, &["a", "b"], true, None);
    let mut ui = core.frame(Size::new(200.0, 300.0), 1.0);
    ui.configure_root(NodeSpec::column().fill());
    let row = || NodeSpec::row().size(100.0, H);
    ui.leaf_keyed("a", row().focusable().label("a"));
    ui.leaf_keyed("b", row().focusable().label("b"));
    ui.focus(b);
    ui.finish();
    assert_eq!(core.focus(), Some(b));

    // And a move the *core* made — a press inside the dialog, which is
    // pointer focus — is not the app saying anything: the restore lands
    // where it always has.
    core.set_focus(Some(a));
    rename_frame(&mut core, &["a", "b"], true, None);
    let field = Key::ROOT.str("rename").str("field");
    assert_eq!(core.focus(), Some(field));
    // The editor's own box, low right: a press on it moves nothing (it
    // already holds focus) — so press the editor after a Tab away first.
    // Simpler: the frame after, focus is the field's and the stamp is
    // spent; closing now restores `a`.
    rename_frame(&mut core, &["a", "b"], true, None);
    rename_frame(&mut core, &["a", "b"], false, None);
    assert_eq!(core.focus(), Some(a), "no app move since: the restore");
}

/// A click focuses without showing (pointer focus, ADR 0002 decision 4) —
/// and then the keyboard acts on that focus. Space presses the button the
/// pointer left focused, and a press whose ring never appears is a press
/// the user cannot attribute to a control: the frame answered, but nothing
/// on screen says which node answered. So the key that acts shows the
/// focus, exactly as the Tab that could have put it there would have.
#[test]
fn a_key_acting_on_pointer_focus_shows_it() {
    let mut core = Core::new();
    let k = frame(&mut core, false, false);

    // Space, after a click on the same button.
    click_at(&mut core, 50.0, 2.0 * H + 10.0);
    assert_eq!(core.focus(), Some(k.go));
    assert!(!core.focus_visible(), "the click alone shows nothing");
    assert_eq!(
        payloads(&core.handle_input(InputEvent::Text(" ".into()))),
        ["go"]
    );
    assert!(core.focus_visible(), "Space pressed it: say which one");
    frame(&mut core, false, false);
    assert_eq!(ring_count(&mut core), 1);

    // Enter, on a switch the pointer focused.
    click_at(&mut core, 50.0, 4.0 * H + 10.0);
    assert_eq!(core.focus(), Some(k.mute));
    assert!(!core.focus_visible());
    assert_eq!(payloads(&key(&mut core, EditKey::Enter)), ["mute"]);
    assert!(core.focus_visible(), "Enter pressed it");

    // An arrow nudging a slider is the keyboard acting too.
    click_at(&mut core, 50.0, 5.0 * H + 10.0);
    assert_eq!(core.focus(), Some(k.vol));
    assert!(!core.focus_visible());
    assert_eq!(
        payloads(&key(&mut core, EditKey::Right)),
        ["access:increment"]
    );
    assert!(core.focus_visible(), "the slider moved: say which one");

    // A key the core does nothing with shows nothing: an arrow on a
    // button is not the keyboard using the focus, it is a key going
    // nowhere.
    click_at(&mut core, 50.0, 2.0 * H + 10.0);
    assert_eq!(core.focus(), Some(k.go));
    assert!(key(&mut core, EditKey::Right).is_empty());
    assert!(!core.focus_visible(), "nothing acted: nothing to show");

    // Escape is the other exception: it acts by letting go, and a ring
    // around nothing is not a ring.
    key(&mut core, EditKey::Escape);
    assert_eq!(core.focus(), None);
    frame(&mut core, false, false);
    assert_eq!(ring_count(&mut core), 0);
}

/// The root is never a Tab stop, sink or not: it encloses everything, so
/// a sink on it hears every key nothing below claims (ADR 0011) and a
/// view may focus it outright, but the ring walks past it — a stop is a
/// thing the user acts on, and the whole window is not one. Before this
/// a root sink drew the ring around the window (found by the examples'
/// harness, whose sink is the root; ADR 0021).
#[test]
fn the_root_is_never_a_tab_stop() {
    let mut core = Core::new();
    let mut go = Key::ROOT;
    let build = |core: &mut Core, go: &mut Key| {
        let mut ui = core.frame(Size::new(200.0, 100.0), 1.0);
        ui.configure_root(NodeSpec::column().fill().on_key("root"));
        *go = ui.leaf_keyed("go", NodeSpec::row().height(H).on_click("go"));
        ui.finish();
    };
    build(&mut core, &mut go);
    tab(&mut core, false);
    assert_eq!(core.focus(), Some(go));
    tab(&mut core, false);
    assert_eq!(
        core.focus(),
        Some(go),
        "one stop: the root is not the other"
    );
    // Focused outright it hears the keys the button does not claim.
    core.set_focus(Some(Key::ROOT));
    build(&mut core, &mut go);
    let evs = core.handle_input(InputEvent::KeyDown(kui_core::KeyPress::new(
        kui_core::KeyCode::Char('x'),
        Default::default(),
    )));
    assert_eq!(
        evs[0].payload.get_str("tag"),
        Some("root"),
        "a focused root sink keeps the keyboard"
    );
}

/// `modal-behind-content` for an in-flow modal is about what paints over
/// it. A `line` in a bar declared before the modal paints in the bar's
/// layer, under the modal (backlog F123), and is not content over it;
/// one anchored to the viewport is a layer of its own, over it, and is.
#[test]
fn a_stroke_declared_before_an_in_flow_modal_is_not_content_over_it() {
    let build = |core: &mut Core, viewport: bool| {
        let mut ui = core.frame(Size::new(200.0, 300.0), 1.0);
        ui.configure_root(NodeSpec::column().fill());
        ui.with_keyed("bar", NodeSpec::row().size(200.0, H), |ui| {
            let mut spec = NodeSpec::row();
            if viewport {
                spec = spec.float(kui_core::FloatConfig::viewport());
            }
            ui.line(
                Vec2::new(4.0, 4.0),
                Vec2::new(16.0, 16.0),
                kui_core::Stroke::new(2.0, Color::WHITE),
                spec,
            );
        });
        ui.leaf_keyed(
            "sheet",
            NodeSpec::column()
                .size(100.0, H)
                .modal(Value::Null)
                .label("Sheet"),
        );
        ui.finish();
        core.take_warnings()
            .iter()
            .filter(|w| w.code == kui_core::diag::MODAL_BEHIND_CONTENT)
            .count()
    };
    let mut core = Core::new();
    assert_eq!(
        build(&mut core, false),
        0,
        "a stroke in the bar's layer is under the modal"
    );
    let mut core = Core::new();
    assert_eq!(
        build(&mut core, true),
        1,
        "a viewport-anchored stroke is a layer over it"
    );
}