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
use super::*;

/// A propagated vertical body establishes the document's principal flow.
/// Consecutive blocks must therefore consume the physical horizontal block
/// track while their descendants retain the same physical inline-start edge.
/// <https://www.w3.org/TR/css-writing-modes-4/#principal-flow>
#[tokio::test]
async fn propagated_vertical_body_advances_block_children_before_laying_out_image() {
    let document = Html::from_string(format!(
        "<style>
           @page {{ size: 200pt 200pt; margin: 10pt }}
           body {{ writing-mode: vertical-rl; margin: 0 }}
           .first {{ width: 40pt; height: 60pt; margin: 0; background: blue }}
           .second {{ width: 30pt; height: 50pt; margin: 0; background: red }}
           img {{ display: block; width: 20pt; height: 30pt }}
         </style>
         <div class=\"first\"></div><div class=\"second\"><img src=\"{GREEN_100_PNG}\"></div>"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(document.pages.len(), 1, "document={document:?}");
    let page = &document.pages[0];
    let first = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .expect("expected first fixed-size block");
    let second = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
        .expect("expected second fixed-size block");
    let image = page.images().first().expect("expected replaced image");

    assert!(
        second.x() + second.width() <= first.x() + 0.01,
        "vertical-rl block progression must move the second child left: first={first:?}, second={second:?}"
    );
    assert!(
        ((second.y() + second.height()) - (image.y() + image.height())).abs() < 0.01,
        "the image must begin at its vertical principal-flow inline-start edge: second={second:?}, image={image:?}"
    );
}

/// A propagated vertical body resolves each direct child's geometry before it
/// is painted. In particular, the UA paragraph block-start margin moves the
/// following replaced block through the horizontal vertical-rl track exactly
/// once; it is not a paint-time translation.
/// <https://www.w3.org/TR/css-writing-modes-4/#principal-flow>
#[tokio::test]
async fn propagated_vertical_body_uses_paragraph_block_margin_for_replaced_child() {
    let document = Html::from_string(format!(
        "<style>
           @page {{ size: 300pt 200pt; margin: 0 }}
           body {{ writing-mode: vertical-rl; margin: 0; font-size: 12pt }}
           .blue {{ width: 75pt; height: 75pt; margin: 0; background: blue }}
           p {{ width: 120pt }}
           img {{ display: block; width: 120pt; height: 30pt }}
         </style>
         <div class=\"blue\"></div><p><img src=\"{GREEN_100_PNG}\"></p>"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(document.pages.len(), 1, "document={document:?}");
    let page = &document.pages[0];
    let blue = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .expect("expected fixed-size blue block");
    let image = page.images().first().expect("expected replaced image");

    assert!(
        ((blue.x() + blue.width()) - 300.0).abs() < 0.01,
        "blue={blue:?}"
    );
    assert!(
        ((blue.y() + blue.height()) - (image.y() + image.height())).abs() < 0.01,
        "both children start at the vertical principal flow inline-start: blue={blue:?}, image={image:?}"
    );
    assert!(
        ((image.x() + image.width()) - (blue.x() - 12.0)).abs() < 0.01,
        "the paragraph's 1em logical block-start margin must move the image once: blue={blue:?}, image={image:?}"
    );
}

const GREEN_100_PNG: &str = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAIAAAD/gAIDAAAAkElEQVR42u3QMQ0AAAjAsElHOhb4eJpUQWviSoEsWbJkyUKBLFmyZMlCgSxZsmTJQoEsWbJkyUKBLFmyZMlCgSxZsmTJQoEsWbJkyUKBLFmyZMlCgSxZsmTJQoEsWbJkyUKBLFmyZMlCgSxZsmTJQoEsWbJkyUKBLFmyZMlCgSxZsmTJQoEsWbJkyUKBLFnfFhDniR6UCYQPAAAAAElFTkSuQmCC";

#[tokio::test]
async fn object_uses_fallback_for_missing_empty_and_unsupported_resources() {
    let document = Html::from_string(format!(
        "<object>missing</object><object data=\"\">empty</object><object type=\"application/pdf\" data=\"{GREEN_100_PNG}\">unsupported</object>"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let visible_text = document
        .pages
        .iter()
        .flat_map(|page| page.lines())
        .map(|line| line.text.as_str())
        .collect::<String>();

    assert!(
        visible_text.contains("missingemptyunsupported"),
        "{visible_text:?}"
    );
    assert!(
        document.pages.iter().all(|page| page.images().is_empty()),
        "fallback objects must not emit their unavailable resource"
    );
}

#[tokio::test]
async fn object_with_supported_image_suppresses_fallback_content() {
    let document = Html::from_string(format!(
        "<object data=\"{GREEN_100_PNG}\">fallback text must be hidden</object>"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let visible_text = document
        .pages
        .iter()
        .flat_map(|page| page.lines())
        .map(|line| line.text.as_str())
        .collect::<String>();

    assert!(!visible_text.contains("fallback text"), "{visible_text:?}");
    assert_eq!(
        document
            .pages
            .iter()
            .map(|page| page.images().len())
            .sum::<usize>(),
        1
    );
}

#[tokio::test]
async fn display_contents_on_unusual_html_elements_computes_to_none() {
    let document = Html::from_string(
        r#"<!DOCTYPE html>
<meta charset="utf-8">
<title>CSS Display: display:contents and unusual HTML elements as display:none</title>
<style>
  html { font-kerning: none; font-feature-settings: "kern" off; }
  body { overflow: hidden }
  br, wbr, meter, progress, canvas, embed, object, audio, iframe, img, video,
  input, textarea, select {
    display: contents;
    border: 10px solid red;
    width: 200px; height: 200px;
  }
</style>
<p>You should see the word PASS below.</p>
<div>
  <meter></meter>
  <progress></progress>
  <canvas></canvas>
  <embed>
  <object>FAIL</object>
  <audio controls></audio>
  <iframe></iframe>
  <img>
  <video></video>
  <input></input>
  <textarea></textarea>
  <select></select>
</div>
P<br>A<wbr>S<br>S"#,
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let visible_text = document
        .pages
        .iter()
        .flat_map(|page| page.lines())
        .map(|line| line.text.as_str())
        .collect::<String>();

    assert_eq!(
        visible_text.matches("PASS").count(),
        2,
        "instruction and result should each contain PASS: {visible_text:?}"
    );
    assert!(
        visible_text.ends_with("PASS"),
        "rendered result should end with PASS: {visible_text:?}"
    );
    assert!(
        !visible_text.contains("FAIL"),
        "object fallback contents should be suppressed: {visible_text:?}"
    );

    let red = CssColor::new(255, 0, 0);
    assert!(
        document
            .pages
            .iter()
            .flat_map(|page| page.rects())
            .all(|rect| rect.fill != Some(red)),
        "unusual elements should not paint red rects"
    );
    assert!(
        document
            .pages
            .iter()
            .flat_map(|page| page.paths())
            .all(|path| path.fill != Some(red)),
        "unusual elements should not paint red border paths"
    );
    assert!(
        document.pages.iter().all(|page| page.images().is_empty()),
        "display:none unusual elements should not emit image output"
    );
}

#[tokio::test]
async fn select_4_option_optgroup_display_none_hides_red_form_content() {
    let document = Html::from_string(
        r#"<!DOCTYPE HTML>
<html><head>
  <meta charset="utf-8">
  <style>
    .none { display:none; }
    .contents { display:contents; }
    .red { color: red; }
    .green { color: green; }
    select { -webkit-appearance: none; }
  </style>
</head>
<body>
<pre>FAIL if there is any red color</pre>

<option class="none red">text</option>
<optgroup class="none red">text</optgroup>

<optgroup class="none red"><option>option</option></optgroup>
<optgroup><option class="none red">option</option></optgroup>
<optgroup class="contents red"><option class="none">option</option></optgroup>
<optgroup class="contents green" label="optgroup"><option class="none red">option</option></optgroup>
<optgroup class="none red" label="optgroup"><option class="red">option</option></optgroup>

<br>

<select class="red" size="4">select</select>
<select size="4" class="red"><optgroup class="none" label="optgroup"></select>
<select size="4" class="red"><option class="none">option</select>
<select size="4" class="red"><optgroup><option class="none">option</select>
<select size="4"><optgroup class="none"><option class="green">option</select>
<select size="4" class="red"><optgroup class="none green" label="optgroup"><option>option</select>
<select size="4" class="red"><optgroup class="none"><option class="none">option</select>
<select size="4" class="red"><optgroup class="none green" label="optgroup"><option class="none">option</select>

</body></html>"#,
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let red = CssColor::new(255, 0, 0);
    let visible_text = document
        .pages
        .iter()
        .flat_map(|page| page.lines())
        .map(|line| line.text.as_str())
        .collect::<String>();

    assert!(
        visible_text.contains("FAIL if there is any red color"),
        "instruction should render: {visible_text:?}"
    );
    assert!(
        !visible_text.contains("select") && !visible_text.contains("option"),
        "hidden select/option text should not render: {visible_text:?}"
    );
    assert!(
        document
            .pages
            .iter()
            .flat_map(|page| page.lines())
            .all(|line| line.color != red),
        "no red text or generated select chrome should render: {:?}",
        document
            .pages
            .iter()
            .flat_map(|page| page.lines())
            .collect::<Vec<_>>()
    );
    assert!(
        document
            .pages
            .iter()
            .flat_map(|page| page.rects())
            .all(|rect| rect.fill != Some(red) && rect.stroke != Some(red)),
        "no red vector rects should render"
    );
    assert!(
        document
            .pages
            .iter()
            .flat_map(|page| page.paths())
            .all(|path| path.fill != Some(red) && path.stroke != Some(red)),
        "no red vector paths should render"
    );
}

#[tokio::test]
async fn baseline_shift_center_centers_inline_images_in_line_box() {
    let document = Html::from_string(format!(
        "<style>\
         @page {{ size: 260pt 180pt; margin: 20pt }}\
         body {{ margin: 0 }}\
         #line {{ font: 20pt/20pt sans-serif }}\
         .big {{ baseline-shift: center; font-size: 100pt; line-height: 100pt; background: rgb(255 0 0); color: transparent }}\
         img {{ baseline-shift: center; width: 60pt; height: 60pt }}\
         .small {{ baseline-shift: center; font-size: 20pt; line-height: 20pt; background: rgb(0 0 255); color: transparent }}\
         </style>\
         <span id=\"line\"><span class=\"big\">X</span><img src=\"{GREEN_100_PNG}\"><span class=\"small\">X</span></span>"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    assert_eq!(page.images().len(), 1, "images={:?}", page.images());
    let image = &page.images()[0];
    assert!((image.width() - 60.0).abs() < 0.01, "image={image:?}");
    assert!((image.height() - 60.0).abs() < 0.01, "image={image:?}");

    let red = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
        .unwrap_or_else(|| panic!("expected big inline background: {:?}", page.rects()));
    let blue = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .unwrap_or_else(|| panic!("expected small inline background: {:?}", page.rects()));

    let image_center = image.y() + image.height() / 2.0;
    let red_center = red.y() + red.height() / 2.0;
    let blue_center = blue.y() + blue.height() / 2.0;
    assert!(
        (image_center - red_center).abs() < 0.5,
        "centered image should match the large centered inline box: image={image:?}, red={red:?}"
    );
    assert!(
        (blue_center - red_center).abs() < 0.5,
        "small centered inline box should match the same line center: blue={blue:?}, red={red:?}"
    );
}

#[tokio::test]
async fn renders_png_data_uri_images() {
    let html = Html::from_string(
        "<img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC\" style=\"height: 10pt\">",
    );
    let document = html.render(&RenderOptions::default()).await.unwrap();

    assert_eq!(document.pages[0].images().len(), 1);
    assert_eq!(document.pages[0].images()[0].pixel_width(), 1);
    assert_eq!(document.pages[0].images()[0].height(), 10.0);

    let pdf = document
        .write_pdf_bytes(&crate::PdfOptions::default())
        .unwrap();
    let rendered = pdf_searchable_text(&pdf);
    // A uniform opaque raster can be emitted as an equivalent calibrated PDF
    // fill. The retained document image still establishes the replaced
    // element's layout and accessibility semantics; this assertion only
    // verifies that its PDF paint representation is present.
    assert!(
        rendered.contains("/Subtype /Image") || rendered.contains("/CSsRGB cs"),
        "{rendered}"
    );
    if rendered.contains("/Subtype /Image") {
        assert!(rendered.contains("/Interpolate false"));
        assert!(rendered.contains("/Im1 Do"));
    }
}

#[tokio::test]
async fn visible_overflow_allows_an_inline_replaced_image_to_escape_its_content_box() {
    let document = Html::from_string(format!(
        "<style>@page {{ size: 160pt 120pt; margin: 0 }} body {{ margin: 0 }} \
         img {{ width: 25pt; height: 25pt; object-fit: none; object-position: left top; overflow: visible; border-radius: 50% }}</style>\
         <img src=\"{GREEN_100_PNG}\">"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let image = &document.pages[0].images()[0];
    assert_eq!(image.width(), 75.0, "image={image:?}");
    assert_eq!(image.height(), 75.0, "image={image:?}");
    assert!(!image.is_clipped(), "image={image:?}");
}

#[tokio::test]
async fn renders_only_the_first_frame_of_an_animated_gif_data_uri() {
    use image::{Frame, RgbaImage};

    let first = RgbaImage::from_raw(2, 1, vec![230, 32, 16, 255, 0, 0, 0, 0])
        .expect("RGBA dimensions match the sample pixels");
    let second = RgbaImage::from_raw(2, 1, vec![0, 96, 255, 255, 0, 96, 255, 255])
        .expect("RGBA dimensions match the sample pixels");
    let mut bytes = Vec::new();
    {
        let mut encoder = image::codecs::gif::GifEncoder::new(&mut bytes);
        encoder
            .encode_frames([Frame::new(first), Frame::new(second)])
            .expect("GIF sample encodes");
    }
    let image = base64::engine::general_purpose::STANDARD.encode(bytes);
    let document = Html::from_string(format!(
        "<img src=\"data:image/gif;base64,{image}\" height=\"10pt\">"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let rendered_image = &document.pages[0].images()[0];
    assert_eq!(rendered_image.pixel_width(), 2);
    assert_eq!(rendered_image.pixel_height(), 1);
    let crate::document::paint::images::RenderedImageSource::Stored { image_id, .. } =
        &rendered_image.source
    else {
        panic!("HTML GIF should retain a store-backed source");
    };
    let raster = document
        .image_store
        .with_rasterized(*image_id, |raster| raster)
        .expect("GIF first frame rasterizes for PDF output");
    assert_eq!(raster.rgb, vec![230, 32, 16, 0, 0, 0]);
    assert_eq!(raster.alpha, Some(vec![255, 0]));

    let pdf = document
        .write_pdf_bytes(&crate::PdfOptions::default())
        .unwrap();
    let rendered = pdf_searchable_text(&pdf);
    assert!(rendered.contains("/Subtype /Image"));
    assert!(rendered.contains("/FlateDecode"));
    assert!(!rendered.contains("/DCTDecode"));
}

#[tokio::test]
async fn renders_only_the_first_frame_of_an_animated_webp_data_uri() {
    const ANIMATED_WEBP: &str = "UklGRoYAAABXRUJQVlA4WAoAAAACAAAAAQAAAAAAQU5JTQYAAAD/////AABBTk1GKgAAAAAAAAAAAAEAAAAAAGQAAAJWUDhMEgAAAC8BAAAADzAgYz4Q8x94yIj+B0FOTUYoAAAAAAAAAAAAAQAAAAAAZAAAAFZQOEwQAAAALwEAAAAHULDof/8DEdH/AA==";
    let document = Html::from_string(format!(
        "<img src=\"data:image/webp;base64,{ANIMATED_WEBP}\" height=\"10pt\">"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let rendered_image = &document.pages[0].images()[0];
    assert_eq!(rendered_image.pixel_width(), 2);
    assert_eq!(rendered_image.pixel_height(), 1);
    let crate::document::paint::images::RenderedImageSource::Stored { image_id, .. } =
        &rendered_image.source
    else {
        panic!("HTML WebP should retain a store-backed source");
    };
    let raster = document
        .image_store
        .with_rasterized(*image_id, |raster| raster)
        .expect("WebP first frame rasterizes for PDF output");
    assert_eq!(raster.rgb, vec![230, 32, 16, 0, 0, 0]);
    assert_eq!(raster.alpha, None);

    let pdf = document
        .write_pdf_bytes(&crate::PdfOptions::default())
        .unwrap();
    let rendered = pdf_searchable_text(&pdf);
    assert!(rendered.contains("/Subtype /Image"));
    assert!(rendered.contains("/FlateDecode"));
    assert!(!rendered.contains("/DCTDecode"));
}

#[tokio::test]
async fn embeds_png_alpha_as_pdf_soft_mask() {
    let html = Html::from_string(
        "<img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGP4z8DQAAAEgQGALFXOsAAAAABJRU5ErkJggg==\" height=\"10\">",
    );
    let document = html.render(&RenderOptions::default()).await.unwrap();

    let pdf = document
        .write_pdf_bytes(&crate::PdfOptions::default())
        .unwrap();
    let rendered = pdf_searchable_text(&pdf);
    assert!(rendered.contains("/SMask"));
    assert!(rendered.contains("/DeviceGray"));
    assert!(rendered.matches("/Interpolate false").count() >= 2);
}

#[tokio::test]
async fn supports_percentage_image_widths() {
    let document = Html::from_string(
        "<style>@page { size: 200pt 300pt; margin: 10pt } body { margin: 0 } img { width: 100%; }</style><div style=\"margin:0; width:50%\"><img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC\"></div>",
    )
    .render(&RenderOptions::default()).await
    .unwrap();

    assert_eq!(document.pages[0].images()[0].width(), 90.0);
}

#[tokio::test]
async fn raster_image_natural_pixels_convert_to_css_layout_points() {
    let document = Html::from_string(format!(
        "<!doctype html><style>@page {{ size: 120pt 120pt; margin: 0 }} body {{ margin: 0 }} img {{ display: block }}</style>\
         <img src=\"{GREEN_100_PNG}\">"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .images()
        .first()
        .expect("expected green raster image paint");
    assert!((green.width() - 75.0).abs() < 0.01, "green={green:?}");
    assert!((green.height() - 75.0).abs() < 0.01, "green={green:?}");
}

#[tokio::test]
async fn vertical_writing_flex_image_uses_converted_natural_main_size() {
    let document = Html::from_string(format!(
        "<!doctype html><style>@page {{ size: 140pt 140pt; margin: 0 }} body {{ margin: 0 }} p {{ display: none }}</style>\
         <p>Test passes if there is a filled green square.</p>\
         <div style=\"writing-mode: vertical-lr; display: flex;\"><img src=\"{GREEN_100_PNG}\"></div>"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .images()
        .first()
        .expect("expected green flex image paint");
    assert!((green.width() - 75.0).abs() < 0.01, "green={green:?}");
    assert!((green.height() - 75.0).abs() < 0.01, "green={green:?}");
}

#[tokio::test]
async fn floated_percentage_width_replays_resolved_used_width_once() {
    let document = Html::from_string(
        "<style>@page { size: 360pt 120pt; margin: 0 } body { margin: 0 }\
         .test { float: left; width: 33.3333% }\
         p { margin: 0 10pt 0 0; height: 20pt; background: #ccc }</style>\
         <div class=\"test\"><p></p></div><div class=\"test\"><p></p></div><div class=\"test\"><p></p></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let mut rects = document.pages[0]
        .rects()
        .iter()
        .filter(|rect| rect.fill == Some(CssColor::new(204, 204, 204)))
        .collect::<Vec<_>>();
    rects.sort_by(|a, b| a.x().total_cmp(&b.x()));

    assert_eq!(rects.len(), 3);
    for (rect, expected_x) in rects.iter().zip([0.0, 120.0, 240.0]) {
        assert!(
            (rect.x() - expected_x).abs() < 0.01,
            "expected float child at x={expected_x}, got {rect:?}"
        );
        assert!(
            (rect.width() - 110.0).abs() < 0.01,
            "float percentage width should not be resolved twice: {rect:?}"
        );
    }
}

#[tokio::test]
async fn floated_border_box_percentage_width_replay_preserves_content_width() {
    let document = Html::from_string(
        "<style>@page { size: 200pt 120pt; margin: 0 } body { margin: 0 }\
         .float { float: left; width: 50%; box-sizing: border-box; padding: 0 10pt;\
                  border-left: 5pt solid green; border-right: 5pt solid green }\
         .fill { height: 20pt; background: blue }</style>\
         <div class=\"float\"><div class=\"fill\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let fill = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .expect("blue child should render");

    assert!((fill.x() - 15.0).abs() < 0.01, "blue child: {fill:?}");
    assert!(
        (fill.width() - 70.0).abs() < 0.01,
        "border-box float replay should preserve the resolved content width: {fill:?}"
    );
}

#[tokio::test]
async fn floated_non_replaced_block_intrinsic_width_honors_definite_max_width() {
    let document = Html::from_string(
        "<style>@page { size: 360pt 420pt; margin: 0 } body { margin: 0 }\
         .container { clear: both; padding: 10pt; width: 0 }\
         .infinite { width: 400pt }\
         .float { float: left; border-left: 20pt solid orange; border-right: 20pt solid orange }\
         .child { border-right: 20pt solid aqua }\
         .atom { display: inline-block; width: 80pt; height: 10pt; background: blue }</style>\
         <div class=\"container\"><div class=\"float\"><div class=\"child\"><span class=\"atom\"></span></div></div></div>\
         <div class=\"container\"><div class=\"float\"><div class=\"child\" style=\"max-width: 50%\"><span class=\"atom\"></span></div></div></div>\
         <div class=\"container\"><div class=\"float\"><div class=\"child\" style=\"max-width: calc(45pt + 0%)\"><span class=\"atom\"></span></div></div></div>\
         <div class=\"container\"><div class=\"float\"><div class=\"child\" style=\"max-width: 40pt\"><span class=\"atom\"></span></div></div></div>\
         <div class=\"container infinite\"><div class=\"float\"><div class=\"child\"><span class=\"atom\"></span></div></div></div>\
         <div class=\"container infinite\"><div class=\"float\"><div class=\"child\" style=\"max-width: 50%\"><span class=\"atom\"></span></div></div></div>\
         <div class=\"container infinite\"><div class=\"float\"><div class=\"child\" style=\"max-width: calc(45pt + 0%)\"><span class=\"atom\"></span></div></div></div>\
         <div class=\"container infinite\"><div class=\"float\"><div class=\"child\" style=\"max-width: 40pt\"><span class=\"atom\"></span></div></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let orange = CssColor::new(255, 165, 0);
    let mut right_borders = document.pages[0]
        .rects()
        .iter()
        .filter(|rect| {
            rect.fill == Some(orange) && (rect.width() - 20.0).abs() < 0.01 && rect.height() > 10.0
        })
        .collect::<Vec<_>>();
    right_borders.sort_by(|a, b| b.y().total_cmp(&a.y()).then(a.x().total_cmp(&b.x())));
    let right_borders = right_borders
        .as_chunks::<2>()
        .0
        .iter()
        .map(|row| row[1].x())
        .collect::<Vec<_>>();

    assert_eq!(right_borders.len(), 8, "orange borders={right_borders:?}");
    for row in [0usize, 1, 2, 4, 5, 6] {
        assert!(
            (right_borders[row] - right_borders[0]).abs() < 0.01,
            "percentage max-width rows should keep the intrinsic float width: {right_borders:?}"
        );
    }
    for (row, reference) in [(3usize, 0usize), (7, 4)] {
        assert!(
            (right_borders[row] - (right_borders[reference] - 40.0)).abs() < 0.01,
            "definite max-width should shrink the parent float: {right_borders:?}"
        );
    }
}

#[tokio::test]
async fn min_content_block_resolves_calc_margin_percent_against_zero() {
    let document = Html::from_string(
        "<!doctype html>\
         <style>@page { size: 200pt 200pt; margin: 0 } body { margin: 0 }</style>\
         <div style=\"width: min-content; height: 100px; background: green\">\
           <div style=\"margin-left: calc(10% + 100px)\"></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("green min-content background should paint");

    assert!(
        (green.width() - 75.0).abs() < 0.01,
        "green square should be 100 CSS px wide: {green:?}"
    );
    assert!(
        (green.height() - 75.0).abs() < 0.01,
        "green square should be 100 CSS px tall: {green:?}"
    );
}

#[tokio::test]
async fn hidden_float_placeholders_reserve_reference_grid_cells() {
    let document = Html::from_string(
        "<!DOCTYPE html><meta charset=\"utf-8\">\
         <style>\
         @page { size: 900px 600px; margin: 0 } body { margin: 0 }\
         .flexContainer { height: 60px; width: 60px; font: 10px sans-serif;\
             background: yellow; float: left; border: 1px solid black }\
         .flexContainer > * { border: 1px dotted gray; width: 28px; height: 28px;\
             float: left }\
         .hidden { visibility: hidden }\
         </style>\
         <div class=\"flexContainer\"><div>1</div><div>2</div><div>3</div><div class=\"hidden\">4</div></div>\
         <div class=\"flexContainer\"><div>2</div><div>1</div><div class=\"hidden\">4</div><div>3</div></div>\
         <div class=\"flexContainer\"><div>1</div><div>3</div><div>2</div><div class=\"hidden\">4</div></div>\
         <div class=\"flexContainer\"><div>2</div><div class=\"hidden\">4</div><div>1</div><div>3</div></div>\
         <div style=\"clear:both\"></div>\
         <div class=\"flexContainer\"><div>1</div><div>2</div><div>3</div><div class=\"hidden\">4</div></div>\
         <div class=\"flexContainer\"><div>2</div><div>1</div><div class=\"hidden\">4</div><div>3</div></div>\
         <div class=\"flexContainer\"><div>1</div><div>3</div><div>2</div><div class=\"hidden\">4</div></div>\
         <div class=\"flexContainer\"><div>2</div><div class=\"hidden\">4</div><div>1</div><div>3</div></div>\
         <div style=\"clear:both\"></div>\
         <div class=\"flexContainer\"><div>3</div><div class=\"hidden\">4</div><div>1</div><div>2</div></div>\
         <div class=\"flexContainer\"><div class=\"hidden\">4</div><div>3</div><div>2</div><div>1</div></div>\
         <div class=\"flexContainer\"><div>3</div><div>1</div><div class=\"hidden\">4</div><div>2</div></div>\
         <div class=\"flexContainer\"><div class=\"hidden\">4</div><div>2</div><div>3</div><div>1</div></div>\
         <div style=\"clear:both\"></div>\
         <div class=\"flexContainer\"><div>3</div><div class=\"hidden\">4</div><div>1</div><div>2</div></div>\
         <div class=\"flexContainer\"><div class=\"hidden\">4</div><div>3</div><div>2</div><div>1</div></div>\
         <div class=\"flexContainer\"><div>3</div><div>1</div><div class=\"hidden\">4</div><div>2</div></div>\
         <div class=\"flexContainer\"><div class=\"hidden\">4</div><div>2</div><div>3</div><div>1</div></div>\
         <div style=\"clear:both\"></div>\
         <div class=\"flexContainer\"><div>1</div><div>2</div><div>3</div><div class=\"hidden\">4</div></div>\
         <div class=\"flexContainer\"><div>3</div><div class=\"hidden\">4</div><div>1</div><div>2</div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let mut containers = document.pages[0]
        .rects()
        .iter()
        .filter(|rect| rect.fill == Some(CssColor::new(255, 255, 0)))
        .collect::<Vec<_>>();
    containers.sort_by(|a, b| {
        b.y()
            .total_cmp(&a.y())
            .then_with(|| a.x().total_cmp(&b.x()))
    });

    let expected = [
        [Some("1"), Some("2"), Some("3"), None],
        [Some("2"), Some("1"), None, Some("3")],
        [Some("1"), Some("3"), Some("2"), None],
        [Some("2"), None, Some("1"), Some("3")],
        [Some("1"), Some("2"), Some("3"), None],
        [Some("2"), Some("1"), None, Some("3")],
        [Some("1"), Some("3"), Some("2"), None],
        [Some("2"), None, Some("1"), Some("3")],
        [Some("3"), None, Some("1"), Some("2")],
        [None, Some("3"), Some("2"), Some("1")],
        [Some("3"), Some("1"), None, Some("2")],
        [None, Some("2"), Some("3"), Some("1")],
        [Some("3"), None, Some("1"), Some("2")],
        [None, Some("3"), Some("2"), Some("1")],
        [Some("3"), Some("1"), None, Some("2")],
        [None, Some("2"), Some("3"), Some("1")],
        [Some("1"), Some("2"), Some("3"), None],
        [Some("3"), None, Some("1"), Some("2")],
    ];

    assert_eq!(
        containers.len(),
        expected.len(),
        "containers={containers:?}"
    );
    for (container_index, (container, expected_cells)) in
        containers.iter().zip(expected).enumerate()
    {
        let mut actual = [None, None, None, None];
        for line in document.pages[0].lines().iter().filter(|line| {
            line.x() >= container.x() - 0.01
                && line.x() <= container.x() + container.width() + 0.01
                && line.y() >= container.y() - 0.01
                && line.y() <= container.y() + container.height() + 0.01
        }) {
            let column = if line.x() < container.x() + container.width() / 2.0 {
                0
            } else {
                1
            };
            let row = if line.y() > container.y() + container.height() / 2.0 {
                0
            } else {
                1
            };
            actual[row * 2 + column] = Some(line.text.as_str());
        }
        assert_eq!(
            actual,
            expected_cells,
            "container {container_index} should match reference grid cells: container={container:?}, lines={:?}",
            document.pages[0].lines()
        );
    }
}

#[tokio::test]
async fn direct_inline_images_reserve_baseline_descent_in_line_box() {
    let document = Html::from_string(
        "<style>@page { size: 200pt 160pt; margin: 20pt } body, div, p { margin: 0; font-size: 12pt; line-height: 12pt } img { height: 20pt }</style>\
         <div><img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC\"></div><p>After</p>",
    )
    .render(&RenderOptions::default()).await
    .unwrap();

    let image = &document.pages[0].images()[0];
    let after = document.pages[0]
        .lines()
        .iter()
        .find(|line| line.text == "After")
        .unwrap();

    assert!(image.y() - after.y() >= 12.0 - 0.01);
}

/// An auto-height block that owns only an inline replaced element still owns
/// that element's line box. The next in-flow table must therefore begin below
/// the image, not in the image's painted area.
///
/// <https://www.w3.org/TR/css-inline-3/#line-box>
/// <https://www.w3.org/TR/CSS22/visudet.html#root-height>
#[tokio::test]
async fn inline_replaced_image_advances_nested_block_before_following_table() {
    let document = Html::from_string(format!(
        "<style>
           @page {{ size: 200pt 160pt; margin: 20pt }}
           body, div, p, table {{ margin: 0; padding: 0; border-spacing: 0; font-size: 12pt; line-height: 12pt }}
           .label {{ height: 15pt; padding-bottom: 2pt }}
           .chart {{ width: 100pt }}
           .chart img {{ width: 100%; height: 20pt }}
         </style>
         <div class=\"block\"><p class=\"label\">chr1</p><div><div class=\"chart\"><img src=\"{GREEN_100_PNG}\"></div></div><table><tr><td>Status</td></tr></table></div><p class=\"label\">chr2</p>"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let image = page.images().first().expect("expected chart image");
    let status = page
        .lines()
        .iter()
        .find(|line| line.text.trim() == "Status")
        .expect("expected table status");
    let next_label = page
        .lines()
        .iter()
        .find(|line| line.text.trim() == "chr2")
        .expect("expected following block label");

    assert!(
        image.y() - status.y() >= 12.0 - 0.01,
        "the table text must follow the image line box: image={image:?}, status={status:?}"
    );
    assert!(
        status.y() - next_label.y() >= 12.0 - 0.01,
        "the following block must remain after the table: status={status:?}, next_label={next_label:?}"
    );
}

/// Break avoidance must use the actual height of a block containing an inline
/// replaced element. This keeps each chart and its table on its own page.
///
/// <https://www.w3.org/TR/css-break-3/#break-within>
#[tokio::test]
async fn inline_replaced_image_height_participates_in_page_break_avoidance() {
    let block = |label: &str, status: &str| {
        format!(
            "<div class=\"block\"><p class=\"label\">{label}</p><div><div class=\"chart\"><img src=\"{GREEN_100_PNG}\"></div></div><table><tr><td>{status}</td></tr></table></div>"
        )
    };
    let document = Html::from_string(format!(
        "<style>
           @page {{ size: 160pt 90pt; margin: 15pt }}
           body, div, p, table {{ margin: 0; padding: 0; border-spacing: 0; font-size: 12pt; line-height: 12pt }}
           .block {{ break-inside: avoid }}
           .label {{ height: 15pt; padding-bottom: 2pt }}
           .chart {{ width: 100pt }}
           .chart img {{ width: 100%; height: 20pt }}
         </style>{}{}",
        block("chr1", "Status 1"),
        block("chr2", "Status 2"),
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(document.pages.len(), 2, "document={document:?}");
    for (page, label, status) in [
        (&document.pages[0], "chr1", "Status 1"),
        (&document.pages[1], "chr2", "Status 2"),
    ] {
        let image = page.images().first().expect("expected chart image");
        let label = page
            .lines()
            .iter()
            .find(|line| line.text.trim() == label)
            .expect("expected chart label");
        let status = page
            .lines()
            .iter()
            .find(|line| line.text.trim() == status)
            .expect("expected table status");

        assert_eq!(page.images().len(), 1, "page={page:?}");
        assert!(label.y() > image.y(), "label={label:?}, image={image:?}");
        assert!(
            image.y() - status.y() >= 12.0 - 0.01,
            "the table text must follow the image line box: image={image:?}, status={status:?}"
        );
    }
}

#[tokio::test]
async fn anonymous_inline_runs_layout_replaced_atoms_with_text() {
    let document = Html::from_string(
        "<style>@page { size: 200pt 160pt; margin: 20pt } body, div, p { margin: 0; font-size: 12pt; line-height: 12pt } img { width: 10pt; height: 10pt }</style>\
         <div>Before <img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC\"> After<p>Block</p></div>",
    )
    .render(&RenderOptions::default()).await
    .unwrap();

    let image = &document.pages[0].images()[0];
    let before = document.pages[0]
        .lines()
        .iter()
        .find(|line| line.text.trim() == "Before")
        .unwrap();
    let after = document.pages[0]
        .lines()
        .iter()
        .find(|line| line.text.trim() == "After")
        .unwrap();

    assert!(image.x() > before.x());
    assert!(after.x() > image.x());
    assert!((before.y() - after.y()).abs() < 0.1);
}

#[tokio::test]
async fn inline_svg_block_margins_do_not_shift_sibling_text_across_breaks() {
    let document = Html::from_string(
        "<style>@page { size: 200pt 120pt; margin: 10pt } body, div, span { margin:0; font-size:12pt; line-height:12pt } svg { width:10pt; height:10pt; margin-right:3pt; margin-bottom:-5px; padding-bottom:2px }</style>\
         <div><svg style=\"margin-top:15px\" width=\"10\" height=\"10\"><rect width=\"10\" height=\"10\" fill=\"red\" /></svg><span>Alpha</span><br>\
         <svg width=\"10\" height=\"10\"><rect width=\"10\" height=\"10\" fill=\"green\" /></svg><span>Bravo</span><br>\
         <svg width=\"10\" height=\"10\"><rect width=\"10\" height=\"10\" fill=\"blue\" /></svg><span>Charlie</span></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let swatches = [
        CssColor::new(255, 0, 0),
        CssColor::new(0, 128, 0),
        CssColor::new(0, 0, 255),
    ]
    .map(|color| {
        page.paths()
            .iter()
            .find(|path| path.fill == Some(color))
            .unwrap_or_else(|| panic!("expected {color:?} SVG swatch"))
    });
    let labels = ["Alpha", "Bravo", "Charlie"].map(|text| {
        page.lines()
            .iter()
            .find(|line| line.text == text)
            .unwrap_or_else(|| panic!("expected label {text:?}"))
    });

    for (swatch, label) in swatches.iter().zip(labels) {
        let swatch_bounds = swatch.bounds().expect("SVG swatch bounds");
        assert!(
            label.x() > swatch_bounds.origin.x,
            "label must follow its SVG swatch: swatch={swatch:?}, label={label:?}"
        );
        assert!(
            (label.y() - swatch_bounds.origin.y).abs() < 5.0,
            "label must share the swatch line: swatch={swatch:?}, label={label:?}"
        );
    }
    assert!(
        labels.windows(2).all(|pair| pair[0].y() > pair[1].y()),
        "labels must remain on successive source-order rows: {labels:?}"
    );
}

#[tokio::test]
async fn inline_formatting_context_places_atomic_image_between_text_fragments() {
    let document = Html::from_string(
        "<style>@page { size: 200pt 100pt; margin: 20pt } body, div { margin: 0; font-size: 12pt; line-height: 12pt } img { width: 10pt; height: 10pt }</style>\
         <div>Before <img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC\"> After</div>",
    )
    .render(&RenderOptions::default()).await
    .unwrap();

    let image = &document.pages[0].images()[0];
    let before = document.pages[0]
        .lines()
        .iter()
        .find(|line| line.text.trim() == "Before")
        .unwrap();
    let after = document.pages[0]
        .lines()
        .iter()
        .find(|line| line.text.trim() == "After")
        .unwrap();

    assert!(image.x() > before.x());
    assert!(after.x() > image.x());
    assert!((before.y() - after.y()).abs() < 0.1);
}

#[tokio::test]
async fn flex_replaced_images_use_border_box_for_flex_distribution() {
    let image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC";
    let document = Html::from_string(format!(
        "<style>@page {{ size: 260pt 100pt; margin: 10pt }} body {{ margin: 0 }} .flex {{ width: 200pt; display: flex; line-height: 8pt }} img {{ min-width: 0; width: 10pt; height: 20pt; border: 1pt dotted green }}</style>\
         <div class=\"flex\"><img src=\"{image}\" style=\"flex: 5\"><img src=\"{image}\" style=\"flex: 3\"></div>",
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let images = &document.pages[0].images();
    assert_eq!(images.len(), 2);
    assert!((images[0].width() - 122.5).abs() < 0.01);
    assert!((images[1].width() - 73.5).abs() < 0.01);
    assert!((images[1].x() - images[0].x() - 124.5).abs() < 0.01);
}

#[tokio::test]
async fn column_flex_replaced_image_min_height_transfers_through_aspect_ratio() {
    let image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC";
    let document = Html::from_string(format!(
        "<style>@page {{ size: 180pt 180pt; margin: 10pt }} body {{ margin:0 }}\
         .flex {{ display:flex; flex-direction:column; align-items:flex-start; width:75pt; height:150pt }}\
         img {{ min-height:75pt; flex:1 0 auto }} .spacer {{ flex:1 0 1pt }}\
         </style><div class=\"flex\"><img src=\"{image}\"><div class=\"spacer\"></div></div>",
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let image = &document.pages[0].images()[0];
    assert!((image.width() - 75.0).abs() < 0.01, "image={image:?}");
    assert!((image.height() - 75.0).abs() < 0.01, "image={image:?}");
}

#[tokio::test]
async fn flex_container_aspect_ratio_height_is_definite_for_stretched_image() {
    let document = Html::from_string(format!(
        "<style>@page {{ size: 460pt 430pt; margin: 0 }} body {{ margin:0 }}\
         .flex {{ display:flex; width:400pt }}\
         .ratio {{ aspect-ratio:2/1 }}\
         .explicit {{ height:200pt }}\
         img {{ display:block }}\
         </style>\
         <div class=\"flex ratio\"><img src=\"{GREEN_100_PNG}\"></div>\
         <div class=\"flex explicit\"><img src=\"{GREEN_100_PNG}\"></div>",
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let images = document.pages[0].images();
    assert_eq!(images.len(), 2, "images={images:?}");
    for image in images {
        assert!((image.width() - 200.0).abs() < 0.01, "image={image:?}");
        assert!((image.height() - 200.0).abs() < 0.01, "image={image:?}");
    }
}

#[tokio::test]
async fn row_flex_replaced_image_authored_aspect_ratio_sets_auto_cross_size() {
    let image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAAFCAYAAABvsz2cAAAAFElEQVR4nGNg+A+EDUAMJkAQtwgAfnURcnh7KuYAAAAASUVORK5CYII=";
    let document = Html::from_string(format!(
        "<style>@page {{ size: 200px 200px; margin: 0 }} body {{ margin:0 }}\
         div {{ display:flex; width:100px }}\
         img {{ width:50px; aspect-ratio:1/1; flex:1; min-height:0 }}\
         </style><div><img src=\"{image}\"></div>",
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let has_square_rect = page
        .rects()
        .iter()
        .any(|rect| (rect.width() - 75.0).abs() < 0.01 && (rect.height() - 75.0).abs() < 0.01);
    let has_square_image = page
        .images()
        .iter()
        .any(|image| (image.width() - 75.0).abs() < 0.01 && (image.height() - 75.0).abs() < 0.01);
    assert!(
        has_square_rect || has_square_image,
        "expected 100px by 100px painted image, rects={:?}, images={:?}",
        page.rects(),
        page.images()
    );
}

#[tokio::test]
async fn column_flex_replaced_image_cross_min_width_transfers_to_main_basis() {
    let image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAIAAAAFCAYAAABvsz2cAAAAFElEQVR4nGNg+A+EDUAMJkAQtwgAfnURcnh7KuYAAAAASUVORK5CYII=";
    let document = Html::from_string(format!(
        "<style>@page {{ size: 260pt 160pt; margin: 10pt }} body {{ margin:0 }}\
         .flex {{ display:flex; flex-direction:column; align-items:flex-start; width:200pt }}\
         img {{ min-width:20%; min-height:0 }}\
         </style><div class=\"flex\"><img src=\"{image}\"></div>",
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let image = &document.pages[0].images()[0];
    assert!((image.width() - 40.0).abs() < 0.01, "image={image:?}");
    assert!((image.height() - 100.0).abs() < 0.01, "image={image:?}");
}

#[tokio::test]
async fn inline_floated_image_is_removed_from_text_flow_and_shifted_right() {
    let document = Html::from_string(
        "<style>@page { size: 260pt 100pt; margin: 10pt } body { margin: 0; font-size: 10pt; line-height: 10pt } div { width: 200pt; height: 22pt } img { width: 10pt; height: 20pt; border: 1pt dotted green; float: right }</style>\
         <div>some words <img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC\"></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let text = document.pages[0]
        .lines()
        .iter()
        .find(|line| line.text == "some words")
        .unwrap();
    let image = &document.pages[0].images()[0];
    assert!((text.x() - 10.0).abs() < 0.01);
    assert!((image.x() - 199.0).abs() < 0.01);
}

#[tokio::test]
async fn inline_block_before_right_float_stays_on_same_line() {
    let document = Html::from_string(
        "<!DOCTYPE html><meta charset=\"utf-8\">\
         <style>\
         @page { size: 900px 600px; margin: 0 }\
         body { margin: 0 }\
         .container { width: 100px; height: 100px; background-color: red }\
         .inline-block { display: inline-block; width: 50px; height: 100px; background-color: green }\
         .float-right { float: right; width: 50px; height: 100px; background-color: green }\
         .float-left { width: 30px; height: 50px; clear: both; float: left }\
         </style>\
         <div class=\"container\"><div class=\"inline-block\"></div><div class=\"float-right\"></div><div class=\"float-left\"></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("container background should paint");
    assert!((red.width() - 75.0).abs() < 0.01, "red={red:?}");
    assert!((red.height() - 75.0).abs() < 0.01, "red={red:?}");

    let mut green = page
        .rects()
        .iter()
        .filter(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .collect::<Vec<_>>();
    green.sort_by(|left, right| left.x().total_cmp(&right.x()));

    assert_eq!(green.len(), 2, "green rects={green:?}");
    let left = green[0];
    let right = green[1];
    for rect in [left, right] {
        assert!((rect.width() - 37.5).abs() < 0.01, "green={rect:?}");
        assert!((rect.height() - 75.0).abs() < 0.01, "green={rect:?}");
        assert!(
            (rect.y() - red.y()).abs() < 0.01,
            "red={red:?} green={rect:?}"
        );
    }
    assert!(
        (left.x() - red.x()).abs() < 0.01,
        "left={left:?} red={red:?}"
    );
    assert!(
        ((right.x() + right.width()) - (red.x() + red.width())).abs() < 0.01,
        "right={right:?} red={red:?}"
    );
}

/// A non-fragmentable atomic inline that cannot fit in the residual band beside
/// a float moves to the first later slab where its complete margin box fits.
/// CSS 2.2 §9.5 requires this line-box retry before `text-align` is applied.
#[tokio::test]
async fn atomic_inline_moves_below_float_when_shortened_line_cannot_contain_it() {
    let document = Html::from_string(
        "<!DOCTYPE html><meta charset=\"utf-8\">\
         <style>\
         @page { size: 200px 120px; margin: 0 }\
         body { margin: 0 }\
         .outer { float: left; width: 4px; background: red }\
         .float { float: right; width: 50px; height: 20px; background: orange }\
         .center-parent { width: 100px; margin-left: -48px; text-align: center; background: yellow }\
         .atom { display: inline-block; width: 50px; height: 10px; background: lime }\
         </style>\
         <div class=\"outer\"><div class=\"float\"></div><div class=\"center-parent\"><div class=\"atom\"></div></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let float = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 165, 0)))
        .expect("right float should paint");
    let parent = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 255, 0)))
        .expect("center parent should paint");
    let atom = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 255, 0)))
        .expect("atomic inline should paint");

    assert!(
        atom.y() + atom.height() <= float.y() + 0.01,
        "atomic inline must move below the constraining float: float={float:?}, parent={parent:?}, atom={atom:?}"
    );
    assert!(
        ((atom.x() + atom.width() * 0.5) - (parent.x() + parent.width() * 0.5)).abs() < 0.01,
        "the retried line must be centered in the parent's full measure: parent={parent:?}, atom={atom:?}"
    );
}

/// An established float marker in an anonymous run does not make its following
/// atomic inline part of the source-order float transaction. The atom is
/// normal-flow content and must retry below the float when its full margin box
/// cannot fit in the residual band.
/// CSS 2.2 §9.5 applies after block-in-inline normalization.
#[tokio::test]
async fn atomic_inline_after_block_in_inline_and_intervening_float_clears_float() {
    let document = Html::from_string(
        "<!DOCTYPE html><meta charset=\"utf-8\">\
         <style>\
         @page { size: 160px 220px; margin: 0 }\
         body { margin: 0 }\
         .container { width: 100px }\
         .first { width: 100px; height: 10px; margin-bottom: 50px; background: blue }\
         .intervening { float: left; width: 90px; height: 50px; background: green }\
         .atomic { display: inline-block; width: 50px; height: 10px; vertical-align: top; background: orange }\
         </style>\
         <div class=\"container\"><span><div class=\"first\"></div></span><div class=\"intervening\"></div><span class=\"atomic\"></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("the preceding block should paint");
    let float = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .expect("the intervening float should paint");
    let atom = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 165, 0)))
        .expect("the atomic inline should paint");

    assert!(
        (atom.x() - blue.x()).abs() < 0.01,
        "the retried atom must use the container's inline start: blue={blue:?}, float={float:?}, atom={atom:?}"
    );
    assert!(
        atom.y() + atom.height() <= float.y() + 0.01,
        "the atom must move below the intervening float: blue={blue:?}, float={float:?}, atom={atom:?}"
    );
}

/// An atomic inline that does fit in the shortened band remains beside its
/// preceding float; CSS 2.2's retry is not an unconditional float clear.
#[tokio::test]
async fn fitting_atomic_inline_remains_beside_float() {
    let document = Html::from_string(
        "<!DOCTYPE html><meta charset=\"utf-8\">\
         <style>\
         @page { size: 200px 120px; margin: 0 }\
         body { margin: 0 }\
         .outer { float: left; width: 4px; background: red }\
         .float { float: right; width: 50px; height: 20px; background: orange }\
         .center-parent { width: 100px; margin-left: -48px; text-align: center; background: yellow }\
         .atom { display: inline-block; width: 10px; height: 10px; background: lime }\
         </style>\
         <div class=\"outer\"><div class=\"float\"></div><div class=\"center-parent\"><div class=\"atom\"></div></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let float = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 165, 0)))
        .expect("right float should paint");
    let atom = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 255, 0)))
        .expect("atomic inline should paint");

    assert!(
        atom.y() + atom.height() > float.y() + 0.01,
        "a fitting atomic inline must remain in the shortened band: float={float:?}, atom={atom:?}"
    );
}

/// A parent float shortens the outer centered line once, but cannot become an
/// exclusion while intrinsic sizing the atomic inline-block that line contains.
/// CSS 2.2 §9.4.1 gives inline-blocks an independent BFC.
#[tokio::test]
async fn inline_block_intrinsic_layout_does_not_inherit_parent_float_clearance() {
    let document = Html::from_string(
        "<!DOCTYPE html><meta charset=\"utf-8\">\
         <style>\
         @page { size: 240px 500px; margin: 0 }\
         body { margin: 0; font-family: sans-serif; font-size: 10px }\
         .outer { float: left; width: 4px }\
         .float, .atom { clear: both; margin: 1px 2px 3px 4px; border-width: 2px 3px 4px 5px; border-style: solid; padding: 3px 4px 5px 6px }\
         .left { float: left; background: red }\
         .right { float: right; background: orange }\
         .big { font-size: 18px; width: 50px }\
         .center-parent { width: 100px; margin-left: -48px; text-align: center }\
         .control-parent { clear: both; width: 100px; text-align: center }\
         .atom { display: inline-block; text-align: left }\
         #first { background: rgb(10, 20, 30) }\
         #second { background: rgb(40, 50, 60) }\
         #control { background: rgb(70, 80, 90) }\
         </style>\
         <div class=\"outer\">\
           <div class=\"float left\">start</div><div class=\"float left big\">a b</div>\
           <div class=\"float right\">end</div><div class=\"float right big\">a b</div>\
           <div class=\"center-parent\"><span id=\"first\" class=\"atom\">center</span></div>\
           <div class=\"center-parent\"><span id=\"second\" class=\"atom\">center</span></div>\
         </div>\
         <div class=\"control-parent\"><span id=\"control\" class=\"atom\">center</span></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let rect_with_fill = |fill| {
        page.rects()
            .iter()
            .find(|rect| rect.fill == Some(fill))
            .expect("expected colored atomic inline-block background")
    };
    let first = rect_with_fill(CssColor::new(10, 20, 30));
    let second = rect_with_fill(CssColor::new(40, 50, 60));
    let control = rect_with_fill(CssColor::new(70, 80, 90));

    assert!(
        (first.height() - control.height()).abs() < 0.01,
        "the parent float must not inflate the first atom's intrinsic height: first={first:?}, control={control:?}"
    );
    assert!(
        (second.height() - control.height()).abs() < 0.01,
        "the parent float must not inflate the second atom's intrinsic height: second={second:?}, control={control:?}"
    );
    // The atom's authored 1px + 3px vertical margins are 3pt in the PDF
    // coordinate system, so consecutive parent lines advance by its margin box.
    let first_margin_box_height = first.height() + 3.0;
    assert!(
        ((first.y() - second.y()).abs() - first_margin_box_height).abs() < 0.01,
        "the second in-flow atom must begin after normal single-line progression, without an additional parent-float clearance: first={first:?}, second={second:?}"
    );
}

#[tokio::test]
async fn zero_height_float_does_not_shorten_same_top_line_box() {
    let document = Html::from_string(
        "<!DOCTYPE html>\
         <style>@page { size: 160px 140px; margin: 0 } body { margin: 0 }</style>\
         <div style=\"width: 100px; height: 100px; background: red; position: relative;\">\
           <div style=\"float: left; width: 20px;\"></div>\
           <div style=\"line-height: 0;\">\
             <div style=\"display: inline-block; width: 100px; height: 20px; background: green;\"></div>\
           </div>\
           <div style=\"float: right; width: 20px; height: 80px; background: green;\"></div>\
           <div style=\"float: right; clear: right; width: 30px; clear: right;\"></div>\
           <div style=\"display: inline-block; width: 60px; height: 60px; background: green;\"></div>\
           <div style=\"position: absolute; width: 20px; height: 80px; background: green; top: 20px; right: 20px;\"></div>\
           <div style=\"position: absolute; width: 60px; height: 20px; background: green; bottom: 0; left: 0;\"></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("container background should paint");
    assert!((red.width() - 75.0).abs() < 0.01, "red={red:?}");
    assert!((red.height() - 75.0).abs() < 0.01, "red={red:?}");

    let top_strip = page
        .rects()
        .iter()
        .find(|rect| {
            rect.fill == Some(CssColor::new(0, 128, 0))
                && (rect.width() - 75.0).abs() < 0.01
                && (rect.height() - 15.0).abs() < 0.01
        })
        .expect("top green strip should paint");
    assert!(
        (top_strip.x() - red.x()).abs() < 0.01,
        "zero-height left float should not offset the top strip: top={top_strip:?} red={red:?}"
    );
    let lower_left = page
        .rects()
        .iter()
        .find(|rect| {
            rect.fill == Some(CssColor::new(0, 128, 0))
                && (rect.width() - 45.0).abs() < 0.01
                && (rect.height() - 45.0).abs() < 0.01
        })
        .expect("lower-left inline-block should paint");
    assert!(
        (lower_left.x() - red.x()).abs() < 0.01,
        "lower={lower_left:?}"
    );
    assert!(
        (lower_left.y() - (red.y() + 15.0)).abs() < 0.01,
        "lower-left inline-block should occupy the lower-left band: lower={lower_left:?} red={red:?}"
    );
}

#[tokio::test]
async fn inline_block_intrinsic_width_uses_own_definite_height_for_percentage_canvas() {
    let document = Html::from_string(
        "<!DOCTYPE html>\
         <title>Intrinsic size of an atomic inline with an anonymous block</title>\
         <style>\
         @page { size: 300px 220px; margin: 0 }\
         body { margin: 0 }\
         #test {\
           display: inline-block;\
           height: 100px;\
           background: green;\
         }\
         #test > canvas {\
           height: 100%;\
           background: red;\
           position: relative;\
           z-index: -1;\
         }\
         </style>\
         <div id=\"test\"><canvas width=\"10\" height=\"10\"></canvas><p></p></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("inline-block background should paint");
    assert!((green.width() - 75.0).abs() < 0.01, "green={green:?}");
    assert!((green.height() - 75.0).abs() < 0.01, "green={green:?}");

    let red = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
        .expect("canvas background should paint behind green");
    assert!((red.width() - 75.0).abs() < 0.01, "red={red:?}");
    assert!((red.height() - 75.0).abs() < 0.01, "red={red:?}");
    assert!(
        first_rect_paint_operation_index(page, CssColor::new(255, 0, 0))
            < first_rect_paint_operation_index(page, CssColor::new(0, 128, 0)),
        "the negative-z canvas must paint before the inline-block's in-flow background: {:?}",
        page.paint_operations()
    );
}

#[tokio::test]
async fn abspos_intrinsic_width_uses_own_definite_height_for_percentage_canvas() {
    let document = Html::from_string(
        "<!DOCTYPE html>\
         <style>\
         @page { size: 300px 220px; margin: 0 }\
         body { margin: 0 }\
         #container { position: relative; height: 200px }\
         #abs { position: absolute; top: 0; bottom: 100px; background: green }\
         canvas { height: 100% }\
         </style>\
         <div id=\"container\"><div id=\"abs\"><canvas width=\"10\" height=\"10\"></canvas></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("absolute positioned background should paint");
    assert!((green.width() - 75.0).abs() < 0.01, "green={green:?}");
    assert!((green.height() - 75.0).abs() < 0.01, "green={green:?}");
}

#[tokio::test]
async fn orthogonal_abspos_canvas_static_top_keeps_physical_top_edge() {
    for writing_mode in ["vertical-lr", "vertical-rl"] {
        let document = Html::from_string(format!(
            "<!DOCTYPE html>\
             <style>\
             @page {{ size: 300px 220px; margin: 0 }}\
             body {{ margin: 0 }}\
             #container {{ position: relative; width: 200px; height: 200px }}\
             #abs {{ writing-mode: {writing_mode}; position: absolute; left: 0; right: 100px; background: green }}\
             canvas {{ width: 100% }}\
             </style>\
             <div id=\"container\"><div id=\"abs\"><canvas width=\"10\" height=\"10\"></canvas></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)))
            .unwrap_or_else(|| {
                panic!("absolute positioned background should paint in {writing_mode}")
            });
        assert!(
            (green.width() - 75.0).abs() < 0.01,
            "green={green:?} writing-mode={writing_mode}"
        );
        assert!(
            (green.height() - 75.0).abs() < 0.01,
            "green={green:?} writing-mode={writing_mode}"
        );
        assert!(
            (green.y() + green.height() - page.height()).abs() < 0.01,
            "orthogonal abspos should keep its static top edge: green={green:?} writing-mode={writing_mode}"
        );
    }
}

#[tokio::test]
async fn orthogonal_abspos_block_content_static_top_keeps_physical_top_edge() {
    for writing_mode in ["vertical-lr", "vertical-rl"] {
        let document = Html::from_string(format!(
            "<!DOCTYPE html>\
             <style>\
             @page {{ size: 300px 220px; margin: 0 }}\
             body {{ margin: 0 }}\
             #container {{ position: relative; width: 200px; height: 200px }}\
             #abs {{ writing-mode: {writing_mode}; position: absolute; left: 0; right: 100px; height: 100px; background: green }}\
             #abs > div {{ width: 40px; height: 40px }}\
             </style>\
             <div id=\"container\"><div id=\"abs\"><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)))
            .unwrap_or_else(|| {
                panic!("absolute positioned background should paint in {writing_mode}")
            });
        assert!(
            (green.width() - 75.0).abs() < 0.01,
            "green={green:?} writing-mode={writing_mode}"
        );
        assert!(
            (green.height() - 75.0).abs() < 0.01,
            "green={green:?} writing-mode={writing_mode}"
        );
        assert!(
            (green.y() + green.height() - page.height()).abs() < 0.01,
            "orthogonal abspos block content should keep its static top edge: green={green:?} writing-mode={writing_mode}"
        );
    }
}

#[tokio::test]
async fn auto_height_inline_block_masks_ancestor_height_for_percentage_canvas() {
    let document = Html::from_string(
        "<!DOCTYPE html>\
         <style>\
         @page { size: 300px 220px; margin: 0 }\
         body { margin: 0 }\
         #outer { height: 100px }\
         #test { display: inline-block; background: green }\
         #test > canvas { height: 100%; background: red }\
         </style>\
         <div id=\"outer\"><div id=\"test\"><canvas width=\"10\" height=\"10\"></canvas><p></p></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("canvas background should paint");
    assert!(
        (red.width() - 7.5).abs() < 0.01,
        "auto-height inline-block should not provide the ancestor's height as canvas percentage basis: {red:?}"
    );
    assert!(
        (red.height() - 7.5).abs() < 0.01,
        "auto-height inline-block should leave percentage canvas height unresolved: {red:?}"
    );
}

#[tokio::test]
async fn overflow_scroll_float_preserves_later_inline_block_paint_order() {
    let document = Html::from_string(
        "<!DOCTYPE html>\
         <title>Overflow:scroll floating paint order</title>\
         <style>\
         @page { size: 300px 200px; margin: 0 }\
         body { margin: 0 }\
         #scroller {\
           float: left;\
           background: red;\
           padding: 20px;\
           box-sizing: border-box;\
           width: 100px;\
           height: 100px;\
           overflow: scroll;\
         }\
         #negative-margin {\
           float: left;\
           width: 100px;\
           height: 100px;\
           background: green;\
           margin-left: -100px;\
         }\
         #foreground1, #foreground2 {\
           display: inline-block;\
           width: 50px;\
           height: 50px;\
         }\
         #foreground1 { background: blue }\
         #foreground2 { background: magenta }\
         </style>\
         <div id=\"scroller\">\
           <div style=\"height: 200px; background: yellow\">\
             <div id=\"foreground1\"></div>\
           </div>\
         </div>\
         <div id=\"negative-margin\">\
           <div id=\"foreground2\"></div>\
         </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 yellow = first_rect_paint_operation_index(page, CssColor::new(255, 255, 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 magenta = first_rect_paint_operation_index(page, CssColor::new(255, 0, 255));

    assert!(
        red < yellow,
        "scroller background should paint before child background"
    );
    assert!(
        yellow < blue,
        "scroller child background should paint before foreground1"
    );
    assert!(
        blue < green,
        "earlier float contents should paint before later float background"
    );
    assert!(
        green < magenta,
        "later float background should paint before foreground2"
    );
    assert_eq!(
        final_rect_fill_at(page, 10.0, 140.0),
        Some(CssColor::new(255, 0, 255))
    );
}

#[tokio::test]
async fn inline_text_after_left_float_uses_float_exclusion_and_line_end_tracking() {
    let document = Html::from_string(
        "<style>\
         @page { size: 300pt 160pt; margin: 20pt }\
         body, div { margin: 0 }\
         div { font-family: monospace; font-size: 30pt; line-height: 30pt }\
         span { float: left; letter-spacing: 1ch }\
         </style>\
         <div>12345</div><div><span>aa</span>a</div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let lines = &document.pages[0].lines();
    let ruler = lines.iter().find(|line| line.text == "12345").unwrap();
    let floated = lines.iter().find(|line| line.text == "aa").unwrap();
    let following = lines
        .iter()
        .filter(|line| line.text == "a")
        .max_by(|left, right| {
            left.x()
                .partial_cmp(&right.x())
                .unwrap_or(std::cmp::Ordering::Equal)
        })
        .unwrap();
    let ch = rendered_line_advance(ruler) / 5.0;

    assert!((floated.x() - ruler.x()).abs() < 0.01);
    assert!(
        (following.x() - (ruler.x() + ch * 3.0)).abs() < ch * 0.2,
        "expected following a under the fourth ruler column: ruler x={}, ch={}, following x={}",
        ruler.x(),
        ch,
        following.x()
    );
}

#[tokio::test]
async fn block_image_avoids_active_left_float() {
    let document = Html::from_string(
        "<style>@page { size: 160pt 120pt; margin: 10pt } body { margin: 0 }\
         .float { float: left; width: 30pt; height: 30pt; background: green }\
         img { display: block; width: 20pt; height: 10pt }</style>\
         <div class=\"float\"></div><img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC\">",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let image = &document.pages[0].images()[0];
    assert!(
        image.x() >= 39.0,
        "block image should avoid active float: {image:?}"
    );
}

#[tokio::test]
async fn overflow_hidden_bfc_border_box_avoids_left_float_in_rtl() {
    let document = Html::from_string(
        "<!DOCTYPE html>\
         <style>@page { size: 120px 120px; margin: 0 } body { margin: 0 }</style>\
         <div style=\"width: 100px; height: 100px; background: red; direction: rtl;\">\
           <div style=\"float: left; width: 50px; height: 100px; background: green;\"></div>\
           <div style=\"overflow: hidden; height: 100px; margin-left: -20px; background: green;\"></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("container background should paint");
    assert!((red.width() - 75.0).abs() < 0.01, "red={red:?}");
    assert!((red.height() - 75.0).abs() < 0.01, "red={red:?}");

    let mut green_rects = page
        .rects()
        .iter()
        .filter(|rect| {
            rect.fill == Some(CssColor::new(0, 128, 0)) && (rect.height() - 75.0).abs() < 0.01
        })
        .collect::<Vec<_>>();
    green_rects.sort_by(|left, right| left.x().total_cmp(&right.x()));

    assert_eq!(green_rects.len(), 2, "green rects={green_rects:?}");
    let left_green = green_rects[0];
    let right_green = green_rects[1];
    assert!((left_green.x() - red.x()).abs() < 0.01, "{left_green:?}");
    assert!((left_green.width() - 37.5).abs() < 0.01, "{left_green:?}");
    assert!((left_green.y() - red.y()).abs() < 0.01, "{left_green:?}");
    assert!(
        (right_green.x() - (red.x() + 37.5)).abs() < 0.01,
        "{right_green:?}"
    );
    assert!((right_green.width() - 37.5).abs() < 0.01, "{right_green:?}");
    assert!((right_green.y() - red.y()).abs() < 0.01, "{right_green:?}");

    for x in [red.x() + 18.75, red.x() + 56.25] {
        assert_eq!(
            final_rect_fill_at(page, x, red.y() + 37.5),
            Some(CssColor::new(0, 128, 0)),
            "sample at x={x} should be green"
        );
    }
}

#[tokio::test]
async fn overflow_hidden_bfc_reflows_to_avoid_later_float_overlap() {
    let document = Html::from_string(
        "<!DOCTYPE html>\
         <style>@page { size: 300px 180px; margin: 0 } body { margin: 0 }</style>\
         <div style=\"overflow: hidden\">\
           <div style=\"width: 300px; height: 100px; margin-left: -200px; background: red\">\
             <div style=\"float: left; clear: left; width: 100px; height: 25px\"></div>\
             <div style=\"float: left; clear: left; width: 200px; height: 25px\"></div>\
             <div style=\"overflow: hidden; background: green\">\
               <div style=\"float: left; width: 100px; height: 50px\"></div>\
               <div style=\"float: left; width: 100px; height: 50px\"></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("BFC background should paint");

    assert!((green.x() - 0.0).abs() < 0.01, "green={green:?}");
    assert!(
        (green.y() + green.height() - page.height()).abs() < 0.01,
        "BFC should start in the first float-free band, not leave red exposed above it: {green:?}"
    );
    assert!(
        (green.width() - 75.0).abs() < 0.01,
        "BFC should narrow to the final 100px float band: {green:?}"
    );
    assert!(
        (green.height() - 75.0).abs() < 0.01,
        "BFC auto height should reflect its internal floats after narrowing: {green:?}"
    );
    for y in [5.0, 37.5, 70.0] {
        assert_eq!(
            final_rect_fill_at(page, 37.5, green.y() + y),
            Some(CssColor::new(0, 128, 0)),
            "visible BFC area should be green at y={y}: {green:?}"
        );
    }
}

#[tokio::test]
async fn bfc_adjoining_float_top_margin_pulls_float_down_when_it_fits() {
    let document = Html::from_string(
        "<!DOCTYPE html>\
         <style>@page { size: 500px 360px; margin: 0 }</style>\
         <p>Test passes if there is a filled green square and <strong>no red</strong>.</p>\
         <div style=\"overflow:hidden; width:200px; background:green;\">\
           <div style=\"width:300px; margin-top:50px; background:red;\">\
             <div>\
               <div style=\"float:left; width:200px; height:10px; background:green;\"></div>\
             </div>\
             <div style=\"margin-top:190px; overflow:hidden; width:100px; height:10px; background:red;\"></div>\
           </div>\
         </div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let green = CssColor::new(0, 128, 0);
    let bfc_background = page
        .rects()
        .iter()
        .filter(|rect| rect.fill == Some(green))
        .max_by(|left, right| left.height().partial_cmp(&right.height()).unwrap())
        .expect("BFC background should paint");
    assert!(
        (bfc_background.width() - 150.0).abs() < 0.01
            && (bfc_background.height() - 150.0).abs() < 0.01,
        "the BFC should retain the 200px-wide, 200px-tall used box: {bfc_background:?}"
    );
    for x in [24.0, 74.0, 149.0] {
        for y in [
            bfc_background.y() + 24.0,
            bfc_background.y() + 74.0,
            bfc_background.y() + 124.0,
        ] {
            assert_eq!(
                final_rect_fill_at(page, x, y),
                Some(green),
                "sample at ({x}, {y}) should be green; rects={:?} operations={:?}",
                page.rects(),
                page.paint_operations()
            );
        }
    }
}

#[tokio::test]
async fn clear_both_moves_block_image_below_active_float() {
    let document = Html::from_string(
        "<style>@page { size: 120pt 120pt; margin: 10pt } body { margin: 0 }\
         .float { float: left; width: 40pt; height: 20pt; background: green }\
         img { display: block; clear: both; width: 10pt; height: 10pt }</style>\
         <div class=\"float\"></div><img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC\">",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .unwrap();
    let image = &document.pages[0].images()[0];

    assert!(
        image.y() + image.height() <= green.y() + 0.01,
        "clear block image should start below float: green={green:?} image={image:?}"
    );
}

#[tokio::test]
async fn overwide_block_image_moves_below_active_float() {
    let document = Html::from_string(
        "<style>@page { size: 120pt 120pt; margin: 10pt } body { margin: 0 }\
         .float { float: left; width: 30pt; height: 20pt; background: green }\
         img { display: block; width: 90pt; height: 10pt }</style>\
         <div class=\"float\"></div><img src=\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGP4z8AAAAMBAQDJ/pLvAAAAAElFTkSuQmCC\">",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let green = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .unwrap();
    let image = &document.pages[0].images()[0];

    assert!((image.x() - 10.0).abs() < 0.01, "image={image:?}");
    assert!(
        image.y() + image.height() <= green.y() + 0.01,
        "overwide block image should move below float: green={green:?} image={image:?}"
    );
}

#[tokio::test]
async fn block_canvas_and_svg_avoid_active_float() {
    let document = Html::from_string(
        "<style>@page { size: 180pt 140pt; margin: 10pt } body, canvas, svg { margin: 0 }\
         .float { float: left; width: 30pt; height: 40pt; background: green }\
         canvas { display: block; width: 20pt; height: 10pt; background: blue }\
         svg { display: block; width: 20pt; height: 10pt }</style>\
         <div class=\"float\"></div><canvas></canvas><svg><rect width=\"20pt\" height=\"10pt\" fill=\"#ff0000\"></rect></svg>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let blue = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 0, 255)))
        .unwrap();
    let red = document.pages[0]
        .paths()
        .iter()
        .find(|path| path.fill == Some(CssColor::new(255, 0, 0)))
        .unwrap();
    let red_bounds = red.paint_bounds().unwrap();

    assert!(
        blue.x() >= 39.0,
        "block canvas should avoid active float: {blue:?}"
    );
    assert!(
        red_bounds.origin.x >= 39.0,
        "block svg should avoid active float: {red_bounds:?}"
    );
}

#[tokio::test]
async fn flow_root_auto_height_expands_to_contain_internal_float() {
    let document = Html::from_string(
        "<style>\
         @page { size: 160pt 140pt; margin: 10pt }\
         body, div { margin: 0 }\
         .root { display: flow-root; width: 100pt; background: rgb(0 128 0) }\
         .float { float: left; width: 30pt; height: 40pt; background: rgb(0 0 255) }\
         </style>\
         <div class=\"root\"><div class=\"float\"></div></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let root = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .unwrap();

    assert!(
        root.height() >= 39.99,
        "flow-root background should include its internal float: {root:?}"
    );
}

#[tokio::test]
async fn internal_flow_root_float_does_not_leak_to_following_sibling() {
    let document = Html::from_string(
        "<style>\
         @page { size: 160pt 160pt; margin: 10pt }\
         body, div { margin: 0 }\
         .root { display: flow-root; width: 100pt; background: rgb(0 128 0) }\
         .float { float: left; width: 30pt; height: 40pt; background: rgb(0 0 255) }\
         .after { width: 100pt; height: 10pt; background: rgb(255 0 0) }\
         </style>\
         <div class=\"root\"><div class=\"float\"></div></div><div class=\"after\"></div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let root = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(0, 128, 0)))
        .unwrap();
    let after = document.pages[0]
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
        .unwrap();

    assert!(
        after.y() + after.height() <= root.y() + 0.01,
        "following sibling should start below the flow-root: root={root:?} after={after:?}"
    );
}

#[tokio::test]
async fn renders_simple_svg_rects_in_table_cells() {
    let document = Html::from_string(
        "<table style=\"margin:0;width:100pt\"><tr><td><svg width=\"15pt\" height=\"15pt\"><rect width=\"15pt\" height=\"15pt\" fill=\"#2292d4\"></rect></svg></td><td>Half Match</td></tr></table>",
    )
    .render(&RenderOptions::default()).await
    .unwrap();

    assert!(document.pages[0].paths().iter().any(|path| {
        let Some(bounds) = path.paint_bounds() else {
            return false;
        };
        bounds.size.width == 15.0
            && bounds.size.height == 15.0
            && path.fill == Some(CssColor::new(34, 146, 212))
    }));
    let text = document.pages[0]
        .lines()
        .iter()
        .map(|line| line.text.as_str())
        .collect::<Vec<_>>()
        .join(" ");
    assert!(text.contains("Half"));
    assert!(text.contains("Match"));
}

#[tokio::test]
async fn renders_uri_link_annotations() {
    let document = Html::from_string("<a href=\"https://example.com\">Example</a>")
        .render(&RenderOptions::default())
        .await
        .unwrap();

    assert_eq!(document.pages[0].links().len(), 1);
    assert_eq!(
        document.pages[0].links()[0].target.as_ref(),
        "https://example.com"
    );

    let pdf = document
        .write_pdf_bytes(&crate::PdfOptions::default())
        .unwrap();
    let rendered = pdf_searchable_text(&pdf);
    assert!(rendered.contains("/Subtype /Link"));
    assert!(rendered.contains("/URI (https://example.com)"));
    assert!(rendered.contains("/Annots ["));
}

#[tokio::test]
async fn draws_text_decorations() {
    let document = Html::from_string(
        "<p style=\"margin: 0; color: red; text-decoration: underline line-through\">Decorated</p>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert!(document.pages[0].rects().len() >= 2);
    assert!(
        document.pages[0]
            .rects()
            .iter()
            .all(|rect| rect.fill == Some(CssColor::new(255, 0, 0)))
    );
}

#[tokio::test]
async fn vertical_filled_text_emphasis_adds_sesame_marks() {
    let document = Html::from_string(
        "<div style=\"writing-mode: vertical-rl; text-emphasis-style: filled\">試験テスト</div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let lines = document
        .pages
        .iter()
        .flat_map(|page| page.lines())
        .map(|line| line.text.as_str())
        .collect::<Vec<_>>();
    assert!(lines.contains(&"試験テスト"), "{lines:?}");
    assert_eq!(
        lines.iter().filter(|line| **line == "\u{FE45}").count(),
        5,
        "{lines:?}"
    );
}

#[tokio::test]
async fn preserves_basic_styled_inline_runs() {
    let document = Html::from_string(
        "<p style=\"margin:0;font-size:12pt\">A <em>italic</em> <strong>bold</strong> <small>small</small> ref<sup>1</sup></p>",
    )
    .render(&RenderOptions::default()).await
    .unwrap();

    let lines = &document.pages[0].lines();
    assert!(
        lines
            .iter()
            .any(|line| line_run_font_is_italic(&document, line, "italic"))
    );
    assert!(
        lines
            .iter()
            .any(|line| line_run_font_is_bold(&document, line, "bold"))
    );
    assert!(
        lines
            .iter()
            .any(|line| line.text == "small" && (line.font_size - 10.0).abs() < 0.01)
    );

    let reference = lines.iter().find(|line| line.text == "ref").unwrap();
    let superscript = lines.iter().find(|line| line.text == "1").unwrap();
    assert!(superscript.font_size < reference.font_size);
    assert!(superscript.y() > reference.y());
}

#[tokio::test]
async fn supports_authored_vertical_align_super_and_sub() {
    let document = Html::from_string(
        "<p style=\"margin:0;font-size:12pt\">Base<span style=\"vertical-align: super; font-size: 9pt\">up</span><span style=\"vertical-align: sub; font-size: 9pt\">down</span><sup style=\"vertical-align: baseline\">flat</sup></p>",
    )
    .render(&RenderOptions::default()).await
    .unwrap();

    let lines = &document.pages[0].lines();
    let base = lines.iter().find(|line| line.text == "Base").unwrap();
    let up = lines.iter().find(|line| line.text == "up").unwrap();
    let down = lines.iter().find(|line| line.text == "down").unwrap();
    let flat = lines.iter().find(|line| line.text == "flat").unwrap();

    assert!(up.y() > base.y());
    assert!(down.y() < base.y());
    assert!(flat.y() < up.y());
}

#[tokio::test]
async fn regular_inline_top_and_bottom_align_descendant_text_to_line_edges() {
    let document = Html::from_string(
        "<style>\
         @page { size: 240pt 160pt; margin: 20pt }\
         body, p { margin: 0 }\
         .small { font: 10pt/10pt sans-serif }\
         .big { font: 20pt/20pt sans-serif }\
         </style>\
         <p class=\"small\">small<span class=\"big\" style=\"vertical-align:top\">top</span></p>\
         <p class=\"big\">big<span class=\"small\" style=\"vertical-align:bottom\">bottom</span></p>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let lines = &document.pages[0].lines();
    let line = |text: &str| {
        lines
            .iter()
            .find(|line| line.text == text)
            .unwrap_or_else(|| panic!("expected rendered line {text:?}: {lines:?}"))
    };
    let small = line("small");
    let top = line("top");
    let big = line("big");
    let bottom = line("bottom");

    assert!(
        top.y() < small.y() - 4.0,
        "top-aligned descendant should sit above the small baseline sibling: top={top:?}, small={small:?}"
    );
    assert!(
        bottom.y() < big.y() - 2.0,
        "bottom-aligned descendant should sit below the big baseline sibling: bottom={bottom:?}, big={big:?}"
    );
}

#[tokio::test]
async fn nested_regular_inline_top_and_bottom_scopes_are_independent() {
    let document = Html::from_string(
        "<style>\
         @page { size: 240pt 120pt; margin: 20pt }\
         body, p { margin: 0 }\
         .small { font: 10pt/10pt sans-serif }\
         .big { font: 20pt/20pt sans-serif }\
         </style>\
         <p class=\"small\">peer<span class=\"big\" style=\"vertical-align:top\">outer<span class=\"small\" style=\"vertical-align:bottom\">inner</span></span></p>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let lines = &document.pages[0].lines();
    let line = |text: &str| {
        lines
            .iter()
            .find(|line| line.text == text)
            .unwrap_or_else(|| panic!("expected rendered line {text:?}: {lines:?}"))
    };
    let peer = line("peer");
    let outer = line("outer");
    let inner = line("inner");

    assert!(outer.y() < peer.y() - 4.0);
    assert!(
        inner.y() < outer.y() - 2.0,
        "nested bottom scope must not inherit the outer top placement: inner={inner:?}, outer={outer:?}"
    );
}

#[tokio::test]
async fn inline_block_overflow_baseline_uses_css22_fallback_edges() {
    let document = Html::from_string(
        "<style>\
         @page { size: 360pt 360pt; margin: 20pt }\
         body { margin: 0; font: 10pt/10pt sans-serif }\
         .row { margin: 0 0 6pt 0 }\
         .outer { display: inline-block; width: 50pt; padding-bottom: 20pt; vertical-align: baseline }\
         .empty { height: 30pt; margin-bottom: 12pt; padding-bottom: 0; background: rgb(255 0 0) }\
         .empty > div { height: 30pt }\
         .block-text { background: rgb(0 128 0) }\
         .block-text > div { width: 30pt; height: 30pt; overflow: hidden }\
         .self-hidden { height: 30pt; margin-bottom: 12pt; padding-bottom: 0; overflow: hidden; background: rgb(255 0 255) }\
         </style>\
         <div class=\"row\"><div class=\"outer empty\"><div></div></div>EMPTY</div>\
         <div class=\"row\"><div class=\"outer block-text\"><div>INNER</div></div>BLOCK</div>\
         <div class=\"row\"><div class=\"outer self-hidden\">SELF</div>SELFREF</div>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    let line = |text: &str| {
        page.lines()
            .iter()
            .find(|line| line.text == text)
            .unwrap_or_else(|| panic!("expected rendered line {text:?}: {:?}", page.lines()))
    };
    let rect = |color| {
        page.rects()
            .iter()
            .find(|rect| rect.fill == Some(color))
            .unwrap_or_else(|| panic!("expected rect {color:?}: {:?}", page.rects()))
    };

    let empty_outer = rect(CssColor::new(255, 0, 0));
    assert!(
        (line("EMPTY").y() - (empty_outer.y() - 12.0)).abs() < 0.5,
        "inline-block with no in-flow line boxes should use bottom margin edge: rect={empty_outer:?}, line={:?}",
        line("EMPTY")
    );

    assert!(
        (line("BLOCK").y() - line("INNER").y()).abs() < 0.5,
        "visible-overflow inline-block should keep using its last in-flow text baseline: inner={:?}, block={:?}",
        line("INNER"),
        line("BLOCK")
    );

    let self_hidden = rect(CssColor::new(255, 0, 255));
    assert!(
        (line("SELFREF").y() - (self_hidden.y() - 12.0)).abs() < 0.5,
        "overflow:hidden inline-block should ignore its internal text baseline and use bottom margin edge: rect={self_hidden:?}, line={:?}",
        line("SELFREF")
    );
}

#[tokio::test]
async fn vertical_align_length_and_percentage_shift_inline_baselines() {
    let document = Html::from_string(
        "<p style=\"margin:0;font-size:20pt;line-height:20pt\">\
         Base<span style=\"vertical-align:10pt\">up</span>\
         <span style=\"vertical-align:-10pt\">down</span>\
         <span style=\"vertical-align:50%;line-height:20pt\">pct</span></p>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let lines = &document.pages[0].lines();
    let base = lines.iter().find(|line| line.text == "Base").unwrap();
    let up = lines.iter().find(|line| line.text == "up").unwrap();
    let down = lines.iter().find(|line| line.text == "down").unwrap();
    let pct = lines.iter().find(|line| line.text == "pct").unwrap();

    assert!(
        up.y() > base.y() + 9.0,
        "positive vertical-align length should raise the inline box: base={base:?}, up={up:?}"
    );
    assert!(
        down.y() < base.y() - 9.0,
        "negative vertical-align length should lower the inline box: base={base:?}, down={down:?}"
    );
    assert!(
        (pct.y() - up.y()).abs() < 1.0,
        "50% of a 20pt line-height should match a 10pt shift: up={up:?}, pct={pct:?}"
    );
}

#[tokio::test]
async fn baseline_shift_longhand_moves_inline_baselines() {
    let document = Html::from_string(
        "<p style=\"margin:0;font-size:20pt;line-height:20pt\">\
         Base<span style=\"baseline-shift:10pt\">up</span>\
         <span style=\"baseline-shift:-10pt\">down</span>\
         <span style=\"baseline-shift:50%;line-height:20pt\">pct</span></p>",
    )
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let lines = &document.pages[0].lines();
    let base = lines.iter().find(|line| line.text == "Base").unwrap();
    let up = lines.iter().find(|line| line.text == "up").unwrap();
    let down = lines.iter().find(|line| line.text == "down").unwrap();
    let pct = lines.iter().find(|line| line.text == "pct").unwrap();

    assert!(up.y() > base.y() + 9.0);
    assert!(down.y() < base.y() - 9.0);
    assert!((pct.y() - up.y()).abs() < 1.0);
}

#[tokio::test]
async fn baseline_shift_length_percentage_places_text_and_replaced_inline_atoms() {
    let document = Html::from_string(format!(
        "<style>@page {{ size: 260pt 500pt; margin: 20pt }} body {{ margin: 0 }}</style>\
         <span style=\"font:20pt/2 sans-serif\">\
         <img style=\"width:60pt;height:60pt;baseline-shift:0\" src=\"{GREEN_100_PNG}\">\
         <img style=\"width:60pt;height:60pt;baseline-shift:-0.2em\" src=\"{GREEN_100_PNG}\">\
         <span style=\"baseline-shift:0\">ZERO</span>\
         <span style=\"baseline-shift:1em\">UP</span>\
         <span style=\"baseline-shift:-100%\">DOWN</span>\
         <br><span>NEXT</span></span>"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    let page = &document.pages[0];
    assert_eq!(page.images().len(), 2, "images={:?}", page.images());
    let baseline_image = &page.images()[0];
    let shifted_image = &page.images()[1];
    let line = |text: &str| {
        page.lines()
            .iter()
            .find(|line| line.text == text)
            .unwrap_or_else(|| panic!("expected line {text:?}: {:?}", page.lines()))
    };
    let zero = line("ZERO");
    let up = line("UP");
    let down = line("DOWN");
    let next = line("NEXT");

    assert!(
        (up.y() - zero.y() - 20.0).abs() < 1.0,
        "1em baseline-shift should raise text by 20pt: zero={zero:?}, up={up:?}"
    );
    assert!(
        (down.y() - zero.y() + 40.0).abs() < 1.0,
        "-100% baseline-shift should lower text by one 40pt line-height: zero={zero:?}, down={down:?}"
    );
    assert!(
        (shifted_image.y() - baseline_image.y() + 4.0).abs() < 1.0,
        "-0.2em baseline-shift should lower the replaced atom by 4pt: baseline_y={}, shifted_y={}",
        baseline_image.y(),
        shifted_image.y()
    );
    assert!(
        zero.y() - next.y() > 60.0,
        "line advance should include shifted first-line bounds: zero={zero:?}, next={next:?}"
    );
}

/// A root pseudo keeps its computed horizontal style, but must still consume
/// the propagated body's vertical-lr principal block track before the body
/// starts.
/// <https://www.w3.org/TR/css-writing-modes-4/#principal-flow>
#[tokio::test]
async fn root_before_advances_a_propagated_vertical_lr_body() {
    let document = Html::from_string(format!(
        "<style>
           @page {{ size: 300pt 200pt; margin: 0 }}
           html {{ writing-mode: horizontal-tb }}
           html::before {{
             background: orange;
             content: \"\";
             display: block;
             height: 75pt;
             margin-left: 6pt;
             margin-right: 12pt;
             margin-top: 6pt;
             width: 75pt;
           }}
           body {{ margin: 0; writing-mode: vertical-lr }}
           img {{ display: block; height: 30pt; width: 100pt }}
         </style>
         <div><img src=\"{GREEN_100_PNG}\"></div>"
    ))
    .render(&RenderOptions::default())
    .await
    .unwrap();

    assert_eq!(document.pages.len(), 1, "document={document:?}");
    let page = &document.pages[0];
    let pseudo = page
        .rects()
        .iter()
        .find(|rect| rect.fill == Some(CssColor::new(255, 165, 0)))
        .expect("expected the root ::before block");
    let image = page
        .images()
        .first()
        .expect("expected propagated body image");

    assert!((pseudo.x() - 6.0).abs() < 0.01, "pseudo={pseudo:?}");
    assert!(
        ((image.x() - (pseudo.x() + pseudo.width() + 6.0)).abs()) < 0.01,
        "the body must begin from the root track advanced by the pseudo's border box and block-end margin: pseudo={pseudo:?}, image={image:?}"
    );
}