rux-layout 0.6.1

Rux layout: a styled node tree resolved to absolute paint rects via taffy. Internal to Rux; the supported entry point is the ruxlang crate.
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
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
//! Rux layout, milestones M1–M4.
//!
//! A styled node tree fed through `taffy` (flexbox) to produce absolute paint
//! items. Boxes come straight from taffy; text leaves are sized through a
//! caller-supplied `measure` callback (so this crate stays free of any font
//! dependency, the shell owns the text engine). See `docs/04-architecture.md`,
//! Stage 4.
//!
//! The crate is mostly its vocabulary. [`Style`] is the honored subset of CSS
//! as the engine actually sees it, and [`Node`] is one styled element with its
//! children. `rux-style` produces that tree; this crate turns it into the flat
//! [`Paint`] list `rux-paint` consumes, in absolute coordinates with the
//! cascade and the box model already collapsed into numbers.
//!
//! Layout emits more than pictures, because a frame's geometry is the only
//! place several other questions can be answered honestly. Alongside the paint
//! items come the regions the shell needs and cannot recompute for itself:
//! [`HitRegion`] for pointer targets, [`ScrollRegion`] for what scrolls and how
//! far, [`FocusRegion`] and [`FocusItem`] for tab order, [`SelectRegion`] for
//! selectable text, [`StateRegion`] for hover and active, and [`AccessNode`]
//! for the accessibility tree. All of them are in the same coordinate space as
//! the paint items, which is the point: two places doing the same coordinate
//! arithmetic eventually disagree, so there is one conversion and everyone
//! reads its output.
//!
//! Both flexbox and grid come from taffy. What does not come from taffy is
//! text sizing, which is why `measure` is a callback: pulling a font
//! stack into this crate would put shaping under layout, and the shell already
//! owns one.

use std::collections::HashMap;

use taffy::prelude::*;
use taffy::geometry::Point;

/// Straight RGBA in the 0..=1 range. Renderer-agnostic.
#[derive(Clone, Copy, Debug)]
pub struct Rgba {
    pub r: f32,
    pub g: f32,
    pub b: f32,
    pub a: f32,
}

impl Rgba {
    pub const fn new(r: f32, g: f32, b: f32, a: f32) -> Self {
        Self { r, g, b, a }
    }
}

/// Per-side box-model lengths (padding / margin / border widths).
#[derive(Clone, Copy, Debug, Default)]
pub struct Sides {
    pub top: f32,
    pub right: f32,
    pub bottom: f32,
    pub left: f32,
}

impl Sides {
    pub const fn uniform(v: f32) -> Self {
        Self {
            top: v,
            right: v,
            bottom: v,
            left: v,
        }
    }
}

/// A CSS length. Percentages are stored as a fraction (`0.0..=1.0`); `vh`/`vw`
/// hold the raw viewport-percentage number (e.g. `100vh` → `Vh(100.0)`). `rem`
/// is resolved to pixels at parse time.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Len {
    Px(f32),
    Pct(f32),
    Vw(f32),
    Vh(f32),
}

/// A grid track size (`grid-template-columns`/`-rows`).
#[derive(Clone, Copy, Debug)]
pub enum Track {
    Px(f32),
    Fr(f32),
    Auto,
    /// `minmax(min, max)`. Its whole point over a bare `1fr` is a `0` (or `px`)
    /// minimum, which lets the track shrink *below* its content's min-content,
    /// so a grid of fixed-size cards squeezes to fit instead of overflowing.
    MinMax(TrackSide, TrackSide),
}

/// One side of a `minmax()`, never itself a `minmax`. A `Fr` is only valid on
/// the max side (a flex minimum is meaningless), and degrades to `auto` if used
/// as a minimum.
#[derive(Clone, Copy, Debug)]
pub enum TrackSide {
    Px(f32),
    Fr(f32),
    Auto,
}

/// How a node lays out its children. Defaults to `Row` to match CSS's
/// `flex-direction` initial value.
#[derive(Clone, Copy, Debug, Default)]
pub enum Axis {
    #[default]
    Row,
    Column,
}

/// Main-axis distribution (`justify-content`).
#[derive(Clone, Copy, Debug)]
pub enum Justify {
    Start,
    Center,
    End,
    SpaceBetween,
    SpaceAround,
}

/// Cross-axis alignment (`align-items`).
#[derive(Clone, Copy, Debug)]
pub enum Align {
    Start,
    Center,
    End,
    Stretch,
}

/// Horizontal text alignment within a text box (`text-align`).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum TextAlign {
    #[default]
    Start,
    Center,
    End,
    Justify,
}

/// How a line may break when a word is wider than its box (`overflow-wrap` /
/// `word-break`). CSS's default lets a long word overflow rather than break.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum TextWrap {
    #[default]
    Normal,
    /// `overflow-wrap: break-word`: break inside a word rather than overflow.
    BreakWord,
    /// `word-break: break-all`: break anywhere.
    Anywhere,
}

/// CSS `display`. Defaults to `Block` (strict-CSS fidelity): flex layout,
/// `gap`, and `flex-direction` only apply under `Flex`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Display {
    #[default]
    Block,
    /// Hugs its content and does not stretch to fill (works inside flex parents;
    /// taffy has no true inline text flow).
    Inline,
    Flex,
    Grid,
    /// Removed from layout entirely (no space reserved).
    None,
}

/// Overflow behaviour for content exceeding a box.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Overflow {
    #[default]
    Visible,
    /// Clip the subtree to this box (`hidden` / `clip`).
    Clip,
    /// Clip, and let the wheel move the content (`auto` / `scroll`). The box
    /// keeps its own size; taffy reports how tall the content actually is.
    Scroll,
}

/// The mouse cursor shown while the pointer is over a box (`cursor`). Only the
/// values the shell maps to a winit `CursorIcon` are modelled; the default is
/// the arrow.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Cursor {
    #[default]
    Default,
    /// `cursor: pointer`: the hand, for tappable things.
    Pointer,
}

/// `position`. `Relative` is the normal in-flow box (the default); `Absolute`
/// takes the box out of flow and positions it by its `inset` against the
/// nearest positioned ancestor.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum Position {
    #[default]
    Relative,
    Absolute,
}

/// Corner radii in CSS order, top-left, top-right, bottom-right, bottom-left.
/// A single `border-radius` fills all four; the per-corner longhands override.
pub type Corners = [f32; 4];

/// A 2-D affine `transform`, as the six coefficients `[a, b, c, d, e, f]` (kurbo
/// `Affine` order: `x' = a·x + c·y + e`, `y' = b·x + d·y + f`). Translations are
/// in logical px; the origin is applied at paint time (CSS default: box centre).
pub type Transform = [f32; 6];

/// `grid-auto-flow`: how auto-placed items fill the implicit grid.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum GridFlow {
    #[default]
    Row,
    Column,
    RowDense,
    ColumnDense,
}

/// One endpoint of a `grid-column` / `grid-row` placement.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub enum GridPlace {
    /// Auto-placed by the grid algorithm.
    #[default]
    Auto,
    /// A specific grid line (1-based; negative counts back from the end).
    Line(i16),
    /// Span this many tracks from the other endpoint.
    Span(u16),
}

/// A box background: a flat colour, a gradient, or an image.
#[derive(Clone, Debug)]
pub enum Background {
    Color(Rgba),
    Gradient(Gradient),
    /// `background-image: url(…)`. The runtime resolves this to an absolute path
    /// (like `<image src>`); the painter decodes it and draws it `cover`-sized.
    Image(String),
}

/// A CSS gradient reduced to what the painter needs: a shape and colour stops.
#[derive(Clone, Debug)]
pub struct Gradient {
    pub kind: GradientKind,
    /// Colour stops as `(colour, offset)` with offset in 0..=1, in order.
    pub stops: Vec<(Rgba, f32)>,
}

#[derive(Clone, Copy, Debug)]
pub enum GradientKind {
    /// `linear-gradient(<angle>, …)`: angle in radians, CSS convention (0 = to
    /// top, increasing clockwise).
    Linear { angle: f32 },
    /// `radial-gradient(…)`: a centred circle out to the nearest edge.
    Radial,
}

/// A single (outer) `box-shadow`. Offsets, blur and spread are logical px.
#[derive(Clone, Copy, Debug)]
pub struct BoxShadow {
    pub dx: f32,
    pub dy: f32,
    pub blur: f32,
    pub spread: f32,
    pub color: Rgba,
    /// `inset` shadows are parsed but not yet drawn.
    pub inset: bool,
}

/// The style subset M-series understands (a stand-in for the CSS `ComputedStyle`).
#[derive(Clone, Debug)]
pub struct Style {
    pub display: Display,
    pub width: Option<Len>,
    pub height: Option<Len>,
    pub min_width: Option<Len>,
    pub max_width: Option<Len>,
    pub min_height: Option<Len>,
    pub max_height: Option<Len>,
    pub grid_columns: Vec<Track>,
    pub grid_rows: Vec<Track>,
    /// `grid-column` / `grid-row` placement for a grid item: `(start, end)`.
    pub grid_column: (GridPlace, GridPlace),
    pub grid_row: (GridPlace, GridPlace),
    /// `grid-auto-flow` and the implicit-track sizes `grid-auto-rows`/`-columns`.
    pub grid_auto_flow: GridFlow,
    pub grid_auto_rows: Vec<Track>,
    pub grid_auto_columns: Vec<Track>,
    pub grow: f32,
    /// `flex-shrink`. CSS defaults to 1: a flex item gives up space to fit its
    /// container. `0` keeps the item's size and lets it overflow, which is the
    /// author's call, and what `overflow: clip` is for.
    pub shrink: f32,
    /// `flex-basis`. `None` = `auto` (size from width/content).
    pub basis: Option<Len>,
    /// `flex-wrap: wrap`: items that don't fit start a new line.
    pub wrap: bool,
    /// `opacity`, 0.0–1.0. Applies to the whole subtree.
    pub opacity: f32,
    /// `overflow-wrap` / `word-break`, applied to a text node's own content.
    pub text_wrap: TextWrap,
    pub padding: Sides,
    pub margin: Sides,
    pub border: Sides,
    pub border_color: Option<Rgba>,
    pub gap: f32,
    /// `row-gap` / `column-gap` overrides for the shorthand `gap`. `None` keeps
    /// the shorthand (`gap`) value on that axis.
    pub row_gap: Option<f32>,
    pub column_gap: Option<f32>,
    pub axis: Axis,
    pub justify: Option<Justify>,
    pub align: Option<Align>,
    /// `align-self` (flex/grid cross-axis) and `justify-self` (grid inline-axis)
    /// for this item, overriding the parent's `align-items`/`justify-items`.
    pub align_self: Option<Align>,
    pub justify_self: Option<Align>,
    /// `justify-items` (grid) and `align-content` (multi-line flex / grid).
    pub justify_items: Option<Align>,
    pub align_content: Option<Justify>,
    pub overflow: Overflow,
    pub background: Option<Background>,
    /// `border-radius`, per corner (top-left, top-right, bottom-right, bottom-left).
    pub radius: Corners,
    /// `box-shadow` (single, outer). Drawn behind the box's own background.
    pub box_shadow: Option<BoxShadow>,
    /// `transform`: an affine applied to this box and its subtree at paint time.
    /// Visual only: hit regions are not transformed.
    pub transform: Option<Transform>,
    /// `cursor`: the pointer shape over this box.
    pub cursor: Cursor,
    /// `position` and its `inset` (top, right, bottom, left). `None` per side =
    /// `auto`. Only meaningful when `position: absolute`.
    pub position: Position,
    pub inset: [Option<Len>; 4],
    /// `aspect-ratio` (width / height).
    pub aspect_ratio: Option<f32>,
}

impl Default for Style {
    fn default() -> Self {
        Self {
            display: Display::Block,
            width: None,
            height: None,
            min_width: None,
            max_width: None,
            min_height: None,
            max_height: None,
            grid_columns: Vec::new(),
            grid_rows: Vec::new(),
            grid_column: (GridPlace::Auto, GridPlace::Auto),
            grid_row: (GridPlace::Auto, GridPlace::Auto),
            grid_auto_flow: GridFlow::Row,
            grid_auto_rows: Vec::new(),
            grid_auto_columns: Vec::new(),
            grow: 0.0,
            shrink: 1.0,
            basis: None,
            wrap: false,
            opacity: 1.0,
            text_wrap: TextWrap::Normal,
            padding: Sides::default(),
            margin: Sides::default(),
            border: Sides::default(),
            border_color: None,
            gap: 0.0,
            row_gap: None,
            column_gap: None,
            axis: Axis::Row,
            justify: None,
            align: None,
            align_self: None,
            justify_self: None,
            justify_items: None,
            align_content: None,
            overflow: Overflow::Visible,
            background: None,
            radius: [0.0; 4],
            box_shadow: None,
            transform: None,
            cursor: Cursor::Default,
            position: Position::Relative,
            inset: [None; 4],
            aspect_ratio: None,
        }
    }
}

/// An image carried by a leaf node. `src` is resolved to a path the painter can
/// open; the intrinsic size is filled in by the runtime (it reads the file's
/// header) and sizes the box when CSS gives no width/height.
#[derive(Clone, Debug)]
pub struct ImageContent {
    pub src: String,
    pub intrinsic: (f32, f32),
}

/// Text carried by a leaf node.
#[derive(Clone, Debug)]
pub struct TextContent {
    pub text: String,
    pub font_size: f32,
    pub weight: u16,
    pub color: Rgba,
    pub align: TextAlign,
    pub wrap: TextWrap,
    /// `font-family` as a raw CSS list (e.g. `"Inter, sans-serif"`). `None` uses
    /// the system default. Inherits, like `color` and `font-size`.
    pub font_family: Option<String>,
    /// `letter-spacing` / `word-spacing`, extra px between letters / words.
    pub letter_spacing: Option<f32>,
    pub word_spacing: Option<f32>,
    /// `line-height` as an absolute pixel value; `None` uses the font metrics.
    pub line_height: Option<f32>,
    /// `font-style: italic`.
    pub italic: bool,
    /// `text-decoration: underline` / `line-through`.
    pub underline: bool,
    pub strikethrough: bool,
    /// `white-space: nowrap`: never wrap, even past the box width.
    pub nowrap: bool,
    /// Byte index of the caret, when this text is inside the focused input.
    pub caret: Option<usize>,
    /// The selected byte range (start < end, normalized), when this text is
    /// inside the focused input and its selection isn't collapsed. The painter
    /// highlights it behind the glyphs.
    pub selection: Option<(usize, usize)>,
    /// The byte range holding an in-progress IME composition, when this text is
    /// inside the focused input and something is being composed. The painter
    /// underlines it.
    ///
    /// The composed text is already inside `text`: the shell writes it into the
    /// bound signal as it is typed, exactly as a browser does to an `<input>`'s
    /// value during composition. This range only says which part of it is not
    /// committed yet, so it can be drawn as provisional rather than as text the
    /// author typed and meant.
    pub preedit: Option<(usize, usize)>,
}

/// What an element *is*, for assistive technology. Deliberately a small enum
/// owned by the layout rather than an `accesskit` type: the layout stays free of
/// the platform a11y crate, and only the shell translates these.
///
/// Resolved during the build, where the tag, the `type=` and the `role=`
/// attribute are all still in hand, deriving it later from painted output would
/// be guesswork.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum AccessRole {
    /// Not interesting to a screen reader on its own (a plain layout box).
    #[default]
    None,
    /// Static text.
    Label,
    Heading,
    Button,
    CheckBox,
    RadioButton,
    TextInput,
    /// `type="textarea"`.
    MultilineTextInput,
    /// `type="select"`.
    ComboBox,
    Image,
    /// A navigation target: `to="/path"`, or an explicit `role="link"`. Distinct
    /// from a button because a screen reader announces it differently, and
    /// because the distinction is what tells someone they are moving rather than
    /// acting.
    Link,
    /// A box that scrolls its content.
    ScrollView,
    /// A meaningful grouping (an explicit `role=` we don't map more precisely).
    Group,
}

impl AccessRole {
    /// Does this element carry meaning worth exposing at all?
    pub fn is_meaningful(self) -> bool {
        self != Self::None
    }
}

/// The accessibility facts about one node: what it is, what it's called, and what
/// state it's in. Attached during the build and carried through layout so the
/// shell can publish a tree with real geometry.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Access {
    pub role: AccessRole,
    /// The accessible *name*, what a screen reader announces. For a control this
    /// is its label, not its value.
    pub label: Option<String>,
    /// An input's placeholder. Kept apart from `label` because it is only a
    /// *fallback* name: a real label (authored `label=`, or a `<text for="…">`)
    /// must win, and labels are linked after the build, so baking the placeholder
    /// into `label` would let a hint outrank the actual label.
    pub placeholder: Option<String>,
    /// Current value, for inputs and selects.
    pub value: Option<String>,
    /// Checked state, for checkboxes and radios.
    pub checked: Option<bool>,
}

impl Access {
    /// What to announce as this element's name: its label, else its placeholder.
    pub fn name(&self) -> Option<&str> {
        self.label.as_deref().or(self.placeholder.as_deref())
    }
}

/// A node in the view tree: a style, optional text, children, and an optional
/// `@tap` handler (raw handler source, run by the shell on tap).
#[derive(Clone, Debug)]
pub struct Node {
    pub style: Style,
    pub text: Option<TextContent>,
    /// `<image src=…>`.
    pub image: Option<ImageContent>,
    /// A checkmark stroked to fill this box, in the given colour. Drawn as a
    /// path rather than a font glyph, since ✓ is whatever the system font happens to
    /// ship, which is not a control mark.
    pub tick: Option<Rgba>,
    pub children: Vec<Node>,
    pub on_tap: Option<String>,
    /// `r-model` signal name for `<input>` nodes (focus target + edit binding).
    pub model: Option<String>,
    /// `type="textarea"`: a multi-line text input, `Enter` inserts a newline.
    pub multiline: bool,
    /// `type="select"`: the bound `:options`, so the shell can open a dropdown.
    pub options: Option<Vec<String>>,
    /// `r-show="false"`: laid out (space reserved) but not painted.
    pub hidden: bool,
    /// `id="…"`: a stable identifier a label's `for=` can target.
    pub id: Option<String>,
    /// `for="…"` on a label, the `id` of the input it labels. Resolved at build
    /// time (the label inherits its target's `@tap`), so tapping the label toggles
    /// the target the same way tapping the target would.
    pub label_for: Option<String>,
    /// A label whose `for=` targets a *text* input: the target input's `r-model`.
    /// The layout emits a `FocusRegion` here so tapping the label focuses that input
    /// (the caret lands in the input itself, matched by model).
    pub focus_model: Option<String>,
    /// This node's tree path, set only when some `:hover`/`:active` rule could
    /// match it. The layout emits a [`StateRegion`] for such nodes so the shell can
    /// tell what the pointer is over and hand the path back as interaction state.
    /// `None`: the common case, costs nothing.
    pub state_path: Option<Vec<usize>>,
    /// What this element is, for assistive technology.
    pub access: Access,
    /// Which component instance this node belongs to, when it is inside one.
    ///
    /// A component's own state is private to the instance, so a handler written
    /// in a component has to say which instance it is running in: two `<panel>`
    /// elements are two separate sets of state, and the handler text is
    /// identical in both.
    pub instance: Option<String>,
    /// `r-key` on an `r-for` row: which *item* this node stands for, rather than
    /// which slot it happens to occupy.
    ///
    /// Without it a list is identified by position, so reordering the data moves
    /// every row's identity by one and anything attached to a row (the caret,
    /// most visibly) stays behind with the slot. The runtime uses this to follow
    /// a row across a reorder. Layout itself ignores it.
    pub key: Option<String>,
}

impl Node {
    pub fn new(style: Style) -> Self {
        Self {
            style,
            text: None,
            image: None,
            tick: None,
            children: Vec::new(),
            on_tap: None,
            model: None,
            multiline: false,
            options: None,
            hidden: false,
            id: None,
            label_for: None,
            focus_model: None,
            state_path: None,
            access: Access::default(),
            instance: None,
            key: None,
        }
    }

    pub fn text(style: Style, text: TextContent) -> Self {
        Self {
            style,
            text: Some(text),
            image: None,
            tick: None,
            children: Vec::new(),
            on_tap: None,
            model: None,
            multiline: false,
            options: None,
            hidden: false,
            id: None,
            label_for: None,
            focus_model: None,
            state_path: None,
            access: Access::default(),
            instance: None,
            key: None,
        }
    }

    pub fn image(style: Style, image: ImageContent) -> Self {
        Self {
            style,
            text: None,
            image: Some(image),
            tick: None,
            children: Vec::new(),
            on_tap: None,
            model: None,
            multiline: false,
            options: None,
            hidden: false,
            id: None,
            label_for: None,
            focus_model: None,
            state_path: None,
            access: Access::default(),
            instance: None,
            key: None,
        }
    }

    pub fn with(mut self, child: Node) -> Self {
        self.children.push(child);
        self
    }
}

/// A resolved, absolutely-positioned box: an optional fill and an optional
/// border, sharing one rounded-rect geometry.
#[derive(Clone, Debug)]
pub struct PaintRect {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    pub background: Option<Background>,
    pub radius: Corners,
    /// Uniform border width for rendering (0 = none).
    pub border_width: f32,
    pub border_color: Option<Rgba>,
}

/// A resolved, absolutely-positioned text block.
#[derive(Clone, Debug)]
pub struct PaintText {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    pub content: TextContent,
}

/// A checkmark stroked inside its laid-out box.
#[derive(Clone, Copy, Debug)]
pub struct PaintTick {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    pub color: Rgba,
}

/// An image scaled to fill its laid-out box.
#[derive(Clone, Debug)]
pub struct PaintImage {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    pub content: ImageContent,
}

/// A drawable item in painter's order (parents before children).
#[derive(Clone, Debug)]
pub enum Paint {
    Rect(PaintRect),
    Text(PaintText),
    Image(PaintImage),
    Tick(PaintTick),
    /// A blurred `box-shadow`, drawn behind its box. Geometry already has the
    /// offset and spread applied.
    Shadow {
        x: f32,
        y: f32,
        width: f32,
        height: f32,
        radius: f32,
        blur: f32,
        color: Rgba,
    },
    /// Begin clipping subsequent items to this rounded rect (overflow: clip).
    PushClip {
        x: f32,
        y: f32,
        width: f32,
        height: f32,
        radius: Corners,
    },
    /// End the most recent clip.
    PopClip,
    /// Begin an affine `transform` on the subtree. The matrix already has the
    /// transform-origin baked in, so it applies directly to absolute coords.
    PushTransform(Transform),
    /// End the most recent transform.
    PopTransform,
    /// Begin a translucent layer over the subtree (`opacity`). The shape is the
    /// whole viewport, so the layer fades without also clipping.
    PushOpacity {
        alpha: f32,
        width: f32,
        height: f32,
    },
    /// End the most recent opacity layer.
    PopOpacity,
}

/// How far a scroller's content has travelled, in logical pixels. Positive
/// moves the content up / left, i.e. `y` is "how far down the content we are".
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Offset {
    pub x: f32,
    pub y: f32,
}

impl Offset {
    pub fn clamp_to(self, max: Offset) -> Offset {
        Offset {
            x: self.x.clamp(0.0, max.x),
            y: self.y.clamp(0.0, max.y),
        }
    }
}

/// A scrollable box. `id` is its index in tree order, stable across rebuilds
/// as long as the tree's shape is, which is what the shell keys offsets by.
#[derive(Clone, Debug)]
pub struct ScrollRegion {
    pub id: usize,
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    /// The size of the content inside, which may exceed the box on either axis.
    pub content_width: f32,
    pub content_height: f32,
    /// How far the content can travel on each axis: content - visible (>= 0).
    pub max: Offset,
}

impl ScrollRegion {
    pub fn contains(&self, px: f32, py: f32) -> bool {
        px >= self.x && px <= self.x + self.width && py >= self.y && py <= self.y + self.height
    }

    /// Whether this box scrolls at all on either axis.
    pub fn scrollable(&self) -> bool {
        self.max.x > 0.0 || self.max.y > 0.0
    }
}

/// An absolutely-positioned tappable region, carrying its `@tap` handler source.
#[derive(Clone, Debug)]
pub struct HitRegion {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    pub on_tap: String,
    /// The `cursor` for this region, so the shell can set the pointer shape when
    /// it hovers here. Carried on the hit region because that is the geometry the
    /// shell already hit-tests; a `cursor` on a non-tappable box is not honored.
    pub cursor: Cursor,
    /// The component instance this handler was written in, if any. Its state is
    /// what the handler reads and writes, and two instances of one component
    /// carry identical handler text, so the text alone cannot say which.
    pub instance: Option<String>,
}

impl HitRegion {
    pub fn contains(&self, px: f32, py: f32) -> bool {
        px >= self.x && px <= self.x + self.width && py >= self.y && py <= self.y + self.height
    }
}

/// An absolutely-positioned focusable region for an `<input>`, carrying its
/// `r-model` signal name.
#[derive(Clone, Debug)]
pub struct FocusRegion {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    pub model: String,
    /// The `r-key` of the `r-for` row this input sits in, when it sits in one.
    ///
    /// `model` alone does not identify an input: `r-model` is stored as written,
    /// so every row of a list carries the *same* model text. Without this, two
    /// inputs in one list are indistinguishable and the caret lands in the first
    /// of them whichever one was tapped.
    pub row: Option<String>,
    /// The input's text box (its laid-out child). The shell needs it to turn a
    /// click into a caret position.
    pub text: Option<PaintText>,
    /// `type="textarea"`: `Enter` inserts a newline instead of being ignored.
    pub multiline: bool,
    /// If this input scrolls (a textarea), the index of its `ScrollRegion` in
    /// `Layout.scrolls`, so the shell can scroll the caret into view.
    pub scroll_id: Option<usize>,
}

impl FocusRegion {
    pub fn contains(&self, px: f32, py: f32) -> bool {
        px >= self.x && px <= self.x + self.width && py >= self.y && py <= self.y + self.height
    }
}

/// An absolutely-positioned `type="select"`, carrying its bound options so the
/// shell can open a dropdown and write the chosen value back to `model`.
#[derive(Clone, Debug)]
pub struct SelectRegion {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    pub model: String,
    /// The `r-key` of the `r-for` row this select is in, when it is in one. The
    /// model repeats across a list's rows, so without this the shell opens the
    /// first row's dropdown wherever you tapped, draws it over that row, and
    /// writes the chosen option into it.
    pub row: Option<String>,
    pub options: Vec<String>,
}

impl SelectRegion {
    pub fn contains(&self, px: f32, py: f32) -> bool {
        px >= self.x && px <= self.x + self.width && py >= self.y && py <= self.y + self.height
    }
}

/// An absolutely-positioned box whose styling depends on pointer state
/// (`:hover` / `:active`), carrying the tree path that identifies it to the
/// builder. Emitted only for nodes some pointer-state rule could match, so a
/// document with no such rules produces none.
#[derive(Clone, Debug)]
pub struct StateRegion {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    /// The node's child-index path from the root, the same identity the binding
    /// registry uses.
    pub path: Vec<usize>,
}

impl StateRegion {
    pub fn contains(&self, px: f32, py: f32) -> bool {
        px >= self.x && px <= self.x + self.width && py >= self.y && py <= self.y + self.height
    }
}

/// One element exposed to assistive technology, with the geometry it ended up
/// occupying. Emitted in document order, and only for nodes whose role is
/// meaningful, a plain layout box contributes nothing.
///
/// Flat rather than nested: the shell publishes these as children of the window,
/// which is enough for a screen reader to enumerate and hit-test the UI. Nesting
/// (landmarks, grouping) can layer on later without changing what is collected.
#[derive(Clone, Debug)]
pub struct AccessNode {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    pub access: Access,
    /// `r-model`, when this element is an input, lets the shell match it against
    /// the focused model and report focus to the platform.
    pub model: Option<String>,
}

/// One keyboard-focusable element, in document (Tab) order. Carries the geometry
/// (for the focus ring) plus how the shell should act on it.
#[derive(Clone, Debug)]
pub struct FocusItem {
    pub x: f32,
    pub y: f32,
    pub width: f32,
    pub height: f32,
    pub kind: FocusKind,
    /// The scroller this item sits inside, if any, as an index into
    /// [`Layout::scrolls`].
    ///
    /// The focus ring is painted by the shell as its own scene *after* the
    /// document's, so it never passes through the `PushClip` a scroller emits
    /// around its children. Without knowing the enclosing scroller, a ring on a
    /// row scrolled out of a list draws over whatever is above the list. This
    /// is the enclosing one, not the item's own: a scroller that is itself
    /// focusable is clipped by its parent, not by itself.
    pub scroll: Option<usize>,
}

impl FocusItem {
    pub fn contains(&self, px: f32, py: f32) -> bool {
        px >= self.x && px <= self.x + self.width && py >= self.y && py <= self.y + self.height
    }
}

#[derive(Clone, Debug)]
pub enum FocusKind {
    /// A text / textarea input: focusing it starts caret editing.
    Text { model: String, row: Option<String>, multiline: bool, text: Option<PaintText> },
    /// A button / checkbox / radio: Space or Enter runs its handler.
    Activate { on_tap: String, instance: Option<String> },
    /// A select: Space or Enter opens its dropdown.
    Select { model: String, row: Option<String>, options: Vec<String> },
}

/// The result of laying out a tree: paint items, hit regions, and focus regions,
/// all in painter's/topmost-last order.
#[derive(Clone, Debug, Default)]
pub struct Layout {
    pub paints: Vec<Paint>,
    pub hits: Vec<HitRegion>,
    pub focuses: Vec<FocusRegion>,
    pub selects: Vec<SelectRegion>,
    /// Keyboard-focusable elements in document (Tab) order.
    pub focusables: Vec<FocusItem>,
    pub scrolls: Vec<ScrollRegion>,
    /// Boxes with `:hover`/`:active` styling, in painter's order (topmost last).
    pub states: Vec<StateRegion>,
    /// Elements exposed to assistive technology, in document order.
    pub access: Vec<AccessNode>,
}

/// A node's content box, as an offset from its border-box origin plus a size.
///
/// Taffy resolves padding and border against the container during layout, so
/// these are already absolute pixels: percentage padding and `em` borders are
/// handled by the time this is asked. Clamped at zero, because padding wider
/// than the box itself is arithmetic, not a crash.
fn content_box(layout: &taffy::Layout) -> (f32, f32, f32, f32) {
    let (p, b) = (layout.padding, layout.border);
    (
        p.left + b.left,
        p.top + b.top,
        (layout.size.width - p.left - p.right - b.left - b.right).max(0.0),
        (layout.size.height - p.top - p.bottom - b.top - b.bottom).max(0.0),
    )
}

/// Callback that measures a text block:
/// `(text, font_size, weight, wrap, max_width) -> (w, h)`.
/// Measures a text node to `(width, height)` given an optional max width. Takes
/// the whole [`TextContent`] so new text properties (family, spacing, style…)
/// don't each widen this signature.
pub type Measure<'a> = dyn FnMut(&TextContent, Option<f32>) -> (f32, f32) + 'a;

/// What each taffy node paints.
enum PaintKind {
    Box {
        bg: Option<Background>,
        radius: Corners,
        border_width: f32,
        border_color: Option<Rgba>,
        clip: bool,
        shadow: Option<BoxShadow>,
    },
    Text(TextContent),
    Image(ImageContent),
    Tick(Rgba),
}

fn to_dim(l: Len, vp: (f32, f32)) -> Dimension {
    match l {
        Len::Px(v) => length(v),
        Len::Pct(p) => percent(p),
        Len::Vw(v) => length(vp.0 * v / 100.0),
        Len::Vh(v) => length(vp.1 * v / 100.0),
    }
}

fn to_placement(p: GridPlace) -> GridPlacement {
    match p {
        GridPlace::Auto => auto(),
        GridPlace::Line(i) => line(i),
        GridPlace::Span(n) => span(n),
    }
}

fn to_track(t: Track) -> TrackSizingFunction {
    match t {
        Track::Px(v) => length(v),
        Track::Fr(f) => fr(f),
        Track::Auto => auto(),
        Track::MinMax(lo, hi) => minmax(
            // A flex minimum is invalid; fall back to `auto` (min-content).
            match lo {
                TrackSide::Px(v) => length(v),
                TrackSide::Fr(_) | TrackSide::Auto => auto(),
            },
            match hi {
                TrackSide::Px(v) => length(v),
                TrackSide::Fr(f) => fr(f),
                TrackSide::Auto => auto(),
            },
        ),
    }
}

/// Like [`to_track`] but for `grid-auto-rows`/`-columns`, whose tracks can't hold
/// a `repeat(…)` and so use taffy's non-repeated track type.
fn to_auto_track(t: Track) -> taffy::NonRepeatedTrackSizingFunction {
    match t {
        Track::Px(v) => length(v),
        Track::Fr(f) => fr(f),
        Track::Auto => auto(),
        Track::MinMax(lo, hi) => minmax(
            match lo {
                TrackSide::Px(v) => length(v),
                TrackSide::Fr(_) | TrackSide::Auto => auto(),
            },
            match hi {
                TrackSide::Px(v) => length(v),
                TrackSide::Fr(f) => fr(f),
                TrackSide::Auto => auto(),
            },
        ),
    }
}

/// `vp` is the viewport `(width, height)` in physical pixels, for `vw`/`vh`.
fn to_taffy(style: &Style, vp: (f32, f32)) -> taffy::Style {
    taffy::Style {
        display: match style.display {
            // Inline is a normal (block) box; the hug comes from width:auto plus
            // not stretching (taffy has no true inline flow).
            Display::Block | Display::Inline => taffy::Display::Block,
            Display::Flex => taffy::Display::Flex,
            Display::Grid => taffy::Display::Grid,
            Display::None => taffy::Display::None,
        },
        grid_template_columns: style.grid_columns.iter().copied().map(to_track).collect(),
        grid_template_rows: style.grid_rows.iter().copied().map(to_track).collect(),
        grid_column: Line {
            start: to_placement(style.grid_column.0),
            end: to_placement(style.grid_column.1),
        },
        grid_row: Line {
            start: to_placement(style.grid_row.0),
            end: to_placement(style.grid_row.1),
        },
        grid_auto_flow: match style.grid_auto_flow {
            GridFlow::Row => taffy::GridAutoFlow::Row,
            GridFlow::Column => taffy::GridAutoFlow::Column,
            GridFlow::RowDense => taffy::GridAutoFlow::RowDense,
            GridFlow::ColumnDense => taffy::GridAutoFlow::ColumnDense,
        },
        grid_auto_rows: style.grid_auto_rows.iter().copied().map(to_auto_track).collect(),
        grid_auto_columns: style.grid_auto_columns.iter().copied().map(to_auto_track).collect(),
        flex_direction: match style.axis {
            Axis::Column => FlexDirection::Column,
            Axis::Row => FlexDirection::Row,
        },
        justify_content: style.justify.map(|j| match j {
            Justify::Start => JustifyContent::FlexStart,
            Justify::Center => JustifyContent::Center,
            Justify::End => JustifyContent::FlexEnd,
            Justify::SpaceBetween => JustifyContent::SpaceBetween,
            Justify::SpaceAround => JustifyContent::SpaceAround,
        }),
        // Default flex cross-alignment is flex-start (hug), not taffy's stretch,
        // so children keep their own width unless the author asks to stretch.
        align_items: style
            .align
            .map(to_align_items)
            .or(if style.display == Display::Flex {
                Some(AlignItems::FlexStart)
            } else {
                None
            }),
        align_self: style.align_self.map(to_align_items),
        justify_self: style.justify_self.map(to_align_items),
        justify_items: style.justify_items.map(to_align_items),
        align_content: style.align_content.map(to_align_content),
        position: match style.position {
            Position::Relative => taffy::Position::Relative,
            Position::Absolute => taffy::Position::Absolute,
        },
        inset: Rect {
            left: to_inset(style.inset[3], vp),
            right: to_inset(style.inset[1], vp),
            top: to_inset(style.inset[0], vp),
            bottom: to_inset(style.inset[2], vp),
        },
        aspect_ratio: style.aspect_ratio,
        // taffy needs to know the box scrolls: it then sizes the box from its own
        // width/height (not its content) and reports `content_size`, which is how
        // far we can scroll.
        overflow: match style.overflow {
            Overflow::Scroll => Point {
                x: taffy::Overflow::Scroll,
                y: taffy::Overflow::Scroll,
            },
            _ => Point {
                x: taffy::Overflow::Visible,
                y: taffy::Overflow::Visible,
            },
        },
        flex_grow: style.grow,
        flex_shrink: style.shrink,
        flex_basis: style.basis.map(|l| to_dim(l, vp)).unwrap_or(auto()),
        flex_wrap: if style.wrap {
            FlexWrap::Wrap
        } else {
            FlexWrap::NoWrap
        },
        size: Size {
            // `flex-wrap` + a *percentage* width + a `max-width` trips a taffy
            // bug (still present in 0.12): it measures the container's content
            // at the full percentage width, ignoring the cap, so it sees one
            // row and sizes the cross-axis for one row, then clamps the width
            // to `max-width`, wraps to two rows, and never revisits the height.
            // The wrapped rows then paint *under* the following sibling. Both a
            // definite width and `auto` measure correctly, so for this exact
            // combination we drop the percentage to `auto` (fit-content, capped
            // by the same `max-width`), which fills available width up to the
            // cap for any content that overflows it, i.e. the wrap case.
            width: match style.width {
                Some(Len::Pct(_)) if style.wrap && style.max_width.is_some() => auto(),
                Some(l) => to_dim(l, vp),
                None => auto(),
            },
            height: style.height.map(|l| to_dim(l, vp)).unwrap_or(auto()),
        },
        min_size: Size {
            width: style.min_width.map(|l| to_dim(l, vp)).unwrap_or(auto()),
            height: style.min_height.map(|l| to_dim(l, vp)).unwrap_or(auto()),
        },
        max_size: Size {
            // A box with no width hugs its content. Hug means CSS `fit-content`
            //, min(max-content, available), so clamp it to the parent's inner
            // width. Without this, taffy hands a hugging box its full max-content
            // size and it bursts out of a narrower parent. An explicit width or
            // max-width is the author's call and is left alone.
            width: match (style.max_width, style.width) {
                (Some(l), _) => to_dim(l, vp),
                // `flex-shrink: 0` says "keep my size", don't clamp behind the
                // author's back; let it overflow and let the parent clip it.
                // `1.0_f32` spelled out: an unsuffixed float literal here makes
                // rustc fall back to f32 through a trait bound it warns about,
                // and that fallback is due to become a hard error. Only newer
                // toolchains than the one used on Windows report it, so it
                // surfaced from CI rather than locally.
                (None, None) if style.shrink != 0.0 => percent(1.0_f32),
                (None, _) => auto(),
            },
            height: style.max_height.map(|l| to_dim(l, vp)).unwrap_or(auto()),
        },
        padding: Rect {
            left: length(style.padding.left),
            right: length(style.padding.right),
            top: length(style.padding.top),
            bottom: length(style.padding.bottom),
        },
        margin: Rect {
            left: length(style.margin.left),
            right: length(style.margin.right),
            top: length(style.margin.top),
            bottom: length(style.margin.bottom),
        },
        border: Rect {
            left: length(style.border.left),
            right: length(style.border.right),
            top: length(style.border.top),
            bottom: length(style.border.bottom),
        },
        // taffy's gap is (column, row): width is the inline gap, height the block
        // gap. `column-gap`/`row-gap` override the `gap` shorthand per axis.
        gap: Size {
            width: length(style.column_gap.unwrap_or(style.gap)),
            height: length(style.row_gap.unwrap_or(style.gap)),
        },
        ..Default::default()
    }
}

fn to_align_items(a: Align) -> AlignItems {
    match a {
        Align::Start => AlignItems::FlexStart,
        Align::Center => AlignItems::Center,
        Align::End => AlignItems::FlexEnd,
        Align::Stretch => AlignItems::Stretch,
    }
}

fn to_align_content(j: Justify) -> AlignContent {
    match j {
        Justify::Start => AlignContent::FlexStart,
        Justify::Center => AlignContent::Center,
        Justify::End => AlignContent::FlexEnd,
        Justify::SpaceBetween => AlignContent::SpaceBetween,
        Justify::SpaceAround => AlignContent::SpaceAround,
    }
}

fn to_inset(l: Option<Len>, vp: (f32, f32)) -> LengthPercentageAuto {
    match l {
        None => auto(),
        Some(Len::Px(v)) => length(v),
        Some(Len::Pct(p)) => percent(p),
        Some(Len::Vw(v)) => length(vp.0 * v / 100.0),
        Some(Len::Vh(v)) => length(vp.1 * v / 100.0),
    }
}

/// A laid-out `<input>`: its model plus what kind it is. Becomes either a
/// `FocusRegion` (text/textarea) or a `SelectRegion` (select) in `collect`.
struct Bound {
    id: NodeId,
    model: String,
    /// The enclosing `r-for` row's key, the other half of an input's identity.
    row: Option<String>,
    multiline: bool,
    options: Option<Vec<String>>,
}

/// The widest a box can ever be, given its own CSS and everything above it.
///
/// `parent` is the parent's *inner* width bound, `None` when nothing above has
/// pinned one down. A `%` resolves against it; `vw`/`vh` against the viewport.
/// `min-width` wins over `max-width`, as in CSS.
fn width_cap(style: &Style, parent: Option<f32>, vp: (f32, f32)) -> Option<f32> {
    let resolve = |l: Len| match l {
        Len::Px(px) => Some(px),
        Len::Pct(p) => parent.map(|b| b * p),
        Len::Vw(v) => Some(vp.0 * v / 100.0),
        Len::Vh(v) => Some(vp.1 * v / 100.0),
    };
    let capped = match (style.width.and_then(resolve), style.max_width.and_then(resolve)) {
        (Some(w), Some(m)) => Some(w.min(m)),
        (Some(w), None) => Some(w),
        (None, Some(m)) => Some(parent.map_or(m, |p| p.min(m))),
        (None, None) => parent,
    };
    match style.min_width.and_then(resolve) {
        Some(min) => Some(capped.map_or(min, |c| c.max(min))),
        None => capped,
    }
}

/// The cap to hand this box's children: its own, less what its padding and
/// border take out of it.
fn inner_cap(style: &Style, own: Option<f32>) -> Option<f32> {
    own.map(|w| {
        let horizontal = style.padding.left + style.padding.right + style.border.left + style.border.right;
        (w - horizontal).max(0.0)
    })
}

#[allow(clippy::too_many_arguments)]
fn build(
    tree: &mut TaffyTree<TextContent>,
    node: &Node,
    paint: &mut Vec<(NodeId, PaintKind)>,
    handlers: &mut Vec<(NodeId, String, Cursor, Option<String>)>,
    models: &mut Vec<Bound>,
    focus_labels: &mut Vec<(NodeId, String, Option<String>)>,
    hidden: &mut Vec<NodeId>,
    opacities: &mut Vec<(NodeId, f32)>,
    scrolls: &mut Vec<NodeId>,
    transforms: &mut Vec<(NodeId, Transform)>,
    states: &mut Vec<(NodeId, Vec<usize>)>,
    access: &mut Vec<(NodeId, Access, Option<String>)>,
    vp: (f32, f32),
    // `cap` is the widest this node can end up, from the constraint chain above
    // it; `caps` is where each text leaf's own cap is left for the measure hook.
    cap: Option<f32>,
    caps: &mut HashMap<NodeId, f32>,
    // The `r-key` of the row this node is inside, inherited by everything under
    // it. A keyed node starts a new row; nothing else changes it.
    row: Option<&str>,
) -> NodeId {
    let own_cap = width_cap(&node.style, cap, vp);
    let child_cap = inner_cap(&node.style, own_cap);
    let row = node.key.as_deref().or(row);
    let id = if let Some(tc) = &node.text {
        // Text leaves carry their content as taffy context so the measure hook
        // can shape them.
        let id = tree
            .new_leaf_with_context(to_taffy(&node.style, vp), tc.clone())
            .expect("taffy text leaf");
        // A text node is a box too: its background and border paint under the
        // glyphs. (collect() walks every paint entry for a node, in order.)
        paint.push((
            id,
            PaintKind::Box {
                bg: node.style.background.clone(),
                radius: node.style.radius,
                border_width: node.style.border.top,
                border_color: node.style.border_color,
                clip: node.style.overflow != Overflow::Visible,
                shadow: node.style.box_shadow,
            },
        ));
        paint.push((id, PaintKind::Text(tc.clone())));
        // The text wraps inside this box, so its own padding and border come
        // out of the width available to the glyphs.
        if let Some(c) = child_cap {
            caps.insert(id, c);
        }
        id
    } else if let Some(color) = node.tick {
        let id = tree.new_leaf(to_taffy(&node.style, vp)).expect("taffy tick");
        paint.push((id, PaintKind::Tick(color)));
        id
    } else if let Some(ic) = &node.image {
        // An image with no CSS size falls back to its intrinsic pixel size, the
        // way a browser sizes an <img>.
        let mut ts = to_taffy(&node.style, vp);
        if node.style.width.is_none() {
            ts.size.width = length(ic.intrinsic.0);
        }
        if node.style.height.is_none() {
            ts.size.height = length(ic.intrinsic.1);
        }
        let id = tree.new_leaf(ts).expect("taffy image leaf");
        paint.push((
            id,
            PaintKind::Box {
                bg: node.style.background.clone(),
                radius: node.style.radius,
                border_width: node.style.border.top,
                border_color: node.style.border_color,
                clip: node.style.overflow != Overflow::Visible,
                shadow: node.style.box_shadow,
            },
        ));
        paint.push((id, PaintKind::Image(ic.clone())));
        id
    } else {
        let children: Vec<NodeId> = node
            .children
            .iter()
            .map(|c| build(tree, c, paint, handlers, models, focus_labels, hidden, opacities, scrolls, transforms, states, access, vp, child_cap, caps, row))
            .collect();
        let id = if children.is_empty() {
            tree.new_leaf(to_taffy(&node.style, vp)).expect("taffy leaf")
        } else {
            tree.new_with_children(to_taffy(&node.style, vp), &children)
                .expect("taffy node")
        };
        paint.push((
            id,
            PaintKind::Box {
                bg: node.style.background.clone(),
                radius: node.style.radius,
                // Uniform border for rendering (top width is representative).
                border_width: node.style.border.top,
                border_color: node.style.border_color,
                clip: node.style.overflow != Overflow::Visible,
                shadow: node.style.box_shadow,
            },
        ));
        id
    };
    if let Some(handler) = &node.on_tap {
        handlers.push((id, handler.clone(), node.style.cursor, node.instance.clone()));
    }
    if let Some(model) = &node.model {
        models.push(Bound {
            id,
            model: model.clone(),
            row: row.map(str::to_string),
            multiline: node.multiline,
            options: node.options.clone(),
        });
    }
    if let Some(fm) = &node.focus_model {
        focus_labels.push((id, fm.clone(), row.map(str::to_string)));
    }
    if node.hidden {
        hidden.push(id);
    }
    if node.style.opacity < 1.0 {
        opacities.push((id, node.style.opacity.max(0.0)));
    }
    if let Some(tf) = node.style.transform {
        transforms.push((id, tf));
    }
    if node.style.overflow == Overflow::Scroll {
        scrolls.push(id);
    }
    if let Some(path) = &node.state_path {
        states.push((id, path.clone()));
    }
    if node.access.role.is_meaningful() {
        access.push((id, node.access.clone(), node.model.clone()));
    }
    id
}

#[allow(clippy::too_many_arguments)]
fn collect(
    tree: &TaffyTree<TextContent>,
    id: NodeId,
    origin_x: f32,
    origin_y: f32,
    paint: &[(NodeId, PaintKind)],
    handlers: &[(NodeId, String, Cursor, Option<String>)],
    models: &[Bound],
    focus_labels: &[(NodeId, String, Option<String>)],
    hidden: &[NodeId],
    opacities: &[(NodeId, f32)],
    scrolls: &[NodeId],
    transforms: &[(NodeId, Transform)],
    states: &[(NodeId, Vec<usize>)],
    access: &[(NodeId, Access, Option<String>)],
    offsets: &[Offset],
    vp: (f32, f32),
    // The nearest scroller above this node, so a focus ring can be clipped to
    // the box that clips everything else in it.
    inside_scroll: Option<usize>,
    out: &mut Layout,
) {
    let layout = tree.layout(id).expect("layout");
    let x = origin_x + layout.location.x;
    let y = origin_y + layout.location.y;

    // r-show=false: the node kept its layout slot but paints nothing (nor its
    // subtree, nor its hit regions).
    if hidden.contains(&id) {
        return;
    }

    // opacity fades this node and everything under it, so the layer opens
    // before the node paints its own background.
    let alpha = opacities
        .iter()
        .find(|(nid, _)| *nid == id)
        .map(|(_, a)| *a)
        .unwrap_or(1.0);
    if alpha < 1.0 {
        out.paints.push(Paint::PushOpacity {
            alpha,
            width: vp.0,
            height: vp.1,
        });
    }

    // `transform` wraps the box and its subtree. The parsed matrix is in local
    // coords; bake in the origin (CSS default: the box centre) so it applies to
    // absolute coordinates directly.
    let transform = transforms.iter().find(|(nid, _)| *nid == id).map(|(_, m)| *m);
    if let Some(m) = transform {
        let (ox, oy) = (x + layout.size.width / 2.0, y + layout.size.height / 2.0);
        out.paints.push(Paint::PushTransform(centre_transform(m, ox, oy)));
    }

    let mut clip = false;
    let mut clip_radius = [0.0; 4];
    // A node can emit more than one paint (a text node paints its box, then its
    // glyphs), so walk every entry it owns, in order.
    for (_, kind) in paint.iter().filter(|(nid, _)| *nid == id) {
        match kind {
            PaintKind::Box {
                bg,
                radius,
                border_width,
                border_color,
                clip: c,
                shadow,
            } => {
                clip = *c;
                clip_radius = *radius;
                // The shadow goes down first, so the box's own fill sits on top.
                // Outer shadows only for now; inset is parsed but not drawn.
                if let Some(sh) = shadow.filter(|s| !s.inset) {
                    out.paints.push(Paint::Shadow {
                        x: x + sh.dx - sh.spread,
                        y: y + sh.dy - sh.spread,
                        width: layout.size.width + 2.0 * sh.spread,
                        height: layout.size.height + 2.0 * sh.spread,
                        // vello's blurred rect takes one radius; use the largest
                        // corner as a stand-in (per-corner blur isn't supported).
                        radius: radius.iter().copied().fold(0.0, f32::max),
                        blur: sh.blur,
                        color: sh.color,
                    });
                }
                let has_border = *border_width > 0.0 && border_color.is_some();
                if bg.is_some() || has_border {
                    out.paints.push(Paint::Rect(PaintRect {
                        x,
                        y,
                        width: layout.size.width,
                        height: layout.size.height,
                        background: bg.clone(),
                        radius: *radius,
                        border_width: *border_width,
                        border_color: *border_color,
                    }));
                }
            }
            // Glyphs go in the *content* box, inside this node's own padding and
            // border. Painting them at the border box put a padded label flush
            // against the edge of its own background: the box grew, the words
            // did not move. The size matters as much as the origin, since it is
            // what the run is aligned and wrapped within.
            PaintKind::Text(tc) => {
                let (cx, cy, cw, ch) = content_box(layout);
                out.paints.push(Paint::Text(PaintText {
                    x: x + cx,
                    y: y + cy,
                    width: cw,
                    height: ch,
                    content: tc.clone(),
                }))
            }
            PaintKind::Tick(color) => out.paints.push(Paint::Tick(PaintTick {
                x,
                y,
                width: layout.size.width,
                height: layout.size.height,
                color: *color,
            })),
            PaintKind::Image(ic) => out.paints.push(Paint::Image(PaintImage {
                x,
                y,
                width: layout.size.width,
                height: layout.size.height,
                content: ic.clone(),
            })),
        }
    }

    // A `for=` label targeting a text input: a focus region at the label's box,
    // carrying the *target's* model, so tapping the label focuses that input.
    if let Some((_, model, row)) = focus_labels.iter().find(|(nid, ..)| *nid == id) {
        out.focuses.push(FocusRegion {
            x,
            y,
            width: layout.size.width,
            height: layout.size.height,
            model: model.clone(),
            row: row.clone(),
            text: None,
            multiline: false,
            scroll_id: None,
        });
    }

    // Assistive technology needs the same geometry the pointer uses, so this rides
    // the same walk. `hidden` nodes returned above, so an `r-show="false"` element
    // is absent from the a11y tree too, not merely invisible.
    if let Some((_, node_access, model)) = access.iter().find(|(nid, ..)| *nid == id) {
        out.access.push(AccessNode {
            x,
            y,
            width: layout.size.width,
            height: layout.size.height,
            access: node_access.clone(),
            model: model.clone(),
        });
    }

    // Emitted for any box a `:hover`/`:active` rule could style, tappable or not,
    // unlike `cursor`, pointer-state styling is not limited to `@tap` boxes.
    if let Some((_, path)) = states.iter().find(|(nid, _)| *nid == id) {
        out.states.push(StateRegion {
            x,
            y,
            width: layout.size.width,
            height: layout.size.height,
            path: path.clone(),
        });
    }

    if let Some((_, handler, cursor, instance)) = handlers.iter().find(|(nid, ..)| *nid == id) {
        out.hits.push(HitRegion {
            x,
            y,
            width: layout.size.width,
            height: layout.size.height,
            on_tap: handler.clone(),
            cursor: *cursor,
            instance: instance.clone(),
        });
    }

    let (fw, fh) = (layout.size.width, layout.size.height);
    if let Some(bound) = models.iter().find(|b| b.id == id) {
        if let Some(options) = &bound.options {
            // A select: no caret, just a tappable box that opens a dropdown.
            out.selects.push(SelectRegion {
                x,
                y,
                width: fw,
                height: fh,
                model: bound.model.clone(),
                row: bound.row.clone(),
                options: options.clone(),
            });
            out.focusables.push(FocusItem {
                x,
                y,
                width: fw,
                height: fh,
                kind: FocusKind::Select {
                    model: bound.model.clone(),
                    row: bound.row.clone(),
                    options: options.clone(),
                },
                scroll: inside_scroll,
            });
        } else {
            // A text/textarea input: its value is rendered by its single text
            // child; find that child's box so a tap resolves to a caret index.
            let text = tree
                .children(id)
                .ok()
                .and_then(|kids| kids.first().copied())
                .and_then(|kid| {
                    let child = tree.layout(kid).ok()?;
                    let content = paint.iter().find_map(|(nid, k)| match k {
                        PaintKind::Text(tc) if *nid == kid => Some(tc.clone()),
                        _ => None,
                    })?;
                    // The same content box the glyphs are painted in, or the
                    // caret would sit at the border box while the text it is
                    // supposed to be inside sits within the padding.
                    let (cx, cy, cw, ch) = content_box(child);
                    Some(PaintText {
                        x: x + child.location.x + cx,
                        y: y + child.location.y + cy,
                        width: cw,
                        height: ch,
                        content,
                    })
                });
            out.focuses.push(FocusRegion {
                x,
                y,
                width: fw,
                height: fh,
                model: bound.model.clone(),
                row: bound.row.clone(),
                text: text.clone(),
                multiline: bound.multiline,
                // The scroll block below assigns ids as `out.scrolls.len()`, so if
                // this node scrolls it will get the current length as its id.
                scroll_id: scrolls.contains(&id).then(|| out.scrolls.len()),
            });
            out.focusables.push(FocusItem {
                x,
                y,
                width: fw,
                height: fh,
                kind: FocusKind::Text {
                    model: bound.model.clone(),
                    row: bound.row.clone(),
                    multiline: bound.multiline,
                    text,
                },
                scroll: inside_scroll,
            });
        }
    } else if let Some((_, handler, _, instance)) = handlers.iter().find(|(nid, ..)| *nid == id) {
        // A button / checkbox / radio (anything with a `@tap` handler) is
        // keyboard-reachable: Space or Enter runs the same handler as a tap.
        out.focusables.push(FocusItem {
            x,
            y,
            width: fw,
            height: fh,
            kind: FocusKind::Activate { on_tap: handler.clone(), instance: instance.clone() },
            scroll: inside_scroll,
        });
    }

    // overflow: clip/scroll, bound the subtree to this box (following its corners).
    if clip {
        out.paints.push(Paint::PushClip {
            x,
            y,
            width: layout.size.width,
            height: layout.size.height,
            radius: clip_radius,
        });
    }

    // A scroller shifts its children by the current offset and registers itself
    // so the wheel, the scrollbars and the keyboard can find it.
    let mut shift = Offset::default();
    // What the children are clipped by: this box if it scrolls, otherwise
    // whatever was clipping us.
    let mut child_scroll = inside_scroll;
    if scrolls.contains(&id) {
        let sid = out.scrolls.len();
        child_scroll = Some(sid);
        let max = Offset {
            x: (layout.content_size.width - layout.size.width).max(0.0),
            y: (layout.content_size.height - layout.size.height).max(0.0),
        };
        shift = offsets.get(sid).copied().unwrap_or_default().clamp_to(max);
        out.scrolls.push(ScrollRegion {
            id: sid,
            x,
            y,
            width: layout.size.width,
            height: layout.size.height,
            content_width: layout.content_size.width,
            content_height: layout.content_size.height,
            max,
        });
    }

    for child in tree.children(id).expect("children") {
        collect(
            tree,
            child,
            x - shift.x,
            y - shift.y,
            paint,
            handlers,
            models,
            focus_labels,
            hidden,
            opacities,
            scrolls,
            transforms,
            states,
            access,
            offsets,
            vp,
            child_scroll,
            out,
        );
    }
    if clip {
        out.paints.push(Paint::PopClip);
    }
    if transform.is_some() {
        out.paints.push(Paint::PopTransform);
    }
    if alpha < 1.0 {
        out.paints.push(Paint::PopOpacity);
    }
}

/// Bake a transform-origin at `(ox, oy)` into a local transform matrix `m`, so
/// the result maps absolute coordinates: `p ↦ M·(p − o) + o`.
fn centre_transform(m: Transform, ox: f32, oy: f32) -> Transform {
    let [a, b, c, d, e, f] = m;
    [
        a,
        b,
        c,
        d,
        e + ox - a * ox - c * oy,
        f + oy - b * ox - d * oy,
    ]
}

/// Lay out `root` into an `avail_w` x `avail_h` viewport, returning paint items
/// and hit regions. Text leaves are sized via `measure`.
pub fn layout(root: &Node, avail_w: f32, avail_h: f32, measure: &mut Measure) -> Layout {
    layout_scrolled(root, avail_w, avail_h, &[], measure)
}

/// Lay out with the shell's current scroll offsets (one per scrollable box, in
/// tree order). A missing entry is 0.
pub fn layout_scrolled(
    root: &Node,
    avail_w: f32,
    avail_h: f32,
    offsets: &[Offset],
    measure: &mut Measure,
) -> Layout {
    let mut tree: TaffyTree<TextContent> = TaffyTree::new();
    // Taffy rounds boxes to whole pixels by default, which can shave a fraction
    // off a text box and make paint re-wrap the last word into a line the box
    // has no height for. Keep the exact sizes measure asked for.
    tree.disable_rounding();
    let mut paint = Vec::new();
    let mut handlers = Vec::new();
    let mut models = Vec::new();
    let mut focus_labels = Vec::new();
    let mut hidden = Vec::new();
    let mut opacities = Vec::new();
    let mut scrolls = Vec::new();
    let mut transforms = Vec::new();
    let mut states = Vec::new();
    let mut access = Vec::new();
    let vp = (avail_w, avail_h);
    let mut caps: HashMap<NodeId, f32> = HashMap::new();
    let root_id = build(
        &mut tree,
        root,
        &mut paint,
        &mut handlers,
        &mut models,
        &mut focus_labels,
        &mut hidden,
        &mut opacities,
        &mut scrolls,
        &mut transforms,
        &mut states,
        &mut access,
        vp,
        // The root is forced to the viewport below, so that is the widest
        // anything can be.
        Some(avail_w),
        &mut caps,
        None, // the root is not inside any row
    );

    // Force the root to fill the viewport so a `screen` always covers the window.
    let mut root_style = to_taffy(&root.style, vp);
    root_style.size = Size {
        width: length(avail_w),
        height: length(avail_h),
    };
    tree.set_style(root_id, root_style).expect("set root style");

    tree.compute_layout_with_measure(
        root_id,
        Size {
            width: AvailableSpace::Definite(avail_w),
            height: AvailableSpace::Definite(avail_h),
        },
        |known, available, id, ctx, _style| {
            if let (Some(w), Some(h)) = (known.width, known.height) {
                return Size { width: w, height: h };
            }
            match ctx {
                Some(tc) => {
                    // Wrap to a definite width; otherwise (content sizing) let
                    // the text take its natural single-line width.
                    let max = known.width.or(match available.width {
                        AvailableSpace::Definite(w) => Some(w),
                        // Min-content is the narrowest the box can be without
                        // its content spilling, which for text is the longest
                        // unbreakable word. Wrapping at zero asks exactly that.
                        // Answering it with the single-line width (which is
                        // what "no constraint" means here) told taffy the box
                        // could never be narrower than one long line.
                        AvailableSpace::MinContent => Some(0.0),
                        AvailableSpace::MaxContent => None,
                    });
                    // Never measure at a width this box can never have. Taffy
                    // sizes a capped box from its *un*capped content, clamps
                    // the width afterwards, and does not revisit the height, so
                    // a `max-width` card was measured as one long line and
                    // drawn as three. Wrapping at the cap up front is what
                    // makes the measured height the height that gets drawn.
                    let cap = caps.get(&id).copied();
                    let max = match (max, cap) {
                        (Some(m), Some(c)) => Some(m.min(c)),
                        (None, Some(c)) => Some(c),
                        (m, None) => m,
                    };
                    let (w, h) = measure(tc, max);
                    Size {
                        width: known.width.unwrap_or(w),
                        height: known.height.unwrap_or(h),
                    }
                }
                None => Size {
                    width: 0.0,
                    height: 0.0,
                },
            }
        },
    )
    .expect("compute layout");

    let mut out = Layout::default();
    collect(
        &tree, root_id, 0.0, 0.0, &paint, &handlers, &models, &focus_labels, &hidden, &opacities,
        &scrolls, &transforms, &states, &access, offsets, vp, None, &mut out,
    );
    out
}