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
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
//! Splitting the laid-out box tree according to the height left on the page.
//!
//! It honours `break-before`/`break-after`/`break-inside`/`orphans`/`widows`, and where a
//! box does not fit on the page it tries to split it in this order of preference:
//! 1. If `break-inside: avoid` and it is small enough to fit a whole page, move it whole to
//!    the top of the next page rather than splitting it
//! 2. If it is a block container, re-place it child box by child box (each child's
//!    `break-before`/`break-after: always` acts as a forced break at this granularity)
//! 3. If it is multi-line inline content, split it line box by line box
//!    ([`compute_orphans_widows_breaks`] adjusts the break points in advance so
//!    `orphans`/`widows` are satisfied)
//! 4. Anything still indivisible (an empty element, single-line content) is moved whole to
//!    the top of the next page (something too large for one page simply overflows)
//!
//! A descendant's `break-before`/`break-after: always` must not be missed even when the
//! ancestor's subtree fits in the height left on the page (a forced break is an explicit
//! setting, independent of overflow). [`subtree_requires_child_walk`] decides in advance
//! whether such a forced break exists inside the subtree, and if it does, falls back to
//! per-child placement rather than the fast path of "place it as a single leaf".
//!
//! Even where a container is itself split across pages, its background and borders are
//! reproduced on each page its children actually landed on (a simple box fragmentation; see
//! [`place_split`]). "Given break points already decided, how the container's decoration
//! carries over" follows these simple rules:
//! - The top margin, border and padding apply to the first fragment only
//! - The bottom margin, border and padding apply to the last fragment only
//! - The left and right borders and padding apply to every fragment
//! - The background colour is painted over each fragment's real content extent
//!
//! A subtree that fits on one page without crossing a boundary, and contains no forced
//! break, is placed with its original structure intact.

use std::collections::HashMap;
use std::rc::Rc;

use crate::fonts::FontCollection;
use crate::html::{Dom, NodeId};
use crate::style::{BreakBetween, BreakInside, ComputedStyle};

use crate::pdf::ImageAssetCache;

use super::block::{
    layout_document, layout_document_positioned, shift_box_x, shift_box_y, shift_box_y_in_place,
    FragmentationHints, LaidOutBox, LaidOutContent, LaidOutTable, LaidOutTableRow, PositionedBox,
    PositionedKind,
};
use super::box_tree::TableSection;
use super::box_tree::{build_box_tree, resolve_images};
use super::geometry::{EdgeSizes, FragmentPosition, Layout, Rect};
use super::grid::{LaidOutGrid, LaidOutGridRow};
use super::inline::LineBox;
use super::page::PageSettings;
use crate::style::CaptionSide;

#[derive(Debug, Clone, Default)]
pub struct Page {
    pub boxes: Vec<LaidOutBox>,
}

/// The state managing "the unflushed page buffer plus the decision of what may be flushed" during pagination.
///
/// The decoration fragments (background and borders) that [`place_split`] inserts for a
/// container are written after every one of its children has been placed, reaching back into
/// pages that were already `push`ed and look settled (see the module docs). So the simple
/// rule "once a new page starts, the previous one is settled" does not hold. The document
/// root itself also goes through `place_split`, so with no countermeasure "no page is
/// settled until the whole document is processed" (which is effectively batch processing
/// again).
///
/// Instead, every `place_split` currently in progress (that is, on the call stack) pushes
/// "the first absolute page index it touched" onto the `active_min_page` stack, and only
/// pages before that minimum are safely flushed ([`Self::try_flush`]). No container started
/// after a given page ever writes back to it (`place_split` never touches a page before the
/// range it spanned), which is what makes this rule safe.
///
/// The persistent part of [`PaginationState`]. Holding no `on_flush` callback (with its
/// lifetime), it can be a field of [`StreamingPaginator`] and survive across several
/// `push_item` calls.
#[derive(Default)]
struct PaginationBuffer {
    /// The buffer of pages not yet flushed (that is, pages we cannot yet guarantee will not
    /// be written to again). The absolute index of `buffer[0]` is `flushed`.
    buffer: Vec<Page>,
    /// How many pages have been flushed so far (that is, the absolute index of the next page
    /// to flush).
    flushed: usize,
    /// The stack of first-touched absolute page indices for the `place_split` calls currently
    /// active (pushed and popped by `enter_split`/`exit_split`).
    active_min_page: Vec<usize>,
}

impl PaginationBuffer {
    fn new() -> Self {
        Self {
            buffer: vec![Page::default()],
            flushed: 0,
            active_min_page: Vec::new(),
        }
    }
}

/// [`PaginationBuffer`] (the persistent part) plus a per-call replaceable `on_flush`
/// callback: what `place_box` and friends actually operate on.
///
/// The decoration fragments (background and borders) that [`place_split`] inserts for a
/// container are written after every one of its children has been placed, reaching back into
/// pages that were already `push`ed and look settled (see the module docs). So the simple
/// rule "once a new page starts, the previous one is settled" does not hold. The document
/// root itself also goes through `place_split`, so with no countermeasure "no page is
/// settled until the whole document is processed" (which is effectively batch processing
/// again).
///
/// Instead, every `place_split` currently in progress (that is, on the call stack) pushes
/// "the first absolute page index it touched" onto the `active_min_page` stack, and only
/// pages before that minimum are safely flushed ([`Self::try_flush`]). No container started
/// after a given page ever writes back to it (`place_split` never touches a page before the
/// range it spanned), which is what makes this rule safe.
struct PaginationState<'a> {
    inner: &'a mut PaginationBuffer,
    on_flush: &'a mut dyn FnMut(Page),
}

impl<'a> PaginationState<'a> {
    fn new(inner: &'a mut PaginationBuffer, on_flush: &'a mut dyn FnMut(Page)) -> Self {
        Self { inner, on_flush }
    }

    /// The current page count, in absolute indices (0-based and running through the whole
    /// document).
    fn len(&self) -> usize {
        self.inner.flushed + self.inner.buffer.len()
    }

    /// The absolute index of the last (most recent) active page.
    fn current_index(&self) -> usize {
        self.len() - 1
    }

    fn last_mut(&mut self) -> &mut Page {
        self.inner
            .buffer
            .last_mut()
            .expect("the buffer always holds at least one page")
    }

    fn last(&self) -> &Page {
        self.inner
            .buffer
            .last()
            .expect("the buffer always holds at least one page")
    }

    /// A reference to the page at absolute index `absolute`. The caller guarantees it has
    /// not been flushed yet (that is, it is still in the buffer)
    /// (only the range protected by `active_min_page` is ever accessed).
    fn get(&self, absolute: usize) -> &Page {
        &self.inner.buffer[absolute - self.inner.flushed]
    }

    fn get_mut(&mut self, absolute: usize) -> &mut Page {
        &mut self.inner.buffer[absolute - self.inner.flushed]
    }

    /// Start a new page.
    fn push_new_page(&mut self) {
        self.inner.buffer.push(Page::default());
    }

    /// On entering [`place_split`], record the current page as "the first page this container
    /// touched".
    fn enter_split(&mut self) {
        let idx = self.current_index();
        self.inner.active_min_page.push(idx);
    }

    /// On leaving [`place_split`], remove the corresponding record and pass any flushable
    /// pages to `on_flush`.
    fn exit_split(&mut self) {
        self.inner.active_min_page.pop();
        self.try_flush();
    }

    /// With no active `place_split`, pass every page but the most recent to `on_flush`,
    /// oldest first; with one, pass every page before the minimum of "the first page each
    /// currently active container touched".
    fn try_flush(&mut self) {
        let safe_until = self
            .inner
            .active_min_page
            .iter()
            .copied()
            .min()
            .unwrap_or_else(|| self.current_index());
        while self.inner.flushed < safe_until {
            let page = self.inner.buffer.remove(0);
            (self.on_flush)(page);
            self.inner.flushed += 1;
        }
    }
}

/// Split `root` (normally the return value of [`super::layout_document`]) into pages of
/// height `page_content_height` (the batch version). Internally a thin wrapper that has
/// [`paginate_streaming`] pile every page into a `Vec`.
pub fn paginate(root: &mut LaidOutBox, page_content_height: f32) -> Vec<Page> {
    let mut result = Vec::new();
    paginate_streaming(root, page_content_height, &mut |page| result.push(page));
    result
}

/// The streaming version of [`paginate`]. `on_page` is called as each page is settled.
///
/// See the documentation of [`PaginationState`] for what "settled" means. The intended use
/// is for the caller to free the DOM subtree corresponding to that page inside `on_page`,
/// via [`crate::html::Dom::release_subtree`].
pub fn paginate_streaming(
    root: &mut LaidOutBox,
    page_content_height: f32,
    on_page: &mut dyn FnMut(Page),
) {
    let mut paginator = StreamingPaginator::new(page_content_height);
    for page in paginator.push_item(root) {
        on_page(page);
    }
    for page in paginator.finish() {
        on_page(page);
    }
}

/// A streaming paginator: several `LaidOutBox`es (normally one per top-level block element
/// of the document) are added in turn with [`Self::push_item`], and [`Self::finish`] flushes
/// the remaining pages.
///
/// [`paginate_streaming`] assumes "one complete `LaidOutBox` tree" processed at once, while
/// `StreamingPaginator` can continue ordinary top-to-bottom pagination (`cursor` and the
/// [`PaginationBuffer`] flush decision included) across several calls. The intended use, with
/// genuinely streaming input, is to lay out each top-level element directly under `<body>`
/// on its own with `layout::layout_document_from` as it becomes final, and `push_item` it.
///
/// The `on_page` callback is not held as a field: `push_item`/`finish` return the settled
/// pages as a `Vec<Page>` instead (giving the struct the callback's lifetime would cause
/// self-referential borrowing problems for a use case such as `Engine`, which wants to hold
/// the struct itself across several calls).
pub struct StreamingPaginator {
    buffer: PaginationBuffer,
    cursor: f32,
    page_height: f32,
    /// Whether the item added just before had `break-after: always`.
    /// It is consumed as a page break when the next item is added.
    pending_break_after: bool,
}

impl StreamingPaginator {
    pub fn new(page_height: f32) -> Self {
        Self {
            buffer: PaginationBuffer::new(),
            cursor: 0.0,
            page_height,
            pending_break_after: false,
        }
    }

    /// Add one item. Returns the pages this call settled.
    ///
    /// The item's own `break-before`/`break-after` are handled here: `place_box` only looks
    /// at forced breaks within a child list, and the relationship between items (that is,
    /// siblings directly under `<body>`) exists only on the paginator's side. It matches the
    /// decision [`place_split`] makes for siblings in the batch version.
    pub fn push_item(&mut self, item: &mut LaidOutBox) -> Vec<Page> {
        let break_before =
            self.pending_break_after || item.fragmentation.break_before == BreakBetween::Always;
        // `break-after` means "break the page before the next sibling", so it is only recorded
        // here and consumed by the next `push_item`. The last item's `break-after` is ignored
        // by `finish`, so no empty page is left at the end.
        self.pending_break_after = item.fragmentation.break_after == BreakBetween::Always;

        let mut flushed = Vec::new();
        {
            let mut on_flush = |page: Page| flushed.push(page);
            let mut state = PaginationState::new(&mut self.buffer, &mut on_flush);
            // With nothing placed on the current page, breaking would only add an empty page,
            // so nothing is done (a `break-before` on the first element, say).
            if break_before && current_page_has_content(&state) {
                new_page(&mut state, &mut self.cursor);
            }
            place_box(item, self.page_height, &mut state, &mut self.cursor);
        }
        flushed
    }

    /// Signal that there are no more items and return every remaining page.
    pub fn finish(self) -> Vec<Page> {
        debug_assert!(
            self.buffer.active_min_page.is_empty(),
            "finish should be called after leaving every place_split call"
        );
        self.buffer.buffer
    }
}

/// Do everything from box tree construction through layout to pagination in one go, from the DOM plus the computed styles.
pub fn paginate_document(
    dom: &Dom,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    settings: &PageSettings,
) -> Vec<Page> {
    let tree = build_box_tree(dom, styles);
    let (laid_out, positioned) = layout_document_positioned(
        &tree,
        styles,
        fonts,
        (settings.content_width(), settings.content_height()),
    );
    // The box tree is finished with once layout is done. Pagination holds both the layout
    // result and the pages, so letting go of it here keeps the peak from spiking.
    drop(tree);
    let mut laid_out = laid_out;
    let mut pages = paginate(&mut laid_out, settings.content_height());
    apply_positioned_overlays(&mut pages, &positioned);
    pages
}

/// Add the absolutely positioned boxes ([`PositionedBox`]) to the pages they belong to as an
/// overlay. They are appended to `page.boxes`, so they are drawn above (in front of) the normal flow.
pub(crate) fn apply_positioned_overlays(pages: &mut [Page], positioned: &[PositionedBox]) {
    for pb in positioned {
        match pb.kind {
            // `fixed` goes in the content area of every page, at its layout coordinates.
            PositionedKind::Fixed => {
                for page in pages.iter_mut() {
                    page.boxes.push(pb.laid.clone());
                }
            }
            // An `absolute` with no positioned ancestor goes on the first page.
            PositionedKind::AbsoluteInitial => {
                if let Some(first) = pages.first_mut() {
                    first.boxes.push(pb.laid.clone());
                }
            }
            // An `absolute` with a positioned ancestor goes on the page where the ancestor
            // appeared, offset by the difference between the ancestor's padding box position on the page and at layout time.
            PositionedKind::AbsoluteAncestor {
                node,
                padding_box_origin,
            } => {
                if let Some((idx, (px, py))) = find_ancestor_padding_box_origin(pages, node) {
                    let dx = px - padding_box_origin.0;
                    let dy = py - padding_box_origin.1;
                    // `shift_box_y`'s delta is an amount to subtract, so moving down means `-dy`.
                    let shifted = shift_box_x(&shift_box_y(&pb.laid, -dy), dx);
                    pages[idx].boxes.push(shifted);
                }
            }
        }
    }
}

/// Find the page where `node` first appears, and the within-page coordinates of the top left of its padding box.
fn find_ancestor_padding_box_origin(pages: &[Page], node: NodeId) -> Option<(usize, (f32, f32))> {
    for (i, page) in pages.iter().enumerate() {
        for b in &page.boxes {
            if let Some(origin) = find_node_padding_origin(b, node) {
                return Some((i, origin));
            }
        }
    }
    None
}

fn find_node_padding_origin(b: &LaidOutBox, node: NodeId) -> Option<(f32, f32)> {
    if b.node == Some(node) {
        return Some((
            b.layout.content.x - b.layout.padding.left,
            b.layout.content.y - b.layout.padding.top,
        ));
    }
    match &b.content {
        LaidOutContent::Blocks(children) | LaidOutContent::Flex(children) => children
            .iter()
            .find_map(|c| find_node_padding_origin(c, node)),
        LaidOutContent::Grid(grid) => grid
            .rows
            .iter()
            .flat_map(|row| &row.items)
            .find_map(|item| find_node_padding_origin(item, node)),
        LaidOutContent::Table(table) => table
            .caption
            .as_deref()
            .and_then(|c| find_node_padding_origin(c, node))
            .or_else(|| {
                table
                    .rows
                    .iter()
                    .flat_map(|r| &r.cells)
                    .find_map(|c| find_node_padding_origin(c, node))
            }),
        LaidOutContent::Inline(lines) => lines
            .iter()
            .flat_map(|l| &l.atomics)
            .find_map(|a| find_node_padding_origin(&a.content, node)),
        LaidOutContent::Image(_) => None,
    }
}

/// For `Mode::Batch`: settle every page, then overlay the absolute positioning and return.
/// Duplicating `fixed` onto every page and resolving an `absolute`'s ancestor page both
/// require every page to be present, so no streaming release is performed
pub fn paginate_document_with_absolutes(
    dom: &mut Dom,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    settings: &PageSettings,
    image_cache: &ImageAssetCache,
) -> Vec<Page> {
    let mut tree = build_box_tree(dom, styles);
    resolve_images(&mut tree, dom, styles, image_cache);
    let (laid_out, positioned) = layout_document_positioned(
        &tree,
        styles,
        fonts,
        (settings.content_width(), settings.content_height()),
    );
    let mut laid_out = laid_out;
    let mut pages = paginate(&mut laid_out, settings.content_height());
    apply_positioned_overlays(&mut pages, &positioned);
    pages
}

/// The streaming version of [`paginate_document`]. As each page is settled, the DOM subtrees
/// that fitted entirely on it (and will not be split further) are freed with
/// [`Dom::release_subtree`] before `on_page` is called.
///
/// In the current pipeline (`compute_styles`, `build_box_tree` and `layout_document` all
/// read the whole DOM at once), style computation and layout are both already complete at
/// this point, and no page's processing reads `dom` again after this.
/// The "never cross the range a sibling or descendant selector can see" constraint is
/// therefore always satisfied here (no later, unparsed elements exist).
#[allow(clippy::too_many_arguments)]
pub fn paginate_document_streaming(
    dom: &mut Dom,
    styles: &HashMap<NodeId, Rc<ComputedStyle>>,
    fonts: &FontCollection,
    settings: &PageSettings,
    image_cache: &ImageAssetCache,
    on_page: &mut dyn FnMut(Page),
) {
    let mut tree = build_box_tree(dom, styles);
    resolve_images(&mut tree, dom, styles, image_cache);
    let mut laid_out = layout_document(&tree, styles, fonts, settings.content_width());
    paginate_streaming(&mut laid_out, settings.content_height(), &mut |page| {
        release_completed_subtrees(dom, &page);
        on_page(page);
    });
}

/// Free the DOM subtrees corresponding to the boxes in `page` that will not be split further
/// (`FragmentPosition::Whole` or `Last`), via
/// [`Dom::release_subtree`].
fn release_completed_subtrees(dom: &mut Dom, page: &Page) {
    for root in collect_completed_subtree_roots(page) {
        dom.release_subtree(root);
    }
}

/// Collect the root nodes of the DOM subtrees corresponding to the boxes in `page` that will
/// not be split further (`FragmentPosition::Whole` or `Last`).
///
/// The same "nodes no later page will reference" decision is needed not only by
/// [`release_completed_subtrees`] (freeing the DOM) but also when `Engine` removes entries
/// it no longer needs from the `ComputedStyle` map, so the logic for walking `page` is
/// factored out on its own.
pub(crate) fn collect_completed_subtree_roots(page: &Page) -> Vec<NodeId> {
    let mut roots = Vec::new();
    for b in &page.boxes {
        collect_completed_subtree_roots_in_box(b, &mut roots);
    }
    roots
}

fn collect_completed_subtree_roots_in_box(b: &LaidOutBox, roots: &mut Vec<NodeId>) {
    if let Some(node) = b.node {
        if matches!(
            b.layout.fragment,
            FragmentPosition::Whole | FragmentPosition::Last
        ) {
            // The caller walks everything under this node recursively, so no recursion into the children is needed.
            roots.push(node);
            return;
        }
    }
    // A container that is not yet complete (whose decoration fragment is `First`/`Middle`)
    // cannot itself count as complete, but boxes where children were really placed (children
    // placed directly on that page, as distinct from the decoration fragments `place_split`
    // generates) may be complete independently, so we recurse.
    match &b.content {
        LaidOutContent::Blocks(children) => {
            for child in children {
                collect_completed_subtree_roots_in_box(child, roots);
            }
        }
        // A flex container is atomic when it fits (treated the same way as
        // `display: table`). One taller than a page is split by `place_split`,
        // and its items are then placed directly on the page (a fragment is never
        // still a `Flex`), so seeing a `Flex` here always means the whole thing is
        // complete. A grid is split by row, but `place_grid` expresses the
        // completion of each fragment through `FragmentPosition`, so, as with a
        // table, there is no recursion here.
        LaidOutContent::Inline(_)
        | LaidOutContent::Table(_)
        | LaidOutContent::Flex(_)
        | LaidOutContent::Grid(_)
        | LaidOutContent::Image(_) => {}
    }
}

fn place_box(
    b: &mut LaidOutBox,
    page_height: f32,
    state: &mut PaginationState<'_>,
    cursor: &mut f32,
) {
    let height = b.layout.margin_box_height();
    let has_forced_break_inside = subtree_requires_child_walk(b);
    let orphans = b.fragmentation.orphans as usize;
    let widows = b.fragmentation.widows as usize;
    let break_inside_avoid = b.fragmentation.break_inside == BreakInside::Avoid;

    if *cursor + height <= page_height && !has_forced_break_inside {
        place_leaf(b, state, cursor);
        return;
    }

    // `break-inside: avoid`: if it is small enough to fit a whole (empty) page and contains no
    // forced break, move it whole to the top of the next page rather than splitting it.
    // Something too large for one page is exempt and is split as usual on a best-effort
    // basis (an exception to avoid an infinite loop or an impossible output).
    // If the current page has no real content on it (including the case where only an
    // ancestor's margin has advanced `cursor`), moving it is pointless, so it is placed on
    // the current page.
    if break_inside_avoid
        && current_page_has_content(state)
        && height <= page_height
        && !has_forced_break_inside
    {
        new_page(state, cursor);
        place_leaf(b, state, cursor);
        return;
    }

    // While the children are handed out by `&mut`, the container's own scalar information is kept aside.
    let mut container = SplitContainer::take_from(b);
    match &mut b.content {
        LaidOutContent::Blocks(children) if !children.is_empty() => {
            place_split(
                &mut container,
                children,
                page_height,
                state,
                cursor,
                |_i, child: &LaidOutBox| {
                    (
                        child.fragmentation.break_before == BreakBetween::Always,
                        child.fragmentation.break_after == BreakBetween::Always,
                    )
                },
                |children: &[LaidOutBox], i| keep_with_next_bottom(children, i, page_height),
                |child: &LaidOutBox| child.is_float,
                |child: &LaidOutBox| {
                    let top = margin_box_top(child);
                    (top, top + child.layout.margin_box_height())
                },
                |child, ph, ps, c| {
                    place_box(child, ph, ps, c);
                },
            );
            return;
        }
        // A table splits per row. Without this, a row that does not fit the page is lost
        // undrawn.
        LaidOutContent::Table(table) if !table.rows.is_empty() => {
            place_table(&container, table, page_height, state, cursor);
            return;
        }
        // A grid splits per row band.
        LaidOutContent::Grid(grid) if grid.rows.len() > 1 => {
            place_grid(&container, grid, page_height, state, cursor);
            return;
        }
        LaidOutContent::Inline(lines) if lines.len() > 1 => {
            // To satisfy `orphans`/`widows`, compute the forced break positions per line in
            // advance (simulating the natural splitting caused by overflow). Unless the top
            // margin, border and padding `place_split` adds (`container_top_extra`) are
            // reflected in the simulation's initial cursor too, the break points diverge from
            // the real placement.
            let initial_cursor = *cursor + container.top_extra();
            let forced_breaks =
                compute_orphans_widows_breaks(lines, orphans, widows, page_height, initial_cursor);
            place_split(
                &mut container,
                lines,
                page_height,
                state,
                cursor,
                // A line box has no `break-after` (the next place is always the line
                // immediately after, and there is no cross-container sibling relationship).
                move |i, _line| (forced_breaks[i], false),
                // `orphans`/`widows` already decide where lines may part.
                |_lines: &[LineBox], _i| None,
                // A line has no concept of a float.
                |_line: &LineBox| false,
                |line: &LineBox| (line.rect.y, line.rect.y + line.rect.height),
                |line, ph, ps, c| {
                    place_line(line, ph, ps, c);
                },
            );
            return;
        }
        // A flex container is atomic as a rule: if it does not fit in what is
        // left of the page it is moved to the next page whole. A container taller
        // than a page, though, does not fit there either, and the overflow is
        // never painted and simply disappears (#18). In that case only, it is
        // split through the same path as a block, in units of bands: groups of
        // items that do not overlap vertically.
        LaidOutContent::Flex(children) if !children.is_empty() && height > page_height => {
            let mut bands = group_flex_items_into_bands(std::mem::take(children));
            place_split(
                &mut container,
                &mut bands,
                page_height,
                state,
                cursor,
                // Forced breaks are deliberately not given a meaning for bands.
                // A container that fits is atomic and never looks at the `break-*`
                // of its items, so honouring them only when it is split would make
                // the behaviour hard to predict.
                |_i, _band: &FlexBand| (false, false),
                |_bands: &[FlexBand], _i| None,
                |_band: &FlexBand| false,
                |band: &FlexBand| (band.top, band.bottom),
                |band, ph, ps, c| {
                    place_flex_band(band, ph, ps, c);
                },
            );
            return;
        }
        _ => {}
    }

    // We did not take a splitting path, so the marker taken away is given back and it is placed as an indivisible unit.
    b.marker = container.marker.take();
    // An indivisible unit. If any of the page has been used, move it to the top of the next
    // page (on a blank page it is placed where it is).
    if *cursor > 0.0 {
        new_page(state, cursor);
    }
    place_leaf(b, state, cursor);
}

/// Whether the page must not break between two adjacent in-flow siblings.
fn avoids_break_between(before: &LaidOutBox, after: &LaidOutBox) -> bool {
    before.fragmentation.break_after == BreakBetween::Avoid
        || after.fragmentation.break_before == BreakBetween::Avoid
}

/// For a block child that must not be parted from the next in-flow sibling, the absolute Y of
/// the bottom of what has to share its page: the child whole and the start of that sibling
/// (see [`first_piece_bottom`]), continuing through any sibling that in turn avoids a break
/// after it. `None` when the page may break after the child.
fn keep_with_next_bottom(children: &[LaidOutBox], i: usize, page_height: f32) -> Option<f32> {
    let next = (i + 1..children.len()).find(|&j| !children[j].is_float)?;
    if !avoids_break_between(&children[i], &children[next]) {
        return None;
    }
    Some(
        keep_with_next_bottom(children, next, page_height)
            .unwrap_or_else(|| first_piece_bottom(&children[next], page_height)),
    )
}

/// The absolute Y of the bottom of the first piece of `b` the page cannot break inside: the
/// first line (or `orphans` lines), table row or grid row, or the first child's own first
/// piece (with the siblings it avoids a break with). A box that is not split (an image, a flex
/// container, one with `break-inside: avoid` that fits a page) counts whole.
fn first_piece_bottom(b: &LaidOutBox, page_height: f32) -> f32 {
    let bottom = margin_box_top(b) + b.layout.margin_box_height();
    if b.fragmentation.break_inside == BreakInside::Avoid
        && b.layout.margin_box_height() <= page_height
    {
        return bottom;
    }
    match &b.content {
        LaidOutContent::Blocks(children) => match children.iter().position(|c| !c.is_float) {
            Some(first) => keep_with_next_bottom(children, first, page_height)
                .unwrap_or_else(|| first_piece_bottom(&children[first], page_height)),
            None => bottom,
        },
        LaidOutContent::Table(table) => table
            .rows
            .iter()
            .find(|row| row.section != TableSection::Head)
            .or(table.rows.first())
            .map(table_row_bottom)
            .unwrap_or(bottom),
        LaidOutContent::Grid(grid) if grid.rows.len() > 1 => grid.rows[0].bottom,
        // Lines too few for `orphans` and `widows` are moved whole, like a single line.
        LaidOutContent::Inline(lines)
            if lines.len() > 1
                && lines.len() >= (b.fragmentation.orphans + b.fragmentation.widows) as usize =>
        {
            let line = &lines[(b.fragmentation.orphans as usize).max(1) - 1];
            line.rect.y + line.rect.height
        }
        LaidOutContent::Grid(_)
        | LaidOutContent::Inline(_)
        | LaidOutContent::Flex(_)
        | LaidOutContent::Image(_) => bottom,
    }
}

/// The absolute Y of the top of `b`'s margin box (its `content.y` minus the margin, border
/// and padding). Shared by `place_leaf`/`extent_of` and `place_split`'s float branch.
fn margin_box_top(b: &LaidOutBox) -> f32 {
    b.layout.content.y - b.layout.padding.top - b.layout.border.top - b.layout.margin.top
}

/// Whether any box inside `b`'s subtree (block descendants only; inline lines and table
/// internals are excluded) has `break-before`/`break-after: always`.
///
/// When this is `true`, the fast path of "place it as a single leaf" cannot be used even
/// where `b` itself fits the height left on the page (it would miss the forced break's
/// position). A table's internal rows and inline lines are not split here, so only `Blocks`
/// is recursed into.
fn subtree_requires_child_walk(b: &LaidOutBox) -> bool {
    match &b.content {
        LaidOutContent::Blocks(children) => children.iter().any(|child| {
            child.fragmentation.break_before == BreakBetween::Always
                || child.fragmentation.break_after == BreakBetween::Always
                || subtree_requires_child_walk(child)
        }),
        // A flex container is atomic when it fits, and even when it is split for
        // being taller than a page the `break-*` of its items is not consulted.
        // Splitting a grid by row is `place_grid`'s job. Neither recurses here.
        LaidOutContent::Inline(_)
        | LaidOutContent::Table(_)
        | LaidOutContent::Flex(_)
        | LaidOutContent::Grid(_)
        | LaidOutContent::Image(_) => false,
    }
}

/// When splitting multi-line inline content line by line, compute in advance whether a
/// forced break should be inserted before each line so that `orphans`/`widows` are
/// satisfied. In the return value `v`, `v[i] == true` means "break the page before
/// `lines[i]`" (passed straight to `place_split`'s `break_hints`).
///
/// It simulates the natural break points caused by overflow across all of `lines` (the same
/// decision `place_line` really makes: `cursor > 0.0 && cursor + line.height > page_height`)
/// and checks at each of them whether `orphans` (the lines left on this page) and `widows`
/// (the lines moved to the next) are sufficient:
/// - If both are satisfied, that natural break point is taken as-is (no extra marker is
///   needed, `place_line` itself breaking on the same decision)
/// - If `orphans` falls short, no more lines can physically be fitted onto this page, so all
///   the lines that were to go on it are moved to the next page (a forced break at the top
///   of this page)
/// - If `orphans` is sufficient but `widows` is not, the break point is brought forward to
///   `lines.len() - widows` (securing `widows` by sending lines not yet placed to the next page)
///
/// - If `orphans` still cannot be satisfied after bringing it forward, everything is moved
///   to the next page as in the `orphans`-shortfall case
/// - If the conditions cannot be met again at the break point immediately after such a whole
///   move (a run of lines so tall that one alone takes most of a page, say), the natural
///   break point is accepted on a best-effort basis to avoid an infinite loop (giving up on `orphans`/`widows`)
///
/// A paragraph too short to have `orphans + widows` lines cannot satisfy both at any break
/// point, so it ends up moved whole to the next page (if the current page has real content).
fn compute_orphans_widows_breaks(
    lines: &[LineBox],
    orphans: usize,
    widows: usize,
    page_height: f32,
    initial_cursor: f32,
) -> Vec<bool> {
    let n = lines.len();
    let mut force_break_before = vec![false; n];

    let mut cursor = initial_cursor;
    let mut page_start = 0usize;
    let mut i = 0usize;

    while i < n {
        let height = lines[i].rect.height;
        if !(cursor > 0.0 && cursor + height > page_height) {
            cursor += height;
            i += 1;
            continue;
        }

        let fit_count = i - page_start;
        let remaining = n - i;
        let orphans_ok = fit_count >= orphans;
        let widows_ok = remaining >= widows;

        if orphans_ok && widows_ok {
            // Take the natural break point as-is (no marker needed).
            page_start = i;
            cursor = 0.0;
            continue;
        }

        if force_break_before[page_start] {
            // To avoid an infinite loop, natural break points are accepted best-effort from here on.
            page_start = i;
            cursor = 0.0;
            continue;
        }

        if !orphans_ok {
            force_break_before[page_start] = true;
            cursor = 0.0;
            i = page_start;
            continue;
        }

        // orphans_ok == true, widows_ok == false: try bringing the break point forward to
        // secure widows. If orphans still cannot be satisfied afterwards, move everything to
        // the next page as in the orphans-shortfall case.
        let candidate = n.saturating_sub(widows);
        if candidate >= page_start + orphans && candidate < i {
            force_break_before[candidate] = true;
            page_start = candidate;
            cursor = 0.0;
            i = candidate;
        } else {
            force_break_before[page_start] = true;
            cursor = 0.0;
            i = page_start;
        }
    }

    force_break_before
}

/// `b` does not fit on one page (or contains a forced break), so it is split and placed per
/// child (`items`, placed one at a time by `place_one`). After splitting, decoration
/// fragments are inserted to reproduce `b`'s own background and borders over each page's real
/// content extent.
///
/// `items` is either `LaidOutBox` (block children) or [`LineBox`] (inline lines).
/// `break_hints` is a callback returning, for each element (and its index),
/// `(is a forced break needed before it, is one needed after it)` (lines have no concept of
/// `break-before`/`break-after`, so the caller passes a callback indexing into an array
/// precomputed from `orphans`/`widows`).
///
/// `keep_with_next` returns, for an item that must not be parted from the next in-flow one
/// (`break-after: avoid` on it or `break-before: avoid` on the next), the absolute Y of the
/// bottom of what has to share its page (see [`keep_with_next_bottom`]); `None` otherwise.
/// When the item fits on the current page but that does not, the page is broken before the
/// item instead, as long as the two fit on a page together.
///
/// `is_float`/`item_margin_box_top` are callbacks for identifying out-of-flow elements
/// (`float`) among `items` (the `LineBox` side passes dummy implementations always returning
/// `false`/`0.0`; a line has no concept of a float). A float item does not change the shared
/// `cursor`; instead `place_one` is recursed into with a temporary cursor seeded from
/// `shift_reference` (the absolute-Y to within-page-Y conversion offset)
/// (`place_leaf`/`place_line`/`new_page` are left completely unchanged for this branch).
#[allow(clippy::too_many_arguments)]
/// Just the information needed to generate the decoration fragments, extracted from the container being split.
///
/// Because the children (`items`) are handed out by `&mut` while other fields of the same
/// box are still being read, the scalars are copied out first so the borrows do not conflict.
struct SplitContainer {
    node: Option<NodeId>,
    layout: Layout,
    has_visible_decoration: bool,
    /// The marker moves to the first fragment. `place_split` takes it and uses it.
    marker: Option<Box<LineBox>>,
    /// An `<a href>` box is a link area on every page it reaches, so each one gets a fragment.
    link: Option<Rc<str>>,
}

impl SplitContainer {
    /// Extract the scalar information from `b` (taking ownership of the marker).
    fn take_from(b: &mut LaidOutBox) -> Self {
        Self {
            node: b.node,
            layout: b.layout,
            has_visible_decoration: b.has_visible_decoration,
            marker: b.marker.take(),
            link: b.link.take(),
        }
    }

    /// The sum of the container's own top margin, border and padding.
    fn top_extra(&self) -> f32 {
        self.layout.margin.top + self.layout.border.top + self.layout.padding.top
    }
}

#[allow(clippy::too_many_arguments)]
fn place_split<T>(
    container: &mut SplitContainer,
    items: &mut [T],
    page_height: f32,
    state: &mut PaginationState<'_>,
    cursor: &mut f32,
    break_hints: impl Fn(usize, &T) -> (bool, bool),
    keep_with_next: impl Fn(&[T], usize) -> Option<f32>,
    is_float: impl Fn(&T) -> bool,
    item_extent: impl Fn(&T) -> (f32, f32),
    place_one: impl Fn(&mut T, f32, &mut PaginationState<'_>, &mut f32),
) {
    let top_extra = container.top_extra();

    // Reserve room for the container's own top margin, border and padding
    // before the first fragment (no adjustment is made for the extreme case
    // where that room alone exceeds what is left of the page).
    *cursor += top_extra;

    // How much to subtract from an absolute y (the coordinates layout produced)
    // to get an in-page one (`*cursor`). The first in-flow child of a container
    // starts at the container's own content top (`b.layout.content.y`), which is
    // therefore the initial value. It is derived again from where each item
    // actually landed, so that it follows along when a page break resets
    // `*cursor`.
    let mut shift_reference = container.layout.content.y - *cursor;

    // A `b` that paints neither a background nor a border needs no decoration
    // fragment at all. Then there is nothing to track in `segments` and no
    // reason to hold pages back in `PaginationState` (`enter_split` and
    // `exit_split` are not called). Undecorated containers (`<html>`, `<body>`
    // and most wrapper `<div>`s) take this fast path, which is what makes
    // streaming flush often.
    let needs_decoration = container.has_visible_decoration;
    // An outside marker (`list-style-position: outside`) is painted on the first
    // fragment, so a fragment is still needed even without decoration. Skipping
    // it would drop the marker of an `li` split across pages.
    let needs_fragments =
        needs_decoration || container.marker.is_some() || container.link.is_some();
    if needs_fragments {
        // Record the absolute index of the first page this container touches.
        state.enter_split();
    }

    struct Segment {
        page_index: usize,
        start_index: usize,
    }

    let mut current_page = state.current_index();
    let mut segments: Vec<Segment> = if needs_fragments {
        vec![Segment {
            page_index: current_page,
            start_index: state.get(current_page).boxes.len(),
        }]
    } else {
        Vec::new()
    };

    // Shared handling of a forced break (`break-before`/`break-after: always`):
    // start a new page and add the matching segment. `current_page` is updated
    // right here as well, so that a natural break from overflow is not counted
    // twice.
    let force_new_page = |state: &mut PaginationState<'_>,
                          cursor: &mut f32,
                          current_page: &mut usize,
                          segments: &mut Vec<Segment>| {
        new_page(state, cursor);
        *current_page = state.current_index();
        if needs_fragments {
            segments.push(Segment {
                page_index: *current_page,
                start_index: 0,
            });
        }
    };

    let item_count = items.len();
    // Right after a forced break, `shift_reference` still belongs to the
    // previous page. The next item goes to the top of the new one, so it is
    // derived again before use.
    let mut forced_page_start = false;
    for i in 0..item_count {
        let keep_bottom = keep_with_next(items, i);
        let item = &mut items[i];
        let (breaks_before, breaks_after) = break_hints(i, item);
        // If nothing has actually been placed on the current page (including the
        // case where `cursor` has only moved by an ancestor's margin), breaking
        // would only produce an empty page, so do nothing.
        if breaks_before && current_page_has_content(state) {
            force_new_page(state, cursor, &mut current_page, &mut segments);
            forced_page_start = true;
        }

        if is_float(item) {
            // A float takes no part in the flow, so it leaves the shared
            // `cursor` alone. Seeding a temporary cursor from `shift_reference`
            // makes the `shift = margin_box_top - *cursor` inside `place_one`
            // (that is, `place_box`) the same translation as the surrounding
            // flow, which puts the float at the right in-page position.
            let mut local_cursor = item_extent(item).0 - shift_reference;
            place_one(item, page_height, state, &mut local_cursor);
        } else {
            // Map the absolute coordinates layout produced straight into the
            // page. Stacking margin box heights instead would count margin boxes
            // that overlap through margin collapsing twice, reopening the very
            // space the collapse removed: a top margin hoisted out of a first
            // child is added once per ancestor level, and two collapsed sibling
            // margins are both added.
            if forced_page_start {
                shift_reference = item_extent(item).0 - *cursor;
                forced_page_start = false;
            }
            // `break-after: avoid` (or `break-before: avoid` on the next item): the item fits
            // here, but the start of what follows it does not, so the two would be parted.
            // Move the item to the next page with it, unless the page holds nothing yet (the
            // break would gain nothing) or the two do not fit on a page together either.
            if let Some(keep_bottom) = keep_bottom {
                let (top, bottom) = item_extent(item);
                if bottom - shift_reference <= page_height
                    && keep_bottom - shift_reference > page_height
                    && keep_bottom - top <= page_height
                    && current_page_has_content(state)
                {
                    force_new_page(state, cursor, &mut current_page, &mut segments);
                    shift_reference = top - *cursor;
                }
            }
            // Nothing above the top of the page is painted, so stop at 0.
            *cursor = (item_extent(item).0 - shift_reference).max(0.0);
            place_one(item, page_height, state, cursor);
            // `place_one` may have broken the page, so derive the factor again
            // from the result: the in-page coordinate of the item's bottom.
            shift_reference = item_extent(item).1 - *cursor;

            let now_page = state.current_index();
            if now_page != current_page {
                // Moved on to a new page. Nothing but this `b`'s own content can
                // get in, so the pages created here start at index 0.
                if needs_fragments {
                    for p in (current_page + 1)..=now_page {
                        segments.push(Segment {
                            page_index: p,
                            start_index: 0,
                        });
                    }
                }
                current_page = now_page;
            }
        }

        // Break only when there is something left to place, so that no empty
        // page is created after the last item.
        if breaks_after && i + 1 < item_count {
            force_new_page(state, cursor, &mut current_page, &mut segments);
            forced_page_start = true;
        }
    }

    // Hand the caller (the following sibling) the container's own bottom
    // (margin box) in page coordinates. Merely adding `padding-bottom` and the
    // rest would count a `margin-bottom` collapsed with the last child twice, or
    // drop an explicit `height` larger than the content. The cursor is never
    // pulled back above the bottom of the last item placed, so that overflowing
    // content does not end up under a sibling.
    let container_bottom = container.layout.content.y
        + container.layout.content.height
        + container.layout.padding.bottom
        + container.layout.border.bottom
        + container.layout.margin.bottom;
    *cursor = (container_bottom - shift_reference).max(*cursor);

    if !needs_fragments {
        return;
    }

    // Keep only the segments that actually received content (the first child
    // may have forced a break at the top of a page, for one, leaving the page
    // before it empty).
    let valid: Vec<&Segment> = segments
        .iter()
        .filter(|s| state.get(s.page_index).boxes.len() > s.start_index)
        .collect();

    let fragments: Vec<(usize, usize, LaidOutBox)> = valid
        .iter()
        .enumerate()
        .filter_map(|(i, seg)| {
            let is_first = i == 0;
            let is_last = i == valid.len() - 1;
            // An undecorated container only needs the first fragment, the one
            // carrying the marker; the rest would be empty boxes painting
            // nothing. A link needs them all, for its area on each page.
            if !needs_decoration && container.link.is_none() && !is_first {
                return None;
            }
            let end_index = state.get(seg.page_index).boxes.len();
            let (top, bottom) =
                extent_of(&state.get(seg.page_index).boxes[seg.start_index..end_index]);
            let layout = fragment_layout(&container.layout, top, bottom, is_first, is_last);
            // The marker stays on `b`'s first fragment only, so that a box split
            // across pages does not paint it again on every later fragment. Its
            // coordinates are still the absolute ones from layout, so move them
            // into the fragment's in-page space, keeping the offset from the
            // container's content top.
            let marker = if is_first {
                container.marker.take().map(|mut marker| {
                    marker.rect.y -= container.layout.content.y - layout.content.y;
                    marker
                })
            } else {
                None
            };
            let decoration = LaidOutBox {
                node: container.node,
                layout,
                // A decoration-only fragment is never split again, so the
                // fragmentation hints mean nothing here (left at their default).
                fragmentation: FragmentationHints::default(),
                // The box itself holds no children (`Blocks(Vec::new())`) and is
                // never handed to `place_split` again. A fragment made only to
                // carry a marker paints neither background nor border.
                has_visible_decoration: needs_decoration,
                // A decoration fragment is not itself a float: even when `b` is
                // one, the fragment travels with the rest of `place_split`'s loop
                // as part of the normal flow, so this has to stay `false`.
                is_float: false,
                content: LaidOutContent::Blocks(Vec::new()),
                marker,
                link: container.link.clone(),
            };
            Some((seg.page_index, seg.start_index, decoration))
        })
        .collect();

    for (page_index, insert_index, decoration) in fragments {
        state
            .get_mut(page_index)
            .boxes
            .insert(insert_index, decoration);
    }

    // Every decoration fragment of this container is in place, so drop the
    // record. If that made more pages flushable, they go to `on_flush` here.
    state.exit_split();
}

/// Find the vertical union extent, in within-page coordinates, of the descendants really
/// placed in `boxes` (the smallest top and largest bottom of their margin boxes).
fn extent_of(boxes: &[LaidOutBox]) -> (f32, f32) {
    let mut top = f32::INFINITY;
    let mut bottom = f32::NEG_INFINITY;
    for b in boxes {
        let box_top = margin_box_top(b);
        let box_bottom = box_top + b.layout.margin_box_height();
        top = top.min(box_top);
        bottom = bottom.max(box_bottom);
    }
    (top, bottom)
}

/// Assemble the [`Layout`] for drawing one fragment's worth of decoration (background and
/// borders) for the container `original`. `content_y`/`content_bottom` are that fragment's
/// content area extent (with `is_first`, the top is already settled at `content_y`; with
/// `is_last`, the bottom does not yet include `padding-bottom`/`border-bottom`).
///
/// `fragment` (into [`FragmentPosition`]) records the fragment's position, derived from
/// `is_first`/`is_last`. `border-radius` is taken straight from the computed style
/// (`Layout` holds only thicknesses), so the renderer ([`crate::pdf::document`]) uses this
/// information to decide "do not round the corners on a continuing fragment".
fn fragment_layout(
    original: &Layout,
    content_y: f32,
    content_bottom: f32,
    is_first: bool,
    is_last: bool,
) -> Layout {
    let top_border = if is_first { original.border.top } else { 0.0 };
    let bottom_border = if is_last { original.border.bottom } else { 0.0 };
    let top_padding = if is_first { original.padding.top } else { 0.0 };
    let bottom_padding = if is_last {
        original.padding.bottom
    } else {
        0.0
    };
    let fragment = match (is_first, is_last) {
        (true, true) => FragmentPosition::Whole,
        (true, false) => FragmentPosition::First,
        (false, true) => FragmentPosition::Last,
        (false, false) => FragmentPosition::Middle,
    };

    Layout {
        content: Rect {
            x: original.content.x,
            y: content_y,
            width: original.content.width,
            height: (content_bottom - content_y).max(0.0),
        },
        padding: EdgeSizes {
            top: top_padding,
            right: original.padding.right,
            bottom: bottom_padding,
            left: original.padding.left,
        },
        border: EdgeSizes {
            top: top_border,
            right: original.border.right,
            bottom: bottom_border,
            left: original.border.left,
        },
        margin: EdgeSizes::default(),
        fragment,
    }
}

fn place_line(line: &LineBox, page_height: f32, state: &mut PaginationState<'_>, cursor: &mut f32) {
    if *cursor > 0.0 && *cursor + line.rect.height > page_height {
        new_page(state, cursor);
    }

    let shift = line.rect.y - *cursor;
    let mut translated = line.clone();
    translated.rect.y -= shift;
    // The `display: inline-block` boxes in a line move with the line (moving only the line's
    // rect would strand the boxes at their original positions). `shift_box_y`'s `delta` is an
    // amount to subtract (`rect.y -= delta`), so the same movement as the line's
    // `rect.y -= shift` is achieved by passing `shift` through unchanged.
    for atomic in translated.atomics.iter_mut() {
        atomic.content = shift_box_y(&atomic.content, shift);
    }

    let fragment = LaidOutBox {
        node: None,
        layout: Layout {
            content: translated.rect,
            ..Layout::default()
        },
        // A synthesised wrapper box holding a single line, so it carries no fragmentation
        // hints (orphans/widows are decided per line by the caller, `place_split`).
        fragmentation: FragmentationHints::default(),
        has_visible_decoration: false,
        // A line box has no concept of a float.
        is_float: false,
        content: LaidOutContent::Inline(vec![translated]),
        // A single-line synthesised wrapper is never a list-item itself, so this is always
        // `None` (the original container's `marker` is carried by the decoration fragment above).
        marker: None,
        // Likewise, the container's link area is its decoration fragment's.
        link: None,
    };
    *cursor += line.rect.height;
    state.last_mut().boxes.push(fragment);
}

/// Split a table across pages row by row.
///
/// Consecutive rows landing on the same page are gathered into one fragment (a `LaidOutBox`
/// holding `LaidOutContent::Table`). A fragment inherits the table's own node and geometry,
/// replacing only `content.y`/`content.height` and `FragmentPosition`.
/// Place a grid container across pages by row band. The same "assemble a fragment and settle
/// it" structure as `place_table`, with the row band as the unit.
///
/// No split happens at a boundary where an item spans the bottom of the band (a grid item
/// spanning several rows), the same as a table's `rowspan`.
fn place_grid(
    container: &SplitContainer,
    grid: &LaidOutGrid,
    page_height: f32,
    state: &mut PaginationState<'_>,
    cursor: &mut f32,
) {
    let top_extra = container.top_extra();
    let bottom_extra = container.layout.padding.bottom
        + container.layout.border.bottom
        + container.layout.margin.bottom;

    let mut pending: Vec<LaidOutGridRow> = Vec::new();
    let mut shift = 0.0f32;
    let mut fragment_top = 0.0f32;
    let mut is_first_fragment = true;

    // Before the first fragment, reserve the container's own top margin, border and padding
    // (handled the same way as in `place_split`/`place_table`).
    *cursor += top_extra;

    for (index, row) in grid.rows.iter().enumerate() {
        if pending.is_empty() {
            fragment_top = *cursor;
            shift = row.top - *cursor;

            // When the first row of a fragment does not fit in what is left of
            // the page, start at the top of the next one rather than overflow
            // (without this, a row laid down at the bottom of the page loses its
            // lower half). A row too tall for an empty page is placed as it is,
            // so that pagination keeps moving forward.
            if row.bottom - shift > page_height && current_page_has_content(state) {
                new_page(state, cursor);
                // Still the first fragment: its top margin, border and padding were reserved
                // on the page just left, so reserve them again on this one.
                if is_first_fragment {
                    *cursor += top_extra;
                }
                fragment_top = *cursor;
                shift = row.top - *cursor;
            }
        }

        // With an item carried over from the previous band, no cut is possible at that boundary.
        let can_break_before = index > 0 && !grid.rows[index - 1].spans_bottom;
        let row_bottom_on_page = row.bottom - shift;
        if row_bottom_on_page > page_height && !pending.is_empty() && can_break_before {
            flush_grid_fragment(
                container,
                &mut pending,
                fragment_top,
                *cursor,
                is_first_fragment,
                false,
                state,
            );
            is_first_fragment = false;
            new_page(state, cursor);
            fragment_top = *cursor;
            shift = row.top - *cursor;
        }

        pending.push(shift_grid_row_y(row, shift));
        *cursor = row.bottom - shift;
    }

    flush_grid_fragment(
        container,
        &mut pending,
        fragment_top,
        *cursor,
        is_first_fragment,
        true,
        state,
    );
    *cursor += bottom_extra;
}

/// Translates a row band, and the items inside it, along Y. As in `shift_box_y`,
/// `delta` is the amount to subtract (absolute y minus in-page y).
fn shift_grid_row_y(row: &LaidOutGridRow, delta: f32) -> LaidOutGridRow {
    LaidOutGridRow {
        items: row
            .items
            .iter()
            .map(|item| shift_box_y(item, delta))
            .collect(),
        top: row.top - delta,
        bottom: row.bottom - delta,
        spans_bottom: row.spans_bottom,
    }
}

/// Push the row bands `place_grid` assembled onto the page as one fragment.
fn flush_grid_fragment(
    container: &SplitContainer,
    rows: &mut Vec<LaidOutGridRow>,
    fragment_top: f32,
    fragment_bottom: f32,
    is_first: bool,
    is_last: bool,
    state: &mut PaginationState<'_>,
) {
    if rows.is_empty() {
        return;
    }

    // `fragment_top`/`fragment_bottom` already bound the content: the caller reserves the top
    // margin, border and padding before the first fragment and the bottom ones after the
    // last, so the decoration is sliced the same way as in `place_split`.
    let layout = fragment_layout(
        &container.layout,
        fragment_top,
        fragment_bottom,
        is_first,
        is_last,
    );

    let fragment = LaidOutBox {
        node: container.node,
        layout,
        fragmentation: FragmentationHints::default(),
        is_float: false,
        marker: None,
        has_visible_decoration: container.has_visible_decoration,
        content: LaidOutContent::Grid(LaidOutGrid {
            rows: std::mem::take(rows),
        }),
        link: container.link.clone(),
    };
    state.last_mut().boxes.push(fragment);
}

/// The unit a flex container taller than a page is split into: a band grouping
/// items that overlap vertically. In a column flex each item is a band; in a row
/// flex each flex line is. `top`/`bottom` are absolute y coordinates of the
/// margin box.
struct FlexBand {
    items: Vec<LaidOutBox>,
    top: f32,
    bottom: f32,
}

/// Tolerance (px) used when deciding where a band ends. The coordinates taffy
/// returns are floating point, so this keeps items that merely touch from being
/// mistaken for overlapping ones.
const FLEX_BAND_EPSILON: f32 = 0.01;

/// Groups flex items into bands by vertical overlap.
///
/// With `flex-direction: column` each item is a band; with a wrapping row flex
/// each flex line is; a row flex that does not wrap is usually a single band,
/// that is, atomic as before. The decision is purely geometric, so items of one
/// row that do not overlap vertically (`align-self` placing a short item at the
/// far end of a tall line, say) do end up in bands of their own, and a visual
/// order that differs from document order (through `order`, say) makes no
/// difference.
fn group_flex_items_into_bands(mut items: Vec<LaidOutBox>) -> Vec<FlexBand> {
    // Order by top edge (a stable sort, so items sharing a top edge keep their
    // document order).
    items.sort_by(|a, b| margin_box_top(a).total_cmp(&margin_box_top(b)));
    let mut bands: Vec<FlexBand> = Vec::new();
    for item in items {
        let top = margin_box_top(&item);
        let bottom = top + item.layout.margin_box_height();
        match bands.last_mut() {
            Some(band) if top < band.bottom - FLEX_BAND_EPSILON => {
                band.items.push(item);
                band.bottom = band.bottom.max(bottom);
            }
            _ => bands.push(FlexBand {
                items: vec![item],
                top,
                bottom,
            }),
        }
    }
    bands
}

/// Places one flex band on a page. Called from [`place_split`].
///
/// A band holding a single item (each item of a column flex) goes to
/// [`place_box`] as an ordinary box, so an item taller than a page is split
/// inside it like a block. A band with several items side by side is treated as
/// one leaf, to keep the items in the same position relative to each other: if
/// it does not fit in what is left it is moved to the top of the next page, and
/// if the band itself is taller than a page it overflows, as before.
fn place_flex_band(
    band: &mut FlexBand,
    page_height: f32,
    state: &mut PaginationState<'_>,
    cursor: &mut f32,
) {
    if let [item] = band.items.as_mut_slice() {
        place_box(item, page_height, state, cursor);
        return;
    }
    let height = band.bottom - band.top;
    if *cursor > 0.0 && *cursor + height > page_height {
        new_page(state, cursor);
    }
    let base = *cursor;
    for item in band.items.iter_mut() {
        let mut local_cursor = base + (margin_box_top(item) - band.top);
        place_leaf(item, state, &mut local_cursor);
    }
    *cursor = base + height;
}

fn place_table(
    container: &SplitContainer,
    table: &mut LaidOutTable,
    page_height: f32,
    state: &mut PaginationState<'_>,
    cursor: &mut f32,
) {
    let top_extra = container.top_extra();
    let bottom_extra = container.layout.padding.bottom
        + container.layout.border.bottom
        + container.layout.margin.bottom;

    // The rows to push into the fragment, and the translation from absolute to within-page coordinates.
    let mut pending: Vec<LaidOutTableRow> = Vec::new();
    let mut shift = 0.0f32;
    let mut fragment_top = 0.0f32;
    let mut is_first_fragment = true;

    // The `<thead>` rows to repeat at the top of the second page onwards. They are not
    // repeated when the headings alone fill the page (that is, when not a single row advances).
    // A heading row is copied and placed on the second page onwards, so this is the one place
    // that holds a copy (there are few of them). Body rows are moved rather than copied.
    let head_rows: Vec<LaidOutTableRow> = table
        .rows
        .iter()
        .filter(|row| row.section == TableSection::Head)
        .cloned()
        .collect();
    let head_top = head_rows.iter().map(table_row_top).fold(f32::MAX, f32::min);
    let head_bottom = head_rows
        .iter()
        .map(table_row_bottom)
        .fold(f32::MIN, f32::max);
    let head_height = if head_rows.is_empty() {
        0.0
    } else {
        head_bottom - head_top
    };
    let repeat_head = !head_rows.is_empty() && head_height < page_height;
    // A `caption-side: top` caption goes on the first fragment.
    let caption_is_top = table.caption_side == CaptionSide::Top;
    let mut pending_caption = table.caption.as_deref().filter(|_| caption_is_top).cloned();

    // Before the first fragment, reserve the container's own top margin, border and padding
    // (handled the same way as in `place_split`).
    *cursor += top_extra;

    // The caption's height counts towards the first fragment too.
    let caption_height = pending_caption
        .as_ref()
        .map(|c| c.layout.margin_box_height())
        .unwrap_or(0.0);

    let start_new_fragment = |cursor: &f32, first_row_top: f32, extra_above: f32| {
        // The top of the fragment (in within-page coordinates), and the translation to get it there.
        let top = *cursor;
        (top, first_row_top - extra_above - *cursor)
    };

    for (index, mut row) in std::mem::take(&mut table.rows).into_iter().enumerate() {
        let row_top = table_row_top(&row);
        let row_bottom = table_row_bottom(&row);
        let extra_above = if index == 0 { caption_height } else { 0.0 };

        if pending.is_empty() {
            let (top, s) = start_new_fragment(cursor, row_top, extra_above);
            fragment_top = top;
            shift = s;

            // As with the grid, start on the next page when the first row does
            // not fit in what is left (the caption height counts towards it).
            if row_bottom - shift > page_height && current_page_has_content(state) {
                new_page(state, cursor);
                // Still the first fragment: reserve its top margin, border and padding again
                // (as in `place_grid`).
                if is_first_fragment {
                    *cursor += top_extra;
                }
                let (top, s) = start_new_fragment(cursor, row_top, extra_above);
                fragment_top = top;
                shift = s;
            }
        }

        // If this row would overflow the current page, settle the fragment so far and break.
        // The check is "this fragment already has at least one row" (not
        // `current_page_has_content`): a table has to split per row even when it is the only
        // content at the top of a page, and never creating an empty fragment guarantees progress.
        let row_bottom_on_page = row_bottom - shift;
        if row_bottom_on_page > page_height && !pending.is_empty() {
            flush_table_fragment(
                container,
                &mut pending,
                &mut pending_caption,
                fragment_top,
                *cursor,
                is_first_fragment,
                false,
                state,
            );
            is_first_fragment = false;
            new_page(state, cursor);
            fragment_top = *cursor;
            // Copy the heading rows to the top of the new page (the original rows are placed
            // on the first page as-is, so copies only appear from the second page on).
            if repeat_head {
                let head_shift = head_top - *cursor;
                for head_row in &head_rows {
                    pending.push(shift_table_row_y(head_row, head_shift));
                }
                *cursor += head_height;
            }
            shift = row_top - *cursor;
        }

        shift_table_row_y_in_place(&mut row, shift);
        pending.push(row);
        *cursor = row_bottom - shift;
    }

    // A `caption-side: bottom` caption goes on the last fragment.
    if !caption_is_top {
        if let Some(caption) = table.caption.as_deref() {
            let translated = shift_box_y(caption, shift);
            *cursor += caption.layout.margin_box_height();
            pending_caption = Some(translated);
        }
    }

    flush_table_fragment(
        container,
        &mut pending,
        &mut pending_caption,
        fragment_top,
        *cursor,
        is_first_fragment,
        true,
        state,
    );
    *cursor += bottom_extra;
}

/// Push the rows `place_table` assembled onto the page as one fragment.
#[allow(clippy::too_many_arguments)]
fn flush_table_fragment(
    container: &SplitContainer,
    rows: &mut Vec<LaidOutTableRow>,
    caption: &mut Option<LaidOutBox>,
    fragment_top: f32,
    fragment_bottom: f32,
    is_first: bool,
    is_last: bool,
    state: &mut PaginationState<'_>,
) {
    if rows.is_empty() && caption.is_none() {
        return;
    }

    // `fragment_top`/`fragment_bottom` already bound the content: the caller reserves the top
    // margin, border and padding before the first fragment and the bottom ones after the
    // last, so the decoration is sliced the same way as in `place_split`.
    let layout = fragment_layout(
        &container.layout,
        fragment_top,
        fragment_bottom,
        is_first,
        is_last,
    );

    let fragment = LaidOutBox {
        node: container.node,
        layout,
        fragmentation: FragmentationHints::default(),
        has_visible_decoration: container.has_visible_decoration,
        is_float: false,
        content: LaidOutContent::Table(LaidOutTable {
            caption: caption.take().map(Box::new),
            caption_side: CaptionSide::Top,
            rows: std::mem::take(rows),
        }),
        marker: None,
        link: container.link.clone(),
    };
    state.last_mut().boxes.push(fragment);
}

/// The absolute Y of the top of a table row's margin box (the topmost among its cells).
fn table_row_top(row: &LaidOutTableRow) -> f32 {
    row.cells
        .iter()
        .map(margin_box_top)
        .fold(f32::MAX, f32::min)
}

/// The absolute Y of the bottom of a table row's margin box (the lowest among its cells).
fn table_row_bottom(row: &LaidOutTableRow) -> f32 {
    row.cells
        .iter()
        .map(|cell| margin_box_top(cell) + cell.layout.margin_box_height())
        .fold(f32::MIN, f32::max)
}

/// Translate a row (all of its cells) vertically in place.
fn shift_table_row_y_in_place(row: &mut LaidOutTableRow, shift: f32) {
    for cell in &mut row.cells {
        shift_box_y_in_place(cell, shift);
    }
}

/// Translate a row (all of its cells) vertically. `shift` is an amount to subtract, as in `shift_box_y`.
fn shift_table_row_y(row: &LaidOutTableRow, shift: f32) -> LaidOutTableRow {
    LaidOutTableRow {
        node: row.node,
        cells: row.cells.iter().map(|c| shift_box_y(c, shift)).collect(),
        section: row.section,
        group: row.group,
    }
}

/// Move a box that will not be split further onto the page as-is.
///
/// The contents (`content`/`marker`) are taken by ownership. Cloning here would mean the
/// layout result and the pages existing at once, doubling the peak memory on a large
/// document. After the take, `b` becomes an empty `Blocks` and the caller never reads its
/// contents again (every path returns immediately afterwards).
fn place_leaf(b: &mut LaidOutBox, state: &mut PaginationState<'_>, cursor: &mut f32) {
    let shift = margin_box_top(b) - *cursor;
    let height = b.layout.margin_box_height();

    let mut translated = LaidOutBox {
        node: b.node,
        layout: b.layout,
        fragmentation: b.fragmentation,
        has_visible_decoration: b.has_visible_decoration,
        is_float: false,
        content: std::mem::replace(&mut b.content, LaidOutContent::Blocks(Vec::new())),
        marker: b.marker.take(),
        link: b.link.take(),
    };
    shift_box_y_in_place(&mut translated, shift);

    *cursor += height;
    state.last_mut().boxes.push(translated);
}

fn new_page(state: &mut PaginationState<'_>, cursor: &mut f32) {
    state.push_new_page();
    // When the call stack holds only containers with no decoration (which never call
    // `enter_split`/`exit_split`), no flush ever happens via `exit_split`, so the flush check
    // also runs here whenever a new page starts. That gives the finest streaming granularity:
    // in a structure with no decoration, a page is flushed the moment it is settled.

    state.try_flush();
    *cursor = 0.0;
}

/// Whether even one box has actually been placed on the current page. `cursor` may already
/// have advanced by an ancestor's margin, border or padding (so `cursor > 0.0` is possible
/// with nothing drawn yet), so this, rather than `cursor`, is what decides "is a forced break
/// really a meaningful move (that is, does it avoid discarding the current page while empty)".
fn current_page_has_content(state: &PaginationState<'_>) -> bool {
    !state.last().boxes.is_empty()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fonts::Font;
    use crate::html::{self, Dom, NodeData};
    use crate::layout::block::layout_document_from;
    use crate::layout::box_tree::build_box_for_element;
    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 box_contains_node(b: &LaidOutBox, target: NodeId) -> bool {
        if b.node == Some(target) {
            return true;
        }
        if let LaidOutContent::Blocks(children) = &b.content {
            return children
                .iter()
                .any(|child| box_contains_node(child, target));
        }
        false
    }

    /// Recursively check that the boxes on a page stay within the page height (allowing a
    /// small tolerance).
    fn assert_within_page(b: &LaidOutBox, page_height: f32) {
        let top = margin_box_top(b);
        assert!(top >= -0.01, "box top {top} should not be negative");
        assert!(
            top + b.layout.margin_box_height() <= page_height + 0.01,
            "box bottom should not exceed page height {page_height}"
        );
        if let LaidOutContent::Blocks(children) = &b.content {
            for child in children {
                assert_within_page(child, page_height);
            }
        }
    }

    #[test]
    fn page_settings_computes_content_area() {
        let settings = PageSettings::default();
        assert_eq!(
            settings.content_width(),
            settings.size.width - settings.margin.left - settings.margin.right
        );
        assert_eq!(
            settings.content_height(),
            settings.size.height - settings.margin.top - settings.margin.bottom
        );
    }

    #[test]
    fn short_document_fits_on_a_single_page_and_keeps_structure() {
        let dom = html::parse(br#"<p>hello</p>"#);
        let ua = user_agent_stylesheet();
        let author = Stylesheet::default();
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let pages = paginate_document(&dom, &styles, &fonts, &settings);
        assert_eq!(pages.len(), 1);

        // No split occurs, so the original structure including the anonymous root (node: None) should be intact.
        let mut htmls = Vec::new();
        find_all(&dom, dom.document(), "html", &mut htmls);
        assert_eq!(pages[0].boxes.len(), 1);
        assert_eq!(pages[0].boxes[0].node, None);
        assert!(box_contains_node(&pages[0].boxes[0], htmls[0]));
        // An unsplit box is `Whole` (border-radius may apply to every corner).
        assert_eq!(pages[0].boxes[0].layout.fragment, FragmentPosition::Whole);
    }

    #[test]
    fn tall_content_distributes_across_multiple_pages_without_losing_items() {
        let mut html_src = String::from("<div>");
        for i in 0..20 {
            html_src.push_str(&format!(r#"<p class="item">item {i}</p>"#));
        }
        html_src.push_str("</div>");
        let dom = html::parse(html_src.as_bytes());

        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(".item { height: 100px; margin: 0; }");
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let pages = paginate_document(&dom, &styles, &fonts, &settings);
        assert!(
            pages.len() > 1,
            "20 items of 100px should overflow a single page"
        );

        let mut ps = Vec::new();
        find_all(&dom, dom.document(), "p", &mut ps);
        assert_eq!(ps.len(), 20);
        for &p_id in &ps {
            let found_on_some_page = pages
                .iter()
                .any(|page| page.boxes.iter().any(|b| box_contains_node(b, p_id)));
            assert!(
                found_on_some_page,
                "p {p_id:?} should be placed on some page"
            );
        }

        for page in &pages {
            for b in &page.boxes {
                assert_within_page(b, settings.content_height());
            }
        }
    }

    #[test]
    fn float_taller_than_a_page_splits_across_pages_without_losing_items() {
        let mut html_src = String::from(r#"<div><div class="f">"#);
        for i in 0..20 {
            html_src.push_str(&format!(r#"<p class="item">item {i}</p>"#));
        }
        html_src.push_str("</div></div>");
        let dom = html::parse(html_src.as_bytes());

        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            "body { margin: 0; } \
             .f { float: left; width: 100px; } \
             .item { height: 100px; margin: 0; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let pages = paginate_document(&dom, &styles, &fonts, &settings);
        assert!(
            pages.len() > 1,
            "a float containing 20 items of 100px should overflow a single page \
             (a float is allowed to cross a page boundary)"
        );

        let mut ps = Vec::new();
        find_all(&dom, dom.document(), "p", &mut ps);
        assert_eq!(ps.len(), 20);
        for &p_id in &ps {
            let found_on_some_page = pages
                .iter()
                .any(|page| page.boxes.iter().any(|b| box_contains_node(b, p_id)));
            assert!(
                found_on_some_page,
                "p {p_id:?} inside the float should be placed on some page"
            );
        }

        for page in &pages {
            for b in &page.boxes {
                assert_within_page(b, settings.content_height());
            }
        }
    }

    #[test]
    fn float_is_translated_to_page_relative_coordinates_consistently_with_siblings() {
        let dom = html::parse(br#"<div><div class="a">a</div><div class="f">F</div></div>"#);
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            "body { margin: 0; } \
             .a { height: 50px; margin: 0; } \
             .f { float: left; width: 30px; height: 20px; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let pages = paginate_document(&dom, &styles, &fonts, &settings);
        assert_eq!(pages.len(), 1);

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

        fn find_box(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_box(child, target) {
                        return Some(found);
                    }
                }
            }
            None
        }

        let float_box = pages[0]
            .boxes
            .iter()
            .find_map(|b| find_box(b, divs[2]))
            .expect("float box not found on the page");

        // On the block.rs side a float is placed at the `cursor_y`=50 the previous sibling `a`
        // (height:50px) advanced the normal flow to (that is, right after `a`), a float starting
        // from the cursor_y where it was found in DOM order. No page break has happened, so
        // this absolute Y should carry over as the within-page Y
        // (if shift_reference works, the float's position does not shift).
        assert_eq!(float_box.layout.content.y, 50.0);
    }

    #[test]
    fn long_paragraph_splits_across_pages_by_line() {
        let words: Vec<String> = (0..1000).map(|i| format!("word{i}")).collect();
        let html_src = format!("<p>{}</p>", words.join(" "));
        let dom = html::parse(html_src.as_bytes());

        let ua = user_agent_stylesheet();
        let author = Stylesheet::default();
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let pages = paginate_document(&dom, &styles, &fonts, &settings);
        assert!(
            pages.len() > 1,
            "1000 words should wrap into more lines than fit on one page"
        );

        let total_lines: usize = pages
            .iter()
            .flat_map(|page| &page.boxes)
            .filter_map(|b| match &b.content {
                LaidOutContent::Inline(lines) => Some(lines.len()),
                _ => None,
            })
            .sum();
        assert!(
            total_lines > 20,
            "1000 words should wrap into many lines total, got {total_lines}"
        );
        assert!(
            pages[0].boxes.len() > 1,
            "first page should hold multiple line fragments, got {}",
            pages[0].boxes.len()
        );
    }

    /// Find, among `page.boxes`, one whose node is `target` and whose content is
    /// `LaidOutContent::Blocks(vec![])` (that is, a decoration-only fragment).
    fn find_decoration_fragment(page: &Page, target: NodeId) -> Option<&LaidOutBox> {
        page.boxes.iter().find(|b| {
            b.node == Some(target)
                && matches!(&b.content, LaidOutContent::Blocks(c) if c.is_empty())
        })
    }

    #[test]
    fn split_container_gets_a_decoration_fragment_on_every_page_it_spans() {
        let mut html_src = String::from(r#"<div class="wrapper">"#);
        for i in 0..20 {
            html_src.push_str(&format!(r#"<p class="item">item {i}</p>"#));
        }
        html_src.push_str("</div>");
        let dom = html::parse(html_src.as_bytes());

        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            ".wrapper { border: 2px solid black; padding: 5px; margin: 0; } \
             .item { height: 100px; margin: 0; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let pages = paginate_document(&dom, &styles, &fonts, &settings);
        assert!(
            pages.len() >= 3,
            "expected the wrapper to span at least 3 pages, got {}",
            pages.len()
        );

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let wrapper = divs[0];

        // Every page should carry a decoration fragment for the wrapper
        // (checking that the background and borders survive across pages).
        let decorations: Vec<&LaidOutBox> = pages
            .iter()
            .map(|page| {
                find_decoration_fragment(page, wrapper)
                    .expect("every page the wrapper spans should carry a decoration fragment")
            })
            .collect();

        // Only the first fragment has the top border and padding.
        assert_eq!(decorations[0].layout.border.top, 2.0);
        assert_eq!(decorations[0].layout.padding.top, 5.0);
        assert_eq!(decorations[0].layout.fragment, FragmentPosition::First);
        // Only the last fragment has the bottom border and padding.
        let last = decorations.last().unwrap();
        assert_eq!(last.layout.border.bottom, 2.0);
        assert_eq!(last.layout.padding.bottom, 5.0);
        assert_eq!(last.layout.fragment, FragmentPosition::Last);
        // A middle fragment is `Middle` (used to suppress border-radius rounding).
        for decoration in &decorations[1..decorations.len() - 1] {
            assert_eq!(decoration.layout.fragment, FragmentPosition::Middle);
        }

        // The left and right borders and padding apply to every fragment.
        for decoration in &decorations {
            assert_eq!(decoration.layout.border.left, 2.0);
            assert_eq!(decoration.layout.padding.left, 5.0);
            assert!(decoration.layout.content.height > 0.0);
        }

        // A middle fragment (neither first nor last) has no top or bottom border or padding.
        for decoration in &decorations[1..decorations.len() - 1] {
            assert_eq!(decoration.layout.border.top, 0.0);
            assert_eq!(decoration.layout.border.bottom, 0.0);
            assert_eq!(decoration.layout.padding.top, 0.0);
            assert_eq!(decoration.layout.padding.bottom, 0.0);
        }

        // Every one of the <p>s inside should still be found (a regression check that adding
        // decoration fragments has no side effect on the existing child placement logic).
        let mut ps = Vec::new();
        find_all(&dom, dom.document(), "p", &mut ps);
        for &p_id in &ps {
            let found = pages
                .iter()
                .any(|page| page.boxes.iter().any(|b| box_contains_node(b, p_id)));
            assert!(found, "p {p_id:?} should still be placed on some page");
        }
    }

    #[test]
    fn split_container_without_visible_decoration_gets_no_decoration_fragment() {
        // A container with neither a background colour nor borders generates no decoration fragment at all
        let mut html_src = String::from("<div>");
        for i in 0..20 {
            html_src.push_str(&format!(r#"<p class="item">item {i}</p>"#));
        }
        html_src.push_str("</div>");
        let dom = html::parse(html_src.as_bytes());

        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(".item { height: 100px; margin: 0; }");
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let pages = paginate_document(&dom, &styles, &fonts, &settings);
        assert!(
            pages.len() > 1,
            "expected the wrapper to span multiple pages"
        );

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let wrapper = divs[0];

        for page in &pages {
            assert!(
                find_decoration_fragment(page, wrapper).is_none(),
                "a wrapper without background/border should not get a decoration fragment"
            );
        }
    }

    /// Whether the page holds a box whose node is `target` and that carries real content
    /// (rather than being a decoration-only fragment).
    fn page_contains_content(page: &Page, target: NodeId) -> bool {
        page.boxes.iter().any(|b| box_contains_node(b, target))
    }

    #[test]
    fn break_before_always_forces_a_new_page_even_though_both_fit_on_one_page() {
        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: 50px; margin: 0; break-before: always; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let pages = paginate_document(&dom, &styles, &fonts, &settings);
        assert_eq!(
            pages.len(),
            2,
            "break-before: always should force a new page even though both \
             paragraphs easily fit on a single page"
        );

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

        assert!(page_contains_content(&pages[0], a));
        assert!(!page_contains_content(&pages[0], b));
        assert!(page_contains_content(&pages[1], b));
        assert!(!page_contains_content(&pages[1], a));
    }

    #[test]
    fn break_before_always_on_the_first_element_does_not_create_a_blank_leading_page() {
        let dom = html::parse(br#"<p class="a">A</p>"#);
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(".a { height: 50px; margin: 0; break-before: always; }");
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let pages = paginate_document(&dom, &styles, &fonts, &settings);
        assert_eq!(
            pages.len(),
            1,
            "break-before: always on the very first element of the document \
             should not produce a blank leading page"
        );
    }

    #[test]
    fn break_after_always_forces_a_new_page_before_the_next_sibling() {
        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; break-after: always; } \
             .b { height: 50px; margin: 0; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let pages = paginate_document(&dom, &styles, &fonts, &settings);
        assert_eq!(pages.len(), 2);

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

        assert!(page_contains_content(&pages[0], a));
        assert!(page_contains_content(&pages[1], b));
        assert!(!page_contains_content(&pages[0], b));
    }

    #[test]
    fn break_after_always_on_the_last_element_does_not_create_a_trailing_blank_page() {
        let dom = html::parse(br#"<p class="a">A</p>"#);
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(".a { height: 50px; margin: 0; break-after: always; }");
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let pages = paginate_document(&dom, &styles, &fonts, &settings);
        assert_eq!(
            pages.len(),
            1,
            "break-after: always on the very last element should not produce \
             a trailing blank page"
        );
    }

    #[test]
    fn nested_break_before_is_honored_even_when_the_whole_subtree_fits_on_one_page() {
        // The wrapper div's contents add up to very little (against the default page height)
        // and could take the "place it as a single leaf" fast path. Even so, the b inside has
        // `break-before: always` and it must not be missed.
        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: 10px; margin: 0; } \
             .b { height: 10px; margin: 0; break-before: always; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let pages = paginate_document(&dom, &styles, &fonts, &settings);
        assert_eq!(pages.len(), 2);

        let mut ps = Vec::new();
        find_all(&dom, dom.document(), "p", &mut ps);
        assert!(page_contains_content(&pages[0], ps[0]));
        assert!(page_contains_content(&pages[1], ps[1]));
    }

    #[test]
    fn break_inside_avoid_moves_the_whole_block_to_the_next_page_instead_of_splitting() {
        let settings = PageSettings::default();
        // Use filler to make the height left on the page smaller than the wrapper's total
        // height (400px), while the wrapper alone still fits a blank page whole.
        let filler_height = settings.content_height() - 200.0;
        let html_src = r#"<div class="filler"></div>
               <div class="wrapper">
                   <p class="a">A</p><p class="b">B</p><p class="c">C</p><p class="d">D</p>
               </div>"#;
        let dom = html::parse(html_src.as_bytes());

        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(&format!(
            ".filler {{ height: {filler_height}px; margin: 0; }} \
             .wrapper {{ break-inside: avoid; margin: 0; }} \
             .a, .b, .c, .d {{ height: 100px; margin: 0; }}"
        ));
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();

        let pages = paginate_document(&dom, &styles, &fonts, &settings);
        assert_eq!(
            pages.len(),
            2,
            "the wrapper should move to a fresh second page instead of splitting"
        );

        let mut ps = Vec::new();
        find_all(&dom, dom.document(), "p", &mut ps);
        for &p in &ps {
            assert!(
                page_contains_content(&pages[1], p),
                "all paragraphs of the avoid-split wrapper should land on page 2"
            );
            assert!(!page_contains_content(&pages[0], p));
        }
    }

    /// Paginates `body` under `css` on the default page, after a filler that leaves `room` px
    /// of the first page free.
    fn paginate_after_filler(room: f32, body: &str, css: &str) -> (Dom, Vec<Page>) {
        let settings = PageSettings::default();
        let filler_height = settings.content_height() - room;
        let dom = html::parse(format!(r#"<div class="filler"></div>{body}"#).as_bytes());
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(&format!(
            ".filler {{ height: {filler_height}px; margin: 0; }} \
             h2, p, table {{ margin: 0; }} h2 {{ height: 40px; }} p {{ height: 100px; }} {css}"
        ));
        let styles = compute_styles(&dom, &ua, &author);
        let pages = paginate_document(&dom, &styles, &test_fonts(), &settings);
        (dom, pages)
    }

    /// The index of the page each `tag` element is placed on.
    fn pages_of(dom: &Dom, pages: &[Page], tag: &str) -> Vec<usize> {
        let mut nodes = Vec::new();
        find_all(dom, dom.document(), tag, &mut nodes);
        nodes
            .iter()
            .map(|&node| {
                pages
                    .iter()
                    .position(|page| page_contains_content(page, node))
                    .expect("every element is placed on a page")
            })
            .collect()
    }

    #[test]
    fn break_after_avoid_moves_a_heading_the_next_block_does_not_fit_under() {
        let (dom, pages) = paginate_after_filler(
            60.0,
            "<section><h2>Heading</h2><p>Body</p></section>",
            "h2 { break-after: avoid; }",
        );
        assert_eq!(pages_of(&dom, &pages, "h2"), vec![1]);
        assert_eq!(pages_of(&dom, &pages, "p"), vec![1]);
    }

    #[test]
    fn a_heading_without_break_after_avoid_stays_at_the_foot_of_the_page() {
        let (dom, pages) =
            paginate_after_filler(60.0, "<section><h2>Heading</h2><p>Body</p></section>", "");
        assert_eq!(pages_of(&dom, &pages, "h2"), vec![0]);
        assert_eq!(pages_of(&dom, &pages, "p"), vec![1]);
    }

    #[test]
    fn break_after_avoid_keeps_a_heading_in_place_when_the_next_block_fits_under_it() {
        let (dom, pages) = paginate_after_filler(
            200.0,
            "<section><h2>Heading</h2><p>Body</p><p>More</p></section>",
            "h2 { break-after: avoid; }",
        );
        assert_eq!(pages_of(&dom, &pages, "h2"), vec![0]);
        assert_eq!(pages_of(&dom, &pages, "p"), vec![0, 1]);
    }

    #[test]
    fn break_before_avoid_on_the_next_block_moves_the_heading_too() {
        let (dom, pages) = paginate_after_filler(
            60.0,
            "<section><h2>Heading</h2><p>Body</p></section>",
            "p { break-before: avoid; }",
        );
        assert_eq!(pages_of(&dom, &pages, "h2"), vec![1]);
    }

    #[test]
    fn break_after_avoid_moves_stacked_headings_together() {
        // A list heading, then a nested item heading, then the item's body: there is room
        // for both headings but not the body, so both move with it.
        let (dom, pages) = paginate_after_filler(
            100.0,
            "<section><h2>List</h2><div><div><h2>Item</h2><p>Body</p></div></div></section>",
            "h2 { break-after: avoid; } div { margin: 0; }",
        );
        assert_eq!(pages_of(&dom, &pages, "h2"), vec![1, 1]);
        assert_eq!(pages_of(&dom, &pages, "p"), vec![1]);
    }

    #[test]
    fn break_after_avoid_keeps_a_heading_with_the_first_row_of_a_table() {
        let mut rows = String::new();
        for i in 0..20 {
            rows.push_str(&format!("<tr><td>row {i}</td></tr>"));
        }
        let (dom, pages) = paginate_after_filler(
            60.0,
            &format!("<section><h2>Heading</h2><table>{rows}</table></section>"),
            "h2 { break-after: avoid; } td { height: 30px; padding: 0; }",
        );
        assert_eq!(pages_of(&dom, &pages, "h2"), vec![1]);
        // The table starts on the page the heading moved to (its first row is there).
        assert_eq!(pages_of(&dom, &pages, "table"), vec![1]);
    }

    #[test]
    fn break_after_avoid_gives_up_when_the_heading_and_the_next_block_do_not_fit_a_page() {
        let settings = PageSettings::default();
        let tall = settings.content_height();
        let (dom, pages) = paginate_after_filler(
            60.0,
            "<section><h2>Heading</h2><p>Body</p></section>",
            &format!("h2 {{ break-after: avoid; }} p {{ height: {tall}px; }}"),
        );
        assert_eq!(pages_of(&dom, &pages, "h2"), vec![0]);
    }

    #[test]
    fn break_inside_avoid_still_splits_when_the_element_is_taller_than_a_full_page() {
        // avoid means "do not split if possible", so something too large for one page has to
        // be split as usual on a best-effort basis.
        let settings = PageSettings::default();
        let mut html_src = String::from(r#"<div class="wrapper">"#);
        for i in 0..30 {
            html_src.push_str(&format!(r#"<p class="item">item {i}</p>"#));
        }
        html_src.push_str("</div>");
        let dom = html::parse(html_src.as_bytes());

        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            ".wrapper { break-inside: avoid; margin: 0; } \
             .item { height: 100px; margin: 0; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();

        let pages = paginate_document(&dom, &styles, &fonts, &settings);
        assert!(
            pages.len() > 2,
            "a wrapper taller than a full page must still be split across pages \
             despite break-inside: avoid, got {} pages",
            pages.len()
        );
    }

    /// Measure how a paragraph of `word_count` words breaks into lines at an explicit `width`
    /// (px): the line count, and that the line heights are uniform. The orphans/widows tests
    /// work back from that uniform line height to the `filler` height, to aim at a specific
    /// natural break point within the page. The tests themselves give the paragraph under test
    /// the same `width: {width}px; margin: 0;`, so the value measured here carries over
    /// (the paragraph's `width` being explicit, the containing width itself does not affect
    /// the wrapping).
    fn measure_paragraph_lines(word_count: usize, width: f32) -> (usize, f32) {
        let words: Vec<String> = (0..word_count).map(|i| format!("word{i}")).collect();
        let html_src = format!(r#"<p class="target">{}</p>"#, words.join(" "));
        let dom = html::parse(html_src.as_bytes());
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(&format!(".target {{ width: {width}px; margin: 0; }}"));
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let tree = build_box_tree(&dom, &styles);
        let laid = layout_document(
            &tree,
            &styles,
            &fonts,
            PageSettings::default().content_width(),
        );

        let mut ps = Vec::new();
        find_all(&dom, dom.document(), "p", &mut ps);
        let lines = find_inline_lines(&laid, ps[0]).expect("expected inline content");
        let height = lines[0].rect.height;
        assert!(
            lines.iter().all(|l| (l.rect.height - height).abs() < 0.01),
            "this test relies on every wrapped line having the same height"
        );
        (lines.len(), height)
    }

    fn find_inline_lines(b: &LaidOutBox, target: NodeId) -> Option<&Vec<LineBox>> {
        if b.node == Some(target) {
            if let LaidOutContent::Inline(lines) = &b.content {
                return Some(lines);
            }
        }
        match &b.content {
            LaidOutContent::Blocks(children) => {
                children.iter().find_map(|c| find_inline_lines(c, target))
            }
            _ => None,
        }
    }

    /// A line fragment after pagination (the anonymous wrapper `place_line` creates) does not
    /// carry the original paragraph's NodeId, so the lines on a page are simply totalled
    /// rather than filtered by node (the DOM in this test has no element with inline content
    /// other than the paragraph under test, so the total matches its line count).
    fn count_inline_lines(b: &LaidOutBox) -> usize {
        match &b.content {
            LaidOutContent::Inline(lines) => lines.len(),
            LaidOutContent::Blocks(children) => children.iter().map(count_inline_lines).sum(),
            LaidOutContent::Table(_)
            | LaidOutContent::Flex(_)
            | LaidOutContent::Grid(_)
            | LaidOutContent::Image(_) => 0,
        }
    }

    fn lines_on_page(page: &Page) -> usize {
        page.boxes.iter().map(count_inline_lines).sum()
    }

    #[test]
    fn orphans_defers_the_whole_paragraph_when_too_few_lines_would_fit() {
        let word_count = 60;
        let width = 200.0;
        let (n, line_height) = measure_paragraph_lines(word_count, width);
        assert!(n >= 4, "expected several wrapped lines, got {n}");

        let settings = PageSettings::default();
        let orphans = 3usize;
        let widows = 1usize;
        // Use filler to leave exactly one line plus half a line of page height
        // (so naturally only one line fits, which cannot satisfy orphans=3).
        let target_fit = 1usize;
        let desired_remaining = (target_fit as f32 + 0.5) * line_height;
        let filler_height = settings.content_height() - 8.0 - desired_remaining;

        let words: Vec<String> = (0..word_count).map(|i| format!("word{i}")).collect();
        let full_html = format!(
            r#"<div class="filler"></div><p class="target">{}</p>"#,
            words.join(" ")
        );
        let dom = html::parse(full_html.as_bytes());
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(&format!(
            ".filler {{ height: {filler_height}px; margin: 0; }} \
             .target {{ width: {width}px; margin: 0; orphans: {orphans}; widows: {widows}; }}"
        ));
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();

        let pages = paginate_document(&dom, &styles, &fonts, &settings);
        assert_eq!(
            pages.len(),
            2,
            "the paragraph should move entirely to a second page"
        );

        assert_eq!(
            lines_on_page(&pages[0]),
            0,
            "orphans: {orphans} should prevent leaving only {target_fit} line(s) behind"
        );
        assert_eq!(lines_on_page(&pages[1]), n);
    }

    #[test]
    fn widows_pulls_lines_forward_to_avoid_stranding_too_few_on_the_next_page() {
        let word_count = 60;
        let width = 200.0;
        let (n, line_height) = measure_paragraph_lines(word_count, width);
        assert!(n >= 8, "expected several wrapped lines, got {n}");

        let settings = PageSettings::default();
        let orphans = 1usize;
        let widows = 3usize;
        // At the natural break point (n - 1) lines fit on this page and only one is left for
        // the next (which cannot satisfy widows=3).
        let target_fit = n - 1;
        let desired_remaining = (target_fit as f32 + 0.5) * line_height;
        let filler_height = settings.content_height() - 8.0 - desired_remaining;

        let words: Vec<String> = (0..word_count).map(|i| format!("word{i}")).collect();
        let full_html = format!(
            r#"<div class="filler"></div><p class="target">{}</p>"#,
            words.join(" ")
        );
        let dom = html::parse(full_html.as_bytes());
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(&format!(
            ".filler {{ height: {filler_height}px; margin: 0; }} \
             .target {{ width: {width}px; margin: 0; orphans: {orphans}; widows: {widows}; }}"
        ));
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();

        let pages = paginate_document(&dom, &styles, &fonts, &settings);
        assert_eq!(pages.len(), 2);

        let on_page_2 = lines_on_page(&pages[1]);
        assert!(
            on_page_2 >= widows,
            "widows: {widows} should keep at least that many lines together on page 2, got {on_page_2}"
        );
        assert_eq!(lines_on_page(&pages[0]) + on_page_2, n);
    }

    #[test]
    fn paragraph_shorter_than_orphans_plus_widows_is_never_split() {
        let word_count = 3;
        // Make the width extremely narrow so each word is its own line (giving three lines).
        let width = 10.0;
        let (n, line_height) = measure_paragraph_lines(word_count, width);
        assert_eq!(n, 3, "expected each word to wrap onto its own line");

        let settings = PageSettings::default();
        // orphans+widows (4) > n (3), so no break point can satisfy both.
        let orphans = 2usize;
        let widows = 2usize;
        let target_fit = 2usize;
        let desired_remaining = (target_fit as f32 + 0.5) * line_height;
        let filler_height = settings.content_height() - 8.0 - desired_remaining;

        let words: Vec<String> = (0..word_count).map(|i| format!("word{i}")).collect();
        let full_html = format!(
            r#"<div class="filler"></div><p class="target">{}</p>"#,
            words.join(" ")
        );
        let dom = html::parse(full_html.as_bytes());
        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(&format!(
            ".filler {{ height: {filler_height}px; margin: 0; }} \
             .target {{ width: {width}px; margin: 0; orphans: {orphans}; widows: {widows}; }}"
        ));
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();

        let pages = paginate_document(&dom, &styles, &fonts, &settings);
        assert_eq!(pages.len(), 2);

        assert_eq!(
            lines_on_page(&pages[0]),
            0,
            "a paragraph shorter than orphans + widows should never be split"
        );
        assert_eq!(lines_on_page(&pages[1]), n);
    }

    /// A test helper that calls [`PaginationState`] and [`place_box`] directly and reports how
    /// many pages are left in the buffer before `finish()` is called.
    fn unflushed_buffer_len_after_place_box(laid_out: &LaidOutBox, page_height: f32) -> usize {
        let mut buffer = PaginationBuffer::new();
        let mut on_page = |_page: Page| {};
        let mut state = PaginationState::new(&mut buffer, &mut on_page);
        let mut cursor = 0.0f32;
        place_box(&mut laid_out.clone(), page_height, &mut state, &mut cursor);
        buffer.buffer.len()
    }

    #[test]
    fn streaming_flushes_undecorated_content_incrementally_not_all_at_finish() {
        // A structure of nothing but containers with no decoration (background colour or borders).
        let mut html_src = String::from("<div>");
        for i in 0..60 {
            html_src.push_str(&format!(r#"<p class="item">item {i}</p>"#));
        }
        html_src.push_str("</div>");
        let dom = html::parse(html_src.as_bytes());

        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(".item { height: 100px; margin: 0; }");
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let tree = build_box_tree(&dom, &styles);
        let mut laid_out = layout_document(&tree, &styles, &fonts, settings.content_width());
        let page_height = settings.content_height();

        let total_pages = paginate(&mut laid_out, page_height).len();
        assert!(
            total_pages >= 5,
            "expected several pages, got {total_pages}"
        );

        // A container with no decoration never calls `place_split`'s enter_split/exit_split,
        // so `PaginationState::try_flush` fires on the spot at every `new_page` and the
        // previous page is flushed immediately (see the module docs and
        // `has_visible_decoration`). So even once the top-level `place_box` call is complete
        // (with `finish()` not yet called), the buffer should hold only "the last page, still
        // being written". An implementation that flushed every page at the end would give
        // `total_pages` here.

        assert_eq!(
            unflushed_buffer_len_after_place_box(&laid_out, page_height),
            1,
            "pages should already be flushed incrementally before finish() is even called"
        );
    }

    #[test]
    fn streaming_still_flushes_down_to_one_page_when_a_decorated_wrapper_spans_many_pages() {
        // Even where a wrapper with a background and borders crosses pages, once the top-level
        // `place_box` call is complete that wrapper's `place_split` must have run through to
        // its own exit_split (`place_split` finishes its work, then calls `exit_split` and
        // returns). So decoration or not, the invariant holds that only the last page remains
        // in the buffer once `place_box` is complete.

        let mut html_src = String::from(r#"<div class="wrapper">"#);
        for i in 0..20 {
            html_src.push_str(&format!(r#"<p class="item">item {i}</p>"#));
        }
        html_src.push_str("</div>");
        let dom = html::parse(html_src.as_bytes());

        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            ".wrapper { border: 2px solid black; padding: 5px; margin: 0; } \
             .item { height: 100px; margin: 0; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let tree = build_box_tree(&dom, &styles);
        let mut laid_out = layout_document(&tree, &styles, &fonts, settings.content_width());
        let page_height = settings.content_height();

        let total_pages = paginate(&mut laid_out, page_height).len();
        assert!(
            total_pages >= 3,
            "expected the wrapper to span multiple pages, got {total_pages}"
        );

        assert_eq!(
            unflushed_buffer_len_after_place_box(&laid_out, page_height),
            1,
            "even a decorated wrapper should be fully resolved (and its earlier pages \
             flushed) by the time the top-level place_box call returns"
        );
    }

    #[test]
    fn paginate_streaming_matches_the_batched_version_for_a_decorated_spanning_wrapper() {
        // A correctness check on whether `PaginationState`'s flush decision (see the module
        // docs) is safe: in the most delicate case involving decoration fragments being
        // (`split_container_gets_a_decoration_fragment_on_every_page_it_spans`
        // written back), confirm that the streaming and batch versions return exactly the same
        // result. Flushing too early would either panic (the page a decoration fragment goes
        // on having already been flushed) or lose the insertion altogether.
        let mut html_src = String::from(r#"<div class="wrapper">"#);
        for i in 0..20 {
            html_src.push_str(&format!(r#"<p class="item">item {i}</p>"#));
        }
        html_src.push_str("</div>");
        let dom = html::parse(html_src.as_bytes());

        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            ".wrapper { border: 2px solid black; padding: 5px; margin: 0; } \
             .item { height: 100px; margin: 0; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let tree = build_box_tree(&dom, &styles);
        let mut laid_out = layout_document(&tree, &styles, &fonts, settings.content_width());
        let page_height = settings.content_height();

        let batched = paginate(&mut laid_out, page_height);
        let mut streamed = Vec::new();
        paginate_streaming(&mut laid_out, page_height, &mut |page| streamed.push(page));

        assert_eq!(batched.len(), streamed.len());
        assert!(batched.len() >= 3);

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let wrapper = divs[0];

        for (b_page, s_page) in batched.iter().zip(streamed.iter()) {
            assert_eq!(b_page.boxes.len(), s_page.boxes.len());

            let b_dec = find_decoration_fragment(b_page, wrapper);
            let s_dec = find_decoration_fragment(s_page, wrapper);
            assert_eq!(
                b_dec.map(|d| d.layout.fragment),
                s_dec.map(|d| d.layout.fragment)
            );
            assert_eq!(
                b_dec.map(|d| d.layout.border.top),
                s_dec.map(|d| d.layout.border.top)
            );
            assert_eq!(
                b_dec.map(|d| d.layout.border.bottom),
                s_dec.map(|d| d.layout.border.bottom)
            );
            assert_eq!(
                b_dec.map(|d| d.layout.padding.top),
                s_dec.map(|d| d.layout.padding.top)
            );
        }
    }

    #[test]
    fn paginate_document_streaming_releases_paragraphs_as_their_page_flushes() {
        // Twenty independent <p> elements with no decoration. Check that each time a page is
        // flushed, the <p> elements placed on it (and their text descendants) have been freed.

        let mut html_src = String::from("<div>");
        for i in 0..20 {
            html_src.push_str(&format!(r#"<p class="item">item {i}</p>"#));
        }
        html_src.push_str("</div>");
        let mut dom = html::parse(html_src.as_bytes());

        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(".item { height: 100px; margin: 0; }");
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

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

        let mut flushed_pages = 0usize;
        paginate_document_streaming(
            &mut dom,
            &styles,
            &fonts,
            &settings,
            &ImageAssetCache::new(std::path::PathBuf::from("."), false),
            &mut |_page| {
                flushed_pages += 1;
            },
        );
        assert!(flushed_pages > 1, "expected multiple pages");

        // After every page is processed, all twenty <p> elements should be freed
        // (the undecorated wrapper div too, on the last page's flush).
        for &p in &ps {
            assert!(
                dom.is_released(p),
                "paragraph {p:?} should be released once its page has flushed"
            );
        }
    }

    #[test]
    fn paginate_document_streaming_eventually_releases_a_spanning_wrapper() {
        // Even where a wrapper with a background and borders spans several pages, once
        // everything has run through `paginate_document_streaming` (the public API) the
        // wrapper's own node should be freed too (it is freed once its decoration fragment
        // becomes `Last` on the final page). Directly checking the intermediate state, that
        // "it is not freed before the last page", is done in the test
        // `wrapper_node_is_not_released_before_its_last_fragment_flushes`
        // below.
        let mut html_src = String::from(r#"<div class="wrapper">"#);
        for i in 0..20 {
            html_src.push_str(&format!(r#"<p class="item">item {i}</p>"#));
        }
        html_src.push_str("</div>");
        let mut dom = html::parse(html_src.as_bytes());

        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            ".wrapper { border: 2px solid black; padding: 5px; margin: 0; } \
             .item { height: 100px; margin: 0; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let wrapper = divs[0];

        let mut flushed_pages = 0usize;
        paginate_document_streaming(
            &mut dom,
            &styles,
            &fonts,
            &settings,
            &ImageAssetCache::new(std::path::PathBuf::from("."), false),
            &mut |_page| {
                flushed_pages += 1;
            },
        );
        assert!(
            flushed_pages >= 3,
            "expected the wrapper to span at least 3 pages, got {flushed_pages}"
        );

        assert!(
            dom.is_released(wrapper),
            "the wrapper should be released once its final page has flushed"
        );
    }

    #[test]
    fn wrapper_node_is_not_released_before_its_last_fragment_flushes() {
        // Observe directly from inside the `on_page` callback that the wrapper node is not yet
        // freed at the point the first page is flushed.
        let mut html_src = String::from(r#"<div class="wrapper">"#);
        for i in 0..20 {
            html_src.push_str(&format!(r#"<p class="item">item {i}</p>"#));
        }
        html_src.push_str("</div>");
        let mut dom = html::parse(html_src.as_bytes());

        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(
            ".wrapper { border: 2px solid black; padding: 5px; margin: 0; } \
             .item { height: 100px; margin: 0; }",
        );
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let mut divs = Vec::new();
        find_all(&dom, dom.document(), "div", &mut divs);
        let wrapper = divs[0];

        let tree = build_box_tree(&dom, &styles);
        let mut laid_out = layout_document(&tree, &styles, &fonts, settings.content_width());
        let page_height = settings.content_height();
        let total_pages = paginate(&mut laid_out, page_height).len();
        assert!(total_pages >= 3);

        let mut flushed_pages = 0usize;
        let mut observed_mid_release = Vec::new();
        paginate_streaming(&mut laid_out, page_height, &mut |page| {
            flushed_pages += 1;
            release_completed_subtrees(&mut dom, &page);
            if flushed_pages < total_pages {
                observed_mid_release.push(dom.is_released(wrapper));
            }
        });

        assert!(
            observed_mid_release.iter().all(|&released| !released),
            "the wrapper must stay alive until its last fragment flushes, observed: \
             {observed_mid_release:?}"
        );
        assert!(dom.is_released(wrapper));
    }

    #[test]
    fn paragraphs_on_a_later_page_are_not_released_before_their_own_page_flushes() {
        // Check there is no premature freeing (a bug wrongly freeing a node that has not
        // appeared yet) by precomputing with the batch version which page each <p> really
        // lands on, and confirming at every `on_page` that it is not yet freed before that page.

        let mut html_src = String::from("<div>");
        for i in 0..20 {
            html_src.push_str(&format!(r#"<p class="item">item {i}</p>"#));
        }
        html_src.push_str("</div>");
        let mut dom = html::parse(html_src.as_bytes());

        let ua = user_agent_stylesheet();
        let author = parse_stylesheet(".item { height: 100px; margin: 0; }");
        let styles = compute_styles(&dom, &ua, &author);
        let fonts = test_fonts();
        let settings = PageSettings::default();

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

        let tree = build_box_tree(&dom, &styles);
        let mut laid_out = layout_document(&tree, &styles, &fonts, settings.content_width());
        let page_height = settings.content_height();

        let batched = paginate(&mut laid_out, page_height);
        assert!(batched.len() > 1, "expected multiple pages");
        let page_of: HashMap<NodeId, usize> = ps
            .iter()
            .map(|&p| {
                let idx = batched
                    .iter()
                    .position(|page| page.boxes.iter().any(|b| box_contains_node(b, p)))
                    .expect("every paragraph should land on some page");
                (p, idx)
            })
            .collect();

        let mut current_page_index = 0usize;
        paginate_streaming(&mut laid_out, page_height, &mut |page| {
            release_completed_subtrees(&mut dom, &page);
            for (&p, &expected_page) in &page_of {
                if expected_page > current_page_index {
                    assert!(
                        !dom.is_released(p),
                        "paragraph destined for page {expected_page} must not be released \
                         while only page {current_page_index} has flushed"
                    );
                }
            }
            current_page_index += 1;
        });
    }

    #[test]
    fn streaming_paginator_multiple_push_item_calls_match_a_single_combined_tree() {
        // Check that "processing all twenty <p>s as one tree at once" and "push_item one at a
        // time" end up with the same page count and contents (the groundwork for those two
        // paths agreeing under top-level-element streaming input).

        let author = parse_stylesheet(".item { height: 100px; margin: 0; }");
        let ua = user_agent_stylesheet();
        let fonts = test_fonts();
        let settings = PageSettings::default();

        // Batch version: lay all twenty <p>s out inside a single div.
        let mut combined_html = String::from("<div>");
        for i in 0..20 {
            combined_html.push_str(&format!(r#"<p class="item">item {i}</p>"#));
        }
        combined_html.push_str("</div>");
        let combined_dom = html::parse(combined_html.as_bytes());
        let combined_styles = compute_styles(&combined_dom, &ua, &author);
        let combined_tree = build_box_tree(&combined_dom, &combined_styles);
        let mut combined_laid_out = layout_document(
            &combined_tree,
            &combined_styles,
            &fonts,
            settings.content_width(),
        );
        let batched_pages = paginate(&mut combined_laid_out, settings.content_height());
        assert!(batched_pages.len() > 1, "expected multiple pages");

        // push_item version: from the same `combined_dom`/`combined_styles`, cut out each <p>
        // element's LayoutBox individually with `build_box_for_element` and push_item each in
        // turn. Calling `html::parse` twenty times would supply an independent <html>/<body>
        // each time, accumulating twenty lots of the UA stylesheet's `body { margin: 8px; }`
        // and testing something other than the push_item logic, so the elements are cut from
        // the same DOM.
        let mut ps = Vec::new();
        find_all(&combined_dom, combined_dom.document(), "p", &mut ps);
        assert_eq!(ps.len(), 20);

        let mut streamed_pages: Vec<Page> = Vec::new();
        let mut paginator = StreamingPaginator::new(settings.content_height());
        let mut start_y = 0.0f32;
        for &p_node in &ps {
            let item_box = build_box_for_element(&combined_dom, &combined_styles, p_node)
                .expect("p element should produce a LayoutBox");
            let item_laid_out = layout_document_from(
                &item_box,
                &combined_styles,
                &fonts,
                settings.content_width(),
                0.0,
                start_y,
            );
            start_y += item_laid_out.layout.margin_box_height();
            streamed_pages.extend(paginator.push_item(&mut item_laid_out.clone()));
        }
        streamed_pages.extend(paginator.finish());

        assert_eq!(
            batched_pages.len(),
            streamed_pages.len(),
            "pushing items one at a time should yield the same page count as a single combined tree"
        );
        for (batched, streamed) in batched_pages.iter().zip(streamed_pages.iter()) {
            assert_eq!(batched.boxes.len(), streamed.boxes.len());
        }
    }

    /// Paginate the same element sequence both with the batch version ([`paginate`]) and with
    /// [`StreamingPaginator`]'s `push_item`, and return each page count.
    ///
    /// Only one DOM is built and shared by both, because parsing each element with
    /// `html::parse` would accumulate one supplied `<body>`'s UA margin per element
    fn page_counts_both_ways(author_css: &str, items_html: &str) -> (usize, usize) {
        let author = parse_stylesheet(author_css);
        let ua = user_agent_stylesheet();
        let fonts = test_fonts();
        let settings = PageSettings::default();

        let dom = html::parse(format!("<div>{items_html}</div>").as_bytes());
        let styles = compute_styles(&dom, &ua, &author);

        let tree = build_box_tree(&dom, &styles);
        let mut laid_out = layout_document(&tree, &styles, &fonts, settings.content_width());
        let batched = paginate(&mut laid_out, settings.content_height()).len();

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

        let mut paginator = StreamingPaginator::new(settings.content_height());
        let mut streamed = 0;
        let mut start_y = 0.0f32;
        for &node in &items {
            let item_box = build_box_for_element(&dom, &styles, node)
                .expect("p element should produce a LayoutBox");
            let mut item_laid_out = layout_document_from(
                &item_box,
                &styles,
                &fonts,
                settings.content_width(),
                0.0,
                start_y,
            );
            start_y += item_laid_out.layout.margin_box_height();
            streamed += paginator.push_item(&mut item_laid_out).len();
        }
        streamed += paginator.finish().len();

        (batched, streamed)
    }

    #[test]
    fn streaming_paginator_honors_break_after_between_items() {
        // `place_box` only looks at forced breaks within a child list, so a `break-after`
        // between top-level elements (that is, across `push_item` calls) would be ignored
        // unless the paginator handled it.
        let (batched, streamed) = page_counts_both_ways(
            ".brk { height: 50px; margin: 0; break-after: always; }",
            r#"<p class="brk">A</p><p class="brk">B</p><p class="brk">C</p>"#,
        );

        assert_eq!(
            batched, 3,
            "break-after: always on each of three short items should give three pages"
        );
        assert_eq!(
            streamed, batched,
            "pushing the same items one at a time must honor break-after too"
        );
    }

    #[test]
    fn streaming_paginator_honors_break_before_between_items() {
        let (batched, streamed) = page_counts_both_ways(
            ".a { height: 50px; margin: 0; } \
             .brk { height: 50px; margin: 0; break-before: always; }",
            r#"<p class="a">A</p><p class="brk">B</p><p class="brk">C</p>"#,
        );

        assert_eq!(batched, 3);
        assert_eq!(
            streamed, batched,
            "pushing the same items one at a time must honor break-before too"
        );
    }

    #[test]
    fn streaming_paginator_does_not_create_blank_pages_at_the_document_edges() {
        // A leading `break-before` and a trailing `break-after` have nothing to move to, so
        // no empty page should be created (the same handling as the batch version).
        let (batched, streamed) = page_counts_both_ways(
            ".first { height: 50px; margin: 0; break-before: always; } \
             .last { height: 50px; margin: 0; break-after: always; }",
            r#"<p class="first">A</p><p class="last">B</p>"#,
        );

        assert_eq!(
            batched, 1,
            "a break-before on the first item and a break-after on the last one \
             should not create blank pages"
        );
        assert_eq!(streamed, batched);
    }

    // ===== Splitting a table across pages row by row =====

    /// Paginate `html_src` and return the table row count per page.
    fn table_rows_per_page(html_src: &str) -> Vec<usize> {
        let dom = html::parse(html_src.as_bytes());
        let styles = compute_styles(&dom, &user_agent_stylesheet(), &Stylesheet::default());
        let fonts = test_fonts();
        let settings = PageSettings::default();
        let pages = paginate_document(&dom, &styles, &fonts, &settings);

        fn count(b: &LaidOutBox) -> usize {
            match &b.content {
                LaidOutContent::Table(table) => table.rows.len(),
                LaidOutContent::Blocks(children) | LaidOutContent::Flex(children) => {
                    children.iter().map(count).sum()
                }
                _ => 0,
            }
        }
        pages
            .iter()
            .map(|page| page.boxes.iter().map(count).sum())
            .collect()
    }

    fn rows_html(n: usize) -> String {
        let rows: String = (0..n).map(|i| format!("<tr><td>{i}</td></tr>")).collect();
        format!("<table>{rows}</table>")
    }

    #[test]
    fn a_table_is_split_row_by_row_instead_of_being_treated_as_atomic() {
        let counts = table_rows_per_page(&rows_html(120));
        assert!(counts.len() >= 2, "got {counts:?}");
        assert_eq!(counts.iter().sum::<usize>(), 120, "got {counts:?}");
        assert!(counts.iter().all(|&c| c > 0), "got {counts:?}");
    }

    #[test]
    fn table_fragments_are_marked_first_middle_last() {
        let dom = html::parse(rows_html(200).as_bytes());
        let styles = compute_styles(&dom, &user_agent_stylesheet(), &Stylesheet::default());
        let fonts = test_fonts();
        let pages = paginate_document(&dom, &styles, &fonts, &PageSettings::default());

        fn positions(b: &LaidOutBox, out: &mut Vec<FragmentPosition>) {
            match &b.content {
                LaidOutContent::Table(_) => out.push(b.layout.fragment),
                LaidOutContent::Blocks(children) | LaidOutContent::Flex(children) => {
                    for c in children {
                        positions(c, out);
                    }
                }
                _ => {}
            }
        }
        let mut found = Vec::new();
        for page in &pages {
            for b in &page.boxes {
                positions(b, &mut found);
            }
        }
        assert!(
            found.len() >= 3,
            "expected several fragments, got {found:?}"
        );
        assert_eq!(found.first(), Some(&FragmentPosition::First));
        assert_eq!(found.last(), Some(&FragmentPosition::Last));
        assert!(found[1..found.len() - 1]
            .iter()
            .all(|p| *p == FragmentPosition::Middle));
    }

    #[test]
    fn rows_keep_their_order_and_spacing_after_being_split() {
        let dom = html::parse(rows_html(120).as_bytes());
        let styles = compute_styles(&dom, &user_agent_stylesheet(), &Stylesheet::default());
        let fonts = test_fonts();
        let settings = PageSettings::default();
        let pages = paginate_document(&dom, &styles, &fonts, &settings);

        fn rows_of(b: &LaidOutBox, out: &mut Vec<f32>) {
            match &b.content {
                LaidOutContent::Table(table) => {
                    for row in &table.rows {
                        out.push(row.cells[0].layout.content.y);
                    }
                }
                LaidOutContent::Blocks(children) | LaidOutContent::Flex(children) => {
                    for c in children {
                        rows_of(c, out);
                    }
                }
                _ => {}
            }
        }
        for page in &pages {
            let mut ys = Vec::new();
            for b in &page.boxes {
                rows_of(b, &mut ys);
            }
            // Within each page the rows run top to bottom and stay within the page height.
            assert!(ys.windows(2).all(|w| w[1] > w[0]), "got {ys:?}");
            assert!(
                ys.iter().all(|y| *y >= 0.0 && *y <= settings.size.height),
                "a row was placed outside the page: {ys:?}"
            );
        }
    }

    #[test]
    fn thead_rows_are_repeated_on_every_page_but_body_rows_are_not() {
        let rows: String = (0..120)
            .map(|i| format!("<tr><td>b{i}</td></tr>"))
            .collect();
        let html_src =
            format!("<table><thead><tr><td>H</td></tr></thead><tbody>{rows}</tbody></table>");
        let dom = html::parse(html_src.as_bytes());
        let styles = compute_styles(&dom, &user_agent_stylesheet(), &Stylesheet::default());
        let fonts = test_fonts();
        let pages = paginate_document(&dom, &styles, &fonts, &PageSettings::default());

        fn sections(b: &LaidOutBox, out: &mut Vec<TableSection>) {
            match &b.content {
                LaidOutContent::Table(table) => {
                    out.extend(table.rows.iter().map(|r| r.section));
                }
                LaidOutContent::Blocks(children) | LaidOutContent::Flex(children) => {
                    for c in children {
                        sections(c, out);
                    }
                }
                _ => {}
            }
        }

        let mut head_total = 0;
        let mut body_total = 0;
        for page in &pages {
            let mut found = Vec::new();
            for b in &page.boxes {
                sections(b, &mut found);
            }
            assert_eq!(
                found.first(),
                Some(&TableSection::Head),
                "each page must start with the repeated header: {found:?}"
            );
            head_total += found.iter().filter(|s| **s == TableSection::Head).count();
            body_total += found.iter().filter(|s| **s == TableSection::Body).count();
        }
        assert_eq!(head_total, pages.len(), "one header row per page");
        assert_eq!(body_total, 120, "body rows must not be duplicated");
    }

    #[test]
    fn a_header_taller_than_the_page_is_not_repeated() {
        // With the headings alone filling the page not a single row could advance, so they are not repeated.
        let rows: String = (0..40).map(|i| format!("<tr><td>b{i}</td></tr>")).collect();
        let head: String = (0..80).map(|i| format!("<tr><td>h{i}</td></tr>")).collect();
        let html_src = format!("<table><thead>{head}</thead><tbody>{rows}</tbody></table>");
        let dom = html::parse(html_src.as_bytes());
        let styles = compute_styles(&dom, &user_agent_stylesheet(), &Stylesheet::default());
        let fonts = test_fonts();
        let pages = paginate_document(&dom, &styles, &fonts, &PageSettings::default());

        fn head_count(b: &LaidOutBox) -> usize {
            match &b.content {
                LaidOutContent::Table(table) => table
                    .rows
                    .iter()
                    .filter(|r| r.section == TableSection::Head)
                    .count(),
                LaidOutContent::Blocks(children) | LaidOutContent::Flex(children) => {
                    children.iter().map(head_count).sum()
                }
                _ => 0,
            }
        }
        let total: usize = pages
            .iter()
            .map(|p| p.boxes.iter().map(head_count).sum::<usize>())
            .sum();
        assert_eq!(total, 80, "the oversized header must not be duplicated");
    }

    /// Paginate `body` onto 400x200 pages with no page margin and return, page by page, the
    /// layout of the grid or table fragment found there (pages without one are skipped).
    fn row_container_fragments(body: &str, css: &str) -> Vec<Layout> {
        fn find(b: &LaidOutBox) -> Option<Layout> {
            match &b.content {
                LaidOutContent::Grid(_) | LaidOutContent::Table(_) => Some(b.layout),
                LaidOutContent::Blocks(children) | LaidOutContent::Flex(children) => {
                    children.iter().find_map(find)
                }
                _ => None,
            }
        }
        let settings = PageSettings {
            size: crate::layout::PageSize {
                width: 400.0,
                height: 200.0,
            },
            margin: EdgeSizes::default(),
        };
        let dom = html::parse(body.as_bytes());
        let author = parse_stylesheet(&format!("html, body {{ margin: 0; }} {css}"));
        let styles = compute_styles(&dom, &user_agent_stylesheet(), &author);
        let pages = paginate_document(&dom, &styles, &test_fonts(), &settings);
        pages
            .iter()
            .filter_map(|page| page.boxes.iter().find_map(find))
            .collect()
    }

    /// Like a block container, a grid or table split across pages slices its decoration
    /// (`box-decoration-break: slice`): the border and padding at a break are dropped, and
    /// the first fragment's border box starts where the container does.
    fn assert_sliced(fragments: &[Layout]) {
        assert_eq!(fragments.len(), 3, "the container should break twice");
        assert_eq!(fragments[0].fragment, FragmentPosition::First);
        assert_eq!(fragments[1].fragment, FragmentPosition::Middle);
        assert_eq!(fragments[2].fragment, FragmentPosition::Last);
        assert_eq!(fragments[0].border_box().y, 0.0);
        assert_eq!(fragments[0].border.top, 4.0);
        assert_eq!(fragments[0].padding.top, 3.0);
        for fragment in &fragments[1..] {
            assert_eq!(fragment.border_box().y, 0.0);
            assert_eq!(fragment.border.top, 0.0);
            assert_eq!(fragment.padding.top, 0.0);
        }
        for fragment in &fragments[..2] {
            assert_eq!(fragment.border.bottom, 0.0);
            assert_eq!(fragment.padding.bottom, 0.0);
        }
        assert_eq!(fragments[2].border.bottom, 4.0);
        assert_eq!(fragments[2].padding.bottom, 3.0);
    }

    #[test]
    fn a_grid_split_across_pages_slices_its_border() {
        let rows = r#"<div class="row"></div>"#.repeat(8);
        let fragments = row_container_fragments(
            &format!(r#"<div class="grid">{rows}</div>"#),
            ".grid { display: grid; border: 4px solid black; padding: 3px 0; } \
             .row { height: 50px; }",
        );
        assert_sliced(&fragments);
    }

    #[test]
    fn a_table_split_across_pages_slices_its_border() {
        let rows = "<tr><td></td></tr>".repeat(8);
        let fragments = row_container_fragments(
            &format!("<table>{rows}</table>"),
            "table { border: 4px solid black; padding: 3px 0; border-spacing: 0; } \
             td { height: 50px; padding: 0; }",
        );
        assert_sliced(&fragments);
    }

    /// A grid or table whose first row does not fit below what precedes it starts on the next
    /// page. Its first fragment is still the one carrying the top border and padding, so they
    /// are reserved again there: the border box starts at the top of the page, and the first
    /// row below them.
    fn assert_first_fragment_moved_whole(fragments: &[Layout]) {
        assert_eq!(fragments[0].fragment, FragmentPosition::First);
        assert_eq!(
            fragments[0].border_box().y,
            0.0,
            "the top border is off the page"
        );
        assert_eq!(fragments[0].content.y, 7.0);
    }

    #[test]
    fn a_grid_moved_to_the_next_page_keeps_its_top_border_on_the_page() {
        let rows = r#"<div class="row"></div>"#.repeat(8);
        let fragments = row_container_fragments(
            &format!(r#"<div style="height:170px"></div><div class="grid">{rows}</div>"#),
            ".grid { display: grid; border: 4px solid black; padding: 3px 0; } \
             .row { height: 50px; }",
        );
        assert_first_fragment_moved_whole(&fragments);
    }

    #[test]
    fn a_table_moved_to_the_next_page_keeps_its_top_border_on_the_page() {
        let rows = "<tr><td></td></tr>".repeat(8);
        let fragments = row_container_fragments(
            &format!(r#"<div style="height:170px"></div><table>{rows}</table>"#),
            "table { border: 4px solid black; padding: 3px 0; border-spacing: 0; } \
             td { height: 50px; padding: 0; }",
        );
        assert_first_fragment_moved_whole(&fragments);
    }
}