spindrift 0.1.0

A HTML/CSS to PDF renderer, targeting spec compliance and efficiency
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
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
use super::*;

const DISPLAY_CONTENTS_FLEX_ACID_CSS: &str = "\
html, body { color: black; background-color: white; font-size: 16px; padding: 0; margin: 0 }\
body { color: red }\
.flex { display: flex }\
.ib { display: inline-block }\
.inline { display: inline }\
.contents { display: contents; align-items: inherit; justify-items: inherit }\
.c1 { color: lime }\
.c2 { background: blue; color: pink }\
.c3 { color: teal }\
.c4 { color: green }\
.c5 { color: silver }\
.c6 { color: cyan }\
.c7 { color: magenta }\
.c9 { color: grey }\
.c10 { color: black }\
.b { background: inherit }";

const RTL_JUSTIFY_CONTENT_LEFT_WPT: &str =
    include_str!("../../../tests/fixtures/wpt/css/css-flexbox/justify-content-left-rtl.html");
const RTL_JUSTIFY_CONTENT_LEFT_REFERENCE: &str =
    include_str!("../../../tests/fixtures/wpt/css/css-flexbox/justify-content-left-rtl-ref.html");

fn rects_overlap_y(
    a: &crate::document::paint::shapes::RenderedRect,
    b: &crate::document::paint::shapes::RenderedRect,
) -> bool {
    a.y() < b.y() + b.height() - 0.01 && b.y() < a.y() + a.height() - 0.01
}

fn rects_have_gap_x(
    a: &crate::document::paint::shapes::RenderedRect,
    b: &crate::document::paint::shapes::RenderedRect,
    expected: f32,
) -> bool {
    let gap = if a.x() <= b.x() {
        b.x() - (a.x() + a.width())
    } else {
        a.x() - (b.x() + b.width())
    };
    (gap - expected).abs() < 0.5
}

fn rects_have_gap_y(
    a: &crate::document::paint::shapes::RenderedRect,
    b: &crate::document::paint::shapes::RenderedRect,
    expected: f32,
) -> bool {
    let gap = if a.y() <= b.y() {
        b.y() - (a.y() + a.height())
    } else {
        a.y() - (b.y() + b.height())
    };
    (gap - expected).abs() < 0.5
}

fn page_rect_with_fill(
    page: &crate::document::Page,
    color: CssColor,
) -> &crate::document::paint::shapes::RenderedRect {
    page.rects()
        .iter()
        .find(|rect| rect.fill == Some(color))
        .unwrap_or_else(|| panic!("expected {color:?} background: {:?}", page.rects()))
}

#[tokio::test]
async fn size_contained_flex_descendants_keep_definite_sizes_and_auto_constraints() {
    let document = Html::from_string(
        "<style>@page { size: 100pt 100pt; margin: 0 } body { margin: 0 }\
         #flex { display: flex; flex-direction: column; width: 40pt }\
         #definite { background: green } #automatic { background: blue }\
         #definite > div { contain: size; height: 30pt }\
         #automatic > div { contain: size; min-height: 12pt; padding: 2pt 0 3pt }\
         </style><div id=flex><div id=definite><div></div></div><div id=automatic><div></div></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let definite = page_rect_with_fill(page, CssColor::new(0, 128, 0));
    let automatic = page_rect_with_fill(page, CssColor::new(0, 0, 255));
    assert_eq!(definite.height(), 30.0);
    assert_eq!(automatic.height(), 17.0);
}

#[tokio::test]
async fn rtl_row_justify_content_left_uses_the_physical_left_edge() {
    let document = Html::from_string(RTL_JUSTIFY_CONTENT_LEFT_WPT)
        .render(&RenderOptions::default())
        .await
        .unwrap();
    let reference = Html::from_string(RTL_JUSTIFY_CONTENT_LEFT_REFERENCE)
        .render(&RenderOptions::default())
        .await
        .unwrap();

    let page = &document.pages[0];
    let reference_page = &reference.pages[0];
    let container = page_rect_with_fill(page, CssColor::new(255, 0, 0));
    let item = page_rect_with_fill(page, CssColor::new(0, 128, 0));
    assert!(
        (item.x() - container.x()).abs() < 0.01,
        "`justify-content:left` must remain physical left in an RTL row: container={container:?}, item={item:?}"
    );
    assert_eq!(page.rects(), reference_page.rects());
}

#[tokio::test]
async fn vertical_rl_inline_flex_central_baseline_matches_empty_inline_block_line_extent() {
    let document = Html::from_string(
        "<style>@page { size: 140px 140px; margin: 0 }\
         body { margin: 0 }\
         #container { width: 100px; height: 100px; line-height: 0; writing-mode: vertical-rl; background: rgb(255 0 0) }\
         #inline-block { display: inline-block; width: 100px; height: 50px; background: rgb(0 0 255) }\
         #inline-flex { display: inline-flex }\
         #inline-flex > div { width: 100px; height: 50px; background: rgb(0 128 0) }\
         </style><div id=container><span id=inline-block></span><span id=inline-flex><div></div></span></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let container = page_rect_with_fill(page, CssColor::new(255, 0, 0));
    let inline_block = page_rect_with_fill(page, CssColor::new(0, 0, 255));
    let inline_flex = page_rect_with_fill(page, CssColor::new(0, 128, 0));

    assert_eq!(container.width(), 75.0);
    assert_eq!(inline_block.width(), 75.0);
    assert_eq!(inline_flex.width(), 75.0);
    assert_eq!(inline_block.x(), container.x());
    assert_eq!(inline_flex.x(), container.x());
}

#[tokio::test]
async fn static_flex_and_grid_items_paint_after_container_decorations() {
    for layout in ["flex", "grid"] {
        let document = Html::from_string(format!(
            "<style>@page {{ size: 160pt 100pt; margin: 0 }} body {{ margin: 0 }}\
             .container {{ display: {layout}; width: 40pt; height: 20pt }}\
             .first {{ background: rgb(255 0 0) }} .second {{ background: rgb(0 0 255) }}\
             .item {{ width: 20pt; height: 20pt }}\
             .green {{ background: rgb(0 128 0); order: 1 }}\
             .yellow {{ background: rgb(255 255 0); order: 0 }}\
             </style>\
             <div class=\"container first\"><div class=\"item green\"></div><div class=\"item yellow\"></div></div>\
             <div class=\"container second\"></div>"
        ))
        .render(&RenderOptions::default())
        .await
        .unwrap();

        let page = &document.pages[0];
        let red = first_rect_paint_operation_index(page, CssColor::new(255, 0, 0));
        let blue = first_rect_paint_operation_index(page, CssColor::new(0, 0, 255));
        let green = first_rect_paint_operation_index(page, CssColor::new(0, 128, 0));
        let yellow = first_rect_paint_operation_index(page, CssColor::new(255, 255, 0));
        assert!(
            red < green && red < yellow && blue < green && blue < yellow,
            "{layout} container decorations must paint before their static items: {:?}",
            page.paint_operations()
        );
        assert!(
            yellow < green,
            "{layout} items must retain order-modified document order: {:?}",
            page.paint_operations()
        );
    }
}

#[tokio::test]
async fn static_flex_item_positioned_descendants_interleave_in_parent_stacking_context() {
    let document = Html::from_string(
        "<style>@page { size: 160pt 100pt; margin: 0 } body { margin: 0 }\
         .flex { display: flex; width: 90pt; height: 20pt }\
         .first { flex: 0 0 45pt; min-width: 0; height: 20pt; background: lightblue }\
         .second { flex: 0 0 45pt; min-width: 0; height: 20pt; background: yellow }\
         .a, .b { position: relative; width: 70pt; height: 6pt }\
         .a { z-index: 10; background: purple }\
         .b { z-index: 20; background: teal }\
         .c { position: relative; z-index: 15; width: 20pt; height: 20pt; background: lime }\
         </style><div class=\"flex\"><div class=\"first\"><div class=\"a\"></div><div class=\"b\"></div></div><div class=\"second\"><div class=\"c\"></div></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    assert_eq!(
        final_rect_fill_at(page, 50.0, 97.0),
        Some(CssColor::new(0, 255, 0)),
        "the second item's z-index:15 descendant must paint above the first item's z-index:10 descendant: {:?}",
        page.rects()
    );
    assert_eq!(
        final_rect_fill_at(page, 50.0, 90.0),
        Some(CssColor::new(0, 128, 128)),
        "the first item's z-index:20 descendant must paint above the second item's z-index:15 descendant: {:?}",
        page.rects()
    );
}

#[tokio::test]
async fn relative_auto_flex_item_paints_in_auto_positioned_phase() {
    let document = Html::from_string(
        "<style>@page { size: 160pt 100pt; margin: 0 } body { margin: 0 }\
         .flex { display: flex; width: 90pt; height: 20pt }\
         .relative { position: relative; flex: 0 0 60pt; height: 20pt; background: red }\
         .static { flex: 0 0 60pt; height: 20pt; margin-left: -30pt; background: blue }\
         </style><div class=\"flex\"><div class=\"relative\"></div><div class=\"static\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    assert_eq!(
        final_rect_fill_at(page, 45.0, 90.0),
        Some(CssColor::new(255, 0, 0)),
        "a relatively positioned flex item with z-index:auto must paint above in-flow siblings: {:?}",
        page.rects()
    );
}

#[tokio::test]
async fn non_auto_z_index_flex_item_captures_positioned_descendants() {
    let document = Html::from_string(
        "<style>@page { size: 160pt 100pt; margin: 0 } body { margin: 0 }\
         .flex { display: flex; width: 90pt; height: 20pt }\
         .lower { z-index: 1; flex: 0 0 60pt; height: 20pt; background: red }\
         .lower > div { position: relative; z-index: 999; width: 60pt; height: 20pt; background: purple }\
         .upper { z-index: 2; flex: 0 0 60pt; height: 20pt; margin-left: -30pt; background: blue }\
         </style><div class=\"flex\"><div class=\"lower\"><div></div></div><div class=\"upper\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    assert_eq!(
        final_rect_fill_at(page, 45.0, 90.0),
        Some(CssColor::new(0, 0, 255)),
        "a positive-z descendant must remain below the later real flex-item stacking context: {:?}",
        page.rects()
    );
}

#[tokio::test]
async fn paged_wrapped_flex_space_between_preserves_definite_cross_size() {
    let document = Html::from_string(
        "<!doctype html><style>\
         @page { size: 200pt 120pt; margin: 0 } body { margin: 0 }\
         .cover { display: flex; flex-wrap: wrap; align-content: space-between; height: 100pt }\
         .title { width: 100%; height: 20pt; background: red }\
         .address { flex: 1 50%; height: 10pt } .left { background: green } .right { background: blue }\
         </style><main class=\"cover\"><div class=\"title\"></div><div class=\"address left\"></div><div class=\"address right\"></div></main>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(document.pages.len(), 1);
    let page = &document.pages[0];
    let red = page_rect_with_fill(page, CssColor::new(255, 0, 0));
    let green = page_rect_with_fill(page, CssColor::new(0, 128, 0));
    let blue = page_rect_with_fill(page, CssColor::new(0, 0, 255));
    assert!(
        (green.y() - 20.0).abs() < 0.01 && (blue.y() - 20.0).abs() < 0.01,
        "the second flex line must pack against the definite container block-end: red={red:?}, green={green:?}, blue={blue:?}"
    );
    assert!(
        (red.y() - green.y() - 80.0).abs() < 0.01,
        "align-content: space-between must preserve its distributed free space: red={red:?}, green={green:?}"
    );
}

#[tokio::test]
async fn paged_wrapped_flex_auto_cross_size_keeps_intrinsic_line_stacking() {
    let document = Html::from_string(
        "<!doctype html><style>\
         @page { size: 200pt 120pt; margin: 0 } body { margin: 0 }\
         .cover { display: flex; flex-wrap: wrap; align-content: space-between }\
         .title { width: 100%; height: 20pt; background: red }\
         .address { flex: 1 50%; height: 10pt } .left { background: green } .right { background: blue }\
         </style><main class=\"cover\"><div class=\"title\"></div><div class=\"address left\"></div><div class=\"address right\"></div></main>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(document.pages.len(), 1);
    let page = &document.pages[0];
    let red = page_rect_with_fill(page, CssColor::new(255, 0, 0));
    let green = page_rect_with_fill(page, CssColor::new(0, 128, 0));
    assert!(
        (red.y() - green.y() - 10.0).abs() < 0.01,
        "an auto-height flex container has no cross-axis free space to distribute: red={red:?}, green={green:?}"
    );
}

#[tokio::test]
async fn paged_wrapped_flex_uses_its_own_remaining_definite_height() {
    let document = Html::from_string(
        "<!doctype html><style>\
         @page { size: 200pt 120pt; margin: 0 } body, p { margin: 0 }\
         p { height: 20pt }\
         .cover { display: flex; flex-wrap: wrap; align-content: space-between; height: 100pt }\
         .title { width: 100%; height: 20pt; background: red }\
         .address { flex: 1 50%; height: 10pt } .left { background: green } .right { background: blue }\
         </style><p></p><main class=\"cover\"><div class=\"title\"></div><div class=\"address left\"></div><div class=\"address right\"></div></main>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(
        document.pages.len(),
        1,
        "the definite flex box fits after its predecessor"
    );
    let page = &document.pages[0];
    let green = page_rect_with_fill(page, CssColor::new(0, 128, 0));
    let blue = page_rect_with_fill(page, CssColor::new(0, 0, 255));
    assert!(
        green.y().abs() < 0.01 && blue.y().abs() < 0.01,
        "the final line packs to its own remaining container edge, not a continuation page: green={green:?}, blue={blue:?}"
    );
}

#[tokio::test]
async fn normal_flow_reference_boxes_keep_definite_sizes_and_siblings() {
    let document = Html::from_string(
        "<!doctype html><style>\
         @page { size: 500px 200px; margin: 0 } body { margin: 0 }\
         #parent { width: 400px; height: 80px; background: blue }\
         .item { display: inline-block; width: 40px; height: 60px; background: yellow }\
         </style><div id=\"parent\"><span class=\"item\"></span><span class=\"item\"></span></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let blue = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .expect("normal-flow parent should paint its background");
    assert!(
        (blue.width() - 300.0).abs() < 0.01 && (blue.height() - 60.0).abs() < 0.01,
        "definite normal-flow parent dimensions must survive child layout: {blue:?}"
    );
    let items = page
        .rects()
        .iter()
        .filter(|rect| rect.fill == Some(CssColor::new(255, 255, 0)))
        .collect::<Vec<_>>();
    assert_eq!(
        items.len(),
        2,
        "both inline-block siblings must paint: {items:?}"
    );
    assert!(
        items
            .iter()
            .all(|rect| (rect.width() - 30.0).abs() < 0.01 && (rect.height() - 45.0).abs() < 0.01),
        "inline-block dimensions must survive normal-flow replay: {items:?}"
    );
    assert!(
        (items[1].x() - (items[0].x() + items[0].width())).abs() < 0.01,
        "inline-block siblings must retain their shared line placement: {items:?}"
    );
}

#[tokio::test]
async fn normal_flow_column_reference_matches_flex_margin_geometry() {
    const COMMON: &str = "<!doctype html><style>\
        @page { margin: 0 }\
        div { background: blue; margin: 1em 0; border: 1px solid black; }\
        span { background: white; margin: 1em; width: 8em; }\
        </style><div><span>filler</span><span>filler</span><span>filler</span><span>filler</span></div>";
    let flex = Html::from_string(format!(
        "{COMMON}<style>div {{ display: flex; flex-direction: column; }} span {{ display: inline-block; }}</style>"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();
    let reference = Html::from_string(format!(
        "{COMMON}<style>span {{ display: block; }} span ~ span {{ margin: 2em 1em 1em; }}</style>"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let colored_rects = |document: &spindrift::Document| {
        document.pages[0]
            .rects()
            .iter()
            .filter(|rect| {
                matches!(
                    rect.fill,
                    Some(color) if color == CssColor::new(0, 0, 255)
                        || color == CssColor::new(255, 255, 255)
                )
            })
            .map(|rect| (rect.x(), rect.y(), rect.width(), rect.height(), rect.fill))
            .collect::<Vec<_>>()
    };
    let reference_rects = colored_rects(&reference);
    let flex_rects = colored_rects(&flex);
    assert_eq!(
        reference_rects.len(),
        flex_rects.len(),
        "ordinary block flow must preserve the same number of colored boxes as the flex reference"
    );
    for (reference, flex) in reference_rects.iter().zip(&flex_rects) {
        assert_eq!(
            reference.4, flex.4,
            "corresponding boxes must keep their paint color"
        );
        for (reference, flex) in [reference.0, reference.1, reference.2, reference.3]
            .into_iter()
            .zip([flex.0, flex.1, flex.2, flex.3])
        {
            assert!(
                (reference - flex).abs() <= 0.01,
                "ordinary block flow must preserve the same flex margin geometry: reference={reference_rects:?}, flex={flex_rects:?}"
            );
        }
    }
}

#[tokio::test]
async fn generated_flex_container_replays_its_anonymous_content_item() {
    let document = Html::from_string(
        "<!doctype html><style>\
         @page { margin: 0 }\
         div { background: #3366cc; border: 1px solid black }\
         div::after { content: 'xxx'; background: yellow; margin: 1em; width: 200px; height: 2em; display: flex }\
         </style><div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    assert!(
        page.lines().iter().any(|line| line.text == "xxx"),
        "a generated flex container must create and paint its anonymous content item"
    );
    assert!(
        page.rects()
            .iter()
            .any(|rect| rect.fill == Some(CssColor::new(255, 255, 0))),
        "the generated flex container's principal background must survive replay"
    );
}

async fn single_x_line_x(target_style: &str) -> f32 {
    let document = Html::from_string(format!(
        "<!DOCTYPE html><style>\
         @page {{ size: 300px 200px; margin: 0 }} body {{ margin: 0 }}\
         #target {{ font: 100px/1 sans-serif; color: green; width: 200px;\
           position: relative; left: -50px; {target_style} }}\
         </style><div id=\"target\">X</div>"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let lines = document.pages[0]
        .lines()
        .iter()
        .filter(|line| line.text == "X")
        .collect::<Vec<_>>();
    assert_eq!(
        lines.len(),
        1,
        "expected one X line: {:?}",
        document.pages[0].lines()
    );
    lines[0].x()
}

async fn assert_vertical_rl_inline_flex_column_wrap_gap(html: &str) {
    let document = Html::from_string(html)
        .render(&RenderOptions::default())
        .await
        .unwrap();
    let page = &document.pages[0];
    let green = CssColor::new(0, 128, 0);
    let gray = CssColor::new(128, 128, 128);
    let container = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(green))
        .unwrap_or_else(|| panic!("expected green inline-flex background: {:?}", page.rects()));
    assert!(
        (container.width() - 100.0).abs() < 0.01 && (container.height() - 200.0).abs() < 0.01,
        "vertical inline-flex should keep block-size as physical width and inline-size as physical height: {container:?}"
    );

    let items = page
        .rects()
        .iter()
        .filter(|rect| rect.fill == Some(gray))
        .collect::<Vec<_>>();
    assert_eq!(
        items.len(),
        4,
        "expected four grey flex item backgrounds: {:?}",
        page.rects()
    );
    assert!(
        items.iter().all(|rect| rect.width() <= 20.0),
        "vertical text flex item physical widths should come from line-height, not text advance: {items:?}"
    );
    assert!(
        items.iter().enumerate().any(|(index, item)| {
            items[index + 1..]
                .iter()
                .any(|other| rects_overlap_y(item, other) && rects_have_gap_x(item, other, 20.0))
        }),
        "same flex line should have a 20pt physical horizontal gap between vertical text items: {items:?}"
    );
    assert!(
        items.iter().enumerate().any(|(index, item)| {
            items[index + 1..]
                .iter()
                .any(|other| !rects_overlap_y(item, other) && rects_have_gap_y(item, other, 20.0))
        }),
        "wrapped flex lines should have a 20pt physical vertical gap: {items:?}"
    );
}

#[tokio::test]
async fn column_flex_centered_anonymous_text_uses_intrinsic_cross_size() {
    let block_center = single_x_line_x("text-align: center").await;
    let flex_center = single_x_line_x(
        "display: flex; flex-direction: column; align-items: center; text-align: center",
    )
    .await;
    let flex_left = single_x_line_x(
        "display: flex; flex-direction: column; align-items: center; text-align: left",
    )
    .await;

    assert!(
        (flex_center - block_center).abs() < 0.01,
        "centered anonymous flex text should match block centering: flex={flex_center}, block={block_center}"
    );
    assert!(
        (flex_center - flex_left).abs() < 0.01,
        "text-align should not add a second offset inside shrinkwrapped anonymous flex text: center={flex_center}, left={flex_left}"
    );
}

#[tokio::test]
async fn inherited_vertical_rl_inline_flex_column_wrap_gap_uses_logical_item_block_sizes() {
    assert_vertical_rl_inline_flex_column_wrap_gap(
        "<!DOCTYPE html><style>@page { size: 400pt 400pt; margin: 0 }\
         body { margin: 0; writing-mode: vertical-rl }\
         section { background-color: green; block-size: 100pt; inline-size: 200pt;\
                   display: inline-flex; flex-direction: column; flex-wrap: wrap;\
                   gap: 20pt; line-height: 18pt; font-size: 12pt; vertical-align: top }\
         section > div { background-color: grey; color: white }</style>\
         <section><div>Black Panther</div><div>Wonder Woman</div><div>Storm</div><div>Flash</div></section>",
    )
    .await;
}

#[tokio::test]
async fn direct_vertical_rl_inline_flex_column_wrap_gap_uses_logical_item_block_sizes() {
    assert_vertical_rl_inline_flex_column_wrap_gap(
        "<!DOCTYPE html><style>@page { size: 400pt 400pt; margin: 0 }\
         body { margin: 0 }\
         section { writing-mode: vertical-rl; background-color: green; block-size: 100pt;\
                   inline-size: 200pt; display: inline-flex; flex-direction: column;\
                   flex-wrap: wrap; gap: 20pt; line-height: 18pt; font-size: 12pt;\
                   vertical-align: top }\
         section > div { background-color: grey; color: white }</style>\
         <section><div>Black Panther</div><div>Wonder Woman</div><div>Storm</div><div>Flash</div></section>",
    )
    .await;
}

#[tokio::test]
async fn stretched_vertical_flex_item_defines_descendant_percentage_padding_basis() {
    let document = Html::from_string(
        "<!DOCTYPE html><style>\
         @page { size: 100px 100px; margin: 0 } body { margin: 0 }\
         x-flexbox { display: flex; height: 100px }\
         x-item { background: green; writing-mode: vertical-lr }\
         x-item > div { padding-right: 70%; width: 30px }\
         </style><x-flexbox><x-item><div></div></x-item></x-flexbox>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .unwrap_or_else(|| {
            panic!(
                "expected green flex item background: {:?}",
                document.pages[0].rects()
            )
        });
    assert!(
        (green.width() - 75.0).abs() < 0.01 && (green.height() - 75.0).abs() < 0.01,
        "stretched vertical item should use its 100px inline size for descendant percentage padding: {green:?}"
    );
}

#[tokio::test]
async fn stretched_replaced_descendant_transfers_size_from_stretched_flex_item() {
    let document = Html::from_string(
        "<!DOCTYPE html><style>\
         @page { size: 140px 140px; margin: 0 } body { margin: 0 } p { display: none }\
         </style>\
         <p>Test passes if there is a filled green square.</p>\
         <div style=\"display: inline-flex; height: 100px; background: green;\">\
           <div><canvas width=\"10\" height=\"10\" style=\"height: 100%\"></canvas></div>\
         </div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .unwrap_or_else(|| {
            panic!(
                "expected green inline-flex background: {:?}",
                document.pages[0].rects()
            )
        });

    assert!(
        (green.width() - 75.0).abs() < 0.01 && (green.height() - 75.0).abs() < 0.01,
        "stretched flex item should give the canvas a definite 100px percentage-height basis and transfer width through its 1:1 ratio: {green:?}"
    );
}

async fn assert_column_flex_post_flexing_percentage_height_descendant_square(doctype: &str) {
    let document = Html::from_string(format!(
        "{doctype}<html><head><style>\
         @page {{ size: 240px 240px; margin: 0 }} body {{ margin: 0 }} p {{ display: none }}\
         </style></head><body>\
         <p style=\"margin-top: 1em\">Test passes if there is a filled green square.</p>\
         <div style=\"display: flex; width: 100px; height: 100px; flex-direction: column;\">\
           <div style=\"flex-grow: 1; height: 0;\">\
             <div style=\"display: flex; flex-direction: column; height: 100%;\">\
               <div style=\"width: 100px; height: 50px; background-color: green;\"></div>\
               <div style=\"flex: 1;\">\
                 <div style=\"height: 100%; background-color: green;\"></div>\
               </div>\
             </div>\
           </div>\
         </div></body></html>"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green_rects = document.pages[0]
        .rects()
        .iter()
        .filter(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .collect::<Vec<_>>();
    assert!(
        !green_rects.is_empty(),
        "expected green square paint: {:?}",
        document.pages[0].rects()
    );

    let min_x = green_rects
        .iter()
        .map(|rect| rect.x())
        .fold(f32::INFINITY, f32::min);
    let max_x = green_rects
        .iter()
        .map(|rect| rect.x() + rect.width())
        .fold(f32::NEG_INFINITY, f32::max);
    let min_y = green_rects
        .iter()
        .map(|rect| rect.y())
        .fold(f32::INFINITY, f32::min);
    let max_y = green_rects
        .iter()
        .map(|rect| rect.y() + rect.height())
        .fold(f32::NEG_INFINITY, f32::max);
    let green_area = green_rects
        .iter()
        .map(|rect| rect.width() * rect.height())
        .sum::<f32>();
    let expected = 75.0;
    assert!(
        (max_x - min_x - expected).abs() < 0.01
            && (max_y - min_y - expected).abs() < 0.01
            && (green_area - expected * expected).abs() < 0.1,
        "post-flexing main size should define nested percentage heights: rects={green_rects:?}"
    );
}

#[tokio::test]
async fn column_flex_post_flexing_main_size_defines_descendant_percentage_height() {
    assert_column_flex_post_flexing_percentage_height_descendant_square("").await;
}

#[tokio::test]
async fn standards_column_flex_post_flexing_main_size_defines_descendant_percentage_height() {
    assert_column_flex_post_flexing_percentage_height_descendant_square("<!DOCTYPE html>").await;
}

#[tokio::test]
async fn block_flex_item_contains_first_child_margin() {
    let document = Html::from_string(
        "<!DOCTYPE html><style>\
         @page { size: 200pt 200pt; margin: 0 } body { margin: 0 }\
         .flex { display: flex; align-items: flex-start; width: 100pt }\
         .item { background: green; width: 50pt }\
         .item > div { margin-top: 20pt; height: 10pt; background: red }\
         </style><div class=\"flex\"><div class=\"item\"><div></div></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .unwrap_or_else(|| {
            panic!(
                "expected flex item background: {:?}",
                document.pages[0].rects()
            )
        });
    assert!(
        (green.height() - 30.0).abs() < 0.01,
        "flex item should establish an independent formatting context and contain first-child margin: {green:?}"
    );
}

#[tokio::test]
async fn block_flex_item_contains_internal_float_height() {
    let document = Html::from_string(
        "<!DOCTYPE html><style>\
         @page { size: 200pt 200pt; margin: 0 } body { margin: 0 }\
         .flex { display: flex; align-items: flex-start; width: 100pt }\
         .item { background: green; width: 50pt }\
         .float { float: left; width: 30pt; height: 25pt; background: red }\
         </style><div class=\"flex\"><div class=\"item\"><div class=\"float\"></div></div><div style=\"width: 10pt; height: 10pt; background: blue\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .unwrap_or_else(|| {
            panic!(
                "expected flex item background: {:?}",
                document.pages[0].rects()
            )
        });
    assert!(
        (green.height() - 25.0).abs() < 0.01,
        "flex item should contain internal floats in its independent formatting context: {green:?}"
    );
}

#[tokio::test]
async fn inline_flex_item_contains_first_child_margin() {
    let document = Html::from_string(
        "<!DOCTYPE html><style>\
         @page { size: 200pt 200pt; margin: 0 } body { margin: 0 }\
         .flex { display: inline-flex; align-items: flex-start; vertical-align: top }\
         .item { background: green; width: 50pt }\
         .item > span { display: block; margin-top: 20pt; height: 10pt; background: red }\
         </style><span class=\"flex\"><span class=\"item\"><span></span></span></span>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .unwrap_or_else(|| {
            panic!(
                "expected inline-flex item background: {:?}",
                document.pages[0].rects()
            )
        });
    assert!(
        (green.height() - 30.0).abs() < 0.01,
        "inline-flex item should use the same independent formatting context semantics: {green:?}"
    );
}

#[tokio::test]
async fn flex_blockified_inline_item_paints_source_background_once() {
    let document = Html::from_string(
        "<!DOCTYPE html><style>\
         @page { size: 200pt 200pt; margin: 0 } body { margin: 0 }\
         .flex { display: flex; width: 100pt; font-size: 10pt; line-height: 10pt }\
         .item { display: inline; background: rgb(10, 20, 30); color: transparent }\
         </style><div class=\"flex\"><span class=\"item\">text</span></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let painted = document.pages[0]
        .rects()
        .iter()
        .filter(|rect| rect.fill == Some(CssColor::new(10, 20, 30)))
        .collect::<Vec<_>>();
    assert_eq!(
        painted.len(),
        1,
        "blockified inline flex item should not also paint inline text-fragment background: {painted:?}"
    );
}

#[tokio::test]
async fn flex_replay_keeps_a_grid_item_descendant_visible_without_root_decoration() {
    let document = Html::from_string(
        "<!DOCTYPE html><style>\
         @page { size: 200pt 200pt; margin: 0 } body { margin: 0 }\
         .flex { display: flex; width: 100pt; height: 100pt }\
         .item { display: grid; width: 100pt; height: 100pt }\
         .child { background: rgb(0, 128, 0) }\
         </style><div class=\"flex\"><div class=\"item\"><div class=\"child\"></div></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let painted = document.pages[0]
        .rects()
        .iter()
        .filter(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .collect::<Vec<_>>();
    assert_eq!(
        painted.len(),
        1,
        "grid descendant must paint once: {painted:?}"
    );
    assert!(
        (painted[0].width() - 100.0).abs() < 0.01 && (painted[0].height() - 100.0).abs() < 0.01,
        "grid descendant must retain the flex item's placed geometry: {:?}",
        painted[0]
    );
}

#[tokio::test]
async fn flex_replay_paints_grid_root_decoration_and_child_once_each() {
    let document = Html::from_string(
        "<!DOCTYPE html><style>\
         @page { size: 200pt 200pt; margin: 0 } body { margin: 0 }\
         .flex { display: flex; width: 100pt; height: 100pt }\
         .item { display: grid; box-sizing: border-box; width: 100pt; height: 100pt;\
                 background: rgb(255, 0, 0); border: 5pt solid rgb(0, 0, 0) }\
         .child { background: rgb(0, 0, 255) }\
         </style><div class=\"flex\"><div class=\"item\"><div class=\"child\"></div></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let rects = document.pages[0].rects();
    let red = rects
        .iter()
        .filter(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
        .collect::<Vec<_>>();
    let blue = rects
        .iter()
        .filter(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .collect::<Vec<_>>();
    let black = rects
        .iter()
        .filter(|rect| rect.fill == Some(CssColor::new(0, 0, 0)))
        .collect::<Vec<_>>();
    assert_eq!(
        red.len(),
        1,
        "grid root background must paint once: {red:?}"
    );
    assert_eq!(
        blue.len(),
        1,
        "grid child background must paint once: {blue:?}"
    );
    assert_eq!(
        black.len(),
        4,
        "grid root border edges must paint once: {black:?}"
    );
}

#[tokio::test]
async fn column_flex_stretched_aspect_ratio_item_keeps_content_auto_minimum() {
    let document = Html::from_string(
        "<!DOCTYPE html><style>\
         @page { size: 240px 180px; margin: 0 } body { margin: 0 } p { display: none }\
         </style>\
         <p>Test passes if there is a filled green square.</p>\
         <div style=\"display: flex; flex-direction: column; width: 100px; height: 0px;\">\
           <div style=\"background: green; aspect-ratio: 2/1;\">\
             <div style=\"height: 100px;\"></div>\
           </div>\
         </div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .unwrap_or_else(|| {
            panic!(
                "expected green flex item background: {:?}",
                document.pages[0].rects()
            )
        });

    assert!(
        (green.width() - 75.0).abs() < 0.01 && (green.height() - 75.0).abs() < 0.01,
        "stretched column flex item should be a 100px square after content auto-minimum sizing: {green:?}"
    );
}

#[tokio::test]
async fn empty_column_flex_stretched_aspect_ratio_item_keeps_transferred_basis() {
    let document = Html::from_string(
        "<!DOCTYPE html><style>\
         @page { size: 240px 180px; margin: 0 } body { margin: 0 }\
         </style>\
         <div style=\"display: flex; flex-direction: column; width: 100px; height: 0px;\">\
           <div style=\"background: green; aspect-ratio: 2/1;\"></div>\
         </div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .unwrap_or_else(|| {
            panic!(
                "expected green flex item background: {:?}",
                document.pages[0].rects()
            )
        });

    assert!(
        (green.width() - 75.0).abs() < 0.01 && (green.height() - 37.5).abs() < 0.01,
        "empty stretched column flex item should keep the 100px by 50px transferred flex basis: {green:?}"
    );
}

#[tokio::test]
async fn stretch_min_cross_size_preserves_non_negative_content_box() {
    let document = Html::from_string(
        "<!DOCTYPE html>\
         <style>\
         @page { size: 220px 220px; margin: 0 } body { margin: 0 } p { display: none }\
         #red { position: absolute; z-index: -1; width: 200px; height: 200px; background: red }\
         #flex-container { display: flex; flex-direction: row; height: 0 }\
         #flex-item { min-height: stretch; border: 100px solid green }\
         </style>\
         <p>Test passes if there is a filled green square and no red.</p>\
         <div id=\"red\"></div><div id=\"flex-container\"><div id=\"flex-item\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let green = CssColor::new(0, 128, 0);
    for (x, y) in [(37.5, 37.5), (112.5, 37.5), (37.5, 112.5), (112.5, 112.5)] {
        assert_eq!(
            final_rect_fill_at(page, x, y),
            Some(green),
            "stretched flex item border should cover the red reference square at ({x}, {y}): {:?}",
            page.rects()
        );
    }
}

#[tokio::test]
async fn abspos_auto_position_honors_flex_alignment_on_both_axes() {
    let document = Html::from_string(
        "<!doctype html><style>\
         @page { size: 220px 220px; margin: 0 } body { margin: 0 }\
         .parent { position: fixed; top: 0; left: 0; display: flex;\
           align-items: center; justify-content: center; width: 200px; height: 200px;\
           background: yellow }\
         .child { position: absolute; width: 100px; height: 100px; background: green }\
         </style><div class=\"parent\"><div class=\"child\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let yellow = CssColor::new(255, 255, 0);
    let green = CssColor::new(0, 128, 0);
    let parent = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(yellow))
        .unwrap_or_else(|| panic!("expected yellow flex container: {:?}", page.rects()));
    let child = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(green))
        .unwrap_or_else(|| panic!("expected green abspos flex child: {:?}", page.rects()));

    let px = 0.75;
    let expected_offset = 50.0 * px;
    assert!(
        (child.x() - parent.x() - expected_offset).abs() < 0.01
            && (child.y() - parent.y() - expected_offset).abs() < 0.01
            && (child.width() - 100.0 * px).abs() < 0.01
            && (child.height() - 100.0 * px).abs() < 0.01,
        "abspos flex child should be centered by justify-content and align-items: parent={parent:?}, child={child:?}"
    );
}

#[tokio::test]
async fn abspos_auto_position_covers_vertical_writing_flex_content_box() {
    for writing_mode in ["vertical-lr", "vertical-rl"] {
        let document = Html::from_string(format!(
            "<!DOCTYPE html><style>\
             @page {{ size: 140px 140px; margin: 0 }} body {{ margin: 0 }} p {{ display: none }}\
             .flex {{ display: flex; position: relative; writing-mode: {writing_mode}; direction: ltr;\
               width: 100px; height: 100px; border: solid white; border-left-width: 20px; left: -20px;\
               border-top-width: 5px; top: -5px; border-right-width: 10px; border-bottom-width: 15px;\
               background: red }}\
             .flex > div {{ position: absolute; width: 100%; height: 100%; background: green }}\
             </style><p>Test passes if there is a filled green square and no red.</p>\
             <div class=\"flex\"><div></div></div>"
        ))
        .render(&RenderOptions::default())
        .await
        .unwrap();

        let page = &document.pages[0];
        let red = page
            .rects()
            .iter()
            .find(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
            .unwrap_or_else(|| {
                panic!(
                    "expected flex background for {writing_mode}: {:?}",
                    page.rects()
                )
            });
        let green = CssColor::new(0, 128, 0);
        let px = 0.75;
        let content_left = red.x() + 20.0 * px;
        let content_bottom = red.y() + 15.0 * px;
        let content_width = 100.0 * px;
        let content_height = 100.0 * px;
        for (x, y) in [
            (
                content_left + content_width / 2.0,
                content_bottom + content_height / 2.0,
            ),
            (content_left + content_width / 2.0, content_bottom + 1.0),
            (
                content_left + content_width / 2.0,
                content_bottom + content_height - 1.0,
            ),
        ] {
            assert_eq!(
                final_rect_fill_at(page, x, y),
                Some(green),
                "{writing_mode} abspos child should cover red flex background at ({x}, {y}): {:?}",
                page.rects()
            );
        }
    }
}

#[tokio::test]
async fn generated_after_pseudo_participates_as_flex_item() {
    let document = Html::from_string(
        r#"<!DOCTYPE html>
<style>
@page { size: 420pt 140pt; margin: 10pt }
body { margin: 0 }
div {
    background: #3366cc;
    display: flex;
}
div::after, p {
    content: "xxx";
    background: yellow;
    margin: 1em;
    width: 200px;
    height: 2em;
}
div::after {
    content: "yyy";
    display: block;
}
</style>
<div>
    <p>FAIL</p>
</div>"#,
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let yellow = page
        .rects()
        .iter()
        .filter(|rect| rect.fill == Some(CssColor::new(255, 255, 0)))
        .collect::<Vec<_>>();
    assert_eq!(
        yellow.len(),
        2,
        "real child and generated ::after should both paint yellow flex item backgrounds: {:?}",
        page.rects()
    );
    assert!(
        yellow[1].x() > yellow[0].x() + yellow[0].width(),
        "generated ::after flex item should be laid out after the real child: {yellow:?}"
    );
    assert!(
        page.lines().iter().any(|line| line.text == "yyy"),
        "generated ::after text should render as flex item content: {:?}",
        page.lines()
    );
}

#[tokio::test]
async fn generated_pseudo_flex_items_participate_in_order_sorting() {
    let document = Html::from_string(
        "<style>@page { size: 140pt 80pt; margin: 10pt } body { margin: 0 }\
         div { display: flex; width: 90pt; font-size: 10pt; line-height: 10pt }\
         span, div::before, div::after { display: block; width: 20pt; height: 10pt }\
         div::before { content: 'A'; order: 3 }\
         span { order: 2 }\
         div::after { content: 'C'; order: 1 }</style>\
         <div><span>B</span></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let mut line_text_by_x = document.pages[0]
        .lines()
        .iter()
        .map(|line| (line.x(), line.text.as_str()))
        .collect::<Vec<_>>();
    line_text_by_x.sort_by(|left, right| left.0.total_cmp(&right.0));
    let text = line_text_by_x
        .iter()
        .map(|(_, text)| *text)
        .collect::<Vec<_>>();
    assert_eq!(
        text,
        vec!["C", "B", "A"],
        "pseudo and element flex items should share order-modified document order: {:?}",
        document.pages[0].lines()
    );
}

#[tokio::test]
async fn flex_order_painting_uses_order_modified_document_order_with_negative_margin() {
    let document = Html::from_string(
        "<!DOCTYPE html><style>\
         @page { size: 200px 160px; margin: 0 } body { margin: 0 } p { display: none }\
         </style>\
         <p>This test passes if there is no red showing.</p>\
         <div style=\"display: flex; width: 100px;\">\
         <div style=\"order: 2; background-color: green; width: 100px; height: 100px; margin-left: -50px;\"></div>\
         <div style=\"order: 1; background-color: red; width: 50px; height: 100px;\"></div>\
         </div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let red = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
        .unwrap_or_else(|| panic!("expected red flex item background: {:?}", page.rects()));
    assert_eq!(
        final_rect_fill_at(
            page,
            red.x() + red.width() / 2.0,
            red.y() + red.height() / 2.0
        ),
        Some(CssColor::new(0, 128, 0)),
        "order-modified flex painting should cover the lower-order red item with the negative-margin green item: {:?}",
        page.rects()
    );
}

#[tokio::test]
async fn flex_items_paint_each_decoration_before_its_own_contents() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 80pt; margin: 10pt } body { margin: 0; font-size: 12pt; line-height: 12pt } .flex { display: flex; height: 36pt } .item { flex: 0 0 0; height: 12pt } .first { background: yellow } .second { background: pink }</style><div class=\"flex\"><span class=\"item first\">one</span><span class=\"item second\">two</span></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let yellow = page
        .rects()
        .iter()
        .position(|rect| rect.fill == Some(CssColor::new(255, 255, 0)))
        .expect("first flex item background should paint");
    let pink = page
        .rects()
        .iter()
        .position(|rect| rect.fill == Some(CssColor::new(255, 192, 203)))
        .expect("second flex item background should paint");
    let one = page
        .lines()
        .iter()
        .position(|line| line.text == "one")
        .expect("first flex item text should paint");
    let two = page
        .lines()
        .iter()
        .position(|line| line.text == "two")
        .expect("second flex item text should paint");

    let yellow_operation = page
        .operations()
        .iter()
        .position(
            |operation| matches!(operation, crate::document::paint::page::PaintOperation::Rect(index) if *index == yellow),
        )
        .expect("first flex item background should have a paint operation");
    let one_operation = page
        .operations()
        .iter()
        .position(
            |operation| matches!(operation, crate::document::paint::page::PaintOperation::Line(index) if *index == one),
        )
        .expect("first flex item text should have a paint operation");
    let pink_operation = page
        .operations()
        .iter()
        .position(
            |operation| matches!(operation, crate::document::paint::page::PaintOperation::Rect(index) if *index == pink),
        )
        .expect("second flex item background should have a paint operation");
    let two_operation = page
        .operations()
        .iter()
        .position(
            |operation| matches!(operation, crate::document::paint::page::PaintOperation::Line(index) if *index == two),
        )
        .expect("second flex item text should have a paint operation");

    assert!(
        yellow_operation < one_operation
            && one_operation < pink_operation
            && pink_operation < two_operation,
        "flex items must paint like inline blocks in order-modified document order: {:?}",
        page.operations()
    );
}

#[tokio::test]
async fn definite_width_block_flex_container_overflows_without_shrinking_items() {
    let document = Html::from_string(
        "<style>@page { size: 500pt 160pt; margin: 20pt } body { margin: 0 }\
         .row { display: flex; width: 480pt; height: 40pt; background: blue }\
         .item { flex: 0 1 auto; width: 60pt; height: 20pt }\
         .a { background: yellow } .b { background: pink }\
         .c { background: lightblue } .d { background: gray }</style>\
         <div class=\"row\"><span class=\"item a\">one</span><span class=\"item b\">two</span><span class=\"item c\">three</span><span class=\"item d\">four</span></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let container = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .expect("definite-width flex container background should paint");
    assert!(
        (container.width() - 480.0).abs() < 0.01,
        "definite-width block flex container should overflow instead of clamping to the 460pt containing block: {container:?}"
    );

    for color in [
        CssColor::new(255, 255, 0),
        CssColor::new(255, 192, 203),
        CssColor::new(173, 216, 230),
        CssColor::new(128, 128, 128),
    ] {
        let item = page
            .rects()
            .iter()
            .find(|rect| rect.fill == Some(color))
            .unwrap_or_else(|| {
                panic!("expected flex item with fill {color:?}: {:?}", page.rects())
            });
        assert!(
            (item.width() - 60.0).abs() < 0.01,
            "flex: 0 1 auto item should keep its definite width: {item:?}"
        );
    }
}

#[tokio::test]
async fn auto_height_row_flex_container_applies_min_max_height_constraints() {
    let document = Html::from_string(
        "<!DOCTYPE html><style>\
         @page { size: 240pt 220pt; margin: 0 } body { margin: 0 }\
         .flexbox { width: 200px; border: 1px dashed blue; background: lightgreen;\
           font-size: 10px; display: flex; margin-bottom: 5px }\
         .flexbox > div { width: 200px }\
         </style>\
         <div class=\"flexbox\"><div>text</div></div>\
         <div class=\"flexbox\" style=\"min-height: 2px\"><div>text</div></div>\
         <div class=\"flexbox\" style=\"max-height: 300px\"><div>text</div></div>\
         <div class=\"flexbox\" style=\"min-height: 30px\"><div>text</div></div>\
         <div class=\"flexbox\" style=\"max-height: 6px\"><div>text</div></div>\
         <div class=\"flexbox\" style=\"min-height: 30px; max-height: 5px\"><div>text</div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let mut flexboxes = document.pages[0]
        .rects()
        .iter()
        .filter(|rect| rect.fill == Some(CssColor::new(144, 238, 144)))
        .collect::<Vec<_>>();
    assert_eq!(
        flexboxes.len(),
        6,
        "expected six flex container backgrounds: {:?}",
        document.pages[0].rects()
    );
    flexboxes.sort_by(|a, b| b.y().partial_cmp(&a.y()).unwrap());

    let px = 0.75;
    let border_box_extra = 2.0 * px;
    let shrinkwrapped_height = flexboxes[0].height();
    for index in 0..3 {
        assert!(
            (flexboxes[index].height() - shrinkwrapped_height).abs() < 0.01,
            "unconstraining min/max-height should preserve shrinkwrapped auto height: {flexboxes:?}"
        );
    }
    assert!(
        (flexboxes[3].height() - (30.0 * px + border_box_extra)).abs() < 0.01,
        "min-height should floor the auto-height flex container: {flexboxes:?}"
    );
    assert!(
        (flexboxes[4].height() - (6.0 * px + border_box_extra)).abs() < 0.01,
        "max-height should clamp the auto-height flex container without using overflowing item extents: {flexboxes:?}"
    );
    assert!(
        (flexboxes[5].height() - (30.0 * px + border_box_extra)).abs() < 0.01,
        "min-height should win when it is larger than max-height: {flexboxes:?}"
    );
}

#[tokio::test]
async fn fixed_width_block_flex_container_resolves_auto_margins() {
    let document = Html::from_string(
        "<style>@page { size: 300pt 120pt; margin: 20pt } body { margin: 0 }\
         .row { display: flex; width: 100pt; height: 20pt; margin-left: auto; margin-right: auto; background: green }\
         .item { width: 20pt; height: 20pt }</style>\
         <div class=\"row\"><div class=\"item\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("centered flex container background should paint");
    assert!(
        (green.x() - 100.0).abs() < 0.01 && (green.width() - 100.0).abs() < 0.01,
        "fixed-width block flex container should resolve auto margins like normal block layout: {green:?}"
    );
}

#[tokio::test]
async fn horizontal_flex_img_items_use_flex_resolved_content_widths() {
    let image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC";
    let document = Html::from_string(format!(
        "<!DOCTYPE html><style>\
         @page {{ size: 260px 260px; margin: 0 }} body {{ margin: 0 }}\
         div.flexbox {{ width: 200px; background: lightgreen; display: flex;\
           justify-content: space-between; margin-bottom: 5px; line-height: 8px }}\
         img {{ min-width: 0; width: 10px; height: 20px; border: 1px dotted green }}\
         </style>\
         <div class=\"flexbox\"><img src=\"{image}\"></div>\
         <div class=\"flexbox\">some words <img src=\"{image}\"></div>\
         <div class=\"flexbox\"><img src=\"{image}\" style=\"flex: 5\"><img src=\"{image}\" style=\"flex: 3\"></div>\
         <div class=\"flexbox\"><img src=\"{image}\" style=\"width: 33px; flex: 2 auto\"><img src=\"{image}\" style=\"width: 13px; flex: 3 auto\"></div>\
         <div class=\"flexbox\"><img src=\"{image}\" style=\"width: 150px; flex: 1 4 auto\"><img src=\"{image}\" style=\"width: 100px; flex: 1 3 auto\"></div>\
         <div class=\"flexbox\"><img src=\"{image}\" style=\"width: 33px; flex: 2 auto\"><img src=\"{image}\" style=\"width: 13px; max-width: 90px; flex: 3 auto\"></div>\
         <div class=\"flexbox\"><img src=\"{image}\" style=\"width: 33px; flex: 2 auto\"><img src=\"{image}\" style=\"width: 13px; min-width: 150px; flex: 3 auto\"></div>",
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let px = 0.75;
    let mut images = document.pages[0]
        .images()
        .iter()
        .filter(|image| !image.background)
        .collect::<Vec<_>>();
    images.sort_by(|left, right| {
        right
            .y()
            .partial_cmp(&left.y())
            .unwrap()
            .then_with(|| left.x().partial_cmp(&right.x()).unwrap())
    });
    let rows = images
        .chunk_by(|left, right| (left.y() - right.y()).abs() < 0.5)
        .map(|row| {
            row.iter()
                .map(|image| image.width() / px)
                .collect::<Vec<_>>()
        })
        .collect::<Vec<_>>();

    assert_eq!(
        rows.len(),
        7,
        "expected one rendered image row for each flexbox: {images:?}"
    );
    assert!(
        images[1].x() / px > 185.0,
        "text and image should be separate flex items so space-between packs the image at the far edge: {images:?}"
    );
    let expected: &[&[f32]] = &[
        &[10.0],
        &[10.0],
        &[122.5, 73.5],
        &[93.0, 103.0],
        &[114.0, 82.0],
        &[106.0, 90.0],
        &[46.0, 150.0],
    ];
    for (row, expected_row) in rows.iter().zip(expected) {
        assert_eq!(
            row.len(),
            expected_row.len(),
            "unexpected image count in row: rows={rows:?}, images={images:?}"
        );
        for (actual, expected) in row.iter().zip(*expected_row) {
            assert!(
                (actual - expected).abs() < 0.25,
                "expected image content width {expected}px, got {actual}px; rows={rows:?}, images={images:?}"
            );
        }
    }
}

#[tokio::test]
async fn align_content_stretch_overflow_falls_back_to_wrap_reverse_flex_start() {
    let document = Html::from_string(
        "<!DOCTYPE html><meta charset=\"utf-8\">\
         <style>@page { size: 420px 420px; margin: 0 } body { margin: 0 }\
         #flex { display: flex; width: 200px; height: 200px; flex-wrap: wrap-reverse; align-content: stretch }\
         #item { width: 200px; height: 400px; background: linear-gradient(to bottom, red 50%, green 50%) }</style>\
         <p>Test passes if there is a filled green square and no red.</p>\
         <div style=\"overflow: hidden\"><div id=\"flex\"><div id=\"item\"></div></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let green = CssColor::new(0, 128, 0);
    let green_rect = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(green) && rect.width() > 149.0 && rect.height() > 149.0)
        .unwrap_or_else(|| panic!("expected clipped green square: {:?}", page.rects()));
    // CSS overflow is retained as an effect scope rather than destructively
    // rewriting the source geometry of its descendants. The raw paint tree
    // consequently still contains the red gradient half; verify the PDF
    // output retains the enclosing overflow clip that excludes it visually.
    let rendered = pdf_searchable_text(
        &document
            .write_pdf_bytes(&PdfOptions::default())
            .expect("document should serialize"),
    );
    assert!(
        rendered.contains("W\nn"),
        "align-content:stretch overflow fallback must clip the red half above {green_rect:?}"
    );
    for (x, y) in [(10.0, 10.0), (75.0, 75.0), (140.0, 140.0)] {
        assert_eq!(
            final_rect_fill_at(page, green_rect.x() + x, green_rect.y() + y),
            Some(green),
            "align-content:stretch overflow fallback should expose only the green half at ({x}, {y}) inside {green_rect:?}: {:?}",
            page.rects()
        );
    }
}

#[tokio::test]
async fn flex_shrink_to_fit_item_remeasures_against_column_line_cross_size() {
    let document = Html::from_string(
        "<!DOCTYPE html><meta charset=\"utf-8\">\
         <style>@page { size: 260px 240px; margin: 0 } body { margin: 0 }\
         #container { display: flex; flex-flow: column wrap; width: 100px; border-right: 100px solid red }\
         #item { align-self: start; background: linear-gradient(to bottom, red 50%, green 50%) }\
         .float { float: left; width: 100px; height: 100px; background: green }</style>\
         <div id=\"container\"><div id=\"item\"><div class=\"float\"></div><div class=\"float\"></div></div><div style=\"width: 200px\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let green = CssColor::new(0, 128, 0);
    let red = CssColor::new(255, 0, 0);
    for (x, y) in [(10.0, 50.0), (140.0, 50.0), (10.0, 150.0), (140.0, 150.0)] {
        let x = x * 0.75;
        let y = y * 0.75;
        assert_eq!(
            final_rect_fill_at(page, x, y),
            Some(green),
            "shrink-to-fit flex item should cover the 200px line cross-size at ({x}, {y}): {:?}",
            page.rects()
        );
        assert_ne!(
            final_rect_fill_at(page, x, y),
            Some(red),
            "final 200px square should not expose red at ({x}, {y}): {:?}",
            page.rects()
        );
    }
}

#[tokio::test]
async fn column_wrap_flex_min_content_width_uses_item_cross_contribution() {
    let document = Html::from_string(
        "<style>@page { size: 300px 200px; margin: 0 } body { margin: 0 }\
         #reference-overlapped-red { position: absolute; background-color: red; width: 100px; height: 100px; z-index: -1 }\
         .item { min-height: 0px; width: 100px; flex: 0 0 auto }\
         .flex { display: flex; flex-flow: column wrap; height: 100px; width: min-content; background: green }\
         </style><div id=\"reference-overlapped-red\"></div><div class=\"flex\"><div class=\"item\"></div><div class=\"item\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let green = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("min-content flex container background should paint");
    assert!(
        (green.width() - 75.0).abs() < 0.01 && (green.height() - 75.0).abs() < 0.01,
        "100px min-content flex container should paint as a 75pt square: {green:?}"
    );
    assert_eq!(
        final_rect_fill_at(
            page,
            green.x() + green.width() / 2.0,
            green.y() + green.height() / 2.0
        ),
        Some(CssColor::new(0, 128, 0)),
        "green flex container should fully cover the red reference square: {:?}",
        page.rects()
    );
}

#[tokio::test]
async fn column_wrap_inline_flex_min_content_width_uses_item_cross_contribution() {
    let document = Html::from_string(
        "<style>@page { size: 300px 200px; margin: 0 } body { margin: 0 }\
         .item { min-height: 0px; width: 100px; flex: 0 0 auto }\
         .flex { display: inline-flex; flex-flow: column wrap; height: 100px; width: min-content; background: green; vertical-align: top }\
         </style><span class=\"flex\"><span class=\"item\"></span><span class=\"item\"></span></span>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("inline-flex background should paint");
    assert!(
        (green.width() - 75.0).abs() < 0.01 && (green.height() - 75.0).abs() < 0.01,
        "100px inline-flex min-content width should paint as 75pt: {green:?}"
    );
}

#[tokio::test]
async fn column_wrap_flex_min_content_width_does_not_sum_wrapped_columns() {
    let document = Html::from_string(
        "<style>@page { size: 300px 200px; margin: 0 } body { margin: 0 }\
         .item { width: 100px; height: 100px; flex: 0 0 auto }\
         .flex { display: flex; flex-flow: column wrap; height: 100px; width: min-content; background: green }\
         </style><div class=\"flex\"><div class=\"item\"></div><div class=\"item\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("min-content column flex background should paint");
    assert!(
        (green.width() - 75.0).abs() < 0.01 && (green.height() - 75.0).abs() < 0.01,
        "column flex min-content cross size should be the largest item contribution, not the sum of wrapped columns: {green:?}"
    );
}

#[tokio::test]
async fn floated_column_wrap_flex_shrink_to_fit_width_matches_wpt() {
    let document = Html::from_string(
        "<!DOCTYPE html>\
         <title>CSS Flexbox: multiline column flexboxes and shrink-to-fit.</title>\
         <style>\
         @page { size: 900px 700px; margin: 0 } body { margin: 0 }\
         .flexbox { display: flex; background-color: #aaa; position: relative;\
                    flex-wrap: wrap; flex-direction: column; float: left;\
                    align-content: flex-start }\
         .flexbox > * { flex: none }\
         .flexbox :nth-child(1) { background-color: lightblue }\
         .flexbox :nth-child(2) { background-color: lightgreen }\
         .flexbox :nth-child(3) { background-color: pink }\
         .flexbox :nth-child(4) { background-color: yellow }\
         </style>\
         <div class=\"flexbox\">\
           <div style=\"width: 100px; height: 20px\"></div>\
           <div style=\"width: 100px; height: 10px\"></div>\
           <div style=\"width: 100px; height: 10px\"></div>\
           <div style=\"width: 100px; height: 20px\"></div>\
         </div>\
         <p style=\"clear:left\">The grey background should be 100px wide.</p>\
         <div class=\"flexbox\" style=\"height: 30px\">\
           <div style=\"width: 100px; height: 20px\"></div>\
           <div style=\"width: 100px; height: 10px\"></div>\
           <div style=\"width: 100px; height: 10px\"></div>\
           <div style=\"width: 100px; height: 20px\"></div>\
         </div>\
         <p style=\"clear:left\">The grey background should be 100px wide.</p>\
         <div style=\"width: 150px\">\
           <div class=\"flexbox\">\
             <div style=\"width: 100px; height: 20px\"></div>\
             <div style=\"width: 100px; height: 10px\"></div>\
             <div style=\"width: 100px; height: 10px\"></div>\
             <div style=\"width: 100px; height: 20px\"></div>\
           </div>\
         </div>\
         <p style=\"clear:left\">The grey background should be 100px wide.</p>\
         <div style=\"width: 150px\">\
           <div class=\"flexbox\" style=\"height: 35px\">\
             <div style=\"width: 100px; height: 20px\"></div>\
             <div style=\"width: 100px; height: 10px\"></div>\
             <div style=\"width: 100px; height: 10px\"></div>\
             <div style=\"width: 100px; height: 20px\"></div>\
           </div>\
         </div>\
         <p style=\"clear:left\">The grey background should be 150px wide and 5px should stick out the bottom.</p>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let grey = CssColor::new(170, 170, 170);
    let grey_rects = page
        .rects()
        .iter()
        .filter(|rect| rect.fill == Some(grey))
        .collect::<Vec<_>>();
    assert_eq!(
        grey_rects.len(),
        4,
        "expected four flex container backgrounds: {:?}",
        page.rects()
    );
    for (index, (rect, (expected_width, expected_height))) in grey_rects
        .iter()
        .zip([(75.0, 45.0), (75.0, 22.5), (75.0, 45.0), (112.5, 26.25)])
        .enumerate()
    {
        assert!(
            (rect.width() - expected_width).abs() < 0.01
                && (rect.height() - expected_height).abs() < 0.01,
            "grey background {} should be {expected_width}pt by {expected_height}pt: {rect:?}",
            index + 1
        );
    }

    let last = grey_rects[3];
    assert_eq!(
        final_rect_fill_at(page, last.x() + 10.0, last.y() + 2.0),
        Some(grey),
        "fourth grey background should visibly stick out below the 30px-tall item columns: {:?}",
        page.rects()
    );
}

#[tokio::test]
async fn wrapped_row_flex_min_content_width_uses_largest_item_contribution() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 120pt; margin: 10pt } body { margin: 0 }\
         .flex { display: flex; flex-wrap: wrap; width: min-content; column-gap: 5pt; background: green }\
         .a { width: 40pt; height: 10pt } .b { width: 30pt; height: 10pt }\
         </style><div class=\"flex\"><div class=\"a\"></div><div class=\"b\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("min-content wrapped flex background should paint");
    assert!(
        (green.width() - 40.0).abs() < 0.01,
        "wrapped row min-content width should be the largest item, not the sum plus gap: {green:?}"
    );
}

#[tokio::test]
async fn floated_row_flex_min_content_caps_non_growing_item_by_flex_base() {
    let document = Html::from_string(
        "<!DOCTYPE html><style>\
         @page { size: 300px 180px; margin: 0 } body { margin: 0 }\
         #reference-overlapped-red { position: absolute; background-color: red; width: 100px; height: 100px; z-index: -1 }\
         </style>\
         <p>Test passes if there is a filled green square and <strong>no red</strong>.</p>\
         <div id=\"reference-overlapped-red\"></div>\
         <div style=\"width: 0px\">\
         <div style=\"display: flex; background: green; height: 100px; float: left\">\
         <div style=\"flex: 0 1 100px; min-width: 0px\"><div style=\"width: 200px\"></div></div>\
         </div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let green = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("floated flex container background should paint");
    assert!(
        (green.width() - 75.0).abs() < 0.01 && (green.height() - 75.0).abs() < 0.01,
        "non-growing item should cap min-content contribution at its 100px flex base: {green:?}"
    );
    assert_eq!(
        final_rect_fill_at(
            page,
            green.x() + green.width() / 2.0,
            green.y() + green.height() / 2.0
        ),
        Some(CssColor::new(0, 128, 0)),
        "green flex container should fully cover the red reference square: {:?}",
        page.rects()
    );
}

#[tokio::test]
async fn intrinsic_row_flex_automatic_minimum_clamps_after_inflexible_basis() {
    let document = Html::from_string(
        "<style>@page { size: 300px 180px; margin: 0 } body { margin: 0 }\
         .flex { display: flex; width: max-content; height: 100px; background: green }\
         .item { flex: 0 0 0px; border: 10px solid transparent }\
         .child { width: 80px }\
         </style><div class=\"flex\"><div class=\"item\"><div class=\"child\"></div></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = page_rect_with_fill(&document.pages[0], CssColor::new(0, 128, 0));
    assert!(
        (green.width() - 75.0).abs() < 0.01 && (green.height() - 75.0).abs() < 0.01,
        "the automatic minimum must floor the capped 0px flex basis at 80px content plus 20px border: {green:?}"
    );
}

#[tokio::test]
async fn intrinsic_row_flex_automatic_minimum_honors_preferred_size_suggestion() {
    let document = Html::from_string(
        "<style>@page { size: 300px 180px; margin: 0 } body { margin: 0 }\
         .flex { display: flex; width: max-content; height: 100px; background: green }\
         .item { width: 10px; flex: 0 0 0px; border: 10px solid transparent }\
         .child { width: 80px }\
         </style><div class=\"flex\"><div class=\"item\"><div class=\"child\"></div></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = page_rect_with_fill(&document.pages[0], CssColor::new(0, 128, 0));
    assert!(
        (green.width() - 22.5).abs() < 0.01 && (green.height() - 75.0).abs() < 0.01,
        "the automatic minimum must use the 10px preferred-size suggestion before adding its 20px border: {green:?}"
    );
}

#[tokio::test]
async fn nowrap_row_flex_min_content_width_keeps_all_items_on_one_line() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 120pt; margin: 10pt } body { margin: 0 }\
         .flex { display: flex; flex-wrap: nowrap; width: min-content; column-gap: 5pt; background: green }\
         .a { width: 40pt; height: 10pt } .b { width: 30pt; height: 10pt }\
         </style><div class=\"flex\"><div class=\"a\"></div><div class=\"b\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("min-content nowrap flex background should paint");
    assert!(
        (green.width() - 75.0).abs() < 0.01,
        "single-line row min-content width should include both item contributions and the gap: {green:?}"
    );
}

#[tokio::test]
async fn flex_intrinsic_width_percentage_gap_contributes_only_length_component() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 120pt; margin: 10pt } body { margin: 0 }\
         .flex { display: flex; width: max-content; column-gap: calc(10pt + 50%); background: green }\
         .item { width: 20pt; height: 10pt }\
         </style><div class=\"flex\"><div class=\"item\"></div><div class=\"item\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("max-content flex background should paint");
    assert!(
        (green.width() - 50.0).abs() < 0.01,
        "intrinsic flex width should resolve the cyclic percentage gap against zero: {green:?}"
    );
}

#[tokio::test]
async fn flex_definite_width_percentage_gap_resolves_against_content_box() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 120pt; margin: 10pt } body { margin: 0 }\
         .flex { display: flex; width: 100pt; column-gap: calc(10pt + 50%); background: green }\
         .item { flex: 0 0 auto; width: 20pt; height: 10pt }\
         .a { background: red } .b { background: blue }\
         </style><div class=\"flex\"><div class=\"item a\"></div><div class=\"item b\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let red = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
        .expect("first flex item should paint");
    let blue = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .expect("second flex item should paint");
    assert!(
        rects_have_gap_x(red, blue, 60.0),
        "definite flex content width should resolve calc(10pt + 50%) to a 60pt gap: red={red:?}, blue={blue:?}"
    );
}

#[tokio::test]
async fn flex_max_content_width_uses_growing_item_max_content_contributions() {
    let document = Html::from_string(
        "<style>@page { size: 240pt 120pt; margin: 10pt } body { margin: 0 }\
         .flex { display: flex; width: max-content; background: green }\
         .a { flex: 2 1 20pt; width: 60pt; height: 10pt }\
         .b { flex: 1 1 10pt; width: 40pt; height: 10pt }\
         </style><div class=\"flex\"><div class=\"a\"></div><div class=\"b\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("max-content flex background should paint");
    assert!(
        (green.width() - 100.0).abs() < 0.01,
        "max-content flex width should use item max-content contributions instead of the 30pt flex-base sum: {green:?}"
    );
}

#[tokio::test]
async fn visibility_collapse_keeps_cross_strut_without_painting_item() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 120pt; margin: 10pt } body { margin: 0 }\
         .row { display: flex; width: 90pt; background: black; align-items: flex-start }\
         .a { width: 20pt; height: 10pt; background: green }\
         .collapsed { visibility: collapse; width: 20pt; height: 36pt; background: red }\
         .b { width: 20pt; height: 8pt; background: blue }</style>\
         <div class=\"row\"><div class=\"a\"></div><div class=\"collapsed\"></div><div class=\"b\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    assert!(
        page.rects()
            .iter()
            .all(|rect| rect.fill != Some(CssColor::new(255, 0, 0))),
        "collapsed flex item should not paint: {:?}",
        page.rects()
    );
    let container = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::BLACK) && rect.width() >= 89.0)
        .expect("flex container background should paint");
    assert!(
        container.height() >= 35.9,
        "collapsed flex item should leave a cross-size strut: {container:?}"
    );
}

#[tokio::test]
async fn visibility_collapse_preserves_column_cross_size_strut() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 120pt; margin: 10pt } body { margin: 0 }\
         .column { display: inline-flex; flex-direction: column; background: black; align-items: flex-start }\
         .a { width: 10pt; height: 20pt; background: green }\
         .collapsed { visibility: collapse; width: 50pt; height: 20pt; background: red }\
         .b { width: 8pt; height: 20pt; background: blue }</style>\
         <div class=\"column\"><div class=\"a\"></div><div class=\"collapsed\"></div><div class=\"b\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    assert!(
        page.rects()
            .iter()
            .all(|rect| rect.fill != Some(CssColor::new(255, 0, 0))),
        "collapsed column flex item should not paint: {:?}",
        page.rects()
    );
    let container = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::BLACK))
        .expect("inline-flex container background should paint");
    assert!(
        container.width() >= 49.9,
        "collapsed column flex item should leave a cross-size strut: {container:?}"
    );
    let green = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("first flex item should paint");
    let blue = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .expect("second flex item should paint");
    assert!(
        rects_have_gap_y(green, blue, 0.0),
        "collapsed column flex item should not consume main-axis space: green={green:?}, blue={blue:?}"
    );
}

#[tokio::test]
async fn visibility_collapse_vertical_row_preserves_cross_size_strut() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 120pt; margin: 10pt } body { margin: 0 }\
         .row { display: inline-flex; writing-mode: vertical-rl; flex-direction: row; background: black; align-items: flex-start }\
         .a { width: 10pt; height: 20pt; background: green }\
         .collapsed { visibility: collapse; width: 50pt; height: 20pt; background: red }\
         .b { width: 8pt; height: 20pt; background: blue }</style>\
         <div class=\"row\"><div class=\"a\"></div><div class=\"collapsed\"></div><div class=\"b\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    assert!(
        page.rects()
            .iter()
            .all(|rect| rect.fill != Some(CssColor::new(255, 0, 0))),
        "collapsed vertical-writing flex item should not paint: {:?}",
        page.rects()
    );
    let container = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::BLACK))
        .expect("vertical-writing inline-flex container background should paint");
    assert!(
        container.width() >= 49.9,
        "collapsed vertical-writing row flex item should leave a physical cross-size strut: {container:?}"
    );
    let green = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("first vertical flex item should paint");
    let blue = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .expect("second vertical flex item should paint");
    assert!(
        rects_have_gap_y(green, blue, 0.0),
        "collapsed vertical-writing row flex item should not consume main-axis space: green={green:?}, blue={blue:?}"
    );
}

#[tokio::test]
async fn visibility_collapse_replaced_item_keeps_cross_strut_without_painting_image() {
    let image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC";
    let document = Html::from_string(format!(
        "<style>@page {{ size: 180pt 120pt; margin: 10pt }} body {{ margin: 0 }}\
         .row {{ display: flex; width: 120pt; background: black; align-items: flex-start }}\
         .a {{ width: 20pt; height: 10pt; background: green }}\
         img {{ visibility: collapse; width: 40pt; height: 50pt }}\
         .b {{ width: 20pt; height: 10pt; background: blue }}</style>\
         <div class=\"row\"><div class=\"a\"></div><img src=\"{image}\"><div class=\"b\"></div></div>",
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    assert!(
        page.images().is_empty(),
        "collapsed replaced flex item should not paint its image: {:?}",
        page.images()
    );
    let container = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::BLACK) && rect.width() >= 119.0)
        .expect("flex container background should paint");
    assert!(
        container.height() >= 49.9,
        "collapsed replaced flex item should leave a cross-size strut: {container:?}"
    );
    let green = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("first flex item should paint");
    let blue = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .expect("second flex item should paint");
    assert!(
        (blue.x() - (green.x() + green.width())).abs() < 0.1,
        "collapsed replaced flex item should not consume main-axis space: green={green:?}, blue={blue:?}"
    );
}

#[tokio::test]
async fn visibility_collapse_column_replaced_item_keeps_cross_strut_without_painting_image() {
    let image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC";
    let document = Html::from_string(format!(
        "<style>@page {{ size: 180pt 120pt; margin: 10pt }} body {{ margin: 0 }}\
         .column {{ display: inline-flex; flex-direction: column; background: black; align-items: flex-start }}\
         .a {{ width: 10pt; height: 20pt; background: green }}\
         img {{ visibility: collapse; width: 50pt; height: 20pt }}\
         .b {{ width: 8pt; height: 20pt; background: blue }}</style>\
         <div class=\"column\"><div class=\"a\"></div><img src=\"{image}\"><div class=\"b\"></div></div>",
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    assert!(
        page.images().is_empty(),
        "collapsed column replaced flex item should not paint its image: {:?}",
        page.images()
    );
    let container = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::BLACK))
        .expect("inline-flex container background should paint");
    assert!(
        container.width() >= 49.9,
        "collapsed column replaced flex item should leave a cross-size strut: {container:?}"
    );
    let green = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("first flex item should paint");
    let blue = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .expect("second flex item should paint");
    assert!(
        rects_have_gap_y(green, blue, 0.0),
        "collapsed column replaced flex item should not consume main-axis space: green={green:?}, blue={blue:?}"
    );
}

#[tokio::test]
async fn visibility_collapse_strut_reflows_wrapped_lines() {
    let document = Html::from_string(
        "<style>@page { size: 160pt 140pt; margin: 10pt } body { margin: 0 }\
         .row { display: flex; flex-wrap: wrap; align-content: flex-start; width: 50pt }\
         .item { flex: 0 0 50pt; width: 50pt; height: 10pt }\
         .a { background: green }\
         .collapsed { visibility: collapse; height: 60pt; background: red }\
         .c { background: yellow }\
         .d { background: blue }</style>\
         <div class=\"row\"><div class=\"item a\"></div><div class=\"item collapsed\"></div><div class=\"item c\"></div><div class=\"item d\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    assert!(
        page.rects()
            .iter()
            .all(|rect| rect.fill != Some(CssColor::new(255, 0, 0))),
        "collapsed flex item should not paint: {:?}",
        page.rects()
    );
    let green = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("first flex line item should paint");
    let blue = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .expect("second flex line item should paint");
    assert!(
        green.y() - blue.y() >= 65.0,
        "collapsed strut should repack later wrapped lines: green={green:?}, blue={blue:?}"
    );
}

#[tokio::test]
async fn visibility_collapse_strut_reflows_wrap_reverse_lines() {
    let document = Html::from_string(
        "<style>@page { size: 160pt 140pt; margin: 10pt } body { margin: 0 }\
         .row { display: flex; flex-wrap: wrap-reverse; align-content: flex-start; width: 50pt }\
         .item { flex: 0 0 50pt; width: 50pt; height: 10pt }\
         .a { background: green }\
         .collapsed { visibility: collapse; height: 60pt; background: red }\
         .c { background: yellow }\
         .d { background: blue }</style>\
         <div class=\"row\"><div class=\"item a\"></div><div class=\"item collapsed\"></div><div class=\"item c\"></div><div class=\"item d\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    assert!(
        page.rects()
            .iter()
            .all(|rect| rect.fill != Some(CssColor::new(255, 0, 0))),
        "collapsed flex item should not paint: {:?}",
        page.rects()
    );
    let green = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("first flex line item should paint");
    let yellow = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 255, 0)))
        .expect("strut-expanded flex line item should paint");
    let blue = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .expect("last flex line item should paint");
    let first_gap = if green.y() <= yellow.y() {
        yellow.y() - (green.y() + green.height())
    } else {
        green.y() - (yellow.y() + yellow.height())
    };
    let second_gap = if yellow.y() <= blue.y() {
        blue.y() - (yellow.y() + yellow.height())
    } else {
        yellow.y() - (blue.y() + blue.height())
    };
    assert!(
        first_gap >= 45.0 || second_gap >= 45.0,
        "wrap-reverse collapsed strut should expand one adjacent flex line gap: green={green:?}, yellow={yellow:?}, blue={blue:?}"
    );
}

#[tokio::test]
async fn baseline_aligned_row_items_share_text_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 120pt; margin: 10pt } body { margin: 0 }\
         .row { display: flex; align-items: baseline; width: 140pt }\
         .big { font-size: 30pt; line-height: 30pt }\
         .small { font-size: 10pt; line-height: 10pt }\
         p { margin: 0 }</style>\
         <div class=\"row\"><p class=\"big\">A</p><p class=\"small\">B</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let big = page
        .lines()
        .iter()
        .find(|line| line.text == "A")
        .expect("large baseline participant should render");
    let small = page
        .lines()
        .iter()
        .find(|line| line.text == "B")
        .expect("small baseline participant should render");
    assert!(
        (big.y() - small.y()).abs() < 0.01,
        "baseline-aligned flex items should share a baseline: big={big:?}, small={small:?}"
    );
}

#[tokio::test]
async fn baseline_fallback_preserves_specified_cross_size_with_negative_margin() {
    let document = Html::from_string(
        "<style>@page { size: 80px 80px; margin: 0 } body { margin: 0 }\
         .flex { align-items: baseline; background: red; display: flex; height: 40px; width: 40px }\
         .item { background: yellow; border: 1px solid black; flex: 1; height: 20px; margin-top: -4px }\
         </style><div class=\"flex\"><div class=\"item\">a</div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let flex = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
        .expect("flex container background should paint");
    let item = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 255, 0)))
        .expect("baseline-aligned flex item background should paint");
    let px = 0.75;
    assert!(
        (item.height() - 22.0 * px).abs() < 0.01,
        "the background paints the specified content box and its two border edges: {item:?}"
    );
    assert!(
        ((item.y() + item.height()) - (flex.y() + flex.height()) - 4.0 * px).abs() < 0.01,
        "baseline fallback aligns the item's margin edge at flex cross-start, so its negative cross-start margin lets the border edge extend before that edge: flex={flex:?}, item={item:?}"
    );
}

#[tokio::test]
async fn wrapped_row_align_items_baseline_preserves_line_cross_slots() {
    let document = Html::from_string(
        "<!DOCTYPE html><style>\
         @page { size: 340px 140px; margin: 0 } body { margin: 0 } p { display: none }\
         #flexbox {\
           background-color: red;\
           background-image: linear-gradient(to bottom,\
             green 0, green 16px, red 17px, red 35px,\
             green 36px, green 66px, red 67px, red 85px,\
             green 86px, green 100px);\
           align-items: baseline; display: flex; flex-flow: wrap;\
           height: 100px; width: 300px;\
         }\
         #flexbox > div {\
           background-color: green; color: green;\
           font: 20px/20px monospace; height: 40px; width: 75px;\
         }\
         #div3, #div7 { font-size: 40px; line-height: 40px }\
         </style>\
         <p>Test passes if there is no red visible on the page.</p>\
         <div id=\"flexbox\">\
           <div id=\"div1\">d1</div><div id=\"div2\">d2</div>\
           <div id=\"div3\">d3</div><div id=\"div4\">d4</div>\
           <div id=\"div5\">d5</div><div id=\"div6\">d6</div>\
           <div id=\"div7\">d7</div><div id=\"div8\">d8</div>\
         </div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let px = 0.75;
    let green = Some(CssColor::new(0, 128, 0));
    let flexbox = page
        .rects()
        .iter()
        .find(|rect| {
            (rect.width() - 300.0 * px).abs() < 0.01 && (rect.height() - 100.0 * px).abs() < 0.01
        })
        .unwrap_or_else(|| panic!("expected flex container background: {:?}", page.rects()));
    for y_px in [25.0, 75.0] {
        for x_px in [37.5, 112.5, 187.5, 262.5] {
            assert_eq!(
                final_rect_fill_at(page, flexbox.x() + x_px * px, flexbox.y() + y_px * px),
                green,
                "baseline-aligned wrapped row should cover red band sample at ({x_px}px, {y_px}px): {:?}",
                page.rects()
            );
        }
    }
}

#[tokio::test]
async fn baseline_aligned_row_items_use_block_child_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 120pt; margin: 10pt } body { margin: 0 }\
         .row { display: flex; align-items: baseline; width: 140pt; font-size: 25pt; line-height: 25pt }\
         .row * { margin: 0 }</style>\
         <div class=\"row\"><span>XX</span><div><div>YY</div></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let direct = page
        .lines()
        .iter()
        .find(|line| line.text == "XX")
        .expect("direct flex item text should render");
    let nested = page
        .lines()
        .iter()
        .find(|line| line.text == "YY")
        .expect("block-descendant flex item text should render");
    assert!(
        (direct.y() - nested.y()).abs() < 0.01,
        "baseline-aligned row flex items should use an in-flow block descendant baseline: direct={direct:?}, nested={nested:?}"
    );
}

#[tokio::test]
async fn last_baseline_aligned_row_items_use_block_child_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 220pt 160pt; margin: 10pt } body { margin: 0 }\
         .row { display: flex; align-items: last baseline; width: 180pt }\
         .row * { margin: 0 }\
         .small { font-size: 10pt; line-height: 10pt }\
         .big { font-size: 30pt; line-height: 30pt }</style>\
         <div class=\"row\"><div><div class=\"small\">Top</div><div class=\"big\">Last</div></div><span class=\"small\">Peer</span></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_last = page
        .lines()
        .iter()
        .find(|line| line.text == "Last")
        .expect("last block-descendant flex item baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "Peer")
        .expect("peer last-baseline participant should render");
    assert!(
        (nested_last.y() - peer.y()).abs() < 0.01,
        "last-baseline row flex items should use the last in-flow block descendant baseline: nested_last={nested_last:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn baseline_aligned_column_items_share_vertical_text_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .column { display: flex; flex-direction: column; align-items: baseline; width: 120pt; height: 120pt }\
         p { margin: 0; writing-mode: vertical-rl; text-orientation: mixed }\
         .wide { font-size: 30pt; line-height: 30pt; background: red }\
         .narrow { font-size: 10pt; line-height: 10pt; background: blue }</style>\
         <div class=\"column\"><p class=\"wide\">A</p><p class=\"narrow\">B</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let wide = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
        .expect("wide column-axis baseline participant should paint");
    let narrow = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .expect("narrow column-axis baseline participant should paint");
    let wide_baseline = wide.x() + wide.width() - 15.0;
    let narrow_baseline = narrow.x() + narrow.width() - 5.0;
    assert!(
        (wide_baseline - narrow_baseline).abs() < 0.01,
        "column-axis baseline sharing should align vertical text baselines: wide={wide:?}, narrow={narrow:?}"
    );
}

#[tokio::test]
async fn last_baseline_aligned_column_items_share_vertical_text_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 180pt; margin: 10pt } body { margin: 0 }\
         .column { display: flex; flex-direction: column; align-items: last baseline; width: 120pt; height: 140pt }\
         p { margin: 0; writing-mode: vertical-rl; text-orientation: mixed }\
         .wide { font-size: 30pt; line-height: 30pt; background: red }\
         .narrow { font-size: 10pt; line-height: 10pt; background: blue }</style>\
         <div class=\"column\"><p class=\"wide\">A<br>B</p><p class=\"narrow\">C<br>D</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let wide = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
        .expect("wide last-baseline participant should paint");
    let narrow = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .expect("narrow last-baseline participant should paint");
    let wide_baseline = wide.x() + wide.width() - 45.0;
    let narrow_baseline = narrow.x() + narrow.width() - 15.0;
    assert!(
        (wide_baseline - narrow_baseline).abs() < 0.01,
        "column-axis last-baseline sharing should align last vertical text baselines: wide={wide:?}, narrow={narrow:?}"
    );
}

#[tokio::test]
async fn baseline_aligned_row_items_use_nested_flex_exported_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 120pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; align-items: baseline; width: 140pt }\
         .nested { display: flex }\
         p { margin: 0 }\
         .big { font-size: 30pt; line-height: 30pt }\
         .small { font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"big\">A</p></div><p class=\"small\">B</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested = page
        .lines()
        .iter()
        .find(|line| line.text == "A")
        .expect("nested flex baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "B")
        .expect("peer baseline participant should render");
    assert!(
        (nested.y() - peer.y()).abs() < 0.01,
        "nested flex exported baseline should join the outer baseline group: nested={nested:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn baseline_aligned_row_items_use_nested_wrapped_flex_first_line_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; align-items: baseline; width: 140pt }\
         .nested { display: flex; flex-wrap: wrap; width: 40pt }\
         .item { flex: 0 0 40pt; margin: 0 }\
         p { margin: 0 }\
         .small { font-size: 10pt; line-height: 10pt }\
         .big { font-size: 30pt; line-height: 30pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item small\">A</p><p class=\"item big\">B</p></div><p class=\"small\">C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_first = page
        .lines()
        .iter()
        .find(|line| line.text == "A")
        .expect("nested wrapped flex first baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer baseline participant should render");
    assert!(
        (nested_first.y() - peer.y()).abs() < 0.01,
        "nested wrapped flex first exported baseline should come from its first line: nested_first={nested_first:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn baseline_aligned_row_items_use_nested_row_reverse_wrapped_startmost_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 200pt 180pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; align-items: baseline; width: 160pt }\
         .nested { display: flex; flex-direction: row-reverse; flex-wrap: wrap; width: 60pt }\
         .item { flex: 0 0 30pt; margin: 0 }\
         p { margin: 0 }\
         .small { font-size: 10pt; line-height: 10pt }\
         .big { font-size: 30pt; line-height: 30pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item small\">A</p><p class=\"item big\">B</p><p class=\"item small\">D</p><p class=\"item small\">E</p></div><p class=\"small\">C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_startmost = page
        .lines()
        .iter()
        .find(|line| line.text == "A")
        .expect("nested row-reverse first-line startmost baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer baseline participant should render");
    assert!(
        (nested_startmost.y() - peer.y()).abs() < 0.01,
        "nested row-reverse exported first baseline should come from the first line's startmost item: nested_startmost={nested_startmost:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn baseline_aligned_row_items_use_nested_wrap_reverse_startmost_line_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 200pt 180pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; align-items: baseline; width: 160pt }\
         .nested { display: flex; flex-wrap: wrap-reverse; width: 40pt }\
         .item { flex: 0 0 40pt; margin: 0 }\
         p { margin: 0 }\
         .small { font-size: 10pt; line-height: 10pt }\
         .big { font-size: 30pt; line-height: 30pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item small\">A</p><p class=\"item big\">B</p></div><p class=\"small\">C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_startmost = page
        .lines()
        .iter()
        .find(|line| line.text == "B")
        .expect("nested wrap-reverse startmost line baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer baseline participant should render");
    assert!(
        (nested_startmost.y() - peer.y()).abs() < 0.01,
        "nested wrap-reverse exported first baseline should come from the cross-startmost line: nested_startmost={nested_startmost:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn baseline_aligned_row_items_use_nested_max_width_wrapped_first_line_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 200pt 180pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; align-items: baseline; width: 160pt }\
         .nested { display: flex; flex-wrap: wrap; max-width: 40pt }\
         .item { flex: 0 0 40pt; margin: 0 }\
         p { margin: 0 }\
         .small { font-size: 10pt; line-height: 10pt }\
         .big { font-size: 30pt; line-height: 30pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item small\">A</p><p class=\"item big\">B</p></div><p class=\"small\">C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_first = page
        .lines()
        .iter()
        .find(|line| line.text == "A")
        .expect("nested max-width wrapped first baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer baseline participant should render");
    assert!(
        (nested_first.y() - peer.y()).abs() < 0.01,
        "max-width-constrained nested flex should export the first wrapped line baseline: nested_first={nested_first:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn baseline_aligned_row_items_use_nested_fit_content_wrapped_first_line_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 200pt 180pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; align-items: baseline; width: 160pt }\
         .nested { display: flex; flex-wrap: wrap; width: fit-content(40pt) }\
         .item { flex: 0 0 40pt; margin: 0 }\
         p { margin: 0 }\
         .small { font-size: 10pt; line-height: 10pt }\
         .big { font-size: 30pt; line-height: 30pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item small\">A</p><p class=\"item big\">B</p></div><p class=\"small\">C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_first = page
        .lines()
        .iter()
        .find(|line| line.text == "A")
        .expect("nested fit-content wrapped first baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer baseline participant should render");
    assert!(
        (nested_first.y() - peer.y()).abs() < 0.01,
        "fit-content-constrained nested flex should export the first wrapped line baseline: nested_first={nested_first:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn last_baseline_aligned_row_items_use_nested_flex_exported_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 120pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; align-items: last baseline; width: 140pt }\
         .nested { display: flex }\
         p { margin: 0 }\
         .two { font-size: 10pt; line-height: 10pt }\
         .big { font-size: 30pt; line-height: 30pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"two\">A<br>B</p></div><p class=\"big\">C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_last = page
        .lines()
        .iter()
        .find(|line| line.text == "B")
        .expect("nested flex last baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer last baseline participant should render");
    assert!(
        (nested_last.y() - peer.y()).abs() < 0.01,
        "nested flex exported last baseline should join the outer baseline group: nested_last={nested_last:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn last_baseline_aligned_row_items_use_nested_fit_content_wrapped_last_line_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 200pt 180pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; align-items: last baseline; width: 160pt }\
         .nested { display: flex; flex-wrap: wrap; width: fit-content(40pt) }\
         .item { flex: 0 0 40pt; margin: 0 }\
         p { margin: 0 }\
         .big { font-size: 30pt; line-height: 30pt }\
         .small { font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item big\">A</p><p class=\"item small\">B</p></div><p class=\"small\">C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_last = page
        .lines()
        .iter()
        .find(|line| line.text == "B")
        .expect("nested fit-content wrapped last baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer last baseline participant should render");
    assert!(
        (nested_last.y() - peer.y()).abs() < 0.01,
        "fit-content-constrained nested flex should export the last wrapped line baseline: nested_last={nested_last:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn last_baseline_aligned_row_items_use_nested_max_content_gap_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 220pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; align-items: last baseline; width: 180pt }\
         .nested { display: flex; flex-wrap: wrap; width: max-content; column-gap: 10pt }\
         .item { flex: 0 0 40pt; margin: 0 }\
         p { margin: 0 }\
         .big { font-size: 30pt; line-height: 30pt }\
         .small { font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item big\">A</p><p class=\"item small\">B</p></div><p class=\"small\">C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_endmost = page
        .lines()
        .iter()
        .find(|line| line.text == "B")
        .expect("nested max-content gap baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer last baseline participant should render");
    assert!(
        (nested_endmost.y() - peer.y()).abs() < 0.01,
        "max-content nested flex should include main-axis gaps when exporting the same-line last baseline: nested_endmost={nested_endmost:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn last_baseline_aligned_row_items_use_nested_max_width_wrapped_last_line_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 200pt 180pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; align-items: last baseline; width: 160pt }\
         .nested { display: flex; flex-wrap: wrap; max-width: 40pt }\
         .item { flex: 0 0 40pt; margin: 0 }\
         p { margin: 0 }\
         .big { font-size: 30pt; line-height: 30pt }\
         .small { font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item big\">A</p><p class=\"item small\">B</p></div><p class=\"small\">C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_last = page
        .lines()
        .iter()
        .find(|line| line.text == "B")
        .expect("nested max-width wrapped last baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer last baseline participant should render");
    assert!(
        (nested_last.y() - peer.y()).abs() < 0.01,
        "max-width-constrained nested flex should export the last wrapped line baseline: nested_last={nested_last:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn last_baseline_aligned_row_items_use_nested_wrap_reverse_endmost_line_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 200pt 180pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; align-items: last baseline; width: 160pt }\
         .nested { display: flex; flex-wrap: wrap-reverse; width: 40pt }\
         .item { flex: 0 0 40pt; margin: 0 }\
         p { margin: 0 }\
         .big { font-size: 30pt; line-height: 30pt }\
         .small { font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item small\">A</p><p class=\"item small\">B</p></div><p class=\"small\">C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_endmost = page
        .lines()
        .iter()
        .find(|line| line.text == "A")
        .expect("nested wrap-reverse endmost line baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer last baseline participant should render");
    assert!(
        (nested_endmost.y() - peer.y()).abs() < 0.01,
        "nested wrap-reverse exported last baseline should come from the cross-endmost line: nested_endmost={nested_endmost:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn last_baseline_aligned_row_items_use_nested_row_reverse_wrapped_endmost_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 200pt 180pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; align-items: last baseline; width: 160pt }\
         .nested { display: flex; flex-direction: row-reverse; flex-wrap: wrap; width: 60pt }\
         .item { flex: 0 0 30pt; margin: 0 }\
         p { margin: 0 }\
         .small { font-size: 10pt; line-height: 10pt }\
         .big { font-size: 30pt; line-height: 30pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item small\">A</p><p class=\"item small\">B</p><p class=\"item big\">D</p><p class=\"item small\">E</p></div><p class=\"small\">C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_endmost = page
        .lines()
        .iter()
        .find(|line| line.text == "E")
        .expect("nested row-reverse last-line endmost baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer last baseline participant should render");
    assert!(
        (nested_endmost.y() - peer.y()).abs() < 0.01,
        "nested row-reverse exported last baseline should come from the last line's endmost item: nested_endmost={nested_endmost:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn last_baseline_aligned_row_items_use_nested_wrapped_flex_last_line_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; align-items: last baseline; width: 140pt }\
         .nested { display: flex; flex-wrap: wrap; width: 40pt }\
         .item { flex: 0 0 40pt; margin: 0 }\
         p { margin: 0 }\
         .big { font-size: 30pt; line-height: 30pt }\
         .small { font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item big\">A</p><p class=\"item small\">B</p></div><p class=\"small\">C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_last = page
        .lines()
        .iter()
        .find(|line| line.text == "B")
        .expect("nested wrapped flex last baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer last baseline participant should render");
    assert!(
        (nested_last.y() - peer.y()).abs() < 0.01,
        "nested wrapped flex last exported baseline should come from its last line: nested_last={nested_last:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn baseline_aligned_vertical_row_items_use_nested_vertical_flex_exported_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; flex-direction: row; align-items: baseline; writing-mode: vertical-lr;\
                  width: 120pt; height: 80pt }\
         .nested { display: flex; flex-direction: row; flex-wrap: wrap; writing-mode: vertical-lr;\
                   width: 80pt; height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0 }\
         p { margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item\">A</p><p class=\"item\">B</p></div><p>C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_first = page
        .lines()
        .iter()
        .find(|line| line.text == "A")
        .expect("nested vertical first baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer vertical baseline participant should render");
    assert!(
        (nested_first.x() - peer.x()).abs() < 0.01,
        "nested vertical flex exported first horizontal baseline should join the outer group: nested_first={nested_first:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn last_baseline_aligned_vertical_row_items_use_nested_vertical_flex_exported_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; flex-direction: row; align-items: last baseline; writing-mode: vertical-lr;\
                  width: 120pt; height: 80pt }\
         .nested { display: flex; flex-direction: row; flex-wrap: wrap; writing-mode: vertical-lr;\
                   width: 80pt; height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0 }\
         p { margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item\">A</p><p class=\"item\">B</p></div><p>C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_last = page
        .lines()
        .iter()
        .find(|line| line.text == "B")
        .expect("nested vertical last baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer vertical last baseline participant should render");
    assert!(
        (nested_last.x() - peer.x()).abs() < 0.01,
        "nested vertical flex exported last horizontal baseline should join the outer group: nested_last={nested_last:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn baseline_aligned_vertical_row_items_use_auto_width_nested_vertical_exported_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; flex-direction: row; align-items: baseline; writing-mode: vertical-lr;\
                  width: 120pt; height: 80pt }\
         .nested { display: flex; flex-direction: row; flex-wrap: wrap; writing-mode: vertical-lr;\
                   height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0 }\
         p { margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item\">A</p><p class=\"item\">B</p></div><p>C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_first = page
        .lines()
        .iter()
        .find(|line| line.text == "A")
        .expect("auto-width nested vertical first baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer vertical first baseline participant should render");
    assert!(
        (nested_first.x() - peer.x()).abs() < 0.01,
        "auto-width nested vertical flex exported first horizontal baseline should join the outer group: nested_first={nested_first:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn last_baseline_aligned_vertical_row_items_use_auto_width_nested_vertical_exported_baseline()
{
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; flex-direction: row; align-items: last baseline; writing-mode: vertical-lr;\
                  width: 120pt; height: 80pt }\
         .nested { display: flex; flex-direction: row; flex-wrap: wrap; writing-mode: vertical-lr;\
                   height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0 }\
         p { margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item\">A</p><p class=\"item\">B</p></div><p>C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_last = page
        .lines()
        .iter()
        .find(|line| line.text == "B")
        .expect("auto-width nested vertical last baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer vertical last baseline participant should render");
    assert!(
        (nested_last.x() - peer.x()).abs() < 0.01,
        "auto-width nested vertical flex exported last horizontal baseline should join the outer group: nested_last={nested_last:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn baseline_aligned_vertical_row_items_use_nested_wrap_reverse_exported_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; flex-direction: row; align-items: baseline; writing-mode: vertical-lr;\
                  width: 120pt; height: 80pt }\
         .nested { display: flex; flex-direction: row; flex-wrap: wrap-reverse; writing-mode: vertical-lr;\
                   width: 80pt; height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0 }\
         p { margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item\">A</p><p class=\"item\">B</p></div><p>C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_first = page
        .lines()
        .iter()
        .find(|line| line.text == "B")
        .expect("nested vertical wrap-reverse first baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer vertical first baseline participant should render");
    assert!(
        (nested_first.x() - peer.x()).abs() < 0.01,
        "nested vertical wrap-reverse flex exported first horizontal baseline should join the outer group: nested_first={nested_first:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn last_baseline_aligned_vertical_row_items_use_nested_wrap_reverse_exported_baseline() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; flex-direction: row; align-items: last baseline; writing-mode: vertical-lr;\
                  width: 120pt; height: 80pt }\
         .nested { display: flex; flex-direction: row; flex-wrap: wrap-reverse; writing-mode: vertical-lr;\
                   width: 80pt; height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0 }\
         p { margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item\">A</p><p class=\"item\">B</p></div><p>C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_last = page
        .lines()
        .iter()
        .find(|line| line.text == "A")
        .expect("nested vertical wrap-reverse last baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer vertical last baseline participant should render");
    assert!(
        (nested_last.x() - peer.x()).abs() < 0.01,
        "nested vertical wrap-reverse flex exported last horizontal baseline should join the outer group: nested_last={nested_last:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn baseline_aligned_vertical_row_items_use_auto_width_nested_wrap_reverse_exported_baseline()
{
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; flex-direction: row; align-items: baseline; writing-mode: vertical-lr;\
                  width: 120pt; height: 80pt }\
         .nested { display: flex; flex-direction: row; flex-wrap: wrap-reverse; writing-mode: vertical-lr;\
                   height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0 }\
         p { margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item\">A</p><p class=\"item\">B</p></div><p>C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_first =
        page.lines().iter().find(|line| line.text == "B").expect(
            "auto-width nested vertical wrap-reverse first baseline participant should render",
        );
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer vertical first baseline participant should render");
    assert!(
        (nested_first.x() - peer.x()).abs() < 0.01,
        "auto-width nested vertical wrap-reverse flex exported first horizontal baseline should join the outer group: nested_first={nested_first:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn last_baseline_aligned_vertical_row_items_use_auto_width_nested_wrap_reverse_exported_baseline()
 {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; flex-direction: row; align-items: last baseline; writing-mode: vertical-lr;\
                  width: 120pt; height: 80pt }\
         .nested { display: flex; flex-direction: row; flex-wrap: wrap-reverse; writing-mode: vertical-lr;\
                   height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0 }\
         p { margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item\">A</p><p class=\"item\">B</p></div><p>C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_last =
        page.lines().iter().find(|line| line.text == "A").expect(
            "auto-width nested vertical wrap-reverse last baseline participant should render",
        );
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer vertical last baseline participant should render");
    assert!(
        (nested_last.x() - peer.x()).abs() < 0.01,
        "auto-width nested vertical wrap-reverse flex exported last horizontal baseline should join the outer group: nested_last={nested_last:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn baseline_aligned_vertical_row_items_use_percentage_width_nested_vertical_exported_baseline()
 {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; flex-direction: row; align-items: baseline; writing-mode: vertical-lr;\
                  width: 120pt; height: 80pt }\
         .nested { display: flex; flex-direction: row; flex-wrap: wrap; writing-mode: vertical-lr;\
                   width: 50%; height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0 }\
         p { margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item\">A</p><p class=\"item\">B</p></div><p>C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_first = page
        .lines()
        .iter()
        .find(|line| line.text == "A")
        .expect("percentage-width nested vertical first baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer vertical first baseline participant should render");
    assert!(
        (nested_first.x() - peer.x()).abs() < 0.01,
        "percentage-width nested vertical flex exported first horizontal baseline should join the outer group: nested_first={nested_first:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn last_baseline_aligned_vertical_row_items_use_percentage_width_nested_vertical_exported_baseline()
 {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; flex-direction: row; align-items: last baseline; writing-mode: vertical-lr;\
                  width: 120pt; height: 80pt }\
         .nested { display: flex; flex-direction: row; flex-wrap: wrap; writing-mode: vertical-lr;\
                   width: 50%; height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0 }\
         p { margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item\">A</p><p class=\"item\">B</p></div><p>C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_last = page
        .lines()
        .iter()
        .find(|line| line.text == "B")
        .expect("percentage-width nested vertical last baseline participant should render");
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer vertical last baseline participant should render");
    assert!(
        (nested_last.x() - peer.x()).abs() < 0.01,
        "percentage-width nested vertical flex exported last horizontal baseline should join the outer group: nested_last={nested_last:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn baseline_aligned_vertical_row_items_use_indefinite_percentage_width_nested_vertical_exported_baseline()
 {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: inline-flex; flex-direction: row; align-items: baseline; writing-mode: vertical-lr;\
                  height: 80pt }\
         .nested { display: flex; flex-direction: row; flex-wrap: wrap; writing-mode: vertical-lr;\
                   width: 50%; height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0 }\
         p { margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item\">A</p><p class=\"item\">B</p></div><p>C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_first = page.lines().iter().find(|line| line.text == "A").expect(
        "indefinite percentage-width nested vertical first baseline participant should render",
    );
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer vertical first baseline participant should render");
    assert!(
        (nested_first.x() - peer.x()).abs() < 0.01,
        "indefinite percentage-width nested vertical flex exported first horizontal baseline should join the outer group: nested_first={nested_first:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn last_baseline_aligned_vertical_row_items_use_indefinite_percentage_width_nested_vertical_exported_baseline()
 {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: inline-flex; flex-direction: row; align-items: last baseline; writing-mode: vertical-lr;\
                  height: 80pt }\
         .nested { display: flex; flex-direction: row; flex-wrap: wrap; writing-mode: vertical-lr;\
                   width: 50%; height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0 }\
         p { margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item\">A</p><p class=\"item\">B</p></div><p>C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_last = page.lines().iter().find(|line| line.text == "B").expect(
        "indefinite percentage-width nested vertical last baseline participant should render",
    );
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer vertical last baseline participant should render");
    assert!(
        (nested_last.x() - peer.x()).abs() < 0.01,
        "indefinite percentage-width nested vertical flex exported last horizontal baseline should join the outer group: nested_last={nested_last:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn baseline_aligned_vertical_row_items_use_indefinite_percentage_width_nested_wrap_reverse_exported_baseline()
 {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: inline-flex; flex-direction: row; align-items: baseline; writing-mode: vertical-lr;\
                  height: 80pt }\
         .nested { display: flex; flex-direction: row; flex-wrap: wrap-reverse; writing-mode: vertical-lr;\
                   width: 50%; height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0 }\
         p { margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item\">A</p><p class=\"item\">B</p></div><p>C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_first = page.lines().iter().find(|line| line.text == "B").expect(
        "indefinite percentage-width nested vertical wrap-reverse first baseline participant should render",
    );
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer vertical first baseline participant should render");
    assert!(
        (nested_first.x() - peer.x()).abs() < 0.01,
        "indefinite percentage-width nested vertical wrap-reverse flex exported first horizontal baseline should join the outer group: nested_first={nested_first:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn last_baseline_aligned_vertical_row_items_use_indefinite_percentage_width_nested_wrap_reverse_exported_baseline()
 {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: inline-flex; flex-direction: row; align-items: last baseline; writing-mode: vertical-lr;\
                  height: 80pt }\
         .nested { display: flex; flex-direction: row; flex-wrap: wrap-reverse; writing-mode: vertical-lr;\
                   width: 50%; height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0 }\
         p { margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item\">A</p><p class=\"item\">B</p></div><p>C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_last = page.lines().iter().find(|line| line.text == "A").expect(
        "indefinite percentage-width nested vertical wrap-reverse last baseline participant should render",
    );
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer vertical last baseline participant should render");
    assert!(
        (nested_last.x() - peer.x()).abs() < 0.01,
        "indefinite percentage-width nested vertical wrap-reverse flex exported last horizontal baseline should join the outer group: nested_last={nested_last:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn baseline_aligned_vertical_row_items_use_percentage_width_nested_wrap_reverse_exported_baseline()
 {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; flex-direction: row; align-items: baseline; writing-mode: vertical-lr;\
                  width: 120pt; height: 80pt }\
         .nested { display: flex; flex-direction: row; flex-wrap: wrap-reverse; writing-mode: vertical-lr;\
                   width: 50%; height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0 }\
         p { margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item\">A</p><p class=\"item\">B</p></div><p>C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_first = page.lines().iter().find(|line| line.text == "B").expect(
        "percentage-width nested vertical wrap-reverse first baseline participant should render",
    );
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer vertical first baseline participant should render");
    assert!(
        (nested_first.x() - peer.x()).abs() < 0.01,
        "percentage-width nested vertical wrap-reverse flex exported first horizontal baseline should join the outer group: nested_first={nested_first:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn last_baseline_aligned_vertical_row_items_use_percentage_width_nested_wrap_reverse_exported_baseline()
 {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .outer { display: flex; flex-direction: row; align-items: last baseline; writing-mode: vertical-lr;\
                  width: 120pt; height: 80pt }\
         .nested { display: flex; flex-direction: row; flex-wrap: wrap-reverse; writing-mode: vertical-lr;\
                   width: 50%; height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0 }\
         p { margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"outer\"><div class=\"nested\"><p class=\"item\">A</p><p class=\"item\">B</p></div><p>C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let nested_last = page.lines().iter().find(|line| line.text == "A").expect(
        "percentage-width nested vertical wrap-reverse last baseline participant should render",
    );
    let peer = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("peer vertical last baseline participant should render");
    assert!(
        (nested_last.x() - peer.x()).abs() < 0.01,
        "percentage-width nested vertical wrap-reverse flex exported last horizontal baseline should join the outer group: nested_last={nested_last:?}, peer={peer:?}"
    );
}

#[tokio::test]
async fn align_content_baseline_packs_wrapped_row_line_baselines() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .row { display: flex; flex-wrap: wrap; align-content: baseline; width: 60pt; height: 120pt }\
         .item { flex: 0 0 60pt; margin: 0 }\
         .big { font-size: 30pt; line-height: 30pt }\
         .small { font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"row\"><p class=\"item big\">A</p><p class=\"item small\">B</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let big = page
        .lines()
        .iter()
        .find(|line| line.text == "A")
        .expect("first flex line should render");
    let small = page
        .lines()
        .iter()
        .find(|line| line.text == "B")
        .expect("second flex line should render");
    assert!(
        (big.y() - small.y()).abs() < 0.01,
        "align-content: baseline should align wrapped line baselines: big={big:?}, small={small:?}"
    );
}

#[tokio::test]
async fn vertical_row_align_content_baseline_packs_wrapped_line_baselines() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .row { display: flex; flex-direction: row; flex-wrap: wrap; writing-mode: vertical-lr;\
                align-content: baseline; width: 80pt; height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"row\"><p class=\"item\">A</p><p class=\"item\">B</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let first = page
        .lines()
        .iter()
        .find(|line| line.text == "A")
        .expect("first vertical flex line should render");
    let second = page
        .lines()
        .iter()
        .find(|line| line.text == "B")
        .expect("second vertical flex line should render");

    assert!(
        (first.x() - second.x()).abs() < 0.01,
        "vertical align-content:baseline should align wrapped line x baselines: first={first:?}, second={second:?}"
    );
}

#[tokio::test]
async fn vertical_row_align_content_last_baseline_packs_wrapped_line_baselines() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .row { display: flex; flex-direction: row; flex-wrap: wrap; writing-mode: vertical-lr;\
                align-content: last baseline; width: 80pt; height: 40pt }\
         .item { flex: 0 0 40pt; width: 20pt; margin: 0; font-size: 10pt; line-height: 10pt }</style>\
         <div class=\"row\"><p class=\"item\">A</p><p class=\"item\">B</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let first = page
        .lines()
        .iter()
        .find(|line| line.text == "A")
        .expect("first vertical flex line should render");
    let second = page
        .lines()
        .iter()
        .find(|line| line.text == "B")
        .expect("second vertical flex line should render");

    assert!(
        (first.x() - second.x()).abs() < 0.01,
        "vertical align-content:last baseline should align wrapped line x baselines: first={first:?}, second={second:?}"
    );
}

#[tokio::test]
async fn align_content_last_baseline_packs_wrapped_row_line_baselines() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 160pt; margin: 10pt } body { margin: 0 }\
         .row { display: flex; flex-wrap: wrap; align-content: last baseline; width: 60pt; height: 120pt }\
         .item { flex: 0 0 60pt; margin: 0 }\
         .two { font-size: 10pt; line-height: 10pt }\
         .big { font-size: 30pt; line-height: 30pt }</style>\
         <div class=\"row\"><p class=\"item two\">A<br>B</p><p class=\"item big\">C</p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let first_last = page
        .lines()
        .iter()
        .find(|line| line.text == "B")
        .expect("last baseline of first flex line should render");
    let second = page
        .lines()
        .iter()
        .find(|line| line.text == "C")
        .expect("second flex line should render");
    assert!(
        (first_last.y() - second.y()).abs() < 0.01,
        "align-content: last baseline should align wrapped line last baselines: first_last={first_last:?}, second={second:?}"
    );
}

#[tokio::test]
async fn column_flex_align_content_last_baseline_uses_safe_end_fallback() {
    let document = Html::from_string(
        "<style>@page { size: 160pt 120pt; margin: 10pt } body { margin: 0 }\
         .flex { display: flex; flex-direction: column; flex-wrap: wrap; align-items: flex-start; align-content: last baseline; width: 100pt; height: 60pt; background: red }\
         .item { width: 20pt; height: 30pt; background: green }</style>\
         <div class=\"flex\"><div class=\"item\"></div><div class=\"item\"></div><div class=\"item\"></div><div class=\"item\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let red = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
        .expect("flex container background should paint");
    let first_green = page
        .rects()
        .iter()
        .filter(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .min_by(|left, right| left.x().total_cmp(&right.x()))
        .expect("flex item backgrounds should paint");

    assert!(
        (first_green.x() - red.x() - 60.0).abs() < 0.01,
        "column flex align-content:last baseline should fall back to safe cross-end packing: red={red:?}, first_green={first_green:?}"
    );
}

#[tokio::test]
async fn abspos_flex_child_static_position_uses_flex_alignment() {
    let document = Html::from_string(
        "<style>@page { size: 160pt 120pt; margin: 10pt } body { margin: 0 }\
         .container { position: relative; display: flex; justify-content: center; align-items: center; width: 100pt; height: 40pt }\
         .abs { position: absolute; width: 20pt; height: 10pt; background: red }</style>\
         <div class=\"container\"><div class=\"abs\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let red = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
        .expect("absolutely positioned flex child should paint");
    assert!(
        (red.x() - 50.0).abs() < 0.5,
        "static position should honor main-axis flex centering: {red:?}"
    );
}

#[tokio::test]
async fn abspos_flex_static_alignment_consumes_fixed_margins_once() {
    let document = Html::from_string(
        "<style>@page { size: 100pt 100pt; margin: 0 } body { margin: 0 }\
         .container { position: relative; display: flex; justify-content: flex-end; align-items: flex-end; width: 20pt; height: 14pt; padding: 1pt 2pt; border: 1pt solid black }\
         .abs { position: absolute; width: 8pt; height: 6pt }\
         .fixed { margin: 1pt 2pt 3pt 4pt; background: red }\
         .auto { margin: auto; background: green }</style>\
         <div class=\"container\"><div class=\"abs fixed\"></div><div class=\"abs auto\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let red = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
        .expect("fixed-margin absolutely positioned flex child should paint");
    let green = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("auto-margin absolutely positioned flex child should paint");

    assert!(
        (red.x() - 13.0).abs() < 0.01 && (red.y() - 87.0).abs() < 0.01,
        "fixed margins must be consumed once from the flex static rectangle: {red:?}"
    );
    assert!(
        (green.x() - 15.0).abs() < 0.01 && (green.y() - 84.0).abs() < 0.01,
        "auto margins must be zero for the flex static-position probe: {green:?}"
    );
}

#[tokio::test]
async fn inline_source_abspos_flex_child_uses_flex_static_rect_for_auto_horizontal_insets() {
    let document = Html::from_string(
        "<style>@page { size: 160pt 120pt; margin: 10pt } body { margin: 0 }\
         .container { position: relative; display: flex; justify-content: center; align-items: center; width: 100pt; height: 40pt }\
         .ref, .abs { position: absolute; width: 20pt; height: 10pt }\
         .ref { background: red } .abs { background: green }</style>\
         <div class=\"container\"><div class=\"ref\"></div><span class=\"abs\"></span></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let red = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
        .expect("block-source absolutely positioned flex child should paint");
    let green = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("inline-source absolutely positioned flex child should paint");
    assert!(
        (green.x() - red.x()).abs() < 0.01,
        "inline-source abspos flex child should share the block-source flex static x: red={red:?}, green={green:?}"
    );
}

#[tokio::test]
async fn display_contents_inline_flex_item_normalizes_mixed_flow_children() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 100pt; margin: 10pt } body { margin: 0; font: 12pt/1 serif }\
         .flex { display: flex } .contents { display: contents } .inline { display: inline }</style>\
         <div class=\"flex\"><div class=\"contents\"><div class=\"inline\">2a<div>2</div></div></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    assert!(
        page.lines().iter().any(|line| line.text == "2a"),
        "leading inline text in a blockified flex item should render: {:?}",
        page.lines()
    );
    assert!(
        page.lines().iter().any(|line| line.text == "2"),
        "block descendant in the same flex item should still render: {:?}",
        page.lines()
    );
}

#[tokio::test]
async fn display_contents_children_participate_as_flex_items() {
    let document = Html::from_string(
        "<style>@page { size: 160pt 100pt; margin: 10pt } body { margin: 0 }\
         .row { display: flex; width: 90pt }\
         .contents { display: contents }\
         .item { display: block; width: 20pt; height: 10pt }\
         .a { background: green }\
         .b { background: blue }\
         .c { background: yellow }</style>\
         <div class=\"row\"><span class=\"contents\"><span class=\"item a\"></span><span class=\"item b\"></span></span><span class=\"item c\"></span></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let green = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("first display: contents child should paint");
    let blue = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .expect("second display: contents child should paint");
    let yellow = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 255, 0)))
        .expect("following flex item should paint");
    assert!(
        (green.x() - 10.0).abs() < 0.5
            && (blue.x() - 30.0).abs() < 0.5
            && (yellow.x() - 50.0).abs() < 0.5,
        "display: contents children should be direct flex items: green={green:?}, blue={blue:?}, yellow={yellow:?}"
    );
}

#[tokio::test]
async fn display_contents_wpt_flex_direct_contents_children_match_reference_paint() {
    let document = Html::from_string(format!(
        "<style>@page {{ size: 500pt 120pt; margin: 10pt }} {DISPLAY_CONTENTS_FLEX_ACID_CSS}</style>\
         <div class=\"flex c1\">\
           0\
           <div class=\"contents c1\">x</div>\
           <div class=\"contents c1\"><div class=\"contents c2\">y</div></div>\
           <div class=\"contents c1\"><div class=\"contents c2\"><div>1<span class=\"b\">1</span></div></div></div>\
           <div class=\"contents c2\"><div class=\"inline\">2a<div>2<div class=\"contents c2\">b<span class=\"b\">b</span></div></div></div></div>\
           <div class=\"contents c3\"><div class=\"inline\">3</div></div>\
           <div class=\"inline\"><div class=\"contents c4\">4</div></div>\
           <div><div class=\"contents c5\">5a</div></div>\
           <div class=\"c5\">5b</div>\
           <div class=\"contents c6\"><div>6</div></div>\
           <div class=\"ib\"><div class=\"contents c7\"><div class=\"contents c2\">7<span class=\"b\">a</span></div></div></div>\
           <div class=\"contents c9\"><div>8</div></div>\
           <div class=\"contents c9\"><div class=\"contents\">9<div class=\"contents c2\">a<span class=\"b\">b</span>c</div></div></div>\
           <div class=\"contents c10\"><div>10</div></div>\
         </div>",
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_display_contents_wpt_flex_output(&document);
}

#[tokio::test]
async fn display_contents_wpt_flex_single_contents_child_match_reference_paint() {
    let document = Html::from_string(format!(
        "<style>@page {{ size: 500pt 120pt; margin: 10pt }} {DISPLAY_CONTENTS_FLEX_ACID_CSS}</style>\
         <div class=\"flex\"><div class=\"contents c1\">\
           0\
           <div class=\"contents c1\">x</div>\
           <div class=\"contents c1\"><div class=\"contents c2\">y</div></div>\
           <div class=\"contents c1\"><div class=\"contents c2\"><div>1<span class=\"b\">1</span></div></div></div>\
           <div class=\"contents c2\"><div class=\"inline\">2a<div>2<div class=\"contents c2\">b<span class=\"b\">b</span></div></div></div></div>\
           <div class=\"contents c3\"><div class=\"inline\">3</div></div>\
           <div><div class=\"contents c4\">4</div></div>\
           <div><div class=\"contents c5\">5a</div></div>\
           <div class=\"c5\">5b</div>\
           <div class=\"contents c6\"><div>6</div></div>\
           <div class=\"ib\"><div class=\"contents c7\"><div class=\"contents c2\">7<span class=\"b\">a</span></div></div></div>\
           <div class=\"contents c9\"><div>8</div></div>\
           <div class=\"contents c9\"><div class=\"contents\">9<div class=\"contents c2\">a<span class=\"b\">b</span>c</div></div></div>\
           <div class=\"contents c10\"><div>10</div></div>\
         </div></div>",
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_display_contents_wpt_flex_output(&document);
}

fn assert_display_contents_wpt_flex_output(document: &spindrift::Document) {
    let page = &document.pages[0];
    for text in ["0x", "y", "2a", "3", "4", "5a", "5b", "6", "8", "10"] {
        assert!(
            page.lines().iter().any(|line| line.text == text),
            "expected rendered text {text:?}: {:?}",
            page.lines()
        );
    }
    let line_2bb = rendered_line(page, "2bb");
    assert_blue_at_text_position(page, line_2bb, glyph_center_x(line_2bb, 2));
    assert_no_blue_at_text_position(page, line_2bb, glyph_center_x(line_2bb, 1));

    let line_7a = rendered_line(page, "7a");
    assert_blue_at_text_position(page, line_7a, glyph_center_x(line_7a, 1));
    assert_no_blue_at_text_position(page, line_7a, glyph_center_x(line_7a, 0));

    let line_b = rendered_line(page, "b");
    assert_blue_at_text_position(page, line_b, glyph_center_x(line_b, 0));
    assert_no_blue_at_text_position(
        page,
        rendered_line(page, "y"),
        glyph_center_x(rendered_line(page, "y"), 0),
    );
    assert_no_blue_at_text_position(
        page,
        rendered_line(page, "a"),
        glyph_center_x(rendered_line(page, "a"), 0),
    );
    assert_no_blue_at_text_position(
        page,
        rendered_line(page, "c"),
        glyph_center_x(rendered_line(page, "c"), 0),
    );
}

fn rendered_line<'a>(
    page: &'a spindrift::Page,
    text: &str,
) -> &'a crate::document::paint::text::RenderedLine {
    page.lines()
        .iter()
        .find(|line| line.text == text)
        .unwrap_or_else(|| panic!("expected rendered text {text:?}: {:?}", page.lines()))
}

fn glyph_start_x(line: &crate::document::paint::text::RenderedLine, index: usize) -> f32 {
    let run = line
        .runs
        .first()
        .unwrap_or_else(|| panic!("expected text run for {line:?}"));
    let glyphs = run
        .glyphs
        .as_ref()
        .unwrap_or_else(|| panic!("expected glyph advances for {line:?}"));
    line.x()
        + run.x_offset
        + glyphs
            .iter()
            .take(index)
            .map(|glyph| glyph.x_advance)
            .sum::<f32>()
}

fn glyph_center_x(line: &crate::document::paint::text::RenderedLine, index: usize) -> f32 {
    let run = line
        .runs
        .first()
        .unwrap_or_else(|| panic!("expected text run for {line:?}"));
    let glyphs = run
        .glyphs
        .as_ref()
        .unwrap_or_else(|| panic!("expected glyph advances for {line:?}"));
    glyph_start_x(line, index) + glyphs[index].x_advance / 2.0
}

fn assert_blue_at_text_position(
    page: &spindrift::Page,
    line: &crate::document::paint::text::RenderedLine,
    x: f32,
) {
    assert!(
        blue_rect_covers_text_position(page, line, x),
        "expected blue background at x={x} for {line:?}; rects={:?}",
        page.rects()
    );
}

fn assert_no_blue_at_text_position(
    page: &spindrift::Page,
    line: &crate::document::paint::text::RenderedLine,
    x: f32,
) {
    assert!(
        !blue_rect_covers_text_position(page, line, x),
        "suppressed .contents.c2 should not paint blue background at x={x} for {line:?}; rects={:?}",
        page.rects()
    );
}

fn blue_rect_covers_text_position(
    page: &spindrift::Page,
    line: &crate::document::paint::text::RenderedLine,
    x: f32,
) -> bool {
    page.rects().iter().any(|rect| {
        rect.fill == Some(CssColor::new(0, 0, 255))
            && x >= rect.x() - 0.5
            && x <= rect.x() + rect.width() + 0.5
            && line.y() >= rect.y() - 0.5
            && line.y() <= rect.y() + rect.height() + 0.5
    })
}

#[tokio::test]
async fn display_contents_text_runs_form_anonymous_flex_items_without_contents_background() {
    let document = Html::from_string(
        "<style>@page { size: 240pt 100pt; margin: 10pt } body { margin: 0; font: 12pt/1 serif }\
         .flex { display: flex; column-gap: 20pt }\
         .contents { display: contents }\
         .c2 { background: blue; color: pink }\
         .b { background: inherit }</style>\
         <div class=\"flex\"><div class=\"contents\">9<div class=\"contents c2\">a<span class=\"b\">b</span>c</div></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let line_x = |text: &str| {
        page.lines()
            .iter()
            .find(|line| line.text == text)
            .map(|line| line.x())
            .unwrap_or_else(|| panic!("expected rendered text {text:?}: {:?}", page.lines()))
    };
    let nine_x = line_x("9");
    let a_x = line_x("a");
    let b_x = line_x("b");
    assert!(
        a_x - nine_x < 12.0 && b_x - a_x > 20.0,
        "9 and a should be contiguous inside one anonymous flex item, with the flex gap before b: {:?}",
        page.lines()
    );
    let blue_rects = page
        .rects()
        .iter()
        .filter(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .collect::<Vec<_>>();
    assert_eq!(
        blue_rects.len(),
        1,
        "only the real .b span should paint the inherited blue background, not suppressed contents boxes: {blue_rects:?}"
    );
}

#[tokio::test]
async fn column_flex_fragments_by_item_progression() {
    let document = Html::from_string(
        "<style>@page { size: 100pt 80pt; margin: 10pt } body { margin: 0 }\
         .column { display: flex; flex-direction: column; width: 30pt }\
         .item { width: 30pt; height: 40pt; background: green }</style>\
         <div class=\"column\"><div class=\"item\"></div><div class=\"item\"></div><div class=\"item\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(
        document.pages.len(),
        3,
        "each 40pt column item should move to a fresh 60pt page area"
    );
    for (page_index, page) in document.pages.iter().enumerate() {
        assert!(
            page.rects()
                .iter()
                .any(|rect| rect.fill == Some(CssColor::new(0, 128, 0))
                    && (rect.height() - 40.0).abs() < 0.01),
            "page {page_index} should contain one flex item: {:?}",
            page.rects()
        );
    }
}

#[tokio::test]
async fn wrapped_row_flex_fragments_by_line() {
    let document = Html::from_string(
        "<style>@page { size: 100pt 80pt; margin: 10pt } body { margin: 0 }\
         .row { display: flex; flex-wrap: wrap; width: 50pt }\
         .item { width: 50pt; height: 40pt; background: blue }</style>\
         <div class=\"row\"><div class=\"item\"></div><div class=\"item\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(
        document.pages.len(),
        2,
        "wrapped row flex lines should fragment at line boundaries"
    );
    for (page_index, page) in document.pages.iter().enumerate() {
        assert!(
            page.rects()
                .iter()
                .any(|rect| rect.fill == Some(CssColor::new(0, 0, 255))
                    && (rect.height() - 40.0).abs() < 0.01),
            "page {page_index} should contain one row flex line: {:?}",
            page.rects()
        );
    }
}

#[tokio::test]
async fn stretched_wrapped_row_uses_nested_wrapped_flex_full_cross_contribution() {
    let document = Html::from_string(
        "<style>@page { size: 220pt 180pt; margin: 10pt }\
         body { margin: 0; font-size: 12pt; line-height: 12pt }\
         .outer { display: flex; flex-wrap: wrap; width: 180pt }\
         h4, dl, dt, dd, p { margin: 0 }\
         h4 { flex: 1 25% }\
         dl { display: flex; flex: 1 75%; flex-wrap: wrap }\
         dt { width: 30% } dd { flex: 1 70% }\
         .after { margin-top: 6pt }</style>\
         <div class=\"outer\"><h4>Heading</h4><dl>\
         <dt>Alpha</dt><dd>first</dd><dt>Beta</dt><dd>second</dd>\
         <dt>Gamma</dt><dd>third</dd></dl></div><p class=\"after\">After</p>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let alpha = rendered_line(page, "Alpha");
    let beta = rendered_line(page, "Beta");
    let gamma = rendered_line(page, "Gamma");
    let after = rendered_line(page, "After");

    assert!(
        alpha.y() > beta.y() + 0.01 && beta.y() > gamma.y() + 0.01,
        "each nested wrapped row must occupy a later block position: alpha={alpha:?}, beta={beta:?}, gamma={gamma:?}"
    );
    assert!(
        gamma.y() > after.y() + 11.9,
        "following normal-flow content must begin after the nested flex item's final row: gamma={gamma:?}, after={after:?}"
    );
}

#[tokio::test]
async fn fragmented_row_flex_clones_container_background() {
    let document = Html::from_string(
        "<style>@page { size: 100pt 80pt; margin: 10pt } body { margin: 0 }\
         .row { display: flex; flex-wrap: wrap; width: 60pt; background: black }\
         .item { width: 50pt; height: 40pt; background: blue }</style>\
         <div class=\"row\"><div class=\"item\"></div><div class=\"item\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(
        document.pages.len(),
        2,
        "wrapped row flex lines should still fragment at line boundaries"
    );
    for (page_index, page) in document.pages.iter().enumerate() {
        assert!(
            page.rects()
                .iter()
                .any(|rect| rect.fill == Some(CssColor::BLACK)
                    && (rect.width() - 60.0).abs() < 0.01
                    && rect.height() >= 39.9),
            "page {page_index} should contain a cloned flex container background: {:?}",
            page.rects()
        );
    }
}

/// An overflowing descendant of a stretched flex item keeps the inline size
/// established in its first multicolumn fragment. The two inputs correspond to
/// WPT `flex-item-content-overflow-001a` and `-001b`; the latter reaches the
/// same used geometry through content-box sizing.
/// <https://drafts.csswg.org/css-flexbox-1/#pagination>
async fn assert_multicol_flex_item_overflow_matches_block_reference(
    case_name: &str,
    box_sizing: &str,
    multicol_inline_size: u16,
    multicol_block_size: u16,
    flexbox_inline_size: u16,
    flexbox_block_size: u16,
    grandchild_block_size: u16,
) {
    let actual = Html::from_string(format!(
        "<style>{box_sizing}\
         .multicol {{ columns: 2; column-gap: 0; column-fill: auto; inline-size: {multicol_inline_size}px; block-size: {multicol_block_size}px; border: 10px solid purple }}\
         .flexbox {{ display: flex; inline-size: {flexbox_inline_size}px; block-size: {flexbox_block_size}px; border: 10px solid black }}\
         .item {{ flex: 1; border: 10px solid teal }}\
         .grandchild {{ border: 10px solid orange; block-size: {grandchild_block_size}px }}\
         </style><div class=\"multicol\"><div class=\"flexbox\"><div class=\"item\"><div class=\"grandchild\"></div></div></div></div>"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    // This is the local equivalent of the WPT reference: an ordinary block
    // with the flex item's resolved 50px border-box block size. It makes the
    // expected second-column continuation explicit without depending on a WPT
    // checkout or another renderer.
    let reference = Html::from_string(
        "<style>div { box-sizing: border-box }\
         .multicol { columns: 2; column-gap: 0; column-fill: auto; inline-size: 300px; block-size: 100px; border: 10px solid purple }\
         .flexbox { display: block; inline-size: 130px; block-size: 70px; border: 10px solid black }\
         .item { block-size: 50px; border: 10px solid teal }\
         .grandchild { border: 10px solid orange; block-size: 140px }\
         </style><div class=\"multicol\"><div class=\"flexbox\"><div class=\"item\"><div class=\"grandchild\"></div></div></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(actual.pages.len(), 1, "{case_name}: unexpected pagination");
    assert_eq!(
        reference.pages.len(),
        1,
        "{case_name}: invalid local reference"
    );

    let border_colors = [
        CssColor::new(128, 0, 128),
        CssColor::BLACK,
        CssColor::new(0, 128, 128),
        CssColor::new(255, 165, 0),
    ];
    let actual_borders = actual.pages[0]
        .rects()
        .iter()
        .filter(|rect| rect.fill.is_some_and(|fill| border_colors.contains(&fill)))
        .collect::<Vec<_>>();
    let reference_borders = reference.pages[0]
        .rects()
        .iter()
        .filter(|rect| rect.fill.is_some_and(|fill| border_colors.contains(&fill)))
        .collect::<Vec<_>>();

    assert_eq!(
        actual_borders, reference_borders,
        "{case_name}: flex overflow must preserve the complete colored border sequence across the column break"
    );
    assert_eq!(
        actual.pages[0].rects(),
        reference.pages[0].rects(),
        "{case_name}: the continuation must retain the first fragment's inline geometry"
    );
}

/// Regression for CSS Break's multicolumn fragmentation of overflowing flex
/// item content, under both border-box and content-box input sizing.
#[tokio::test]
async fn multicol_flex_item_overflow_preserves_first_fragment_inline_size() {
    for (
        case_name,
        box_sizing,
        multicol_inline_size,
        multicol_block_size,
        flexbox_inline_size,
        flexbox_block_size,
        grandchild_block_size,
    ) in [
        (
            "border-box",
            "div { box-sizing: border-box }",
            300,
            100,
            130,
            70,
            140,
        ),
        ("content-box", "", 280, 80, 110, 50, 120),
    ] {
        assert_multicol_flex_item_overflow_matches_block_reference(
            case_name,
            box_sizing,
            multicol_inline_size,
            multicol_block_size,
            flexbox_inline_size,
            flexbox_block_size,
            grandchild_block_size,
        )
        .await;
    }
}

#[tokio::test]
async fn flex_item_break_before_is_consumed_at_container_layer() {
    let document = Html::from_string(
        "<style>@page { size: 120pt 100pt; margin: 10pt } body { margin: 0 }\
         .column { display: flex; flex-direction: column; width: 30pt }\
         .item { width: 30pt; height: 20pt; background: red }</style>\
         <div class=\"column\"><div class=\"item\"></div><div class=\"item\" style=\"break-before: page\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(
        document.pages.len(),
        2,
        "forced break-before on a flex item should break between flex fragments"
    );
    assert!(
        document.pages[0]
            .rects()
            .iter()
            .any(|rect| rect.fill == Some(CssColor::new(255, 0, 0))),
        "first item should stay on page 1"
    );
    assert!(
        document.pages[1]
            .rects()
            .iter()
            .any(|rect| rect.fill == Some(CssColor::new(255, 0, 0))),
        "second item should render on page 2"
    );
}

#[tokio::test]
async fn wrapped_row_forced_first_item_restarts_and_packs_following_lines() {
    let document = Html::from_string(
        "<style>@page { size: 160pt 120pt; margin: 10pt } body { margin: 0 }\
         .intro { width: 140pt; height: 20pt; background: black }\
         .row { display: flex; flex-wrap: wrap; width: 140pt }\
         .full { width: 140pt; height: 20pt; break-after: avoid; background: red }\
         .subtitle { width: 140pt; height: 20pt; background: yellow }\
         .card { width: 40pt; height: 20pt; background: blue }</style>\
         <div class=\"intro\"></div><div class=\"row\">\
         <div class=\"full\" style=\"break-before: page\"></div>\
         <div class=\"subtitle\"></div><div class=\"card\"></div>\
         <div class=\"card\"></div><div class=\"card\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(
        document.pages.len(),
        2,
        "a forced first flex item must restart wrapped-line packing on its destination page"
    );
    let destination_rects = document.pages[1].rects();
    assert_eq!(
        destination_rects
            .iter()
            .filter(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
            .count(),
        1,
        "the forced full-width item should begin the destination page"
    );
    assert!(
        destination_rects
            .iter()
            .any(|rect| rect.fill == Some(CssColor::new(255, 255, 0))),
        "the following subtitle line should fit on the forced destination page"
    );
    assert_eq!(
        destination_rects
            .iter()
            .filter(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
            .count(),
        3,
        "the following card line should fit on the forced destination page"
    );
}

#[tokio::test]
async fn wrapped_row_forced_later_item_keeps_prior_line_and_packs_remainder() {
    let document = Html::from_string(
        "<style>@page { size: 160pt 120pt; margin: 10pt } body { margin: 0 }\
         .intro { width: 140pt; height: 20pt; background: black }\
         .row { display: flex; flex-wrap: wrap; width: 140pt }\
         .before { width: 40pt; height: 20pt; background: blue }\
         .full { width: 140pt; height: 20pt; break-after: avoid; background: red }\
         .subtitle { width: 140pt; height: 20pt; background: yellow }\
         .card { width: 40pt; height: 20pt; background: green }</style>\
         <div class=\"intro\"></div><div class=\"row\">\
         <div class=\"before\"></div><div class=\"before\"></div><div class=\"before\"></div>\
         <div class=\"full\" style=\"break-before: page\"></div>\
         <div class=\"subtitle\"></div><div class=\"card\"></div>\
         <div class=\"card\"></div><div class=\"card\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(
        document.pages.len(),
        2,
        "a later forced flex item must not leave blank intermediate pages"
    );
    assert_eq!(
        document.pages[0]
            .rects()
            .iter()
            .filter(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
            .count(),
        3,
        "the wrapped line before the forced item should remain on page 1"
    );
    let destination_rects = document.pages[1].rects();
    assert!(
        destination_rects
            .iter()
            .any(|rect| rect.fill == Some(CssColor::new(255, 0, 0))),
        "the forced item should begin page 2"
    );
    assert!(
        destination_rects
            .iter()
            .any(|rect| rect.fill == Some(CssColor::new(255, 255, 0))),
        "the subtitle after the forced item should remain on page 2"
    );
    assert_eq!(
        destination_rects
            .iter()
            .filter(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
            .count(),
        3,
        "the later card line should remain on page 2"
    );
}

#[tokio::test]
async fn final_flex_item_break_after_propagates_after_container() {
    let document = Html::from_string(
        "<style>@page { size: 120pt 100pt; margin: 10pt } body { margin: 0 }\
         .column { display: flex; flex-direction: column; width: 30pt }\
         .item { width: 30pt; height: 20pt; background: green }\
         .after { width: 30pt; height: 20pt; background: blue }</style>\
         <div class=\"column\"><div class=\"item\" style=\"break-after: page\"></div></div><div class=\"after\"></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(
        document.pages.len(),
        2,
        "forced break-after on the final flex item should break after the flex container"
    );
    assert!(
        document.pages[0]
            .rects()
            .iter()
            .any(|rect| rect.fill == Some(CssColor::new(0, 128, 0))),
        "flex item should render before the break"
    );
    assert!(
        document.pages[1]
            .rects()
            .iter()
            .any(|rect| rect.fill == Some(CssColor::new(0, 0, 255))),
        "following block should render after the propagated break"
    );
}

#[tokio::test]
async fn oversized_column_flex_item_splits_across_pages() {
    let document = Html::from_string(
        "<style>@page { size: 100pt 80pt; margin: 10pt } body { margin: 0 }\
         .column { display: flex; flex-direction: column; width: 30pt }\
         .item { width: 30pt; height: 100pt; background: red }</style>\
         <div class=\"column\"><div class=\"item\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(
        document.pages.len(),
        2,
        "oversized column flex item should split over two 60pt fragmentainers"
    );
    let first = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
        .expect("first item slice should paint");
    let second = document.pages[1]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
        .expect("second item slice should paint");
    assert!(
        (first.height() - 60.0).abs() < 0.5 && (second.height() - 40.0).abs() < 0.5,
        "item slices should match fragmentainer remainder: first={first:?}, second={second:?}"
    );
}

#[tokio::test]
async fn split_flex_grid_item_keeps_selected_root_decoration_and_grid_child_paint() {
    let document = Html::from_string(
        "<style>@page { size: 100pt 80pt; margin: 10pt } body { margin: 0 }\
         .flex { display: flex; flex-direction: column; width: 40pt }\
         .item { display: grid; width: 40pt; height: 100pt; background: rgb(255, 0, 0) }\
         .child { height: 100pt; background: rgb(0, 128, 0) }</style>\
         <div class=\"flex\"><div class=\"item\"><div class=\"child\"></div></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(
        document.pages.len(),
        2,
        "the flex item must split across pages"
    );
    for (page_index, page) in document.pages.iter().enumerate() {
        let red = page
            .rects()
            .iter()
            .filter(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
            .collect::<Vec<_>>();
        let green = page
            .rects()
            .iter()
            .filter(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
            .collect::<Vec<_>>();
        assert_eq!(
            red.len(),
            1,
            "page {page_index} must paint one item root slice: {red:?}"
        );
        assert_eq!(
            green.len(),
            1,
            "page {page_index} must retain its grid child slice: {green:?}"
        );
    }
}

#[tokio::test]
async fn oversized_wrapped_row_flex_line_splits_across_pages() {
    let document = Html::from_string(
        "<style>@page { size: 100pt 80pt; margin: 10pt } body { margin: 0 }\
         .row { display: flex; flex-wrap: wrap; width: 50pt }\
         .item { width: 50pt; height: 100pt; background: blue }</style>\
         <div class=\"row\"><div class=\"item\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(
        document.pages.len(),
        2,
        "oversized row flex line should split over two 60pt fragmentainers"
    );
    let first = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .expect("first line slice should paint");
    let second = document.pages[1]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .expect("second line slice should paint");
    assert!(
        (first.height() - 60.0).abs() < 0.5 && (second.height() - 40.0).abs() < 0.5,
        "row line slices should match fragmentainer remainder: first={first:?}, second={second:?}"
    );
}

#[tokio::test]
async fn split_flex_item_continuation_replays_later_child_content() {
    let document = Html::from_string(
        "<style>@page { size: 100pt 80pt; margin: 10pt } body { margin: 0 }\
         .column { display: flex; flex-direction: column; width: 40pt }\
         .item { width: 40pt; height: 100pt }\
         .first { width: 40pt; height: 60pt; background: green }\
         .second { width: 40pt; height: 40pt; background: blue }</style>\
         <div class=\"column\"><div class=\"item\"><div class=\"first\"></div><div class=\"second\"></div></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(
        document.pages.len(),
        2,
        "the oversized item should split across the two page areas"
    );
    assert!(
        document.pages[0]
            .rects()
            .iter()
            .any(|rect| rect.fill == Some(CssColor::new(0, 128, 0))
                && (rect.height() - 60.0).abs() < 0.5),
        "first page should paint the first child content: {:?}",
        document.pages[0].rects()
    );
    assert!(
        document.pages[1]
            .rects()
            .iter()
            .any(|rect| rect.fill == Some(CssColor::new(0, 0, 255))
                && (rect.height() - 40.0).abs() < 0.5),
        "second page should paint the later child content: {:?}",
        document.pages[1].rects()
    );
    assert!(
        !document.pages[1]
            .rects()
            .iter()
            .any(|rect| rect.fill == Some(CssColor::new(0, 128, 0))),
        "second page must not replay the start of the flex item: {:?}",
        document.pages[1].rects()
    );
}