crcbl-ui 0.20.0

Crucible immediate-mode GUI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
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
//! Styles through the tree: the cascade's order, inheritance, `var()`, the
//! resolve counter's skips, layout caches under paint-only changes, and
//! reloading — each held to the behaviour it exists for.

use std::time::Duration;

use glam::Vec2;

use super::tests::{cache_is_empty, frame, idle};
use super::*;
use crate::draw_list::DrawList;
use crate::style::{CACHE_CAPACITY, Declaration, STYLESHEET_POLL_INTERVAL, Severity, StyleStats};

const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];
const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0];
const BLUE: [f32; 4] = [0.0, 0.0, 1.0, 1.0];
const BLACK: [f32; 4] = [0.0, 0.0, 0.0, 1.0];

/// The style `key` was built with this frame.
fn style_of(ui: &Ui, key: NodeKey) -> NodeStyle {
    ui.nodes
        .iter()
        .find(|node| node.key == key)
        .expect("built this frame")
        .style
}

fn hover(at: Vec2) -> PointerInput {
    PointerInput::hovering(at)
}

// ---------------------------------------------------------------------------
// The cascade
// ---------------------------------------------------------------------------

/// **`default.css` loses to any app rule, a higher tier beats a later lower
/// one, a later rule wins within a tier, and inline beats everything** — each
/// against a control that shows the losing rule would otherwise apply.
#[test]
fn the_cascade_orders_origin_then_tier_then_source_and_inline_wins() {
    let app = "
        readout { flex-direction: row-reverse; }
        span { position: relative; }
        #pick { width: 10px; }
        .pick { width: 20px; }
        .a { flex-wrap: wrap-reverse; height: 1px; }
        .b { height: 2px; }
        block { flex-wrap: wrap; }
    ";
    let build = |ui: &mut Ui| {
        let mut keys = Vec::new();
        ui.block("", &[], |ui| {
            keys.push(ui.block("readout", &[], |_| {}).key);
            keys.push(ui.span(".readout-reading", "1", &[]).key);
            keys.push(ui.block("#pick.pick", &[], |_| {}).key);
            keys.push(ui.block(".a.b", &[], |_| {}).key);
            keys.push(
                ui.block(".b.a", &[Declaration::Height(LengthAuto::Px(5.0))], |_| {})
                    .key,
            );
            keys.push(ui.block(".pick", &[], |_| {}).key);
            keys.push(ui.block("", &[], |_| {}).key);
        });
        keys
    };

    let mut plain = Ui::new();
    let mut keys = Vec::new();
    frame(&mut plain, idle(), |ui| keys = build(ui));
    assert_eq!(
        style_of(&plain, keys[0]).flex_direction,
        FlexDirection::Column
    );
    assert_eq!(style_of(&plain, keys[1]).position, Position::Absolute);

    let mut ui = Ui::new();
    ui.add_stylesheet("app.css", app);
    frame(&mut ui, idle(), |ui| keys = build(ui));
    assert_eq!(
        style_of(&ui, keys[0]).flex_direction,
        FlexDirection::RowReverse,
        "default.css's type rule beat the app's"
    );
    assert_eq!(
        style_of(&ui, keys[1]).position,
        Position::Relative,
        "default.css's class rule beat an app type rule: origin must come before tier"
    );
    assert_eq!(
        style_of(&ui, keys[5]).width,
        LengthAuto::Px(20.0),
        "the class rule applies alone"
    );
    assert_eq!(
        style_of(&ui, keys[2]).width,
        LengthAuto::Px(10.0),
        "a later class rule beat an id rule"
    );
    let ab = style_of(&ui, keys[3]);
    assert_eq!(
        ab.height,
        LengthAuto::Px(2.0),
        "the earlier of two class rules won"
    );
    assert_eq!(
        ab.flex_wrap,
        FlexWrap::WrapReverse,
        "a later type rule beat a class rule"
    );
    assert_eq!(
        style_of(&ui, keys[4]).height,
        LengthAuto::Px(5.0),
        "a rule beat inline"
    );
    assert_eq!(
        style_of(&ui, keys[6]).flex_wrap,
        FlexWrap::Wrap,
        "the type rule applies alone"
    );
}

/// **`color` and the text properties inherit and nothing else does; `unset` inherits,
/// `initial` does not** — and a parent's inline colour changing reaches a child
/// whose own inputs did not change.
#[cfg(feature = "parsed-font")]
#[test]
fn inherited_properties_reach_descendants_and_nothing_else_does() {
    let sheet = "
        .panel {
            color: #ff0000; font-size: 20px; background: #0000ff; padding: 3px;
            font-family: sans-serif; line-height: 1.5; text-align: right;
        }
        .own { color: #00ff00; }
        .initial {
            color: initial; font-size: initial;
            font-family: initial; line-height: initial; text-align: initial;
        }
        .reset { color: unset; }
    ";
    let build = |ui: &mut Ui, panel_inline: &[Declaration]| {
        let mut keys = Vec::new();
        ui.block(".panel", panel_inline, |ui| {
            keys.push(ui.span("", "direct", &[]).key);
            ui.block(".own", &[], |ui| keys.push(ui.span("", "own", &[]).key));
            ui.block(".initial", &[], |ui| {
                keys.push(ui.span("", "initial", &[]).key)
            });
            ui.block(".reset", &[], |ui| keys.push(ui.span("", "reset", &[]).key));
            ui.block("", &[], |ui| {
                ui.block("", &[], |ui| keys.push(ui.span("", "deep", &[]).key));
            });
        });
        keys
    };
    let mut ui = Ui::new();
    ui.add_stylesheet("inherit.css", sheet);
    let mut keys = Vec::new();
    frame(&mut ui, idle(), |ui| keys = build(ui, &[]));

    let direct = style_of(&ui, keys[0]);
    assert_eq!((direct.color, direct.font_size), (RED, 20.0));
    assert_eq!(
        (direct.font_family, direct.line_height, direct.text_align),
        (
            FontFamily::Sans,
            LineHeight::Multiple(1.5),
            TextAlign::Right
        )
    );
    assert_eq!(direct.background, [0.0; 4], "background inherited");
    assert_eq!(
        direct.padding,
        NodeStyle::DEFAULT.padding,
        "padding inherited"
    );
    assert_eq!(style_of(&ui, keys[1]).color, GREEN);
    let initial = style_of(&ui, keys[2]);
    assert_eq!(
        (initial.color, initial.font_size),
        (NodeStyle::DEFAULT.color, NodeStyle::DEFAULT.font_size)
    );
    assert_eq!(
        (initial.font_family, initial.line_height, initial.text_align),
        (FontFamily::Bitmap, LineHeight::Normal, TextAlign::Start)
    );
    let deep = style_of(&ui, keys[4]);
    assert_eq!(
        (deep.font_family, deep.line_height, deep.text_align),
        (
            FontFamily::Sans,
            LineHeight::Multiple(1.5),
            TextAlign::Right
        ),
        "two levels down lost the text properties"
    );
    assert_eq!(style_of(&ui, keys[3]).color, RED, "`unset` did not inherit");
    assert_eq!(
        style_of(&ui, keys[4]).color,
        RED,
        "two levels down lost the colour"
    );

    frame(&mut ui, idle(), |ui| {
        keys = build(ui, &[Declaration::Color(BLUE)])
    });
    assert_eq!(
        style_of(&ui, keys[4]).color,
        BLUE,
        "a cached child kept its parent's old inherited colour"
    );
    assert_eq!(style_of(&ui, keys[1]).color, GREEN);
}

/// **`var()` substitutes an inherited or own custom property, falls back,
/// nests in a function, and a cycle or a missing variable unsets the property
/// over an earlier rule** — with a warning naming where it was written.
#[test]
fn var_resolves_through_the_tree_and_an_invalid_one_unsets_its_property() {
    let sheet = "\
.theme { --accent: #00ff00; --pad: 4px 6px; --red: 255; --loop: var(--loop); }
.card { background: var(--accent); padding: var(--pad); width: var(--missing, 30px);
  height: var(--loop, 7px); border-color: rgb(var(--red), 0, 0); margin-left: 9px; }
.dark { --accent: #000000; }
.late { margin-left: var(--nope); }
";
    let logs = crcbl_core::log::capture();
    let mut ui = Ui::new();
    ui.add_stylesheet("vars.css", sheet);
    let mut keys = Vec::new();
    frame(&mut ui, idle(), |ui| {
        ui.block(".theme", &[], |ui| {
            keys.push(ui.block(".card", &[], |_| {}).key);
            keys.push(ui.block(".card.dark.late", &[], |_| {}).key);
        });
    });
    let card = style_of(&ui, keys[0]);
    assert_eq!(
        card.background, GREEN,
        "an inherited variable did not substitute"
    );
    assert_eq!(
        card.padding,
        Edges {
            top: Length::Px(4.0),
            right: Length::Px(6.0),
            bottom: Length::Px(4.0),
            left: Length::Px(6.0)
        },
        "a shorthand did not expand after substitution"
    );
    assert_eq!(
        card.width,
        LengthAuto::Px(30.0),
        "the fallback was not used"
    );
    assert_eq!(
        card.height,
        LengthAuto::Px(7.0),
        "a cyclic variable was not invalid"
    );
    assert_eq!(
        card.border_color, RED,
        "var() inside rgb() did not substitute"
    );
    assert_eq!(card.margin.left, LengthAuto::Px(9.0));

    let dark = style_of(&ui, keys[1]);
    assert_eq!(
        dark.background, BLACK,
        "an own custom property did not shadow the inherited one"
    );
    assert_eq!(
        dark.margin.left,
        NodeStyle::DEFAULT.margin.left,
        "an invalid var() kept the earlier rule's value instead of unsetting"
    );
    let warned = logs
        .records()
        .into_iter()
        .filter(|record| {
            record
                .message
                .starts_with("vars.css:5:9: warning: `margin-left")
        })
        .count();
    assert_eq!(warned, 1, "{:#?}", logs.records());
}

// ---------------------------------------------------------------------------
// The resolve counter
// ---------------------------------------------------------------------------

struct Hovered {
    button: NodeKey,
    hint: NodeKey,
}

/// A 200-wide column: a 50 × 20 `.button`, a `.list` of three 10-high `.row`s
/// and a `.hint` — whose rules are hover on the button, a descendant rule with
/// no pseudo-class for the rows, and hover on the panel for the hint.
fn hovered_page(ui: &mut Ui) -> Hovered {
    let fixed = |width: f32, height: f32| {
        [
            Declaration::Width(LengthAuto::Px(width)),
            Declaration::Height(LengthAuto::Px(height)),
        ]
    };
    let mut button = None;
    let mut hint = None;
    ui.block(
        ".panel",
        &[Declaration::FlexDirection(FlexDirection::Column)],
        |ui| {
            button = Some(ui.block(".button", &fixed(50.0, 20.0), |_| {}).key);
            ui.block(
                ".list",
                &[Declaration::FlexDirection(FlexDirection::Column)],
                |ui| {
                    for row in 0..3 {
                        ui.block_keyed(
                            row,
                            ".row",
                            &[Declaration::Width(LengthAuto::Px(200.0))],
                            |_| {},
                        );
                    }
                },
            );
            hint = Some(ui.block(".hint", &fixed(200.0, 10.0), |_| {}).key);
        },
    );
    Hovered {
        button: button.expect("built"),
        hint: hint.expect("built"),
    }
}

/// One frame of [`hovered_page`] at `pointer`: what resolution did, and the
/// keys.
fn step(ui: &mut Ui, pointer: PointerInput) -> (StyleStats, Hovered) {
    let mut keys = None;
    frame(ui, pointer, |ui| keys = Some(hovered_page(ui)));
    (ui.style_stats(), keys.expect("built"))
}

const HOVERED_SHEET: &str = "
    .button:hover { background: #ff0000; }
    .list .row { height: 10px; }
    .panel:hover .hint { color: #00ff00; }
";

/// **A pointer move re-resolves exactly the nodes whose candidate rules test
/// what changed** — the button for its own hover, the hint for the panel's —
/// and none of the nodes whose hover also changed but whose rules never
/// mention it; and three rows of one class merge their rules once.
#[test]
fn a_hover_change_re_resolves_only_the_nodes_whose_rules_depend_on_it() {
    let mut ui = Ui::new();
    ui.add_stylesheet("hover.css", HOVERED_SHEET);
    let nowhere = idle();
    let on_row = hover(Vec2::new(100.0, 25.0));
    let on_button = hover(Vec2::new(10.0, 10.0));

    let first = step(&mut ui, nowhere).0;
    assert_eq!(first.nodes, 7);
    assert_eq!(first.resolves, 7, "a first frame resolves everything");
    assert_eq!(
        first.definitions, 2,
        "one definition for the unmatched nodes and one for the rows"
    );
    assert_eq!(
        step(&mut ui, nowhere).0.resolves,
        0,
        "an unchanged frame resolved something"
    );

    // Over a row: the panel, the list and the row are hovered now. Only the
    // hint's rule reads any of that.
    assert_eq!(
        step(&mut ui, on_row).0.resolves,
        1,
        "hovering a row re-resolved more than the hint"
    );
    let (_, keys) = step(&mut ui, on_row);
    assert_eq!(style_of(&ui, keys.hint).color, GREEN);
    assert_eq!(ui.style_stats().resolves, 0);

    // Onto the button: its own hover changes; the panel is still hovered.
    assert_eq!(
        step(&mut ui, on_button).0.resolves,
        1,
        "moving within the panel re-resolved the hint"
    );
    let keys = step(&mut ui, on_button).1;
    assert_eq!(style_of(&ui, keys.button).background, RED);
    assert_eq!(ui.style_stats().resolves, 0);

    let (away, keys) = step(&mut ui, nowhere);
    assert_eq!(
        away.resolves, 2,
        "leaving should re-resolve the button and the hint"
    );
    assert_eq!(style_of(&ui, keys.button).background, [0.0; 4]);
    assert_eq!(style_of(&ui, keys.hint).color, NodeStyle::DEFAULT.color);
}

/// **A rule that changes only paint on hover clears no layout cache; one that
/// changes a size clears that node's and its ancestors' and nobody else's.**
#[test]
fn a_paint_only_hover_keeps_every_layout_cache_and_a_size_change_clears_only_its_chain() {
    let sheet = "
        .paint { width: 50px; height: 20px; }
        .paint:hover { background: #ff0000; border-color: #00ff00; color: #0000ff; border-top-left-radius: 3px; }
        .grow { width: 40px; height: 20px; }
        .grow:hover { width: 60px; }
        .sibling { width: 30px; height: 20px; }
    ";
    let build = |ui: &mut Ui| {
        let mut keys = Vec::new();
        let root = ui
            .block("#root", &[], |ui| {
                keys.push(ui.block(".paint", &[], |_| {}).key);
                keys.push(ui.block(".grow", &[], |_| {}).key);
                keys.push(ui.block(".sibling", &[], |_| {}).key);
            })
            .key;
        keys.insert(0, root);
        keys
    };
    let atlas = FontAtlas::built_in();
    let mut ui = Ui::new();
    ui.add_stylesheet("paint.css", sheet);
    let mut keys = Vec::new();
    frame(&mut ui, idle(), |ui| keys = build(ui));
    frame(&mut ui, idle(), |ui| keys = build(ui));

    ui.begin_frame(hover(Vec2::new(10.0, 10.0)));
    keys = build(&mut ui);
    let [root, paint, grow, sibling] = keys[..] else {
        unreachable!("four nodes");
    };
    assert_eq!(
        style_of(&ui, paint).background,
        RED,
        "the hover rule did not apply"
    );
    for key in [root, paint, grow, sibling] {
        assert!(
            !cache_is_empty(&ui, key),
            "a paint-only hover cleared {key:?}'s layout cache"
        );
    }
    ui.layout(Vec2::ZERO, AvailableSpace::MAX_CONTENT, &atlas);

    ui.begin_frame(hover(Vec2::new(60.0, 10.0)));
    build(&mut ui);
    assert!(
        cache_is_empty(&ui, grow) && cache_is_empty(&ui, root),
        "a size change kept a stale cache"
    );
    assert!(
        !cache_is_empty(&ui, paint) && !cache_is_empty(&ui, sibling),
        "a size change cleared its siblings' caches"
    );
    ui.layout(Vec2::ZERO, AvailableSpace::MAX_CONTENT, &atlas);
    assert_eq!(
        ui.rect(sibling).expect("laid out").0.x,
        110.0,
        "the sibling did not move"
    );
}

/// A child under each of `parents` blocks, every parent in a colour of its own
/// so each is an inherited identity, and each child's merged rules a
/// definition, of their own; built last to first when `reversed`. Returns each
/// child's key with its parent's colour.
fn coloured_parents(ui: &mut Ui, parents: usize, reversed: bool) -> Vec<(NodeKey, [f32; 4])> {
    let mut children = Vec::with_capacity(parents);
    let order: Box<dyn Iterator<Item = usize>> = if reversed {
        Box::new((0..parents).rev())
    } else {
        Box::new(0..parents)
    };
    for at in order {
        let colour = [at as f32 / parents as f32, 0.0, 0.0, 1.0];
        ui.block_keyed(at, ".parent", &[Declaration::Color(colour)], |ui| {
            children.push((ui.block(".child", &[], |_| {}).key, colour));
        });
    }
    children
}

/// **A tree that outgrows [`CACHE_CAPACITY`] has the caches dropped at the
/// next frame's start, and every node re-resolves to the style it had** — each
/// child still inheriting its own parent's colour although building in the
/// other order hands the parents each other's old ids — against a control under
/// the cap whose unchanged frame resolves nothing.
#[test]
fn outgrowing_the_cache_re_resolves_every_node_to_the_same_style() {
    // More than the identities and definitions the tree adds of its own.
    const MARGIN: usize = 8;
    let mut under = Ui::new();
    frame(&mut under, idle(), |ui| {
        coloured_parents(ui, CACHE_CAPACITY - MARGIN, false);
    });
    frame(&mut under, idle(), |ui| {
        coloured_parents(ui, CACHE_CAPACITY - MARGIN, false);
    });
    assert_eq!(
        under.style_stats().resolves,
        0,
        "a tree under the cap re-resolved"
    );

    let mut over = Ui::new();
    frame(&mut over, idle(), |ui| {
        coloured_parents(ui, CACHE_CAPACITY, false);
    });
    let mut children = Vec::new();
    frame(&mut over, idle(), |ui| {
        children = coloured_parents(ui, CACHE_CAPACITY, true);
    });
    let stats = over.style_stats();
    assert_eq!(
        stats.resolves, stats.nodes,
        "outgrowing the cache did not re-resolve everything"
    );
    for (child, colour) in children {
        assert_eq!(
            style_of(&over, child).color,
            colour,
            "a child inherited another parent's colour after the trim"
        );
    }
}

// ---------------------------------------------------------------------------
// Stylesheet changes
// ---------------------------------------------------------------------------

/// A file under the system's temporary directory, removed when dropped.
struct TempSheet(std::path::PathBuf);

impl TempSheet {
    fn new(test: &str, css: &str) -> Self {
        let path = std::env::temp_dir().join(format!("crcbl-ui-{test}-{}.css", std::process::id()));
        std::fs::write(&path, css).expect("the temporary sheet is written");
        Self(path)
    }

    fn write(&self, css: &str) {
        std::fs::write(&self.0, css).expect("the temporary sheet is rewritten");
    }
}

impl Drop for TempSheet {
    fn drop(&mut self) {
        // A leftover file in the temporary directory is harmless; a panic here
        // would hide the assertion that failed.
        if let Err(error) = std::fs::remove_file(&self.0) {
            eprintln!("{}: not removed: {error}", self.0.display());
        }
    }
}

fn width_of_x(ui: &mut Ui) -> LengthAuto {
    let mut key = None;
    frame(ui, idle(), |ui| key = Some(ui.block(".x", &[], |_| {}).key));
    style_of(ui, key.expect("built")).width
}

/// **A reload with a parse error keeps the last good sheet and says where the
/// error is; the next good write replaces it, one full re-resolve follows, and
/// the file is looked at no more often than the poll interval.**
#[test]
fn a_reload_keeps_the_last_good_sheet_on_a_parse_error_and_takes_the_next_good_one() {
    // Each write is a different length, so the stamp moves whatever the
    // filesystem's clock granularity.
    let file = TempSheet::new("reload", ".x { width: 10px; }");
    let logs = crcbl_core::log::capture();
    let mut ui = Ui::new();
    ui.load_stylesheet(&file.0).expect("the sheet loads");
    assert_eq!(width_of_x(&mut ui), LengthAuto::Px(10.0));
    let generation = ui.stylesheet_generation();
    assert_eq!(
        ui.poll_stylesheets(Duration::ZERO),
        0,
        "an untouched file was reloaded"
    );

    file.write(".x { width: 20px; }\n.y + .z { width: 1px; }");
    assert_eq!(
        ui.poll_stylesheets(STYLESHEET_POLL_INTERVAL),
        0,
        "a sheet with an error was taken"
    );
    assert_eq!(
        width_of_x(&mut ui),
        LengthAuto::Px(10.0),
        "the last good sheet was not kept"
    );
    assert_eq!(ui.stylesheet_generation(), generation);
    let name = file.0.display().to_string();
    let records = logs.records();
    assert!(
        records
            .iter()
            .any(|record| record.message.starts_with(&format!("{name}:2:1: error:"))),
        "the error was not reported at its file and line: {records:#?}"
    );
    assert!(
        records
            .iter()
            .any(|record| record.message.contains("keeping the last good sheet"))
    );

    file.write(".x { width: 30px; }");
    let within = STYLESHEET_POLL_INTERVAL + STYLESHEET_POLL_INTERVAL / 2;
    assert_eq!(
        ui.poll_stylesheets(within),
        0,
        "the file was looked at inside the interval"
    );
    assert_eq!(
        ui.poll_stylesheets(STYLESHEET_POLL_INTERVAL * 2),
        1,
        "the good write was not taken"
    );
    assert_eq!(width_of_x(&mut ui), LengthAuto::Px(30.0));
    assert_eq!(ui.stylesheet_generation(), generation + 1);
    assert_eq!(
        ui.style_stats().resolves,
        1,
        "the reload did not re-resolve the node"
    );
    assert_eq!(width_of_x(&mut ui), LengthAuto::Px(30.0));
    assert_eq!(ui.style_stats().resolves, 0);
}

/// **`replace_stylesheet` returns the errors that kept the old sheet**, located,
/// and takes a sheet whose only problems are warnings.
#[test]
fn replacing_a_sheet_returns_its_errors_and_takes_one_with_only_warnings() {
    let mut ui = Ui::new();
    let sheet = ui.add_stylesheet("live.css", ".x { width: 10px; }");
    assert_eq!(width_of_x(&mut ui), LengthAuto::Px(10.0));

    let errors = ui
        .replace_stylesheet(sheet, ".x { width: 20px; }\n\n  ::before { }")
        .expect_err("an error was accepted");
    assert_eq!(errors.len(), 1, "{errors:#?}");
    assert_eq!(
        (errors[0].line, errors[0].column, errors[0].severity),
        (3, 3, Severity::Error)
    );
    assert_eq!(width_of_x(&mut ui), LengthAuto::Px(10.0));

    ui.replace_stylesheet(sheet, ".x { width: 20px; wobble: 1px; }")
        .expect("warnings are not errors");
    assert_eq!(width_of_x(&mut ui), LengthAuto::Px(20.0));
}

/// **A malformed builder selector is reported once, and the node is still
/// built and laid out** with no selector at all.
#[test]
fn a_malformed_node_selector_warns_once_and_the_node_is_still_built() {
    let logs = crcbl_core::log::capture();
    let mut ui = Ui::new();
    ui.add_stylesheet("any.css", "* { height: 4px; }");
    let mut key = None;
    for _ in 0..3 {
        frame(&mut ui, idle(), |ui| {
            key = Some(ui.block(".a b", &[], |_| {}).key)
        });
    }
    let warnings = logs
        .records()
        .into_iter()
        .filter(|record| record.message.contains("`.a b` is not a node selector"))
        .count();
    assert_eq!(warnings, 1);
    assert_eq!(
        style_of(&ui, key.expect("built")).height,
        LengthAuto::Px(4.0)
    );
}

// ---------------------------------------------------------------------------
// Images
// ---------------------------------------------------------------------------

/// **`border-image` cascades like any paint property**: a state rule's
/// longhand replaces only the source the base rule's shorthand set, keeping
/// its slice and `fill`; `initial` clears it; and a child inherits none of it.
#[test]
fn border_image_cascades_by_state_and_is_not_inherited() {
    let mut ui = Ui::new();
    ui.add_stylesheet(
        "frame.css",
        ".frame { width: 40px; height: 20px; border-image: url(idle) 4 fill / 2; }
         .frame:hover { border-image-source: url(lit); }
         .cleared { border-image: url(idle) 4; border-image-source: initial; }",
    );
    let build = |ui: &mut Ui| {
        let mut keys = Vec::new();
        ui.block("", &[], |ui| {
            let frame = ui.block(".frame", &[], |ui| {
                keys.push(ui.block("", &[], |_| {}).key);
            });
            keys.insert(0, frame.key);
            keys.push(ui.block(".cleared", &[], |_| {}).key);
        });
        keys
    };
    let mut keys = Vec::new();
    frame(&mut ui, idle(), |ui| keys = build(ui));
    let at_rest = style_of(&ui, keys[0]).border_image;
    assert_eq!(at_rest.source, Some(ImageName::new("idle")));
    assert_eq!(
        (at_rest.slice.left, at_rest.fill, at_rest.width.top),
        (4.0, true, BorderImageWidth::Multiple(2.0))
    );

    // Hit testing reads last frame's rectangles, so the hover lands a frame
    // after the pointer does.
    for _ in 0..2 {
        frame(&mut ui, hover(Vec2::new(10.0, 10.0)), |ui| keys = build(ui));
    }
    let hovered = style_of(&ui, keys[0]).border_image;
    assert_eq!(hovered.source, Some(ImageName::new("lit")));
    assert_eq!(
        BorderImage {
            source: at_rest.source,
            ..hovered
        },
        at_rest,
        "the state rule moved more than the source"
    );
    assert_eq!(style_of(&ui, keys[1]).border_image, BorderImage::NONE);
    assert_eq!(style_of(&ui, keys[2]).border_image.source, None);
    assert_eq!(style_of(&ui, keys[2]).border_image.slice.top, 4.0);
}

/// Every `Image` command of `list`: its rectangle and its UV rectangle.
fn quads(list: &DrawList) -> Vec<[Vec2; 4]> {
    list.commands()
        .iter()
        .filter_map(|command| match *command {
            crate::draw_list::DrawCommand::Image {
                min,
                max,
                uv_min,
                uv_max,
                ..
            } => Some([min, max, uv_min, uv_max]),
            _ => None,
        })
        .collect()
}

/// **A block's `border-image` is a nine-slice over its border box, drawn in
/// place of its border, with each band its side's width** — and its
/// `background-image` is stretched over the padding box between the
/// background and the frame.
///
/// The sides are deliberately uneven, so a band that took another side's
/// width, or a slice read off the wrong edge, lands somewhere else.
#[test]
fn a_border_image_draws_a_nine_slice_over_the_border_box_in_place_of_the_border() {
    let mut images = crate::image::ImageAtlas::new();
    let frame_image = images.register(16, 16, &[200; 16 * 16 * 4]).expect("fits");
    let sky = images.register(8, 8, &[90; 8 * 8 * 4]).expect("fits");
    let sheet = |fill: &str| {
        format!(
            ".box {{ width: 40px; height: 24px; border-width: 2px 3px 4px 5px;
                     border-color: red; background: blue; background-image: url(sky);
                     border-image: url(frame) 1 2 3 4 {fill} / 2 1px 1 6px; }}"
        )
    };
    let draw = |css: &str, bind_frame: bool| {
        let mut ui = Ui::new();
        ui.add_stylesheet("box.css", css);
        ui.set_image("sky", sky);
        if bind_frame {
            ui.set_image("frame", frame_image);
        }
        frame(&mut ui, idle(), |ui| {
            ui.block(".box", &[], |_| {});
        });
        let mut list = DrawList::new();
        ui.emit(&mut list);
        list
    };

    let list = draw(&sheet("fill"), true);
    assert!(
        matches!(list.commands()[0], crate::draw_list::DrawCommand::Rect { color, .. } if color == BLUE),
        "the background is not drawn first: {:#?}",
        list.commands()
    );
    assert!(
        !list.commands().iter().any(|command| matches!(
            command,
            crate::draw_list::DrawCommand::RectOutline { .. }
                | crate::draw_list::DrawCommand::Rect { color: RED, .. }
        )),
        "the border was drawn under its image"
    );
    let drawn = quads(&list);
    assert_eq!(drawn.len(), 1 + 9, "{drawn:?}");
    // The background image over the padding box: in by the border widths.
    assert_eq!(
        drawn[0],
        [
            Vec2::new(5.0, 2.0),
            Vec2::new(37.0, 20.0),
            sky.uv_min(),
            sky.uv_max()
        ]
    );
    // The frame's corners, each band its own side's width: top 2 × 2px,
    // right 1px, bottom 1 × 4px, left 6px.
    let (top, right, bottom, left) = (4.0, 1.0, 4.0, 6.0);
    let corner = |at: usize| (drawn[1 + at][0], drawn[1 + at][1]);
    assert_eq!(corner(0), (Vec2::ZERO, Vec2::new(left, top)));
    assert_eq!(
        corner(2),
        (Vec2::new(40.0 - right, 0.0), Vec2::new(40.0, top))
    );
    assert_eq!(
        corner(6),
        (Vec2::new(0.0, 24.0 - bottom), Vec2::new(left, 24.0))
    );
    // Cut where the slice says, in texels: 4 from the left and 1 from the top.
    assert_eq!(
        (drawn[1][2], drawn[1][3]),
        (
            frame_image.uv(Vec2::ZERO),
            frame_image.uv(Vec2::new(4.0, 1.0))
        )
    );
    assert_eq!(
        drawn[1 + 8][3],
        frame_image.uv(Vec2::new(16.0, 16.0)),
        "the bottom-right quad does not reach the picture's corner"
    );

    // Without `fill` the middle is the one quad left out.
    let hollow = quads(&draw(&sheet(""), true));
    assert_eq!(hollow.len(), 1 + 8);
    assert!(
        !hollow.contains(&drawn[1 + 4]),
        "the middle quad was drawn without `fill`"
    );

    // A name nothing bound draws no picture, and the border is drawn instead,
    // as CSS draws a border whose image did not load.
    let unbound = draw(&sheet("fill"), false);
    assert_eq!(quads(&unbound).len(), 1, "only the background image");
    assert!(
        unbound.commands().iter().any(|command| matches!(
            command,
            crate::draw_list::DrawCommand::Rect { color: RED, .. }
        )),
        "the border was not drawn for an unbound frame"
    );
}

// ---------------------------------------------------------------------------
// Rich text
// ---------------------------------------------------------------------------

/// **Rich text is a row of spans.** A launcher's result with its match
/// highlighted is three runs in one row block, and each draws in its own
/// colour, on one line, edge to edge: the second run starts where the first
/// ends, and the third where the second does.
#[test]
fn a_row_of_spans_draws_each_run_in_its_own_style_edge_to_edge() {
    let mut ui = Ui::new();
    ui.add_stylesheet(
        "rich.css",
        ".line { flex-direction: row; } .hit { color: #ff0000; } .rest { color: #0000ff; }",
    );
    let mut keys = Vec::new();
    frame(&mut ui, idle(), |ui| {
        ui.block(".line", &[], |ui| {
            keys.push(ui.span("#before.rest", "fi", &[]).key);
            keys.push(ui.span("#match.hit", "re", &[]).key);
            keys.push(ui.span("#after.rest", "fox", &[]).key);
        });
    });
    let mut list = DrawList::new();
    ui.emit(&mut list);
    let runs: Vec<(&str, Vec2, [f32; 4])> = list
        .commands()
        .iter()
        .filter_map(|command| match command {
            crate::draw_list::DrawCommand::Text {
                pos, text, color, ..
            } => Some((text.as_str(), *pos, *color)),
            _ => None,
        })
        .collect();
    assert_eq!(
        runs.iter().map(|run| (run.0, run.2)).collect::<Vec<_>>(),
        [("fi", BLUE), ("re", RED), ("fox", BLUE)]
    );
    let [before, matched, after] = [runs[0].1, runs[1].1, runs[2].1];
    assert!(
        before.y == matched.y && matched.y == after.y,
        "one line: {runs:?}"
    );
    // Each run starts at the far edge of the one before it, as laid out.
    let right = |key| {
        let (min, max) = ui.rect(key).expect("laid out");
        assert!(max.x > min.x, "a run with no width");
        max.x
    };
    assert!(matched.x > before.x, "{runs:?}");
    assert_eq!(matched.x, right(keys[0]), "{runs:?}");
    assert_eq!(after.x, right(keys[1]), "{runs:?}");
}

// ---------------------------------------------------------------------------
// The cursor
// ---------------------------------------------------------------------------

/// **The cursor is the topmost node's, inherited, held through a drag.** A
/// span with no `cursor` of its own takes its link's; a `none` hides the
/// pointer; the root's shape shows between its children, and the arrow
/// outside every node. A press on the link keeps its shape while the pointer
/// is dragged off it.
#[test]
fn the_cursor_is_the_topmost_nodes_inherited_and_held_through_a_drag() {
    use crcbl_core::input::CursorIcon;

    let mut ui = Ui::new();
    ui.add_stylesheet(
        "cursor.css",
        "#root { width: 100px; height: 100px; cursor: crosshair; }
         #link { width: 50px; height: 20px; cursor: pointer; }
         #hidden { width: 50px; height: 20px; cursor: none; }",
    );
    let build = |ui: &mut Ui| {
        ui.block("#root", &[], |ui| {
            ui.block("#link", &[], |ui| {
                ui.span("#label", "go", &[]);
            });
            ui.block("#hidden", &[], |_| {});
        });
    };
    let at = |x: f32, y: f32| PointerInput::hovering(Vec2::new(x, y));
    frame(&mut ui, idle(), build);

    let mut cursor_at = |pointer: PointerInput| {
        frame(&mut ui, pointer, build);
        ui.cursor()
    };
    assert_eq!(
        cursor_at(at(2.0, 2.0)),
        Some(CursorIcon::Pointer),
        "the label inherits"
    );
    assert_eq!(cursor_at(at(60.0, 5.0)), None, "cursor: none hides it");
    assert_eq!(cursor_at(at(2.0, 60.0)), Some(CursorIcon::Crosshair));
    assert_eq!(cursor_at(at(500.0, 500.0)), Some(CursorIcon::Default));

    let held = |x, y| PointerInput {
        down: true,
        ..at(x, y)
    };
    assert_eq!(cursor_at(held(2.0, 2.0)), Some(CursorIcon::Pointer));
    assert_eq!(
        cursor_at(held(2.0, 60.0)),
        Some(CursorIcon::Pointer),
        "dragged off the link, the press still holds it"
    );
    assert_eq!(
        cursor_at(PointerInput {
            released: true,
            ..at(2.0, 60.0)
        }),
        Some(CursorIcon::Crosshair),
        "released, the root's again"
    );
}

// ---------------------------------------------------------------------------
// Opacity
// ---------------------------------------------------------------------------

/// Each command's kind and colour, in paint order: a `Rect`'s fill, a text
/// span's colour, an outline's colour.
fn painted(list: &DrawList) -> Vec<(&'static str, [f32; 4])> {
    list.commands()
        .iter()
        .map(|command| match command {
            crate::draw_list::DrawCommand::Rect { color, .. } => ("rect", *color),
            crate::draw_list::DrawCommand::Text { color, .. } => ("text", *color),
            crate::draw_list::DrawCommand::RectOutline { color, .. } => ("outline", *color),
            other => panic!("this tree draws no {other:?}"),
        })
        .collect()
}

/// **A node below full opacity is drawn with its subtree as one group**: its
/// box and everything inside it, a faded child as a group nested in it, and a
/// sibling at full opacity outside both. Not inherited: the child of a faded
/// node keeps its own opacity of one. Its outline, painted after the layer
/// and outside every group, is faded by its own and its ancestors' opacity
/// multiplied.
#[test]
fn a_faded_node_draws_its_subtree_as_one_group_and_nested_ones_multiply() {
    let mut ui = Ui::new();
    ui.add_stylesheet(
        "fade.css",
        ".box { background: #ff0000; opacity: 0.5; }
         .inner { background: #0000ff; opacity: 50%; outline: 2px #00ff00; }
         .plain { background: #000000; }",
    );
    let mut keys = Vec::new();
    frame(&mut ui, idle(), |ui| {
        ui.block("", &[], |ui| {
            let faded = ui.block(".box", &[], |ui| {
                keys.push(ui.span("", "hi", &[]).key);
                let inner = ui.block(".inner", &[], |ui| {
                    ui.span("", "in", &[]);
                });
                keys.push(inner.key);
            });
            keys.insert(0, faded.key);
            keys.push(ui.block(".plain", &[], |_| {}).key);
        });
    });
    assert_eq!(style_of(&ui, keys[1]).opacity, 1.0, "not inherited");
    assert_eq!(style_of(&ui, keys[2]).opacity, 0.5);
    let mut list = DrawList::new();
    ui.emit(&mut list);
    assert_eq!(
        painted(&list),
        [
            ("rect", RED),
            ("text", [1.0; 4]),
            ("rect", BLUE),
            ("text", [1.0; 4]),
            ("rect", BLACK),
            ("outline", [0.0, 1.0, 0.0, 0.25]),
        ]
    );
    assert_eq!(
        list.opacity_groups(),
        &[
            crate::draw_list::OpacityGroup {
                commands: 0..4,
                opacity: 0.5,
            },
            crate::draw_list::OpacityGroup {
                commands: 2..4,
                opacity: 0.5,
            },
        ]
    );
    assert_eq!(list.pop_opacity(), Err(crate::draw_list::OpacityUnderflow));
}

/// **At full opacity, or with none set, a node pushes no group**, so a tree
/// that never says `opacity` draws exactly as it did.
#[test]
fn a_node_at_full_opacity_pushes_no_group() {
    let mut ui = Ui::new();
    ui.add_stylesheet("full.css", ".a { background: #ff0000; opacity: 1; }");
    frame(&mut ui, idle(), |ui| {
        ui.block(".a", &[], |ui| {
            ui.span("", "x", &[]);
        });
    });
    let mut list = DrawList::new();
    ui.emit(&mut list);
    assert_eq!(list.len(), 2);
    assert!(list.opacity_groups().is_empty());
}

// ---------------------------------------------------------------------------
// The layout hash
// ---------------------------------------------------------------------------

const HASHED_SHEET: &str = "
    #root > * { height: 10px; }
    .narrow { width: 10px; }
    .wide { width: 30px; }
    .h { width: 20px; }
    .h:hover { width: 40px; }
    .f { width: 20px; }
    .f:focus { width: 50px; }
    .p1 { --w: 15px; }
    .p2 { --w: 25px; }
    .kid { width: var(--w); height: 10px; }
";

/// What one frame of [`hashed_page`] is built from.
#[derive(Clone, Copy)]
struct HashedInputs {
    class: &'static str,
    inline_width: f32,
    parent: &'static str,
}

const HASHED_STEADY: HashedInputs = HashedInputs {
    class: "#c.narrow",
    inline_width: 10.0,
    parent: "#p.p1",
};

/// The keys of [`hashed_page`]'s nodes whose width each change moves.
struct HashedKeys {
    class: NodeKey,
    inline: NodeKey,
    hover: NodeKey,
    focus: NodeKey,
    kid: NodeKey,
    sheet: NodeKey,
}

/// A row of nodes each sized by one thing a frame can change: a class, an
/// inline width, a hover rule, a focus rule, a custom property inherited from
/// a parent's class, and an app sheet that is replaced.
fn hashed_page(ui: &mut Ui, inputs: HashedInputs) -> HashedKeys {
    let mut keys = None;
    ui.block(
        "#root",
        &[Declaration::FlexDirection(FlexDirection::Row)],
        |ui| {
            let class = ui.block(inputs.class, &[], |_| {}).key;
            let inline = ui
                .block(
                    "#i",
                    &[Declaration::Width(LengthAuto::Px(inputs.inline_width))],
                    |_| {},
                )
                .key;
            let hover = ui.block("#h.h", &[], |_| {}).key;
            let focus = ui.block_with("#f.f", &[], Behavior::BUTTON, |_| {}).key;
            let mut kid = None;
            ui.block(inputs.parent, &[], |ui| {
                kid = Some(ui.block(".kid", &[], |_| {}).key);
            });
            let sheet = ui.block("#s.s", &[], |_| {}).key;
            keys = Some(HashedKeys {
                class,
                inline,
                hover,
                focus,
                kid: kid.expect("built"),
                sheet,
            });
        },
    );
    keys.expect("built")
}

/// One frame of [`hashed_page`]: its keys, how many styles it hashed for
/// layout, and how many it resolved.
fn hashed_step(
    ui: &mut Ui,
    inputs: HashedInputs,
    pointer: PointerInput,
    nav: NavInput,
) -> (HashedKeys, u32, u32) {
    let before = super::resolve::layout_hashes();
    ui.begin_frame_with(pointer, nav);
    let keys = hashed_page(ui, inputs);
    let hashed = super::resolve::layout_hashes() - before;
    ui.layout(
        Vec2::ZERO,
        AvailableSpace::MAX_CONTENT,
        &FontAtlas::built_in(),
    );
    (keys, hashed, ui.style_stats().resolves)
}

fn width(ui: &Ui, key: NodeKey) -> f32 {
    let (min, max) = ui.rect(key).expect("laid out");
    max.x - min.x
}

/// **A node whose style was reused hashes nothing for layout, and every
/// change that re-resolves a style hashes exactly the nodes it re-resolved**
/// — a class, an inline declaration, a hover, a focus, an inherited custom
/// property and a replaced sheet each — with the layout following the change.
#[test]
fn only_a_re_resolved_style_is_hashed_for_layout_and_its_layout_follows() {
    let mut ui = Ui::new();
    let sheet = ui.add_stylesheet("hashed.css", HASHED_SHEET);
    let app = ui.add_stylesheet("app.css", ".s { width: 5px; }");
    let nav = NavInput::default();
    let steady = HASHED_STEADY;

    let (_, hashed, resolves) = hashed_step(&mut ui, steady, idle(), nav);
    assert_eq!(
        (hashed, resolves),
        (8, 8),
        "a first frame hashes every node"
    );
    let (keys, hashed, resolves) = hashed_step(&mut ui, steady, idle(), nav);
    assert_eq!(
        (hashed, resolves),
        (0, 0),
        "a steady frame hashed a reused style"
    );
    assert_eq!(width(&ui, keys.class), 10.0);
    assert_eq!(width(&ui, keys.kid), 15.0);

    // Each change: how many nodes it re-resolves, the node whose width moves,
    // and the width it moves to.
    let check = |ui: &mut Ui,
                 what: &str,
                 inputs: HashedInputs,
                 pointer: PointerInput,
                 nav: NavInput,
                 pick: fn(&HashedKeys) -> NodeKey,
                 want: f32| {
        let (keys, hashed, resolves) = hashed_step(ui, inputs, pointer, nav);
        assert!(resolves > 0, "{what} re-resolved nothing");
        assert_eq!(hashed, resolves, "{what}: hashed {hashed} of {resolves}");
        assert_eq!(width(ui, pick(&keys)), want, "{what}: layout did not move");
        let (_, hashed, _) = hashed_step(ui, inputs, pointer, nav);
        assert_eq!(hashed, 0, "the frame after {what} hashed a reused style");
    };

    let wide = HashedInputs {
        class: "#c.wide",
        ..steady
    };
    check(&mut ui, "a class", wide, idle(), nav, |k| k.class, 30.0);
    check(
        &mut ui,
        "a class back",
        steady,
        idle(),
        nav,
        |k| k.class,
        10.0,
    );

    let inline = HashedInputs {
        inline_width: 12.0,
        ..steady
    };
    check(
        &mut ui,
        "an inline width",
        inline,
        idle(),
        nav,
        |k| k.inline,
        12.0,
    );

    let parent = HashedInputs {
        parent: "#p.p2",
        ..inline
    };
    check(
        &mut ui,
        "a parent's class",
        parent,
        idle(),
        nav,
        |k| k.kid,
        25.0,
    );

    let on_hover = {
        let (min, max) = ui.rect(keys.hover).expect("laid out");
        hover((min + max) * 0.5)
    };
    check(&mut ui, "a hover", parent, on_hover, nav, |k| k.hover, 40.0);
    check(
        &mut ui,
        "an unhover",
        parent,
        idle(),
        nav,
        |k| k.hover,
        20.0,
    );

    let focus = NavInput::NAVIGATION;
    check(&mut ui, "a focus", parent, idle(), focus, |k| k.focus, 50.0);

    ui.replace_stylesheet(app, ".s { width: 7px; }")
        .expect("parses");
    check(
        &mut ui,
        "a replaced sheet",
        parent,
        idle(),
        focus,
        |k| k.sheet,
        7.0,
    );
    ui.replace_stylesheet(sheet, &HASHED_SHEET.replace("30px", "35px"))
        .expect("parses");
    let wide = HashedInputs {
        class: "#c.wide",
        ..parent
    };
    check(
        &mut ui,
        "an edited rule",
        wide,
        idle(),
        focus,
        |k| k.class,
        35.0,
    );
}