sghtmltopdf 0.6.0

HTML to PDF renderer that does not depend on Chromium, WebKit or Gecko
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
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
//! The Block Formatting Context: width calculation against the containing block, plus the
//! vertical stacking of block elements (a simplified CSS2.1 sections 10.3.3 and 9.4.1).
use std::borrow::Cow;
use std::collections::HashMap;
use std::rc::Rc;

use crate::fonts::FontCollection;
use crate::html::NodeId;
use crate::pdf::PreparedImage;
use crate::style::{
    BorderCollapse, BorderStyle, BoxSizing, BreakBetween, BreakInside, CaptionSide, Clear,
    ComputedStyle, Display, Float, Length, LengthPercentage, LengthPercentageOrAuto, MaxSize,
    Position,
};

use super::box_tree::{BoxContent, ImageBoxContent, LayoutBox, RelativeInset, TableSection};
use super::flex::layout_flex;
use super::float_ctx::FloatContext;
use super::geometry::{EdgeSizes, FragmentPosition, Layout, Rect};
use super::grid::{layout_grid, LaidOutGrid};
use super::inline::{
    apply_text_overflow, clear_word_width_cache, finish_line, layout_inline_content, shape_run,
    LineBox,
};
use super::table::layout_table;

/// The fixed gap (px) between a marker (`list-style-position: outside`) and the content edge.
const LIST_MARKER_GAP: f32 = 8.0;

#[derive(Debug, Clone)]
pub struct LaidOutBox {
    pub node: Option<NodeId>,
    pub layout: Layout,
    /// This box's computed `break-before`/`break-after`/`break-inside`/`orphans`/`widows`
    /// (used only for pagination decisions; an anonymous box takes the `ComputedStyle`
    /// initial values, that is `auto`/`auto`/`auto`/2/2).
    pub fragmentation: FragmentationHints,
    /// Whether this box actually draws a background colour or borders.
    /// `paginate.rs` uses it to decide whether a container split across pages needs a
    /// decoration fragment generating (to reproduce the background and borders; see the
    /// module docs).
    pub has_visible_decoration: bool,
    /// Whether the element has `float: left/right`. `paginate.rs` uses it to decide whether
    /// to treat the box specially as out of flow.
    pub is_float: bool,
    pub content: LaidOutContent,
    /// The marker (bullet or number) for `display: list-item`.
    /// It is represented as a `LineBox` holding one already-shaped `TextRun`, so
    /// `pdf::document::render_line` is reused unchanged to draw it.
    /// When pagination splits this box across pages, it is kept only on the first fragment (`paginate.rs`).
    pub marker: Option<Box<LineBox>>,
    /// The href when this is an `<a href>` element's own box (see [`super::box_tree::LayoutBox::link`]).
    /// Its border box, on every page it is split across, becomes the link area.
    pub link: Option<Rc<str>>,
}

/// The CSS Fragmentation computed values carried by a [`LaidOutBox`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FragmentationHints {
    pub break_before: BreakBetween,
    pub break_after: BreakBetween,
    pub break_inside: BreakInside,
    pub orphans: u32,
    pub widows: u32,
}

impl From<&ComputedStyle> for FragmentationHints {
    fn from(style: &ComputedStyle) -> Self {
        Self {
            break_before: style.break_before,
            break_after: style.break_after,
            break_inside: style.break_inside,
            orphans: style.orphans,
            widows: style.widows,
        }
    }
}

impl Default for FragmentationHints {
    fn default() -> Self {
        Self::from(&ComputedStyle::default())
    }
}

#[derive(Debug, Clone)]
pub enum LaidOutContent {
    Blocks(Vec<LaidOutBox>),
    Inline(Vec<LineBox>),
    Table(LaidOutTable),
    /// `display: flex`
    Flex(Vec<LaidOutBox>),
    /// `display: grid`. It holds the row bands, which are the unit of pagination.
    Grid(LaidOutGrid),
    /// An `<img>`. `None` if the fetch or decode failed (treated as an empty replaced element, drawing nothing).
    Image(Option<Rc<PreparedImage>>),
}

/// A whole laid-out table (an optional caption plus the sequence of rows).
#[derive(Debug, Clone)]
pub struct LaidOutTable {
    /// The `Box` is needed to break the `LaidOutBox` -> `LaidOutContent::Table` ->
    /// `LaidOutTable` recursion by indirection.
    pub caption: Option<Box<LaidOutBox>>,
    pub caption_side: CaptionSide,
    pub rows: Vec<LaidOutTableRow>,
}

/// One laid-out table row.
#[derive(Debug, Clone)]
pub struct LaidOutTableRow {
    /// The original `display: table-row` element. `None` for an anonymous row (one created
    /// by the CSS anonymous box generation rules).
    pub node: Option<NodeId>,
    pub cells: Vec<LaidOutBox>,
    /// The section this row belongs to. `paginate` uses it to repeat the `<thead>` rows at
    /// the top of every page.
    pub section: TableSection,
    /// The row group element (`<thead>`/`<tbody>`/`<tfoot>`) the row sits in. `None` for a
    /// row placed directly in the table.
    pub group: Option<NodeId>,
}

/// One absolutely positioned box.
/// `laid` is already laid out against its containing block (in absolute coordinates), and
/// the pagination layer overlays it onto the page it belongs to.
#[derive(Debug, Clone)]
pub struct PositionedBox {
    pub laid: LaidOutBox,
    pub kind: PositionedKind,
}

/// Which kind of destination an absolutely positioned box has.
#[derive(Debug, Clone, Copy)]
pub enum PositionedKind {
    /// `position: fixed`. Repeated in the content area of every page, at the coordinates it
    /// was laid out at.
    Fixed,
    /// `position: absolute` with no positioned ancestor. Placed in the first page's content
    /// area, at the coordinates it was laid out at.
    AbsoluteInitial,
    /// `position: absolute` with a positioned ancestor. Placed on the page where the
    /// ancestor (`node`) first appears, offset by the difference between the ancestor's
    /// padding box position on the page and `padding_box_origin` (its top left at layout time).
    AbsoluteAncestor {
        node: NodeId,
        padding_box_origin: (f32, f32),
    },
}

/// The absolute positioning context carried around during layout.
/// Passed to descendants by `&mut`, like `float_ctx`.
pub(super) struct PosCtx<'a> {
    /// The current containing block for `absolute` (the nearest positioned ancestor's
    /// padding box, or the first page's content area if there is none).
    abs_cb: AbsCB,
    /// The containing block for `fixed`: the `(width, height)` of the page's content area.
    page_size: (f32, f32),
    /// The height of the containing block of the box about to be laid out, when it is
    /// definite (CSS 2.1 section 10.5). A percentage `height`/`min-height`/`max-height`
    /// resolves against it; `None` makes a percentage behave as `auto` (`0` for
    /// `min-height`, `none` for `max-height`).
    cb_height: Option<f32>,
    /// The absolutely positioned boxes collected.
    out: &'a mut Vec<PositionedBox>,
}

/// The containing block for `absolute`.
#[derive(Debug, Clone, Copy)]
enum AbsCB {
    /// The initial containing block (no positioned ancestor): the first page's content area.
    /// Its origin is `(0, 0)`.
    InitialPage,
    /// A positioned ancestor's padding box (in absolute coordinates).
    /// `height` is the padding box height when the ancestor's `height` is definite. It is
    /// only used to resolve percentage heights of the absolute box (`rect.height` stays 0).
    Ancestor {
        node: NodeId,
        rect: Rect,
        height: Option<f32>,
    },
}

impl<'a> PosCtx<'a> {
    /// The definite height of the current containing block, if any (see the field).
    pub(super) fn cb_height(&self) -> Option<f32> {
        self.cb_height
    }

    pub(super) fn new(out: &'a mut Vec<PositionedBox>, page_size: (f32, f32)) -> Self {
        Self {
            abs_cb: AbsCB::InitialPage,
            page_size,
            // The root's percentage heights stay `auto`. The initial containing block (the
            // page area) has a definite height in the spec, but a box with a definite
            // height is not fragmented across pages here, so `html, body { height: 100% }`
            // would cut the document off after the first page.
            cb_height: None,
            out,
        }
    }
}

/// The absolute-positioning-aware version of [`layout_document`]. Returns the normal-flow
/// `LaidOutBox` plus the list of absolutely positioned boxes ([`PositionedBox`]).
/// `page_size` is `(content_width, content_height)`, used as the containing block for `fixed`.
pub fn layout_document_positioned(
    root: &LayoutBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    page_size: (f32, f32),
) -> (LaidOutBox, Vec<PositionedBox>) {
    let mut absolutes = Vec::new();
    let mut pos = PosCtx::new(&mut absolutes, page_size);
    let laid =
        layout_document_from_positioned(root, styles, fonts, page_size.0, 0.0, 0.0, &mut pos);
    (laid, absolutes)
}

/// Lay the whole box tree out with the page width as the initial containing block.
pub fn layout_document(
    root: &LayoutBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    page_width: f32,
) -> LaidOutBox {
    layout_document_from(root, styles, fonts, page_width, 0.0, 0.0)
}

/// A variant of [`layout_document`] that starts laying out at `(start_x, start_y)` rather
/// than at the origin `(0.0, 0.0)`.
pub fn layout_document_from(
    root: &LayoutBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    containing_width: f32,
    start_x: f32,
    start_y: f32,
) -> LaidOutBox {
    // The backward-compatible entry point that collects no absolute positioning (for existing callers and tests).
    let mut absolutes = Vec::new();
    let mut pos = PosCtx::new(&mut absolutes, (containing_width, 0.0));
    layout_document_from_positioned(
        root,
        styles,
        fonts,
        containing_width,
        start_x,
        start_y,
        &mut pos,
    )
}

/// The absolute-positioning-aware version of [`layout_document_from`].
/// Absolutely positioned boxes are collected into `pos`.
#[allow(clippy::too_many_arguments)]
pub(super) fn layout_document_from_positioned(
    root: &LayoutBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    containing_width: f32,
    start_x: f32,
    start_y: f32,
    pos: &mut PosCtx,
) -> LaidOutBox {
    // One `FloatContext` is shared across an entire call to
    // `layout_document`/`layout_document_from`.
    let mut float_ctx = FloatContext::new();
    layout_box(
        root,
        styles,
        fonts,
        containing_width,
        &mut float_ctx,
        start_x,
        start_y,
        pos,
    )
}

/// Used for a `<caption>` (which goes through the normal width resolution; specific to
/// caption placement in `table.rs`) and for recursive calls within block.rs.
#[allow(clippy::too_many_arguments)]
pub(super) fn layout_box(
    b: &LayoutBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    containing_width: f32,
    float_ctx: &mut FloatContext,
    x: f32,
    y: f32,
    pos: &mut PosCtx,
) -> LaidOutBox {
    layout_box_impl(
        b,
        styles,
        fonts,
        containing_width,
        None,
        None,
        float_ctx,
        x,
        y,
        pos,
    )
}

/// Used when the content-box width is to be given directly, without going through the
/// normal `width` resolution (auto and margin calculation), as for a table cell
/// (specific to [`super::table`]).
#[allow(clippy::too_many_arguments)]
pub(super) fn layout_box_with_forced_width(
    b: &LayoutBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    containing_width: f32,
    forced_content_width: f32,
    float_ctx: &mut FloatContext,
    x: f32,
    y: f32,
    pos: &mut PosCtx,
) -> LaidOutBox {
    layout_box_impl(
        b,
        styles,
        fonts,
        containing_width,
        Some(forced_content_width),
        None,
        float_ctx,
        x,
        y,
        pos,
    )
}

/// The height-forcing extension of `layout_box_with_forced_width`: it forces both width and
/// height (specific to [`super::flex`]). Used in the final layout pass that produces the
/// real `LaidOutBox` at the width and height taffy settled for each flex item. Where
/// `align-items: stretch` (the default) had taffy stretch an item to the container's height,
/// this forcing makes the background colour and borders cover the stretched height too.
#[allow(clippy::too_many_arguments)]
pub(super) fn layout_box_with_forced_size(
    b: &LayoutBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    containing_width: f32,
    forced_content_width: f32,
    forced_content_height: f32,
    float_ctx: &mut FloatContext,
    x: f32,
    y: f32,
    pos: &mut PosCtx,
) -> LaidOutBox {
    layout_box_impl(
        b,
        styles,
        fonts,
        containing_width,
        Some(forced_content_width),
        Some(forced_content_height),
        float_ctx,
        x,
        y,
        pos,
    )
}

/// A wrapper specific to the measuring pass, whose result is thrown away. Used on the path
/// where a flex container lays the same item out repeatedly to return an intrinsic size to taffy.
///
/// Any `absolute`/`fixed` found while measuring is discarded. The final layout pass walks
/// the same descendants and collects them into the real `PosCtx`, so collecting here would
/// register the same box several times over.
#[allow(clippy::too_many_arguments)]
pub(super) fn measure_box_with_forced_width(
    b: &LayoutBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    containing_width: f32,
    forced_content_width: f32,
    float_ctx: &mut FloatContext,
    x: f32,
    y: f32,
) -> LaidOutBox {
    let mut sink = Vec::new();
    let mut pos = PosCtx::new(&mut sink, (0.0, 0.0));
    layout_box_with_forced_width(
        b,
        styles,
        fonts,
        containing_width,
        forced_content_width,
        float_ctx,
        x,
        y,
        &mut pos,
    )
}

/// Resolve `b`'s content width, margins, padding and borders (including auto-sizing for a
/// replaced element). Shared logic called both from the body of `layout_box_impl` and from
/// the advance width calculation for float placement (`layout_float_child`).
fn layout_out_of_flow_child(
    child: &LayoutBox,
    child_style: &ComputedStyle,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    pos: &mut PosCtx,
) {
    let (cb_rect, kind) = if child_style.position == Position::Fixed {
        (
            Rect {
                x: 0.0,
                y: 0.0,
                width: pos.page_size.0,
                height: pos.page_size.1,
            },
            PositionedKind::Fixed,
        )
    } else {
        match pos.abs_cb {
            AbsCB::InitialPage => (
                Rect {
                    x: 0.0,
                    y: 0.0,
                    width: pos.page_size.0,
                    height: pos.page_size.1,
                },
                PositionedKind::AbsoluteInitial,
            ),
            AbsCB::Ancestor { node, rect, .. } => (
                rect,
                PositionedKind::AbsoluteAncestor {
                    node,
                    padding_box_origin: (rect.x, rect.y),
                },
            ),
        }
    };

    let padding = resolve_padding(child_style, cb_rect.width);
    let border = resolve_border(child_style);
    let margin_left = resolve_lpa_or_zero(child_style.margin_left, cb_rect.width);
    let margin_right = resolve_lpa_or_zero(child_style.margin_right, cb_rect.width);
    let non_content_width =
        margin_left + border.left + padding.left + padding.right + border.right + margin_right;

    let has_left = !matches!(child_style.left, LengthPercentageOrAuto::Auto);
    let has_right = !matches!(child_style.right, LengthPercentageOrAuto::Auto);
    let left = resolve_lpa_or_zero(child_style.left, cb_rect.width);
    let right = resolve_lpa_or_zero(child_style.right, cb_rect.width);

    // Resolving the content width. `min-width`/`max-width` take effect as a clamp on the
    // used width found here.
    let content_width = match child_style.width {
        LengthPercentageOrAuto::LengthPercentage(lp) => {
            let w = resolve_lp(lp, cb_rect.width);
            if child_style.box_sizing == BoxSizing::BorderBox {
                (w - padding.left - padding.right - border.left - border.right).max(0.0)
            } else {
                w
            }
        }
        LengthPercentageOrAuto::Auto if has_left && has_right => {
            (cb_rect.width - left - right - non_content_width).max(0.0)
        }
        LengthPercentageOrAuto::Auto => {
            let avail = (cb_rect.width - non_content_width).max(0.0);
            // `width: auto` on an absolutely positioned box is shrink-to-fit too, so with a
            // settled height the width follows from `aspect-ratio`.
            aspect_ratio_width(child_style, &padding, &border).unwrap_or_else(|| {
                shrink_to_fit_content_width(child, styles, fonts, child_style, avail)
            })
        }
    };
    let content_width = clamp_used_width(
        child_style,
        cb_rect.width,
        padding.left + padding.right,
        border.left + border.right,
        content_width,
    );

    let margin_box_width = non_content_width + content_width;
    // The x of the top left of the margin box.
    let margin_box_x = if has_left {
        cb_rect.x + left
    } else if has_right {
        cb_rect.x + cb_rect.width - margin_box_width - right
    } else {
        cb_rect.x
    };
    let has_top = !matches!(child_style.top, LengthPercentageOrAuto::Auto);
    let has_bottom = !matches!(child_style.bottom, LengthPercentageOrAuto::Auto);
    let top = resolve_lpa_or_zero(child_style.top, cb_rect.height);
    let bottom = resolve_lpa_or_zero(child_style.bottom, cb_rect.height);
    // Lay out at `top` first (or the top of the cb if there is none).
    let margin_box_y = cb_rect.y + if has_top { top } else { 0.0 };

    // A percentage height resolves against the padding box of the containing block
    // (CSS 2.1 section 10.5), when that height is definite. `fixed` uses the page area.
    let saved_cb_height = pos.cb_height;
    pos.cb_height = if child_style.position == Position::Fixed {
        (pos.page_size.1 > 0.0).then_some(pos.page_size.1)
    } else {
        match pos.abs_cb {
            AbsCB::InitialPage => (pos.page_size.1 > 0.0).then_some(pos.page_size.1),
            AbsCB::Ancestor { height, .. } => height,
        }
    };
    let mut float_ctx = FloatContext::new();
    let mut laid = layout_box_with_forced_width(
        child,
        styles,
        fonts,
        cb_rect.width,
        content_width,
        &mut float_ctx,
        margin_box_x,
        margin_box_y,
        pos,
    );
    pos.cb_height = saved_cb_height;

    // A `bottom` setting (with no `top`) is repositioned to align to the bottom once the
    // laid-out height is known.
    if !has_top && has_bottom && cb_rect.height > 0.0 {
        let mbh = laid.layout.margin_box_height();
        let target_y = cb_rect.y + cb_rect.height - mbh - bottom;
        shift_box_y_in_place(&mut laid, margin_box_y - target_y);
    }
    pos.out.push(PositionedBox { laid, kind });
}

/// The shrink-to-fit (content-based) content width. Shared by the atomic box of
/// `display: inline-block` and by `width: auto` on a float. We have no CSS2.1 preferred
/// minimum width, so it is simplified to `min(preferred, available)` (content exceeding the
/// available width wraps), but never below the min-content width: CSS2.1 section 10.3.5 gives
/// `min(max(preferred minimum, available), preferred)`. For `white-space: nowrap` the
/// min-content width is the whole line, so the box overflows what contains it instead of
/// being narrower than its own text.
pub(super) fn shrink_to_fit_content_width(
    b: &LayoutBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    style: &ComputedStyle,
    available_width: f32,
) -> f32 {
    let _ = style;
    let natural = super::table::measure_natural_content_width(b, styles, fonts);
    if natural <= available_width {
        // The content fits, so min-content (never above natural) cannot change the result.
        return natural.max(0.0);
    }
    // The word caches behind the min-content measure are only valid for one font
    // collection, so they are cleared around the pass, as the table code does.
    clear_word_width_cache();
    let min_content = super::table::measure_min_content_width(b, styles, fonts);
    clear_word_width_cache();
    available_width.max(min_content.min(natural)).max(0.0)
}

fn resolve_box_geometry(
    b: &LayoutBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    containing_width: f32,
    forced_content_width: Option<f32>,
    cb_height: Option<f32>,
) -> (ComputedStyle, EdgeSizes, EdgeSizes, EdgeSizes, f32) {
    let mut style = box_style(b, styles).into_owned();
    resolve_percentage_heights(&mut style, cb_height);
    if let BoxContent::Image(image_content) = &b.content {
        apply_replaced_element_auto_size(&mut style, image_content, containing_width);
    }

    let padding = resolve_padding(&style, containing_width);
    let border = resolve_border(&style);
    let (content_width, margin_left, margin_right) = match forced_content_width {
        Some(w) => (
            w,
            resolve_lpa_or_zero(style.margin_left, containing_width),
            resolve_lpa_or_zero(style.margin_right, containing_width),
        ),
        // When a float has an explicit `width`, `resolve_width_and_horizontal_margins` is not
        // used: passing its "over-constrained" rule straight through (which recomputes
        // margin-right to fill the remaining width when width, margin-left and margin-right
        // are all non-auto, including the default 0 for an omitted `margin`; CSS2.1 section
        // 10.3.3's rule for normal flow) would let the huge recomputed margin-right leak into
        // `margin_box_width`, which is the advance width used for float placement.
        // Floats have no such recomputation rule (CSS2.1 section 10.3.5: an auto margin is
        // simply 0), so it is bypassed here.
        None if style.float != Float::None
            && !matches!(style.width, LengthPercentageOrAuto::Auto) =>
        {
            let width = resolve_lpa_or_zero(style.width, containing_width);
            // The conversion for `box-sizing: border-box`. The same adjustment as the
            // normal-flow `resolve_width_and_horizontal_margins` is applied here too.
            let width = if style.box_sizing == BoxSizing::BorderBox {
                (width - padding.left - padding.right - border.left - border.right).max(0.0)
            } else {
                width
            };
            (
                clamp_used_width(
                    &style,
                    containing_width,
                    padding.left + padding.right,
                    border.left + border.right,
                    width,
                ),
                resolve_lpa_or_zero(style.margin_left, containing_width),
                resolve_lpa_or_zero(style.margin_right, containing_width),
            )
        }
        // On a float, `width: auto` shrinks to the content (shrink-to-fit, CSS2.1 section
        // 10.3.5). It must not fall through to the normal-flow
        // `resolve_width_and_horizontal_margins`, which fills the containing width.
        // An auto margin is 0 on a float.
        None if style.float != Float::None => {
            let available = (containing_width
                - resolve_lpa_or_zero(style.margin_left, containing_width)
                - resolve_lpa_or_zero(style.margin_right, containing_width)
                - padding.left
                - padding.right
                - border.left
                - border.right)
                .max(0.0);
            // With a settled height, the width follows from `aspect-ratio`.
            let width = aspect_ratio_width(&style, &padding, &border).unwrap_or_else(|| {
                shrink_to_fit_content_width(b, styles, fonts, &style, available)
            });
            (
                clamp_used_width(
                    &style,
                    containing_width,
                    padding.left + padding.right,
                    border.left + border.right,
                    width,
                ),
                resolve_lpa_or_zero(style.margin_left, containing_width),
                resolve_lpa_or_zero(style.margin_right, containing_width),
            )
        }
        None => resolve_width_and_horizontal_margins(
            &style,
            containing_width,
            padding.left + padding.right,
            border.left + border.right,
        ),
    };
    let margin = EdgeSizes {
        top: resolve_lpa_or_zero(style.margin_top, containing_width),
        right: margin_right,
        bottom: resolve_lpa_or_zero(style.margin_bottom, containing_width),
        left: margin_left,
    };

    (style, padding, border, margin, content_width)
}

#[allow(clippy::too_many_arguments)]
fn layout_box_impl(
    b: &LayoutBox,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    containing_width: f32,
    forced_content_width: Option<f32>,
    forced_content_height: Option<f32>,
    float_ctx: &mut FloatContext,
    x: f32,
    y: f32,
    pos: &mut PosCtx,
) -> LaidOutBox {
    let (style, padding, border, mut margin, mut content_width) = resolve_box_geometry(
        b,
        styles,
        fonts,
        containing_width,
        forced_content_width,
        pos.cb_height,
    );

    let content_x = x + margin.left + border.left + padding.left;
    let mut content_y = y + margin.top + border.top + padding.top;

    // The visual offset of `position: relative`. The contents are laid out first
    // at unoffset coordinates, and the whole box (decoration, lines, child boxes
    // and marker) is translated at the end with `shift_box_*_in_place` (#29:
    // moving only the decoration leaves the contents behind). The `cursor_y` of
    // the following siblings is computed from `margin_box_height`, which does not
    // depend on the coordinates, so the shift does not affect the flow.
    let (offset_x, offset_y) = match RelativeInset::of(&style) {
        Some(inset) => resolve_relative_offset(&inset, content_width),
        None => (0.0, 0.0),
    };

    // A positioned element (relative/absolute/fixed) becomes the containing
    // block of an `absolute` descendant through its own padding box. The height
    // is not used, to avoid a circular dependency (placing against the bottom is
    // not supported). A relative offset moves the padding box too (CSS 2.1
    // §9.4.3), so it is folded in here.
    let saved_cb = pos.abs_cb;
    let saved_cb_height = pos.cb_height;
    // The height of this box's content box when it is definite (an explicit `height`, or a
    // percentage resolved against a definite containing block): what the percentage heights of
    // its children resolve against. The block-level content kinds below that do not take part
    // in this (table, flex and grid) reset it to `None` for their items.
    let own_definite_height = resolve_definite_content_height(&style, &padding, &border);
    if style.position != Position::Static {
        if let Some(node) = b.node {
            pos.abs_cb = AbsCB::Ancestor {
                node,
                rect: Rect {
                    x: content_x - padding.left + offset_x,
                    y: content_y - padding.top + offset_y,
                    width: padding.left + content_width + padding.right,
                    height: 0.0,
                },
                height: own_definite_height.map(|h| h + padding.top + padding.bottom),
            };
        }
    }

    pos.cb_height = match &b.content {
        // An anonymous block box (no element of its own) has no height of its own to offer,
        // so its children see the height of the box it was generated in.
        BoxContent::Blocks(_) | BoxContent::Inline(_) if b.node.is_none() => saved_cb_height,
        BoxContent::Blocks(_) | BoxContent::Inline(_) => own_definite_height,
        _ => None,
    };
    let (mut content, content_height) = match &b.content {
        BoxContent::Blocks(children) => {
            let mut cursor_y = content_y;
            let mut max_float_bottom = content_y;
            let mut laid_children: Vec<LaidOutBox> = Vec::with_capacity(children.len());
            for child in children {
                let child_style = box_style(child, styles);

                // `position: absolute`/`fixed` is out of flow (occupying no space).
                // It is placed against its containing block and collected into `pos.out`.
                if child_style.position.is_out_of_flow() {
                    layout_out_of_flow_child(child, &child_style, styles, fonts, pos);
                    continue;
                }

                if child_style.clear != Clear::None {
                    cursor_y = float_ctx.clearance(child_style.clear, cursor_y);
                }

                if child_style.float != Float::None {
                    // A float does not take part in the flow (CSS2.1 9.5): it is not subject
                    // to margin collapsing and does not advance `cursor_y`. `float_ctx` is
                    // shared with children and grandchildren, so later normal-flow and inline
                    // content in this BFC can see it for flow-around.
                    let child_laid = layout_float_child(
                        child,
                        &child_style,
                        styles,
                        fonts,
                        content_width,
                        float_ctx,
                        content_x,
                        cursor_y,
                        pos,
                    );
                    let float_top = child_laid.layout.content.y
                        - child_laid.layout.padding.top
                        - child_laid.layout.border.top
                        - child_laid.layout.margin.top;
                    max_float_bottom =
                        max_float_bottom.max(float_top + child_laid.layout.margin_box_height());
                    laid_children.push(child_laid);
                    continue;
                }

                let child_margin_top = resolve_lpa_or_zero(child_style.margin_top, content_width);

                // Margin collapsing between adjacent siblings (CSS2.1 section 8.3.1). The
                // previous sibling's margin-bottom and this child's margin-top are replaced by
                // a single gap: not their sum, but "the largest positive plus the smallest
                // negative". Floats do not take part in the flow and are excluded (we look for the previous non-float child).
                if let Some(prev) = laid_children.iter().rev().find(|c| !c.is_float) {
                    let prev_margin_bottom = prev.layout.margin.bottom;
                    let collapsed = collapse_adjacent_margins(prev_margin_bottom, child_margin_top);
                    cursor_y -= prev_margin_bottom + child_margin_top - collapsed;
                }

                let child_laid = layout_box(
                    child,
                    styles,
                    fonts,
                    content_width,
                    float_ctx,
                    content_x,
                    cursor_y,
                    pos,
                );
                cursor_y += child_laid.layout.margin_box_height();
                laid_children.push(child_laid);
            }
            // If a direct float child extends below the normal flow, extend the auto height
            // by that much (a shallow implementation of CSS2.1 10.6.7 that does not propagate
            // to grandchildren; a known simplification).
            let auto_height = cursor_y.max(max_float_bottom) - content_y;
            let height = resolve_used_height(&style, &padding, &border, content_width, auto_height);
            (LaidOutContent::Blocks(laid_children), height)
        }
        BoxContent::Inline(spans) => {
            let mut lines = layout_inline_content(
                spans,
                styles,
                fonts,
                content_width,
                content_x,
                content_y,
                Some(&*float_ctx),
                // An anonymous box has no style of its own (`style` holds the initial values).
                b.node.is_some().then_some(&style),
                pos,
            );
            // An inline-level `display: inline-block` box is moved to its final coordinates at
            // this point, once the line's position is settled.
            place_atomic_inlines(&mut lines);
            // `text-overflow: ellipsis` is applied as post-processing after line layout.
            apply_text_overflow(&mut lines, &style, content_width, fonts);
            let lines_height: f32 = lines.iter().map(|line| line.rect.height).sum();
            let height =
                resolve_used_height(&style, &padding, &border, content_width, lines_height);
            (LaidOutContent::Inline(lines), height)
        }
        BoxContent::Table(table) => {
            // A `display: table` cell establishes a new Block Formatting Context
            // (CSS2.1 9.4.1), so it is kept independent of the outer `float_ctx`.
            // `border-spacing` is mutually exclusive with `border-collapse: collapse`, so
            // under collapse it is squashed to 0 here before being passed on.
            let (h_spacing, v_spacing) = if style.border_collapse == BorderCollapse::Collapse {
                (0.0, 0.0)
            } else {
                (
                    style.border_spacing_horizontal.0,
                    style.border_spacing_vertical.0,
                )
            };
            let (laid_table, table_height, table_width) = layout_table(
                table,
                styles,
                fonts,
                content_width,
                style.table_layout,
                h_spacing,
                v_spacing,
                content_x,
                content_y,
                pos,
            );
            let height =
                resolve_used_height(&style, &padding, &border, content_width, table_height);
            // A table whose columns cannot fit (a `white-space: nowrap` cell wider than the
            // table's width) grows past it, so its own background and border cover them all.
            content_width = content_width.max(table_width);
            (LaidOutContent::Table(laid_table), height)
        }
        BoxContent::Grid(grid) => {
            // A grid container also establishes a new formatting context, like flex and
            // table.
            let (laid_grid, grid_height) = layout_grid(
                grid,
                styles,
                fonts,
                &style,
                content_width,
                content_x,
                content_y,
                pos,
            );
            let height = resolve_used_height(&style, &padding, &border, content_width, grid_height);
            (LaidOutContent::Grid(laid_grid), height)
        }
        BoxContent::Flex(flex) => {
            // Like `display: table`, a flex container establishes a new formatting context
            // (`float` has no effect on a flex item, per the CSS spec), so it is kept
            // independent of the outer `float_ctx`.
            let (items, flex_height) = layout_flex(
                flex,
                styles,
                fonts,
                &style,
                content_width,
                content_x,
                content_y,
                pos,
            );
            let height = resolve_used_height(&style, &padding, &border, content_width, flex_height);
            (LaidOutContent::Flex(items), height)
        }
        BoxContent::Image(image_content) => {
            // When `apply_replaced_element_auto_size` has run, the case where both widths
            // were auto has already been replaced with concrete Lengths, so `resolve_height`
            // returns `Some` (a height of zero being a sensible default when no intrinsic
            // size is available, that is when the fetch or decode failed).
            // The `min-height`/`max-height` clamps apply as for any other content kind, but
            // the aspect ratio is not preserved.
            let height = resolve_used_height(&style, &padding, &border, content_width, 0.0);
            (LaidOutContent::Image(image_content.image.clone()), height)
        }
    };
    // The descendants are laid out, so the containing block is restored.
    pos.abs_cb = saved_cb;
    pos.cb_height = saved_cb_height;
    // Reflect the height taffy settled directly in the final layout pass
    // (specific to `layout_box_with_forced_size`).
    let mut content_height = forced_content_height.unwrap_or(content_height);

    // Parent/child and empty-block margin collapsing. `layout.margin` becomes the effective
    // (collapsed) value, and `content.y`/`content_height` are adjusted to match. Parent/child
    // collapsing applies only to `height: auto` blocks (a known simplification).
    let height_is_auto =
        forced_content_height.is_none() && matches!(style.height, LengthPercentageOrAuto::Auto);
    apply_margin_collapse(
        &mut content,
        &mut content_height,
        &mut margin,
        &mut content_y,
        &border,
        &padding,
        height_is_auto,
    );

    let marker = b.marker.as_deref().and_then(|text| {
        layout_list_marker(text, &style, fonts, content_x, content_y).map(Box::new)
    });

    let mut laid = LaidOutBox {
        node: b.node,
        layout: Layout {
            content: Rect {
                x: content_x,
                y: content_y,
                width: content_width,
                height: content_height,
            },
            padding,
            border,
            margin,
            fragment: FragmentPosition::Whole,
        },
        fragmentation: FragmentationHints::from(&style),
        has_visible_decoration: has_visible_decoration(&style, &border),
        is_float: style.float != Float::None,
        content,
        marker,
        link: b.link.clone(),
    };
    if offset_x != 0.0 {
        shift_box_x_in_place(&mut laid, offset_x);
    }
    if offset_y != 0.0 {
        // The delta of `shift_box_y_in_place` is the amount to subtract, so
        // moving down means `-dy`.
        shift_box_y_in_place(&mut laid, -offset_y);
    }
    laid
}

/// Lay out the marker of a `display: list-item` (with `list-style-position: outside`, or
/// having fallen back from `inside` because of block children). The marker is simply placed
/// independently outside the content box, in the left gutter, so the same logic handles
/// `b`'s content whether it is `BoxContent::Inline` or `Blocks`.
///
/// The implementation reuses exactly the same shaping as an ordinary text run (`shape_run`)
/// and returns the result as a `LineBox` with a single `runs` entry. That lets the drawing
/// side (`pdf::document::render_line`) be reused entirely unchanged.
fn layout_list_marker(
    text: &str,
    style: &ComputedStyle,
    fonts: &FontCollection,
    content_x: f32,
    content_y: f32,
) -> Option<LineBox> {
    let first_char = text.chars().next()?;
    let font_index = fonts.select_for_char(
        &style.font_family,
        style.font_weight,
        style.font_style,
        first_char,
    )?;
    let run = shape_run(text, font_index, fonts, style);
    let width = run.width;
    let height = run.line_height;
    Some(finish_line(
        vec![run],
        Vec::new(),
        width,
        content_x - LIST_MARKER_GAP - width,
        content_y,
        height,
        fonts,
    ))
}

/// Place a float child. The width resolution happens twice, here in `resolve_box_geometry`
/// and again in the real layout, because `float_ctx.place` needs the margin box width before
/// it can decide the placement coordinates (and getting an accurate width requires resolving
/// auto-size for a replaced element such as `<img>`, so the precomputation cannot be skipped).
#[allow(clippy::too_many_arguments)]
fn layout_float_child(
    child: &LayoutBox,
    child_style: &ComputedStyle,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    containing_width: f32,
    float_ctx: &mut FloatContext,
    containing_left: f32,
    preferred_top: f32,
    pos: &mut PosCtx,
) -> LaidOutBox {
    let (_, padding, border, margin, child_content_width) =
        resolve_box_geometry(child, styles, fonts, containing_width, None, pos.cb_height);
    let margin_box_width = margin.left
        + border.left
        + padding.left
        + child_content_width
        + padding.right
        + border.right
        + margin.right;

    let (float_x, float_y) = float_ctx.place(
        child_style.float,
        preferred_top,
        containing_left,
        containing_left + containing_width,
        margin_box_width,
    );

    let child_laid = layout_box(
        child,
        styles,
        fonts,
        containing_width,
        float_ctx,
        float_x,
        float_y,
        pos,
    );
    float_ctx.register(
        child_style.float,
        float_x,
        float_y,
        margin_box_width,
        child_laid.layout.margin_box_height(),
    );
    child_laid
}

/// Resolves the visual offset `(dx, dy)` from the top/right/bottom/left of a
/// `position: relative` element. As in the CSS spec, `top` wins over `bottom`
/// and `left` over `right`. A percentage `top`/`bottom` is relative to the
/// height of the containing block, but that height is not settled yet (to avoid
/// a circular dependency), so it is treated as 0: a known simplification.
pub(super) fn resolve_relative_offset(inset: &RelativeInset, containing_width: f32) -> (f32, f32) {
    let resolve =
        |primary: LengthPercentageOrAuto, secondary: LengthPercentageOrAuto, basis: f32| {
            match primary {
                LengthPercentageOrAuto::LengthPercentage(lp) => resolve_lp(lp, basis),
                LengthPercentageOrAuto::Auto => match secondary {
                    LengthPercentageOrAuto::LengthPercentage(lp) => -resolve_lp(lp, basis),
                    LengthPercentageOrAuto::Auto => 0.0,
                },
            }
        };
    let dx = resolve(inset.left, inset.right, containing_width);
    let dy = resolve(inset.top, inset.bottom, 0.0);
    (dx, dy)
}

/// Whether the combination of `style` and `border` (the computed thicknesses) actually draws
/// anything. `true` when there is a background colour, or when any of the four edges has a
/// positive thickness and a `border-style` other than `none` (the same condition under which
/// `pdf::document::render_box_decoration` really draws).
pub(crate) fn has_visible_decoration(style: &ComputedStyle, border: &EdgeSizes) -> bool {
    if style.background_color.alpha > 0.0 {
        return true;
    }
    // An element with only a `background-image` (no background colour or borders) cannot be
    // reached by `collect_image_uses`/`render_box` and is never drawn unless `place_split`
    // includes it among the boxes it generates a decoration fragment for (a `LaidOutBox` with a `node`).
    if style.background_image.is_some() {
        return true;
    }
    [
        (border.top, style.border_top_style),
        (border.right, style.border_right_style),
        (border.bottom, style.border_bottom_style),
        (border.left, style.border_left_style),
    ]
    .into_iter()
    .any(|(width, border_style)| width > 0.0 && border_style != BorderStyle::None)
}

/// A box's computed style.
///
/// A real element's style is borrowed from `styles` as-is. A `ComputedStyle` is over 1KB and
/// holds a `font_family: Vec<String>`, so cloning it piles up heap allocations on every
/// layout (it is called three times per cell in a table).
/// Only a caller that wants to modify it clones, via `into_owned`.
pub(super) fn box_style<'a>(
    b: &LayoutBox,
    styles: &'a HashMap<NodeId, Rc<ComputedStyle>>,
) -> Cow<'a, ComputedStyle> {
    match b.node {
        Some(node) => Cow::Borrowed(&styles[&node]),
        // An anonymous box (CSS2.1 9.2.1.1): a block with no margins, padding or borders.
        None => Cow::Owned(ComputedStyle {
            display: Display::Block,
            ..ComputedStyle::default()
        }),
    }
}

pub(super) fn resolve_lp(lp: LengthPercentage, basis: f32) -> f32 {
    match lp {
        LengthPercentage::Length(px) => px,
        LengthPercentage::Percentage(fraction) => fraction * basis,
        LengthPercentage::Calc { px, percent } => px + percent * basis,
    }
}

pub(crate) fn resolve_lpa_or_zero(lpa: LengthPercentageOrAuto, basis: f32) -> f32 {
    match lpa {
        LengthPercentageOrAuto::Auto => 0.0,
        LengthPercentageOrAuto::LengthPercentage(lp) => resolve_lp(lp, basis),
    }
}

/// Clamping the used width by `min-width`/`max-width`.
///
/// They are applied `max` then `min`, so `min-width` wins when `min-width > max-width`
/// (the same result as the procedure in CSS2.1 section 10.4). Under `box-sizing: border-box`
/// the `min-*`/`max-*` values are border-box based too, so as with `width` the padding and
/// border are subtracted to bring them to content-box before comparing.
pub(crate) fn clamp_used_width(
    style: &ComputedStyle,
    containing_width: f32,
    padding_lr: f32,
    border_lr: f32,
    width: f32,
) -> f32 {
    let to_content_box = |v: f32| {
        if style.box_sizing == BoxSizing::BorderBox {
            (v - padding_lr - border_lr).max(0.0)
        } else {
            v
        }
    };

    let mut used = width;
    if let MaxSize::LengthPercentage(lp) = style.max_width {
        used = used.min(to_content_box(resolve_lp(lp, containing_width)));
    }
    used.max(to_content_box(resolve_lp(
        style.min_width,
        containing_width,
    )))
    .max(0.0)
}

/// Resolve the percentage `height`/`min-height`/`max-height` of `style` against the height of
/// its containing block (CSS 2.1 section 10.5), so the rest of the height logic only sees
/// lengths. `cb_height` is `None` when that height is not specified explicitly (depends on the
/// content): then a percentage `height` computes to `auto`, `min-height` to `0` and
/// `max-height` to `none`. A `calc()` mixing a length and a percentage follows the same rule.
pub(super) fn resolve_percentage_heights(style: &mut ComputedStyle, cb_height: Option<f32>) {
    let has_percent = |lp: LengthPercentage| match lp {
        LengthPercentage::Length(_) => false,
        LengthPercentage::Percentage(_) => true,
        LengthPercentage::Calc { percent, .. } => percent != 0.0,
    };
    let resolve = |lp: LengthPercentage| -> Option<LengthPercentage> {
        if !has_percent(lp) {
            return Some(lp);
        }
        cb_height.map(|h| LengthPercentage::Length(resolve_lp(lp, h)))
    };
    if let LengthPercentageOrAuto::LengthPercentage(lp) = style.height {
        style.height = match resolve(lp) {
            Some(lp) => LengthPercentageOrAuto::LengthPercentage(lp),
            None => LengthPercentageOrAuto::Auto,
        };
    }
    style.min_height = resolve(style.min_height).unwrap_or(LengthPercentage::Length(0.0));
    if let MaxSize::LengthPercentage(lp) = style.max_height {
        style.max_height = match resolve(lp) {
            Some(lp) => MaxSize::LengthPercentage(lp),
            None => MaxSize::None,
        };
    }
}

/// The content height of a box when its `height` is specified explicitly (percentages having
/// been resolved by [`resolve_percentage_heights`]), clamped by `min-height`/`max-height`.
/// `None` when the height depends on the content.
fn resolve_definite_content_height(
    style: &ComputedStyle,
    padding: &EdgeSizes,
    border: &EdgeSizes,
) -> Option<f32> {
    let padding_tb = padding.top + padding.bottom;
    let border_tb = border.top + border.bottom;
    let height = resolve_height(style, padding_tb, border_tb)?;
    Some(clamp_used_height(style, padding_tb, border_tb, height))
}

/// Clamping the used height by `min-height`/`max-height`. A percentage that
/// [`resolve_percentage_heights`] could not resolve has already become `0`/`none`, so only
/// lengths are left here.
pub(crate) fn clamp_used_height(
    style: &ComputedStyle,
    padding_tb: f32,
    border_tb: f32,
    height: f32,
) -> f32 {
    let to_content_box = |v: f32| {
        if style.box_sizing == BoxSizing::BorderBox {
            (v - padding_tb - border_tb).max(0.0)
        } else {
            v
        }
    };

    let mut used = height;
    if let MaxSize::LengthPercentage(lp) = style.max_height {
        if let Some(px) = definite_height_px(lp) {
            used = used.min(to_content_box(px));
        }
    }
    if let Some(px) = definite_height_px(style.min_height) {
        used = used.max(to_content_box(px));
    }
    used.max(0.0)
}

/// The absolute length (px) usable in the vertical direction. A percentage, or a `calc` with a
/// percentage component, returns `None` (is ignored): the containing block height is indefinite.
fn definite_height_px(lp: LengthPercentage) -> Option<f32> {
    match lp {
        LengthPercentage::Length(px) => Some(px),
        LengthPercentage::Percentage(_) => None,
        LengthPercentage::Calc { px, percent: 0.0 } => Some(px),
        LengthPercentage::Calc { .. } => None,
    }
}

pub(crate) fn resolve_padding(style: &ComputedStyle, basis: f32) -> EdgeSizes {
    EdgeSizes {
        top: resolve_lp(style.padding_top, basis),
        right: resolve_lp(style.padding_right, basis),
        bottom: resolve_lp(style.padding_bottom, basis),
        left: resolve_lp(style.padding_left, basis),
    }
}

/// An edge with `border-style: none` has a used value of `0` regardless of its `border-width`
/// (CSS2.1 8.5.3). That rounding has to be reflected in layout (width calculation) too.
pub(crate) fn resolve_border(style: &ComputedStyle) -> EdgeSizes {
    let width_or_zero = |width: Length, border_style: BorderStyle| {
        if border_style == BorderStyle::None {
            0.0
        } else {
            width.0
        }
    };
    EdgeSizes {
        top: width_or_zero(style.border_top_width, style.border_top_style),
        right: width_or_zero(style.border_right_width, style.border_right_style),
        bottom: width_or_zero(style.border_bottom_width, style.border_bottom_style),
        left: width_or_zero(style.border_left_width, style.border_left_style),
    }
}

/// The used height: the value chosen in the order "explicit `height`, then derived from
/// `aspect-ratio`, then `auto_height` (the height derived from the content)", clamped by
/// `min-height`/`max-height`.
pub(crate) fn resolve_used_height(
    style: &ComputedStyle,
    padding: &EdgeSizes,
    border: &EdgeSizes,
    content_width: f32,
    auto_height: f32,
) -> f32 {
    let padding_tb = padding.top + padding.bottom;
    let border_tb = border.top + border.bottom;
    let height = resolve_height(style, padding_tb, border_tb)
        .or_else(|| aspect_ratio_height(style, padding, border, content_width))
        .unwrap_or(auto_height);
    clamp_used_height(style, padding_tb, border_tb, height)
}

/// The content height derived from `aspect-ratio`. `None` if there is no ratio. The box the
/// ratio applies to follows `box-sizing`.
fn aspect_ratio_height(
    style: &ComputedStyle,
    padding: &EdgeSizes,
    border: &EdgeSizes,
    content_width: f32,
) -> Option<f32> {
    let ratio = style.aspect_ratio.ratio?;
    if style.box_sizing == BoxSizing::BorderBox {
        let border_box_width =
            content_width + padding.left + padding.right + border.left + border.right;
        Some(
            (border_box_width / ratio - padding.top - padding.bottom - border.top - border.bottom)
                .max(0.0),
        )
    } else {
        Some(content_width / ratio)
    }
}

/// The content width derived from `aspect-ratio`. Used where the height is settled and
/// `width: auto` is in a shrink-to-fit context (a float, `inline-block`, absolute positioning
/// or `<img>`). It is not called for `width: auto` on a normal-flow block, where stretch wins.
pub(crate) fn aspect_ratio_width(
    style: &ComputedStyle,
    padding: &EdgeSizes,
    border: &EdgeSizes,
) -> Option<f32> {
    let ratio = style.aspect_ratio.ratio?;
    let padding_tb = padding.top + padding.bottom;
    let border_tb = border.top + border.bottom;
    let content_height = resolve_height(style, padding_tb, border_tb)?;
    if style.box_sizing == BoxSizing::BorderBox {
        let border_box_height = content_height + padding_tb + border_tb;
        Some(
            (border_box_height * ratio - padding.left - padding.right - border.left - border.right)
                .max(0.0),
        )
    } else {
        Some(content_height * ratio)
    }
}

/// Return the `height` if it is given explicitly. `auto`, and a percentage (the containing
/// block's height being indefinite), give `None`, and the caller uses the content height
/// instead. Under `box-sizing: border-box` the value is the border-box height, so
/// `padding_tb`/`border_tb` are subtracted to bring it to content-box.
fn resolve_height(style: &ComputedStyle, padding_tb: f32, border_tb: f32) -> Option<f32> {
    let LengthPercentageOrAuto::LengthPercentage(lp) = style.height else {
        return None;
    };
    let px = definite_height_px(lp)?;
    Some(if style.box_sizing == BoxSizing::BorderBox {
        (px - padding_tb - border_tb).max(0.0)
    } else {
        px
    })
}

/// Only where both `width` and `height` of a replaced element (`<img>`) are `auto`, apply a
/// simplified version of CSS2.2 sections 10.3.2 and 10.6.2 (resolution from a replaced
/// element's intrinsic size): decide from the HTML attributes (`width`/`height`) first and the
/// intrinsic size (on a successful decode) second, deriving the other side from the ratio.
///
/// Where CSS gives exactly one of `width`/`height` explicitly, the other is derived from the
/// used ratio (the `aspect-ratio` setting, or the intrinsic ratio when there is none).
/// "A settled width with `height: auto`" is derived downstream by [`resolve_used_height`],
/// so nothing happens here.
pub(super) fn apply_replaced_element_auto_size(
    style: &mut ComputedStyle,
    image: &ImageBoxContent,
    containing_width: f32,
) {
    // Bake the intrinsic ratio into the computed style. The general logic downstream then
    // only has to say "use `style.aspect_ratio.ratio` if it is there".
    if style.aspect_ratio.auto {
        if let Some(ratio) = intrinsic_ratio(image) {
            style.aspect_ratio.ratio = Some(ratio);
        }
    }

    let width_is_auto = matches!(style.width, LengthPercentageOrAuto::Auto);
    let height_is_auto = matches!(style.height, LengthPercentageOrAuto::Auto);

    let padding = resolve_padding(style, containing_width);
    let border = resolve_border(style);

    if !width_is_auto {
        return;
    }
    if !height_is_auto {
        // A settled height with `width: auto`. `width: auto` on a replaced element is
        // shrink-to-fit (not an ordinary block's stretch), so the width follows from the ratio.
        if let Some(width) = aspect_ratio_width(style, &padding, &border) {
            style.width = LengthPercentageOrAuto::LengthPercentage(LengthPercentage::Length(width));
        }
        return;
    }

    // Both `auto`: decide from the HTML attributes (`width`/`height`) first and the intrinsic
    // size (on a successful decode) second, deriving the other side from the aspect ratio when
    // only one value is available (a simplified CSS2.2 sections 10.3.2 and 10.6.2).
    let attr_size = (
        image.attr_width.map(|w| w as f32),
        image.attr_height.map(|h| h as f32),
    );
    let intrinsic_size = image
        .image
        .as_ref()
        .map(|prepared| (prepared.width, prepared.height));

    let (width, height) = match attr_size {
        (Some(w), Some(h)) => (w, h),
        (Some(w), None) => (
            w,
            derive_via_aspect_ratio(w, intrinsic_size.map(|(iw, ih)| (ih, iw))),
        ),
        (None, Some(h)) => (derive_via_aspect_ratio(h, intrinsic_size), h),
        (None, None) => intrinsic_size.unwrap_or((0.0, 0.0)),
    };

    // An `aspect-ratio` given without `auto` (`aspect-ratio: 16 / 9`, say) wins over the
    // intrinsic ratio. The width stays intrinsic and only the height is redecided by the ratio.
    let height = if style.aspect_ratio.auto {
        height
    } else {
        aspect_ratio_height(style, &padding, &border, width).unwrap_or(height)
    };

    // HTML `width`/`height` attributes are presentational hints, i.e. not `auto` in CSS terms,
    // so only a size taken from the image itself goes through the ratio-preserving table.
    // Clamping the two axes independently afterwards would distort the image.
    let (width, height) = if attr_size == (None, None) {
        let (w, h) =
            constrain_replaced_size(style, containing_width, &padding, &border, width, height);
        // `width`/`height` are read as border-box lengths under `box-sizing: border-box`, but
        // a size taken from the image is the content box.
        if style.box_sizing == BoxSizing::BorderBox {
            (
                w + padding.left + padding.right + border.left + border.right,
                h + padding.top + padding.bottom + border.top + border.bottom,
            )
        } else {
            (w, h)
        }
    } else {
        (width, height)
    };

    style.width = LengthPercentageOrAuto::LengthPercentage(LengthPercentage::Length(width));
    style.height = LengthPercentageOrAuto::LengthPercentage(LengthPercentage::Length(height));
}

/// The content-box `(width, height)` a replaced element with `width` and `height` both
/// `auto` settles on, for callers that size it before laying it out (a flex or grid item
/// measured by taffy). `None` when either of them is set.
pub(super) fn replaced_auto_content_size(
    style: &ComputedStyle,
    image: &ImageBoxContent,
    containing_width: f32,
) -> Option<(f32, f32)> {
    if !matches!(style.width, LengthPercentageOrAuto::Auto)
        || !matches!(style.height, LengthPercentageOrAuto::Auto)
    {
        return None;
    }
    let mut style = style.clone();
    apply_replaced_element_auto_size(&mut style, image, containing_width);
    let width = resolve_lpa_or_zero(style.width, containing_width);
    let height = resolve_lpa_or_zero(style.height, containing_width);
    if style.box_sizing == BoxSizing::BorderBox {
        let padding = resolve_padding(&style, containing_width);
        let border = resolve_border(&style);
        Some((
            (width - padding.left - padding.right - border.left - border.right).max(0.0),
            (height - padding.top - padding.bottom - border.top - border.bottom).max(0.0),
        ))
    } else {
        Some((width, height))
    }
}

/// Resolve `min-width`/`max-width`/`min-height`/`max-height` of a replaced element whose
/// `width` and `height` are both `auto`, keeping the aspect ratio where the constraints allow
/// (the table in CSS2.2 section 10.4). Returns the content-box `(width, height)`.
///
/// The limits are brought to content-box under `box-sizing: border-box` in the same way as
/// [`clamp_used_width`]/[`clamp_used_height`], and a percentage `min-height`/`max-height` is
/// ignored for the same reason (the containing block's height is indefinite).
fn constrain_replaced_size(
    style: &ComputedStyle,
    containing_width: f32,
    padding: &EdgeSizes,
    border: &EdgeSizes,
    width: f32,
    height: f32,
) -> (f32, f32) {
    if width <= 0.0 || height <= 0.0 {
        return (width, height);
    }

    let padding_lr = padding.left + padding.right;
    let border_lr = border.left + border.right;
    let padding_tb = padding.top + padding.bottom;
    let border_tb = border.top + border.bottom;
    let border_box = style.box_sizing == BoxSizing::BorderBox;
    let to_content_w = |v: f32| {
        if border_box {
            (v - padding_lr - border_lr).max(0.0)
        } else {
            v
        }
    };
    let to_content_h = |v: f32| {
        if border_box {
            (v - padding_tb - border_tb).max(0.0)
        } else {
            v
        }
    };

    let min_w = to_content_w(resolve_lp(style.min_width, containing_width));
    let max_w = match style.max_width {
        MaxSize::LengthPercentage(lp) => to_content_w(resolve_lp(lp, containing_width)),
        MaxSize::None => f32::INFINITY,
    }
    .max(min_w);
    let min_h = definite_height_px(style.min_height)
        .map(to_content_h)
        .unwrap_or(0.0);
    let max_h = match style.max_height {
        MaxSize::LengthPercentage(lp) => definite_height_px(lp).map(to_content_h),
        MaxSize::None => None,
    }
    .unwrap_or(f32::INFINITY)
    .max(min_h);

    let (w, h) = (width, height);
    match (w > max_w, w < min_w, h > max_h, h < min_h) {
        (true, _, true, _) if max_w / w <= max_h / h => (max_w, (max_w * h / w).max(min_h)),
        (true, _, true, _) => ((max_h * w / h).max(min_w), max_h),
        (_, true, _, true) if min_w / w <= min_h / h => ((min_h * w / h).min(max_w), min_h),
        (_, true, _, true) => (min_w, (min_w * h / w).min(max_h)),
        (_, true, true, _) => (min_w, max_h),
        (true, _, _, true) => (max_w, min_h),
        (true, _, _, _) => (max_w, (max_w * h / w).max(min_h)),
        (_, true, _, _) => (min_w, (min_w * h / w).min(max_h)),
        (_, _, true, _) => ((max_h * w / h).max(min_w), max_h),
        (_, _, _, true) => ((min_h * w / h).min(max_w), min_h),
        _ => (w, h),
    }
}

/// The image's intrinsic aspect ratio (`width / height`). `None` when it has not been
/// decoded, or when the height is 0.
fn intrinsic_ratio(image: &ImageBoxContent) -> Option<f32> {
    let prepared = image.image.as_ref()?;
    (prepared.height > 0.0).then(|| prepared.width / prepared.height)
}

/// From `known` (the length of one known side), derive the other side preserving the aspect
/// ratio, using `ratio_basis` (the intrinsic length of the unknown side and of the known one).
/// Returns 0 when there is no intrinsic size (the decode failed) or the known side's
/// intrinsic length is 0 (which the caller reads as "size unknown").
fn derive_via_aspect_ratio(known: f32, ratio_basis: Option<(f32, f32)>) -> f32 {
    match ratio_basis {
        Some((other_intrinsic, known_intrinsic)) if known_intrinsic > 0.0 => {
            known * other_intrinsic / known_intrinsic
        }
        _ => 0.0,
    }
}

/// Apply parent/child and empty-block margin collapsing.
///
/// `margin` becomes the effective (collapsed) value, and `content.y` and `content_height`
/// are adjusted to match. By storing the returned effective `margin` on the `LaidOutBox`
/// as-is, the caller lets an ancestor's adjacent-sibling collapsing loop chain naturally into multi-level collapsing.
fn apply_margin_collapse(
    content: &mut LaidOutContent,
    content_height: &mut f32,
    margin: &mut EdgeSizes,
    content_y: &mut f32,
    border: &EdgeSizes,
    padding: &EdgeSizes,
    height_is_auto: bool,
) {
    // An empty block: height 0, no border or padding, no children. Its own top and bottom
    // margins collapse into one (moved up so `margin_box_height` is that single collapsed
    // value). It then collapses with the sibling above against that value, preventing a double margin.
    let content_is_empty = match content {
        LaidOutContent::Blocks(children) | LaidOutContent::Flex(children) => children.is_empty(),
        // A `<div></div>` with no children becomes an empty `Inline`.
        LaidOutContent::Inline(lines) => lines.is_empty(),
        LaidOutContent::Grid(grid) => grid.rows.iter().all(|row| row.items.is_empty()),
        LaidOutContent::Table(_) | LaidOutContent::Image(_) => false,
    };
    let is_empty_block = *content_height == 0.0
        && border.top == 0.0
        && border.bottom == 0.0
        && padding.top == 0.0
        && padding.bottom == 0.0
        && content_is_empty;
    if is_empty_block {
        let collapsed = collapse_adjacent_margins(margin.top, margin.bottom);
        margin.top = collapsed;
        margin.bottom = 0.0;
        return;
    }

    let LaidOutContent::Blocks(children) = content else {
        return;
    };

    // Parent and first child: with no top boundary on the parent (no border-top or
    // padding-top), the first non-float child's effective `margin-top` is lifted out of the parent and collapsed.
    if border.top == 0.0 && padding.top == 0.0 && height_is_auto {
        if let Some(first_top) = children
            .iter()
            .find(|c| !c.is_float)
            .map(|c| c.layout.margin.top)
        {
            let effective = collapse_adjacent_margins(margin.top, first_top);
            // Every child moves up by however much the first child's `margin-top` left the
            // parent's content. delta <= 0.
            let child_delta = effective - first_top - margin.top;
            for child in children.iter_mut() {
                shift_box_y_in_place(child, -child_delta);
            }
            *content_y += effective - margin.top;
            *content_height -= first_top;
            margin.top = effective;
        }
    }

    // Parent and last child: with no bottom boundary on the parent (no border-bottom,
    // padding-bottom or explicit height), the last non-float child's `margin-bottom` is
    // lifted out of the parent and collapsed.
    if border.bottom == 0.0 && padding.bottom == 0.0 && height_is_auto {
        if let Some(last_bottom) = children
            .iter()
            .rev()
            .find(|c| !c.is_float)
            .map(|c| c.layout.margin.bottom)
        {
            let effective = collapse_adjacent_margins(margin.bottom, last_bottom);
            // The last child's margin-bottom leaves the parent's content, so it shrinks by that much.
            *content_height -= last_bottom;
            margin.bottom = effective;
        }
    }
}

/// Find the gap resulting from collapsing two adjacent margins (CSS2.1 section 8.3.1).
/// With both non-negative it is the larger; with both negative it is the smaller (the larger
/// in absolute value); with mixed signs it is their plain sum (the largest positive plus the smallest negative).
fn collapse_adjacent_margins(a: f32, b: f32) -> f32 {
    let positive = a.max(0.0).max(b.max(0.0));
    let negative = a.min(0.0).min(b.min(0.0));
    positive + negative
}

/// A simplified version of CSS2.1 section 10.3.3 (block-level, non-replaced elements).
/// `margin-left + border-left + padding-left + width + padding-right + border-right + margin-right
/// = the containing block's width`, fill in whichever items are `auto`.
pub(crate) fn resolve_width_and_horizontal_margins(
    style: &ComputedStyle,
    containing_width: f32,
    padding_lr: f32,
    border_lr: f32,
) -> (f32, f32, f32) {
    let (width, margin_left, margin_right) =
        solve_horizontal(style, containing_width, padding_lr, border_lr, None);

    // Clamp by `min-width`/`max-width`, and if the value changed, re-solve the horizontal
    // equation treating that width as though it had been given explicitly (CSS2.1 section
    // 10.4). Without that, a setting such as `width: auto; max-width: 600px; margin: 0 auto`
    // would keep the margin autos that the auto-width branch had squashed to 0, and never centre.

    let clamped = clamp_used_width(style, containing_width, padding_lr, border_lr, width);
    if clamped == width {
        return (width, margin_left, margin_right);
    }
    solve_horizontal(
        style,
        containing_width,
        padding_lr,
        border_lr,
        Some(clamped),
    )
}

/// Solve CSS2.1 section 10.3.3's horizontal equation (margin-left + border + padding +
/// width + margin-right = the containing width). Passing `Some` for `used_width` treats that
/// value (content-box based and already converted) as an explicitly given `width`
/// (for re-solving after the min/max width clamp).
fn solve_horizontal(
    style: &ComputedStyle,
    containing_width: f32,
    padding_lr: f32,
    border_lr: f32,
    used_width: Option<f32>,
) -> (f32, f32, f32) {
    let margin_left_is_auto = matches!(style.margin_left, LengthPercentageOrAuto::Auto);
    let margin_right_is_auto = matches!(style.margin_right, LengthPercentageOrAuto::Auto);

    let specified_width = match used_width {
        Some(w) => Some(w),
        None if matches!(style.width, LengthPercentageOrAuto::Auto) => None,
        None => {
            // Under `box-sizing: border-box` the value is the border-box width, so padding
            // and border are subtracted to bring it to content-box before it is handed to the
            // existing equation.
            let width = resolve_lpa_or_zero(style.width, containing_width);
            Some(if style.box_sizing == BoxSizing::BorderBox {
                (width - padding_lr - border_lr).max(0.0)
            } else {
                width
            })
        }
    };

    let Some(width) = specified_width else {
        let margin_left = resolve_lpa_or_zero(style.margin_left, containing_width);
        let margin_right = resolve_lpa_or_zero(style.margin_right, containing_width);
        let width =
            (containing_width - margin_left - border_lr - padding_lr - margin_right).max(0.0);
        return (width, margin_left, margin_right);
    };

    let remaining = (containing_width - border_lr - padding_lr - width).max(0.0);

    match (margin_left_is_auto, margin_right_is_auto) {
        (true, true) => {
            let half = remaining / 2.0;
            (width, half, half)
        }
        (true, false) => {
            let margin_right = resolve_lpa_or_zero(style.margin_right, containing_width);
            (width, (remaining - margin_right).max(0.0), margin_right)
        }
        (false, true) => {
            let margin_left = resolve_lpa_or_zero(style.margin_left, containing_width);
            (width, margin_left, (remaining - margin_left).max(0.0))
        }
        (false, false) => {
            // Over-constrained (CSS2.1 section 10.3.3): where width, margin-left and
            // margin-right are all given explicitly, the margin-right value is ignored and
            // its used value is recomputed so that the equation (margin-left + border/padding
            // + width + margin-right = the containing width) holds exactly (it may come out
            // negative). Under `direction: rtl` margin-left should be recomputed instead, but
            // rtl itself is unsupported, so ltr is always assumed.
            let margin_left = resolve_lpa_or_zero(style.margin_left, containing_width);
            let margin_right = containing_width - border_lr - padding_lr - width - margin_left;
            (width, margin_left, margin_right)
        }
    }
}

/// Return a copy of `b`'s whole subtree with its Y coordinates translated by `delta`.
/// `paginate.rs` uses it to convert from continuous whole-page coordinates to within-page
/// coordinates (subtracting `delta`). `table.rs` also uses it to place a caption for
/// `caption-side: bottom` (passing a negative `delta` to move it downwards).
/// Move each line's atomic inline boxes (`display: inline-block`) to match the line's
/// settled position (`line.rect` and the baseline).
///
/// `layout::inline` lays their contents out before the line's vertical position is known
/// (at the origin 0,0), so they are all translated here. Vertically they are placed so that
/// the bottom of the margin box sits on the baseline.
fn place_atomic_inlines(lines: &mut [LineBox]) {
    for line in lines.iter_mut() {
        let baseline_y = line.rect.y + line.baseline;
        for atomic in line.atomics.iter_mut() {
            // The target position of the top left of the margin box.
            let target_x = line.rect.x + atomic.x_offset;
            let target_y = baseline_y - atomic.baseline_shift - atomic.margin_box_height
                + atomic.baseline_from_bottom;
            // The current top left of the margin box (laid out at the origin 0, so it follows
            // from the content coordinates minus margin/border/padding).
            let layout = atomic.content.layout;
            let current_x =
                layout.content.x - layout.padding.left - layout.border.left + -layout.margin.left;
            let current_y =
                layout.content.y - layout.padding.top - layout.border.top - layout.margin.top;
            // Note that `shift_box_y`'s `delta` is an amount to subtract (`shift_rect_y` does
            // `y -= delta`), whereas `shift_box_x`'s is an amount to add.
            shift_box_y_in_place(&mut atomic.content, current_y - target_y);
            shift_box_x_in_place(&mut atomic.content, target_x - current_x);
        }
    }
}

/// The x-direction counterpart of [`shift_box_y`] (used for horizontal placement of atomic inline boxes).
pub(super) fn shift_box_x(b: &LaidOutBox, delta: f32) -> LaidOutBox {
    let mut shifted = b.clone();
    shift_box_x_in_place(&mut shifted, delta);
    shifted
}

/// The in-place version of [`shift_box_x`] (for the same reason as [`shift_box_y_in_place`]).
pub(super) fn shift_box_x_in_place(b: &mut LaidOutBox, delta: f32) {
    b.layout.content.x += delta;
    if let Some(marker) = &mut b.marker {
        marker.rect.x += delta;
    }

    match &mut b.content {
        LaidOutContent::Blocks(children) | LaidOutContent::Flex(children) => {
            for child in children.iter_mut() {
                shift_box_x_in_place(child, delta);
            }
        }
        LaidOutContent::Grid(grid) => {
            for row in grid.rows.iter_mut() {
                for item in row.items.iter_mut() {
                    shift_box_x_in_place(item, delta);
                }
            }
        }
        LaidOutContent::Inline(lines) => {
            for line in lines.iter_mut() {
                line.rect.x += delta;
                for atomic in line.atomics.iter_mut() {
                    shift_box_x_in_place(&mut atomic.content, delta);
                }
            }
        }
        LaidOutContent::Table(table) => {
            if let Some(caption) = &mut table.caption {
                shift_box_x_in_place(caption, delta);
            }
            for row in table.rows.iter_mut() {
                for cell in row.cells.iter_mut() {
                    shift_box_x_in_place(cell, delta);
                }
            }
        }
        LaidOutContent::Image(_) => {}
    }
}

pub(super) fn shift_box_y(b: &LaidOutBox, delta: f32) -> LaidOutBox {
    let mut shifted = b.clone();
    shift_box_y_in_place(&mut shifted, delta);
    shifted
}

/// The in-place version of [`shift_box_y`].
///
/// Cloning the subtree at every level of the recursion would rebuild the same data once per
/// level, inflating both the time and the peak memory for nothing. The move can be done on a
/// borrow, so the caller clones once, only when it has to.
pub(super) fn shift_box_y_in_place(b: &mut LaidOutBox, delta: f32) {
    shift_rect_y(&mut b.layout.content, delta);
    if let Some(marker) = &mut b.marker {
        shift_rect_y(&mut marker.rect, delta);
    }

    match &mut b.content {
        LaidOutContent::Blocks(children) | LaidOutContent::Flex(children) => {
            for child in children.iter_mut() {
                shift_box_y_in_place(child, delta);
            }
        }
        LaidOutContent::Grid(grid) => {
            for row in grid.rows.iter_mut() {
                // A row band's top and bottom live in the same coordinate space
                // as the items in it, so they move the way `shift_rect_y` does:
                // by subtracting `delta`.
                row.top -= delta;
                row.bottom -= delta;
                for item in row.items.iter_mut() {
                    shift_box_y_in_place(item, delta);
                }
            }
        }
        LaidOutContent::Inline(lines) => {
            for line in lines.iter_mut() {
                shift_rect_y(&mut line.rect, delta);
                // The atomic boxes in a line move with the line.
                for atomic in line.atomics.iter_mut() {
                    shift_box_y_in_place(&mut atomic.content, delta);
                }
            }
        }
        LaidOutContent::Table(table) => {
            if let Some(caption) = &mut table.caption {
                shift_box_y_in_place(caption, delta);
            }
            for row in table.rows.iter_mut() {
                for cell in row.cells.iter_mut() {
                    shift_box_y_in_place(cell, delta);
                }
            }
        }
        // Translating `b.layout.content` (at the top of this function) is enough. An image
        // has no child that carries a Rect of its own, unlike the lines of an `Inline`.
        LaidOutContent::Image(_) => {}
    }
}

fn shift_rect_y(rect: &mut Rect, delta: f32) {
    rect.y -= delta;
}

/// Shift only `b`'s contents (its child boxes, lines, or table rows and cells) vertically,
/// leaving `b`'s own position (`b.layout`) unchanged. It is deliberately distinct from
/// `shift_box_y`, which translates everything including the box itself: in the table cell
/// `vertical-align` implementation, the cell's own height and position are already settled by
/// the row height equalisation and must not change, while the content inside does need moving.
pub(super) fn shift_content_vertical(b: &LaidOutBox, delta: f32) -> LaidOutBox {
    let mut b = b.clone();

    match &mut b.content {
        LaidOutContent::Blocks(children) | LaidOutContent::Flex(children) => {
            for child in children.iter_mut() {
                *child = shift_box_y(child, delta);
            }
        }
        LaidOutContent::Grid(grid) => {
            for row in grid.rows.iter_mut() {
                row.top -= delta;
                row.bottom -= delta;
                for item in row.items.iter_mut() {
                    *item = shift_box_y(item, delta);
                }
            }
        }
        LaidOutContent::Inline(lines) => {
            for line in lines.iter_mut() {
                shift_rect_y(&mut line.rect, delta);
                // The atomic boxes in a line move with the line.
                for atomic in line.atomics.iter_mut() {
                    atomic.content = shift_box_y(&atomic.content, delta);
                }
            }
        }
        LaidOutContent::Table(table) => {
            if let Some(caption) = &mut table.caption {
                **caption = shift_box_y(caption, delta);
            }
            for row in table.rows.iter_mut() {
                for cell in row.cells.iter_mut() {
                    *cell = shift_box_y(cell, delta);
                }
            }
        }
        // An `Image` has no child carrying a Rect of its own, unlike the lines of an
        // `Inline`, so there is nothing to move (the `vertical-align` of an image nested in a
        // cell is left to moving the cell's whole content as one block).
        LaidOutContent::Image(_) => {}
    }

    b
}

#[cfg(test)]
mod tests {
    use super::super::box_tree::build_box_tree;
    use super::*;
    use crate::fonts::Font;
    use crate::html::{self, Dom, NodeData};
    use crate::pdf::{ImagePlane, PlaneColorSpace};
    use crate::style::{compute_styles, parse_stylesheet, user_agent_stylesheet, Stylesheet};

    const TEST_FONT_PATH: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fonts/DejaVuSans.ttf");

    fn test_fonts() -> FontCollection {
        FontCollection::new(vec![
            Font::load(TEST_FONT_PATH).expect("should load bundled test font")
        ])
    }

    fn find_all(dom: &Dom, id: NodeId, tag: &str, out: &mut Vec<NodeId>) {
        if let NodeData::Element { name, .. } = &dom.node(id).data {
            if &*name.local == tag {
                out.push(id);
            }
        }
        for child in dom.children(id) {
            find_all(dom, child, tag, out);
        }
    }

    fn find_box(b: &LayoutBox, target: NodeId) -> Option<&LayoutBox> {
        if b.node == Some(target) {
            return Some(b);
        }
        if let BoxContent::Blocks(children) = &b.content {
            for child in children {
                if let Some(found) = find_box(child, target) {
                    return Some(found);
                }
            }
        }
        None
    }

    fn find_laid_out(b: &LaidOutBox, target: NodeId) -> Option<&LaidOutBox> {
        if b.node == Some(target) {
            return Some(b);
        }
        if let LaidOutContent::Blocks(children) = &b.content {
            for child in children {
                if let Some(found) = find_laid_out(child, target) {
                    return Some(found);
                }
            }
        }
        None
    }

    #[test]
    fn display_none_excludes_element_and_subtree() {
        let dom = html::parse(
            br#"<div><p class="hidden">hidden</p><p class="visible">visible</p></div>"#,
        );
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(".hidden { display: none; }");
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);

        let mut ps = Vec::new();
        find_all(&dom, dom.document(), "p", &mut ps);
        let (hidden_p, visible_p) = (ps[0], ps[1]);

        assert!(find_box(&tree, hidden_p).is_none());
        assert!(find_box(&tree, visible_p).is_some());
    }

    #[test]
    fn mixed_block_and_inline_children_get_anonymous_block_wrapping() {
        let dom = html::parse(br#"<div class="outer">before <p>P</p> after</div>"#);
        let ua = user_agent_stylesheet();
        let author = Stylesheet::default();
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let mut ps = Vec::new();
        find_all(&dom, dom.document(), "p", &mut ps);

        let div_box = find_box(&tree, divs[0]).expect("div box not found");
        let BoxContent::Blocks(children) = &div_box.content else {
            panic!("expected block container")
        };
        assert_eq!(children.len(), 3, "before-text / <p> / after-text");
        let joined_text = |content: &BoxContent| match content {
            BoxContent::Inline(spans) => spans.iter().map(|s| s.text.as_str()).collect::<String>(),
            BoxContent::Blocks(_)
            | BoxContent::Table(_)
            | BoxContent::Flex(_)
            | BoxContent::Grid(_)
            | BoxContent::Image(_) => {
                panic!("expected inline content")
            }
        };
        assert_eq!(joined_text(&children[0].content).trim(), "before");
        assert_eq!(children[1].node, Some(ps[0]));
        assert_eq!(joined_text(&children[2].content).trim(), "after");
    }

    #[test]
    fn auto_width_fills_containing_block_minus_margins() {
        let dom = html::parse(br#"<div class="box"></div>"#);
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(".box { margin: 10px; }");
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let div_box = find_laid_out(&laid, divs[0]).expect("div box not found");

        // html: no margin, padding or border -> content_width=800
        // body: the UA default margin of 8px -> content_width=784
        // div: margin:10px → content_width=764
        assert_eq!(div_box.layout.margin.left, 10.0);
        assert_eq!(div_box.layout.content.width, 764.0);
        assert_eq!(div_box.layout.content.x, 18.0);
    }

    #[test]
    fn auto_margins_center_element_with_explicit_width() {
        let dom = html::parse(br#"<div class="centered"></div>"#);
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(".centered { width: 400px; margin: 0 auto; }");
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let div_box = find_laid_out(&laid, divs[0]).expect("div box not found");

        assert_eq!(div_box.layout.content.width, 400.0);
        assert_eq!(div_box.layout.margin.left, div_box.layout.margin.right);
        assert_eq!(div_box.layout.margin.left, 192.0);
    }

    #[test]
    fn over_constrained_box_recalculates_margin_right_to_fit_the_containing_block() {
        // Where width, margin-left and margin-right are all given explicitly and do not add
        // up to the containing width (over-constrained), CSS2.1 section 10.3.3 ignores the
        // given margin-right and recomputes it so the equation holds.
        let dom = html::parse(br#"<div class="box"></div>"#);
        let ua = user_agent_stylesheet();
        // containing width = 784 (html: 800, body margin: 8px each side).
        // width:300 + margin-left:50 + the given margin-right:50 = 400, so margin-right should
        // be recomputed to 434 to reach 784.
        let author = parse_stylesheet(".box { width: 300px; margin: 0 50px 0 50px; }");
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let div_box = find_laid_out(&laid, divs[0]).expect("div box not found");

        assert_eq!(div_box.layout.content.width, 300.0);
        assert_eq!(div_box.layout.margin.left, 50.0);
        assert_eq!(
            div_box.layout.margin.right, 434.0,
            "over-constrained margin-right should be recalculated, not the specified 50px"
        );
    }

    #[test]
    fn over_constrained_recalculation_can_produce_a_negative_margin_right() {
        let dom = html::parse(br#"<div class="box"></div>"#);
        let ua = user_agent_stylesheet();
        // containing width = 784. The width alone fills it, so margin-left pushes it over and
        // the recomputed margin-right should come out negative, differing even in sign from
        // the given value (99px).
        let author = parse_stylesheet(".box { width: 784px; margin: 0 99px 0 30px; }");
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let div_box = find_laid_out(&laid, divs[0]).expect("div box not found");

        assert_eq!(div_box.layout.margin.right, -30.0);
    }

    #[test]
    fn block_siblings_stack_vertically_by_content_height() {
        let dom = html::parse(br#"<div><p class="a">A</p><p class="b">B</p></div>"#);
        let ua = user_agent_stylesheet();
        let author =
            parse_stylesheet(".a { height: 50px; margin: 0; } .b { height: 30px; margin: 0; }");
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut ps = Vec::new();
        find_all(&dom, dom.document(), "p", &mut ps);
        let a = find_laid_out(&laid, ps[0]).expect("p.a not found");
        let b = find_laid_out(&laid, ps[1]).expect("p.b not found");

        assert_eq!(
            b.layout.content.y,
            a.layout.content.y + a.layout.content.height
        );
    }

    #[test]
    fn equal_adjacent_margins_collapse_to_a_single_gap_instead_of_summing() {
        let dom = html::parse(br#"<div><p class="a">A</p><p class="b">B</p></div>"#);
        let ua = user_agent_stylesheet();
        // Both have 16px top and bottom margins. Collapsed, the gap between the border boxes
        // should be 16px, not 32px (their sum).
        let author = parse_stylesheet(
            ".a { height: 20px; margin: 16px 0; } .b { height: 20px; margin: 16px 0; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut ps = Vec::new();
        find_all(&dom, dom.document(), "p", &mut ps);
        let a = find_laid_out(&laid, ps[0]).expect("p.a not found");
        let b = find_laid_out(&laid, ps[1]).expect("p.b not found");

        let gap =
            b.layout.border_box().y - (a.layout.border_box().y + a.layout.border_box().height);
        assert_eq!(
            gap, 16.0,
            "equal adjacent margins should collapse to their shared value"
        );
    }

    #[test]
    fn left_float_is_removed_from_normal_flow_and_placed_at_containing_left() {
        let dom = html::parse(
            br#"<div class="outer"><div class="f">F</div><div class="after">after</div></div>"#,
        );
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            "body { margin: 0; } \
             .f { float: left; width: 100px; height: 50px; } \
             .after { height: 20px; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let float_box = find_laid_out(&laid, divs[1]).expect("float box not found");
        let after_box = find_laid_out(&laid, divs[2]).expect("after box not found");

        assert!(float_box.is_float);
        assert_eq!(float_box.layout.content.x, 0.0);
        assert_eq!(float_box.layout.content.y, 0.0);
        // A float does not take part in the flow, so the block that follows ignores the
        // float's height (50px) and is placed straight from the top of the containing block.
        assert_eq!(after_box.layout.content.y, 0.0);
    }

    #[test]
    fn right_float_is_placed_against_the_containing_right_edge() {
        let dom = html::parse(br#"<div class="outer"><div class="f">F</div></div>"#);
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            "body { margin: 0; } .f { float: right; width: 100px; height: 50px; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let float_box = find_laid_out(&laid, divs[1]).expect("float box not found");

        assert_eq!(float_box.layout.content.x, 700.0);
        assert_eq!(float_box.layout.content.y, 0.0);
    }

    #[test]
    fn second_left_float_packs_next_to_the_first_instead_of_stacking() {
        let dom = html::parse(
            br#"<div class="outer"><div class="a">A</div><div class="b">B</div></div>"#,
        );
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            "body { margin: 0; } \
             .a { float: left; width: 100px; height: 50px; } \
             .b { float: left; width: 100px; height: 30px; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let a_box = find_laid_out(&laid, divs[1]).expect("a not found");
        let b_box = find_laid_out(&laid, divs[2]).expect("b not found");

        assert_eq!(a_box.layout.content.x, 0.0);
        assert_eq!(b_box.layout.content.x, 100.0);
        assert_eq!(b_box.layout.content.y, 0.0);
    }

    #[test]
    fn floats_with_non_round_percentages_summing_to_100_sit_side_by_side() {
        // Bootstrap 3's `.col-xs-8`/`.col-xs-4`. Even when f32 rounding makes the two widths
        // overshoot the containing width slightly, the second float stays on the same row (#64).
        let dom = html::parse(
            br#"<div class="outer"><div class="a">A</div><div class="b">B</div></div>"#,
        );
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            "body { margin: 0; } \
             .a { float: left; width: 66.66667%; height: 50px; } \
             .b { float: left; width: 33.33333%; height: 30px; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        for containing_width in [595.0, 612.0, 700.0, 793.7, 800.0, 1000.0] {
            let laid = layout_document(&tree, &styles, &fonts, containing_width);
            let a_box = find_laid_out(&laid, divs[1]).expect("a not found");
            let b_box = find_laid_out(&laid, divs[2]).expect("b not found");

            assert_eq!(
                b_box.layout.content.y, 0.0,
                "b stacked below a at containing width {containing_width}"
            );
            assert_eq!(b_box.layout.content.x, a_box.layout.content.width);
        }
    }

    #[test]
    fn clear_pushes_the_element_below_the_float() {
        let dom = html::parse(
            br#"<div class="outer"><div class="f">F</div><div class="c">after</div></div>"#,
        );
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            "body { margin: 0; } \
             .f { float: left; width: 100px; height: 50px; } \
             .c { clear: left; height: 20px; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let cleared_box = find_laid_out(&laid, divs[2]).expect("cleared box not found");

        assert_eq!(cleared_box.layout.content.y, 50.0);
    }

    #[test]
    fn float_does_not_participate_in_adjacent_margin_collapsing() {
        let dom = html::parse(
            br#"<div class="outer">
                <div class="a">a</div><div class="f">F</div><div class="b">b</div>
                </div>"#,
        );
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            "body { margin: 0; } \
             .a { height: 10px; margin: 0 0 20px 0; } \
             .f { float: left; width: 30px; height: 5px; } \
             .b { height: 10px; margin: 30px 0 0 0; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let a_box = find_laid_out(&laid, divs[1]).expect("a not found");
        let b_box = find_laid_out(&laid, divs[3]).expect("b not found");

        assert_eq!(a_box.layout.content.y, 0.0);
        // Even with a float between a and b, margin collapsing with the previous non-float
        // child (a) still applies: max(20, 30) = 30. Including the float in the collapsing
        // would skew this value (a float has no margin and would count as 0).
        assert_eq!(b_box.layout.content.y, 40.0);
    }

    #[test]
    fn container_auto_height_expands_to_include_a_taller_float_child() {
        let dom = html::parse(br#"<div class="outer"><div class="f">F</div></div>"#);
        let ua = user_agent_stylesheet();
        let author =
            parse_stylesheet("body { margin: 0; } .f { float: left; width: 50px; height: 200px; }");
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let outer_box = find_laid_out(&laid, divs[0]).expect("outer not found");

        assert_eq!(outer_box.layout.content.height, 200.0);
    }

    #[test]
    fn position_relative_offsets_visual_position_without_affecting_siblings() {
        let dom = html::parse(
            br#"<div class="outer">
                <div class="a">a</div><div class="rel">b</div><div class="c">c</div>
                </div>"#,
        );
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            "body { margin: 0; } \
             .a { height: 10px; } \
             .rel { position: relative; top: 5px; left: 7px; height: 20px; } \
             .c { height: 10px; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let rel_box = find_laid_out(&laid, divs[2]).expect("rel not found");
        let c_box = find_laid_out(&laid, divs[3]).expect("c not found");

        // The normal position is x=0, y=10 (below a), plus the top:5px/left:7px offset.
        assert_eq!(rel_box.layout.content.x, 7.0);
        assert_eq!(rel_box.layout.content.y, 15.0);
        // c is placed against the rel element's real (pre-offset) bottom edge (10+20=30) and
        // is unaffected by the visual offset.
        assert_eq!(c_box.layout.content.y, 30.0);
    }

    #[test]
    fn unequal_adjacent_margins_collapse_to_the_larger_one() {
        let dom = html::parse(br#"<div><p class="a">A</p><p class="b">B</p></div>"#);
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            ".a { height: 20px; margin: 0 0 10px 0; } .b { height: 20px; margin: 24px 0 0 0; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut ps = Vec::new();
        find_all(&dom, dom.document(), "p", &mut ps);
        let a = find_laid_out(&laid, ps[0]).expect("p.a not found");
        let b = find_laid_out(&laid, ps[1]).expect("p.b not found");

        let gap =
            b.layout.border_box().y - (a.layout.border_box().y + a.layout.border_box().height);
        assert_eq!(
            gap, 24.0,
            "collapsed gap should be the larger of the two margins"
        );
    }

    #[test]
    fn a_negative_margin_reduces_the_collapsed_gap() {
        let dom = html::parse(br#"<div><p class="a">A</p><p class="b">B</p></div>"#);
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            ".a { height: 20px; margin: 0 0 10px 0; } .b { height: 20px; margin: -4px 0 0 0; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut ps = Vec::new();
        find_all(&dom, dom.document(), "p", &mut ps);
        let a = find_laid_out(&laid, ps[0]).expect("p.a not found");
        let b = find_laid_out(&laid, ps[1]).expect("p.b not found");

        let gap =
            b.layout.border_box().y - (a.layout.border_box().y + a.layout.border_box().height);
        assert_eq!(
            gap, 6.0,
            "positive + negative margins should sum (10 + (-4) = 6)"
        );
    }

    #[test]
    fn parent_and_first_child_top_margins_collapse_through_the_parent() {
        // With no border-top or padding-top on the parent, the first child's margin-top
        // escapes the parent and collapses with the parent's margin-top.
        let dom = html::parse(br#"<div class="outer"><p class="inner">x</p></div>"#);
        let ua = user_agent_stylesheet();
        let author =
            parse_stylesheet(".outer { margin: 0; } .inner { height: 20px; margin: 12px 0; }");
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let outer = find_laid_out(&laid, divs[0]).expect("outer not found");
        let mut ps = Vec::new();
        find_all(&dom, dom.document(), "p", &mut ps);
        let inner = find_laid_out(&laid, ps[0]).expect("inner not found");

        // After collapsing, the parent's effective margin-top is collapse(0, 12) = 12.
        assert_eq!(outer.layout.margin.top, 12.0);
        // The top of the child's border coincides with the top of the parent's content (no gap between them).
        assert_eq!(inner.layout.content.y, outer.layout.content.y);
        // The parent's height covers the child's content (the child's margin has moved outside, so it is not included).
        assert_eq!(outer.layout.content.height, 20.0);
    }

    #[test]
    fn a_top_border_on_the_parent_prevents_the_collapse() {
        // With a border-top on the parent there is no collapsing, and the child's margin-top stays inside the parent.
        let dom = html::parse(br#"<div class="outer"><p class="inner">x</p></div>"#);
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            ".outer { margin: 0; border-top: 5px solid black; }              .inner { height: 20px; margin: 12px 0; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let outer = find_laid_out(&laid, divs[0]).expect("outer not found");
        let mut ps = Vec::new();
        find_all(&dom, dom.document(), "p", &mut ps);
        let inner = find_laid_out(&laid, ps[0]).expect("inner not found");

        assert_eq!(outer.layout.margin.top, 0.0, "no collapse through a border");
        // The child sits margin-top below the top of the parent's content.
        assert_eq!(inner.layout.content.y, outer.layout.content.y + 12.0);
    }

    #[test]
    fn an_empty_block_collapses_its_own_top_and_bottom_margins() {
        // The top and bottom margins of an empty block (height 0, no border or padding)
        // collapse into one and do not apply twice.
        let dom = html::parse(br#"<div class="empty"></div>"#);
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(".empty { margin: 30px 0; }");
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let empty = find_laid_out(&laid, divs[0]).expect("empty not found");
        // The margin box height is 30 (the single collapsed value), not 60 (=30+30).
        assert_eq!(empty.layout.margin_box_height(), 30.0);
    }

    #[test]
    fn auto_height_block_sizes_to_children_content() {
        let dom = html::parse(br#"<div class="outer"><p class="inner">x</p></div>"#);
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(".inner { height: 40px; margin: 0; }");
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let outer = find_laid_out(&laid, divs[0]).expect("outer div not found");

        assert_eq!(outer.layout.content.height, 40.0);
    }

    #[test]
    fn wrapped_inline_content_drives_auto_height() {
        // With enough width it is one line; when narrow it wraps onto several.
        let dom = html::parse(br#"<p class="a">hello world</p>"#);
        let ua = user_agent_stylesheet();
        let author = Stylesheet::default();
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();

        let mut ps = Vec::new();
        find_all(&dom, dom.document(), "p", &mut ps);

        let wide = layout_document(&tree, &styles, &fonts, 800.0);
        let p_wide = find_laid_out(&wide, ps[0]).expect("p not found");
        let LaidOutContent::Inline(lines_wide) = &p_wide.content else {
            panic!("expected inline content")
        };
        assert_eq!(lines_wide.len(), 1);

        let narrow = layout_document(&tree, &styles, &fonts, 60.0);
        let p_narrow = find_laid_out(&narrow, ps[0]).expect("p not found");
        let LaidOutContent::Inline(lines_narrow) = &p_narrow.content else {
            panic!("expected inline content")
        };
        assert_eq!(lines_narrow.len(), 2);

        assert!(p_narrow.layout.content.height > p_wide.layout.content.height);
    }

    #[test]
    fn padding_and_border_offset_content_box() {
        let dom = html::parse(br#"<div class="box"></div>"#);
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            ".box { width: 100px; margin: 0; padding: 5px; border: 2px solid black; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let div_box = find_laid_out(&laid, divs[0]).expect("div box not found");

        assert_eq!(div_box.layout.content.width, 100.0);
        assert_eq!(div_box.layout.padding.left, 5.0);
        assert_eq!(div_box.layout.border.left, 2.0);

        let border_box = div_box.layout.border_box();
        assert_eq!(border_box.width, 2.0 + 5.0 + 100.0 + 5.0 + 2.0);
    }

    #[test]
    fn box_sizing_border_box_makes_the_specified_width_include_padding_and_border() {
        let dom = html::parse(br#"<div class="box"></div>"#);
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            ".box { box-sizing: border-box; width: 100px; height: 60px; margin: 0; \
             padding: 5px; border: 2px solid black; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let div_box = find_laid_out(&laid, divs[0]).expect("div box not found");

        // Under border-box the given 100px/60px are the outer dimensions including padding
        // and border, so the content box is smaller by that much (100 - 2*5 - 2*2 = 86).
        assert_eq!(div_box.layout.content.width, 100.0 - 2.0 * 5.0 - 2.0 * 2.0);
        assert_eq!(div_box.layout.content.height, 60.0 - 2.0 * 5.0 - 2.0 * 2.0);

        let border_box = div_box.layout.border_box();
        assert_eq!(border_box.width, 100.0);
        assert_eq!(border_box.height, 60.0);
    }

    #[test]
    fn box_sizing_border_box_clamps_to_zero_when_padding_and_border_exceed_the_specified_width() {
        let dom = html::parse(br#"<div class="box"></div>"#);
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            ".box { box-sizing: border-box; width: 5px; margin: 0; \
             padding: 10px; border: 10px solid black; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let div_box = find_laid_out(&laid, divs[0]).expect("div box not found");

        assert_eq!(div_box.layout.content.width, 0.0);
    }

    #[test]
    fn border_style_none_zeroes_out_the_used_border_width_in_layout() {
        // CSS2.1 8.5.3: an edge whose border-style is none has a used value of 0 regardless
        // of its border-width (it is not merely undrawn; it does not affect the width
        // calculation in layout either).
        let dom = html::parse(br#"<div class="box"></div>"#);
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            ".box { width: 100px; margin: 0; border-width: 5px; border-style: none; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let div_box = find_laid_out(&laid, divs[0]).expect("div box not found");

        assert_eq!(div_box.layout.border.left, 0.0);
        let border_box = div_box.layout.border_box();
        assert_eq!(border_box.width, 100.0);
    }

    #[test]
    fn fragmentation_hints_reflect_the_elements_computed_style() {
        let dom = html::parse(br#"<div class="box"></div>"#);
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            ".box { break-before: always; break-inside: avoid; orphans: 3; widows: 4; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let div_box = find_laid_out(&laid, divs[0]).expect("div box not found");

        assert_eq!(
            div_box.fragmentation.break_before,
            super::BreakBetween::Always
        );
        assert_eq!(div_box.fragmentation.break_after, super::BreakBetween::Auto);
        assert_eq!(
            div_box.fragmentation.break_inside,
            super::BreakInside::Avoid
        );
        assert_eq!(div_box.fragmentation.orphans, 3);
        assert_eq!(div_box.fragmentation.widows, 4);
    }

    #[test]
    fn anonymous_boxes_get_default_fragmentation_hints() {
        // An anonymous box (from wrapping mixed content, say) has no corresponding DOM
        // element, so its fragmentation hints should always be the initial values (auto/auto/auto/2/2).
        let dom = html::parse(br#"<div class="outer">before <p>P</p> after</div>"#);
        let ua = user_agent_stylesheet();
        let author = Stylesheet::default();
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let div_box = find_laid_out(&laid, divs[0]).expect("div box not found");
        let LaidOutContent::Blocks(children) = &div_box.content else {
            panic!("expected block container")
        };
        let anonymous = children
            .iter()
            .find(|c| c.node.is_none())
            .expect("expected an anonymous block wrapping the loose text");

        assert_eq!(anonymous.fragmentation, FragmentationHints::default());
    }

    fn image_prepared(width: f32, height: f32) -> Rc<PreparedImage> {
        Rc::new(PreparedImage {
            width,
            height,
            content: crate::pdf::PreparedContent::Raster {
                color: ImagePlane {
                    data: Vec::new(),
                    filter: pdf_writer::Filter::FlateDecode,
                    color_space: PlaneColorSpace::Rgb,
                    bits_per_component: 8,
                },
                alpha: None,
            },
        })
    }

    fn image_box(content: ImageBoxContent) -> LayoutBox {
        LayoutBox::anonymous(BoxContent::Image(content))
    }

    #[test]
    fn image_with_no_attrs_uses_intrinsic_size_when_decoded() {
        let tree = image_box(ImageBoxContent {
            image: Some(image_prepared(200.0, 100.0)),
            attr_width: None,
            attr_height: None,
        });
        let laid = layout_document(&tree, &HashMap::new(), &test_fonts(), 800.0);

        assert_eq!(laid.layout.content.width, 200.0);
        assert_eq!(laid.layout.content.height, 100.0);
    }

    #[test]
    fn image_width_attr_only_derives_height_via_aspect_ratio() {
        // The intrinsic size is 200x100 (2:1). With only width=50px given -> height=25px.
        let tree = image_box(ImageBoxContent {
            image: Some(image_prepared(200.0, 100.0)),
            attr_width: Some(50),
            attr_height: None,
        });
        let laid = layout_document(&tree, &HashMap::new(), &test_fonts(), 800.0);

        assert_eq!(laid.layout.content.width, 50.0);
        assert_eq!(laid.layout.content.height, 25.0);
    }

    #[test]
    fn image_height_attr_only_derives_width_via_aspect_ratio() {
        let tree = image_box(ImageBoxContent {
            image: Some(image_prepared(200.0, 100.0)),
            attr_width: None,
            attr_height: Some(40),
        });
        let laid = layout_document(&tree, &HashMap::new(), &test_fonts(), 800.0);

        assert_eq!(laid.layout.content.height, 40.0);
        assert_eq!(laid.layout.content.width, 80.0);
    }

    #[test]
    fn image_with_both_attrs_ignores_the_intrinsic_aspect_ratio() {
        let tree = image_box(ImageBoxContent {
            image: Some(image_prepared(200.0, 100.0)),
            attr_width: Some(10),
            attr_height: Some(10),
        });
        let laid = layout_document(&tree, &HashMap::new(), &test_fonts(), 800.0);

        assert_eq!(laid.layout.content.width, 10.0);
        assert_eq!(laid.layout.content.height, 10.0);
    }

    #[test]
    fn failed_image_with_no_attrs_collapses_to_zero_size() {
        let tree = image_box(ImageBoxContent {
            image: None,
            attr_width: None,
            attr_height: None,
        });
        let laid = layout_document(&tree, &HashMap::new(), &test_fonts(), 800.0);

        assert_eq!(laid.layout.content.width, 0.0);
        assert_eq!(laid.layout.content.height, 0.0);
    }

    #[test]
    fn failed_image_with_explicit_attrs_still_reserves_the_specified_space() {
        // Even on a failed fetch, width/height attributes make it an empty box of that size
        // (reserving the space so the content that follows does not suddenly shift).

        let tree = image_box(ImageBoxContent {
            image: None,
            attr_width: Some(50),
            attr_height: Some(50),
        });
        let laid = layout_document(&tree, &HashMap::new(), &test_fonts(), 800.0);

        assert_eq!(laid.layout.content.width, 50.0);
        assert_eq!(laid.layout.content.height, 50.0);
    }

    #[test]
    fn image_does_not_stretch_to_fill_the_containing_block_like_a_block_div_would() {
        // An ordinary block element with width:auto fills the containing block, but a
        // replaced element does not (it uses its intrinsic size as-is).
        let tree = image_box(ImageBoxContent {
            image: Some(image_prepared(50.0, 50.0)),
            attr_width: None,
            attr_height: None,
        });
        let laid = layout_document(&tree, &HashMap::new(), &test_fonts(), 800.0);

        assert_eq!(laid.layout.content.width, 50.0);
    }

    #[test]
    fn outside_marker_is_positioned_left_of_the_content_edge_with_a_fixed_gap() {
        let dom = html::parse(br#"<ul><li>text</li></ul>"#);
        let ua = user_agent_stylesheet();
        let styles = compute_styles(&dom, &ua, &Stylesheet::default());
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let mut lis = Vec::new();
        find_all(&dom, dom.document(), "li", &mut lis);
        let li = find_laid_out(&laid, lis[0]).expect("li not found");

        let marker = li.marker.as_ref().expect("li should have a marker");
        assert_eq!(marker.runs.len(), 1);
        assert!(marker.rect.width > 0.0);
        assert_eq!(
            marker.rect.x,
            li.layout.content.x - LIST_MARKER_GAP - marker.rect.width
        );
        assert_eq!(
            marker.rect.y, li.layout.content.y,
            "marker should align with the top of the li's own content"
        );
    }

    #[test]
    fn list_style_type_none_produces_no_marker_in_the_laid_out_box() {
        let dom = html::parse(br#"<ul><li style="list-style-type: none;">text</li></ul>"#);
        let ua = user_agent_stylesheet();
        let styles = compute_styles(&dom, &ua, &Stylesheet::default());
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let li = find(&dom, dom.document(), "li").expect("li not found");
        let li_laid = find_laid_out(&laid, li).expect("li not found");
        assert!(li_laid.marker.is_none());
    }

    fn find(dom: &Dom, id: NodeId, tag: &str) -> Option<NodeId> {
        if let NodeData::Element { name, .. } = &dom.node(id).data {
            if &*name.local == tag {
                return Some(id);
            }
        }
        dom.children(id).find_map(|child| find(dom, child, tag))
    }

    /// A `position: relative` offset moves the contents (lines, child blocks,
    /// marker) as well as the decoration (background, border)
    /// (waka/sghtmltopdf#29).
    #[test]
    fn position_relative_moves_inline_content_and_block_children_with_the_box() {
        let dom = html::parse(
            br#"<div class="rel"><p>child</p></div><ul><li class="rel">item</li></ul>"#,
        );
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            "body, p, ul { margin: 0; padding: 0; } \
             .rel { position: relative; top: 5px; left: 7px; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let laid = layout_document(&tree, &styles, &fonts, 800.0);

        let div = find(&dom, dom.document(), "div").expect("div not found");
        let p = find(&dom, dom.document(), "p").expect("p not found");
        let div_box = find_laid_out(&laid, div).expect("div not laid out");
        let p_box = find_laid_out(&laid, p).expect("p not laid out");
        assert_eq!(
            (div_box.layout.content.x, div_box.layout.content.y),
            (7.0, 5.0)
        );
        // A child block moves with its parent.
        assert_eq!((p_box.layout.content.x, p_box.layout.content.y), (7.0, 5.0));
        // And its line box is in the same place.
        let LaidOutContent::Inline(lines) = &p_box.content else {
            panic!("p should hold inline content");
        };
        assert_eq!((lines[0].rect.x, lines[0].rect.y), (7.0, 5.0));

        // The list marker moves with the contents too, staying to the left of
        // the content box.
        let li = find(&dom, dom.document(), "li").expect("li not found");
        let li_box = find_laid_out(&laid, li).expect("li not laid out");
        let marker = li_box.marker.as_ref().expect("li should have a marker");
        let LaidOutContent::Inline(lines) = &li_box.content else {
            panic!("li should hold inline content");
        };
        assert_eq!(lines[0].rect.x, li_box.layout.content.x);
        assert!(marker.rect.x < li_box.layout.content.x);
        assert_eq!(marker.rect.y, lines[0].rect.y);
    }

    /// An absolutely positioned element with a relatively positioned ancestor
    /// takes the offset padding box as its containing block.
    #[test]
    fn position_relative_offset_shifts_the_containing_block_of_absolute_children() {
        let dom = html::parse(br#"<div class="rel"><div class="abs">x</div></div>"#);
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            "body { margin: 0; } \
             .rel { position: relative; top: 5px; left: 7px; height: 50px; } \
             .abs { position: absolute; top: 0; left: 0; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let tree = build_box_tree(&dom, &styles);
        let fonts = test_fonts();
        let (_, positioned) = layout_document_positioned(&tree, &styles, &fonts, (800.0, 600.0));
        assert_eq!(positioned.len(), 1);
        let abs = &positioned[0].laid;
        assert_eq!((abs.layout.content.x, abs.layout.content.y), (7.0, 5.0));
    }

    /// `position: relative` on an inline element (`<span>`) shifts only its own
    /// runs (the `<span>` case of waka/sghtmltopdf#29).
    #[test]
    fn position_relative_on_an_inline_element_shifts_only_its_runs() {
        let html_src = br#"<div>A <span class="s">TEXT</span> B</div>"#;
        let ua = user_agent_stylesheet();
        let fonts = test_fonts();
        let runs_of = |css: &str| -> Vec<(String, f32, f32)> {
            let dom = html::parse(html_src);
            let styles = compute_styles(&dom, &ua, &parse_stylesheet(css));
            let tree = build_box_tree(&dom, &styles);
            let laid = layout_document(&tree, &styles, &fonts, 800.0);
            let div = find(&dom, dom.document(), "div").expect("div not found");
            let div_box = find_laid_out(&laid, div).expect("div not laid out");
            let LaidOutContent::Inline(lines) = &div_box.content else {
                panic!("div should hold inline content");
            };
            lines[0]
                .runs
                .iter()
                .map(|r| (r.text.clone(), r.x_offset, r.baseline_shift))
                .collect()
        };
        let plain = runs_of("body { margin: 0; }");
        let shifted =
            runs_of("body { margin: 0; } .s { position: relative; left: 120px; top: 3px; }");
        assert_eq!(plain.len(), shifted.len());
        for (before, after) in plain.iter().zip(&shifted) {
            assert_eq!(before.0, after.0);
            if before.0 == "TEXT" {
                assert_eq!(
                    after.1,
                    before.1 + 120.0,
                    "span run should move right by 120px"
                );
                // A positive `baseline_shift` means up, so `top: 3px` is -3.
                assert_eq!(after.2, before.2 - 3.0, "span run should move down by 3px");
            } else {
                assert_eq!(
                    (after.1, after.2),
                    (before.1, before.2),
                    "{:?} should not move",
                    before.0
                );
            }
        }
    }
}