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
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
//! End-to-end scrolling through a live `Core`: wheel routing, offset clamping,
//! content movement, clipping of draw + hit regions, scrollbar emission.

use kui_core::{Color, Core, InputEvent, NodeSpec, Size, Value, Vec2};

const VIEW_H: f32 = 200.0;
const ROWS: usize = 20;
const ROW_H: f32 = 30.0; // 20 * 30 = 600 content in a 200 viewport window

fn frame(core: &mut Core) {
    let mut ui = core.frame(Size::new(400.0, VIEW_H), 1.0);
    ui.configure_root(NodeSpec::column().fill());
    ui.with_keyed("list", NodeSpec::column().fill().scroll_y(), |ui| {
        for i in 0..ROWS {
            ui.leaf_keyed(
                &format!("row{i}"),
                NodeSpec::row()
                    .grow_width()
                    .height(ROW_H)
                    .bg(Color::rgb8(40, 40, 60))
                    .on_click(Value::Int(i as i64)),
            );
        }
    });
    ui.finish();
}

/// Min/max y over emitted row quads (fully clipped rows are culled, so this
/// tracks what actually draws). Rows are the wide solid quads; the scrollbar
/// is only 4px wide.
fn row_quad_ys(core: &mut Core) -> (f32, f32) {
    let (dl, _) = core.output();
    dl.quads
        .iter()
        .filter(|q| q.kind == kui_core::QuadKind::Solid && q.rect.w > 100.0)
        .fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), q| {
            (lo.min(q.rect.y), hi.max(q.rect.y))
        })
}

fn wheel(core: &mut Core, dy: f32) {
    // Cursor over the list, then scroll (negative dy = wheel down).
    core.handle_input(InputEvent::CursorMoved(Vec2::new(200.0, 100.0)));
    core.handle_input(InputEvent::Scroll(Vec2::new(0.0, dy)));
}

#[test]
fn wheel_scrolls_content_and_clamps() {
    let mut core = Core::new();
    frame(&mut core); // establish scroll regions
    assert_eq!(row_quad_ys(&mut core).0, 0.0);

    wheel(&mut core, -50.0); // scroll down 50: row 0 (y=-50) culls, row 1 shows at -20
    frame(&mut core);
    assert_eq!(row_quad_ys(&mut core).0, -20.0);

    wheel(&mut core, -10_000.0); // way past the end: clamps to max (400)
    frame(&mut core);
    // Last row sits flush with the bottom: y = 600 - 400 - 30 padding... = 170.
    assert_eq!(row_quad_ys(&mut core).1, VIEW_H - ROW_H);

    wheel(&mut core, 20_000.0); // way back up: clamps to 0
    frame(&mut core);
    assert_eq!(row_quad_ys(&mut core).0, 0.0);
}

#[test]
fn clipped_away_rows_are_culled_and_unclickable() {
    let mut core = Core::new();
    frame(&mut core);
    let (dl, _) = core.output();
    let solid_rows = dl
        .quads
        .iter()
        .filter(|q| q.kind == kui_core::QuadKind::Solid && q.rect.w > 100.0)
        .count();
    // 200/30 -> 7 rows intersect the viewport; the other 13 are culled.
    assert!(solid_rows < ROWS, "expected culling, got {solid_rows} rows");

    // A click at y=100 hits the visible row 3, not some scrolled-away row.
    core.handle_input(InputEvent::CursorMoved(Vec2::new(200.0, 100.0)));
    core.handle_input(InputEvent::mouse_down(1));
    let evs = core.handle_input(InputEvent::mouse_up());
    assert_eq!(evs.len(), 1);
    assert_eq!(evs[0].payload.as_int(), Some(3));

    // After scrolling down two rows, the same cursor position hits row 5.
    wheel(&mut core, -60.0);
    frame(&mut core);
    core.handle_input(InputEvent::CursorMoved(Vec2::new(200.0, 100.0)));
    core.handle_input(InputEvent::mouse_down(1));
    let evs = core.handle_input(InputEvent::mouse_up());
    assert_eq!(evs[0].payload.as_int(), Some(5));
}

#[test]
fn scrollbar_appears_only_when_overflowing() {
    let mut core = Core::new();
    frame(&mut core);
    let (dl, _) = core.output();
    let bars = dl.quads.iter().filter(|q| q.rect.w == 4.0).count();
    assert_eq!(bars, 1, "expected one vertical scrollbar");

    // A short list needs no scrollbar.
    let mut ui = core.frame(Size::new(400.0, VIEW_H), 1.0);
    ui.with_keyed("list", NodeSpec::column().fill().scroll_y(), |ui| {
        ui.leaf(NodeSpec::row().height(50.0).bg(Color::WHITE));
    });
    ui.finish();
    let (dl, _) = core.output();
    assert_eq!(dl.quads.iter().filter(|q| q.rect.w == 4.0).count(), 0);
}

#[test]
fn scroll_offset_survives_and_reclamps_on_content_shrink() {
    let mut core = Core::new();
    frame(&mut core);
    wheel(&mut core, -10_000.0);
    frame(&mut core); // clamped to 400

    // Rebuild with half the rows: max becomes 10*30-200 = 100.
    let mut ui = core.frame(Size::new(400.0, VIEW_H), 1.0);
    ui.with_keyed("list", NodeSpec::column().fill().scroll_y(), |ui| {
        for i in 0..10 {
            ui.leaf_keyed(
                &format!("row{i}"),
                NodeSpec::row()
                    .grow_width()
                    .height(ROW_H)
                    .bg(Color::rgb8(40, 40, 60)),
            );
        }
    });
    ui.finish();
    // Offset re-clamped from 400 to 100: rows sit at -100 + i*30, and the
    // first one that still intersects the viewport draws at -10 (row 3).
    assert_eq!(row_quad_ys(&mut core).0, -10.0);
}

// -- The scroll API apps drive from outside -------------------------------
// `reveal` / `set_scroll` / `scroll_offset` are the wheel's moves asked for
// by name: the offsets are retained per key, and until these existed only
// the core could reach them.

fn list_key() -> kui_core::Key {
    kui_core::Key::ROOT.str("list")
}

fn row_key(i: usize) -> kui_core::Key {
    list_key().str(&format!("row{i}"))
}

/// The y a row's quad drew at, or None when it was culled.
fn row_y(core: &mut Core, i: usize) -> Option<f32> {
    // Rows are the wide solids; the i-th is at content y = i * ROW_H, so
    // identify it by the offset the frame drew it with.
    let (dl, _) = core.output();
    let ys: Vec<f32> = dl
        .quads
        .iter()
        .filter(|q| q.kind == kui_core::QuadKind::Solid && q.rect.w > 100.0)
        .map(|q| q.rect.y)
        .collect();
    let want = i as f32 * ROW_H - core.scroll_offset(list_key()).y;
    ys.into_iter().find(|y| (*y - want).abs() < 0.01)
}

#[test]
fn reveal_scrolls_a_row_into_view_and_is_idempotent() {
    let mut core = Core::new();
    frame(&mut core);
    assert_eq!(core.scroll_offset(list_key()), Vec2::ZERO);

    // Row 15 sits at 450..480 in a 200-tall window: off the bottom.
    core.reveal(row_key(15));
    frame(&mut core);
    let y = row_y(&mut core, 15).expect("row 15 should draw");
    assert!(
        y >= 0.0 && y + ROW_H <= VIEW_H,
        "row 15 not inside the viewport: y={y}"
    );
    let after = core.scroll_offset(list_key());
    assert!(after.y > 0.0, "reveal moved nothing: {after:?}");

    // The frame that resolved it also cleared it: another frame drifts nowhere.
    frame(&mut core);
    assert_eq!(core.scroll_offset(list_key()), after);

    // Revealing something already visible is a no-op, not a re-alignment.
    core.reveal(row_key(15));
    frame(&mut core);
    assert_eq!(core.scroll_offset(list_key()), after);
}

#[test]
fn reveal_scrolls_back_up() {
    let mut core = Core::new();
    frame(&mut core);
    core.set_scroll(list_key(), Vec2::new(0.0, 400.0));
    frame(&mut core);
    assert_eq!(core.scroll_offset(list_key()).y, 400.0);

    core.reveal(row_key(0));
    frame(&mut core);
    assert_eq!(core.scroll_offset(list_key()), Vec2::ZERO);
    assert_eq!(row_y(&mut core, 0), Some(0.0));
}

#[test]
fn reveal_of_a_key_the_frame_does_not_declare_is_a_no_op() {
    let mut core = Core::new();
    frame(&mut core);
    let before = core.scroll_offset(list_key());

    core.reveal(kui_core::Key::ROOT.str("no-such-node"));
    frame(&mut core);
    assert_eq!(core.scroll_offset(list_key()), before);

    // And it is not remembered: a later frame that *does* declare row 15
    // still does not move, because the request was spent.
    frame(&mut core);
    assert_eq!(core.scroll_offset(list_key()), before);
}

#[test]
fn reveal_reaches_a_row_the_frame_declares_for_the_first_time() {
    // The point of resolving against the frame ahead: an app that appends a
    // row and reveals it in the same update has no last frame to find it in.
    let mut core = Core::new();
    frame(&mut core); // 20 rows

    core.reveal(row_key(39));
    let mut ui = core.frame(Size::new(400.0, VIEW_H), 1.0);
    ui.configure_root(NodeSpec::column().fill());
    ui.with_keyed("list", NodeSpec::column().fill().scroll_y(), |ui| {
        for i in 0..40 {
            ui.leaf_keyed(
                &format!("row{i}"),
                NodeSpec::row()
                    .grow_width()
                    .height(ROW_H)
                    .bg(Color::rgb8(40, 40, 60)),
            );
        }
    });
    ui.finish();
    // 40 * 30 = 1200 of content in 200: the last row is flush with the end.
    assert_eq!(core.scroll_offset(list_key()).y, 1000.0);
}

/// Two lists side by side, each 20 rows of 30 in 200 (F82).
fn two_lists(core: &mut Core) {
    let mut ui = core.frame(Size::new(400.0, VIEW_H), 1.0);
    ui.configure_root(NodeSpec::row().fill());
    for list in ["left", "right"] {
        ui.with_keyed(list, NodeSpec::column().fill().scroll_y(), |ui| {
            for i in 0..ROWS {
                ui.leaf_keyed(
                    &format!("row{i}"),
                    NodeSpec::row().grow_width().height(ROW_H),
                );
            }
        });
    }
    ui.finish();
}

#[test]
fn reveals_into_two_containers_in_one_frame_both_land() {
    // A tab strip and the pane list under it, each revealing its own
    // selection on the frame a key changes both: the asks are not
    // contradictory, so neither may drop the other (F82).
    let left = kui_core::Key::ROOT.str("left");
    let right = kui_core::Key::ROOT.str("right");
    let mut core = Core::new();
    two_lists(&mut core);
    core.reveal(left.str("row15"));
    core.reveal(right.str("row18"));
    two_lists(&mut core);
    // Row 15 at 450..480 shows at the bottom of 200 with 4 of slack:
    // 284; row 18 at 540..570: 374.
    assert_eq!(core.scroll_offset(left).y, 284.0);
    assert_eq!(core.scroll_offset(right).y, 374.0);

    // Into one container, the last ask is the one that stands: row 0
    // after row 19 leaves the list at the top.
    core.reveal(left.str("row19"));
    core.reveal(left.str("row0"));
    two_lists(&mut core);
    assert_eq!(core.scroll_offset(left).y, 0.0);
}

#[test]
fn set_scroll_and_scroll_offset_round_trip_through_a_model() {
    let mut core = Core::new();
    frame(&mut core);
    wheel(&mut core, -150.0);
    frame(&mut core);
    let saved = core.scroll_offset(list_key());
    assert_eq!(saved, Vec2::new(0.0, 150.0));

    // A fresh core (a restarted app) restores it before the first frame.
    let mut restored = Core::new();
    restored.set_scroll(list_key(), saved);
    frame(&mut restored);
    assert_eq!(restored.scroll_offset(list_key()), saved);
    assert_eq!(row_y(&mut restored, 5), Some(0.0));
}

#[test]
fn set_scroll_is_clamped_by_the_next_layout() {
    let mut core = Core::new();
    frame(&mut core);

    // "Jump to the end" without knowing the content height.
    core.set_scroll(list_key(), Vec2::new(0.0, f32::MAX));
    frame(&mut core);
    assert_eq!(core.scroll_offset(list_key()).y, 600.0 - VIEW_H);

    // And back to the top, past it.
    core.set_scroll(list_key(), Vec2::new(0.0, -500.0));
    frame(&mut core);
    assert_eq!(core.scroll_offset(list_key()), Vec2::ZERO);
}

#[test]
fn scroll_offset_of_a_node_that_never_scrolled_is_zero() {
    let mut core = Core::new();
    frame(&mut core);
    assert_eq!(core.scroll_offset(row_key(0)), Vec2::ZERO);
    assert_eq!(
        core.scroll_offset(kui_core::Key::ROOT.str("gone")),
        Vec2::ZERO
    );
}

// -- Geometry and virtual lists ---------------------------------------------
// `scroll_offset` says how far a container has scrolled; on its own that is
// not enough to build only the visible rows, because the view cannot see how
// tall the container came out. `scroll_geometry` is the rest of it, and
// `widgets::uniform_list` is the two together.

/// A tall list built through the widget, in a `VIEW_H`-high window.
fn virtual_frame(core: &mut Core, rows: usize) -> usize {
    let mut built = 0usize;
    let mut ui = core.frame(Size::new(400.0, VIEW_H), 1.0);
    ui.configure_root(NodeSpec::column().fill());
    kui_core::widgets::uniform_list(
        &mut ui,
        "list",
        NodeSpec::column().fill(),
        rows,
        ROW_H,
        |ui, i| {
            built += 1;
            ui.leaf(
                NodeSpec::row()
                    .fill()
                    .bg(Color::rgb8(40, 40, 60))
                    .on_click(Value::Int(i as i64)),
            );
        },
    );
    ui.finish();
    built
}

/// The geometry a view reads is the box and content the last layout
/// resolved — the rect an `on_layout` would have posted, without the round
/// trip, and the content height the scrollbar is drawn from.
#[test]
fn geometry_reports_the_container_box_and_its_content() {
    let mut core = Core::new();
    assert_eq!(core.scroll_geometry(list_key()), None);

    frame(&mut core);
    let g = core.scroll_geometry(list_key()).expect("laid out");
    assert_eq!(g.rect, kui_core::Rect::new(0.0, 0.0, 400.0, VIEW_H));
    assert_eq!(g.content.h, ROWS as f32 * ROW_H);
    assert_eq!(g.offset, Vec2::ZERO);
    // Content minus viewport, which is exactly how far the wheel may go.
    assert_eq!(g.max_offset.y, ROWS as f32 * ROW_H - VIEW_H);

    wheel(&mut core, -10_000.0);
    frame(&mut core);
    let g = core.scroll_geometry(list_key()).expect("laid out");
    assert_eq!(g.offset, g.max_offset);
}

/// Writing an offset at a key does not invent a container: the geometry
/// stays `None` until a layout resolves that key as one.
#[test]
fn geometry_is_none_for_a_node_that_is_not_a_scroll_container() {
    let mut core = Core::new();
    frame(&mut core);
    assert_eq!(core.scroll_geometry(row_key(3)), None);

    core.set_scroll(row_key(3), Vec2::new(0.0, 50.0));
    frame(&mut core);
    assert_eq!(core.scroll_geometry(row_key(3)), None);
    assert_eq!(core.scroll_geometry(kui_core::Key::ROOT.str("gone")), None);
}

/// The geometry is one coherent moment: `scroll_offset` hands back whatever
/// was written, but the geometry's offset is already clamped to the travel
/// the last layout found — so a view that slices by it cannot be handed the
/// "huge value means the end" idiom as a row index.
#[test]
fn geometry_offset_is_clamped_where_the_raw_one_is_not() {
    let mut core = Core::new();
    frame(&mut core);
    core.set_scroll(list_key(), Vec2::new(0.0, 1e9));

    assert_eq!(core.scroll_offset(list_key()).y, 1e9);
    let g = core.scroll_geometry(list_key()).expect("laid out");
    assert_eq!(g.offset.y, ROWS as f32 * ROW_H - VIEW_H);
    assert_eq!(g.offset, g.max_offset);

    // And the next layout agrees with what the geometry predicted.
    frame(&mut core);
    assert_eq!(core.scroll_offset(list_key()).y, g.offset.y);
}

/// An axis that does not scroll has no travel, however far its content
/// overflows — the list scrolls in y only.
#[test]
fn max_offset_is_zero_on_an_axis_that_does_not_scroll() {
    let mut core = Core::new();
    frame(&mut core);
    let g = core.scroll_geometry(list_key()).expect("laid out");
    assert_eq!(g.max_offset.x, 0.0);
    assert_eq!(g.max_offset.y, ROWS as f32 * ROW_H - VIEW_H);
}

/// The point of the whole exercise: a list of 10k rows builds a screenful.
#[test]
fn a_uniform_list_builds_only_what_shows() {
    let mut core = Core::new();
    // First frame has no geometry and slices by the viewport instead.
    let first = virtual_frame(&mut core, 10_000);
    assert!(first < 20, "first frame built {first} rows");
    // Steady state: VIEW_H / ROW_H visible, plus two rows of overscan each
    // side (the leading side is clipped away at offset 0).
    let n = virtual_frame(&mut core, 10_000);
    assert_eq!(n, (VIEW_H / ROW_H).ceil() as usize + 2);
}

/// Scrolling slides the built range without changing its size, and the rows
/// it builds are the ones under the window.
#[test]
fn the_built_range_follows_the_offset() {
    let mut core = Core::new();
    virtual_frame(&mut core, 10_000);
    let steady = virtual_frame(&mut core, 10_000);

    core.set_scroll(list_key(), Vec2::new(0.0, 300.0 * ROW_H));
    virtual_frame(&mut core, 10_000);
    let n = virtual_frame(&mut core, 10_000);
    // Two rows of overscan on each side now that there is room above.
    assert_eq!(n, steady + 2);

    // Row 300 is at the top of the window; row 0 and row 9_999 are not built,
    // so nothing but the spacers stands in for them.
    let (dl, _) = core.output();
    let rows = dl
        .quads
        .iter()
        .filter(|q| q.kind == kui_core::QuadKind::Solid && q.rect.w > 100.0)
        .count();
    // Two overscan rows above the window and two below it are built but
    // clipped away, so they cost a node and no quad.
    assert_eq!(rows, n - 4);
}

/// A virtualized list is the same list: the content height, and so the
/// scrollbar and the end of the travel, match a list that builds every row.
#[test]
fn a_uniform_list_scrolls_like_a_full_one() {
    let mut core = Core::new();
    virtual_frame(&mut core, 1_000);
    virtual_frame(&mut core, 1_000);
    let g = core.scroll_geometry(list_key()).expect("laid out");
    assert_eq!(g.content.h, 1_000.0 * ROW_H);
    assert_eq!(g.max_offset.y, 1_000.0 * ROW_H - VIEW_H);

    // "Jump to the end" with no content height in the app still lands on the
    // last row, because the trailing spacer holds the space of the rows the
    // frame did not build.
    core.set_scroll(list_key(), Vec2::new(0.0, f32::MAX));
    virtual_frame(&mut core, 1_000);
    virtual_frame(&mut core, 1_000);
    assert_eq!(core.scroll_offset(list_key()).y, 1_000.0 * ROW_H - VIEW_H);
}

/// A tall list built through the widget in a window `h` high.
fn virtual_frame_in(core: &mut Core, rows: usize, h: f32) -> usize {
    let mut built = 0usize;
    let mut ui = core.frame(Size::new(400.0, h), 1.0);
    ui.configure_root(NodeSpec::column().fill());
    kui_core::widgets::uniform_list(
        &mut ui,
        "list",
        NodeSpec::column().fill(),
        rows,
        ROW_H,
        |ui, _| {
            built += 1;
            ui.leaf(NodeSpec::row().fill());
        },
    );
    ui.finish();
    built
}

/// The slice is one frame behind the layout, so a frame whose container
/// came out otherwise than the view assumed — taller after a resize, a
/// split sliding open, scrolled elsewhere by a reveal — owes one more
/// frame, or the rows built for the old box stay on screen until the
/// next event, a screenful short. The core asks for it, and the frame
/// after builds the right rows and asks for nothing.
#[test]
fn a_uniform_list_owes_a_frame_when_its_box_moved() {
    let mut core = Core::new();
    virtual_frame_in(&mut core, 1_000, VIEW_H);
    assert!(core.owed().requested, "the first frame sliced blind");
    let fits = |h: f32| kui_core::widgets::visible_rows(0.0, h, 0.0, ROW_H, 1_000, 2).len();
    let built = virtual_frame_in(&mut core, 1_000, VIEW_H);
    assert_eq!(built, fits(VIEW_H), "a screenful and the overscan");
    assert!(!core.owed().requested, "settled");
    // The window grows to three times the height: this frame builds for
    // the old box and must ask for another.
    let built = virtual_frame_in(&mut core, 1_000, VIEW_H * 3.0);
    assert_eq!(built, fits(VIEW_H), "still the old box's rows");
    assert!(core.owed().requested, "the box moved: one more frame");
    let built = virtual_frame_in(&mut core, 1_000, VIEW_H * 3.0);
    assert_eq!(built, fits(VIEW_H * 3.0), "the new box's rows");
    assert!(!core.owed().requested, "settled again");
    // A wheel between two frames: the geometry a view reads already
    // carries the new offset, so the frame that lands it builds the
    // right rows and owes nothing.
    core.set_scroll(list_key(), Vec2::new(0.0, 10.0 * ROW_H));
    virtual_frame_in(&mut core, 1_000, VIEW_H * 3.0);
    assert!(
        !core.owed().requested,
        "a scroll slices right the first time"
    );
    // The rows themselves shrink under the offset: the clamp lands the
    // content elsewhere than the slice assumed, so a frame is owed and
    // the next one settles at the end of the shorter list.
    core.set_scroll(list_key(), Vec2::new(0.0, 900.0 * ROW_H));
    virtual_frame_in(&mut core, 1_000, VIEW_H * 3.0);
    assert!(!core.owed().requested);
    virtual_frame_in(&mut core, 100, VIEW_H * 3.0);
    assert!(core.owed().requested, "clamped short: one more frame");
    virtual_frame_in(&mut core, 100, VIEW_H * 3.0);
    assert!(!core.owed().requested);
    assert_eq!(
        core.scroll_offset(list_key()).y,
        100.0 * ROW_H - VIEW_H * 3.0
    );
}

/// Rows are keyed by data index, not by the slot they land in, so the row
/// under the pointer keeps its identity as the built range slides. This is
/// what would have to be re-solved inside the core to virtualize there.
#[test]
fn list_rows_keep_their_key_as_the_range_slides() {
    let mut core = Core::new();
    virtual_frame(&mut core, 10_000);
    virtual_frame(&mut core, 10_000);
    let key_at_top = list_key().index(0);

    core.set_scroll(list_key(), Vec2::new(0.0, 500.0 * ROW_H));
    virtual_frame(&mut core, 10_000);
    virtual_frame(&mut core, 10_000);
    // Row 0's key is unchanged even though row 0 is no longer built, and it
    // is not the key of whatever row now sits in the first slot.
    assert_eq!(key_at_top, list_key().index(0));
    assert_ne!(key_at_top, list_key().index(500));
}

/// The spacers stand outside the index namespace the rows use, so the row at
/// index 0 and the spacer beside it are two nodes, not a duplicate key.
#[test]
fn spacers_do_not_collide_with_row_keys() {
    let mut core = Core::new();
    virtual_frame(&mut core, 10_000);
    core.set_scroll(list_key(), Vec2::new(0.0, 300.0 * ROW_H));
    virtual_frame(&mut core, 10_000);
    virtual_frame(&mut core, 10_000);
    let dup = core
        .take_warnings()
        .iter()
        .any(|w| w.code == "duplicate-key");
    assert!(!dup, "virtual rows and spacers collided");
}

/// The slice arithmetic on its own, for views that build their own container.
#[test]
fn visible_rows_covers_the_band_and_no_more() {
    use kui_core::widgets::visible_rows;
    // 200px window over 30px rows at the top: rows 0..7 cross it.
    assert_eq!(visible_rows(0.0, 200.0, 0.0, 30.0, 10_000, 0), 0..7);
    // Scrolled to row 100 exactly.
    assert_eq!(visible_rows(3000.0, 200.0, 0.0, 30.0, 10_000, 0), 100..107);
    // Overscan widens both ends, clamped to the list.
    assert_eq!(visible_rows(3000.0, 200.0, 0.0, 30.0, 10_000, 2), 98..109);
    assert_eq!(visible_rows(0.0, 200.0, 0.0, 30.0, 10_000, 2), 0..9);
    // Padding above the first row shifts the band down the flow.
    assert_eq!(visible_rows(3000.0, 200.0, 60.0, 30.0, 10_000, 0), 98..105);
    // Degenerate inputs answer with an empty range rather than a panic.
    assert_eq!(visible_rows(0.0, 200.0, 0.0, 30.0, 0, 2), 0..0);
    assert_eq!(visible_rows(0.0, 200.0, 0.0, 0.0, 10, 2), 0..0);
    // A list shorter than the window builds all of it, never past the end.
    assert_eq!(visible_rows(0.0, 200.0, 0.0, 30.0, 3, 2), 0..3);
}

// -- Variable-height virtual lists ------------------------------------------
// `uniform_list` takes one stride; these are the rows that have none. The
// heights come from a `measure` callback the widget runs for the rows it is
// about to build, everything else stands at the mean of what has been
// measured, and the prefix sums over both are what the spacers and the search
// are made of.

use kui_core::Key;
use kui_core::testing::{click, hover, kinds};
use kui_core::widgets::RowHeights;

const VAR_ROWS: usize = 1_000;

/// Row `i`'s true height. Short at the top and tall for the rest, so the
/// estimate the first screenful produces is badly wrong for the middle of
/// the list — which is what makes the anchoring observable.
fn var_h(i: usize) -> f32 {
    if i < 100 { 20.0 } else { 60.0 }
}

/// One frame of a variable-height list, returning what it built.
fn var_frame(core: &mut Core, heights: &mut RowHeights) -> std::ops::Range<usize> {
    let (mut first, mut last) = (usize::MAX, 0usize);
    let mut ui = core.frame(Size::new(400.0, VIEW_H), 1.0);
    ui.configure_root(NodeSpec::column().fill());
    kui_core::widgets::list(
        &mut ui,
        "list",
        NodeSpec::column().fill(),
        heights,
        |_ui, i, _w| var_h(i),
        |ui, i| {
            first = first.min(i);
            last = i + 1;
            ui.leaf(
                NodeSpec::row()
                    .fill()
                    .bg(Color::rgb8(40, 40, 60))
                    .on_click(Value::Int(i as i64)),
            );
        },
    );
    ui.finish();
    if last == 0 { 0..0 } else { first..last }
}

/// Which row is under the top edge of the window, by hit-testing rather than
/// by arithmetic — the question "did the content move" asks of the pixels.
fn row_under(core: &mut Core, y: f32) -> Option<i64> {
    hit_under(core, y).map(|(i, _)| i)
}

/// The same hit, with the key of the node that took it — the row wrapper's
/// own first child, so the wrapper's key is one step up.
fn hit_under(core: &mut Core, y: f32) -> Option<(i64, kui_core::Key)> {
    core.handle_input(InputEvent::CursorMoved(Vec2::new(200.0, y)));
    core.handle_input(InputEvent::mouse_down(1));
    let evs = core.handle_input(InputEvent::mouse_up());
    let e = evs.first()?;
    Some((e.payload.as_int()?, e.key))
}

#[test]
fn row_heights_answer_the_three_questions_a_stride_answered() {
    let mut h = RowHeights::new(10, 20.0);
    // Nothing measured: every row stands at the seed.
    assert_eq!(h.estimate(), 20.0);
    assert_eq!(h.total(), 200.0);
    assert_eq!(h.offset_of(3), 60.0);
    assert_eq!(h.row_at(0.0), 0);
    assert_eq!(h.row_at(65.0), 3);

    // Measure three rows: they take their own height and the estimate
    // becomes their mean, which moves every row that has none.
    h.set(0, 50.0);
    h.set(1, 50.0);
    h.set(2, 50.0);
    assert_eq!(h.measured(0), Some(50.0));
    assert_eq!(h.measured(9), None);
    assert_eq!(h.estimate(), 50.0);
    assert_eq!(h.get(9), 50.0);
    assert_eq!(h.total(), 500.0);
    assert_eq!(h.offset_of(3), 150.0);
    assert_eq!(h.row_at(149.0), 2);
    assert_eq!(h.row_at(150.0), 3);
    // Past the end clamps to the last row rather than panicking.
    assert_eq!(h.row_at(1e9), 9);

    // Appending keeps what is measured; clearing keeps only the length.
    h.set_len(12);
    assert_eq!(h.measured(0), Some(50.0));
    assert_eq!(h.total(), 600.0);
    h.clear();
    assert_eq!(h.measured(0), None);
    assert_eq!(h.estimate(), 20.0, "back to the seed with nothing measured");
    assert_eq!(h.len(), 12);
}

/// A width that differs from the one the heights were measured at rewraps
/// every row, so the cache is void — the frame after a resize measures again.
#[test]
fn a_new_width_drops_every_measurement() {
    let mut h = RowHeights::new(10, 20.0);
    assert!(h.set_width(300.0));
    h.set(0, 55.0);
    assert!(!h.set_width(300.0), "the same width changes nothing");
    assert_eq!(h.measured(0), Some(55.0));
    assert!(h.set_width(200.0));
    assert_eq!(h.measured(0), None);
    assert_eq!(h.width(), 200.0);
}

/// The point of the exercise, without a stride: a thousand rows of three
/// different heights build a screenful.
#[test]
fn a_variable_list_builds_only_what_shows() {
    let mut core = Core::new();
    let mut h = RowHeights::new(VAR_ROWS, 20.0);
    var_frame(&mut core, &mut h);
    let built = var_frame(&mut core, &mut h);
    // 200px of window over 20px rows at the top, plus two of overscan.
    assert!(built.len() <= 14, "built {built:?}");
    assert_eq!(built.start, 0);
    // Only what was built has been measured; the rest stands at the mean.
    assert_eq!(h.measured(built.end - 1), Some(20.0));
    assert_eq!(h.measured(built.end + 50), None);
}

/// Each row is exactly as tall as it measured, so the arithmetic above and
/// below it cannot disagree with the layout the way an estimate would.
#[test]
fn a_row_is_as_tall_as_it_measured() {
    let mut core = Core::new();
    let mut h = RowHeights::new(VAR_ROWS, 20.0);
    var_frame(&mut core, &mut h);
    var_frame(&mut core, &mut h);
    let (dl, _) = core.output();
    let mut rows: Vec<f32> = dl
        .quads
        .iter()
        .filter(|q| q.kind == kui_core::QuadKind::Solid && q.rect.w > 100.0)
        .map(|q| q.rect.h)
        .collect();
    rows.dedup();
    assert_eq!(rows, vec![20.0], "every visible row is its measured height");
}

/// The content height — the scrollbar, the travel and "jump to the end" —
/// is what has been measured plus what is estimated, and it converges on the
/// truth as the list is scrolled through.
#[test]
fn the_content_height_is_the_measured_and_the_estimated_together() {
    let mut core = Core::new();
    let mut h = RowHeights::new(VAR_ROWS, 20.0);
    var_frame(&mut core, &mut h);
    var_frame(&mut core, &mut h);
    let g = core.scroll_geometry(list_key()).expect("laid out");
    // Everything estimated at 20 (the seed, and the mean of the short rows
    // the first screenful measured).
    assert_eq!(g.content.h, VAR_ROWS as f32 * 20.0);
    assert_eq!(h.total(), VAR_ROWS as f32 * 20.0);

    // Scroll into the tall half: the rows built there are measured at 60,
    // the mean rises, and the list learns it is longer than it looked.
    core.set_scroll(list_key(), Vec2::new(0.0, 5_000.0));
    for _ in 0..4 {
        var_frame(&mut core, &mut h);
    }
    assert!(
        h.total() > VAR_ROWS as f32 * 20.0 * 1.5,
        "total {} did not grow with what was measured",
        h.total()
    );
}

/// The crux. Measuring the rows a frame builds changes the height of every
/// row it does not — including the ones above the window — so without a
/// correction the content slides out from under the pointer on the frame the
/// list learns anything. The row under the top edge has to stay the row
/// under the top edge.
#[test]
fn the_row_under_the_pointer_stays_there_while_the_estimate_moves() {
    let mut core = Core::new();
    let mut h = RowHeights::new(VAR_ROWS, 20.0);
    var_frame(&mut core, &mut h);
    var_frame(&mut core, &mut h);

    // Jump into the tall half. The estimate is still 20, so this lands
    // around row 250 by the arithmetic of the moment; which row does not
    // matter, only that it is the same one on every frame after.
    core.set_scroll(list_key(), Vec2::new(0.0, 5_000.0));
    var_frame(&mut core, &mut h);
    let settled = row_under(&mut core, 4.0);
    assert!(settled.is_some(), "nothing under the top edge");

    // Four more frames, each measuring more of the list and moving the mean
    // under everything above the window.
    for n in 0..4 {
        var_frame(&mut core, &mut h);
        assert_eq!(
            row_under(&mut core, 4.0),
            settled,
            "the content slid on frame {n} as the estimate moved",
        );
    }
}

/// "Scroll to row `i`" is the prefix sum, and it lands the row at the top —
/// exactly for a row whose height is known, and within a frame or two for
/// one standing at the estimate.
#[test]
fn set_scroll_to_a_rows_offset_lands_it_at_the_top() {
    let mut core = Core::new();
    let mut h = RowHeights::new(VAR_ROWS, 20.0);
    var_frame(&mut core, &mut h);
    var_frame(&mut core, &mut h);

    let target = 400usize;
    core.set_scroll(list_key(), Vec2::new(0.0, h.offset_of(target)));
    // Two frames: the first builds and measures around the target, the
    // second is drawn from what it learned.
    var_frame(&mut core, &mut h);
    var_frame(&mut core, &mut h);
    assert_eq!(row_under(&mut core, 4.0), Some(target as i64));
}

/// Tailing a log: a list told to stay at the end stays at the end while it
/// learns how long it is. The widget's own correction keeps the *rows* still
/// (which is what a reader who scrolled there wants), so "the end" is the
/// app asking for it every frame — one `set_scroll` after the widget, the
/// last write of the frame.
#[test]
fn a_list_that_asks_for_the_end_every_frame_converges_on_it() {
    let mut core = Core::new();
    let mut h = RowHeights::new(VAR_ROWS, 20.0);
    for _ in 0..8 {
        var_frame(&mut core, &mut h);
        core.set_scroll(list_key(), Vec2::new(0.0, f32::MAX));
    }
    let built = var_frame(&mut core, &mut h);
    assert_eq!(built.end, VAR_ROWS, "the last row is built at the end");
    let g = core.scroll_geometry(list_key()).expect("laid out");
    assert_eq!(g.offset, g.max_offset);
}

/// Left to itself the widget keeps the *rows* still rather than the offset,
/// so a list that was scrolled to the end of an estimate is no longer at the
/// end once the estimate grows — it is still showing what it was showing.
#[test]
fn a_list_left_alone_keeps_its_rows_not_its_place_in_the_travel() {
    let mut core = Core::new();
    let mut h = RowHeights::new(VAR_ROWS, 20.0);
    var_frame(&mut core, &mut h);
    var_frame(&mut core, &mut h);
    core.set_scroll(list_key(), Vec2::new(0.0, f32::MAX));
    var_frame(&mut core, &mut h);
    let at = row_under(&mut core, 4.0);
    for _ in 0..4 {
        var_frame(&mut core, &mut h);
    }
    assert_eq!(row_under(&mut core, 4.0), at);
    let g = core.scroll_geometry(list_key()).expect("laid out");
    assert!(g.offset.y < g.max_offset.y, "the travel grew under it");
}

/// The same list, and the same identity rule as the uniform one: a row is
/// keyed by its data index, so the built range sliding over it changes
/// nothing it retains.
#[test]
fn variable_rows_keep_their_key_as_the_range_slides() {
    let mut core = Core::new();
    let mut h = RowHeights::new(VAR_ROWS, 20.0);
    var_frame(&mut core, &mut h);
    var_frame(&mut core, &mut h);

    core.set_scroll(list_key(), Vec2::new(0.0, 3_000.0));
    var_frame(&mut core, &mut h);
    let built = var_frame(&mut core, &mut h);
    assert!(built.start > 0, "scrolled past the top: {built:?}");

    // The row under the top edge is the one the arithmetic says, and the
    // node that took the click is that row wrapper's own child — so the
    // wrapper is keyed by the *data* index, which is the key auto-keying
    // would have given it in a list that built every row.
    let (row, key) = hit_under(&mut core, 4.0).expect("a row under the edge");
    assert_eq!(key, list_key().index(row as u64).index(0));
    assert!(row as usize > built.start, "overscan sits above the window");
}

/// The bar quads of the last frame: (width, colour) of every solid that
/// is not a row.
fn bars(core: &mut Core) -> Vec<(f32, Color)> {
    let (dl, _) = core.output();
    dl.quads
        .iter()
        .filter(|q| q.kind == kui_core::QuadKind::Solid && q.rect.w < 100.0)
        .map(|q| (q.rect.w, q.color))
        .collect()
}

/// The list frame with a bar style on the scroller.
fn styled(core: &mut Core, style: impl Fn(NodeSpec) -> NodeSpec) {
    let mut ui = core.frame(Size::new(400.0, VIEW_H), 1.0);
    ui.configure_root(NodeSpec::column().fill());
    ui.with_keyed("list", style(NodeSpec::column().fill().scroll_y()), |ui| {
        for i in 0..ROWS {
            ui.leaf_keyed(
                &format!("row{i}"),
                NodeSpec::row()
                    .grow_width()
                    .height(ROW_H)
                    .bg(Color::rgb8(40, 40, 60)),
            );
        }
    });
    ui.finish();
}

#[test]
fn a_hidden_scrollbar_draws_nothing_and_takes_no_press() {
    use kui_core::ScrollbarMode;
    let mut core = Core::new();
    styled(&mut core, |s| s.scrollbar(ScrollbarMode::Hidden));
    assert!(bars(&mut core).is_empty(), "no thumb");
    let list = core.key_of("list").unwrap();
    // The track a visible bar would have: a press there is content now.
    click(&mut core, Vec2::new(396.0, 190.0));
    styled(&mut core, |s| s.scrollbar(ScrollbarMode::Hidden));
    assert_eq!(core.scroll_offset(list).y, 0.0, "nothing to jump");
    // Scrolling itself is untouched.
    wheel(&mut core, -50.0);
    styled(&mut core, |s| s.scrollbar(ScrollbarMode::Hidden));
    assert_eq!(core.scroll_offset(list).y, 50.0);
    assert!(bars(&mut core).is_empty());
}

#[test]
fn a_scrollbar_takes_its_width_and_colours_from_the_node() {
    const REST: Color = Color {
        r: 1.0,
        g: 0.0,
        b: 0.0,
        a: 1.0,
    };
    const ACTIVE: Color = Color {
        r: 0.0,
        g: 1.0,
        b: 0.0,
        a: 1.0,
    };
    let style = |s: NodeSpec| {
        s.scrollbar_width(8.0)
            .scrollbar_color(REST)
            .scrollbar_active_color(ACTIVE)
    };
    let mut core = Core::new();
    styled(&mut core, style);
    assert_eq!(bars(&mut core), vec![(8.0, REST)]);
    // On the track: two wider, in the active colour. The track grew to
    // hold the wide thumb, so a pointer 11 px in is still on it.
    core.handle_input(InputEvent::CursorMoved(Vec2::new(389.0, 100.0)));
    styled(&mut core, style);
    assert_eq!(bars(&mut core), vec![(10.0, ACTIVE)]);
    // And the press there is the track's: below the thumb, so it pages.
    let list = core.key_of("list").unwrap();
    click(&mut core, Vec2::new(389.0, 190.0));
    styled(&mut core, style);
    assert!(core.scroll_offset(list).y > 0.0);
}

#[test]
fn an_auto_scrollbar_fades_out_when_the_scroll_state_is_quiet() {
    use kui_core::ScrollbarMode;
    let auto = |s: NodeSpec| s.scrollbar(ScrollbarMode::Auto);
    let mut core = Core::new();
    core.set_time(0.0);
    styled(&mut core, auto);
    let first = bars(&mut core);
    assert_eq!(first.len(), 1, "first seen: shown");
    assert!(core.animating(), "the hold is running");
    // Inside the hold: full.
    core.set_time(0.9);
    styled(&mut core, auto);
    assert_eq!(bars(&mut core)[0].1.a, first[0].1.a);
    // Mid-fade: dimmer.
    core.set_time(1.125);
    styled(&mut core, auto);
    let mid = bars(&mut core);
    assert_eq!(mid.len(), 1);
    assert!((mid[0].1.a - first[0].1.a * 0.5).abs() < 1e-3, "{:?}", mid);
    assert!(core.animating());
    // Gone, and nothing owed.
    core.set_time(1.3);
    styled(&mut core, auto);
    assert!(bars(&mut core).is_empty());
    assert!(!core.animating());
    // A press where the track was is content now.
    let list = core.key_of("list").unwrap();
    click(&mut core, Vec2::new(396.0, 190.0));
    core.set_time(1.31);
    styled(&mut core, auto);
    assert_eq!(core.scroll_offset(list).y, 0.0);
    // A wheel brings it back for another second.
    wheel(&mut core, -30.0);
    core.set_time(1.4);
    styled(&mut core, auto);
    assert_eq!(bars(&mut core).len(), 1);
    core.set_time(2.3);
    styled(&mut core, auto);
    assert_eq!(bars(&mut core).len(), 1, "quiet since 1.4: still held");
    core.set_time(2.7);
    styled(&mut core, auto);
    assert!(bars(&mut core).is_empty());
    // The pointer on the track holds it, and asks for no frames.
    core.handle_input(InputEvent::CursorMoved(Vec2::new(396.0, 100.0)));
    core.set_time(2.8);
    styled(&mut core, auto);
    assert_eq!(bars(&mut core).len(), 1);
    assert!(!core.animating(), "held by the pointer: input ends that");
    core.set_time(9.0);
    styled(&mut core, auto);
    assert_eq!(bars(&mut core).len(), 1);
}

#[test]
fn an_auto_scrollbar_without_a_clock_is_visible() {
    use kui_core::ScrollbarMode;
    let mut core = Core::new();
    styled(&mut core, |s| s.scrollbar(ScrollbarMode::Auto));
    assert_eq!(bars(&mut core).len(), 1);
    assert!(!core.animating());
}

/// A padded `widgets::list` shorter than its box asks for no frame once
/// it is laid out: the correction that puts a measured anchor back where it
/// was is for measurements, not for the clamp that keeps `top` at zero
/// while the offset is zero and the padding is not — a `set_scroll` every
/// frame was a frame every frame, which the devtools' events list paid
/// from its first event on (found building ADR 0029).
#[test]
fn a_short_padded_list_settles() {
    let mut core = Core::new();
    let mut heights = kui_core::widgets::RowHeights::new(3, 20.0);
    let frame = |core: &mut Core, heights: &mut kui_core::widgets::RowHeights| {
        let mut ui = core.frame(Size::new(400.0, 300.0), 1.0);
        ui.configure_root(NodeSpec::column().fill());
        kui_core::widgets::list(
            &mut ui,
            "list",
            NodeSpec::column().fill().pad(6.0),
            heights,
            |_ui, _i, _w| 20.0,
            |ui, _i| {
                ui.leaf(NodeSpec::row().fill());
            },
        );
        ui.finish();
    };
    frame(&mut core, &mut heights);
    frame(&mut core, &mut heights);
    let mut asked = 0;
    for _ in 0..5 {
        frame(&mut core, &mut heights);
        asked += usize::from(core.animating());
    }
    assert_eq!(
        asked, 0,
        "a laid-out list with nothing to measure asks for no frame"
    );
}

/// Hover resolves through the same `target_at` the press and the cursor
/// use (ADR 0023 decision 4; backlog AR31): over the scrollbar's track the
/// row beneath is not hovered — no `enter`, no `hover_bg` — where a press
/// there would grab the thumb; beside the bar it is.
#[test]
fn hover_over_the_scrollbar_is_not_hover_over_the_row_beneath() {
    let mut core = Core::new();
    let hovered_row = |core: &mut Core| -> Option<Key> {
        let mut ui = core.frame(Size::new(400.0, VIEW_H), 1.0);
        ui.configure_root(NodeSpec::column().fill());
        ui.with_keyed("list", NodeSpec::column().fill().scroll_y(), |ui| {
            for i in 0..ROWS {
                ui.leaf_keyed(
                    &format!("row{i}"),
                    NodeSpec::row()
                        .grow_width()
                        .height(ROW_H)
                        .bg(Color::rgb8(40, 40, 60))
                        .hover_bg(Color::WHITE)
                        .on_hover(Value::Int(i as i64)),
                );
            }
        });
        ui.finish();
        let keys: Vec<Key> = (0..ROWS)
            .map(|i| core.key_of(&format!("row{i}")).unwrap())
            .collect();
        keys.into_iter().find(|k| core.is_hovered(*k))
    };
    hovered_row(&mut core);
    // Beside the bar, on row 1: entered.
    let evs = hover(&mut core, Vec2::new(200.0, 45.0));
    assert_eq!(kinds(&evs), ["hover"]);
    assert_eq!(hovered_row(&mut core), core.key_of("row1"));
    // On the bar's track (the 4 px at the right edge), still at row 1's
    // height: the row is left, nothing is hovered, and the cursor is the
    // plain arrow the bar has.
    let evs = hover(&mut core, Vec2::new(398.0, 45.0));
    assert_eq!(kinds(&evs), ["hover"], "the leave");
    assert_eq!(evs[0].payload.get_str("phase"), Some("leave"));
    assert_eq!(
        hovered_row(&mut core),
        None,
        "over the bar, no row is hovered"
    );
    // Back beside it: entered again.
    let evs = hover(&mut core, Vec2::new(200.0, 45.0));
    assert_eq!(evs[0].payload.get_str("phase"), Some("enter"));
    assert_eq!(hovered_row(&mut core), core.key_of("row1"));
}

/// A line and a polygon inside a scrolled row are clipped as the row is:
/// a stroke drawn for a row above the container's top names the
/// container's clip, not the window's, so a graph beside a virtual list
/// does not spill over the strip above it.
#[test]
fn strokes_in_a_scrolled_row_are_clipped_by_the_container() {
    let mut core = Core::new();
    let build = |core: &mut Core| {
        let mut ui = core.frame(Size::new(400.0, VIEW_H), 1.0);
        ui.configure_root(NodeSpec::column().fill());
        ui.leaf_keyed("strip", NodeSpec::row().grow_width().height(40.0));
        ui.with_keyed("list", NodeSpec::column().fill().scroll_y(), |ui| {
            for i in 0..ROWS {
                ui.with_keyed(
                    &format!("row{i}"),
                    NodeSpec::row().grow_width().height(ROW_H),
                    |ui| {
                        ui.line(
                            Vec2::new(10.0, 0.0),
                            Vec2::new(10.0, ROW_H),
                            kui_core::Stroke::new(2.0, Color::rgb8(200, 200, 200)),
                            NodeSpec::row(),
                        );
                        ui.polygon(
                            &[
                                Vec2::new(4.0, ROW_H / 2.0 - 4.0),
                                Vec2::new(16.0, ROW_H / 2.0 - 4.0),
                                Vec2::new(16.0, ROW_H / 2.0 + 4.0),
                                Vec2::new(4.0, ROW_H / 2.0 + 4.0),
                            ],
                            NodeSpec::row().bg(Color::rgb8(255, 0, 0)),
                        );
                    },
                );
            }
        });
        ui.finish();
    };
    build(&mut core);
    core.set_scroll(list_key(), Vec2::new(0.0, 3.0 * ROW_H));
    build(&mut core);
    let (dl, _) = core.output();
    // Every quad drawn above the list's top (y < 40) must be clipped to a
    // rect that starts at the list's top or below — nothing of a row that
    // scrolled away may show over the strip.
    let spill: Vec<_> = dl
        .quads
        .iter()
        .filter(|q| q.rect.y < 40.0 - 0.5 && q.rect.h > 0.0)
        .filter(|q| dl.clips[q.clip as usize].rect.y < 40.0 - 0.5)
        .map(|q| (q.rect, q.kind, dl.clips[q.clip as usize].rect))
        .collect();
    assert!(
        spill.is_empty(),
        "drawn over the strip unclipped: {spill:?}"
    );
}

/// A container that declares a `transition` eases a *programmatic*
/// offset change — a `reveal`, a `set_scroll` — instead of jumping
/// (F80): the ribbon a keyboard walks glides, and the thumb and the
/// wheel, which are the hand's own, still land whole. `scroll_offset`
/// answers where it is going, so a view's arithmetic is the same;
/// `scroll_geometry` answers where the content is drawn, which is what
/// a virtual list slices by.
#[test]
fn a_programmatic_scroll_eases_where_the_container_asks_and_the_wheel_never_does() {
    use kui_core::{Easing, Transition};
    // A 100-wide row that scrolls, holding four 100-wide boxes.
    let build = |core: &mut Core, smooth: bool, reveal: Option<usize>| {
        let mut ui = core.frame(Size::new(100.0, 50.0), 1.0);
        ui.configure_root(NodeSpec::column().fill());
        let mut spec = NodeSpec::row().fill().scroll_x();
        if smooth {
            spec = spec.transition_with(Transition::ms(100.0).easing(Easing::Linear));
        }
        let mut boxes = Vec::new();
        let row = ui.with_keyed("row", spec, |ui| {
            for i in 0..4 {
                boxes.push(ui.leaf_keyed(
                    &format!("b{i}"),
                    NodeSpec::column().width(100.0).grow_height(),
                ));
            }
        });
        if let Some(i) = reveal {
            ui.reveal(boxes[i]);
        }
        ui.finish();
        (row, boxes)
    };
    // Where the content is drawn: the offset the last layout placed it
    // at, which is what a virtual list slices by — not the target.
    let drawn = |core: &Core, row| {
        core.scroll_geometry(row)
            .expect("a resolved container")
            .offset
            .x
    };

    let mut core = Core::new();
    core.set_time(0.0);
    let (row, _) = build(&mut core, true, None);
    assert_eq!(drawn(&core, row), 0.0, "the ribbon starts at the left");
    // A reveal of the box three widths along: the offset is the target
    // at once, the content is still where it was, and a frame is owed.
    core.set_time(0.0);
    build(&mut core, true, Some(3));
    assert_eq!(core.scroll_offset(row).x, 300.0, "the offset is the target");
    assert_eq!(drawn(&core, row), 0.0, "the content has not moved yet");
    assert!(core.owed().scroll, "a frame is owed for the leg");
    core.set_time(0.05);
    build(&mut core, true, None);
    let mid = drawn(&core, row);
    assert!((mid - 150.0).abs() < 2.0, "halfway along: {mid}");
    assert!(core.owed().scroll);
    core.set_time(0.1);
    build(&mut core, true, None);
    assert_eq!(drawn(&core, row), 300.0, "landed");
    assert!(!core.owed().scroll, "nothing owed once it lands");

    // The wheel is the hand's: it moves the content the whole way on
    // the frame it happens, mid-ease or not.
    core.set_time(0.2);
    build(&mut core, true, None);
    core.handle_input(InputEvent::CursorMoved(Vec2::new(50.0, 25.0)));
    core.handle_input(InputEvent::Scroll(Vec2::new(40.0, 0.0)));
    core.set_time(0.2);
    build(&mut core, true, None);
    let after = drawn(&core, row);
    assert!(
        (after - (300.0 - 40.0)).abs() < 1.0,
        "the wheel landed whole: {after}"
    );

    // And a container that asks for no transition jumps, as it always
    // did.
    let mut core = Core::new();
    core.set_time(0.0);
    let (row, _) = build(&mut core, false, None);
    core.set_time(0.0);
    build(&mut core, false, Some(3));
    assert_eq!(drawn(&core, row), 300.0, "no transition, no easing");
    assert!(!core.owed().scroll);
}

/// The F80 ribbon with `n` boxes and a 100 ms linear `transition`: a
/// 100-wide row that scrolls, holding `n` 100-wide boxes.
fn eased_ribbon(
    core: &mut Core,
    n: usize,
    reveal: Option<usize>,
) -> (kui_core::Key, Vec<kui_core::Key>) {
    use kui_core::{Easing, Transition};
    let mut ui = core.frame(Size::new(100.0, 50.0), 1.0);
    ui.configure_root(NodeSpec::column().fill());
    let spec = NodeSpec::row()
        .fill()
        .scroll_x()
        .transition_with(Transition::ms(100.0).easing(Easing::Linear));
    let mut boxes = Vec::new();
    let row = ui.with_keyed("row", spec, |ui| {
        for i in 0..n {
            boxes.push(ui.leaf_keyed(
                &format!("b{i}"),
                NodeSpec::column().width(100.0).grow_height(),
            ));
        }
    });
    if let Some(i) = reveal {
        ui.reveal(boxes[i]);
    }
    ui.finish();
    (row, boxes)
}

/// Where the ribbon's content is drawn, as the access tree reports it.
fn drawn_x(core: &mut Core, row: kui_core::Key) -> f32 {
    core.access_tree()
        .nodes
        .iter()
        .find(|n| n.key == row)
        .and_then(|n| n.scroll)
        .expect("the ribbon is a scroll node")
        .x
}

/// A ribbon halfway along a 0 → 300 leg: drawn at 150, going to 300.
fn ribbon_mid_leg() -> (Core, kui_core::Key) {
    let mut core = Core::new();
    core.set_time(0.0);
    let (row, _) = eased_ribbon(&mut core, 4, None);
    eased_ribbon(&mut core, 4, Some(3));
    core.set_time(0.05);
    eased_ribbon(&mut core, 4, None);
    assert!((drawn_x(&mut core, row) - 150.0).abs() < 1.0);
    (core, row)
}

/// RG17: the wheel mid-leg moves the content from where it is drawn —
/// the notch is the hand's, measured against what is on screen — not
/// from the target the leg was going to.
#[test]
fn the_wheel_mid_glide_moves_from_the_drawn_place() {
    let (mut core, row) = ribbon_mid_leg();
    core.handle_input(InputEvent::CursorMoved(Vec2::new(50.0, 25.0)));
    core.handle_input(InputEvent::Scroll(Vec2::new(40.0, 0.0)));
    eased_ribbon(&mut core, 4, None);
    let at = drawn_x(&mut core, row);
    assert!((at - 110.0).abs() < 1.0, "150 back by the notch's 40: {at}");
    assert!(!core.owed().scroll, "the hand ended the leg");
}

/// RG17: a reveal mid-leg measures its gap from the drawn node, so its
/// target is the drawn place plus that gap — not the old target plus it.
#[test]
fn a_reveal_mid_glide_lands_the_node_it_asked_for() {
    let (mut core, row) = ribbon_mid_leg();
    // b2 spans 200..300 of the content, 50..150 of the view at 150.
    eased_ribbon(&mut core, 4, Some(2));
    let target = core.scroll_offset(row).x;
    assert!(
        (target - 204.0).abs() < 1.0,
        "b2's right edge in view: {target}"
    );
    core.set_time(0.2);
    eased_ribbon(&mut core, 4, None);
    assert!((drawn_x(&mut core, row) - 204.0).abs() < 1.0, "and landed");
}

/// RG19: during a leg the geometry a view slices by is the place the
/// coming frame will draw — the leg sampled at the clock that frame's
/// layout reads — not the place the last frame drew.
#[test]
fn geometry_mid_glide_is_where_the_coming_frame_draws() {
    let mut core = Core::new();
    core.set_time(0.0);
    let (row, _) = eased_ribbon(&mut core, 4, None);
    eased_ribbon(&mut core, 4, Some(3));
    core.set_time(0.05);
    let read = core.scroll_geometry(row).expect("resolved").offset.x;
    eased_ribbon(&mut core, 4, None);
    let drawn = drawn_x(&mut core, row);
    assert!((read - drawn).abs() < 0.5, "read {read}, drawn {drawn}");
    assert!((drawn - 150.0).abs() < 1.0);
    assert!(
        !core.owed().requested,
        "the slice was right, nothing re-owed"
    );
}

/// RG22: content that shrinks under a leg is never drawn past its new
/// end — the leg's start is clamped with the target.
#[test]
fn a_leg_over_content_that_shrank_stays_inside_it() {
    let mut core = Core::new();
    core.set_time(0.0);
    let (row, _) = eased_ribbon(&mut core, 4, None);
    eased_ribbon(&mut core, 4, Some(3));
    core.set_time(0.2);
    eased_ribbon(&mut core, 4, None);
    assert_eq!(drawn_x(&mut core, row), 300.0);
    // Back to the start, and the ribbon loses two boxes mid-way: the
    // travel is 100 now.
    eased_ribbon(&mut core, 4, Some(0));
    core.set_time(0.25);
    eased_ribbon(&mut core, 2, None);
    let at = drawn_x(&mut core, row);
    assert!(at <= 100.0 + 0.5, "drawn past the end: {at}");
    let read = core.scroll_geometry(row).expect("resolved").offset.x;
    assert!(read <= 100.0 + 0.5, "sliced past the end: {read}");
}

/// RG21: mid-leg, the thumb and the access tree show where the content
/// is, not where it is going.
#[test]
fn the_access_tree_mid_glide_reports_the_drawn_offset() {
    let (mut core, row) = ribbon_mid_leg();
    assert_eq!(core.scroll_offset(row).x, 300.0, "the target");
    let at = drawn_x(&mut core, row);
    assert!((at - 150.0).abs() < 1.0, "reported {at}, drawn at 150");
}

/// RG24: a geometry read *between* two frames — Node's view runs before
/// the frame begins — is still the coming frame's read, so a container
/// that comes out another size owes the frame that re-slices it.
#[test]
fn a_geometry_read_before_the_frame_begins_is_that_frames_read() {
    let build = |core: &mut Core, h: f32| {
        let mut ui = core.frame(Size::new(100.0, h), 1.0);
        ui.configure_root(NodeSpec::column().fill());
        let k = ui.with_keyed("list", NodeSpec::column().fill().scroll_y(), |ui| {
            ui.leaf_keyed("tall", NodeSpec::column().height(1000.0));
        });
        ui.finish();
        k
    };
    // Without a read, a taller window owes nothing of the list.
    let mut core = Core::new();
    build(&mut core, 100.0);
    build(&mut core, 100.0);
    build(&mut core, 300.0);
    assert!(!core.owed().requested, "no read, nothing owed");
    // With one, between the frames, it does.
    let mut core = Core::new();
    let k = build(&mut core, 100.0);
    build(&mut core, 100.0);
    core.scroll_geometry(k).expect("resolved");
    build(&mut core, 300.0);
    assert!(core.owed().requested, "the read was sliced by a 100 box");
}

/// RG25: a container read and then not laid out — a pane in a hidden tab
/// — owes nothing, however its offset moved since: there is no frame of
/// it on screen to correct.
#[test]
fn a_read_of_a_container_not_laid_out_owes_no_frame() {
    let build = |core: &mut Core, show: bool| {
        let mut ui = core.frame(Size::new(100.0, 100.0), 1.0);
        ui.configure_root(NodeSpec::column().fill());
        // The view reads the pane's geometry whether or not it shows it
        // — a virtual list sizing its slice before the tab test.
        ui.scroll_geometry(list_key());
        if show {
            ui.with_keyed("list", NodeSpec::column().fill().scroll_y(), |ui| {
                ui.leaf_keyed("tall", NodeSpec::column().height(1000.0));
            });
        }
        ui.finish();
    };
    let mut core = Core::new();
    build(&mut core, true);
    core.set_scroll(list_key(), Vec2::new(0.0, 200.0));
    build(&mut core, false);
    for _ in 0..3 {
        build(&mut core, false);
        assert!(!core.owed().requested, "a hidden list asked for a frame");
    }
}

/// RG18: a variable-height list on a container with a `transition`
/// glides a long `set_scroll` all the way. Its height correction moved
/// the target to where the content stood — a `set_scroll` from inside the
/// view — and the leg ended a screen along instead of at the row asked
/// for.
#[test]
fn a_long_glide_over_variable_rows_reaches_the_row_asked_for() {
    use kui_core::{Easing, Transition};
    let frame = |core: &mut Core, h: &mut RowHeights| {
        let mut ui = core.frame(Size::new(400.0, VIEW_H), 1.0);
        ui.configure_root(NodeSpec::column().fill());
        kui_core::widgets::list(
            &mut ui,
            "list",
            NodeSpec::column()
                .fill()
                .transition_with(Transition::ms(100.0).easing(Easing::Linear)),
            h,
            |_ui, i, _w| var_h(i),
            |ui, i| {
                ui.leaf(
                    NodeSpec::row()
                        .fill()
                        .bg(Color::rgb8(40, 40, 60))
                        .on_click(Value::Int(i as i64)),
                );
            },
        );
        ui.finish();
    };
    let mut core = Core::new();
    let mut h = RowHeights::new(VAR_ROWS, 20.0);
    let mut t = 0.0;
    core.set_time(t);
    frame(&mut core, &mut h);
    frame(&mut core, &mut h);
    let target = 400usize;
    core.set_scroll(list_key(), Vec2::new(0.0, h.offset_of(target)));
    for _ in 0..30 {
        t += 1.0 / 60.0;
        core.set_time(t);
        frame(&mut core, &mut h);
    }
    // One ask: the row under the target stays the target while the rows
    // the leg passes are measured.
    assert_eq!(row_under(&mut core, 4.0), Some(target as i64));
}

/// RG26: F78's rule holds for a departing subtree too — a stroke in a
/// scrolled row of a panel playing its exit is cut at the list's edge,
/// as the live pass cuts it, rather than drawn over the strip above.
#[test]
fn strokes_in_a_departing_scrolled_row_are_clipped_by_the_container() {
    let mut core = Core::new();
    let build = |core: &mut Core, now: f64, show: bool| {
        core.set_time(now);
        let mut ui = core.frame(Size::new(400.0, VIEW_H), 1.0);
        ui.configure_root(NodeSpec::column().fill());
        if show {
            let panel = NodeSpec::column()
                .fill()
                .transition(100.0)
                .exit(kui_core::Enter::default().opacity(0.0));
            ui.with_keyed("panel", panel, |ui| {
                ui.leaf_keyed("strip", NodeSpec::row().grow_width().height(40.0));
                ui.with_keyed("list", NodeSpec::column().fill().scroll_y(), |ui| {
                    for i in 0..ROWS {
                        ui.with_keyed(
                            &format!("row{i}"),
                            NodeSpec::row().grow_width().height(ROW_H),
                            |ui| {
                                ui.line(
                                    Vec2::new(10.0, 0.0),
                                    Vec2::new(10.0, ROW_H),
                                    kui_core::Stroke::new(2.0, Color::rgb8(200, 200, 200)),
                                    NodeSpec::row(),
                                );
                            },
                        );
                    }
                });
            });
        }
        ui.finish();
    };
    build(&mut core, 0.0, true);
    core.set_scroll(
        Key::ROOT.str("panel").str("list"),
        Vec2::new(0.0, 3.0 * ROW_H),
    );
    build(&mut core, 0.0, true);
    // Gone: the ghost plays on this frame.
    build(&mut core, 0.01, false);
    assert!(core.animating(), "the exit is playing");
    let (dl, _) = core.output();
    let segments: Vec<_> = dl
        .quads
        .iter()
        .filter(|q| q.rect.h > 0.0 && q.kind == kui_core::QuadKind::Segment)
        .collect();
    assert!(!segments.is_empty(), "the ghost draws its strokes");
    let spill: Vec<_> = segments
        .iter()
        .filter(|q| q.rect.y < 40.0 - 0.5)
        .filter(|q| dl.clips[q.clip as usize].rect.y < 40.0 - 0.5)
        .map(|q| (q.rect, dl.clips[q.clip as usize].rect))
        .collect();
    assert!(
        spill.is_empty(),
        "a ghost's stroke over the strip: {spill:?}"
    );
}