inkferro-core 0.1.0

Layout, text measurement, ANSI render, and frame-diff engine for inkferro — a Rust-backed, byte-for-byte drop-in for the ink terminal UI library.
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
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
//! `TaffyEngine` — the Taffy 0.10 backend for `LayoutEngine`.
//!
//! See `mod.rs` for measure-seam and rounding rationale.
//!
//! ## Id mapping
//! The dom arena owns u32 ids allocated by the JS reconciler.  `TaffyEngine`
//! maintains a `HashMap<u32, taffy::NodeId>` (dom id → taffy id).  Each taffy
//! node carries the corresponding dom id as its `NodeContext` (`TaffyTree<u32>`),
//! so the measure closure receives it directly as a parameter — no reverse map
//! needed, no per-calculate clone.

use std::collections::HashMap;

use taffy::{
    NodeId, TaffyTree, TraversePartialTree,
    geometry::{Point, Rect as TaffyRect, Size},
    style::{
        AlignContent, AlignItems, AlignSelf, AvailableSpace, Dimension, Display as TaffyDisplay,
        FlexDirection, FlexWrap as TaffyFlexWrap, JustifyContent, LengthPercentage,
        LengthPercentageAuto, Overflow as TaffyOverflow, Position as TaffyPosition,
        Style as TaffyStyle,
    },
};

use crate::dom::{
    Align, ContentAlign, Dim, Display, FlexDir, FlexWrap, Lp, Overflow, Position, Style,
};

use super::engine::{LayoutEngine, MeasureFn, Rect};

// ─── Style mapping ───────────────────────────────────────────────────────────

/// Convert an inkferro `dom::Style` to a `taffy::Style`.
///
/// Mirrors the `apply*` functions in ink's `styles.ts`, reading every
/// group in the same order (styles.ts:415–777).  Divergences from yoga
/// are noted inline.
///
/// ### Percentage scale
/// ink/yoga use 0–100 (e.g. `parseInt("50%", 10)` → 50).  Taffy wants
/// 0.0–1.0.  All `Dim::Percent(p)` and `Lp::Percent(p)` values are
/// divided by 100 exactly once in this function.
pub fn style_to_taffy(s: &Style) -> TaffyStyle {
    TaffyStyle {
        // ── position (styles.ts:415–442) ──────────────────────────────────
        // Divergence: Yoga has POSITION_TYPE_STATIC; Taffy only has
        // Relative / Absolute.  `static` maps to Relative. The difference
        // is visible only when inset is set on a static node: yoga ignores
        // top/right/bottom/left for static (styles.ts:21), this mapping
        // honors them. Accepted: ink documents static as ignoring offsets
        // and Box never defaults to static.
        position: map_position(s.position),

        // ── inset / top/right/bottom/left (styles.ts:430–442) ─────────────
        inset: TaffyRect {
            top: map_dim_lpa(s.top.as_ref()),
            right: map_dim_lpa(s.right.as_ref()),
            bottom: map_dim_lpa(s.bottom.as_ref()),
            left: map_dim_lpa(s.left.as_ref()),
        },

        // ── margin (styles.ts:444–472) ────────────────────────────────────
        // Cascade: per-edge > axis shorthand > all shorthand (later yoga call
        // overrides earlier, so per-edge wins — mirrored with Option::or).
        margin: TaffyRect {
            top: map_lpa(
                s.margin_top
                    .as_ref()
                    .or(s.margin_y.as_ref())
                    .or(s.margin.as_ref()),
            ),
            bottom: map_lpa(
                s.margin_bottom
                    .as_ref()
                    .or(s.margin_y.as_ref())
                    .or(s.margin.as_ref()),
            ),
            left: map_lpa(
                s.margin_left
                    .as_ref()
                    .or(s.margin_x.as_ref())
                    .or(s.margin.as_ref()),
            ),
            right: map_lpa(
                s.margin_right
                    .as_ref()
                    .or(s.margin_x.as_ref())
                    .or(s.margin.as_ref()),
            ),
        },

        // ── padding (styles.ts:474–502) ───────────────────────────────────
        padding: TaffyRect {
            top: map_lp(
                s.padding_top
                    .as_ref()
                    .or(s.padding_y.as_ref())
                    .or(s.padding.as_ref()),
            ),
            bottom: map_lp(
                s.padding_bottom
                    .as_ref()
                    .or(s.padding_y.as_ref())
                    .or(s.padding.as_ref()),
            ),
            left: map_lp(
                s.padding_left
                    .as_ref()
                    .or(s.padding_x.as_ref())
                    .or(s.padding.as_ref()),
            ),
            right: map_lp(
                s.padding_right
                    .as_ref()
                    .or(s.padding_x.as_ref())
                    .or(s.padding.as_ref()),
            ),
        },

        // ── border (styles.ts:729–763) ────────────────────────────────────
        // borderWidth = 1 iff borderStyle is set (styles.ts:745).
        // Each edge = 0 if that edge is explicitly `false` (styles.ts:748-762).
        // Uses the shared Style::border_edges() helper — single source of truth
        // shared with the render clip inset in walk.rs.
        border: {
            let [top, right, bottom, left] = s.border_edges();
            TaffyRect {
                top: LengthPercentage::length(top as f32),
                right: LengthPercentage::length(right as f32),
                bottom: LengthPercentage::length(bottom as f32),
                left: LengthPercentage::length(left as f32),
            }
        },

        // ── flex (styles.ts:504–661) ──────────────────────────────────────
        // Box.tsx defaults (flexDirection:row, flexWrap:nowrap, flexGrow:0,
        // flexShrink:1) equal taffy's defaults, so None → taffy default is
        // correct with no special-casing needed.
        flex_direction: map_flex_dir(s.flex_direction),
        flex_wrap: map_flex_wrap(s.flex_wrap),
        flex_grow: s.flex_grow.unwrap_or(0.0),
        flex_shrink: s.flex_shrink.unwrap_or(1.0),
        flex_basis: map_dim(s.flex_basis.as_ref()),
        align_items: s.align_items.map(map_align_items),
        // alignSelf: taffy has no Auto variant — None encodes auto.
        align_self: s.align_self.map(map_align_self),
        // alignContent: Yoga's node default is flex-start (verified empirically
        // against ink's yoga-layout: getAlignContent() == ALIGN_FLEX_START),
        // while Taffy's None resolves to stretch. ink never sets alignContent
        // unless the prop is given (styles.ts), so None must map to FlexStart
        // or wrapped lines stretch/spread across the container cross axis.
        align_content: Some(
            s.align_content
                .map(map_content_align_content)
                .unwrap_or(AlignContent::FlexStart),
        ),
        justify_content: s.justify_content.map(map_content_align_justify),

        // ── dimensions (styles.ts:663–719) ────────────────────────────────
        size: Size {
            width: map_dim(s.width.as_ref()),
            height: map_dim(s.height.as_ref()),
        },
        // Divergence (width only): yoga ignores percent minWidth/maxWidth
        // (styles.ts:220/231, yoga#872); Taffy honors them. minHeight/
        // maxHeight percent is honored by BOTH — no divergence there
        // (styles.ts:225/236).  We map faithfully for all four fields.
        min_size: Size {
            width: map_dim(s.min_width.as_ref()),
            height: map_dim(s.min_height.as_ref()),
        },
        max_size: Size {
            width: map_dim(s.max_width.as_ref()),
            height: map_dim(s.max_height.as_ref()),
        },
        // aspectRatio: faithful f32 passthrough. Yoga-vs-Taffy resolution
        // order against size constraints is unverified; styles.ts:243
        // advises use with ≥1 size constraint.
        aspect_ratio: s.aspect_ratio,

        // ── display (styles.ts:721–727) ───────────────────────────────────
        display: map_display(s.display),

        // ── gap (styles.ts:765–777) ───────────────────────────────────────
        // Cascade: per-axis > all shorthand (column_gap/row_gap override gap).
        gap: Size {
            width: map_gap(s.column_gap.or(s.gap)),
            height: map_gap(s.row_gap.or(s.gap)),
        },

        // ── overflow (styles.ts; Box.tsx resolves shorthand JS-side) ──────
        overflow: Point {
            x: map_overflow(s.overflow_x),
            y: map_overflow(s.overflow_y),
        },

        // All remaining taffy fields (scrollbar_width, direction, etc.) not
        // present in ink's Styles type — use taffy defaults.
        ..Default::default()
    }
}

// ─── Mapping helpers (flat — ≤2 indent levels inside each fn) ────────────────

fn map_position(p: Option<Position>) -> TaffyPosition {
    match p.unwrap_or(Position::Relative) {
        Position::Absolute => TaffyPosition::Absolute,
        Position::Relative | Position::Static => TaffyPosition::Relative,
    }
}

fn map_dim(d: Option<&Dim>) -> Dimension {
    match d {
        None | Some(Dim::Auto) => Dimension::auto(),
        Some(Dim::Points(v)) => Dimension::length(*v),
        Some(Dim::Percent(p)) => Dimension::percent(p / 100.0),
    }
}

fn map_dim_lpa(d: Option<&Dim>) -> LengthPercentageAuto {
    match d {
        None | Some(Dim::Auto) => LengthPercentageAuto::auto(),
        Some(Dim::Points(v)) => LengthPercentageAuto::length(*v),
        Some(Dim::Percent(p)) => LengthPercentageAuto::percent(p / 100.0),
    }
}

fn map_lp(lp: Option<&Lp>) -> LengthPercentage {
    match lp {
        None => LengthPercentage::length(0.0),
        Some(Lp::Points(v)) => LengthPercentage::length(*v),
        Some(Lp::Percent(p)) => LengthPercentage::percent(p / 100.0),
    }
}

/// Margin edges: `None` → `0` (yoga default for unset margins).
/// Do NOT use `auto()` here — taffy auto-margins distribute free space,
/// producing centering that ink never exhibits on unset margins.
fn map_lpa(lp: Option<&Lp>) -> LengthPercentageAuto {
    match lp {
        // Yoga default for unset margins is 0, not auto.  Taffy auto margins
        // distribute free space (centering effect) — must not use auto for None.
        None => LengthPercentageAuto::length(0.0),
        Some(Lp::Points(v)) => LengthPercentageAuto::length(*v),
        Some(Lp::Percent(p)) => LengthPercentageAuto::percent(p / 100.0),
    }
}

fn map_flex_dir(d: Option<FlexDir>) -> FlexDirection {
    match d.unwrap_or(FlexDir::Row) {
        FlexDir::Row => FlexDirection::Row,
        FlexDir::Column => FlexDirection::Column,
        FlexDir::RowReverse => FlexDirection::RowReverse,
        FlexDir::ColumnReverse => FlexDirection::ColumnReverse,
    }
}

fn map_flex_wrap(w: Option<FlexWrap>) -> TaffyFlexWrap {
    match w.unwrap_or(FlexWrap::NoWrap) {
        FlexWrap::NoWrap => TaffyFlexWrap::NoWrap,
        FlexWrap::Wrap => TaffyFlexWrap::Wrap,
        FlexWrap::WrapReverse => TaffyFlexWrap::WrapReverse,
    }
}

fn map_align_items(a: Align) -> AlignItems {
    match a {
        Align::Stretch => AlignItems::Stretch,
        Align::FlexStart => AlignItems::FlexStart,
        Align::Center => AlignItems::Center,
        Align::FlexEnd => AlignItems::FlexEnd,
        Align::Baseline => AlignItems::Baseline,
    }
}

fn map_align_self(a: Align) -> AlignSelf {
    match a {
        Align::Stretch => AlignSelf::Stretch,
        Align::FlexStart => AlignSelf::FlexStart,
        Align::Center => AlignSelf::Center,
        Align::FlexEnd => AlignSelf::FlexEnd,
        Align::Baseline => AlignSelf::Baseline,
    }
}

fn map_content_align_content(c: ContentAlign) -> AlignContent {
    match c {
        ContentAlign::FlexStart => AlignContent::FlexStart,
        ContentAlign::Center => AlignContent::Center,
        ContentAlign::FlexEnd => AlignContent::FlexEnd,
        ContentAlign::SpaceBetween => AlignContent::SpaceBetween,
        ContentAlign::SpaceAround => AlignContent::SpaceAround,
        ContentAlign::SpaceEvenly => AlignContent::SpaceEvenly,
        ContentAlign::Stretch => AlignContent::Stretch,
    }
}

fn map_content_align_justify(c: ContentAlign) -> JustifyContent {
    match c {
        ContentAlign::FlexStart => JustifyContent::FlexStart,
        ContentAlign::Center => JustifyContent::Center,
        ContentAlign::FlexEnd => JustifyContent::FlexEnd,
        ContentAlign::SpaceBetween => JustifyContent::SpaceBetween,
        ContentAlign::SpaceAround => JustifyContent::SpaceAround,
        ContentAlign::SpaceEvenly => JustifyContent::SpaceEvenly,
        ContentAlign::Stretch => JustifyContent::Stretch,
    }
}

fn map_display(d: Option<Display>) -> TaffyDisplay {
    match d.unwrap_or(Display::Flex) {
        Display::Flex => TaffyDisplay::Flex,
        Display::None => TaffyDisplay::None,
    }
}

fn map_gap(g: Option<f32>) -> LengthPercentage {
    match g {
        None => LengthPercentage::length(0.0),
        Some(v) => LengthPercentage::length(v),
    }
}

fn map_overflow(o: Option<Overflow>) -> TaffyOverflow {
    match o.unwrap_or(Overflow::Visible) {
        Overflow::Visible => TaffyOverflow::Visible,
        Overflow::Hidden => TaffyOverflow::Hidden,
    }
}

// ─── TaffyEngine ─────────────────────────────────────────────────────────────

/// Taffy 0.10 backend.
///
/// Invariant: every dom id in `id_map` has a valid `NodeId` in `tree`.
pub struct TaffyEngine {
    /// The taffy tree (flexbox layout).  Taffy's built-in rounding is DISABLED
    /// at construction (`disable_rounding`); `calculate` runs a Yoga-compatible
    /// pixel-grid post-pass instead (see `round_layout_yoga` / `mod.rs`).
    /// Each node's context is the dom id (`u32`) so the measure closure can
    /// dispatch into `measures` without a secondary reverse map.
    tree: TaffyTree<u32>,

    /// dom id → taffy NodeId.
    id_map: HashMap<u32, NodeId>,

    /// Measure callbacks keyed by dom id.  Populated by `set_measure`; called
    /// by the closure passed to `compute_layout_with_measure`.  A registered
    /// measure marks the node as a Yoga "Text" node for rounding purposes
    /// (`PixelGrid.cpp` `node->getNodeType() == NodeType::Text`).
    measures: HashMap<u32, Box<MeasureFn>>,

    /// Rounded, parent-relative rects keyed by dom id, produced by the
    /// Yoga-compatible post-pass at the end of `calculate`.  `computed` reads
    /// from here; it falls back to the live (unrounded) taffy layout for ids
    /// not present (e.g. a node created but never laid out).
    rounded: HashMap<u32, Rect>,

    /// Rounded, ABSOLUTE (root-relative) rects keyed by dom id — the same
    /// post-pass also accumulates the rounded parent-relative offsets down the
    /// recursion (the renderer paints each node at exactly this sum, and the
    /// jacob314/ink fork's `getBoundingBox` computes the same sum by walking
    /// `getComputedLeft/Top` up the parent chain).  `computed_absolute` reads
    /// from here.  ADDITIVE alongside `rounded`: the parent-relative map and
    /// `computed`'s contract are unchanged.
    rounded_absolute: HashMap<u32, Rect>,
}

impl TaffyEngine {
    /// Create an empty engine.
    pub fn new() -> Self {
        let mut tree = TaffyTree::new();
        // Disable taffy's cumulative round-half-away rounding; we apply Yoga's
        // pixel-grid rounding in `round_layout_yoga` after each `calculate`, so
        // tie-breaks and text-node floor/ceil match ink's yoga 3.2.1 exactly.
        tree.disable_rounding();
        Self {
            tree,
            id_map: HashMap::new(),
            measures: HashMap::new(),
            rounded: HashMap::new(),
            rounded_absolute: HashMap::new(),
        }
    }

    /// Resolve `dom_id` to a taffy `NodeId`.
    fn taffy_id(&self, dom_id: u32) -> Result<NodeId, String> {
        self.id_map
            .get(&dom_id)
            .copied()
            .ok_or_else(|| format!("layout: unknown dom id {dom_id}"))
    }

    /// The node's rounded ABSOLUTE (root-relative) rect — `x`/`y` are the sum
    /// of the rounded parent-relative offsets down the ancestor chain (the
    /// integer cell where the renderer paints the node); `width`/`height` are
    /// identical to [`LayoutEngine::computed`]'s.
    ///
    /// ADDITIVE companion to `computed` (which stays parent-relative —
    /// wire/API covenant): produced by the same `round_node` post-pass, so the
    /// two are coherent per `calculate`.  Returns `None` for unknown, freed,
    /// or never-calculated ids.  A node detached AFTER the last `calculate`
    /// (`remove_child` without `destroy`) serves its last-calculated rect
    /// until the next `calculate` evicts it — the same staleness contract as
    /// `rounded` (see `destroy`'s eviction note).  No live-taffy fallback
    /// like `computed`'s: an absolute position requires the ancestor chain
    /// walked by `calculate`, which a not-yet-calculated node does not have.
    /// The rendered path (build → `calculate` → read) never hits that case.
    pub fn computed_absolute(&self, id: u32) -> Option<Rect> {
        self.rounded_absolute.get(&id).copied()
    }
}

// ─── Yoga-compatible pixel-grid rounding (yoga 3.2.1 PixelGrid.cpp) ───────────
//
// Ink uses yoga-layout 3.2.1 (ink/package.json: "yoga-layout": "~3.2.1").  Yoga
// rounds layout results to the pixel grid *after* the flex solve, in
// `roundLayoutResultsToPixelGrid` (yoga/algorithm/PixelGrid.cpp), using
// `roundValueToPixelGrid` for the actual half-up / floor / ceil decision.  Taffy
// 0.10 rounds differently (cumulative round-half-away in `compute::round_layout`,
// compute/mod.rs:219), which diverges from yoga by ±1 on tie-breaks and on
// text-node sizing.  We disable taffy rounding and port yoga's algorithm here so
// our integer rects match ink cell-for-cell.
//
// `pointScaleFactor` is 1.0 for terminals (one cell == one "point"); we hardcode
// it and drop the `* pointScaleFactor` / `/ pointScaleFactor` no-ops.  All math
// is done in f64 (yoga uses `double` throughout PixelGrid.cpp) and only narrowed
// to integer cells at the very end.

/// Yoga's `inexactEquals(double, double)` — yoga/numeric/Comparison.h:
/// `std::abs(a - b) < 0.0001`.  (Both args are always defined here, so the
/// undefined-handling branch is omitted.)
fn inexact_equals(a: f64, b: f64) -> bool {
    (a - b).abs() < 0.0001
}

/// Port of yoga 3.2.1 `roundValueToPixelGrid` (PixelGrid.cpp), specialized to
/// `pointScaleFactor == 1.0`.
///
/// ```text
/// double scaledValue = value;            // value * 1.0
/// double fractial = fmod(scaledValue, 1.0);
/// if (fractial < 0) ++fractial;          // make fractial in [0,1) even for value<0
/// if      (inexactEquals(fractial, 0.0)) scaledValue -= fractial;        // already whole
/// else if (inexactEquals(fractial, 1.0)) scaledValue += 1.0 - fractial;  // ~whole below
/// else if (forceCeil)  scaledValue += 1.0 - fractial;                    // ceil
/// else if (forceFloor) scaledValue -= fractial;                          // floor
/// else                 scaledValue += (fractial > 0.5 || inexactEquals(fractial, 0.5))
///                                          ? (1.0 - fractial) : -fractial; // round half up
/// return scaledValue;                    // / 1.0
/// ```
fn round_value_to_pixel_grid(value: f64, force_ceil: bool, force_floor: bool) -> f64 {
    let mut scaled = value;
    // fmod keeps the sign of the dividend (matches C++ fmod): e.g.
    // fmod(-2.2, 1.0) == -0.2.  Add 1 so `scaled - fractial == floor(scaled)`
    // for negatives too (PixelGrid.cpp comment).
    let mut fractial = scaled % 1.0;
    if fractial < 0.0 {
        fractial += 1.0;
    }
    // Yoga's PixelGrid.cpp branches in this exact order (order matters — e.g.
    // `fractial ≈ 1.0` must ceil even when `force_floor` is set):
    //   1. fractial ≈ 0.0        → floor (already whole):       scaled -= fractial
    //   2. fractial ≈ 1.0        → ceil  (whole, just below):   scaled += 1 - fractial
    //   3. forceCeil             → ceil:                        scaled += 1 - fractial
    //   4. forceFloor            → floor:                       scaled -= fractial
    //   5. else (round half up)  → +1 iff fractial >= 0.5, else +0
    //
    // We preserve that order exactly.  To satisfy clippy's `if_same_then_else`
    // without reordering, the arithmetic is expressed as a single delta computed
    // in yoga's priority order, then applied once.
    let delta = if inexact_equals(fractial, 0.0) {
        // (1) already whole → floor
        -fractial
    } else if inexact_equals(fractial, 1.0) || force_ceil {
        // (2)/(3) ~whole-just-below or forced ceil → round up
        1.0 - fractial
    } else if force_floor {
        // (4) forced floor (text nodes never round down)
        -fractial
    } else if fractial > 0.5 || inexact_equals(fractial, 0.5) {
        // (5) round half up — exactly-0.5 ties go toward +inf, matching yoga
        1.0 - fractial
    } else {
        // (5) round half down
        -fractial
    };
    scaled += delta;
    scaled
}

/// Parent origins threaded through `round_node`'s recursion.
///
/// `absolute_left`/`absolute_top` are yoga's `absoluteLeft`/`absoluteTop` —
/// the *unrounded* absolute offset of the parent, used only for the
/// edge-rounding of dimensions.  `rounded_left`/`rounded_top` are the sum of
/// the ROUNDED parent-relative offsets of all ancestors — the integer cell
/// origin the renderer actually paints the parent at — used to accumulate the
/// absolute rects (`TaffyEngine::rounded_absolute`).
struct RoundOrigin {
    absolute_left: f64,
    absolute_top: f64,
    rounded_left: i32,
    rounded_top: i32,
}

/// Recursive port of yoga 3.2.1 `roundLayoutResultsToPixelGrid` (PixelGrid.cpp),
/// specialized to `pointScaleFactor == 1.0`.
///
/// `absolute_left` / `absolute_top` are the *unrounded* absolute offsets of this
/// node's parent (yoga threads these through the recursion).  We compute each
/// node's rounded parent-relative position and rounded dimension and store the
/// result keyed by dom id; the renderer re-accumulates absolute offsets from the
/// parent-relative rects, so storing parent-relative here matches yoga's
/// `setLayoutPosition` (which overwrites the *relative* position).
///
/// `is_text(dom_id)` is true iff the node has a measure fn registered — that is
/// our equivalent of yoga's `node->getNodeType() == NodeType::Text`, the flag
/// yoga uses to floor (never round down) text positions/sizes so glyphs are not
/// truncated.
fn round_node(
    tree: &TaffyTree<u32>,
    is_text: &dyn Fn(u32) -> bool,
    nid: NodeId,
    dom_id: u32,
    origin: RoundOrigin,
    out: &mut HashMap<u32, Rect>,
    out_absolute: &mut HashMap<u32, Rect>,
) {
    let RoundOrigin {
        absolute_left,
        absolute_top,
        rounded_left,
        rounded_top,
    } = origin;
    // Read the unrounded layout taffy produced for this node.
    let Ok(layout) = tree.layout(nid) else {
        return;
    };
    let node_left = f64::from(layout.location.x);
    let node_top = f64::from(layout.location.y);
    let node_width = f64::from(layout.size.width);
    let node_height = f64::from(layout.size.height);

    let absolute_node_left = absolute_left + node_left;
    let absolute_node_top = absolute_top + node_top;
    let absolute_node_right = absolute_node_left + node_width;
    let absolute_node_bottom = absolute_node_top + node_height;

    // pointScaleFactor (== 1.0) is never 0, so we always take yoga's rounding
    // branch.  textRounding: yoga floors text nodes so they never shrink below
    // their measured glyph extent (PixelGrid.cpp).
    let text_rounding = is_text(dom_id);

    // Position: parent-relative, rounded from the *relative* nodeLeft/nodeTop
    // (PixelGrid.cpp: roundValueToPixelGrid(nodeLeft, …, forceFloor=textRounding)).
    let rx = round_value_to_pixel_grid(node_left, false, text_rounding);
    let ry = round_value_to_pixel_grid(node_top, false, text_rounding);

    // Dimensions: round(absoluteRight) - round(absoluteLeft) so cumulative edges
    // line up with neighbors.  For text nodes, ceil when there is a fractional
    // remainder and floor otherwise (PixelGrid.cpp hasFractionalWidth/Height).
    let has_fractional_width =
        !inexact_equals(node_width % 1.0, 0.0) && !inexact_equals(node_width % 1.0, 1.0);
    let has_fractional_height =
        !inexact_equals(node_height % 1.0, 0.0) && !inexact_equals(node_height % 1.0, 1.0);

    let rw = round_value_to_pixel_grid(
        absolute_node_right,
        text_rounding && has_fractional_width,
        text_rounding && !has_fractional_width,
    ) - round_value_to_pixel_grid(absolute_node_left, false, text_rounding);
    let rh = round_value_to_pixel_grid(
        absolute_node_bottom,
        text_rounding && has_fractional_height,
        text_rounding && !has_fractional_height,
    ) - round_value_to_pixel_grid(absolute_node_top, false, text_rounding);

    let rect = Rect {
        x: rx.round() as i32,
        y: ry.round() as i32,
        width: rw.max(0.0).round() as u16,
        height: rh.max(0.0).round() as u16,
    };
    out.insert(dom_id, rect);

    // Absolute (root-relative) position: the sum of the ROUNDED parent-relative
    // offsets down the ancestor chain — exactly where the renderer paints this
    // node (it re-accumulates the rounded relative rects), and exactly what the
    // jacob314/ink fork's `getBoundingBox` computes by summing yoga's
    // `getComputedLeft/Top` (post-pixel-grid values) up `parentNode`.  NOT
    // `round(absolute_node_left)` — rounding the unrounded absolute can differ
    // by ±1 from the painted position on fractional ancestors.
    let abs_x = rounded_left + rect.x;
    let abs_y = rounded_top + rect.y;
    out_absolute.insert(
        dom_id,
        Rect {
            x: abs_x,
            y: abs_y,
            ..rect
        },
    );

    // Recurse with this node's *unrounded* absolute origin (yoga passes
    // absoluteNodeLeft/absoluteNodeTop, not the rounded values) plus the
    // rounded painted origin for the absolute-rect accumulation.
    let child_count = tree.child_count(nid);
    for index in 0..child_count {
        let Ok(child_nid) = tree.child_at_index(nid, index) else {
            continue;
        };
        // The dom id is the node's taffy context.
        let Some(child_dom) = tree.get_node_context(child_nid).copied() else {
            continue;
        };
        round_node(
            tree,
            is_text,
            child_nid,
            child_dom,
            RoundOrigin {
                absolute_left: absolute_node_left,
                absolute_top: absolute_node_top,
                rounded_left: abs_x,
                rounded_top: abs_y,
            },
            out,
            out_absolute,
        );
    }
}

impl Default for TaffyEngine {
    fn default() -> Self {
        Self::new()
    }
}

impl LayoutEngine for TaffyEngine {
    fn create(&mut self, id: u32) -> Result<(), String> {
        // Idempotent: if already present, no-op (mirrors dom Create no-op on
        // an occupied slot — `arena.rs:30-32`).
        if self.id_map.contains_key(&id) {
            return Ok(());
        }
        // Store the dom id as the node's context so the measure closure can
        // read it directly from the `ctx` parameter — no reverse map needed.
        let nid = self
            .tree
            .new_leaf_with_context(TaffyStyle::default(), id)
            .map_err(|e| e.to_string())?;
        self.id_map.insert(id, nid);
        Ok(())
    }

    fn apply_style(&mut self, id: u32, style: &Style) -> Result<(), String> {
        let nid = self.taffy_id(id)?;
        self.tree
            .set_style(nid, style_to_taffy(style))
            .map_err(|e| e.to_string())
    }

    fn set_measure(&mut self, id: u32, f: Box<MeasureFn>) {
        // Store; dispatched during `calculate`.  The dom id is available via
        // the node's taffy context (`TaffyTree<u32>`), so no reverse map is
        // needed here or in `calculate`.
        self.measures.insert(id, f);
    }

    fn insert_child(&mut self, parent: u32, child: u32, index: usize) -> Result<(), String> {
        let pnid = self.taffy_id(parent)?;
        let cnid = self.taffy_id(child)?;

        let child_count = self.tree.child_count(pnid);
        if index >= child_count {
            // Clamp to append — callers with a stale index must not panic.
            self.tree.add_child(pnid, cnid).map_err(|e| e.to_string())
        } else {
            self.tree
                .insert_child_at_index(pnid, index, cnid)
                .map_err(|e| e.to_string())
        }
    }

    fn remove_child(&mut self, parent: u32, child: u32) -> Result<(), String> {
        let pnid = self.taffy_id(parent)?;
        let cnid = self.taffy_id(child)?;
        self.tree
            .remove_child(pnid, cnid)
            .map(|_| ())
            .map_err(|e| e.to_string())
    }

    fn destroy(&mut self, id: u32) {
        // Look up the taffy NodeId; silently no-op if not present.
        let Some(nid) = self.id_map.remove(&id) else {
            return;
        };
        // Drop any measure function registered for this dom id.
        self.measures.remove(&id);
        // Evict from the rounded map so computed() cannot serve a stale rect
        // after the node is destroyed (violates the destroy→computed-None
        // contract).  Note: remove_child (detach without destroy) intentionally
        // does NOT evict — a detached-but-alive node retains its last-calculated
        // rect until the next calculate(), matching yoga's behavior (yoga also
        // serves the last layout for detached nodes until recompute).
        self.rounded.remove(&id);
        self.rounded_absolute.remove(&id);
        // Taffy 0.10 `remove` detaches the node from its parent and children
        // (children become orphan taffy leaves — their Free ops arrive
        // separately; see Free-no-cascade in dom/mod.rs).  Errors are swallowed
        // because a missing NodeId is a bug, not a recoverable condition here.
        let _ = self.tree.remove(nid);
    }

    fn mark_dirty(&mut self, id: u32) -> Result<(), String> {
        let nid = self.taffy_id(id)?;
        self.tree.mark_dirty(nid).map_err(|e| e.to_string())
    }

    fn calculate(
        &mut self,
        root_id: u32,
        viewport_width: f32,
        viewport_height: Option<f32>,
    ) -> Result<(), String> {
        let root_nid = self.taffy_id(root_id)?;

        // ink render-to-string.ts:62 — rootNode.yogaNode!.setWidth(columns).
        // The root container is given a DEFINITE width equal to the terminal
        // columns so no-width children stretch to fill it (instead of the root
        // shrink-wrapping to content under an auto width).
        // The other half of ink-root identity (column/stretch defaults) lives
        // in render::create_layout_nodes, which sees node kinds.
        if let Ok(mut s) = self.tree.style(root_nid).cloned() {
            s.size.width = Dimension::length(viewport_width);
            let _ = self.tree.set_style(root_nid, s);
        }

        // viewport_height: None → MaxContent (unconstrained, render-to-string.ts:62-68).
        let available = Size {
            width: AvailableSpace::Definite(viewport_width),
            height: match viewport_height {
                Some(h) => AvailableSpace::Definite(h),
                None => AvailableSpace::MaxContent,
            },
        };

        // Taffy 0.10 passes the node's context (`&mut u32` dom id) directly to
        // the measure closure — no reverse-map snapshot needed.  `ctx` is a
        // parameter, not a capture, so borrowing `self.measures` here does not
        // conflict with the `&mut self.tree` borrow held by taffy.
        self.tree
            .compute_layout_with_measure(root_nid, available, |known, avail, _nid, ctx, _style| {
                // `ctx` is `Option<&mut u32>` — the dom id stored on the node.
                if let Some(&mut did) = ctx
                    && let Some(f) = self.measures.get_mut(&did)
                {
                    return f(known, avail);
                }
                // No measure function registered → zero size (leaf with no
                // intrinsic size, e.g. a box with only flex children).
                Size::ZERO
            })
            .map_err(|e| e.to_string())?;

        // Yoga-compatible pixel-grid rounding post-pass.  Taffy's own rounding
        // is disabled (see `new`); we round the unrounded float layout exactly
        // like yoga 3.2.1 `roundLayoutResultsToPixelGrid` so integer cell rects
        // match ink.  Rebuild the map each calculate; the root recursion starts
        // at absolute (0.0, 0.0) (yoga calls it with absoluteLeft/Top = 0).
        self.rounded.clear();
        self.rounded_absolute.clear();
        let is_text = |dom_id: u32| self.measures.contains_key(&dom_id);
        round_node(
            &self.tree,
            &is_text,
            root_nid,
            root_id,
            RoundOrigin {
                absolute_left: 0.0,
                absolute_top: 0.0,
                rounded_left: 0,
                rounded_top: 0,
            },
            &mut self.rounded,
            &mut self.rounded_absolute,
        );
        Ok(())
    }

    fn computed(&self, id: u32) -> Option<Rect> {
        // Primary path: the Yoga-compatible rounded rect produced by the
        // post-pass in `calculate` (see `round_node`).  Parent-relative, integer
        // cells — same contract as before.
        if let Some(r) = self.rounded.get(&id) {
            return Some(*r);
        }

        // Fallback: a node that was created but never laid out (no `calculate`
        // covering it yet).  Return the live taffy layout, truncated.  Taffy's
        // own rounding is disabled, so these floats are unrounded; truncation
        // here is a best-effort placeholder for the not-yet-calculated case and
        // is never hit on the rendered path (which always runs `calculate`).
        // Detached-but-alive nodes (remove_child without destroy) also land here
        // after the next calculate() evicts them from `rounded` — they retain
        // their last-calculated rect from `tree.layout()` until recompute, which
        // matches yoga's behavior of serving the last layout for detached nodes.
        let nid = self.id_map.get(&id).copied()?;
        let lay = self.tree.layout(nid).ok()?;
        Some(Rect {
            x: lay.location.x as i32,
            y: lay.location.y as i32,
            width: lay.size.width as u16,
            height: lay.size.height as u16,
        })
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dom::BorderStyle;
    use taffy::style::FlexDirection as TFD;

    fn pt(v: f32) -> Dimension {
        Dimension::length(v)
    }

    /// Convenience: create a TaffyEngine with `ids` pre-registered.
    fn engine_with(ids: &[u32]) -> TaffyEngine {
        let mut e = TaffyEngine::new();
        for &id in ids {
            e.create(id).unwrap();
        }
        e
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Style mapping unit tests (prop-group by prop-group)
    // ═══════════════════════════════════════════════════════════════════════════

    // ── M1. position (styles.ts:415–442) ────────────────────────────────────
    #[test]
    fn map_position_absolute() {
        let s = Style {
            position: Some(Position::Absolute),
            ..Default::default()
        };
        assert_eq!(style_to_taffy(&s).position, TaffyPosition::Absolute);
    }

    #[test]
    fn map_position_relative() {
        let s = Style {
            position: Some(Position::Relative),
            ..Default::default()
        };
        assert_eq!(style_to_taffy(&s).position, TaffyPosition::Relative);
    }

    #[test]
    fn map_position_static_maps_to_relative() {
        // Divergence: Taffy has no Static; map to Relative.
        let s = Style {
            position: Some(Position::Static),
            ..Default::default()
        };
        assert_eq!(style_to_taffy(&s).position, TaffyPosition::Relative);
    }

    #[test]
    fn map_inset_points() {
        let s = Style {
            top: Some(Dim::Points(2.0)),
            left: Some(Dim::Points(5.0)),
            ..Default::default()
        };
        let t = style_to_taffy(&s);
        assert_eq!(t.inset.top, LengthPercentageAuto::length(2.0));
        assert_eq!(t.inset.left, LengthPercentageAuto::length(5.0));
        assert_eq!(t.inset.right, LengthPercentageAuto::auto());
        assert_eq!(t.inset.bottom, LengthPercentageAuto::auto());
    }

    #[test]
    fn map_inset_percent() {
        let s = Style {
            top: Some(Dim::Percent(50.0)),
            ..Default::default()
        };
        // 50% → 0.5 in taffy
        assert_eq!(
            style_to_taffy(&s).inset.top,
            LengthPercentageAuto::percent(0.5)
        );
    }

    // ── M2. margin cascade (styles.ts:444–472) ───────────────────────────────
    // Hand-derived: margin_all=2, margin_x=4, margin_left=7.
    // Expected: top=2, bottom=2, right=4, left=7.
    #[test]
    fn map_margin_cascade() {
        let s = Style {
            margin: Some(Lp::Points(2.0)),
            margin_x: Some(Lp::Points(4.0)),
            margin_left: Some(Lp::Points(7.0)),
            ..Default::default()
        };
        let t = style_to_taffy(&s);
        assert_eq!(t.margin.top, LengthPercentageAuto::length(2.0));
        assert_eq!(t.margin.bottom, LengthPercentageAuto::length(2.0));
        assert_eq!(t.margin.right, LengthPercentageAuto::length(4.0));
        assert_eq!(t.margin.left, LengthPercentageAuto::length(7.0));
    }

    #[test]
    fn map_margin_y_shorthand() {
        let s = Style {
            margin: Some(Lp::Points(1.0)),
            margin_y: Some(Lp::Points(3.0)),
            ..Default::default()
        };
        let t = style_to_taffy(&s);
        assert_eq!(t.margin.top, LengthPercentageAuto::length(3.0));
        assert_eq!(t.margin.bottom, LengthPercentageAuto::length(3.0));
        assert_eq!(t.margin.left, LengthPercentageAuto::length(1.0));
        assert_eq!(t.margin.right, LengthPercentageAuto::length(1.0));
    }

    #[test]
    fn map_margin_percent() {
        // Yoga/ink convention: 50 means 50%; taffy needs 0.5.
        let s = Style {
            margin: Some(Lp::Percent(50.0)),
            ..Default::default()
        };
        let t = style_to_taffy(&s);
        assert_eq!(t.margin.top, LengthPercentageAuto::percent(0.5));
    }

    // ── M3. padding cascade (styles.ts:474–502) ──────────────────────────────
    #[test]
    fn map_padding_cascade() {
        let s = Style {
            padding: Some(Lp::Points(2.0)),
            padding_x: Some(Lp::Points(4.0)),
            padding_top: Some(Lp::Points(1.0)),
            ..Default::default()
        };
        let t = style_to_taffy(&s);
        assert_eq!(t.padding.top, LengthPercentage::length(1.0));
        assert_eq!(t.padding.bottom, LengthPercentage::length(2.0));
        assert_eq!(t.padding.left, LengthPercentage::length(4.0));
        assert_eq!(t.padding.right, LengthPercentage::length(4.0));
    }

    // ── M4. flex (styles.ts:504–661) ─────────────────────────────────────────
    #[test]
    fn map_flex_direction_column() {
        let s = Style {
            flex_direction: Some(FlexDir::Column),
            ..Default::default()
        };
        assert_eq!(style_to_taffy(&s).flex_direction, FlexDirection::Column);
    }

    #[test]
    fn map_flex_direction_row_reverse() {
        let s = Style {
            flex_direction: Some(FlexDir::RowReverse),
            ..Default::default()
        };
        assert_eq!(style_to_taffy(&s).flex_direction, FlexDirection::RowReverse);
    }

    #[test]
    fn map_flex_wrap() {
        let s = Style {
            flex_wrap: Some(FlexWrap::Wrap),
            ..Default::default()
        };
        assert_eq!(style_to_taffy(&s).flex_wrap, TaffyFlexWrap::Wrap);
    }

    #[test]
    fn map_flex_grow_shrink() {
        let s = Style {
            flex_grow: Some(2.0),
            flex_shrink: Some(0.5),
            ..Default::default()
        };
        let t = style_to_taffy(&s);
        assert_eq!(t.flex_grow, 2.0);
        assert_eq!(t.flex_shrink, 0.5);
    }

    #[test]
    fn map_flex_basis_points() {
        let s = Style {
            flex_basis: Some(Dim::Points(40.0)),
            ..Default::default()
        };
        assert_eq!(style_to_taffy(&s).flex_basis, Dimension::length(40.0));
    }

    #[test]
    fn map_flex_basis_percent() {
        // ink passes 50 for "50%"; taffy needs 0.5.
        let s = Style {
            flex_basis: Some(Dim::Percent(50.0)),
            ..Default::default()
        };
        assert_eq!(style_to_taffy(&s).flex_basis, Dimension::percent(0.5));
    }

    #[test]
    fn map_flex_basis_auto() {
        let s = Style {
            flex_basis: Some(Dim::Auto),
            ..Default::default()
        };
        assert_eq!(style_to_taffy(&s).flex_basis, Dimension::auto());
    }

    #[test]
    fn map_align_items_center() {
        let s = Style {
            align_items: Some(Align::Center),
            ..Default::default()
        };
        assert_eq!(style_to_taffy(&s).align_items, Some(AlignItems::Center));
    }

    #[test]
    fn map_align_self_none_is_auto() {
        // align_self: None in dom::Style → None in taffy (encodes auto).
        let s = Style {
            align_self: None,
            ..Default::default()
        };
        assert_eq!(style_to_taffy(&s).align_self, None);
    }

    #[test]
    fn map_align_content_space_between() {
        let s = Style {
            align_content: Some(ContentAlign::SpaceBetween),
            ..Default::default()
        };
        assert_eq!(
            style_to_taffy(&s).align_content,
            Some(AlignContent::SpaceBetween)
        );
    }

    #[test]
    fn map_justify_content_center() {
        let s = Style {
            justify_content: Some(ContentAlign::Center),
            ..Default::default()
        };
        assert_eq!(
            style_to_taffy(&s).justify_content,
            Some(JustifyContent::Center)
        );
    }

    // ── M5. dimensions (styles.ts:663–719) ───────────────────────────────────
    // Oracle case 1 (hand-derived): width=80, height=24 → fixed terminal size.
    // A flex root with explicit 80×24 should report exactly 80×24 after layout.
    #[test]
    fn map_width_height_points() {
        let s = Style {
            width: Some(Dim::Points(80.0)),
            height: Some(Dim::Points(24.0)),
            ..Default::default()
        };
        let t = style_to_taffy(&s);
        assert_eq!(t.size.width, Dimension::length(80.0));
        assert_eq!(t.size.height, Dimension::length(24.0));
    }

    #[test]
    fn map_width_percent() {
        let s = Style {
            width: Some(Dim::Percent(50.0)),
            ..Default::default()
        };
        assert_eq!(style_to_taffy(&s).size.width, Dimension::percent(0.5));
    }

    #[test]
    fn map_width_auto() {
        let s = Style {
            width: Some(Dim::Auto),
            ..Default::default()
        };
        assert_eq!(style_to_taffy(&s).size.width, Dimension::auto());
    }

    #[test]
    fn map_min_max_size() {
        let s = Style {
            min_width: Some(Dim::Points(10.0)),
            max_width: Some(Dim::Points(100.0)),
            min_height: Some(Dim::Points(5.0)),
            max_height: Some(Dim::Points(50.0)),
            ..Default::default()
        };
        let t = style_to_taffy(&s);
        assert_eq!(t.min_size.width, Dimension::length(10.0));
        assert_eq!(t.max_size.width, Dimension::length(100.0));
        assert_eq!(t.min_size.height, Dimension::length(5.0));
        assert_eq!(t.max_size.height, Dimension::length(50.0));
    }

    #[test]
    fn map_aspect_ratio() {
        let s = Style {
            aspect_ratio: Some(16.0 / 9.0),
            ..Default::default()
        };
        let t = style_to_taffy(&s);
        assert!((t.aspect_ratio.unwrap() - 16.0 / 9.0).abs() < f32::EPSILON);
    }

    // ── M6. display (styles.ts:721–727) ──────────────────────────────────────
    #[test]
    fn map_display_flex() {
        let s = Style {
            display: Some(Display::Flex),
            ..Default::default()
        };
        assert_eq!(style_to_taffy(&s).display, TaffyDisplay::Flex);
    }

    #[test]
    fn map_display_none() {
        let s = Style {
            display: Some(Display::None),
            ..Default::default()
        };
        assert_eq!(style_to_taffy(&s).display, TaffyDisplay::None);
    }

    // ── M7. border (styles.ts:729–763) ───────────────────────────────────────
    // Oracle case 2 (hand-derived): borderStyle="single" with no per-edge
    // overrides → all four edges = 1 cell.  A 10×5 box with border has
    // content area 8×3 (1 cell consumed each side).
    #[test]
    fn map_border_all_edges_active() {
        let s = Style {
            border_style: Some(BorderStyle::Named("single".into())),
            ..Default::default()
        };
        let t = style_to_taffy(&s);
        assert_eq!(t.border.top, LengthPercentage::length(1.0));
        assert_eq!(t.border.right, LengthPercentage::length(1.0));
        assert_eq!(t.border.bottom, LengthPercentage::length(1.0));
        assert_eq!(t.border.left, LengthPercentage::length(1.0));
    }

    #[test]
    fn map_border_top_disabled() {
        let s = Style {
            border_style: Some(BorderStyle::Named("single".into())),
            border_top: Some(false),
            ..Default::default()
        };
        let t = style_to_taffy(&s);
        assert_eq!(t.border.top, LengthPercentage::length(0.0));
        assert_eq!(t.border.bottom, LengthPercentage::length(1.0));
        assert_eq!(t.border.left, LengthPercentage::length(1.0));
        assert_eq!(t.border.right, LengthPercentage::length(1.0));
    }

    #[test]
    fn map_border_none_when_no_border_style() {
        let s = Style {
            border_style: None,
            ..Default::default()
        };
        let t = style_to_taffy(&s);
        assert_eq!(t.border.top, LengthPercentage::length(0.0));
        assert_eq!(t.border.right, LengthPercentage::length(0.0));
        assert_eq!(t.border.bottom, LengthPercentage::length(0.0));
        assert_eq!(t.border.left, LengthPercentage::length(0.0));
    }

    // ── M8. gap (styles.ts:765–777) ──────────────────────────────────────────
    // Oracle case 3 (hand-derived): gap=2 with two 10×5 children in a row
    // inside an 80×5 container.  Expected: c1.x=0, c2.x=12 (10+2 gap).
    #[test]
    fn map_gap_all() {
        let s = Style {
            gap: Some(2.0),
            ..Default::default()
        };
        let t = style_to_taffy(&s);
        assert_eq!(t.gap.width, LengthPercentage::length(2.0));
        assert_eq!(t.gap.height, LengthPercentage::length(2.0));
    }

    #[test]
    fn map_gap_per_axis() {
        let s = Style {
            column_gap: Some(4.0),
            row_gap: Some(1.0),
            ..Default::default()
        };
        let t = style_to_taffy(&s);
        assert_eq!(t.gap.width, LengthPercentage::length(4.0));
        assert_eq!(t.gap.height, LengthPercentage::length(1.0));
    }

    #[test]
    fn map_gap_per_axis_overrides_all() {
        // column_gap=4 wins over gap=2 for the horizontal axis.
        let s = Style {
            gap: Some(2.0),
            column_gap: Some(4.0),
            ..Default::default()
        };
        let t = style_to_taffy(&s);
        assert_eq!(t.gap.width, LengthPercentage::length(4.0));
        assert_eq!(t.gap.height, LengthPercentage::length(2.0));
    }

    // ── M9. overflow (styles.ts; Box.tsx resolves shorthand JS-side) ──────────
    #[test]
    fn map_overflow_hidden() {
        let s = Style {
            overflow_x: Some(Overflow::Hidden),
            ..Default::default()
        };
        assert_eq!(style_to_taffy(&s).overflow.x, TaffyOverflow::Hidden);
        assert_eq!(style_to_taffy(&s).overflow.y, TaffyOverflow::Visible);
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // End-to-end layout tests through apply_style (engine trait path)
    // ═══════════════════════════════════════════════════════════════════════════

    // ── E1. apply_style width/height end-to-end ───────────────────────────────
    // Oracle case 1 (hand-derived): root at 80×24 via apply_style.
    // Flexbox: a node with explicit size fills exactly that size.
    #[test]
    fn apply_style_width_height() {
        let mut e = TaffyEngine::new();
        e.create(0).unwrap();
        let s = Style {
            width: Some(Dim::Points(80.0)),
            height: Some(Dim::Points(24.0)),
            ..Default::default()
        };
        e.apply_style(0, &s).unwrap();
        e.calculate(0, 80.0, Some(24.0)).unwrap();
        assert_eq!(
            e.computed(0).unwrap(),
            Rect {
                x: 0,
                y: 0,
                width: 80,
                height: 24
            }
        );
    }

    // ── E2. apply_style flexDirection end-to-end ──────────────────────────────
    // Oracle case 3 (hand-derived): column layout; two 80×12 children at y=0 and y=12.
    #[test]
    fn apply_style_flex_direction_column() {
        let mut e = engine_with(&[0, 1, 2]);
        e.insert_child(0, 1, 0).unwrap();
        e.insert_child(0, 2, 1).unwrap();

        e.apply_style(
            0,
            &Style {
                width: Some(Dim::Points(80.0)),
                height: Some(Dim::Points(24.0)),
                flex_direction: Some(FlexDir::Column),
                ..Default::default()
            },
        )
        .unwrap();
        e.apply_style(
            1,
            &Style {
                width: Some(Dim::Points(80.0)),
                height: Some(Dim::Points(12.0)),
                ..Default::default()
            },
        )
        .unwrap();
        e.apply_style(
            2,
            &Style {
                width: Some(Dim::Points(80.0)),
                height: Some(Dim::Points(12.0)),
                ..Default::default()
            },
        )
        .unwrap();

        e.calculate(0, 80.0, Some(24.0)).unwrap();
        let r1 = e.computed(1).unwrap();
        let r2 = e.computed(2).unwrap();
        assert_eq!(
            r1,
            Rect {
                x: 0,
                y: 0,
                width: 80,
                height: 12
            }
        );
        assert_eq!(
            r2,
            Rect {
                x: 0,
                y: 12,
                width: 80,
                height: 12
            }
        );
    }

    // ── E3. apply_style gap end-to-end ────────────────────────────────────────
    // Oracle case 3 (hand-derived): gap=2, two 10×5 children in a flex row.
    // Expected: c1.x=0, c2.x=12 (c1.width + gap = 10 + 2).
    #[test]
    fn apply_style_gap() {
        let mut e = engine_with(&[0, 1, 2]);
        e.insert_child(0, 1, 0).unwrap();
        e.insert_child(0, 2, 1).unwrap();

        e.apply_style(
            0,
            &Style {
                width: Some(Dim::Points(80.0)),
                height: Some(Dim::Points(24.0)),
                gap: Some(2.0),
                align_items: Some(Align::FlexStart),
                ..Default::default()
            },
        )
        .unwrap();
        e.apply_style(
            1,
            &Style {
                width: Some(Dim::Points(10.0)),
                height: Some(Dim::Points(5.0)),
                ..Default::default()
            },
        )
        .unwrap();
        e.apply_style(
            2,
            &Style {
                width: Some(Dim::Points(10.0)),
                height: Some(Dim::Points(5.0)),
                ..Default::default()
            },
        )
        .unwrap();

        e.calculate(0, 80.0, Some(24.0)).unwrap();
        let c1 = e.computed(1).unwrap();
        let c2 = e.computed(2).unwrap();
        assert_eq!(c1.x, 0);
        assert_eq!(c2.x, 12); // 10 (c1 width) + 2 (gap)
    }

    // ── E4. apply_style padding end-to-end ───────────────────────────────────
    // A root with padding=2 and two children: the first child starts at x=2, y=2.
    #[test]
    fn apply_style_padding() {
        let mut e = engine_with(&[0, 1]);
        e.insert_child(0, 1, 0).unwrap();

        e.apply_style(
            0,
            &Style {
                width: Some(Dim::Points(80.0)),
                height: Some(Dim::Points(24.0)),
                padding: Some(Lp::Points(2.0)),
                align_items: Some(Align::FlexStart),
                ..Default::default()
            },
        )
        .unwrap();
        e.apply_style(
            1,
            &Style {
                width: Some(Dim::Points(10.0)),
                height: Some(Dim::Points(5.0)),
                ..Default::default()
            },
        )
        .unwrap();

        e.calculate(0, 80.0, Some(24.0)).unwrap();
        let child = e.computed(1).unwrap();
        assert_eq!(child.x, 2);
        assert_eq!(child.y, 2);
    }

    // ── E5. apply_style border end-to-end ────────────────────────────────────
    // Oracle case 2 (hand-derived): a 10×5 box with a full border (all 4 edges
    // = 1 cell).  The single child (6×3 explicit size) should start at x=1, y=1
    // (pushed inward by the 1-cell border on left and top).
    #[test]
    fn apply_style_border() {
        let mut e = engine_with(&[0, 1]);
        e.insert_child(0, 1, 0).unwrap();

        e.apply_style(
            0,
            &Style {
                width: Some(Dim::Points(10.0)),
                height: Some(Dim::Points(5.0)),
                border_style: Some(BorderStyle::Named("single".into())),
                align_items: Some(Align::FlexStart),
                ..Default::default()
            },
        )
        .unwrap();
        e.apply_style(
            1,
            &Style {
                width: Some(Dim::Points(6.0)),
                height: Some(Dim::Points(3.0)),
                ..Default::default()
            },
        )
        .unwrap();

        e.calculate(0, 10.0, Some(5.0)).unwrap();
        let child = e.computed(1).unwrap();
        // Border = 1 each side → content area origin at (1, 1).
        assert_eq!(child.x, 1);
        assert_eq!(child.y, 1);
    }

    // ── E6. computed_absolute on a nested-offset tree (#124, pin A1) ────────
    // Three levels with offsets at EVERY level (root padding, middle margin,
    // inner margin), hand-computed:
    //   root (id 0): padding 2                  → abs (0, 0)
    //   middle (id 1): margin-left 3, -top 2    → rel (2+3, 2+2) = (5, 4); abs (5, 4)
    //   inner (id 2): margin-left 4, -top 1     → rel (4, 1);              abs (9, 5)
    // Mutation guard: the inner node's absolute (9, 5) differs from its
    // parent-relative (4, 1) — an implementation returning relative coords
    // (the pre-#124 limitation) fails the abs assertions.
    #[test]
    fn computed_absolute_nested_offsets() {
        let mut e = engine_with(&[0, 1, 2]);
        e.insert_child(0, 1, 0).unwrap();
        e.insert_child(1, 2, 0).unwrap();

        e.apply_style(
            0,
            &Style {
                width: Some(Dim::Points(40.0)),
                height: Some(Dim::Points(10.0)),
                padding: Some(Lp::Points(2.0)),
                align_items: Some(Align::FlexStart),
                ..Default::default()
            },
        )
        .unwrap();
        e.apply_style(
            1,
            &Style {
                width: Some(Dim::Points(20.0)),
                height: Some(Dim::Points(6.0)),
                margin_left: Some(Lp::Points(3.0)),
                margin_top: Some(Lp::Points(2.0)),
                align_items: Some(Align::FlexStart),
                ..Default::default()
            },
        )
        .unwrap();
        e.apply_style(
            2,
            &Style {
                width: Some(Dim::Points(6.0)),
                height: Some(Dim::Points(2.0)),
                margin_left: Some(Lp::Points(4.0)),
                margin_top: Some(Lp::Points(1.0)),
                ..Default::default()
            },
        )
        .unwrap();

        e.calculate(0, 40.0, Some(10.0)).unwrap();

        // Parent-relative truths (unchanged contract — `computed` stays relative).
        assert_eq!(
            e.computed(1).unwrap(),
            Rect {
                x: 5,
                y: 4,
                width: 20,
                height: 6
            }
        );
        assert_eq!(
            e.computed(2).unwrap(),
            Rect {
                x: 4,
                y: 1,
                width: 6,
                height: 2
            }
        );

        // Absolute rects: root at origin; nested offsets ACCUMULATE.
        assert_eq!(
            e.computed_absolute(0).unwrap(),
            Rect {
                x: 0,
                y: 0,
                width: 40,
                height: 10
            }
        );
        assert_eq!(
            e.computed_absolute(1).unwrap(),
            Rect {
                x: 5,
                y: 4,
                width: 20,
                height: 6
            }
        );
        assert_eq!(
            e.computed_absolute(2).unwrap(),
            Rect {
                x: 9,
                y: 5,
                width: 6,
                height: 2
            }
        );

        // Discrimination: absolute ≠ relative for the doubly-nested node.
        assert_ne!(e.computed_absolute(2), e.computed(2));

        // Unknown id → None (no fallback; see `computed_absolute` docs).
        assert_eq!(e.computed_absolute(99), None);
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // Pre-existing layout tests (kept; bypass apply_style for direct coverage)
    // ═══════════════════════════════════════════════════════════════════════════

    // ── 1. Single root sized to the viewport ────────────────────────────────
    // The root node has an explicit 80×24 size; after calculate its rect must
    // exactly match the viewport.
    #[test]
    fn single_root_fills_viewport() {
        let mut e = TaffyEngine::new();
        e.create(0).unwrap();

        let nid = e.id_map[&0];
        e.tree
            .set_style(
                nid,
                TaffyStyle {
                    size: taffy::geometry::Size {
                        width: pt(80.0),
                        height: pt(24.0),
                    },
                    ..Default::default()
                },
            )
            .unwrap();

        e.calculate(0, 80.0, Some(24.0)).unwrap();

        let r = e.computed(0).unwrap();
        assert_eq!(
            r,
            Rect {
                x: 0,
                y: 0,
                width: 80,
                height: 24
            }
        );
    }

    // ── 2. Root + two default-style children ────────────────────────────────
    // Default style: display:flex, flex-direction:row (taffy default).
    // Give the children explicit widths (10 and 20) that sum well under the
    // 80-column root so flex-shrink does not compress them.  The key assertion
    // is `c2.x == c1.width`, which pins the row-advance that proves
    // flex-direction:row is the default.
    #[test]
    fn root_two_default_children() {
        let mut e = engine_with(&[0, 1, 2]);
        e.insert_child(0, 1, 0).unwrap();
        e.insert_child(0, 2, 1).unwrap();

        let root_nid = e.id_map[&0];
        let c1_nid = e.id_map[&1];
        let c2_nid = e.id_map[&2];
        e.tree
            .set_style(
                root_nid,
                TaffyStyle {
                    size: taffy::geometry::Size {
                        width: pt(80.0),
                        height: pt(24.0),
                    },
                    ..Default::default()
                },
            )
            .unwrap();
        e.tree
            .set_style(
                c1_nid,
                TaffyStyle {
                    size: taffy::geometry::Size {
                        width: pt(10.0),
                        height: pt(24.0),
                    },
                    ..Default::default()
                },
            )
            .unwrap();
        e.tree
            .set_style(
                c2_nid,
                TaffyStyle {
                    size: taffy::geometry::Size {
                        width: pt(20.0),
                        height: pt(24.0),
                    },
                    ..Default::default()
                },
            )
            .unwrap();

        e.calculate(0, 80.0, Some(24.0)).unwrap();

        assert_eq!(
            e.computed(0).unwrap(),
            Rect {
                x: 0,
                y: 0,
                width: 80,
                height: 24
            }
        );

        let c1 = e.computed(1).unwrap();
        let c2 = e.computed(2).unwrap();
        assert_eq!(c1.x, 0);
        assert_eq!(c1.y, 0);
        assert_eq!(c2.y, 0); // flex-direction:row → both on same row
        assert_eq!(c1.width, 10);
        assert_eq!(c2.width, 20);
        assert_eq!(c2.x, c1.x + i32::from(c1.width));
    }

    // ── 3. Nested box ────────────────────────────────────────────────────────
    // root(80×24) → outer(40×24) → inner(20×24)
    #[test]
    fn nested_box() {
        let mut e = engine_with(&[0, 1, 2]);
        e.insert_child(0, 1, 0).unwrap();
        e.insert_child(1, 2, 0).unwrap();

        let root_nid = e.id_map[&0];
        let outer_nid = e.id_map[&1];
        let inner_nid = e.id_map[&2];

        e.tree
            .set_style(
                root_nid,
                TaffyStyle {
                    size: taffy::geometry::Size {
                        width: pt(80.0),
                        height: pt(24.0),
                    },
                    ..Default::default()
                },
            )
            .unwrap();
        e.tree
            .set_style(
                outer_nid,
                TaffyStyle {
                    size: taffy::geometry::Size {
                        width: pt(40.0),
                        height: pt(24.0),
                    },
                    ..Default::default()
                },
            )
            .unwrap();
        e.tree
            .set_style(
                inner_nid,
                TaffyStyle {
                    size: taffy::geometry::Size {
                        width: pt(20.0),
                        height: pt(24.0),
                    },
                    ..Default::default()
                },
            )
            .unwrap();

        e.calculate(0, 80.0, Some(24.0)).unwrap();

        assert_eq!(
            e.computed(0).unwrap(),
            Rect {
                x: 0,
                y: 0,
                width: 80,
                height: 24
            }
        );
        assert_eq!(
            e.computed(1).unwrap(),
            Rect {
                x: 0,
                y: 0,
                width: 40,
                height: 24
            }
        );
        assert_eq!(
            e.computed(2).unwrap(),
            Rect {
                x: 0,
                y: 0,
                width: 20,
                height: 24
            }
        );
    }

    // ── 4. Recalculate after apply_style ─────────────────────────────────────
    // Resize root from 80×24 to 40×12 via apply_style, then recalculate.
    #[test]
    fn recalculate_after_style_change() {
        let mut e = TaffyEngine::new();
        e.create(0).unwrap();

        let initial = Style {
            width: Some(Dim::Points(80.0)),
            height: Some(Dim::Points(24.0)),
            ..Default::default()
        };
        e.apply_style(0, &initial).unwrap();
        e.calculate(0, 80.0, Some(24.0)).unwrap();
        assert_eq!(
            e.computed(0).unwrap(),
            Rect {
                x: 0,
                y: 0,
                width: 80,
                height: 24
            }
        );

        // Resize via apply_style (mark_dirty is implicit in set_style).
        let resized = Style {
            width: Some(Dim::Points(40.0)),
            height: Some(Dim::Points(12.0)),
            ..Default::default()
        };
        e.apply_style(0, &resized).unwrap();
        e.mark_dirty(0).unwrap();
        e.calculate(0, 40.0, Some(12.0)).unwrap();
        assert_eq!(
            e.computed(0).unwrap(),
            Rect {
                x: 0,
                y: 0,
                width: 40,
                height: 12
            }
        );
    }

    // ── 5. computed() on unknown id returns None, not a panic ─────────────────
    #[test]
    fn computed_unknown_id_returns_none() {
        let e = TaffyEngine::new();
        assert_eq!(e.computed(999), None);
    }

    // ── 6. create duplicate id is a no-op ────────────────────────────────────
    #[test]
    fn create_duplicate_is_noop() {
        let mut e = TaffyEngine::new();
        e.create(0).unwrap();
        let nid_first = e.id_map[&0];
        e.create(0).unwrap();
        assert_eq!(e.id_map[&0], nid_first);
    }

    // ── 7. measure function is called for leaf nodes ──────────────────────────
    #[test]
    fn measure_fn_is_invoked() {
        let mut e = TaffyEngine::new();
        e.create(0).unwrap();
        e.create(1).unwrap();

        let root_nid = e.id_map[&0];
        e.tree
            .set_style(
                root_nid,
                TaffyStyle {
                    size: taffy::geometry::Size {
                        width: pt(80.0),
                        height: pt(24.0),
                    },
                    align_items: Some(AlignItems::FlexStart),
                    ..Default::default()
                },
            )
            .unwrap();

        e.insert_child(0, 1, 0).unwrap();

        e.set_measure(
            1,
            Box::new(|_known, _avail| Size {
                width: 10.0,
                height: 3.0,
            }),
        );

        e.calculate(0, 80.0, Some(24.0)).unwrap();

        let leaf = e.computed(1).unwrap();
        assert_eq!(leaf.width, 10);
        assert_eq!(leaf.height, 3);
    }

    // ── 8. insert_child index clamping ───────────────────────────────────────
    #[test]
    fn insert_child_index_clamp_appends() {
        let mut e = engine_with(&[0, 1, 2]);
        e.insert_child(0, 1, 0).unwrap();
        e.insert_child(0, 2, 9999).unwrap();

        let root_nid = e.id_map[&0];
        let root_nid_children = e.tree.children(root_nid).unwrap();
        assert_eq!(root_nid_children, vec![e.id_map[&1], e.id_map[&2]]);
    }

    // ── destroy: node lifecycle ───────────────────────────────────────────────

    // destroy removes the node from the engine; computed() returns None after.
    // Also verifies that a registered measure function is dropped on destroy.
    #[test]
    fn destroy_removes_node() {
        let mut e = TaffyEngine::new();
        e.create(0).unwrap();
        e.create(1).unwrap();
        e.set_measure(
            1,
            Box::new(|_, _| Size {
                width: 5.0,
                height: 1.0,
            }),
        );
        // Pre-calculate: computed() falls back to the live taffy layout.
        assert!(e.computed(1).is_some());

        // Post-calculate: node 1 is inserted under root 0, calculate() fills
        // self.rounded.  After destroy(1), computed() must return None — not the
        // stale rounded rect (the bug self.rounded.remove(&id) fixes).
        e.insert_child(0, 1, 0).unwrap();
        let root_s = crate::dom::Style {
            width: Some(crate::dom::Dim::Points(80.0)),
            height: Some(crate::dom::Dim::Points(24.0)),
            ..Default::default()
        };
        e.apply_style(0, &root_s).unwrap();
        e.calculate(0, 80.0, Some(24.0)).unwrap();
        // Now served from self.rounded (not the fallback path).
        assert!(e.computed(1).is_some());

        e.destroy(1);
        assert!(e.computed(1).is_none());
        // id_map and measures entries must also be gone (no dangling state).
        assert!(!e.id_map.contains_key(&1));
        assert!(!e.measures.contains_key(&1));
    }

    // destroy on unknown id is a silent no-op — matches ink's guard-style
    // error philosophy (no panic, no change to other nodes).
    #[test]
    fn destroy_unknown_id_is_noop() {
        let mut e = TaffyEngine::new();
        e.create(0).unwrap();
        e.destroy(999); // must not panic
        assert!(e.computed(0).is_some());
    }

    // destroy cleans up state so re-create + new measure works cleanly.
    // Validates the invalidation contract: after destroy, a fresh node at the
    // same id has no stale measure function from the previous occupant.
    #[test]
    fn destroy_then_recreate_clean_state() {
        let mut e = TaffyEngine::new();
        e.create(0).unwrap();
        e.create(1).unwrap();
        e.insert_child(0, 1, 0).unwrap();

        let root_s = crate::dom::Style {
            width: Some(crate::dom::Dim::Points(80.0)),
            height: Some(crate::dom::Dim::Points(24.0)),
            align_items: Some(crate::dom::Align::FlexStart),
            ..Default::default()
        };
        e.apply_style(0, &root_s).unwrap();
        e.set_measure(
            1,
            Box::new(|_, _| Size {
                width: 5.0,
                height: 1.0,
            }),
        );
        e.calculate(0, 80.0, Some(24.0)).unwrap();
        assert_eq!(e.computed(1).unwrap().width, 5);

        e.destroy(1);
        e.destroy(0);

        // Re-create with different measure — must not inherit old closure.
        e.create(0).unwrap();
        e.create(1).unwrap();
        e.insert_child(0, 1, 0).unwrap();
        e.apply_style(0, &root_s).unwrap();
        e.set_measure(
            1,
            Box::new(|_, _| Size {
                width: 7.0,
                height: 1.0,
            }),
        );
        e.calculate(0, 80.0, Some(24.0)).unwrap();
        assert_eq!(e.computed(1).unwrap().width, 7);
    }

    // ── 9. remove_child detaches without destroying node ─────────────────────
    #[test]
    fn remove_child_detaches() {
        let mut e = engine_with(&[0, 1]);
        e.insert_child(0, 1, 0).unwrap();
        e.remove_child(0, 1).unwrap();

        assert!(e.id_map.contains_key(&1));
        let root_nid = e.id_map[&0];
        assert_eq!(e.tree.child_count(root_nid), 0);
    }

    // ── 10. flex column layout ────────────────────────────────────────────────
    #[test]
    fn flex_column_two_children() {
        let mut e = engine_with(&[0, 1, 2]);
        e.insert_child(0, 1, 0).unwrap();
        e.insert_child(0, 2, 1).unwrap();

        let root_nid = e.id_map[&0];
        let c1_nid = e.id_map[&1];
        let c2_nid = e.id_map[&2];

        e.tree
            .set_style(
                root_nid,
                TaffyStyle {
                    size: taffy::geometry::Size {
                        width: pt(80.0),
                        height: pt(24.0),
                    },
                    flex_direction: TFD::Column,
                    ..Default::default()
                },
            )
            .unwrap();
        e.tree
            .set_style(
                c1_nid,
                TaffyStyle {
                    size: taffy::geometry::Size {
                        width: pt(80.0),
                        height: pt(12.0),
                    },
                    ..Default::default()
                },
            )
            .unwrap();
        e.tree
            .set_style(
                c2_nid,
                TaffyStyle {
                    size: taffy::geometry::Size {
                        width: pt(80.0),
                        height: pt(12.0),
                    },
                    ..Default::default()
                },
            )
            .unwrap();

        e.calculate(0, 80.0, Some(24.0)).unwrap();

        let r1 = e.computed(1).unwrap();
        let r2 = e.computed(2).unwrap();

        assert_eq!(
            r1,
            Rect {
                x: 0,
                y: 0,
                width: 80,
                height: 12
            }
        );
        assert_eq!(
            r2,
            Rect {
                x: 0,
                y: 12,
                width: 80,
                height: 12
            }
        );
    }

    // ═══════════════════════════════════════════════════════════════════════════
    // round_value_to_pixel_grid kernel — full branch-matrix unit tests
    //
    // Each case is hand-derived from the branch order in the source (lines
    // 443-458 at the time of writing).  Branch order matters; the most critical
    // invariant is that the fractial≈1 ceil fires BEFORE the force_floor guard.
    // ═══════════════════════════════════════════════════════════════════════════

    // (1) fractial ≈ 0 within epsilon (e.g. 5.00005) → floor to whole number
    // regardless of force flags (branch 1 fires first).
    #[test]
    fn kernel_fractional_near_zero_floors_to_whole() {
        // 5.00005 % 1.0 = 0.00005; inexact_equals(0.00005, 0.0) = true (< 0.0001)
        assert_eq!(round_value_to_pixel_grid(5.00005, false, false), 5.0);
        // force_ceil=true must not override branch 1
        assert_eq!(round_value_to_pixel_grid(5.00005, true, false), 5.0);
        // force_floor=true must not override branch 1
        assert_eq!(round_value_to_pixel_grid(5.00005, false, true), 5.0);
    }

    // (2) fractial ≈ 1 within epsilon (e.g. 4.99995) → ceil to whole number.
    // CRITICAL: this branch fires BEFORE force_floor, so even force_floor=true
    // must produce 5.0 (not 4.0).  This is the ordering the review most wants
    // guarded.
    #[test]
    fn kernel_fractional_near_one_ceils_before_force_floor() {
        // 4.99995 % 1.0 = 0.99995; inexact_equals(0.99995, 1.0) = true
        assert_eq!(round_value_to_pixel_grid(4.99995, false, false), 5.0);
        // force_floor=true must NOT override: branch 2 wins over branch 3
        assert_eq!(round_value_to_pixel_grid(4.99995, false, true), 5.0);
    }

    // (3) force_ceil with mid-fractional value → ceil.
    #[test]
    fn kernel_force_ceil_rounds_up() {
        // 4.3 % 1.0 = 0.3; not near 0/1; force_ceil=true → branch 2/3 → 5.0
        assert_eq!(round_value_to_pixel_grid(4.3, true, false), 5.0);
    }

    // (4) force_floor with mid-fractional value → floor.
    #[test]
    fn kernel_force_floor_rounds_down() {
        // 4.7 % 1.0 = 0.7; not near 0/1; force_floor=true → branch 3 → 4.0
        assert_eq!(round_value_to_pixel_grid(4.7, false, true), 4.0);
    }

    // (5) round-half-up: ties go toward +inf.
    #[test]
    fn kernel_round_half_up_tie() {
        // 4.5: fractial=0.5; inexact_equals(0.5, 0.5)=true → branch 4 → 5.0
        assert_eq!(round_value_to_pixel_grid(4.5, false, false), 5.0);
        // 4.49: fractial=0.49; not near 0/1; 0.49<0.5; inexact(0.49,0.5)=false → branch 5 → 4.0
        assert_eq!(round_value_to_pixel_grid(4.49, false, false), 4.0);
        // 4.51: fractial=0.51; 0.51>0.5 → branch 4 → 5.0
        assert_eq!(round_value_to_pixel_grid(4.51, false, false), 5.0);
    }

    // (5b) exact 0.5 tie via inexact_equals: 4.49995 → 5.0.
    // fractial=0.49995; inexact_equals(0.49995, 0.5) = |−0.00005| < 0.0001 = true → branch 4
    #[test]
    fn kernel_half_epsilon_tie_ceils() {
        assert_eq!(round_value_to_pixel_grid(4.49995, false, false), 5.0);
    }

    // (6) Negative values: the fractial<0 correction (+=1.0) normalises fmod
    // output into [0,1) before the branch tree.
    #[test]
    fn kernel_negative_values() {
        // -4.5 % 1.0 = -0.5 → +1.0 → 0.5; inexact(0.5,0.5)=true → branch 4 → -4.5+0.5 = -4.0
        assert_eq!(round_value_to_pixel_grid(-4.5, false, false), -4.0);
        // -4.3 % 1.0 = -0.3 → +1.0 → 0.7; 0.7>0.5 → branch 4 → -4.3+0.3 = -4.0
        assert_eq!(round_value_to_pixel_grid(-4.3, false, false), -4.0);
        // -4.7 % 1.0 = -0.7 → +1.0 → 0.3; 0.3<0.5; inexact(0.3,0.5)=false → branch 5 → -4.7-0.3 = -5.0
        assert_eq!(round_value_to_pixel_grid(-4.7, false, false), -5.0);
    }

    // ── inexact_equals boundary ───────────────────────────────────────────────
    // The operator is strict `<` (yoga/Comparison.h, mirrored at line 405).
    // |a−b| == 0.0001 exactly is NOT equal; just under is equal.

    #[test]
    fn inexact_equals_at_threshold_is_not_equal() {
        // |0.0001 − 0.0| = 0.0001; 0.0001 < 0.0001 is false
        assert!(!inexact_equals(0.0001, 0.0));
    }

    #[test]
    fn inexact_equals_just_under_threshold_is_equal() {
        // |0.00009 − 0.0| = 0.00009 < 0.0001 → true
        assert!(inexact_equals(0.00009, 0.0));
    }
}