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
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
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
//! The element tree: blocks and spans rebuilt every frame, with identity that
//! survives the rebuild, laid out by Taffy.
//!
//! UI rungs 2 and 3. A frame is four calls:
//!
//! ```text
//! ui.begin_frame(pointer)      hover and press, from LAST frame's rectangles
//! ui.block(..., |ui| { ... })  the tree, built from nothing, each node styled
//! ui.layout(origin, space, atlas)   flexbox on Taffy; untouched nodes pruned
//! ui.emit(&mut list)           backgrounds, borders, clips, text, images
//! ```
//!
//! ```
//! use crcbl_ui::style::Declaration;
//! use crcbl_ui::tree::{AvailableSpace, LengthAuto, Ui};
//! use crcbl_ui::{DrawList, FontAtlas, PointerInput};
//!
//! let atlas = FontAtlas::built_in();
//! let mut ui = Ui::new();
//! ui.add_stylesheet(
//!     "hud.css",
//!     ".hud { padding: 8px; gap: 4px; background: #1a1a1a; color: gold }",
//! );
//! ui.begin_frame(PointerInput::default());
//! ui.block("#panel.hud", &[Declaration::MinWidth(LengthAuto::Px(120.0))], |ui| {
//!     ui.span("", "SCORE", &[]);
//!     ui.span("", "120", &[]);
//! });
//! ui.layout(glam::Vec2::ZERO, AvailableSpace::MAX_CONTENT, &atlas);
//! let mut list = DrawList::new();
//! ui.emit(&mut list);
//! assert_eq!(list.len(), 3, "a background and two strings");
//! ```
//!
//! # Styles
//!
//! A node's style comes from the stylesheets — see [`crate::style`] — matched
//! against the selector its builder was given, `type#id.class`, with the
//! builder's inline [`Declaration`]s over the top. [`NodeStyle::declarations`]
//! turns a whole style into an inline override that leaves the stylesheets no
//! say. A stylesheet changes with [`Ui::add_stylesheet`],
//! [`Ui::replace_stylesheet`] and, for one loaded from a file,
//! [`Ui::poll_stylesheets`]; how resolution is cached is `resolve.rs`'s.
//!
//! # Focus
//!
//! A frame that begins with [`Ui::begin_frame_with`] also takes a
//! [`NavInput`], and a node built with [`Ui::block_with`] declares a
//! [`Behavior`]: whether it is a button, a widget with an engaged state or a
//! focus scope. Focus sets `:focus`, engagement `:engaged` and a disabled
//! behavior `:disabled`; `focus/mod.rs` has the rules, and
//! [`Ui::set_nav_debug`] draws why a move went where it did.
//!
//! # Widgets
//!
//! [`Ui::button`], [`Ui::checkbox`], [`Ui::slider`], [`Ui::drag_value`],
//! [`Ui::collapsing`], [`Ui::tree_node`], [`Ui::split`], [`Ui::list`],
//! [`Ui::text_input`], [`Ui::outliner`], [`Ui::tabs`], [`Ui::select`] and
//! [`Ui::dock`] are builders over blocks and spans, each styled by
//! `default.css`; `widgets/mod.rs` has what each builds and the rules it keeps.
//!
//! # Paragraphs
//!
//! [`Ui::paragraph`] is a block whose content is runs of text, each a node
//! styled by its own selector — `<b>`, a highlighted match, a link — broken
//! into lines together and laid out as one leaf; each run is hit on the line
//! fragments it lies on. `paragraph.rs` has the rules and `inline.rs` the line
//! breaker.
//!
//! # Pop-ups
//!
//! [`Ui::open_popup`] and [`Ui::popup`] hang a block from any node: a root of
//! its own, drawn over the whole tree in a layer of its own, clipped only by
//! the viewport, hit-tested first and holding focus until it closes — by
//! [`Ui::close_popup`], by back, or by a press outside it, which it spends.
//! [`Ui::open_popup_at`] places one beside its anchor or at a point instead of
//! below it. `popup.rs` has the rules.
//!
//! [`Ui::context_menu`] is a widget's context menu on that layer: a list of
//! [`ContextItem`]s opened at the pointer by a secondary press, or below the
//! focused widget by `ui_menu`, with submenus beside their items.
//! `widgets/context_menu.rs` has the rules.
//!
//! A pop-up taller than the viewport is capped and scrolls, and inside the
//! topmost one Home, End, Page Up and Page Down ([`Jump`]) and a list's
//! typeahead move focus; `popup_nav.rs` has those rules.
//!
//! [`Ui::tooltip`] hangs a line of text from a widget the same way once the
//! pointer has rested on it, or navigation has held focus on it, for
//! [`TOOLTIP_DELAY`]: a pop-up of its own kind, drawn over every other but
//! inert — the pointer passes through it, and a press only hides it.
//! `tooltip.rs` has the rules.
//!
//! # Accessibility
//!
//! With the `accesskit` feature, `Ui::accessibility_update` turns the laid-out
//! frame into an AccessKit tree update — each node keyed by its [`NodeKey`],
//! its role from what its widget builder recorded it as — and
//! `Ui::accessibility_action` acts on the focus and click a screen reader asks
//! for. `accessibility.rs` has the rules.
//!
//! # Identity
//!
//! Every node has a [`NodeKey`]: `hash(parent key, id)`, where the id is
//!
//! * the `#id` in the selector passed to [`Ui::block`] or [`Ui::span`]
//!   (`"#health.hud"`), or
//! * the key passed to [`Ui::block_keyed`], for the rows of a loop, or
//! * otherwise the **call site** and how many nodes that call site has already
//!   built under the same parent this frame.
//!
//! A loop's rows need [`Ui::block_keyed`]: by call site alone the third row is
//! "the third node from this line", so reordering the list moves each row's
//! hover, press and scroll onto whatever row lands in its place. Clay's and
//! React's documentation both warn of exactly that.
//!
//! **A duplicate key is a warning, not a panic**: the second node gets a key
//! derived from the first so layout stays correct, and the duplicate is
//! reported once per frame per key through `crcbl_core::warn!` and
//! [`Ui::duplicate_keys`].
//!
//! # What survives a rebuild, and what clears it
//!
//! The store keeps, per key, the pointer's hover and press, focus and
//! engagement, a scope's remembered node, a scroll offset, a widget's state,
//! last frame's rectangle, its resolved style, Taffy's layout cache, and three
//! hashes: the node's resolved layout style ([`NodeStyle::layout_hash`], which
//! no paint field reaches), its
//! children's keys in order, and its measured content. **When any of the three
//! moves, that node's cache and every ancestor's is cleared; nothing else is.**
//! A sibling keeps its cache, and so does everything under the changed node,
//! whose own inputs have not changed. A node no frame touched is pruned at
//! [`Ui::layout`].
//!
//! # Hit testing is one frame behind
//!
//! [`Ui::begin_frame`] tests the pointer against the rectangles the previous
//! [`Ui::layout`] produced, before this frame's tree exists — the classic
//! immediate-mode trade the plan takes. The topmost node under the pointer —
//! by layer, so an open pop-up's before the tree's, then by paint order — and
//! every node containing it are hovered; a press latches on the topmost node
//! — or on the innermost node around it with a [`Role`], so a click on a
//! button's label clicks the button — through [`UiState`]'s capture, so
//! pressing one node and releasing over another clicks neither. A disabled
//! node takes the press and is never clicked.
//!
//! # Emission
//!
//! A block paints its border box, and so does a text span, behind its text; a
//! paragraph's run paints none. With square corners it is a filled rect, then the
//! border — one [`DrawList::rect_outline`] when every side is one width, a rect
//! per side otherwise. With any corner radius it is one
//! [`DrawList::rounded_rect`], whose border is uniform, **drawn at the top
//! side's width**. A `background-image` is stretched over the padding box
//! between the background and the border, and a `border-image` is a
//! [`DrawList::nine_slice_bands`] over the border box in the border's place;
//! both are pictures [`Ui::set_image`] bound by name, and a rounded corner
//! clips neither. A block with `overflow: hidden` clips its children to its
//! padding box, and so does `overflow: scroll`. A text span draws from its content box's top-left: in the
//! bitmap font as one line per newline, or — when its `font-family` names a
//! parsed font, the committed one or one [`Ui::register_font`] registered — as
//! a [`crate::font::layout::TextLayout`] broken at the width layout measured it
//! under, aligned by its `text-align` and pushed as one
//! [`DrawList::glyphs`] run of that font. A span that is
//! `text-overflow: ellipsis`, `white-space: nowrap` and `overflow: hidden` (or
//! `scroll`) draws each line too long for its content box cut to fit and ending
//! in `…` — `...` in a font without that glyph — and [`Ui::text`] reads back
//! what it drew; `ellipsis.rs` has the rule. A span or a paragraph's run that
//! is `text-decoration: underline` draws a rectangle under each line it lies
//! on, before its text, where its font's `post` table says or — for a font
//! that does not, and the bitmap font — `emit.rs`'s fallback. An image span
//! stretches its picture over its content box. Outlines are drawn after the
//! whole tree, in build order, each under the clip its node was drawn under,
//! so a later sibling never covers a focus ring: a ring `outline-offset`
//! outside the border box, one [`DrawList::rect_outline`] — or a
//! [`DrawList::rounded_rect`], its radii grown by the offset, when the node has
//! any. Each open pop-up is drawn after all of that, outlines and all, as a
//! layer of its own. A node whose `opacity` is below one is drawn with its
//! subtree inside one [`DrawList::push_opacity`] group; its outline, drawn
//! outside the groups, has its colour's alpha multiplied by its own opacity
//! and every ancestor's instead.
//!
//! # Text measures through Taffy
//!
//! A text span is a leaf whose measure callback lays its text out under the
//! width Taffy offers: unbroken for max-content, broken at every space for
//! min-content, and broken to fit for a definite width — so a wrapped label
//! grows its block's height. A `white-space: nowrap` span is measured unbroken
//! under every width. Measurements are cached by the text, the style
//! fields that size it and the whole-pixel width; see `layout.rs`.
//!
//! # Layout output is rounded
//!
//! Positions and sizes are snapped to whole pixels by Taffy's `round_layout`,
//! on the cumulative position so that no gap opens between neighbours. That is
//! what Chrome's fixtures were generated with, and what keeps a bitmap glyph on
//! the pixel grid. With the features this crate enables, Taffy's flexbox and
//! rounding are comparisons, the four operations and `floor` — no `sqrt`,
//! `powf` or `mul_add` — so the result does not depend on a platform's libm.

#[cfg(feature = "accesskit")]
mod accessibility;
mod ellipsis;
#[cfg(all(test, feature = "parsed-font"))]
mod ellipsis_tests;
mod emit;
#[cfg(all(test, feature = "parsed-font"))]
mod fallback_tests;
pub mod focus;
#[cfg(all(test, feature = "parsed-font"))]
mod font_tests;
pub(crate) mod inline;
mod layout;
#[cfg(test)]
mod measure_tests;
mod paragraph;
#[cfg(test)]
mod paragraph_tests;
mod popup;
mod popup_nav;
#[cfg(test)]
mod popup_tests;
mod resolve;
mod store;
mod style;
#[cfg(test)]
mod style_tests;
#[cfg(test)]
mod tests;
mod tooltip;
#[cfg(test)]
mod tooltip_tests;
pub mod widgets;

use std::collections::{HashMap, HashSet};
use std::hash::{DefaultHasher, Hash, Hasher};
use std::panic::Location;
use std::sync::Arc;

use crcbl_core::input::CursorIcon;
use glam::Vec2;
use taffy::{NodeId, compute_root_layout, round_layout};

use crate::draw_list::ClipRect;
#[cfg(doc)]
use crate::draw_list::DrawList;
use crate::font::face::select_face;
use crate::font::layout::TextLayout;
use crate::font::{Font, ReservedFamilyName, is_reserved_family};
use crate::image::AtlasImage;
use crate::style::{Declaration, InheritedId, NodeSelector, PseudoClasses, Styles};
use crate::text::FontAtlas;
use crate::widget::{ButtonState, PointerInput, UiState};

use focus::FocusState;
use layout::{LayoutTree, MeasureCache};
use store::{Interaction, NodeStore};
use widgets::WidgetKind;

pub use crate::font::face::{FontStyle, FontWeight};
pub use crate::font::layout::TextAlign;
pub use crate::font::{FamilyName, FontFamily};
pub use focus::{
    Behavior, Direction, Engagement, FOCUS_HISTORY, InputMode, Jump, NavInput, NavScore, NavStep,
    Role, Scope,
};
pub use paragraph::ParagraphBuilder;
pub use popup::{POPUP_MARGIN, Placement};
pub use popup_nav::TYPEAHEAD_TIMEOUT;
pub use store::NodeKey;
pub use style::{
    Align, BorderImage, BorderImageWidth, Display, Edges, FlexDirection, FlexWrap, ImageName,
    Justify, Length, LengthAuto, LineHeight, NavId, NavTarget, NavWrap, NodeStyle, Overflow,
    Position, TextDecoration, TextOverflow, WhiteSpace,
};
pub use tooltip::{TOOLTIP_AUTOPOP_FACTOR, TOOLTIP_DELAY, TOOLTIP_RESHOW_DIVISOR};
pub use widgets::{
    AXES, CONTEXT_ARROW, ClipboardAnswer, ClipboardReply, ClipboardRequest, ContextItem,
    ContextMenuResponse, DOUBLE_CLICK_TIME, DockLayout, DockSide, DragNumber, FieldEdit, FieldRow,
    INSPECTOR_STEP, Inspection, InspectorOptions, LIST_OVERSCAN, MASK, MIN_SCROLL_HANDLE,
    OUTLINER_INDENT, OUTLINER_ROW_HEIGHT, OutlinerBuilder, OutlinerId, OutlinerOptions,
    OutlinerRow, OutlinerState, Overrides, Preedit, RowBuilder, SELECT_CARET, SPLIT_NAV_STEP,
    SelectMode, SplitAxis, TextInput, TextInputOptions, VARIANT_LABEL, VariantEdit, WHOLE_STEP,
};

/// How far the pointer must move from where a press began, in pixels, before
/// the press is a drag rather than a click: the default of Windows'
/// `SM_CXDRAG`. A drag that ends over an engage widget focuses it without
/// engaging it — dragging a slider is engage, adjust and commit in one
/// gesture — and a drag-value moves only once its press is a drag.
pub const DRAG_THRESHOLD: f32 = 4.0;

/// The space a root is laid out in, on one axis.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Available {
    /// This many pixels.
    Definite(f32),
    /// As little as the content can take.
    MinContent,
    /// As much as the content wants.
    MaxContent,
}

/// The space every root is laid out in.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct AvailableSpace {
    /// Horizontally.
    pub width: Available,
    /// Vertically.
    pub height: Available,
}

impl AvailableSpace {
    /// Unbounded on both axes: a root sized by its content and its own style.
    pub const MAX_CONTENT: Self = Self {
        width: Available::MaxContent,
        height: Available::MaxContent,
    };

    /// A surface of `size` pixels.
    #[must_use]
    pub const fn definite(size: Vec2) -> Self {
        Self {
            width: Available::Definite(size.x),
            height: Available::Definite(size.y),
        }
    }
}

impl Available {
    const fn to_taffy(self) -> taffy::AvailableSpace {
        match self {
            Self::Definite(px) => taffy::AvailableSpace::Definite(px),
            Self::MinContent => taffy::AvailableSpace::MinContent,
            Self::MaxContent => taffy::AvailableSpace::MaxContent,
        }
    }
}

/// What a span holds.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Span<'a> {
    /// A string, measured in the font its style names.
    Text(&'a str),
    /// A registered picture, measured by its size in texels.
    Image(AtlasImage),
}

impl<'a> From<&'a str> for Span<'a> {
    fn from(text: &'a str) -> Self {
        Self::Text(text)
    }
}

impl From<AtlasImage> for Span<'_> {
    fn from(image: AtlasImage) -> Self {
        Self::Image(image)
    }
}

/// A node's key and its interaction state — the pointer's relation to it, its
/// focus and its engagement — as resolved when the frame began.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Response {
    /// The node's identity; [`Ui::rect`] takes it.
    pub key: NodeKey,
    /// The pointer is over the node or over something inside it, and no press
    /// elsewhere is captured.
    pub hovered: bool,
    /// The node captured the press that is held.
    pub pressed: bool,
    /// The node captured a press that was released over it this frame, or —
    /// focused, and not a [`Role::Engage`] — was accepted: the one event a
    /// widget fires on, whichever device spoke.
    pub clicked: bool,
    /// The node holds the tree's focus, in either [`InputMode`].
    pub focused: bool,
    /// Where the node's engagement is this frame.
    pub engagement: Engagement,
    /// The navigation step the engaged node took instead of focus this frame.
    pub captured: Option<NavStep>,
    /// A widget builder changed the value it edits, or the state it keeps,
    /// this frame. Always false from [`Ui::block`] and its kin.
    pub changed: bool,
}

/// What a frame node is.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Content {
    /// A container.
    Block,
    /// A string: `Ui::text[start..end]`.
    Text { start: usize, end: usize },
    /// A picture.
    Image(AtlasImage),
    /// A paragraph: a block whose children are its runs, laid out as one
    /// leaf; see `paragraph.rs`.
    Paragraph,
    /// One run of a paragraph: `Ui::text[start..end]`.
    Run { start: usize, end: usize },
}

impl Content {
    /// Whether a node of this content is styled as a span — a leaf that
    /// passes nothing down — rather than as a block.
    const fn is_span(self) -> bool {
        !matches!(self, Self::Block | Self::Paragraph)
    }
}

/// What a text span shows, decided at layout.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Shown {
    /// Not laid out yet this frame.
    Pending,
    /// Its whole text.
    Whole,
    /// Its text cut to fit: `Ui::cut[start..end]`.
    Cut { start: usize, end: usize },
}

/// One node as this frame built it.
#[derive(Clone, Debug)]
struct FrameNode {
    key: NodeKey,
    /// Its slot in the store.
    slot: usize,
    parent: Option<usize>,
    /// Its builder's selector: `Ui::selectors[start..end]`, empty when the
    /// builder's was malformed.
    selector: (usize, usize),
    /// Its pseudo-class state this frame.
    pseudo: PseudoClasses,
    /// What it passes to its children.
    inherited: InheritedId,
    /// Its resolved style.
    style: NodeStyle,
    /// [`NodeStyle::layout_hash`] of `style`, as resolving it produced.
    style_hash: u64,
    content: Content,
    /// The parsed font a text span measures and draws in — a registered one,
    /// else its built-in family's — or `None` for the bitmap font. Resolved
    /// when the span is built.
    font: Option<Font>,
    /// What a text span shows; [`Shown::Whole`] for every other node once
    /// laid out.
    shown: Shown,
    /// What a `white-space: nowrap` span in a parsed font shows, laid out
    /// unbroken as layout measured it or cutting it did, so drawing it shapes
    /// nothing again: the layout [`TextLayout::nowrap`] gives its shown text
    /// in its font, at its size and line height — whether a one-line
    /// `text-overflow: ellipsis` span was cut or fits whole. Shared with the
    /// measure cache when the span shows its whole text. For a wrapped span
    /// in a parsed font, its text as [`TextLayout::new`] breaks it at its
    /// content-box width, shared with the measure cache. `None` until laid
    /// out, for a `nowrap` span layout did not measure, an ellipsis span of
    /// several lines, one too narrow for even the ellipsis, and every other
    /// node.
    shown_layout: Option<Arc<TextLayout>>,
    content_hash: u64,
    /// Folded over each child's key as the child is built.
    child_hash: u64,
    /// Whether the store had no node of this key before this frame.
    fresh: bool,
    first_child: Option<usize>,
    last_child: Option<usize>,
    next_sibling: Option<usize>,
    /// Where its children start in `Ui::children`, once flattened at layout.
    child_start: usize,
    child_count: usize,
    /// The rounded layout, relative to the parent.
    layout: taffy::Layout,
}

/// The seed a root's key is derived from, in place of a parent's key.
const ROOT_KEY: NodeKey = NodeKey(0x6372_6362_6c2d_7569);

/// Which of the three identity rules made a key, folded into it so that an
/// explicit id can never collide with a loop key of the same hash.
#[derive(Hash)]
enum KeySource<'a> {
    CallSite(&'a str, u32, u32, u32),
    Id(&'a str),
    Keyed(u64),
    Duplicate(u64, u32),
    /// A pop-up's root, by its anchor's key.
    Popup(u64),
    /// A tooltip's root, by its anchor's key.
    Tooltip(u64),
    /// The text run a screen reader reads a text field's value from, under
    /// the field's key; never a node the tree builds.
    #[cfg(feature = "accesskit")]
    TextRun,
}

fn hash_of(value: impl Hash) -> u64 {
    let mut hasher = DefaultHasher::new();
    value.hash(&mut hasher);
    hasher.finish()
}

/// The element tree and the store it keeps between frames. See the module
/// docs for the frame's shape.
#[derive(Debug, Default)]
pub struct Ui {
    store: NodeStore,
    nodes: Vec<FrameNode>,
    children: Vec<NodeId>,
    text: String,
    /// Every text span's text as `text-overflow: ellipsis` cut it at the last
    /// layout, run together.
    cut: String,
    /// The blocks whose closures are running, innermost last.
    open: Vec<usize>,
    /// How many nodes each call site has built under each parent this frame.
    call_sites: HashMap<(Option<usize>, u64), u32>,
    duplicates: Vec<NodeKey>,
    /// The content hash of every text span built this frame.
    live_text: HashSet<u64>,
    /// Every node's selector this frame, run together.
    selectors: String,
    /// Its stylesheets and cascade state.
    styles: Styles,
    /// Builder selectors already reported as malformed, so each is reported
    /// once.
    malformed: HashSet<String>,
    measure: MeasureCache,
    capture: UiState,
    focus: FocusState,
    frame: u64,
    /// This frame's pointer, for a widget a press drags.
    pointer: PointerInput,
    /// Where the press held now, or the last one, began.
    press_origin: Vec2,
    /// Whether that press has moved past [`DRAG_THRESHOLD`].
    dragged: bool,
    /// How many [`Ui::enabled`] scopes that disable are open.
    disabled_depth: u32,
    /// The rows of the tree nodes whose children are being built, innermost
    /// last.
    tree_rows: Vec<NodeKey>,
    /// This frame's text input, from [`Ui::set_text_input`].
    text_frame: TextInput,
    /// Every frame's [`TextInput::dt`] together.
    text_clock: std::time::Duration,
    /// Each text input's editing state, pruned with the store.
    edits: HashMap<NodeKey, widgets::EditState>,
    /// This frame's text inputs, for the pass after layout.
    fits: Vec<widgets::TextFit>,
    /// The clipboard requests this frame's text inputs made.
    clipboard_requests: Vec<ClipboardRequest>,
    /// The pictures a stylesheet's `url()` names, from [`Ui::set_image`].
    images: HashMap<ImageName, AtlasImage>,
    /// The faces of each family a `font-family` list names, from
    /// [`Ui::register_font`].
    fonts: HashMap<FamilyName, Vec<Font>>,
    /// Family names a text span was built in with no font registered under
    /// them, already warned about, so each is reported once.
    unregistered: HashSet<FamilyName>,
    /// The faces every parsed-font span falls back to, in order, from
    /// [`Ui::set_fallback_fonts`].
    fallback: Vec<Font>,
    /// A hash of their identities, folded into each span's content hash so a
    /// new list measures every span again.
    fallback_hash: u64,
    /// The node this frame's pointer clicked, resolved when the frame began.
    clicked: Option<NodeKey>,
    /// The node whose `cursor` [`Ui::cursor`] reports: the one a press holds,
    /// or else the topmost under the pointer. Resolved when the frame began.
    cursor_node: Option<NodeKey>,
    /// The tree row [`Ui::tree_item_step`] opened or closed when this frame
    /// began, if it opened or closed one.
    tree_toggled: Option<NodeKey>,
    /// The focus endpoints of this frame's up or down navigation step.
    vertical_focus_move: Option<(NodeKey, NodeKey)>,
    /// The open pop-ups, the topmost last; see `popup.rs`.
    popups: Vec<popup::OpenPopup>,
    /// Each pop-up root this frame built, as its index in `nodes` and its
    /// anchor.
    popup_roots: Vec<(usize, NodeKey)>,
    /// The space the last [`Ui::layout`] was given, from its origin; `None`
    /// before the first.
    viewport: Option<ClipRect>,
    /// Each virtualized block this frame built, and the rows it built.
    built_rows: Vec<widgets::BuiltRows>,
    /// Whether the last layout showed a row its build left out; see
    /// [`Ui::needs_rebuild`].
    rows_missed: bool,
    /// The tooltip's subject and clock; see `tooltip.rs`.
    tooltip: tooltip::TooltipState,
    /// The node whose context menu this frame's secondary press or `ui_menu`
    /// asked for, and where it goes, until its [`Ui::context_menu`] call
    /// opens it; see `widgets/context_menu.rs`.
    context_request: Option<(NodeKey, Placement)>,
    /// What has been typed into the topmost list; see `popup_nav.rs`.
    typeahead: popup_nav::Typeahead,
    /// The node a screen reader asked to click, for the next frame to report
    /// clicked, as [`Ui::set_focus`] waits for it; see `accessibility.rs`.
    #[cfg(feature = "accesskit")]
    requested_click: Option<NodeKey>,
    /// This frame's names for nodes a screen reader should hear as one thing;
    /// see [`Ui::set_accessible_label`].
    #[cfg(feature = "accesskit")]
    accessible_labels: HashMap<NodeKey, String>,
    /// This frame's blocks a caller drew as text fields; see
    /// [`Ui::set_accessible_text_input`].
    #[cfg(feature = "accesskit")]
    accessible_text_inputs: HashMap<NodeKey, accessibility::TextField>,
    /// Every paragraph as the last layout broke it into lines; see
    /// `paragraph.rs`.
    paragraphs: Vec<paragraph::LaidOut>,
}

impl Ui {
    /// An empty tree with nothing stored.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Starts a frame with no navigation input from a pointer: drops last
    /// frame's nodes, and resolves `pointer` against last frame's rectangles.
    /// [`Ui::begin_frame_with`] with [`NavInput::default`].
    pub fn begin_frame(&mut self, pointer: PointerInput) {
        self.begin_frame_with(pointer, NavInput::default());
    }

    /// Starts a frame: drops last frame's nodes, resolves `pointer` against
    /// last frame's rectangles, and then focus and engagement from `nav`
    /// against last frame's tree. See `focus/mod.rs`.
    pub fn begin_frame_with(&mut self, pointer: PointerInput, nav: NavInput) {
        self.frame += 1;
        self.nodes.clear();
        #[cfg(feature = "accesskit")]
        self.accessible_labels.clear();
        #[cfg(feature = "accesskit")]
        self.accessible_text_inputs.clear();
        self.children.clear();
        self.text.clear();
        self.cut.clear();
        self.open.clear();
        self.call_sites.clear();
        self.duplicates.clear();
        self.live_text.clear();
        self.selectors.clear();
        self.styles.begin_frame();
        self.disabled_depth = 0;
        self.tree_rows.clear();
        self.text_frame = TextInput::default();
        self.fits.clear();
        self.clipboard_requests.clear();
        self.pointer = pointer;
        self.tree_toggled = None;
        self.vertical_focus_move = None;
        self.popup_roots.clear();
        self.built_rows.clear();
        self.paragraphs.clear();
        self.typeahead.built = None;
        let clicked = self.resolve_pointer(pointer);
        #[cfg(feature = "accesskit")]
        let clicked = self.resolve_requested_click().or(clicked);
        self.clicked = clicked;
        self.resolve_navigation(nav, clicked, self.dragged);
        self.resolve_tooltip(pointer, nav);
        self.resolve_context_menu(pointer, nav);
    }

    /// Hover, press capture and click for every stored node, from last frame's
    /// rectangles, recording where the press began and whether it is a drag.
    /// Returns the node clicked, unless it is disabled.
    fn resolve_pointer(&mut self, pointer: PointerInput) -> Option<NodeKey> {
        let held_before = self.capture.active().is_some();
        let over = self.store.hit_chain(pointer.pos);
        let over = self.press_outside_popups(pointer, over);
        // A press goes to the innermost node with a role around the topmost
        // one, so a button's label does not take its button's click.
        let target = over
            .iter()
            .copied()
            .find(|&key| {
                self.store
                    .by_key(key)
                    .is_some_and(|node| node.behavior.role != Role::None)
            })
            .or_else(|| over.first().copied());
        let mut pressed = None;
        let mut clicked = None;

        // The captured node first, so a release frees the capture before
        // anything else can be offered the press — `UiState::interact`'s rule.
        if let Some(active) = self.capture.active() {
            let (state, click) = self.capture.interact(
                active,
                over.contains(&NodeKey(active)),
                pointer.down,
                pointer.released,
            );
            pressed = (state == ButtonState::Pressed).then_some(NodeKey(active));
            clicked = click.then_some(NodeKey(active));
        }
        if self.capture.active().is_none()
            && let Some(target) = target
        {
            let (state, click) =
                self.capture
                    .interact(target.0, true, pointer.down, pointer.released);
            if state == ButtonState::Pressed {
                pressed = Some(target);
            }
            if click {
                clicked = Some(target);
            }
        }

        // A press that began this frame starts a new gesture; one held since an
        // earlier frame becomes a drag once it has moved far enough, and stays
        // one until the next press.
        if !held_before && (pressed.is_some() || clicked.is_some()) {
            self.press_origin = pointer.pos;
            self.dragged = false;
        } else if held_before
            && (pointer.pos - self.press_origin).length_squared() > DRAG_THRESHOLD * DRAG_THRESHOLD
        {
            self.dragged = true;
        }

        let clicked = clicked.filter(|&key| {
            self.store
                .by_key(key)
                .is_some_and(|node| !node.behavior.disabled)
        });
        let captured = self.store.ancestry(self.capture.active().map(NodeKey));
        self.cursor_node = self
            .capture
            .active()
            .map(NodeKey)
            .or_else(|| over.first().copied());
        for node in self.store.iter_mut() {
            node.interaction = Interaction {
                hovered: over.contains(&node.key)
                    && (captured.is_empty() || captured.contains(&node.key)),
                pressed: pressed == Some(node.key),
                clicked: clicked == Some(node.key),
                ..Interaction::default()
            };
        }
        clicked
    }

    /// A block: a flex container whose children `build` adds.
    ///
    /// `selector` is the node's own `type#id.class` — every part optional,
    /// `""` for a plain block — which stylesheet rules match against; its
    /// `#id` is also the node's explicit identity, and with none the block is
    /// keyed by this call site. See the module docs. `inline` overrides every
    /// rule; `&[]` for none.
    #[track_caller]
    pub fn block(
        &mut self,
        selector: &str,
        inline: &[Declaration],
        build: impl FnOnce(&mut Self),
    ) -> Response {
        self.block_with(selector, inline, Behavior::NONE, build)
    }

    /// A block that takes part in focus as `behavior` says: [`Ui::block`]
    /// otherwise.
    #[track_caller]
    pub fn block_with(
        &mut self,
        selector: &str,
        inline: &[Declaration],
        behavior: Behavior,
        build: impl FnOnce(&mut Self),
    ) -> Response {
        let parsed = self.node_selector(selector);
        let key = self.selector_key(parsed, Location::caller());
        self.open_block(key, parsed, inline, behavior, PseudoClasses::NONE, build)
    }

    /// A block keyed by `key`, for one row of a loop: its identity follows the
    /// item rather than its position. `selector` and `inline` are
    /// [`Ui::block`]'s, and an `#id` in the selector does not key it.
    pub fn block_keyed(
        &mut self,
        key: impl Hash,
        selector: &str,
        inline: &[Declaration],
        build: impl FnOnce(&mut Self),
    ) -> Response {
        self.block_keyed_with(key, selector, inline, Behavior::NONE, build)
    }

    /// [`Ui::block_keyed`] with a [`Behavior`], as [`Ui::block_with`].
    pub fn block_keyed_with(
        &mut self,
        key: impl Hash,
        selector: &str,
        inline: &[Declaration],
        behavior: Behavior,
        build: impl FnOnce(&mut Self),
    ) -> Response {
        let parsed = self.node_selector(selector);
        let key = self.key(KeySource::Keyed(hash_of(key)));
        self.open_block(key, parsed, inline, behavior, PseudoClasses::NONE, build)
    }

    /// [`Ui::block_keyed`] drawn in pseudo-class `state` whatever the pointer
    /// and focus say: for a view of a model that keeps its own interaction
    /// state, as [`crate::menu::Menu`] keeps its selection and press.
    pub(crate) fn block_keyed_in_state(
        &mut self,
        key: impl Hash,
        selector: &str,
        inline: &[Declaration],
        state: PseudoClasses,
        build: impl FnOnce(&mut Self),
    ) -> Response {
        let parsed = self.node_selector(selector);
        let key = self.key(KeySource::Keyed(hash_of(key)));
        self.open_block(key, parsed, inline, Behavior::NONE, state, build)
    }

    /// A span: text or a picture, keyed by its selector's `#id` or else by
    /// this call site. `selector` and `inline` are [`Ui::block`]'s; a span's
    /// type is `span` unless the selector names one.
    ///
    /// **Rich text that wraps is a [`Ui::paragraph`]**: its runs, each styled
    /// as its own node, break into lines together. A single line whose runs
    /// differ in colour, size or family can also be a `flex-direction: row`
    /// block with one span per run, each starting where the last ends — but
    /// spans do not wrap into each other.
    #[track_caller]
    pub fn span<'a>(
        &mut self,
        selector: &str,
        content: impl Into<Span<'a>>,
        inline: &[Declaration],
    ) -> Response {
        let parsed = self.node_selector(selector);
        let key = self.selector_key(parsed, Location::caller());
        let content = match content.into() {
            Span::Text(text) => {
                let start = self.text.len();
                self.text.push_str(text);
                Content::Text {
                    start,
                    end: self.text.len(),
                }
            }
            Span::Image(image) => Content::Image(image),
        };
        let index = self.push(
            key,
            parsed,
            inline,
            Behavior::NONE,
            PseudoClasses::NONE,
            content,
        );
        self.close(index);
        self.response(index)
    }

    /// `selector` split into its parts, or — reported once — no parts at all.
    fn node_selector<'s>(&mut self, selector: &'s str) -> NodeSelector<'s> {
        NodeSelector::parse(selector).unwrap_or_else(|()| {
            if self.malformed.insert(selector.to_owned()) {
                crcbl_core::warn!(
                    "ui tree: `{selector}` is not a node selector (`type#id.class`, names of \
                     letters, digits, `-` and `_`); the node is built with none"
                );
            }
            NodeSelector::EMPTY
        })
    }

    fn open_block(
        &mut self,
        key: NodeKey,
        selector: NodeSelector<'_>,
        inline: &[Declaration],
        behavior: Behavior,
        state: PseudoClasses,
        build: impl FnOnce(&mut Self),
    ) -> Response {
        let index = self.push(key, selector, inline, behavior, state, Content::Block);
        let response = self.response(index);
        self.open.push(index);
        build(self);
        self.open.pop();
        self.close(index);
        response
    }

    /// The key a node built from `selector` at `location` gets: its `#id`, or
    /// else the call site.
    fn selector_key(&mut self, selector: NodeSelector<'_>, location: &Location<'_>) -> NodeKey {
        match selector.id {
            Some(id) => self.key(KeySource::Id(id)),
            None => self.call_site_key(location),
        }
    }

    /// The current parent's key folded with `source`.
    fn key(&self, source: KeySource<'_>) -> NodeKey {
        let parent = self
            .open
            .last()
            .map_or(ROOT_KEY, |&parent| self.nodes[parent].key);
        Self::key_under(parent, source)
    }

    /// The key a node built under `parent` from `source` gets, before the
    /// duplicate rule.
    fn key_under(parent: NodeKey, source: KeySource<'_>) -> NodeKey {
        NodeKey(hash_of((parent, source)))
    }

    /// The key for the next node built at `location` under the current parent.
    fn call_site_key(&mut self, location: &Location<'_>) -> NodeKey {
        let site = hash_of((location.file(), location.line(), location.column()));
        let occurrence = self
            .call_sites
            .entry((self.open.last().copied(), site))
            .or_insert(0);
        let nth = *occurrence;
        *occurrence += 1;
        self.key(KeySource::CallSite(
            location.file(),
            location.line(),
            location.column(),
            nth,
        ))
    }

    /// Appends a node under the current parent, touches its slot and resolves
    /// its style.
    fn push(
        &mut self,
        key: NodeKey,
        selector: NodeSelector<'_>,
        inline: &[Declaration],
        behavior: Behavior,
        state: PseudoClasses,
        content: Content,
    ) -> usize {
        let key = self.unique(key);
        let behavior = Behavior {
            disabled: behavior.disabled || self.disabled_depth > 0,
            ..behavior
        };
        let (slot, fresh) = match self.store.find(key) {
            Some(slot) => (slot, false),
            None => (self.store.insert(key, self.frame), true),
        };
        let parent = self.open.last().copied();
        let stored = self.store.get_mut(slot);
        stored.last_touched_frame = self.frame;
        stored.parent = parent.map(|parent| self.nodes[parent].key);
        stored.behavior = behavior;
        stored.state = state;
        // Until this frame's builder says what it built.
        stored.kind = WidgetKind::None;
        // Until this frame's `Ui::tooltip` and `Ui::context_menu` ask again.
        stored.tooltip = false;
        stored.context_menu = false;
        stored.id = selector.id.map(NavId::new);
        // A run's, until this frame's layout places it again.
        stored.fragments.clear();

        let span = content.is_span();
        let start = self.selectors.len();
        self.selectors.push_str(selector.text());
        let text = (start, self.selectors.len());
        let resolved = self.resolve_style(slot, fresh, parent, selector, span, inline);

        let font = match content {
            Content::Text { .. } | Content::Run { .. } => {
                self.font_for(&resolved.style, selector.text())
            }
            Content::Block | Content::Image(_) | Content::Paragraph => None,
        };
        let content_hash = match content {
            // A paragraph's is its runs', folded once they are built.
            Content::Block | Content::Paragraph => 0,
            Content::Text { start, end } | Content::Run { start, end } => {
                let style = &resolved.style;
                // The resolved font's identity too: registering a font under
                // the span's family name, or replacing it, re-measures it.
                let hash = hash_of((
                    &self.text[start..end],
                    style.font_size.to_bits(),
                    style.font_family,
                    font.as_ref().map(|font| (font.id(), self.fallback_hash)),
                    style.line_height.bits(),
                    style.white_space,
                ));
                // A run is measured as part of its paragraph, under the
                // paragraph's hash.
                if matches!(content, Content::Text { .. }) {
                    self.live_text.insert(hash);
                }
                hash
            }
            Content::Image(image) => hash_of((image.width, image.height)),
        };

        let index = self.nodes.len();
        self.nodes.push(FrameNode {
            key,
            slot,
            parent,
            selector: text,
            pseudo: resolved.pseudo,
            inherited: resolved.inherited,
            style: resolved.style,
            style_hash: resolved.layout_hash,
            content,
            font,
            shown: Shown::Pending,
            shown_layout: None,
            content_hash,
            child_hash: 0,
            fresh,
            first_child: None,
            last_child: None,
            next_sibling: None,
            child_start: 0,
            child_count: 0,
            layout: taffy::Layout::new(),
        });
        if let Some(parent) = parent {
            if let Some(last) = self.nodes[parent].last_child {
                self.nodes[last].next_sibling = Some(index);
            } else {
                self.nodes[parent].first_child = Some(index);
            }
            let node = &mut self.nodes[parent];
            node.last_child = Some(index);
            node.child_hash = hash_of((node.child_hash, key));
        }
        index
    }

    /// `key`, or — if a node already took it this frame — a key derived from
    /// it, after reporting the duplicate once for this frame.
    fn unique(&mut self, key: NodeKey) -> NodeKey {
        let frame = self.frame;
        let taken = |store: &NodeStore, key| {
            store
                .find(key)
                .is_some_and(|slot| store.get(slot).last_touched_frame == frame)
        };
        if !taken(&self.store, key) {
            return key;
        }
        if !self.duplicates.contains(&key) {
            crcbl_core::warn!(
                "ui tree: two nodes under one parent share the key {key:?}; give a loop's rows \
                 `block_keyed` or distinct ids"
            );
            self.duplicates.push(key);
        }
        let mut nth = 0;
        loop {
            let derived = NodeKey(hash_of(KeySource::Duplicate(key.0, nth)));
            if !taken(&self.store, derived) {
                return derived;
            }
            nth += 1;
        }
    }

    /// Diffs a finished node against the store, and clears its cache and every
    /// ancestor's when its style, children or content changed.
    fn close(&mut self, index: usize) {
        let node = &self.nodes[index];
        let stored = self.store.get_mut(node.slot);
        let changed = node.fresh
            || stored.style_hash != node.style_hash
            || stored.child_hash != node.child_hash
            || stored.content_hash != node.content_hash;
        if !changed {
            return;
        }
        stored.style_hash = node.style_hash;
        stored.child_hash = node.child_hash;
        stored.content_hash = node.content_hash;
        let mut next = Some(index);
        while let Some(index) = next {
            let node = &self.nodes[index];
            self.store.get_mut(node.slot).cache.clear();
            next = node.parent;
        }
    }

    fn response(&self, index: usize) -> Response {
        let node = &self.nodes[index];
        let Interaction {
            hovered,
            pressed,
            clicked,
            focused,
            engagement,
            captured,
        } = self.store.get(node.slot).interaction;
        Response {
            key: node.key,
            hovered,
            pressed,
            clicked,
            focused,
            engagement,
            captured,
            changed: false,
        }
    }

    /// The innermost open block's stored state, if a block is open.
    fn current(&self) -> Option<&store::StoredNode> {
        self.open
            .last()
            .map(|&index| self.store.get(self.nodes[index].slot))
    }

    /// Whether the pointer is over the innermost open block; see
    /// [`Response::hovered`]. False outside every block.
    #[must_use]
    pub fn hovered(&self) -> bool {
        self.current().is_some_and(|node| node.interaction.hovered)
    }

    /// Whether the innermost open block holds the press; see
    /// [`Response::pressed`].
    #[must_use]
    pub fn pressed(&self) -> bool {
        self.current().is_some_and(|node| node.interaction.pressed)
    }

    /// Whether the innermost open block was clicked this frame; see
    /// [`Response::clicked`].
    #[must_use]
    pub fn clicked(&self) -> bool {
        self.current().is_some_and(|node| node.interaction.clicked)
    }

    /// How far the innermost open block's children are scrolled. Zero outside
    /// every block.
    #[must_use]
    pub fn scroll_offset(&self) -> Vec2 {
        self.current().map_or(Vec2::ZERO, |node| node.scroll_offset)
    }

    /// Scrolls the innermost open block's children by `offset`: they are drawn
    /// and hit that far up and left of where they are laid out. For an
    /// `overflow: scroll` block the offset is clamped at layout to how far its
    /// content reaches; any other block takes it as given. Does nothing
    /// outside every block.
    pub fn set_scroll_offset(&mut self, offset: Vec2) {
        if let Some(&index) = self.open.last() {
            self.store.get_mut(self.nodes[index].slot).scroll_offset = offset;
        }
    }

    /// Lays out this frame's tree and prunes every stored node it did not
    /// build, then records whether a virtualized view showed a row the build
    /// left out, for [`Ui::needs_rebuild`].
    ///
    /// Every top-level block is a root, laid out in `available` and placed at
    /// `origin`; a page with more than one panel puts them under one root and
    /// positions them there. A pop-up is a root too, laid out in `available`
    /// and placed against its anchor inside that space; see `popup.rs`.
    pub fn layout(&mut self, origin: Vec2, available: AvailableSpace, atlas: &FontAtlas) {
        self.viewport = Some(popup::viewport_of(origin, available));
        self.flatten_children();
        self.store.prune(self.frame);
        let store = &self.store;
        self.edits.retain(|key, _| store.find(*key).is_some());

        let space = taffy::Size {
            width: available.width.to_taffy(),
            height: available.height.to_taffy(),
        };
        let roots: Vec<usize> = (0..self.nodes.len())
            .filter(|&index| self.nodes[index].parent.is_none())
            .collect();
        let mut tree = LayoutTree {
            nodes: &mut self.nodes,
            children: &self.children,
            store: &mut self.store,
            text: &self.text,
            measure: &mut self.measure,
            atlas,
        };
        for &root in &roots {
            compute_root_layout(&mut tree, NodeId::from(root), space);
            round_layout(&mut tree, NodeId::from(root));
        }
        self.lay_out_paragraphs(atlas);
        self.cut_text(atlas);
        self.measure.end_cycle(&self.live_text);
        self.fit_text_inputs(atlas);
        self.clamp_scroll();
        self.place(origin);
        if self.reveal_requested() {
            self.place(origin);
        }
        self.check_built_rows();
    }

    /// The text `node` shows: `None` unless it is a text span.
    fn shown_text(&self, node: &FrameNode) -> Option<&str> {
        match (node.content, node.shown) {
            (Content::Text { .. }, Shown::Cut { start, end }) => Some(&self.cut[start..end]),
            (Content::Text { start, end } | Content::Run { start, end }, _) => {
                Some(&self.text[start..end])
            }
            (Content::Block | Content::Image(_) | Content::Paragraph, _) => None,
        }
    }

    /// The text the span `key` showed at this frame's layout: its text as it
    /// was built, or — under `text-overflow: ellipsis` — cut to fit its box,
    /// so `"Take item 18 fr…"`. What a caller reads a span's text back by
    /// whatever font it is in: a span in a parsed font draws a
    /// [`DrawList::glyphs`] run, which carries glyph ids and no string.
    ///
    /// **A wrapped span answers its text unbroken**: the lines layout broke it
    /// into are where it was drawn, not what it says, and the spaces a line
    /// broke at are still in it. Lines are joined by the newlines the text
    /// itself holds, each one cut on its own.
    ///
    /// `None` for a block, an image span, a key no node of this frame has, and
    /// a span built since the last [`Ui::layout`] — so from
    /// [`Ui::begin_frame`] until the frame is laid out.
    #[must_use]
    pub fn text(&self, key: NodeKey) -> Option<&str> {
        let index = self.store.by_key(key)?.paint_order;
        let node = self.nodes.get(index).filter(|node| node.key == key)?;
        if node.shown == Shown::Pending {
            return None;
        }
        self.shown_text(node)
    }

    /// Clamps every `overflow: scroll` block's offset to the reach its content
    /// was just laid out with, and records that reach for focus to scroll by.
    fn clamp_scroll(&mut self) {
        for node in &self.nodes {
            let stored = self.store.get_mut(node.slot);
            if node.style.overflow == Overflow::Scroll {
                let reach = Vec2::new(node.layout.scroll_width(), node.layout.scroll_height());
                stored.scroll_max = reach;
                stored.scroll_offset = stored.scroll_offset.clamp(Vec2::ZERO, reach);
            } else {
                stored.scroll_max = Vec2::ZERO;
            }
        }
    }

    /// Writes each node's children into `children` in build order — none for
    /// a paragraph, which Taffy lays out as a leaf.
    fn flatten_children(&mut self) {
        self.children.clear();
        for index in 0..self.nodes.len() {
            let start = self.children.len();
            let mut next = match self.nodes[index].content {
                Content::Paragraph => None,
                _ => self.nodes[index].first_child,
            };
            while let Some(child) = next {
                self.children.push(NodeId::from(child));
                next = self.nodes[child].next_sibling;
            }
            let node = &mut self.nodes[index];
            node.child_start = start;
            node.child_count = self.children.len() - start;
        }
    }

    /// Resolves every node's screen rectangle, clip and layer into the store,
    /// for emission and for next frame's hit test: the tree's roots at
    /// `origin`, then each open pop-up's against its anchor, lowest first, so
    /// an anchor is placed before what hangs from it, then the tooltip's.
    fn place(&mut self, origin: Vec2) {
        let layers = self.layers();
        let mut placed = vec![(Vec2::ZERO, ClipRect::NONE, true); self.nodes.len()];
        self.place_layer(0, &layers, &mut placed, |ui, index| {
            let location = ui.nodes[index].layout.location;
            (
                origin + Vec2::new(location.x, location.y),
                ClipRect::NONE,
                false,
            )
        });
        for layer in 1..=self.popups.len() {
            let popup = self.popups[layer - 1];
            let viewport = self.viewport();
            self.place_layer(layer, &layers, &mut placed, |ui, index| {
                (ui.popup_origin(index, popup), viewport, false)
            });
        }
        if let Some((_, anchor)) = self.tooltip.built {
            // Hidden with its anchor, which was placed in a lower layer.
            let hidden = placed[anchor].2;
            let popup = popup::OpenPopup {
                anchor: self.nodes[anchor].key,
                placement: Placement::Below,
            };
            let viewport = self.viewport();
            self.place_layer(tooltip::TOOLTIP_LAYER, &layers, &mut placed, |ui, index| {
                (ui.popup_origin(index, popup), viewport, hidden)
            });
        }
        self.place_layer(popup::CLOSED_LAYER, &layers, &mut placed, |_, _| {
            (Vec2::ZERO, ClipRect::NONE, true)
        });
        self.place_runs();
    }

    /// Places every node of `layer`, in build order: a root where `root` says,
    /// as its border box's top-left, the clip it is under and whether it is
    /// hidden, and every other node inside its parent. `placed` holds each
    /// node's top-left, clip and hiddenness once it is placed.
    fn place_layer(
        &mut self,
        layer: usize,
        layers: &[usize],
        placed: &mut [(Vec2, ClipRect, bool)],
        root: impl Fn(&Self, usize) -> (Vec2, ClipRect, bool),
    ) {
        // Nodes are in build order, so a parent is always placed before its
        // children and its entry in `placed` is filled in by the time a child
        // reads it.
        for index in 0..self.nodes.len() {
            if layers[index] != layer {
                continue;
            }
            let node = &self.nodes[index];
            let (min, clip, hidden) = match node.parent {
                Some(parent) => {
                    let (parent_min, parent_clip, parent_hidden) = placed[parent];
                    let parent_node = &self.nodes[parent];
                    let scroll = self.store.get(parent_node.slot).scroll_offset;
                    let clip = if parent_node.style.overflow.clips() {
                        let (min, max) = padding_box(parent_min, &parent_node.layout);
                        parent_clip.intersect(ClipRect { min, max })
                    } else {
                        parent_clip
                    };
                    let location = Vec2::new(node.layout.location.x, node.layout.location.y);
                    (parent_min - scroll + location, clip, parent_hidden)
                }
                None => root(self, index),
            };
            let node = &self.nodes[index];
            let max = min + Vec2::new(node.layout.size.width, node.layout.size.height);
            let hidden = hidden || node.style.display == Display::None;
            placed[index] = (min, clip, hidden);

            let stored = self.store.get_mut(node.slot);
            stored.rect = (min, max);
            stored.clip = clip;
            stored.paint_order = index;
            stored.layer = layer;
            stored.hittable = !hidden;
            stored.inert = layer == tooltip::TOOLTIP_LAYER;
        }
    }

    /// How far `key`'s children are scrolled, as last frame left it; zero for a
    /// node the store does not hold.
    #[must_use]
    pub fn scroll_offset_of(&self, key: NodeKey) -> Vec2 {
        self.store
            .by_key(key)
            .map_or(Vec2::ZERO, |node| node.scroll_offset)
    }

    /// Scrolls `key`'s children to `offset`, whether or not that node is the
    /// one being built: [`Ui::set_scroll_offset`] by key, and the mirror of
    /// [`Ui::scroll_offset_of`]. Does nothing for a node the store does not
    /// hold.
    ///
    /// **This is how a caller scrolls a virtualized row into view.** A list or
    /// an outliner builds only the rows in its window, so a row the offset is
    /// nowhere near has no node and no rectangle — [`Ui::set_focus`]'s
    /// scroll-into-view, which works from a node's rectangle, cannot reach it.
    /// The caller knows the row's index and height and so knows where it is; it
    /// writes the offset here, and the next [`Ui::layout`] clamps it to the
    /// content's reach, as it clamps every offset it is given.
    pub fn set_scroll_offset_of(&mut self, key: NodeKey, offset: Vec2) {
        if let Some(slot) = self.store.find(key) {
            self.store.get_mut(slot).scroll_offset = offset;
        }
    }

    /// Scrolls the `overflow: scroll` blocks under this frame's pointer by a
    /// wheel's `delta`, in pixels, and says whether anything moved. Call it
    /// after [`Ui::begin_frame`], with the frame's wheel movement; positive `y`
    /// moves toward the end of the content, as a wheel turned toward the
    /// player does in a browser.
    ///
    /// **Each axis goes to the innermost block that can still move along it.**
    /// The pointer is hit-tested against last frame's rectangles, as
    /// [`Ui::begin_frame`] resolves hover, and the chain of blocks holding it is
    /// walked innermost first: a list scrolls until it is at its end, and only
    /// then does the wheel reach the panel around it — a browser's scroll
    /// chaining. Each block moves no further than the reach its last layout
    /// gave it.
    ///
    /// `false` when nothing under the pointer could move — so the caller can
    /// give the wheel to something else, such as a zoom bound to it. Any
    /// movement of the wheel hides the tooltip, as [`Ui::dismiss_tooltip`]
    /// does.
    pub fn scroll_wheel(&mut self, delta: Vec2) -> bool {
        if delta != Vec2::ZERO {
            self.dismiss_tooltip();
        }
        let chain = self.store.hit_chain(self.pointer.pos);
        let mut moved = false;
        for axis in 0..2 {
            let step = delta[axis];
            if step == 0.0 {
                continue;
            }
            for &key in &chain {
                let Some(slot) = self.store.find(key) else {
                    continue;
                };
                let node = self.store.get_mut(slot);
                let offset = node.scroll_offset[axis];
                let next = (offset + step).clamp(0.0, node.scroll_max[axis]);
                if next != offset {
                    node.scroll_offset[axis] = next;
                    moved = true;
                    break;
                }
            }
        }
        moved
    }

    /// The cursor for where the pointer is, as `crcbl_shell`'s
    /// `Shell::set_cursor` takes it: the `cursor` of the node a press is holding while a drag lasts, or
    /// else of the topmost node under the pointer, which inherits it from the
    /// nodes around it. `None` is `cursor: none`, a hidden pointer, and over no
    /// node at all it is the default arrow.
    ///
    /// Call it once the frame is built, since the node's style is this
    /// frame's, and hand it to the shell only when it changes: setting a
    /// cursor is a platform call, not free.
    #[must_use]
    pub fn cursor(&self) -> Option<CursorIcon> {
        self.cursor_node
            .and_then(|key| self.nodes.iter().find(|node| node.key == key))
            .map_or(Some(CursorIcon::Default), |node| node.style.cursor)
    }

    /// Last layout's border box for `key`, in screen pixels.
    #[must_use]
    pub fn rect(&self, key: NodeKey) -> Option<(Vec2, Vec2)> {
        self.store.by_key(key).map(|node| node.rect)
    }

    /// How many nodes the store holds.
    #[must_use]
    pub fn len(&self) -> usize {
        self.store.len()
    }

    /// Whether the store holds no nodes.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.store.len() == 0
    }

    /// Binds `name` — what a stylesheet's `url(name)` says — to `image`, a
    /// picture registered in an [`ImageAtlas`](crate::image::ImageAtlas),
    /// replacing whatever the name was bound to.
    ///
    /// Read when the tree is emitted, so a binding changes what the next
    /// [`Ui::emit`] draws and never moves a box. A name no call bound draws
    /// nothing; see [`crate::style`]'s image notes.
    pub fn set_image(&mut self, name: &str, image: AtlasImage) {
        self.images.insert(ImageName::new(name), image);
    }

    /// Registers `font` as a face of the family `name`, so a `font-family`
    /// list that names it ahead of its first built-in family measures and
    /// draws in it.
    ///
    /// `name` is matched as [`FamilyName`] says: ASCII case ignored, and an
    /// unquoted name's words joined by single spaces. **A family holds one
    /// face per weight and style**, as the font's own tables give them
    /// ([`Font::weight`], [`Font::is_italic`]): registering a bold font under
    /// a name that has a regular one adds a face, and a span picks among them
    /// by its `font-weight` and `font-style` — see [`crate::font::face`] for
    /// the rule, and for the bold and italic drawn when the family has no such
    /// face. **Registering a face of a weight and style the family already
    /// has replaces it**, as [`Ui::set_image`] replaces a picture, and every
    /// span in it is measured again. The registry is read when a span is
    /// built, so a span built this frame before the call keeps the font it was
    /// built in. See `crate::style`'s property notes for what a name nothing is
    /// registered under does.
    ///
    /// `font` is a [`Font`] or a reference to one, which is cloned: a font
    /// parsed at run time from bytes the application read registers as
    /// readily as a compiled-in one.
    ///
    /// # Errors
    ///
    /// [`ReservedFamilyName`] for an empty name, a built-in family's (`bitmap`,
    /// `Atkinson Hyperlegible`), a generic family (`serif`, `sans-serif`,
    /// `monospace`, …) or a CSS-wide keyword: no `font-family` list selects a
    /// registered font by one of those, so the font would never draw.
    pub fn register_font(
        &mut self,
        name: &str,
        font: impl Into<Font>,
    ) -> Result<(), ReservedFamilyName> {
        if is_reserved_family(name) {
            return Err(ReservedFamilyName(name.to_owned()));
        }
        let font = font.into();
        let faces = self.fonts.entry(FamilyName::new(name)).or_default();
        let same_face =
            |face: &Font| face.weight() == font.weight() && face.is_italic() == font.is_italic();
        match faces.iter_mut().find(|face| same_face(face)) {
            Some(face) => *face = font,
            None => faces.push(font),
        }
        Ok(())
    }

    /// Sets the faces every text span in a parsed font falls back to, in the
    /// order they are asked, for a char its own face has no glyph for — an
    /// emoji in a notification body, say, drawn from a colour emoji font. See
    /// [`crate::font::fallback`] for the rule and the presentation selectors.
    ///
    /// **One list for the whole tree, asked after whatever face a span's
    /// `font-family` selected**, so a stylesheet never has to name the emoji
    /// font beside every family; `emoji`, CSS's generic family, stays a
    /// reserved name rather than a second way to say the same thing. A span
    /// in the bitmap font falls back only for a char it has no glyph for,
    /// and keeps its grid: the face's glyph is drawn inside that char's one
    /// cell, which measuring never changes. The faces draw as registered: a
    /// bold span's fallback glyphs are not synthesised bold.
    ///
    /// Read when a span is built, like [`Ui::register_font`]'s registry, and
    /// every span is measured again under a new list. An empty list, the
    /// default, turns fallback off.
    ///
    /// A colour glyph — an emoji font's CBDT, sbix or COLR picture — draws in
    /// colour when the emitted list is drawn by `crcbl-frame`'s UI pass, which
    /// puts it in its image atlas as it tessellates; see
    /// [`crate::font::color`] for a renderer of its own.
    pub fn set_fallback_fonts(&mut self, fonts: impl IntoIterator<Item = impl Into<Font>>) {
        self.fallback = fonts.into_iter().map(Into::into).collect();
        self.fallback_hash = hash_of(self.fallback.iter().map(Font::id).collect::<Vec<_>>());
    }

    /// The faces [`Ui::set_fallback_fonts`] set, in order.
    #[must_use]
    pub fn fallback_fonts(&self) -> &[Font] {
        &self.fallback
    }

    /// The parsed font a text span in `style` draws in: the face of the family
    /// registered under its family name that its weight and style select,
    /// else its built-in family's — synthesised where the face falls short,
    /// see [`crate::font::face`] — carrying [`Ui::set_fallback_fonts`]'s
    /// faces, and `None` for the bitmap font. Warns once per name when the
    /// span names a family nothing is registered under; `selector` says which
    /// span.
    fn font_for(&mut self, style: &NodeStyle, selector: &str) -> Option<Font> {
        let face = self.face_for(style, selector)?;
        Some(if self.fallback.is_empty() {
            face
        } else {
            face.with_fallback(&self.fallback)
        })
    }

    /// [`Ui::font_for`]'s face, before its fallback faces.
    fn face_for(&mut self, style: &NodeStyle, selector: &str) -> Option<Font> {
        if let Some(name) = style.family_name {
            if let Some(font) = self
                .fonts
                .get(&name)
                .and_then(|faces| select_face(faces, style.font_weight, style.font_style))
            {
                return Some(font);
            }
            if self.unregistered.insert(name) {
                crcbl_core::warn!(
                    "tree: the text span `{selector}` names a font family no font is registered \
                     under (Ui::register_font); it draws in {:?}",
                    style.font_family
                );
            }
        }
        let built_in = style.font_family.font()?;
        select_face(
            core::slice::from_ref(built_in),
            style.font_weight,
            style.font_style,
        )
    }

    /// The keys two nodes shared this frame, each once.
    #[must_use]
    pub fn duplicate_keys(&self) -> &[NodeKey] {
        &self.duplicates
    }

    /// The key of the block whose builder is running: what a closure a widget
    /// calls back — a list's row, an outliner's row, a dock's pane — reads to
    /// learn which node it is filling. None outside every block.
    #[must_use]
    pub fn current_key(&self) -> Option<NodeKey> {
        self.open.last().map(|&index| self.nodes[index].key)
    }

    /// The keys of every node built inside `key` this frame, in build order;
    /// empty for a node this frame did not build. What a test or a UI
    /// inspector walks the tree with.
    #[must_use]
    pub fn child_keys(&self, key: NodeKey) -> Vec<NodeKey> {
        let Some(parent) = self.nodes.iter().position(|node| node.key == key) else {
            return Vec::new();
        };
        let mut keys = Vec::new();
        let mut next = self.nodes[parent].first_child;
        while let Some(child) = next {
            keys.push(self.nodes[child].key);
            next = self.nodes[child].next_sibling;
        }
        keys
    }
}

/// A node's padding box, given its border box's top-left.
fn padding_box(min: Vec2, layout: &taffy::Layout) -> (Vec2, Vec2) {
    let border = layout.border;
    (
        min + Vec2::new(border.left, border.top),
        min + Vec2::new(
            layout.size.width - border.right,
            layout.size.height - border.bottom,
        ),
    )
}