spindrift 0.1.0

A HTML/CSS to PDF renderer, targeting spec compliance and efficiency
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};

use super::*;
use crate::dom::ElementId;
use crate::layout::assets::DocumentPageIndex;
use crate::layout::text_paint::TextInlineSpan;

#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct PositionedPaintLayer {
    pub(in crate::layout) page_index: usize,
    /// The positioned-paint transaction that still owns this layer's scratch
    /// fragmentainers. A nonzero depth may not be flushed into a document
    /// page until the owning transaction restores its parent state.
    pub(in crate::layout) transaction_depth: usize,
    /// Source element for layers built by the ordinary positioned-box path.
    /// Re-entering that path replaces stale provisional layout for the same
    /// element and final page.
    pub(in crate::layout) source_element: Option<crate::dom::ElementId>,
    /// The originating box's computed style is retained with the final
    /// page-space stacking context so enclosing scroll containers can form
    /// snap areas only after positioned remapping is complete.
    pub(in crate::layout) source_style: ComputedStyle,
    /// Runtime identity of this independently constructed layout instance.
    /// Semantic box identity distinguishes generated siblings; this retains
    /// distinct speculative/committed captures until replay selects the final
    /// fragment.
    pub(in crate::layout) source_style_identity: usize,
    /// Semantic element box that produced this positioned principal.
    /// Principal and generated boxes share an `ElementId`, so duplicate
    /// suppression must retain this role rather than infer identity from a
    /// temporary computed-style address.
    pub(in crate::layout) source_box: InlineStaticPositionBoxSource,
    /// Distinguishes independently clipped continuations of one positioned
    /// principal in a multicolumn fragmentainer sequence.
    pub(in crate::layout) multicol_fragment_index: Option<usize>,
    pub(in crate::layout) source_is_target: bool,
    pub(in crate::layout) stack_level: StackLevel,
    pub(in crate::layout) context: PaintStackingContext,
    pub(in crate::layout) links: Vec<RenderedLink>,
    pub(in crate::layout) escaped_atom_replay: EscapedAtomReplay,
    /// The containing-block stack entry that owns this out-of-flow layer.
    ///
    /// `None` denotes an escaped normal-flow paint context, which remains
    /// subject to every ancestor overflow clip. Positioned layers retain the
    /// selected stack depth so a deferred clip can determine whether it lies
    /// between the positioned descendant and its containing block.
    /// <https://www.w3.org/TR/CSS22/visufx.html#overflow-clipping>
    pub(in crate::layout) overflow_clip_containing_block:
        Option<PositionedContainingBlockScopeDepth>,
}

/// Containing-block ancestry relevant to overflow clipping of one positioned
/// paint layer.
///
/// Absolute and fixed positioning use distinct containing-block stacks. The
/// depth is recorded at selection time, while the corresponding ancestor box
/// records the stack depths at which its contents began.
/// <https://www.w3.org/TR/css-position-3/#def-cb>
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum PositionedContainingBlockScopeDepth {
    Absolute(usize),
    Fixed(usize),
}

/// Positioned containing-block ancestry visible at the start of an in-flow
/// box's contents.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) struct PositionedOverflowClipBoundary {
    absolute_depth: usize,
    fixed_depth: usize,
}

impl PositionedOverflowClipBoundary {
    pub(in crate::layout) const fn new(absolute_depth: usize, fixed_depth: usize) -> Self {
        Self {
            absolute_depth,
            fixed_depth,
        }
    }

    /// Whether this ancestor may clip or scroll the escaped layer.
    ///
    /// CSS 2.2 excludes overflow clipping by an ancestor between an absolutely
    /// positioned descendant and its containing block. A containing block
    /// established by this box or one of its descendants has a greater stack
    /// depth and therefore remains subject to the box's overflow effects.
    /// <https://www.w3.org/TR/CSS22/visufx.html#overflow-clipping>
    pub(in crate::layout) const fn applies_to(self, layer: &PositionedPaintLayer) -> bool {
        self.applies_to_containing_block(layer.overflow_clip_containing_block)
    }

    const fn applies_to_containing_block(
        self,
        containing_block: Option<PositionedContainingBlockScopeDepth>,
    ) -> bool {
        match containing_block {
            None => true,
            Some(PositionedContainingBlockScopeDepth::Absolute(depth)) => {
                depth > self.absolute_depth
            }
            Some(PositionedContainingBlockScopeDepth::Fixed(depth)) => depth > self.fixed_depth,
        }
    }
}

#[cfg(test)]
mod positioned_overflow_clip_boundary_tests {
    use super::*;

    #[test]
    fn clip_applies_only_when_the_containing_block_is_inside_its_boundary() {
        let boundary = PositionedOverflowClipBoundary::new(2, 3);

        assert!(boundary.applies_to_containing_block(None));
        assert!(
            !boundary.applies_to_containing_block(Some(
                PositionedContainingBlockScopeDepth::Absolute(2),
            ))
        );
        assert!(
            boundary.applies_to_containing_block(Some(
                PositionedContainingBlockScopeDepth::Absolute(3),
            ))
        );
        assert!(
            !boundary
                .applies_to_containing_block(Some(PositionedContainingBlockScopeDepth::Fixed(3),))
        );
        assert!(
            boundary
                .applies_to_containing_block(Some(PositionedContainingBlockScopeDepth::Fixed(4),))
        );
    }
}

/// Runtime identity for one page-local positioned principal. Rust ownership
/// proves a captured paint record is consumed once; speculative layout can
/// still independently construct the same logical record, so final commit
/// asserts this key is unique.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(in crate::layout) struct PositionedPaintCommitKey {
    source_element: crate::dom::ElementId,
    source_box: InlineStaticPositionBoxSource,
    source_style_identity: usize,
    multicol_fragment_index: Option<usize>,
}

impl PositionedPaintLayer {
    pub(in crate::layout) fn commit_key(&self) -> Option<PositionedPaintCommitKey> {
        self.source_element
            .map(|source_element| PositionedPaintCommitKey {
                source_element,
                source_box: self.source_box,
                source_style_identity: self.source_style_identity,
                multicol_fragment_index: self.multicol_fragment_index,
            })
    }

    pub(in crate::layout) fn with_multicol_fragment_index(mut self, index: usize) -> Self {
        self.multicol_fragment_index = Some(index);
        self
    }

    pub(in crate::layout) fn translated(mut self, offset: PaintTranslation) -> Self {
        self.context = self.context.translated(offset);
        self.links = self
            .links
            .into_iter()
            .map(|link| link.translated(offset))
            .collect();
        self
    }
}

/// How an escaped positioned layer from an atomic inline should be translated.
///
/// CSS 2.2 lays out `inline-block` contents in a separate formatting context,
/// but positioned descendants whose containing block is outside that
/// inline-block still escape to the ancestor stacking context. Auto insets use
/// the inline-block-local static-position rectangle, while explicit insets are
/// already resolved in page coordinates and must not be translated by the
/// atom's final line position:
/// <https://www.w3.org/TR/CSS22/visuren.html#inline-blocks> and
/// <https://www.w3.org/TR/CSS22/visudet.html#abs-non-replaced-width>.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) enum EscapedAtomAxisReplay {
    RetainPageCoordinate,
    FollowAtomicInline,
}

/// Horizontal source used when an escaped positioned layer follows its atom.
///
/// Page-owned automatic coordinates were resolved relative to their page
/// containing block and must first be normalized from that origin. Atom-owned
/// coordinates already belong to the scratch atomic formatting context, so
/// replacing its capture origin with an intermediate containing-block origin
/// would discard positioned-ancestor displacement.
/// <https://drafts.csswg.org/css-position-3/#staticpos-rect>
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) enum EscapedAtomHorizontalReplay {
    RetainPageCoordinate,
    FollowFromAtomicCapture,
    FollowFromPageContainingBlock(PageInlinePosition),
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct EscapedAtomReplayPolicy {
    pub(in crate::layout) horizontal: EscapedAtomHorizontalReplay,
    pub(in crate::layout) vertical: EscapedAtomAxisReplay,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct EscapedAtomReplayTransform {
    pub(in crate::layout) source_origin: PaintPoint,
    pub(in crate::layout) horizontal: EscapedAtomAxisReplay,
    pub(in crate::layout) vertical: EscapedAtomAxisReplay,
}

#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub(in crate::layout) enum EscapedAtomReplay {
    #[default]
    RetainPageCoordinates,
    Pending(EscapedAtomReplayPolicy),
    Resolved(EscapedAtomReplayTransform),
}

impl EscapedAtomReplay {
    pub(in crate::layout) fn none() -> Self {
        Self::default()
    }

    /// Translate a deferred normal-flow fragment out of an atomic inline's
    /// temporary formatting context and into the final inline line box.
    ///
    /// Relative positioning does not change a box's layout-space origin, but
    /// its retained paint still uses that origin. Both physical axes must
    /// therefore follow the atom when the fragment escapes the temporary
    /// inline-block page.
    /// <https://www.w3.org/TR/css-position-3/#relative-positioning>
    pub(in crate::layout) fn normal_flow_fragment() -> Self {
        Self::Pending(EscapedAtomReplayPolicy {
            horizontal: EscapedAtomHorizontalReplay::FollowFromAtomicCapture,
            vertical: EscapedAtomAxisReplay::FollowAtomicInline,
        })
    }

    pub(in crate::layout) fn for_positioned_box(
        containing_block: ContainingBlock,
        containing_block_is_atom_local: bool,
        uses_static_x: bool,
        uses_static_y: bool,
    ) -> Self {
        let follows_y = containing_block_is_atom_local || uses_static_y;
        Self::Pending(EscapedAtomReplayPolicy {
            horizontal: if containing_block_is_atom_local {
                EscapedAtomHorizontalReplay::FollowFromAtomicCapture
            } else if uses_static_x {
                EscapedAtomHorizontalReplay::FollowFromPageContainingBlock(PageInlinePosition::new(
                    containing_block.x(),
                ))
            } else {
                EscapedAtomHorizontalReplay::RetainPageCoordinate
            },
            vertical: if follows_y {
                EscapedAtomAxisReplay::FollowAtomicInline
            } else {
                EscapedAtomAxisReplay::RetainPageCoordinate
            },
        })
    }

    pub(in crate::layout) fn resolve_from_capture_origin(self, capture_origin: PaintPoint) -> Self {
        match self {
            Self::Pending(policy) => {
                let (horizontal, source_x) = match policy.horizontal {
                    EscapedAtomHorizontalReplay::RetainPageCoordinate => (
                        EscapedAtomAxisReplay::RetainPageCoordinate,
                        capture_origin.x,
                    ),
                    EscapedAtomHorizontalReplay::FollowFromAtomicCapture => {
                        (EscapedAtomAxisReplay::FollowAtomicInline, capture_origin.x)
                    }
                    EscapedAtomHorizontalReplay::FollowFromPageContainingBlock(origin) => {
                        (EscapedAtomAxisReplay::FollowAtomicInline, origin.points())
                    }
                };
                Self::Resolved(EscapedAtomReplayTransform {
                    source_origin: PaintPoint::new(source_x, capture_origin.y),
                    horizontal,
                    vertical: policy.vertical,
                })
            }
            Self::RetainPageCoordinates | Self::Resolved(_) => self,
        }
    }

    pub(in crate::layout) fn translation_to(self, final_origin: PaintPoint) -> PaintTranslation {
        debug_assert!(
            !matches!(self, Self::Pending(_)),
            "escaped atomic-inline replay must be resolved at capture"
        );
        let Self::Resolved(transform) = self else {
            return PaintTranslation::identity();
        };
        PaintTranslation::new(
            match transform.horizontal {
                EscapedAtomAxisReplay::RetainPageCoordinate => 0.0,
                EscapedAtomAxisReplay::FollowAtomicInline => {
                    final_origin.x - transform.source_origin.x
                }
            },
            match transform.vertical {
                EscapedAtomAxisReplay::RetainPageCoordinate => 0.0,
                EscapedAtomAxisReplay::FollowAtomicInline => {
                    final_origin.y - transform.source_origin.y
                }
            },
        )
    }

    /// Rebase a layer that has just been placed inside an enclosing atomic
    /// inline's scratch page. Axes retained in page space remain retained;
    /// axes that followed the inner atom acquire the enclosing capture origin
    /// when that outer atom is sealed.
    pub(in crate::layout) fn pending_in_enclosing_atomic_space(self) -> Self {
        let (horizontal, vertical) = match self {
            Self::Resolved(transform) => (
                match transform.horizontal {
                    EscapedAtomAxisReplay::RetainPageCoordinate => {
                        EscapedAtomHorizontalReplay::RetainPageCoordinate
                    }
                    EscapedAtomAxisReplay::FollowAtomicInline => {
                        EscapedAtomHorizontalReplay::FollowFromAtomicCapture
                    }
                },
                transform.vertical,
            ),
            Self::RetainPageCoordinates => (
                EscapedAtomHorizontalReplay::RetainPageCoordinate,
                EscapedAtomAxisReplay::RetainPageCoordinate,
            ),
            Self::Pending(policy) => (
                match policy.horizontal {
                    EscapedAtomHorizontalReplay::RetainPageCoordinate => {
                        EscapedAtomHorizontalReplay::RetainPageCoordinate
                    }
                    EscapedAtomHorizontalReplay::FollowFromAtomicCapture
                    | EscapedAtomHorizontalReplay::FollowFromPageContainingBlock(_) => {
                        EscapedAtomHorizontalReplay::FollowFromAtomicCapture
                    }
                },
                policy.vertical,
            ),
        };
        Self::Pending(EscapedAtomReplayPolicy {
            horizontal,
            vertical,
        })
    }

    /// Select the page that owns a replayed escaped layer.
    ///
    /// A static block-axis position follows the atom to its selected line and
    /// consequently takes that line's fragmentainer. An explicit block-axis
    /// inset is already in outer page coordinates and retains the page chosen
    /// by positioned layout:
    /// <https://www.w3.org/TR/css-position-3/#static-position>.
    pub(in crate::layout) fn replay_page_index(
        self,
        atom_page_index: usize,
        positioned_page_index: usize,
    ) -> usize {
        match self {
            Self::Resolved(EscapedAtomReplayTransform {
                vertical: EscapedAtomAxisReplay::FollowAtomicInline,
                ..
            }) => atom_page_index,
            Self::RetainPageCoordinates
            | Self::Pending(_)
            | Self::Resolved(EscapedAtomReplayTransform {
                vertical: EscapedAtomAxisReplay::RetainPageCoordinate,
                ..
            }) => positioned_page_index,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct FixedPaintLayer {
    /// The originating DOM element identifies the fixed formatting tree.
    pub(in crate::layout) source_element: crate::dom::ElementId,
    /// The originating computed style distinguishes separately generated
    /// boxes such as `::before` and `::after` on one DOM element while still
    /// allowing a speculative replay of the same fixed box to be replaced.
    pub(in crate::layout) source_style: ComputedStyle,
    pub(in crate::layout) stack_level: StackLevel,
    pub(in crate::layout) context: PaintStackingContext,
    pub(in crate::layout) links: Vec<RenderedLink>,
}

/// Internal CSS stacking-context decision for one laid-out box fragment.
///
/// CSS Positioned Layout and CSS 2.2 Appendix E decide paint placement from
/// stack level, while CSS Transforms, CSS CssColor opacity, and CSS Overflow add
/// group effects. Keeping this classification in one value prevents layout
/// paths from independently deciding which positioned descendants are captured:
/// <https://www.w3.org/TR/css-position-3/#painting-order>,
/// <https://www.w3.org/TR/CSS22/zindex.html>,
/// <https://www.w3.org/TR/css-transforms-1/#transform-rendering>,
/// <https://www.w3.org/TR/css-color-4/#transparency>, and
/// <https://www.w3.org/TR/css-overflow-3/#overflow-clip-edge>.
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct StackingContextPolicy {
    pub(in crate::layout) parent_band: PaintBand,
    pub(in crate::layout) stack_level: StackLevel,
    pub(in crate::layout) context_kind: StackingContextKind,
    pub(in crate::layout) child_layer_policy: ChildLayerPolicy,
    pub(in crate::layout) is_real_stacking_context: bool,
    pub(in crate::layout) is_fake_context: bool,
    pub(in crate::layout) creates_compositing_group: bool,
    pub(in crate::layout) establishes_containing_block: bool,
    pub(in crate::layout) captures_positioned_descendants: bool,
    pub(in crate::layout) effects: PaintEffects,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum StackingContextKind {
    None,
    Real,
    FakeAtomic,
}

/// The paint-order context for flex or grid item replay.
///
/// CSS Flexbox and Grid give same-page unfragmented static items
/// inline-block-like atomic painting. Fragmented and column-nested replay
/// still uses the in-flow band while the fragmented/nested Appendix E ordering
/// model is incomplete.
/// <https://drafts.csswg.org/css-flexbox/#painting>
/// <https://www.w3.org/TR/css-grid-1/#z-order>
/// <https://www.w3.org/TR/css-break-3/#fragmentation-model>
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(in crate::layout) enum FlexGridItemPaintContext {
    SamePageUnfragmented,
    FragmentedOrNested,
}

impl FlexGridItemPaintContext {
    fn static_parent_band(self) -> PaintBand {
        match self {
            Self::SamePageUnfragmented => PaintBand::Inline,
            Self::FragmentedOrNested => PaintBand::InFlowBlock,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum ChildLayerPolicy {
    CaptureAll,
    CaptureAutoLevel,
    EscapeAll,
}

impl StackingContextPolicy {
    pub(in crate::layout) fn for_positioned(
        element: &Element,
        style: &ComputedStyle,
        bounds: PaintClip,
    ) -> Self {
        let effects = assets::paint_effects_for_element_box(element, style, bounds);
        let is_real_stacking_context =
            matches!(&style.position, Position::Fixed | Position::Sticky)
                || style.z_index.establishes_stacking_context()
                || style_creates_effect_stacking_context_with_containment(
                    style,
                    &effects,
                    property_containment_applies_to_element(element, style),
                );
        let is_fake_context = !is_real_stacking_context
            && matches!(&style.position, Position::Relative | Position::Absolute);
        Self {
            parent_band: StackLevel::from_optional_z_index(style.z_index.stack_level())
                .paint_band(),
            stack_level: StackLevel::from_optional_z_index(style.z_index.stack_level()),
            context_kind: if is_real_stacking_context {
                StackingContextKind::Real
            } else if is_fake_context {
                StackingContextKind::FakeAtomic
            } else {
                StackingContextKind::None
            },
            child_layer_policy: if is_real_stacking_context {
                ChildLayerPolicy::CaptureAll
            } else {
                ChildLayerPolicy::EscapeAll
            },
            is_real_stacking_context,
            is_fake_context,
            creates_compositing_group: effects.needs_group(),
            establishes_containing_block: matches!(
                &style.position,
                Position::Relative | Position::Absolute | Position::Fixed | Position::Sticky
            ) || style.has_transform_or_preserve_3d(),
            captures_positioned_descendants: is_real_stacking_context,
            effects,
        }
    }

    pub(in crate::layout) fn for_non_positioned_effect(
        element: &Element,
        style: &ComputedStyle,
        bounds: PaintClip,
    ) -> Self {
        Self::for_non_positioned_effect_with_geometry(
            element,
            style,
            assets::PrincipalPaintGeometry::css_layout(bounds),
        )
    }

    pub(in crate::layout) fn for_non_positioned_effect_with_geometry(
        element: &Element,
        style: &ComputedStyle,
        geometry: assets::PrincipalPaintGeometry,
    ) -> Self {
        let effects = assets::paint_effects_for_principal_box(style, geometry);
        Self::for_non_positioned_effect_with_effects(
            style,
            effects,
            property_containment_applies_to_element(element, style),
        )
    }

    pub(in crate::layout) fn for_non_positioned_style_effect(
        style: &ComputedStyle,
        bounds: PaintClip,
    ) -> Self {
        let effects = assets::paint_effects_for_box(style, bounds);
        // This constructor is used for retained inline and anonymous-box
        // fragments, which have no `Element` to query.  Containment is only
        // effective when that fragment has a containment-capable principal
        // box; treating every style as applicable recreates a stacking
        // context for non-atomic inlines and ruby internals.
        // <https://www.w3.org/TR/css-contain-1/#containment-layout>
        Self::for_non_positioned_effect_with_effects(
            style,
            effects,
            property_containment_applies_to_style(style),
        )
    }

    pub(in crate::layout) fn for_non_positioned_effect_with_effects(
        style: &ComputedStyle,
        effects: PaintEffects,
        containment_applies: bool,
    ) -> Self {
        let in_flow_positioned = matches!(&style.position, Position::Relative | Position::Sticky);
        let stack_level = if in_flow_positioned {
            StackLevel::from_optional_z_index(style.z_index.stack_level())
        } else {
            StackLevel::Auto
        };
        let is_real_stacking_context = matches!(&style.position, Position::Sticky)
            || (style.position == Position::Relative
                && style.z_index.establishes_stacking_context())
            || style_creates_effect_stacking_context_with_containment(
                style,
                &effects,
                containment_applies,
            );
        let is_fake_context = style.position == Position::Relative && !is_real_stacking_context;
        Self {
            parent_band: if in_flow_positioned {
                stack_level.paint_band()
            } else {
                PaintBand::InFlowBlock
            },
            stack_level,
            context_kind: if is_real_stacking_context {
                StackingContextKind::Real
            } else if is_fake_context {
                StackingContextKind::FakeAtomic
            } else {
                StackingContextKind::None
            },
            child_layer_policy: if is_real_stacking_context {
                ChildLayerPolicy::CaptureAll
            } else if is_fake_context {
                ChildLayerPolicy::CaptureAutoLevel
            } else {
                ChildLayerPolicy::EscapeAll
            },
            is_real_stacking_context,
            is_fake_context,
            creates_compositing_group: effects.needs_group(),
            establishes_containing_block: style.has_transform_or_preserve_3d(),
            captures_positioned_descendants: is_real_stacking_context,
            effects,
        }
    }

    pub(in crate::layout) fn for_atomic(
        style: &ComputedStyle,
        parent_band: PaintBand,
        bounds: PaintClip,
    ) -> Self {
        Self::for_atomic_with_geometry(
            style,
            parent_band,
            assets::PrincipalPaintGeometry::css_layout(bounds),
        )
    }

    pub(in crate::layout) fn for_atomic_with_geometry(
        style: &ComputedStyle,
        parent_band: PaintBand,
        geometry: assets::PrincipalPaintGeometry,
    ) -> Self {
        let effects = assets::paint_effects_for_principal_box(style, geometry);
        // Atomic inline/replaced boxes still participate in positioned
        // stacking. In particular, a relatively positioned inline image with
        // a negative z-index belongs below later in-flow inline content, even
        // though its contents are otherwise painted as one atomic unit.
        // <https://www.w3.org/TR/CSS22/zindex.html#painting-order>
        let in_flow_positioned = matches!(&style.position, Position::Relative | Position::Sticky);
        let stack_level = if in_flow_positioned {
            StackLevel::from_optional_z_index(style.z_index.stack_level())
        } else {
            StackLevel::Auto
        };
        let is_real_stacking_context = matches!(&style.position, Position::Sticky)
            || (style.position == Position::Relative
                && style.z_index.establishes_stacking_context())
            || style_creates_effect_stacking_context(style, &effects);
        Self {
            parent_band: if is_real_stacking_context || in_flow_positioned {
                stack_level.paint_band()
            } else {
                parent_band
            },
            stack_level,
            context_kind: if is_real_stacking_context {
                StackingContextKind::Real
            } else {
                StackingContextKind::FakeAtomic
            },
            child_layer_policy: if is_real_stacking_context {
                ChildLayerPolicy::CaptureAll
            } else {
                ChildLayerPolicy::EscapeAll
            },
            is_real_stacking_context,
            is_fake_context: true,
            creates_compositing_group: effects.needs_group(),
            establishes_containing_block: in_flow_positioned
                || style.has_transform_or_preserve_3d(),
            captures_positioned_descendants: is_real_stacking_context,
            effects,
        }
    }

    /// Build the stacking policy for an embedded SVG root.
    ///
    /// An outermost SVG element is an atomic stacking context whose own
    /// background and border paint before its rendered descendants. SVG also
    /// requires the root element to establish an isolated compositing group,
    /// independently of CSS `opacity`, blending, or filters. Keeping this as
    /// a distinct policy prevents the generic replaced-element path from
    /// treating the group as an optional PDF optimization.
    /// <https://www.w3.org/TR/SVG2/render.html#EstablishingANewStackingContext>
    /// <https://www.w3.org/TR/SVG2/render.html#ParentCompositing>
    pub(in crate::layout) fn for_inline_svg_root(
        style: &ComputedStyle,
        parent_band: PaintBand,
        bounds: PaintClip,
    ) -> Self {
        Self::for_inline_svg_root_with_geometry(
            style,
            parent_band,
            assets::PrincipalPaintGeometry::css_layout(bounds),
        )
    }

    pub(in crate::layout) fn for_inline_svg_root_with_geometry(
        style: &ComputedStyle,
        parent_band: PaintBand,
        geometry: assets::PrincipalPaintGeometry,
    ) -> Self {
        let mut policy = Self::for_atomic_with_geometry(style, parent_band, geometry);
        policy.context_kind = StackingContextKind::Real;
        policy.child_layer_policy = ChildLayerPolicy::CaptureAll;
        policy.is_real_stacking_context = true;
        policy.is_fake_context = false;
        policy.creates_compositing_group = true;
        policy.captures_positioned_descendants = true;
        policy.effects.isolation = true;
        policy
    }

    pub(in crate::layout) fn for_flex_item(style: &ComputedStyle, bounds: PaintClip) -> Self {
        Self::for_flex_or_grid_item(
            style,
            bounds,
            FlexGridItemPaintContext::SamePageUnfragmented,
        )
    }

    /// Return the stacking policy for a fragment of a split flex item.
    pub(in crate::layout) fn for_fragmented_flex_item(
        style: &ComputedStyle,
        bounds: PaintClip,
    ) -> Self {
        Self::for_flex_or_grid_item(style, bounds, FlexGridItemPaintContext::FragmentedOrNested)
    }

    fn for_flex_or_grid_item(
        style: &ComputedStyle,
        bounds: PaintClip,
        paint_context: FlexGridItemPaintContext,
    ) -> Self {
        let stack_level = StackLevel::from_optional_z_index(style.z_index.stack_level());
        // The grid/flex item's independent formatting context owns the used
        // padding-box clip, and its replayed paint is captured as one atomic
        // item context. Keep that clip on the item policy so descendants
        // whose geometry was intentionally retained for positioning and
        // compositing cannot escape when the context is serialized.
        // <https://www.w3.org/TR/css-overflow-3/#overflow-clipping>
        let effects = assets::paint_effects_for_box(style, bounds);
        // The replay checkpoint contains the independently formatted item
        // contents and captured descendants; its principal decoration is
        // emitted by the owning flex/grid formatter outside this context.
        // Keep the shared used overflow effect here so static and fragmented
        // items use the same descendant-only clipping path.
        let in_flow_positioned = matches!(&style.position, Position::Relative | Position::Sticky);
        let is_real_stacking_context = matches!(&style.position, Position::Sticky)
            || style.z_index.establishes_stacking_context()
            || style_creates_effect_stacking_context(style, &effects);
        let is_fake_context = style.position == Position::Relative && !is_real_stacking_context;
        Self {
            // Complete flex/grid items paint as inline-block-like atomic
            // units in order-modified document order. A static `z-index:
            // auto` item therefore belongs to the parent's inline phase,
            // after its in-flow block backgrounds and borders. Fragmented
            // replay remains in the in-flow phase until the fragmented
            // Appendix E model can express that atomic ordering. A relatively
            // positioned item with `z-index: auto` always paints atomically
            // in the parent's auto/zero positioned phase without becoming a
            // real stacking context. Its positioned descendants still belong
            // to that parent context.
            // <https://drafts.csswg.org/css-flexbox/#painting>
            // <https://www.w3.org/TR/css-position-3/#painting-order>
            // <https://www.w3.org/TR/CSS22/zindex.html#painting-order>
            parent_band: if is_real_stacking_context || in_flow_positioned {
                stack_level.paint_band()
            } else {
                paint_context.static_parent_band()
            },
            stack_level,
            context_kind: if is_real_stacking_context {
                StackingContextKind::Real
            } else if is_fake_context {
                StackingContextKind::FakeAtomic
            } else {
                StackingContextKind::None
            },
            child_layer_policy: if is_real_stacking_context {
                ChildLayerPolicy::CaptureAll
            } else {
                ChildLayerPolicy::EscapeAll
            },
            is_real_stacking_context,
            is_fake_context,
            creates_compositing_group: effects.needs_group(),
            establishes_containing_block: in_flow_positioned
                || style.has_transform_or_preserve_3d(),
            captures_positioned_descendants: is_real_stacking_context,
            effects,
        }
    }

    /// Return the stacking policy for a grid item fragment.
    ///
    /// CSS Grid items, like flex items, paint as stacking-context-capable
    /// formatting-context items even when `position` is `static`; a non-auto
    /// `z-index` therefore creates a stacking context:
    /// <https://www.w3.org/TR/css-grid-1/#z-order> and
    /// <https://www.w3.org/TR/css-position-3/#painting-order>.
    pub(in crate::layout) fn for_grid_item(style: &ComputedStyle, bounds: PaintClip) -> Self {
        Self::for_flex_item(style, bounds)
    }

    /// Return the stacking policy for a fragment of a split grid item.
    pub(in crate::layout) fn for_fragmented_grid_item(
        style: &ComputedStyle,
        bounds: PaintClip,
    ) -> Self {
        Self::for_fragmented_flex_item(style, bounds)
    }

    pub(in crate::layout) fn style_needs_non_positioned_scope(
        element: &Element,
        style: &ComputedStyle,
    ) -> bool {
        matches!(&style.position, Position::Relative | Position::Sticky)
            || style_creates_effect_stacking_context_with_containment(
                style,
                &assets::paint_effects_for_element_box(
                    element,
                    style,
                    PaintClip::from_paint_rect(paint_space_rect(0.0, 0.0, 0.0, 0.0)),
                ),
                property_containment_applies_to_element(element, style),
            )
            || used_overflow_clips_element(element, style)
    }
}

pub(in crate::layout) fn style_creates_effect_stacking_context(
    style: &ComputedStyle,
    effects: &PaintEffects,
) -> bool {
    style_creates_effect_stacking_context_with_containment(
        style,
        effects,
        property_containment_applies_to_style(style),
    )
}

fn style_creates_effect_stacking_context_with_containment(
    style: &ComputedStyle,
    effects: &PaintEffects,
    containment_applies: bool,
) -> bool {
    effects.opacity < 1.0
        || effects.transform.is_some()
        // `perspective` applies to descendants, but it nevertheless
        // establishes a stacking context and therefore needs an owning paint
        // subtree even when the element has no transform of its own.
        // <https://drafts.csswg.org/css-transforms-2/#perspective-property>
        || effects.descendant_projective_3d_transform.is_some()
        || effects.three_d_participation
            != crate::document::paint::effects::ThreeDParticipation::Flat
        || effects.clip_path.is_active()
        || effects.mask.is_active()
        || effects.filter.is_active()
        || effects.blend_mode != PaintBlendMode::Normal
        || effects.isolation
        || style.isolation == Isolation::Isolate
        || style.mix_blend_mode != MixBlendMode::Normal
        || !matches!(style.filter, FilterValue::None)
        || style.clip_path != ClipPath::None
        || !matches!(style.mask, MaskValue::None)
        // Layout containment establishes an independent formatting context,
        // containing blocks, and a stacking context. Paint containment adds
        // the corresponding paint isolation and clipping.
        // <https://www.w3.org/TR/css-contain-1/#containment-layout>
        // <https://www.w3.org/TR/css-contain-1/#containment-paint>
        || (containment_applies && (style.contain.layout || style.contain.paint))
        || matches!(
            style.content_visibility,
            ContentVisibility::Auto | ContentVisibility::Hidden
        )
        || style.will_change.opacity
        || style.will_change.transform
        || style.will_change.filter
        || style.will_change.clip_path
        || style.will_change.mask
        || style.will_change.mix_blend_mode
        || style.will_change.isolation
        || style.will_change.contain
}

pub(in crate::layout) type NamedStringAssignment = PageAssignment<PageAssignmentValue>;

#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct CapturedPageAssignment {
    pub(in crate::layout) name: String,
    pub(in crate::layout) value: PageAssignmentValue,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(in crate::layout) struct AssignmentId(pub(in crate::layout) usize);

/// Page-local captured value for named strings and running elements.
///
/// CSS GCPM resolves `string()` and `element()` against assignments made by
/// source elements during pagination. Keeping placement with the value lets
/// page-margin resolution distinguish `first`/`last` from exact page-start
/// lookups:
/// <https://www.w3.org/TR/css-gcpm-3/#named-strings> and
/// <https://www.w3.org/TR/css-gcpm-3/#running-elements>.
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct PageAssignment<T> {
    pub(in crate::layout) id: AssignmentId,
    pub(in crate::layout) value: T,
    pub(in crate::layout) placement: AssignmentPlacement,
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct AssignmentPlacement {
    pub(in crate::layout) page_index: usize,
    pub(in crate::layout) starts_page_fragment: bool,
    pub(in crate::layout) border_box: Option<PaintClip>,
}

#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct FragmentPageValue {
    pub(in crate::layout) page_name: Option<String>,
    pub(in crate::layout) specified: bool,
}

impl FragmentPageValue {
    pub(in crate::layout) fn unspecified() -> Self {
        Self {
            page_name: None,
            specified: false,
        }
    }
}

/// Final page-local metadata for a visible layout fragment.
///
/// CSS Fragmentation defines fragments as the durable pieces of a source box,
/// while CSS Paged Media and GCPM resolve named pages, named strings, and
/// running elements from the page fragment that actually contains the source:
/// <https://www.w3.org/TR/css-break-3/#fragmentation-model>,
/// <https://www.w3.org/TR/css-page-3/#using-named-pages>, and
/// <https://www.w3.org/TR/css-gcpm-3/#named-strings>.
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct FragmentPageMetadata {
    pub(in crate::layout) page_index: usize,
    pub(in crate::layout) source_border_box: Option<PaintClip>,
    pub(in crate::layout) starts_page_fragment: bool,
    pub(in crate::layout) continues_from_previous_page: bool,
    pub(in crate::layout) continues_to_next_page: bool,
    pub(in crate::layout) first_page_value: FragmentPageValue,
    pub(in crate::layout) last_page_value: FragmentPageValue,
    pub(in crate::layout) assignment_ids: Vec<AssignmentId>,
}

impl FragmentPageMetadata {
    pub(in crate::layout) fn new(
        page_index: usize,
        source_border_box: Option<PaintClip>,
        starts_page_fragment: bool,
    ) -> Self {
        Self {
            page_index,
            source_border_box,
            starts_page_fragment,
            continues_from_previous_page: false,
            continues_to_next_page: false,
            first_page_value: FragmentPageValue::unspecified(),
            last_page_value: FragmentPageValue::unspecified(),
            assignment_ids: Vec::new(),
        }
    }

    pub(in crate::layout) fn empty(page_index: usize) -> Self {
        Self::new(page_index, None, false)
    }

    pub(in crate::layout) fn assignment_placement(&self) -> AssignmentPlacement {
        AssignmentPlacement {
            page_index: self.page_index,
            starts_page_fragment: self.starts_page_fragment,
            border_box: self.source_border_box,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) enum PageAssignmentValue {
    GeneratedContent(Vec<page_generated::PageMarginContentItem>),
    RunningElement(Box<RunningElementCapture>),
}

#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct RunningElementCapture {
    pub(in crate::layout) fallback_text: String,
    pub(in crate::layout) content_parts: Vec<GeneratedContentPart>,
    pub(in crate::layout) element: Element,
    pub(in crate::layout) style: Box<ComputedStyle>,
    pub(in crate::layout) counter_set: CounterSet,
    pub(in crate::layout) quote_depth: usize,
}

#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct ListMarker {
    /// Stable source identity used while an outside marker waits for its
    /// principal-line anchor. Recomputed marker styles are not a reliable
    /// identity because inline collection may normalize their style state.
    pub(in crate::layout) source_element: Option<ElementId>,
    pub(in crate::layout) text: String,
    pub(in crate::layout) image: Option<MarkerImage>,
    pub(in crate::layout) style: ComputedStyle,
    pub(in crate::layout) position: ListStylePosition,
    pub(in crate::layout) positioning_direction: Direction,
    pub(in crate::layout) suffix_space: bool,
}

/// The physical line geometry used to place an outside list marker.
///
/// CSS Lists intentionally leaves the exact outside-marker position
/// undefined.  Spindrift follows interoperable line-box behavior: textual
/// markers align their alphabetic baseline with the first in-flow formatted
/// line, while image markers use that line's block-start edge.
/// <https://drafts.csswg.org/css-lists-3/#list-style-position-property>
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct OutsideMarkerAnchor {
    /// The final physical inline span of the principal line. Float-adjacent
    /// fallbacks resolve their containing span before constructing this
    /// paint-only geometry.
    pub(in crate::layout) principal_line_inline_span: PageInlineSpan,
    pub(in crate::layout) formatted_line_block_start: PageTopBlockPosition,
    pub(in crate::layout) alphabetic_baseline: PageTopBlockPosition,
}

/// Unresolved fallback geometry for an outside marker with no principal line.
///
/// CSS Lists leaves the float-adjacent placement of such markers undefined.
/// Keeping the containing span distinct from [`OutsideMarkerAnchor`] makes
/// the compatibility float-band resolution explicit at the paint boundary.
/// <https://drafts.csswg.org/css-lists-3/#list-style-position-property>
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct OutsideMarkerFallbackCandidate {
    pub(in crate::layout) containing_inline_span: PageInlineSpan,
    pub(in crate::layout) fallback_line_block_span: PageBlockSpan,
    pub(in crate::layout) alphabetic_baseline: PageTopBlockPosition,
}

/// A resolved outside-marker paint operation retained until its list-item
/// owner can commit it outside a descendant paint scope.
///
/// The marker is the list item's first generated child, so its paint belongs
/// to the list item rather than to whichever nested block happened to expose
/// the first eligible line. Retaining a page-local fragment makes that
/// ownership explicit across descendant stacking contexts and fragmentation.
/// <https://drafts.csswg.org/css-lists-3/#markers>
/// <https://www.w3.org/TR/CSS22/zindex.html>
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct ResolvedOutsideMarkerPaint {
    /// The generated first child whose paint belongs to the list item.
    pub(in crate::layout) marker: ListMarker,
    /// The originating list-item style used by marker painting.
    pub(in crate::layout) list_item_style: ComputedStyle,
    /// The accepted principal-line geometry that resolved this operation.
    pub(in crate::layout) anchor: OutsideMarkerAnchor,
    /// The page fragment containing the resolved line.
    pub(in crate::layout) page: DocumentPageIndex,
    /// Isolated page-local marker paint, detached from the descendant scope.
    pub(in crate::layout) fragment: PaintFragment,
}

/// Where a resolved outside marker must be painted relative to the line that
/// establishes its geometry.
///
/// A normal-flow relatively positioned block is painted as an auto/zero
/// positioned atom. Its nested principal line can resolve an ancestor list
/// item's marker geometry, but cannot own that marker's paint.
/// <https://www.w3.org/TR/CSS22/zindex.html>
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum OutsideMarkerPaintOwner {
    CurrentPaintScope,
    ListItem,
}

impl OutsideMarkerPaintOwner {
    pub(in crate::layout) fn for_principal_line_block(style: &ComputedStyle) -> Self {
        if matches!(style.position, Position::Relative | Position::Sticky) {
            Self::ListItem
        } else {
            Self::CurrentPaintScope
        }
    }
}

/// Progress of an outside marker whose first principal line is discovered in
/// descendant layout.
///
/// `Capturing` prevents the marker's own generated inline sequence from
/// recursively treating itself as the list item's principal line.
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) enum DeferredOutsideMarkerPaintState {
    AwaitingAnchor,
    Capturing,
    Resolved(Box<ResolvedOutsideMarkerPaint>),
    PaintedInPlace,
}

#[derive(Debug, Clone)]
pub(in crate::layout) struct PendingOutsideMarkerAnchor {
    pub(in crate::layout) marker: ListMarker,
    pub(in crate::layout) list_item_style: ComputedStyle,
    /// Principal-line geometry retained for an item that never produces an
    /// eligible in-flow line. Fragmented descendants may advance the layout
    /// cursor before the pending marker is finalized, but they must not move
    /// this CSS Lists fallback anchor.
    pub(in crate::layout) fallback: OutsideMarkerFallbackCandidate,
    pub(in crate::layout) paint: DeferredOutsideMarkerPaintState,
}

/// Outside-marker anchors that belong to the current principal line-layout
/// coordinate space.
///
/// Off-page measurements and atomic-inline paint captures do lay out lines,
/// but none of those lines is eligible to anchor an ancestor list item's
/// marker. Keeping the collection behind this semantic type makes that
/// boundary explicit instead of allowing a scratch layout to consume an
/// ambient `Vec` by accident.
/// <https://drafts.csswg.org/css-lists-3/#list-style-position-property>
#[derive(Debug, Clone, Default)]
pub(in crate::layout) struct PendingOutsideMarkerAnchors {
    anchors: Vec<PendingOutsideMarkerAnchor>,
}

/// Principal-flow marker anchors suspended while a nested layout owns only
/// scratch-local line geometry.
///
/// This token is deliberately not `Clone`: there is one authoritative set of
/// anchors, and it must be restored exactly once to its owning principal flow.
/// <https://drafts.csswg.org/css-lists-3/#list-style-position-property>
#[must_use = "suspended outside-marker anchors must be restored after scratch layout"]
#[derive(Debug)]
pub(in crate::layout) struct SuspendedOutsideMarkerAnchors(PendingOutsideMarkerAnchors);

impl PendingOutsideMarkerAnchors {
    pub(in crate::layout) fn push(&mut self, anchor: PendingOutsideMarkerAnchor) {
        self.anchors.push(anchor);
    }

    pub(in crate::layout) fn pop(&mut self) -> Option<PendingOutsideMarkerAnchor> {
        self.anchors.pop()
    }

    pub(in crate::layout) fn iter(&self) -> impl Iterator<Item = &PendingOutsideMarkerAnchor> {
        self.anchors.iter()
    }

    pub(in crate::layout) fn begin_paint_capture(&mut self, index: usize) {
        debug_assert!(
            matches!(
                self.anchors[index].paint,
                DeferredOutsideMarkerPaintState::AwaitingAnchor
            ),
            "only an unresolved marker anchor can begin paint capture"
        );
        self.anchors[index].paint = DeferredOutsideMarkerPaintState::Capturing;
    }

    pub(in crate::layout) fn finish_paint_capture(
        &mut self,
        index: usize,
        paint: ResolvedOutsideMarkerPaint,
    ) {
        debug_assert!(
            matches!(
                self.anchors[index].paint,
                DeferredOutsideMarkerPaintState::Capturing
            ),
            "only a marker being captured can receive its paint fragment"
        );
        self.anchors[index].paint = DeferredOutsideMarkerPaintState::Resolved(Box::new(paint));
    }

    pub(in crate::layout) fn mark_painted_in_place(&mut self, index: usize) {
        debug_assert!(
            matches!(
                self.anchors[index].paint,
                DeferredOutsideMarkerPaintState::AwaitingAnchor
            ),
            "only an unresolved marker anchor can paint in its current owner"
        );
        self.anchors[index].paint = DeferredOutsideMarkerPaintState::PaintedInPlace;
    }

    pub(in crate::layout) fn suspend(&mut self) -> SuspendedOutsideMarkerAnchors {
        SuspendedOutsideMarkerAnchors(std::mem::take(self))
    }

    pub(in crate::layout) fn restore(&mut self, suspended: SuspendedOutsideMarkerAnchors) {
        debug_assert!(
            self.anchors.is_empty(),
            "a scratch layout must finalize its local outside-marker anchors"
        );
        *self = suspended.0;
    }

    pub(in crate::layout) fn is_empty(&self) -> bool {
        self.anchors.is_empty()
    }
}

/// Whether a nested inline paint replay may query active float exclusions.
///
/// Outside marker geometry is resolved before it enters nested text painting;
/// reapplying the enclosing float band would treat the marker as a second
/// principal line and move it away from that resolved position.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum NestedInlinePaintFloatPolicy {
    ReapplyActiveFloatBands,
    PreserveResolvedGeometry,
}

impl ListMarker {
    /// Whether this marker has content that can establish an inside line box.
    ///
    /// A marker made only of collapsible white space disappears during CSS
    /// Text processing, so it must not manufacture a principal line for an
    /// otherwise empty list item. A generated image remains an atomic inline
    /// participant even when its textual representation is empty.
    /// <https://drafts.csswg.org/css-lists-3/#list-style-position-property>
    /// <https://drafts.csswg.org/css-inline-3/#line-box>
    pub(in crate::layout) fn has_in_flow_content(&self) -> bool {
        self.image.is_some() || !crate::text::trim_css_collapsible_whitespace(&self.text).is_empty()
    }

    pub(in crate::layout) fn participates_in_first_line(&self) -> bool {
        self.position == ListStylePosition::Inside
    }

    pub(in crate::layout) fn paints_outside(&self) -> bool {
        self.position == ListStylePosition::Outside && !self.participates_in_first_line()
    }

    pub(in crate::layout) fn follows_content_in_first_line(&self) -> bool {
        false
    }
}

#[derive(Debug, Clone)]
pub(in crate::layout) struct MarkerImage {
    pub(in crate::layout) decoded: DecodedPngImage,
    pub(in crate::layout) svg: Option<SharedSvgAsset>,
    pub(in crate::layout) width: f32,
    pub(in crate::layout) height: f32,
}

impl PartialEq for MarkerImage {
    fn eq(&self, other: &Self) -> bool {
        self.decoded == other.decoded
            && self.width == other.width
            && self.height == other.height
            && self.svg.as_ref().map(Rc::as_ptr) == other.svg.as_ref().map(Rc::as_ptr)
    }
}

#[derive(Debug, Clone)]
pub(in crate::layout) struct InlineWord {
    pub(in crate::layout) text: String,
    pub(in crate::layout) style: InlineStyle,
    pub(in crate::layout) baseline_shift: f32,
    pub(in crate::layout) visual_offset: InlineVisualOffset,
    pub(in crate::layout) link_target: Option<Rc<str>>,
    pub(in crate::layout) mergeable: bool,
    pub(in crate::layout) source: InlineTextSource,
    pub(in crate::layout) hanging_edges: InlineHangingEdges,
    /// A positioned ancestor excluded from this occurrence's content-edge
    /// geometry after CSS Text relocates boundary whitespace outside it.
    pub(in crate::layout) excluded_positioning_geometry_source:
        Option<InlinePositioningContainingBlockId>,
    pub(in crate::layout) ancestor_inline_decorations: Rc<[InlineAncestorDecoration]>,
}

pub(in crate::layout) type InlineStyle = Rc<ComputedStyle>;

/// CSS Text wrapping behavior owned by one lexical inline scope.
///
/// A soft-wrap opportunity *between* two typographic units belongs to their
/// nearest common inline ancestor, rather than to either descendant that owns
/// the text or atomic box.  Keep that small, boundary-specific fact separate
/// from paint and shaping styles so graph construction can retain it through
/// transparent inline edges and source slicing:
/// <https://drafts.csswg.org/css-text-3/#line-break-details>.
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct InlineBoundaryPolicy {
    allows_soft_wrap: bool,
}

impl InlineBoundaryPolicy {
    fn from_style(style: &ComputedStyle) -> Self {
        Self {
            allows_soft_wrap: style.allows_soft_wrap(),
        }
    }

    pub(in crate::layout) fn allows_soft_wrap(self) -> bool {
        self.allows_soft_wrap
    }
}

/// Lexical inline ancestry retained for CSS Text boundary-owned behavior.
///
/// A regular inline box whose aligned subtree is positioned against the final
/// line box rather than the parent baseline.
///
/// CSS 2.2 defines `vertical-align: top` and `bottom` in terms of an inline
/// element's aligned subtree.  This is deliberately distinct from the
/// fragment's own computed style because `vertical-align` is not inherited:
/// descendant text must still retain the enclosing inline box's placement.
/// <https://www.w3.org/TR/CSS22/visudet.html#propdef-vertical-align>
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum InlineScopeLineRelativeAlignment {
    Top,
    Bottom,
}

impl InlineScopeLineRelativeAlignment {
    pub(in crate::layout) fn from_baseline_shift(baseline_shift: &BaselineShift) -> Option<Self> {
        match baseline_shift {
            BaselineShift::Top => Some(Self::Top),
            BaselineShift::Bottom => Some(Self::Bottom),
            BaselineShift::LengthPercentage(_)
            | BaselineShift::Super
            | BaselineShift::Sub
            | BaselineShift::Center => None,
        }
    }
}

#[derive(Debug)]
/// Retains the local used tracking value and the ancestry needed for
/// cross-element wrapping and line-relative alignment. This immutable parent
/// chain survives collection, source slicing, and bidi reordering without
/// making layout consumers reconstruct scope from decoration atoms:
/// <https://drafts.csswg.org/css-text-3/#letter-spacing-property> and
/// <https://drafts.csswg.org/css-text-3/#line-break-details>.
pub(in crate::layout) struct InlineTrackingScope {
    parent: Option<Rc<Self>>,
    depth: usize,
    /// The computed style of this lexical inline scope. CSS Text owns
    /// autospace at the innermost scope shared by the two adjacent
    /// typographic units, rather than at either unit's leaf style.
    autospace_style: InlineStyle,
    letter_spacing: LayoutLength,
    boundary_policy: InlineBoundaryPolicy,
    line_relative_alignment: Option<InlineScopeLineRelativeAlignment>,
    line_relative_style: Option<Rc<ComputedStyle>>,
}

impl InlineTrackingScope {
    pub(in crate::layout) fn root(style: &ComputedStyle) -> Rc<Self> {
        Rc::new(Self {
            parent: None,
            depth: 0,
            autospace_style: inline_style(style),
            letter_spacing: style.used_letter_spacing(),
            boundary_policy: InlineBoundaryPolicy::from_style(style),
            line_relative_alignment: None,
            line_relative_style: None,
        })
    }

    pub(in crate::layout) fn child(parent: Rc<Self>, style: &ComputedStyle) -> Rc<Self> {
        let line_relative_alignment = InlineScopeLineRelativeAlignment::from_baseline_shift(
            &style.vertical_align.baseline_shift,
        );
        Rc::new(Self {
            depth: parent.depth + 1,
            parent: Some(parent),
            autospace_style: inline_style(style),
            letter_spacing: style.used_letter_spacing(),
            boundary_policy: InlineBoundaryPolicy::from_style(style),
            line_relative_alignment,
            line_relative_style: line_relative_alignment
                .is_some()
                .then(|| Rc::new(style.clone())),
        })
    }

    pub(in crate::layout) fn letter_spacing(&self) -> LayoutLength {
        self.letter_spacing
    }

    /// Rebuild this lexical scope for a CSS Text `text-fit` used font size.
    /// Percentage tracking and autospace follow that font size, whereas fixed
    /// length components remain unchanged in the cloned computed style.
    /// <https://drafts.csswg.org/css-text-5/#text-fit-property>
    pub(in crate::layout) fn scaled_for_text_fit(&self, scale: f32) -> Rc<Self> {
        let parent = self
            .parent
            .as_deref()
            .map(|parent| parent.scaled_for_text_fit(scale));
        let mut autospace_style = (*self.autospace_style).clone();
        autospace_style.font_size *= scale;
        if matches!(
            autospace_style.line_height_value,
            css::ComputedLineHeight::Normal | css::ComputedLineHeight::Number(_)
        ) {
            autospace_style.line_height = autospace_style
                .line_height_value
                .clone()
                .projected(autospace_style.font_size)
                .0;
        }
        let line_relative_style = self.line_relative_style.as_ref().map(|style| {
            let mut style = (**style).clone();
            style.font_size *= scale;
            if matches!(
                style.line_height_value,
                css::ComputedLineHeight::Normal | css::ComputedLineHeight::Number(_)
            ) {
                style.line_height = style.line_height_value.clone().projected(style.font_size).0;
            }
            Rc::new(style)
        });
        Rc::new(Self {
            parent,
            depth: self.depth,
            letter_spacing: autospace_style.used_letter_spacing(),
            autospace_style: Rc::new(autospace_style),
            boundary_policy: self.boundary_policy,
            line_relative_alignment: self.line_relative_alignment,
            line_relative_style,
        })
    }

    pub(in crate::layout) fn boundary_policy(&self) -> InlineBoundaryPolicy {
        self.boundary_policy
    }

    pub(in crate::layout) fn autospace_style(&self) -> &ComputedStyle {
        &self.autospace_style
    }

    /// Return the innermost enclosing inline box whose aligned subtree is
    /// positioned relative to the final line box.
    ///
    /// A nested `top`/`bottom` inline establishes a separate subtree, so
    /// selecting the nearest scope also excludes it from an outer scope's
    /// placement as required by CSS 2.2.
    pub(in crate::layout) fn nearest_line_relative_scope(&self) -> Option<&InlineTrackingScope> {
        let mut scope = Some(self);
        while let Some(current) = scope {
            if current.line_relative_alignment.is_some() {
                return Some(current);
            }
            scope = current.parent.as_deref();
        }
        None
    }

    pub(in crate::layout) fn line_relative_alignment(
        &self,
    ) -> Option<InlineScopeLineRelativeAlignment> {
        self.line_relative_alignment
    }

    pub(in crate::layout) fn line_relative_style(&self) -> &ComputedStyle {
        debug_assert!(self.line_relative_alignment.is_some());
        self.line_relative_style
            .as_deref()
            .expect("a line-relative inline scope retains its own style")
    }

    /// Return the nearest shared lexical ancestor without allocating a
    /// temporary ancestor list.
    ///
    /// All scopes for one inline formatting context share a root.  The depth
    /// recorded at construction lets this walk align both immutable parent
    /// chains, then advance them together until their allocation identities
    /// match.
    fn lowest_common<'left>(left: &'left Self, right: &Self) -> &'left Self {
        let mut left = left;
        let mut right = right;
        while left.depth > right.depth {
            left = left
                .parent
                .as_deref()
                .expect("a deeper inline tracking scope has a parent");
        }
        while right.depth > left.depth {
            right = right
                .parent
                .as_deref()
                .expect("a deeper inline tracking scope has a parent");
        }
        while !std::ptr::eq(left, right) {
            left = left
                .parent
                .as_deref()
                .expect("all inline tracking participants share a paragraph root");
            right = right
                .parent
                .as_deref()
                .expect("all inline tracking participants share a paragraph root");
        }
        left
    }

    /// Resolve the shared inline-box policy used by CSS Text line breaking.
    ///
    /// Letter spacing deliberately has no corresponding common-ancestor API:
    /// each adjacent typographic unit contributes half of its own used value.
    pub(in crate::layout) fn common_boundary_policy(
        left: &Self,
        right: &Self,
    ) -> InlineBoundaryPolicy {
        Self::lowest_common(left, right).boundary_policy()
    }

    /// Return the innermost inline scope that owns an autospace boundary.
    ///
    /// CSS Text places inter-script spacing within the innermost element that
    /// contains both directly adjoining typographic units:
    /// <https://drafts.csswg.org/css-text-4/#text-autospace-property>.
    pub(in crate::layout) fn common_autospace_style<'left>(
        left: &'left Self,
        right: &Self,
    ) -> &'left ComputedStyle {
        Self::lowest_common(left, right).autospace_style()
    }
}

pub(in crate::layout) fn inline_style(style: &ComputedStyle) -> InlineStyle {
    Rc::new(style.clone())
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct InlineVisualOffset {
    pub(in crate::layout) vector: InlineVector,
}

impl InlineVisualOffset {
    pub(in crate::layout) fn zero() -> Self {
        Self {
            vector: InlineVector::new(0.0, 0.0),
        }
    }

    pub(in crate::layout) fn from_relative_offset(offset: RelativeOffset) -> Self {
        Self {
            vector: InlineVector::new(offset.x(), offset.y()),
        }
    }

    pub(in crate::layout) fn plus(self, other: Self) -> Self {
        Self {
            vector: self.vector + other.vector,
        }
    }

    pub(in crate::layout) fn is_zero(self) -> bool {
        self.x().abs() <= 0.01 && self.y().abs() <= 0.01
    }

    pub(in crate::layout) fn x(self) -> f32 {
        self.vector.x
    }

    pub(in crate::layout) fn y(self) -> f32 {
        self.vector.y
    }
}

impl Default for InlineVisualOffset {
    fn default() -> Self {
        Self::zero()
    }
}

/// The used-role of a fragment split from a `::first-letter` pseudo-element.
///
/// Preserved whitespace preceding the typographic initial remains styled by
/// the pseudo, but does not itself establish `initial-letter` sizing. Keeping
/// that distinction in the fragment model lets the initial-letter exclusion
/// reserve the complete pseudo span without confusing its tab advance for the
/// glyph's cap-height geometry.
/// <https://www.w3.org/TR/css-pseudo-4/#first-letter-pseudo>
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(in crate::layout) enum FirstLetterPseudoFragmentRole {
    #[default]
    Ordinary,
    /// Associated punctuation that precedes the typographic initial.
    ///
    /// This text is inside `::first-letter`, but is not the base glyph used
    /// for `initial-letter` sizing and exclusion geometry.
    AssociatedPrefix,
    /// The selected Letter, Number, or Symbol typographic character unit.
    ///
    /// `initial-letter` geometry must be derived from this component rather
    /// than an associated punctuation fragment that happens to precede it in
    /// source order.
    TypographicInitial,
    /// Associated punctuation that follows the typographic initial.
    AssociatedSuffix,
    LeadingPreservedWhitespace,
}

/// Opaque identity shared by every fragment materialized from one
/// `::first-letter` pseudo-element.
///
/// A stream selection can split punctuation and its typographic initial into
/// separate source fragments. Paint-time grouping must retain their common
/// pseudo ownership without making either fragment generally mergeable.
/// <https://www.w3.org/TR/css-pseudo-4/#first-letter-pseudo>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(in crate::layout) struct FirstLetterPseudoGroupId(u64);

impl FirstLetterPseudoGroupId {
    pub(in crate::layout) fn allocate() -> Self {
        static NEXT_ID: AtomicU64 = AtomicU64::new(1);
        Self(NEXT_ID.fetch_add(1, Ordering::Relaxed))
    }
}

#[derive(Debug, Clone)]
pub(in crate::layout) struct InlineFragmentData {
    pub(in crate::layout) text: Rc<str>,
    /// Opaque identity for one authored text run. Graph splitting preserves
    /// this across typographic units so paint projection can distinguish
    /// tracking fragments from independently authored adjacent text.
    pub(in crate::layout) source_run: Rc<()>,
    pub(in crate::layout) style: Rc<ComputedStyle>,
    pub(in crate::layout) link_target: Option<Rc<str>>,
    pub(in crate::layout) mergeable: bool,
    pub(in crate::layout) source: InlineTextSource,
    pub(in crate::layout) generated_leader: bool,
    /// Whether a typographic pseudo gives this text fragment an inline
    /// decoration even though its originating display type is block-level.
    pub(in crate::layout) force_inline_background_paint: bool,
    pub(in crate::layout) hanging_edges: InlineHangingEdges,
    /// A contextual source-shape selection that may be reused at paint time.
    ///
    /// This is deliberately an artifact, rather than a flag: the selected
    /// glyphs are only valid together with the full logical source, source
    /// range, and UAX #9 direction that produced them.
    pub(in crate::layout) source_shaped_selection: Option<SourceShapedSelection>,
    /// A full shaped source shared by transparent inline-boundary fragments.
    ///
    /// A CSS inline boundary can fall inside one OpenType cluster (for
    /// example a lam-alef ligature). Such a cluster cannot be represented by
    /// independently slicing glyphs for each lexical fragment, but it must
    /// remain available after line selection and bidi reordering.
    pub(in crate::layout) boundary_shaped_source: Option<Rc<BoundaryShapedSource>>,
    /// This fragment's authored range in [`BoundaryShapedSource::shaped`].
    pub(in crate::layout) boundary_shaped_range: Option<std::ops::Range<usize>>,
    /// UAX #9 direction resolved for a selected visual source slice.
    ///
    /// Logical source fragments leave this unset. It is only carried after
    /// mixed-inline visual reordering so the final paint shaping pass can
    /// preserve the already-selected order and glyph mirroring level.
    pub(in crate::layout) resolved_bidi_direction: Option<ResolvedBidiDirection>,
    pub(in crate::layout) excluded_positioning_geometry_source:
        Option<InlinePositioningContainingBlockId>,
    pub(in crate::layout) ancestor_inline_decorations: Rc<[InlineAncestorDecoration]>,
    /// The source inline ancestry used to resolve visual tracking boundaries.
    pub(in crate::layout) tracking_scope: Option<Rc<InlineTrackingScope>>,
    /// Whether this item starts a separate visual fragment after UAX #9
    /// reordering. Tracking must not reconnect text across that fragment
    /// boundary even when the adjacent items share an inline ancestor.
    pub(in crate::layout) starts_visual_fragment: bool,
    /// A `hyphenate-character` materialized at a selected discretionary
    /// boundary. It is painted with its own styled inline item, while the
    /// graph source range remains the owner of extraction and decoration.
    ///
    /// This is semantic used-line metadata, rather than a character test:
    /// markers may be transparent, RTL, or contain bidi-neutral text.
    pub(in crate::layout) selected_discretionary_marker: bool,
    pub(in crate::layout) first_letter_pseudo_role: FirstLetterPseudoFragmentRole,
    pub(in crate::layout) first_letter_pseudo_group_id: Option<FirstLetterPseudoGroupId>,
    /// A visual inline advance retained after an initial-letter exclusion has
    /// removed this pseudo fragment from normal line advancement.
    pub(in crate::layout) out_of_flow_paint_inline_advance: Option<LayoutLength>,
    /// A visual block extent retained with an out-of-flow first-letter prefix
    /// without allowing that prefix to enlarge its ordinary line box.
    pub(in crate::layout) out_of_flow_paint_block_size: Option<LayoutLength>,
}

/// One complete shaped source retained across transparent inline boundaries.
///
/// CSS Text boundary shaping is performed before individual inline fragments
/// are placed in visual order. Keeping the full glyph stream lets paint reuse
/// a ligature or contextual cluster that spans those fragments instead of
/// falling back to independently shaped source slices:
/// <https://www.w3.org/TR/css-text-3/#boundary-shaping>.
#[derive(Debug, Clone)]
pub(in crate::layout) struct BoundaryShapedSource {
    pub(in crate::layout) shaped: Rc<ShapedInlineLine>,
}

/// A glyph slice selected from one complete logical shaping artifact.
///
/// CSS Text chooses a soft-wrap range only after shaping has established the
/// source word's contextual forms.  Keeping both artifacts makes it
/// impossible to mark an unrelated independently-shaped fragment as reusable:
/// <https://drafts.csswg.org/css-text-3/#boundary-shaping>.
#[derive(Debug, Clone)]
pub(in crate::layout) struct SourceShapedSelection {
    source: Rc<ShapedInlineLine>,
    source_range: std::ops::Range<usize>,
    selected: Rc<ShapedInlineLine>,
    /// The selected range's final visual UAX #9 text. Before reordering it is
    /// the same logical text held by `selected`.
    visual_text: Rc<str>,
    resolved_bidi_direction: Option<ResolvedBidiDirection>,
}

impl SourceShapedSelection {
    /// Select a cluster-aligned range directly from its complete source.
    pub(in crate::layout) fn from_source(
        source: Rc<ShapedInlineLine>,
        source_range: std::ops::Range<usize>,
    ) -> Option<Self> {
        let selected = Rc::new(source.source_slice(source_range.clone())?);
        Some(Self {
            source,
            source_range,
            visual_text: Rc::clone(&selected.text),
            selected,
            resolved_bidi_direction: None,
        })
    }

    /// Select a child visual range while retaining the original logical
    /// source. `range` is relative to this already-selected fragment.
    pub(in crate::layout) fn subselection(&self, range: std::ops::Range<usize>) -> Option<Self> {
        let source_range =
            (self.source_range.start + range.start)..(self.source_range.start + range.end);
        if range.end > self.selected.text.len()
            || self.selected.text.get(range) != self.source.text.get(source_range.clone())
        {
            return None;
        }
        Self::from_source(Rc::clone(&self.source), source_range)
    }

    pub(in crate::layout) fn selected(&self) -> &ShapedInlineLine {
        &self.selected
    }

    pub(in crate::layout) fn selected_rc(&self) -> Rc<ShapedInlineLine> {
        Rc::clone(&self.selected)
    }

    pub(in crate::layout) fn selected_mut(&mut self) -> &mut ShapedInlineLine {
        Rc::make_mut(&mut self.selected)
    }

    pub(in crate::layout) fn replace_selected(&mut self, selected: ShapedInlineLine) {
        debug_assert_eq!(selected.text, self.selected.text);
        self.selected = Rc::new(selected);
    }

    pub(in crate::layout) fn resolve_bidi_context(
        &mut self,
        direction: ResolvedBidiDirection,
        visual_text: impl Into<Rc<str>>,
    ) {
        self.resolved_bidi_direction = Some(direction);
        self.visual_text = visual_text.into();
    }

    /// A source selection is only paintable when its selected text and UAX #9
    /// context still exactly match the fragment that carries it.
    pub(in crate::layout) fn is_reusable_for(
        &self,
        text: &str,
        direction: Option<ResolvedBidiDirection>,
    ) -> bool {
        self.visual_text.as_ref() == text
            && self.source.text.get(self.source_range.clone()) == Some(self.selected.text.as_ref())
            && self.resolved_bidi_direction == direction
    }

    /// Reassemble adjacent logical source ranges from one visual paint group.
    ///
    /// Individual RTL fragments are already in visual item order, whereas
    /// their glyphs retain positions from the one logical source run. Joining
    /// those fragments by concatenating per-fragment glyph streams would
    /// reverse that geometry. Re-slicing their contiguous logical union keeps
    /// the full source run's visual glyph order and advances intact.
    pub(in crate::layout) fn combine_contiguous(
        selections: &[&SourceShapedSelection],
    ) -> Option<ShapedInlineLine> {
        let first = *selections.first()?;
        if !selections.iter().all(|selection| {
            Rc::ptr_eq(&first.source, &selection.source)
                && first.resolved_bidi_direction == selection.resolved_bidi_direction
        }) {
            return None;
        }
        let mut ranges = selections
            .iter()
            .map(|selection| selection.source_range.clone())
            .collect::<Vec<_>>();
        ranges.sort_by_key(|range| range.start);
        let range = ranges
            .iter()
            .skip(1)
            .try_fold(ranges.first()?.clone(), |range, next| {
                (range.end == next.start).then_some(range.start..next.end)
            })?;
        first.source.source_slice(range)
    }
}

#[derive(Debug, Clone)]
pub(in crate::layout) struct InlineFragment {
    pub(in crate::layout) data: Rc<InlineFragmentData>,
    pub(in crate::layout) baseline_shift: f32,
    pub(in crate::layout) visual_offset: InlineVisualOffset,
}

impl InlineFragment {
    #[allow(clippy::too_many_arguments)]
    pub(in crate::layout) fn new(
        text: impl Into<String>,
        style: ComputedStyle,
        baseline_shift: f32,
        link_target: Option<String>,
        mergeable: bool,
        source: InlineTextSource,
        generated_leader: bool,
        hanging_edges: InlineHangingEdges,
        ancestor_inline_decorations: Vec<InlineAncestorDecoration>,
    ) -> Self {
        Self::new_shared_style(
            Rc::<str>::from(text.into()),
            Rc::new(style),
            baseline_shift,
            link_target.map(Rc::from),
            mergeable,
            source,
            generated_leader,
            hanging_edges,
            Rc::from(ancestor_inline_decorations.into_boxed_slice()),
        )
    }

    #[allow(clippy::too_many_arguments)]
    pub(in crate::layout) fn new_shared_style(
        text: impl Into<Rc<str>>,
        style: InlineStyle,
        baseline_shift: f32,
        link_target: Option<Rc<str>>,
        mergeable: bool,
        source: InlineTextSource,
        generated_leader: bool,
        hanging_edges: InlineHangingEdges,
        ancestor_inline_decorations: Rc<[InlineAncestorDecoration]>,
    ) -> Self {
        Self {
            data: Rc::new(InlineFragmentData {
                text: text.into(),
                source_run: Rc::new(()),
                style,
                link_target,
                mergeable,
                source,
                generated_leader,
                force_inline_background_paint: false,
                hanging_edges,
                source_shaped_selection: None,
                boundary_shaped_source: None,
                boundary_shaped_range: None,
                resolved_bidi_direction: None,
                excluded_positioning_geometry_source: None,
                ancestor_inline_decorations,
                tracking_scope: None,
                starts_visual_fragment: false,
                selected_discretionary_marker: false,
                first_letter_pseudo_role: FirstLetterPseudoFragmentRole::Ordinary,
                first_letter_pseudo_group_id: None,
                out_of_flow_paint_inline_advance: None,
                out_of_flow_paint_block_size: None,
            }),
            baseline_shift,
            visual_offset: InlineVisualOffset::zero(),
        }
    }

    pub(in crate::layout) fn with_baseline_shift(mut self, baseline_shift: f32) -> Self {
        self.baseline_shift = baseline_shift;
        self
    }

    pub(in crate::layout) fn with_excluded_positioning_geometry_source(
        mut self,
        source: Option<InlinePositioningContainingBlockId>,
    ) -> Self {
        Rc::make_mut(&mut self.data).excluded_positioning_geometry_source = source;
        self
    }

    pub(in crate::layout) fn excluded_positioning_geometry_source(
        &self,
    ) -> Option<InlinePositioningContainingBlockId> {
        self.data.excluded_positioning_geometry_source
    }

    pub(in crate::layout) fn with_visual_offset(
        mut self,
        visual_offset: InlineVisualOffset,
    ) -> Self {
        self.visual_offset = visual_offset;
        self
    }

    pub(in crate::layout) fn with_tracking_scope(mut self, scope: Rc<InlineTrackingScope>) -> Self {
        Rc::make_mut(&mut self.data).tracking_scope = Some(scope);
        self
    }

    pub(in crate::layout) fn with_source_run(mut self, source_run: Rc<()>) -> Self {
        Rc::make_mut(&mut self.data).source_run = source_run;
        self
    }

    pub(in crate::layout) fn source_run(&self) -> &Rc<()> {
        &self.data.source_run
    }

    pub(in crate::layout) fn tracking_scope(&self) -> Option<&Rc<InlineTrackingScope>> {
        self.data.tracking_scope.as_ref()
    }

    pub(in crate::layout) fn line_relative_scope(&self) -> Option<&InlineTrackingScope> {
        self.tracking_scope()
            .and_then(|scope| scope.nearest_line_relative_scope())
    }

    pub(in crate::layout) fn line_relative_alignment(
        &self,
    ) -> Option<InlineScopeLineRelativeAlignment> {
        // Text has no principal box of its own. A computed `top`/`bottom`
        // value belongs to the element that established its enclosing inline
        // box, and block boxes do not establish such a scope. Reading the
        // fragment style directly would therefore make a block descendant's
        // inapplicable `vertical-align` reposition its anonymous text.
        self.line_relative_scope()
            .and_then(InlineTrackingScope::line_relative_alignment)
    }

    pub(in crate::layout) fn starts_visual_fragment(&self) -> bool {
        self.data.starts_visual_fragment
    }

    pub(in crate::layout) fn mark_starts_visual_fragment(&mut self) {
        Rc::make_mut(&mut self.data).starts_visual_fragment = true;
    }

    pub(in crate::layout) fn mark_selected_discretionary_marker(&mut self) {
        let data = Rc::make_mut(&mut self.data);
        data.selected_discretionary_marker = true;
        // A used marker is an independently styled, logical inline item. It
        // must not be coalesced back into the source fragment that caused the
        // selected break.
        data.mergeable = false;
    }

    #[cfg(test)]
    pub(in crate::layout) fn is_selected_discretionary_marker(&self) -> bool {
        self.data.selected_discretionary_marker
    }

    pub(in crate::layout) fn set_first_letter_pseudo_role(
        &mut self,
        role: FirstLetterPseudoFragmentRole,
    ) {
        Rc::make_mut(&mut self.data).first_letter_pseudo_role = role;
    }

    pub(in crate::layout) fn first_letter_pseudo_role(&self) -> FirstLetterPseudoFragmentRole {
        self.data.first_letter_pseudo_role
    }

    pub(in crate::layout) fn set_first_letter_pseudo_group_id(
        &mut self,
        group_id: FirstLetterPseudoGroupId,
    ) {
        Rc::make_mut(&mut self.data).first_letter_pseudo_group_id = Some(group_id);
    }

    pub(in crate::layout) fn first_letter_pseudo_group_id(
        &self,
    ) -> Option<FirstLetterPseudoGroupId> {
        self.data.first_letter_pseudo_group_id
    }

    pub(in crate::layout) fn set_out_of_flow_paint_inline_advance(
        &mut self,
        advance: LayoutLength,
    ) {
        Rc::make_mut(&mut self.data).out_of_flow_paint_inline_advance = Some(advance);
    }

    pub(in crate::layout) fn out_of_flow_paint_inline_advance(&self) -> Option<LayoutLength> {
        self.data.out_of_flow_paint_inline_advance
    }

    pub(in crate::layout) fn set_out_of_flow_paint_block_size(&mut self, size: LayoutLength) {
        Rc::make_mut(&mut self.data).out_of_flow_paint_block_size = Some(size);
    }

    pub(in crate::layout) fn out_of_flow_paint_block_size(&self) -> Option<LayoutLength> {
        self.data.out_of_flow_paint_block_size
    }

    pub(in crate::layout) fn with_hanging_edges(
        mut self,
        hanging_edges: InlineHangingEdges,
    ) -> Self {
        Rc::make_mut(&mut self.data).hanging_edges = hanging_edges;
        self
    }

    pub(in crate::layout) fn set_text(&mut self, text: impl Into<Rc<str>>) {
        let data = Rc::make_mut(&mut self.data);
        let text = text.into();
        if data.text != text {
            data.source_shaped_selection = None;
            data.boundary_shaped_source = None;
            data.boundary_shaped_range = None;
        }
        data.text = text;
    }

    /// Discard source shaping when a line-local used style changes a shaping
    /// input while retaining the authored text and source ownership.
    ///
    /// CSS Text used-value adjustments such as `text-fit` happen after the
    /// graph has selected a break. Those selections remain valid, but their
    /// cached glyph advances and boundary shapes are not.
    pub(in crate::layout) fn clear_cached_shaping_for_used_style_change(&mut self) {
        let data = Rc::make_mut(&mut self.data);
        data.source_shaped_selection = None;
        data.boundary_shaped_source = None;
        data.boundary_shaped_range = None;
    }

    pub(in crate::layout) fn set_mergeable(&mut self, mergeable: bool) {
        Rc::make_mut(&mut self.data).mergeable = mergeable;
    }

    pub(in crate::layout) fn set_source_shaped_selection(
        &mut self,
        selection: Option<SourceShapedSelection>,
    ) {
        if let Some(selection) = &selection {
            debug_assert!(
                selection.source.text.get(selection.source_range.clone())
                    == Some(self.data.text.as_ref())
            );
        }
        Rc::make_mut(&mut self.data).source_shaped_selection = selection;
    }

    pub(in crate::layout) fn source_shaped_selection(&self) -> Option<&SourceShapedSelection> {
        self.data.source_shaped_selection.as_ref()
    }

    pub(in crate::layout) fn set_boundary_shaped_source(
        &mut self,
        source: Rc<BoundaryShapedSource>,
        range: std::ops::Range<usize>,
    ) {
        let data = Rc::make_mut(&mut self.data);
        data.boundary_shaped_source = Some(source);
        data.boundary_shaped_range = Some(range);
    }

    pub(in crate::layout) fn boundary_shaped_source(&self) -> Option<&BoundaryShapedSource> {
        self.data.boundary_shaped_source.as_deref()
    }

    pub(in crate::layout) fn boundary_shaped_range(&self) -> Option<&std::ops::Range<usize>> {
        self.data.boundary_shaped_range.as_ref()
    }

    /// Return the complete boundary source identity before a visual-selection
    /// step changes this fragment's paint text.  UAX #9 removes formatting
    /// controls from the selected text, but that must not discard the
    /// logical source which owns their shaping context.
    pub(in crate::layout) fn boundary_shaped_source_and_range(
        &self,
    ) -> Option<(Rc<BoundaryShapedSource>, std::ops::Range<usize>)> {
        Some((
            Rc::clone(self.data.boundary_shaped_source.as_ref()?),
            self.data.boundary_shaped_range.as_ref()?.clone(),
        ))
    }

    pub(in crate::layout) fn set_resolved_bidi_direction(
        &mut self,
        value: Option<ResolvedBidiDirection>,
    ) {
        Rc::make_mut(&mut self.data).resolved_bidi_direction = value;
    }

    /// Preserve a `::first-line` background on text directly owned by a block
    /// formatting context. Such a fragment has a block computed display, but
    /// its pseudo decoration still paints as an inline line fragment.
    pub(in crate::layout) fn set_force_inline_background_paint(&mut self, value: bool) {
        Rc::make_mut(&mut self.data).force_inline_background_paint = value;
    }

    pub(in crate::layout) fn force_inline_background_paint(&self) -> bool {
        self.data.force_inline_background_paint
    }

    #[cfg(test)]
    pub(in crate::layout) fn set_link_target(&mut self, link_target: Option<String>) {
        Rc::make_mut(&mut self.data).link_target = link_target.map(Rc::from);
    }

    #[cfg(test)]
    pub(in crate::layout) fn set_generated_leader(&mut self, generated_leader: bool) {
        Rc::make_mut(&mut self.data).generated_leader = generated_leader;
    }

    pub(in crate::layout) fn style_mut(&mut self) -> &mut ComputedStyle {
        Rc::make_mut(&mut Rc::make_mut(&mut self.data).style)
    }

    /// Apply a line-local inherited-style adjustment to every retained inline
    /// ancestor decoration. These snapshots own cloned background and border
    /// paint; leaving them at the pre-`::first-line` foreground would resolve
    /// their `currentcolor` against the wrong fragment color.
    pub(in crate::layout) fn apply_to_ancestor_inline_decoration_styles(
        &mut self,
        mut apply: impl FnMut(&mut ComputedStyle),
    ) {
        let data = Rc::make_mut(&mut self.data);
        let decorations = Rc::make_mut(&mut data.ancestor_inline_decorations);
        decorations
            .iter_mut()
            .for_each(|decoration| apply(&mut decoration.style));
    }

    pub(in crate::layout) fn text(&self) -> &str {
        &self.data.text
    }

    pub(in crate::layout) fn style(&self) -> &ComputedStyle {
        &self.data.style
    }

    pub(in crate::layout) fn link_target(&self) -> Option<&str> {
        self.data.link_target.as_deref()
    }

    pub(in crate::layout) fn mergeable(&self) -> bool {
        self.data.mergeable
    }

    pub(in crate::layout) fn source(&self) -> InlineTextSource {
        self.data.source
    }

    pub(in crate::layout) fn generated_leader(&self) -> bool {
        self.data.generated_leader
    }

    pub(in crate::layout) fn hanging_edges(&self) -> InlineHangingEdges {
        self.data.hanging_edges
    }

    pub(in crate::layout) fn ancestor_inline_decorations(&self) -> &[InlineAncestorDecoration] {
        &self.data.ancestor_inline_decorations
    }

    /// Retain a paint-only lexical ancestor while materializing a typographic
    /// pseudo.  The graph owns first-letter splitting, so this metadata must
    /// be attached there rather than reconstructed after bidi reordering.
    pub(in crate::layout) fn push_ancestor_inline_decoration(
        &mut self,
        decoration: InlineAncestorDecoration,
    ) {
        let data = Rc::make_mut(&mut self.data);
        let mut decorations = data.ancestor_inline_decorations.to_vec();
        decorations.push(decoration);
        data.ancestor_inline_decorations = Rc::from(decorations.into_boxed_slice());
    }
}

pub(in crate::layout) trait InlineFragmentAccess {
    fn text(&self) -> &str;
    fn style(&self) -> &ComputedStyle;
    fn baseline_shift(&self) -> f32;
    fn visual_offset(&self) -> InlineVisualOffset;
    fn link_target(&self) -> Option<&str>;
    fn mergeable(&self) -> bool;
    fn source(&self) -> InlineTextSource;
    /// Opaque identity for the authored text run that produced this fragment.
    ///
    /// This survives graph-level typographic-unit splitting so paint metadata
    /// can reconstitute one source word without conflating independent text.
    fn source_run(&self) -> &Rc<()>;
    /// The lexical inline-ancestry scope that owns this fragment.
    ///
    /// Reordering can split one scoped source run into visual fragments. The
    /// shared scope distinguishes those internal fragments from text across
    /// an actual `unicode-bidi` isolate boundary.
    fn tracking_scope(&self) -> Option<&Rc<InlineTrackingScope>>;
    fn generated_leader(&self) -> bool;
    fn first_letter_pseudo_group_id(&self) -> Option<FirstLetterPseudoGroupId> {
        None
    }
    /// A complete source shape shared with adjacent transparent fragments.
    fn boundary_shaped_source(&self) -> Option<&BoundaryShapedSource> {
        None
    }
    /// This fragment's authored range in the shared boundary shape.
    fn boundary_shaped_range(&self) -> Option<&std::ops::Range<usize>> {
        None
    }
    fn source_shaped_selection(&self) -> Option<&SourceShapedSelection> {
        None
    }
    fn resolved_bidi_direction(&self) -> Option<ResolvedBidiDirection>;
    fn ancestor_inline_decorations(&self) -> &[InlineAncestorDecoration];
}

impl InlineFragmentAccess for InlineFragment {
    fn text(&self) -> &str {
        self.text()
    }

    fn style(&self) -> &ComputedStyle {
        self.style()
    }

    fn baseline_shift(&self) -> f32 {
        self.baseline_shift
    }

    fn visual_offset(&self) -> InlineVisualOffset {
        self.visual_offset
    }

    fn link_target(&self) -> Option<&str> {
        self.link_target()
    }

    fn mergeable(&self) -> bool {
        self.mergeable()
    }

    fn source(&self) -> InlineTextSource {
        self.source()
    }

    fn source_run(&self) -> &Rc<()> {
        InlineFragment::source_run(self)
    }

    fn tracking_scope(&self) -> Option<&Rc<InlineTrackingScope>> {
        InlineFragment::tracking_scope(self)
    }

    fn generated_leader(&self) -> bool {
        self.generated_leader()
    }

    fn first_letter_pseudo_group_id(&self) -> Option<FirstLetterPseudoGroupId> {
        InlineFragment::first_letter_pseudo_group_id(self)
    }

    fn boundary_shaped_source(&self) -> Option<&BoundaryShapedSource> {
        InlineFragment::boundary_shaped_source(self)
    }

    fn boundary_shaped_range(&self) -> Option<&std::ops::Range<usize>> {
        InlineFragment::boundary_shaped_range(self)
    }

    fn source_shaped_selection(&self) -> Option<&SourceShapedSelection> {
        InlineFragment::source_shaped_selection(self)
    }

    fn resolved_bidi_direction(&self) -> Option<ResolvedBidiDirection> {
        self.data.resolved_bidi_direction
    }

    fn ancestor_inline_decorations(&self) -> &[InlineAncestorDecoration] {
        self.ancestor_inline_decorations()
    }
}

#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct PendingInlineFragment<'a> {
    fragment: &'a InlineFragment,
    baseline_shift: f32,
    visual_offset: InlineVisualOffset,
}

impl<'a> PendingInlineFragment<'a> {
    pub(in crate::layout) fn new(fragment: &'a InlineFragment) -> Self {
        Self {
            fragment,
            baseline_shift: fragment.baseline_shift,
            visual_offset: fragment.visual_offset,
        }
    }

    pub(in crate::layout) fn to_owned_fragment(self) -> InlineFragment {
        self.fragment
            .clone()
            .with_baseline_shift(self.baseline_shift())
            .with_visual_offset(self.visual_offset())
    }

    pub(in crate::layout) fn line_relative_alignment(
        self,
    ) -> Option<InlineScopeLineRelativeAlignment> {
        self.fragment.line_relative_alignment()
    }

    pub(in crate::layout) fn excluded_positioning_geometry_source(
        self,
    ) -> Option<InlinePositioningContainingBlockId> {
        self.fragment.excluded_positioning_geometry_source()
    }
}

impl InlineFragmentAccess for PendingInlineFragment<'_> {
    fn text(&self) -> &str {
        self.fragment.text()
    }

    fn style(&self) -> &ComputedStyle {
        self.fragment.style()
    }

    fn baseline_shift(&self) -> f32 {
        self.baseline_shift
    }

    fn visual_offset(&self) -> InlineVisualOffset {
        self.visual_offset
    }

    fn link_target(&self) -> Option<&str> {
        self.fragment.link_target()
    }

    fn mergeable(&self) -> bool {
        self.fragment.mergeable()
    }

    fn source(&self) -> InlineTextSource {
        self.fragment.source()
    }

    fn source_run(&self) -> &Rc<()> {
        self.fragment.source_run()
    }

    fn tracking_scope(&self) -> Option<&Rc<InlineTrackingScope>> {
        self.fragment.tracking_scope()
    }

    fn generated_leader(&self) -> bool {
        self.fragment.generated_leader()
    }

    fn first_letter_pseudo_group_id(&self) -> Option<FirstLetterPseudoGroupId> {
        self.fragment.first_letter_pseudo_group_id()
    }

    fn boundary_shaped_source(&self) -> Option<&BoundaryShapedSource> {
        self.fragment.boundary_shaped_source()
    }

    fn boundary_shaped_range(&self) -> Option<&std::ops::Range<usize>> {
        self.fragment.boundary_shaped_range()
    }

    fn source_shaped_selection(&self) -> Option<&SourceShapedSelection> {
        self.fragment.source_shaped_selection()
    }

    fn resolved_bidi_direction(&self) -> Option<ResolvedBidiDirection> {
        self.fragment.data.resolved_bidi_direction
    }

    fn ancestor_inline_decorations(&self) -> &[InlineAncestorDecoration] {
        self.fragment.ancestor_inline_decorations()
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum InlineTextSource {
    Normal,
    Generated,
    /// Generated U+200B emitted by the HTML UA `<wbr>` pseudo-element.
    ///
    /// It remains distinct until `word-space-transform` determines whether
    /// the separator survives its surrounding source boundary.
    GeneratedWbr,
    /// A layout-only replacement introduced by `word-space-transform`.
    ///
    /// The replacement space participates in layout and painting, but its PDF
    /// text mapping retains the authored U+200B or omits an HTML `<wbr>`.
    /// <https://drafts.csswg.org/css-text-4/#word-space-transform>
    WordSpaceTransform(ExplicitWordSeparatorSource),
    /// The anonymous inline generated by CSS Overflow's block ellipsis.
    ///
    /// It remains paintable with the terminal root inline's style, but has no
    /// line-box extent of its own (`line-height: 0`).
    /// <https://drafts.csswg.org/css-overflow-4/#block-ellipsis>
    BlockEllipsis,
    /// Generated text emitted by a `::footnote-call` pseudo-element.
    ///
    /// The call identity survives inline collection and line selection so a
    /// footnote is assigned only when its selected line is committed to a
    /// fragmentainer, rather than while a speculative measurement traverses
    /// the source tree.
    FootnoteCall(ElementId),
    RunIn,
    Marker,
    /// A directional formatting control synthesized from a CSS `unicode-bidi`
    /// scope. This remains distinct from authored control characters so
    /// line-local bidi resolution can restore only CSS scope boundaries after
    /// soft wrapping.
    BidiControl,
}

/// Source ownership for an explicit CSS Text expandable separator.
///
/// U+200B remains part of document text, while `<wbr>` is an HTML element
/// represented by generated U+200B in the UA stylesheet and contributes no
/// character to plain-text extraction.
/// <https://drafts.csswg.org/css-text-4/#word-space-transform>
/// <https://html.spec.whatwg.org/multipage/text-level-semantics.html#the-wbr-element>
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum ExplicitWordSeparatorSource {
    AuthoredZeroWidthSpace,
    HtmlWbr,
}

impl ExplicitWordSeparatorSource {
    pub(in crate::layout) const fn extraction_text(self) -> Option<&'static str> {
        match self {
            Self::AuthoredZeroWidthSpace => Some("\u{200b}"),
            Self::HtmlWbr => None,
        }
    }
}

impl InlineTextSource {
    pub(in crate::layout) fn is_generated(self) -> bool {
        matches!(
            self,
            Self::Generated | Self::GeneratedWbr | Self::BlockEllipsis | Self::FootnoteCall(_)
        )
    }

    pub(in crate::layout) fn footnote_call(self) -> Option<ElementId> {
        match self {
            Self::FootnoteCall(element) => Some(element),
            _ => None,
        }
    }
}

/// Inline edge decorations that affect CSS Text hanging punctuation.
///
/// CSS Text prevents hanging punctuation when nonzero inline-axis padding or
/// border separates the punctuation from the line edge, even when that edge
/// belongs to an ancestor inline box rather than the text fragment itself:
/// <https://www.w3.org/TR/css-text-3/#hanging-punctuation-property>.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(in crate::layout) struct InlineHangingEdges {
    pub(in crate::layout) blocks_start: bool,
    pub(in crate::layout) blocks_end: bool,
}

/// Background and border decoration inherited from an ancestor inline box.
///
/// CSS 2.2 paints a non-replaced inline box's backgrounds and borders across
/// its generated inline boxes, including descendant inline text with different
/// computed styles. Keeping ancestor decorations as paint-only fragment
/// metadata avoids duplicating shaped text while preserving the ancestor's
/// inline-box decoration geometry:
/// <https://www.w3.org/TR/CSS22/visuren.html#inline-boxes> and
/// <https://www.w3.org/TR/css-backgrounds-3/#the-background-color>.
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct InlineAncestorDecoration {
    pub(in crate::layout) style: ComputedStyle,
    pub(in crate::layout) hanging_edges: InlineHangingEdges,
    /// Whether this occurrence paints the ancestor's background and border.
    ///
    /// A positioned inline's own text fragment carries the containing-block
    /// metadata below, but already paints its matching style directly.  Keep
    /// those two responsibilities separate so recording positioning geometry
    /// cannot paint the same inline box twice.
    pub(in crate::layout) paints_background_or_border: bool,
    /// A positioned inline scope whose generated line fragment contains this
    /// source. This is metadata-only when `style` has no paintable decoration.
    /// It lets positioned layout collect independent logical content-edge
    /// extrema without inferring ownership from visual or paint order.
    pub(in crate::layout) positioning_containing_block_id:
        Option<InlinePositioningContainingBlockId>,
    /// Identity of an opacity-owning lexical inline scope.
    ///
    /// Opacity is non-inherited, but its effect subtree must survive text
    /// splitting and bidi reordering.  Equal opacity values are not a valid
    /// substitute for lexical identity: two sibling inline boxes each form a
    /// separate compositing group.
    /// <https://drafts.csswg.org/css-color-4/#transparency>
    pub(in crate::layout) paint_effect_scope_id: Option<InlinePaintScopeId>,
}

/// Whether an inline style establishes a non-auto positioned stacking context.
///
/// Non-atomic inline descendants are represented by text runs plus lexical
/// edge metadata rather than by one principal paint box.  Retaining this fact
/// on the lexical scope lets the text painter place its captured run in the
/// owning Appendix-E band.
/// <https://www.w3.org/TR/CSS22/zindex.html>
pub(in crate::layout) fn inline_style_establishes_positioned_stacking_context(
    style: &ComputedStyle,
) -> bool {
    matches!(style.position, Position::Relative | Position::Sticky)
        && style.z_index.establishes_stacking_context()
}

/// Opaque identity for a lexical inline paint-effect subtree.
///
/// A monotonically allocated id is intentionally independent of style
/// equality, source text, and visual order.  It is carried by copied inline
/// metadata through typographic-unit splitting and UAX #9 reordering.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(in crate::layout) struct InlinePaintScopeId(u64);

impl InlinePaintScopeId {
    pub(in crate::layout) fn allocate() -> Self {
        static NEXT_ID: AtomicU64 = AtomicU64::new(1);
        Self(NEXT_ID.fetch_add(1, Ordering::Relaxed))
    }
}

/// Return whether two ancestor-decoration chains require the same text paint
/// subtree.
///
/// Inline backgrounds and borders are emitted before the line's text and do
/// not alter glyph painting or shaping. Opacity, however, creates a stacking
/// context, so its lexical scope must remain a text-group boundary:
/// <https://www.w3.org/TR/css-color-4/#transparency> and
/// <https://www.w3.org/TR/CSS22/zindex.html#painting-order>.
pub(in crate::layout) fn inline_ancestor_decorations_have_same_text_paint_effect(
    left: &[InlineAncestorDecoration],
    right: &[InlineAncestorDecoration],
) -> bool {
    left.iter()
        .filter_map(|decoration| decoration.paint_effect_scope_id)
        .eq(right
            .iter()
            .filter_map(|decoration| decoration.paint_effect_scope_id))
        && left
            .iter()
            .filter(|decoration| {
                inline_style_establishes_positioned_stacking_context(&decoration.style)
            })
            .map(|decoration| decoration.positioning_containing_block_id)
            .eq(right
                .iter()
                .filter(|decoration| {
                    inline_style_establishes_positioned_stacking_context(&decoration.style)
                })
                .map(|decoration| decoration.positioning_containing_block_id))
}

#[derive(Debug, Clone, Copy)]
/// Static-position data captured while the hypothetical normal-flow source
/// still participates in its formatting context.
///
/// The rectangle is page-coordinate geometry. Text layout is entered from the
/// resolved positioned content box, not from an alternate static-position
/// baseline.
/// <https://drafts.csswg.org/css-position-3/#staticpos-rect>
pub(in crate::layout) struct StaticPositionCapture {
    /// The sole page-coordinate representation of the static position.
    pub(in crate::layout) rectangle: StaticPositionRectangle,
}

#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct PhysicalStaticAxisFallback {
    pub(in crate::layout) left: f32,
    pub(in crate::layout) right: f32,
    pub(in crate::layout) can_fall_outside: bool,
}

impl PhysicalStaticAxisFallback {
    pub(in crate::layout) fn new(left: f32, right: f32) -> Self {
        Self {
            left,
            right,
            can_fall_outside: false,
        }
    }

    pub(in crate::layout) fn new_unclamped(left: f32, right: f32) -> Self {
        Self {
            left,
            right,
            can_fall_outside: true,
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct AbsoluteStaticPosition {
    page_left_x: f32,
    page_right_x: f32,
    page_top_y: f32,
    horizontal_can_fall_outside: bool,
    has_vertical_position: bool,
    static_alignment_source: Option<StaticAlignmentSource>,
}

/// The physical content rectangle and applicable inline-axis alignment default
/// owned by one block formatting context for descendants' block-layout static-
/// position rectangles.
///
/// This record is captured when the owner enters child layout and stays
/// immutable through inline collection and deferred positioned replay.
/// Anonymous inline wrappers have no principal box geometry or independent
/// `justify-items` default, so they must use this owner rather than
/// reconstructing state from their own used style. `align-items` is not
/// retained: it does not apply to hypothetical block-level children.
/// <https://www.w3.org/TR/css-position-3/#static-position>
/// <https://drafts.csswg.org/css-align-3/#align-self-property>
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct StaticPositionContainingBlock {
    pub(in crate::layout) axes: WritingModeAxes,
    pub(in crate::layout) content_rect: PageTopRect,
    pub(in crate::layout) justify_items: css::SelfAlignment,
}

impl StaticPositionContainingBlock {
    pub(in crate::layout) fn new(
        axes: WritingModeAxes,
        content_rect: PageTopRect,
        justify_items: css::SelfAlignment,
    ) -> Self {
        Self {
            axes,
            content_rect,
            justify_items,
        }
    }

    /// Builds CSS Position's block-layout static-position rectangle from the
    /// hypothetical box's used border box. The static rectangle spans the
    /// static-position containing block in the inline axis and has zero
    /// block-axis extent at the hypothetical box's block-start edge.
    /// <https://drafts.csswg.org/css-position-3/#staticpos-rect>
    pub(in crate::layout) fn rectangle_at_hypothetical_block_box(
        self,
        hypothetical_border_box: PageTopRect,
    ) -> StaticPositionRectangle {
        let block_start = match self.axes.physical_side(LogicalSide::BlockStart) {
            PhysicalSide::Left => hypothetical_border_box.x(),
            PhysicalSide::Right => hypothetical_border_box.x() + hypothetical_border_box.width(),
            PhysicalSide::Top => hypothetical_border_box.top_y(),
            PhysicalSide::Bottom => {
                hypothetical_border_box.top_y() + hypothetical_border_box.height()
            }
        };
        let area = match self.axes.physical_axis(LogicalAxis::Inline) {
            PhysicalAxis::Horizontal => PageTopRect::new(
                self.content_rect.x(),
                block_start,
                self.content_rect.width(),
                0.0,
            ),
            PhysicalAxis::Vertical => PageTopRect::new(
                block_start,
                self.content_rect.top_y(),
                0.0,
                self.content_rect.height(),
            ),
        };
        StaticPositionRectangle {
            area,
            writing_mode: self.axes.writing_mode(),
            direction: self.axes.direction(),
            justify_items: self.justify_items,
            align_items: css::SelfAlignment::NORMAL,
        }
    }
}

/// The spec-defined alignment container used to resolve an absolutely
/// positioned child's static insets.
///
/// Capture it while normal flow still owns the hypothetical source fragment;
/// deferred positioned replay can otherwise see only an outer formatting
/// context.
/// <https://drafts.csswg.org/css-position-3/#staticpos-rect>
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct StaticPositionRectangle {
    pub(in crate::layout) area: PageTopRect,
    pub(in crate::layout) writing_mode: WritingMode,
    pub(in crate::layout) direction: Direction,
    pub(in crate::layout) justify_items: css::SelfAlignment,
    pub(in crate::layout) align_items: css::SelfAlignment,
}

impl StaticPositionRectangle {
    /// CSS 2's both-auto `left`/`right` rule is selected by the direction of
    /// the static-position containing block. In vertical writing this is the
    /// physical horizontal direction of that block axis, not the positioned
    /// subject's inline direction.
    /// <https://www.w3.org/TR/CSS22/visudet.html#abs-non-replaced-width>
    /// <https://drafts.csswg.org/css-writing-modes-4/#logical-to-physical>
    pub(in crate::layout) fn css2_horizontal_direction(self) -> Direction {
        crate::layout::assets::physical_horizontal_axis_direction(self.writing_mode, self.direction)
    }
}

/// The formatting context owns the exact source of static-position alignment.
/// Ordinary flow keeps its immutable rectangle separate from the alignment
/// resolved later for the positioned subject; Flexbox and Grid provide an
/// already-resolved alignment rectangle of their own.
#[derive(Debug, Clone, Copy)]
enum StaticAlignmentSource {
    OrdinaryFlow {
        rectangle: StaticPositionRectangle,
        alignment: Option<AbsposStaticAlignment>,
    },
    FormattingContext(AbsposStaticAlignment),
}

/// Static-position alignment data retained until an absolutely positioned
/// child has a used margin-box size.
///
/// The static-position rectangle may come from ordinary flow, Flexbox, or
/// Grid.  Keeping the rectangle, its writing mode, and its already-resolved
/// static-position self-alignment together makes positioned layout independent
/// of the formatting context that supplied it:
/// <https://drafts.csswg.org/css-position-3/#static-position>
/// <https://drafts.csswg.org/css-align-3/#align-abspos>
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct AbsposStaticAlignment {
    /// The spec-defined static-position rectangle. Unlike an absolute
    /// positioning containing block this is allowed (and, for ordinary block
    /// and inline layout, required) to be zero-sized in one physical axis.
    /// <https://drafts.csswg.org/css-position-3/#staticpos-rect>
    pub(in crate::layout) area: PageTopRect,
    /// Axes of the static-position containing block / alignment container.
    pub(in crate::layout) writing_mode: WritingMode,
    pub(in crate::layout) direction: Direction,
    /// Axes of the positioned alignment subject. These differ from the
    /// container axes for `self-start` and `self-end`.
    pub(in crate::layout) subject_writing_mode: WritingMode,
    pub(in crate::layout) subject_direction: Direction,
    /// The effective `justify-self` used while calculating the static
    /// position. `auto` has already inherited the appropriate parent default.
    pub(in crate::layout) inline: css::SelfAlignment,
    /// The effective `align-self` used while calculating the static position.
    /// `auto` has already inherited the appropriate parent default.
    pub(in crate::layout) block: css::SelfAlignment,
}

impl AbsposStaticAlignment {
    pub(in crate::layout) fn new(
        area: PageTopRect,
        writing_mode: WritingMode,
        direction: Direction,
        subject_writing_mode: WritingMode,
        subject_direction: Direction,
        inline: css::SelfAlignment,
        block: css::SelfAlignment,
    ) -> Self {
        Self {
            area,
            writing_mode,
            direction,
            subject_writing_mode,
            subject_direction,
            inline,
            block,
        }
    }

    fn alignment_for_physical_axis(self, axis: PhysicalAxis) -> css::SelfAlignment {
        let axes = WritingModeAxes::new(self.writing_mode, self.direction);
        if axes.logical_axis_for_physical(axis) == LogicalAxis::Inline {
            self.inline
        } else {
            self.block
        }
    }

    fn alignment_direction(self, axis: PhysicalAxis) -> AbsposAlignmentDirection {
        let container_axes = WritingModeAxes::new(self.writing_mode, self.direction);
        let container_logical_axis = container_axes.logical_axis_for_physical(axis);
        let subject_axes = WritingModeAxes::new(self.subject_writing_mode, self.subject_direction);
        let subject_logical_axis = subject_axes.logical_axis_for_physical(axis);
        let container_reverse_start_end = matches!(
            container_axes.physical_start_side(container_logical_axis),
            PhysicalSide::Right | PhysicalSide::Bottom
        );
        let subject_reverse_start_end = matches!(
            subject_axes.physical_start_side(subject_logical_axis),
            PhysicalSide::Right | PhysicalSide::Bottom
        );
        AbsposAlignmentDirection {
            container_reverse_start_end,
            subject_reverse_start_end,
            left_right_are_physical: axis == PhysicalAxis::Horizontal
                && container_logical_axis == LogicalAxis::Inline,
            left_right_resolve_to_inline_edges: container_logical_axis == LogicalAxis::Inline,
        }
    }

    pub(in crate::layout) fn available_outer_size(
        self,
        axis: PhysicalAxis,
        containing_block: ContainingBlock,
    ) -> Option<f32> {
        let alignment = self.alignment_for_physical_axis(axis);
        let direction = self.alignment_direction(axis);
        let (area_start, area_size, containing_start, containing_size) = match axis {
            PhysicalAxis::Horizontal => (
                self.area.x(),
                self.area.width(),
                containing_block.x(),
                containing_block.width(),
            ),
            PhysicalAxis::Vertical => (
                self.area.top_y(),
                self.area.height(),
                containing_block.top_y(),
                containing_block.height(),
            ),
        };
        match alignment.keyword {
            SelfAlignmentKeyword::Center => Some({
                let center = area_start + area_size / 2.0;
                (2.0 * (center - containing_start).min(containing_start + containing_size - center))
                    .max(0.0)
            }),
            keyword => {
                // CSS Align §6.5 sizes a statically positioned automatic
                // inline axis from the static rectangle edge selected by the
                // alignment value to the opposite edge of the actual
                // containing block. This is intentionally not the static
                // rectangle's own width: ordinary-flow rectangles are
                // degenerate in one axis.
                // <https://drafts.csswg.org/css-align-3/#abspos-static-size>
                let physical_start_is_left = match keyword {
                    SelfAlignmentKeyword::SelfStart | SelfAlignmentKeyword::SelfEnd => {
                        let subject_start_is_left = !direction.subject_reverse_start_end;
                        if matches!(keyword, SelfAlignmentKeyword::SelfStart) {
                            subject_start_is_left
                        } else {
                            !subject_start_is_left
                        }
                    }
                    SelfAlignmentKeyword::End | SelfAlignmentKeyword::FlexEnd => {
                        direction.container_reverse_start_end
                    }
                    SelfAlignmentKeyword::Right if direction.left_right_are_physical => false,
                    SelfAlignmentKeyword::Left if direction.left_right_are_physical => true,
                    _ => !direction.container_reverse_start_end,
                };
                let static_edge = if physical_start_is_left {
                    area_start
                } else {
                    area_start + area_size
                };
                let containing_opposite_edge = if physical_start_is_left {
                    containing_start + containing_size
                } else {
                    containing_start
                };
                Some((containing_opposite_edge - static_edge).abs().max(0.0))
            }
        }
    }

    pub(in crate::layout) fn available_horizontal_outer_size(
        self,
        containing_block: ContainingBlock,
    ) -> Option<f32> {
        self.available_outer_size(PhysicalAxis::Horizontal, containing_block)
    }

    /// Resolve the static position to the physical margin-box start inset.
    ///
    /// [`PositionedAxis::start`] is the CSS inset before its start margin;
    /// positioned layout applies that margin when it projects the resolved
    /// axis to the border box. Returning a border-box edge here would make
    /// aligned absolutely positioned boxes consume their start margin twice.
    /// CSS Box Alignment aligns the margin box, including for Flexbox and
    /// Grid static-position rectangles:
    /// <https://drafts.csswg.org/css-align-3/#align-abspos>.
    pub(in crate::layout) fn horizontal_static_position(
        self,
        containing_block: ContainingBlock,
        border_box_width: f32,
        margin_left: f32,
        margin_right: f32,
    ) -> PhysicalStaticAxisFallback {
        let outer_width = margin_left + border_box_width + margin_right;
        let alignment = self.alignment_for_physical_axis(PhysicalAxis::Horizontal);
        let direction = self.alignment_direction(PhysicalAxis::Horizontal);
        let offset = abspos_static_alignment_offset(
            alignment,
            self.area.width(),
            border_box_width,
            margin_left,
            margin_right,
            direction,
        );
        // Convert the border-edge alignment offset to a margin-box offset
        // before adding the rectangle origin. Besides expressing the correct
        // coordinate contract directly, this preserves an exact zero for
        // start alignment instead of rounding `origin + margin - margin`.
        let margin_box_offset = offset - margin_left;
        let candidate_margin_box_start = self.area.x() + margin_box_offset;
        let candidate_overflows_containing_block = candidate_margin_box_start
            < containing_block.x()
            || candidate_margin_box_start + outer_width
                > containing_block.x() + containing_block.width();
        let margin_box_start = if safe_alignment_falls_back_to_static_position_start(
            alignment,
            offset,
            self.area.width(),
            border_box_width,
            margin_left,
            margin_right,
            direction,
            candidate_overflows_containing_block,
        ) {
            if direction.container_reverse_start_end {
                self.area.x() + self.area.width() - outer_width
            } else {
                self.area.x()
            }
        } else {
            candidate_margin_box_start
        };
        let start_in_containing_block = margin_box_start - containing_block.x();
        PhysicalStaticAxisFallback::new_unclamped(
            start_in_containing_block,
            containing_block.width() - start_in_containing_block - outer_width,
        )
    }

    /// Resolve the static position to the physical margin-box start inset.
    ///
    /// See [`Self::horizontal_static_position`] for why this deliberately
    /// excludes the start margin from the returned absolute-position inset.
    pub(in crate::layout) fn vertical_static_start(
        self,
        containing_block: ContainingBlock,
        border_box_height: f32,
        margin_top: f32,
        margin_bottom: f32,
    ) -> f32 {
        let outer_height = margin_top + border_box_height + margin_bottom;
        let alignment = self.alignment_for_physical_axis(PhysicalAxis::Vertical);
        let direction = self.alignment_direction(PhysicalAxis::Vertical);
        let offset = abspos_static_alignment_offset(
            alignment,
            self.area.height(),
            border_box_height,
            margin_top,
            margin_bottom,
            direction,
        );
        // As on the horizontal axis, form the margin-box offset first. This
        // avoids losing a fractional page coordinate when a start margin
        // cancels the start-alignment border offset.
        let margin_box_offset = offset - margin_top;
        let candidate_margin_box_top = self.area.top_y() - margin_box_offset;
        let candidate_overflows_containing_block = candidate_margin_box_top
            > containing_block.top_y()
            || candidate_margin_box_top - outer_height
                < containing_block.top_y() - containing_block.height();
        if safe_alignment_falls_back_to_static_position_start(
            alignment,
            offset,
            self.area.height(),
            border_box_height,
            margin_top,
            margin_bottom,
            direction,
            candidate_overflows_containing_block,
        ) {
            let margin_box_top = if direction.container_reverse_start_end {
                self.area.top_y() - outer_height
            } else {
                self.area.top_y()
            };
            containing_block.top_y() - margin_box_top
        } else {
            containing_block.top_y() - candidate_margin_box_top
        }
    }
}

#[derive(Debug, Clone, Copy)]
struct AbsposAlignmentDirection {
    container_reverse_start_end: bool,
    subject_reverse_start_end: bool,
    left_right_are_physical: bool,
    left_right_resolve_to_inline_edges: bool,
}

/// Resolve one physical-axis offset within a static-position rectangle.
///
/// `normal`, `stretch`, and baseline values fall back to logical start while
/// establishing a static position. The actual abspos sizing algorithm decides
/// whether `normal` or `stretch` changes an automatic size.
fn abspos_static_alignment_offset(
    alignment: css::SelfAlignment,
    area_size: f32,
    border_size: f32,
    margin_start: f32,
    margin_end: f32,
    direction: AbsposAlignmentDirection,
) -> f32 {
    let free_space = area_size - margin_start - border_size - margin_end;
    let keyword = alignment.keyword;
    let start = margin_start;
    let end = margin_start + free_space;
    match keyword {
        SelfAlignmentKeyword::Center => margin_start + free_space / 2.0,
        SelfAlignmentKeyword::End | SelfAlignmentKeyword::FlexEnd => {
            if direction.container_reverse_start_end {
                start
            } else {
                end
            }
        }
        SelfAlignmentKeyword::SelfEnd => {
            if direction.subject_reverse_start_end {
                start
            } else {
                end
            }
        }
        // First-baseline alignment falls back to start while last-baseline
        // alignment falls back to end when deriving a static position.
        // <https://drafts.csswg.org/css-align-3/#baseline-align-content>
        SelfAlignmentKeyword::LastBaseline => {
            if direction.container_reverse_start_end {
                start
            } else {
                end
            }
        }
        SelfAlignmentKeyword::Start | SelfAlignmentKeyword::FlexStart => {
            if direction.container_reverse_start_end {
                end
            } else {
                start
            }
        }
        SelfAlignmentKeyword::SelfStart => {
            if direction.subject_reverse_start_end {
                end
            } else {
                start
            }
        }
        SelfAlignmentKeyword::Left if direction.left_right_are_physical => start,
        SelfAlignmentKeyword::Right if direction.left_right_are_physical => end,
        // In a vertical inline axis `left` and `right` resolve to the inline
        // start and end edges respectively. When the alignment axis is the
        // block axis, they instead fall back to `start`.
        // <https://drafts.csswg.org/css-align-3/#self-align-terms>
        SelfAlignmentKeyword::Left if direction.left_right_resolve_to_inline_edges => {
            if direction.container_reverse_start_end {
                end
            } else {
                start
            }
        }
        SelfAlignmentKeyword::Right if direction.left_right_resolve_to_inline_edges => {
            if direction.container_reverse_start_end {
                start
            } else {
                end
            }
        }
        SelfAlignmentKeyword::Left
        | SelfAlignmentKeyword::Right
        | SelfAlignmentKeyword::Auto
        | SelfAlignmentKeyword::Normal
        | SelfAlignmentKeyword::Stretch
        | SelfAlignmentKeyword::Baseline => {
            if direction.container_reverse_start_end {
                end
            } else {
                start
            }
        }
    }
}

/// `safe` alignment is first evaluated in the static-position rectangle. If
/// that result would overflow the inset-modified containing block, it falls
/// back to the static-position rectangle's logical start edge. The real
/// containing block detects unsafe overflow, but it does not replace the
/// Flex/Grid-derived static alignment container. A value that already resolves
/// to the static rectangle's logical start is unchanged: substituting `start`
/// must not make `safe start` behave as a different alignment value.
/// <https://drafts.csswg.org/css-align-3/#overflow-values>
#[allow(clippy::too_many_arguments)]
fn safe_alignment_falls_back_to_static_position_start(
    alignment: css::SelfAlignment,
    offset: f32,
    area_size: f32,
    border_size: f32,
    margin_start: f32,
    margin_end: f32,
    direction: AbsposAlignmentDirection,
    candidate_overflows_containing_block: bool,
) -> bool {
    if alignment.safety != AlignmentSafety::Safe || !candidate_overflows_containing_block {
        return false;
    }

    let logical_start_offset = if direction.container_reverse_start_end {
        area_size - border_size - margin_end
    } else {
        margin_start
    };
    (offset - logical_start_offset).abs() > 0.01
}

impl AbsoluteStaticPosition {
    /// Store an absolutely positioned box's static-position rectangle in page
    /// coordinates so it can be resolved against either an absolute or fixed
    /// containing block later.
    ///
    /// CSS 2.2 defines auto insets from the hypothetical normal-flow static
    /// position, while CSS Positioned Layout makes fixed boxes use the viewport
    /// as their containing block:
    /// <https://www.w3.org/TR/CSS22/visudet.html#abs-non-replaced-width> and
    /// <https://www.w3.org/TR/css-position-3/#fixed-positioning>.
    pub(in crate::layout) fn from_page_rect(
        page_left_x: f32,
        page_right_x: f32,
        page_top_y: f32,
    ) -> Self {
        Self::from_page_rect_with_horizontal_outside(page_left_x, page_right_x, page_top_y, false)
    }

    pub(in crate::layout) fn from_page_rect_with_horizontal_outside(
        page_left_x: f32,
        page_right_x: f32,
        page_top_y: f32,
        horizontal_can_fall_outside: bool,
    ) -> Self {
        Self {
            page_left_x,
            page_right_x,
            page_top_y,
            horizontal_can_fall_outside,
            has_vertical_position: true,
            static_alignment_source: None,
        }
    }

    /// Store only the inline-axis part of a static-position rectangle.
    ///
    /// A blockified box encountered within an inline run retains that run's
    /// inline position, while its block position is still selected by the
    /// block formatting context's hypothetical in-flow box.
    /// <https://www.w3.org/TR/css-position-3/#static-position>
    pub(in crate::layout) fn from_page_horizontal_position(
        page_left_x: f32,
        page_right_x: f32,
    ) -> Self {
        Self {
            page_left_x,
            page_right_x,
            page_top_y: 0.0,
            horizontal_can_fall_outside: false,
            has_vertical_position: false,
            static_alignment_source: None,
        }
    }

    pub(in crate::layout) fn with_static_alignment(
        mut self,
        static_alignment: AbsposStaticAlignment,
    ) -> Self {
        self.static_alignment_source = Some(match self.static_alignment_source {
            Some(StaticAlignmentSource::OrdinaryFlow { rectangle, .. }) => {
                StaticAlignmentSource::OrdinaryFlow {
                    rectangle,
                    alignment: Some(static_alignment),
                }
            }
            Some(StaticAlignmentSource::FormattingContext(_)) | None => {
                StaticAlignmentSource::FormattingContext(static_alignment)
            }
        });
        self
    }

    pub(in crate::layout) fn with_static_position_rectangle(
        mut self,
        rectangle: StaticPositionRectangle,
    ) -> Self {
        self.static_alignment_source = Some(StaticAlignmentSource::OrdinaryFlow {
            rectangle,
            alignment: self
                .static_alignment_source
                .and_then(|source| match source {
                    StaticAlignmentSource::OrdinaryFlow { alignment, .. } => alignment,
                    StaticAlignmentSource::FormattingContext(_) => None,
                }),
        });
        self
    }

    /// Attach an inline-source static-position rectangle and replace the
    /// physical page-top fallback with its captured inline edge.
    ///
    /// Vertical inline layout resolves automatic physical `top`/`bottom`
    /// through the scalar fallback before the rectangle's alignment payload.
    /// Retaining an ancestor's earlier page-top value here would therefore
    /// discard the hypothetical inline placeholder edge that this rectangle
    /// just captured.
    /// <https://drafts.csswg.org/css-position-3/#staticpos-rect>
    pub(in crate::layout) fn with_inline_static_position_rectangle(
        mut self,
        rectangle: StaticPositionRectangle,
    ) -> Self {
        self.page_top_y = rectangle.area.top_y();
        self.has_vertical_position = true;
        self.with_static_position_rectangle(rectangle)
    }

    pub(in crate::layout) fn static_position_rectangle(self) -> Option<StaticPositionRectangle> {
        match self.static_alignment_source {
            Some(StaticAlignmentSource::OrdinaryFlow { rectangle, .. }) => Some(rectangle),
            Some(StaticAlignmentSource::FormattingContext(_)) | None => None,
        }
    }

    pub(in crate::layout) fn static_alignment(self) -> Option<AbsposStaticAlignment> {
        match self.static_alignment_source {
            Some(StaticAlignmentSource::OrdinaryFlow { alignment, .. }) => alignment,
            Some(StaticAlignmentSource::FormattingContext(alignment)) => Some(alignment),
            None => None,
        }
    }

    /// Whether a formatting context (currently Flexbox or Grid) supplied the
    /// static-position alignment rectangle. Such a rectangle has not already
    /// selected an ordinary-flow hypothetical margin-box edge, even when its
    /// effective alignment is `normal`.
    pub(in crate::layout) fn has_formatting_context_static_alignment(self) -> bool {
        matches!(
            self.static_alignment_source,
            Some(StaticAlignmentSource::FormattingContext(_))
        )
    }

    /// The degenerate rectangle of a block-level source in a horizontal
    /// formatting context. Its inline span and hypothetical block-start are
    /// captured while normal flow still knows the source fragment.
    /// <https://drafts.csswg.org/css-position-3/#staticpos-rect>
    pub(in crate::layout) fn horizontal_block_static_rectangle(self) -> Option<PageTopRect> {
        self.has_vertical_position.then(|| {
            PageTopRect::new(
                self.page_left_x,
                self.page_top_y,
                (self.page_right_x - self.page_left_x).max(0.0),
                0.0,
            )
        })
    }

    pub(in crate::layout) fn horizontal_position(
        self,
        containing_block: ContainingBlock,
    ) -> PhysicalStaticAxisFallback {
        let left = self.page_left_x - containing_block.x();
        let right = containing_block.x() + containing_block.width() - self.page_right_x;
        if self.horizontal_can_fall_outside {
            PhysicalStaticAxisFallback::new_unclamped(left, right)
        } else {
            PhysicalStaticAxisFallback::new(left, right)
        }
    }

    pub(in crate::layout) fn vertical_start(self, containing_block: ContainingBlock) -> f32 {
        containing_block.top_y() - self.page_top_y
    }

    pub(in crate::layout) const fn has_vertical_position(self) -> bool {
        self.has_vertical_position
    }
}

#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct InlineLineMetrics {
    pub(in crate::layout) width: f32,
    pub(in crate::layout) height: f32,
    pub(in crate::layout) baseline_offset: f32,
}

#[derive(Debug, Clone, Copy, Default)]
pub(in crate::layout) struct HangingPunctuationWidths {
    pub(in crate::layout) start: f32,
    pub(in crate::layout) end: f32,
}

/// A positioned inline line ready for painting.
///
/// CSS Inline Layout constructs a line box before painting its inline
/// fragments. This prepared line stores the resolved line metrics and ordered
/// paint items so text shaping, atom placement, backgrounds, links, and
/// decorations consume one reusable line artifact:
/// <https://www.w3.org/TR/css-inline-3/#line-box>.
#[derive(Debug, Clone)]
pub(in crate::layout) struct PreparedInlineLine {
    pub(in crate::layout) metrics: InlineLineMetrics,
    pub(in crate::layout) paint_items: Vec<PreparedInlinePaintItem>,
    /// Used content-edge geometry for positioned inline ancestors on this
    /// line. This is layout output, not paint metadata: bidi can split one
    /// inline into disjoint visual fragments, while CSS Positioned Layout
    /// selects the start-most and end-most content edges independently.
    /// <https://drafts.csswg.org/css-position-3/#def-cb>
    pub(in crate::layout) positioning_geometry: Vec<PreparedInlinePositioningGeometry>,
    /// Origin-owned decorating-box fragment geometry selected for this line.
    /// It is intentionally separate from text receiver provenance, which is
    /// segmented for paint but cannot define CSS percentage bases.
    pub(in crate::layout) decoration_origin_fragments:
        Rc<[crate::layout::text_paint::TextDecorationOriginFragmentGeometry]>,
}

/// Logical content-edge extrema contributed by one positioned inline on one
/// prepared line. The four coordinates deliberately do not form a rectangle:
/// disjoint bidi fragments can contribute different extrema.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct PreparedInlineLogicalContentEdges {
    inline_start: InlinePositioningInlineCoordinate,
    inline_end: InlinePositioningInlineCoordinate,
    block_start: InlinePositioningBlockCoordinate,
    block_end: InlinePositioningBlockCoordinate,
}

impl PreparedInlineLogicalContentEdges {
    fn from_rect(rect: PageTopRect, axes: WritingModeAxes) -> Self {
        Self {
            inline_start: InlinePositioningLogicalCoordinate::from_rect_side(
                rect,
                axes.physical_side(LogicalSide::InlineStart),
            ),
            inline_end: InlinePositioningLogicalCoordinate::from_rect_side(
                rect,
                axes.physical_side(LogicalSide::InlineEnd),
            ),
            block_start: InlinePositioningLogicalCoordinate::from_rect_side(
                rect,
                axes.physical_side(LogicalSide::BlockStart),
            ),
            block_end: InlinePositioningLogicalCoordinate::from_rect_side(
                rect,
                axes.physical_side(LogicalSide::BlockEnd),
            ),
        }
    }

    fn extend_with_rect(&mut self, rect: PageTopRect, axes: WritingModeAxes) {
        let candidate = Self::from_rect(rect, axes);
        self.inline_start = self.inline_start.farther_toward(
            candidate.inline_start,
            axes.physical_side(LogicalSide::InlineStart),
        );
        self.inline_end = self.inline_end.farther_toward(
            candidate.inline_end,
            axes.physical_side(LogicalSide::InlineEnd),
        );
        self.block_start = self.block_start.farther_toward(
            candidate.block_start,
            axes.physical_side(LogicalSide::BlockStart),
        );
        self.block_end = self.block_end.farther_toward(
            candidate.block_end,
            axes.physical_side(LogicalSide::BlockEnd),
        );
    }

    pub(in crate::layout) fn start_corner(self) -> InlinePositioningLogicalCorner {
        InlinePositioningLogicalCorner {
            inline: self.inline_start,
            block: self.block_start,
        }
    }

    pub(in crate::layout) fn end_corner(self) -> InlinePositioningLogicalCorner {
        InlinePositioningLogicalCorner {
            inline: self.inline_end,
            block: self.block_end,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum InlinePositioningInlineAxis {}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum InlinePositioningBlockAxis {}

/// A page-space coordinate whose value is associated with one logical axis.
///
/// The scalar is already physically projected, but the axis marker prevents
/// callers from swapping the inline and block components before the named
/// containing-block adapter consumes them.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct InlinePositioningLogicalCoordinate<Axis> {
    physical_page_coordinate: f32,
    axis: std::marker::PhantomData<Axis>,
}

pub(in crate::layout) type InlinePositioningInlineCoordinate =
    InlinePositioningLogicalCoordinate<InlinePositioningInlineAxis>;
pub(in crate::layout) type InlinePositioningBlockCoordinate =
    InlinePositioningLogicalCoordinate<InlinePositioningBlockAxis>;

impl<Axis> InlinePositioningLogicalCoordinate<Axis> {
    pub(in crate::layout) const fn new(physical_page_coordinate: f32) -> Self {
        Self {
            physical_page_coordinate,
            axis: std::marker::PhantomData,
        }
    }

    fn from_rect_side(rect: PageTopRect, side: PhysicalSide) -> Self {
        Self::new(match side {
            PhysicalSide::Left => rect.x(),
            PhysicalSide::Right => rect.x() + rect.width(),
            PhysicalSide::Top => rect.top_y(),
            PhysicalSide::Bottom => rect.bottom_y(),
        })
    }

    fn farther_toward(self, candidate: Self, side: PhysicalSide) -> Self {
        let physical_page_coordinate = match side {
            PhysicalSide::Left | PhysicalSide::Bottom => self
                .physical_page_coordinate
                .min(candidate.physical_page_coordinate),
            PhysicalSide::Right | PhysicalSide::Top => self
                .physical_page_coordinate
                .max(candidate.physical_page_coordinate),
        };
        Self::new(physical_page_coordinate)
    }

    pub(in crate::layout) const fn physical_page_coordinate(self) -> f32 {
        self.physical_page_coordinate
    }
}

/// A logical corner whose coordinates remain associated with their axes until
/// the containing-block writing mode projects them into page space.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(in crate::layout) struct InlinePositioningLogicalCorner {
    pub(in crate::layout) inline: InlinePositioningInlineCoordinate,
    pub(in crate::layout) block: InlinePositioningBlockCoordinate,
}

/// Prepared geometry belonging to one positioned inline source on one line.
#[derive(Debug, Clone, PartialEq)]
pub(in crate::layout) struct PreparedInlinePositioningGeometry {
    pub(in crate::layout) source: InlinePositioningContainingBlockId,
    pub(in crate::layout) axes: WritingModeAxes,
    pub(in crate::layout) content_edges: Option<PreparedInlineLogicalContentEdges>,
    pub(in crate::layout) start_marker: Option<PageTopRect>,
    pub(in crate::layout) end_marker: Option<PageTopRect>,
}

impl PreparedInlinePositioningGeometry {
    pub(in crate::layout) fn new(
        source: InlinePositioningContainingBlockId,
        axes: WritingModeAxes,
    ) -> Self {
        Self {
            source,
            axes,
            content_edges: None,
            start_marker: None,
            end_marker: None,
        }
    }

    pub(in crate::layout) fn record_content_rect(&mut self, rect: PageTopRect) {
        if let Some(edges) = &mut self.content_edges {
            edges.extend_with_rect(rect, self.axes);
        } else {
            self.content_edges = Some(PreparedInlineLogicalContentEdges::from_rect(
                rect, self.axes,
            ));
        }
    }

    pub(in crate::layout) fn record_marker(&mut self, edge: InlineLogicalEdge, rect: PageTopRect) {
        match edge {
            InlineLogicalEdge::Start => self.start_marker = Some(rect),
            InlineLogicalEdge::End => self.end_marker = Some(rect),
        }
    }

    pub(in crate::layout) fn start_corner(&self) -> Option<InlinePositioningLogicalCorner> {
        self.content_edges
            .map(PreparedInlineLogicalContentEdges::start_corner)
            .or_else(|| {
                self.start_marker.map(|marker| {
                    PreparedInlineLogicalContentEdges::from_rect(marker, self.axes).start_corner()
                })
            })
    }

    pub(in crate::layout) fn end_corner(&self) -> Option<InlinePositioningLogicalCorner> {
        self.content_edges
            .map(PreparedInlineLogicalContentEdges::end_corner)
            .or_else(|| {
                self.end_marker.map(|marker| {
                    PreparedInlineLogicalContentEdges::from_rect(marker, self.axes).end_corner()
                })
            })
    }
}

/// A positioned inline paint item inside a prepared line box.
///
/// CSS painting observes source/line-box order: inline fragment backgrounds
/// are painted for each line fragment, shaped text groups are emitted on the
/// same baseline, and atomic inline boxes paint as indivisible margin boxes:
/// <https://www.w3.org/TR/CSS22/zindex.html> and
/// <https://www.w3.org/TR/css-inline-3/#model>.
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub(in crate::layout) enum PreparedInlinePaintItem {
    FragmentBackground(PreparedInlineFragment),
    TextGroup(PreparedInlineTextGroup),
    Atom(PreparedInlineAtom),
    Scope(Box<PreparedInlinePaintScope>),
}

/// The generated inline-like box that owns a prepared paint-effect subtree.
///
/// Keeping this hierarchy in prepared layout output makes non-inherited
/// effects apply once to the generated box and all of its contents, rather
/// than being copied onto independently painted descendants.
/// <https://drafts.csswg.org/css-pseudo-4/#first-line-styling> and
/// <https://drafts.csswg.org/css-color-4/#transparency>
#[derive(Debug, Clone)]
pub(in crate::layout) struct PreparedInlinePaintScope {
    pub(in crate::layout) kind: PreparedInlinePaintScopeKind,
    pub(in crate::layout) opacity: css::Opacity,
    pub(in crate::layout) items: Vec<PreparedInlinePaintItem>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(in crate::layout) enum PreparedInlinePaintScopeKind {
    FirstLine,
}

impl PreparedInlinePaintItem {
    /// Visit leaf paint items in tree order, descending through generated
    /// paint scopes without exposing scope representation to geometry users.
    pub(in crate::layout) fn for_each_leaf<'a>(
        &'a self,
        visit: &mut impl FnMut(&'a PreparedInlinePaintItem),
    ) {
        match self {
            Self::Scope(scope) => {
                for item in &scope.items {
                    item.for_each_leaf(visit);
                }
            }
            Self::FragmentBackground(_) | Self::TextGroup(_) | Self::Atom(_) => visit(self),
        }
    }

    fn find_map_leaf<'a, T>(
        &'a self,
        find: &mut impl FnMut(&'a PreparedInlinePaintItem) -> Option<T>,
    ) -> Option<T> {
        match self {
            Self::Scope(scope) => scope.items.iter().find_map(|item| item.find_map_leaf(find)),
            Self::FragmentBackground(_) | Self::TextGroup(_) | Self::Atom(_) => find(self),
        }
    }
}

impl PreparedInlineLine {
    /// Visit every prepared leaf while preserving nested effect-scope order.
    pub(in crate::layout) fn for_each_paint_leaf<'a>(
        &'a self,
        mut visit: impl FnMut(&'a PreparedInlinePaintItem),
    ) {
        for item in &self.paint_items {
            item.for_each_leaf(&mut visit);
        }
    }

    pub(in crate::layout) fn find_map_paint_leaf<'a, T>(
        &'a self,
        mut find: impl FnMut(&'a PreparedInlinePaintItem) -> Option<T>,
    ) -> Option<T> {
        self.paint_items
            .iter()
            .find_map(|item| item.find_map_leaf(&mut find))
    }
}

/// A positioned inline text fragment with its line-fragment geometry.
///
/// CSS Backgrounds and Borders paints inline backgrounds and borders per
/// generated line fragment, while CSS Text may shape adjacent fragments as one
/// typographic context. Keeping both the original fragment and its used
/// geometry lets background/decor/link painting stay fragment-specific:
/// <https://www.w3.org/TR/css-backgrounds-3/#box-decoration-break> and
/// <https://www.w3.org/TR/css-text-3/#boundary-shaping>.
#[derive(Debug, Clone)]
pub(in crate::layout) struct PreparedInlineFragment {
    pub(in crate::layout) fragment: InlineFragment,
    pub(in crate::layout) rect: PhysicalInlineRect,
}

/// A positioned atomic inline box with resolved content geometry.
///
/// CSS 2.2 treats inline-blocks, replaced elements, and similar atomic inline
/// boxes as a single inline-level box participating in the parent line box:
/// <https://www.w3.org/TR/CSS22/visuren.html#inline-boxes>.
#[derive(Debug, Clone)]
pub(in crate::layout) struct PreparedInlineAtom {
    pub(in crate::layout) atom: InlineAtom,
    /// The resolved physical border box to paint after the atom's separate
    /// margin-box participation has selected its line position.
    pub(in crate::layout) border_box: PhysicalInlineRect,
}

/// A shaped group of adjacent inline text fragments.
///
/// CSS Text requires boundary shaping to preserve cursive and complex-script
/// context across eligible inline boxes. This group stores the exact Parley
/// shaped runs selected before painting, including resolved font ids and
/// glyph advances used later by PDF text emission:
/// <https://www.w3.org/TR/css-text-3/#boundary-shaping>,
/// <https://www.w3.org/TR/css-fonts-4/#font-matching-algorithm>, and
/// ISO 32000-2:2020, 9.10.3 "ToUnicode CMaps".
#[derive(Debug, Clone)]
pub(in crate::layout) struct PreparedInlineTextGroup {
    pub(in crate::layout) bounds: PhysicalInlineTextBounds,
    pub(in crate::layout) style: ComputedStyle,
    /// Logical block-size of the containing line box.
    ///
    /// A rotated sideways run aligns its horizontal font metrics within this
    /// line box rather than within its own `line-height` value.
    /// <https://www.w3.org/TR/css-inline-3/#line-box>
    pub(in crate::layout) line_block_size: f32,
    /// Lexical decoration receivers preserved alongside a shared shaped run.
    ///
    /// CSS Text allows shaping across transparent inline boundaries, but line
    /// decoration propagation stops at the lexical receivers that carry a
    /// given origin.  These segments therefore affect only decoration paint;
    /// `shaped` remains the single glyph program used for PDF text output.
    /// <https://drafts.csswg.org/css-text-decor-4/#line-decoration>
    pub(in crate::layout) decoration_provenance: Vec<PreparedTextDecorationProvenanceSegment>,
    /// Block-axis trim belonging to the inline scope that owns this text.
    /// The text style itself may not carry the value because `text-box-trim`
    /// is not inherited, while the inline scope's background and link still
    /// cover this descendant text:
    /// <https://drafts.csswg.org/css-inline-3/#text-box-trim>.
    pub(in crate::layout) text_box_trim: TextBoxLineTrim,
    /// The product of this text run's used opacity and each owning inline
    /// effect scope. Opacity is non-inherited, so its lexical owners are
    /// retained separately from the text style through inline collection.
    /// <https://www.w3.org/TR/css-color-4/#transparency>
    pub(in crate::layout) paint_opacity: f32,
    /// Lexical opacity scopes, from outermost to innermost, that own this
    /// prepared text.  This keeps paint-effect ancestry explicit after text
    /// collection, typographic splitting, bidi reordering, and shaping.
    pub(in crate::layout) paint_scope_ancestry: Rc<[InlinePaintScopeId]>,
    /// The innermost lexical inline scope that owns this text group's
    /// positioned stacking context.  The scope's style is retained because
    /// descendant text itself inherits typography, not `position` or
    /// `z-index`.
    pub(in crate::layout) positioned_paint_style: Option<ComputedStyle>,
    pub(in crate::layout) link_target: Option<String>,
    pub(in crate::layout) link_paint_rect: Option<PaintRect>,
    pub(in crate::layout) decoration_paint_rect: Option<PaintRect>,
    pub(in crate::layout) shaped: ShapedInlineLine,
    /// Plain-text replacement for a shaped group containing one or more
    /// layout-only `word-space-transform` separators.
    ///
    /// The group can retain one continuous glyph stream while PDF output
    /// restores authored U+200B characters and omits generated `<wbr>` text.
    /// <https://drafts.csswg.org/css-text-4/#word-space-transform>
    pub(in crate::layout) actual_text: Option<Rc<str>>,
    pub(in crate::layout) source: InlineTextSource,
    pub(in crate::layout) source_run: Rc<()>,
}

/// Consecutive receiver ranges that carry the same ordered decoration-origin
/// chain.  Equality of declarations is not enough: `Rc` identity distinguishes
/// nested equal-looking decorating boxes.
#[derive(Debug, Clone)]
pub(in crate::layout) struct PreparedTextDecorationProvenanceSegment {
    pub(in crate::layout) layers: Vec<css::TextDecorationLayer>,
    pub(in crate::layout) receivers: Vec<PreparedTextDecorationReceiver>,
}

/// One source fragment's physical receiver span within a shaped text group.
#[derive(Debug, Clone)]
pub(in crate::layout) struct PreparedTextDecorationReceiver {
    pub(in crate::layout) inline_span: TextInlineSpan,
    pub(in crate::layout) style: ComputedStyle,
}

impl PreparedInlineTextGroup {
    pub(in crate::layout) fn x(&self) -> f32 {
        self.bounds.x()
    }

    pub(in crate::layout) fn y(&self) -> f32 {
        self.bounds.y()
    }

    pub(in crate::layout) fn width(&self) -> f32 {
        self.bounds.width()
    }

    pub(in crate::layout) fn set_x(&mut self, x: f32) {
        self.bounds.set_x(x);
    }

    pub(in crate::layout) fn set_y(&mut self, y: f32) {
        self.bounds.set_y(y);
    }

    pub(in crate::layout) fn set_width(&mut self, width: f32) {
        self.bounds.set_width(width);
    }

    pub(in crate::layout) fn link_paint_rect(&self) -> PaintRect {
        self.link_paint_rect
            .unwrap_or_else(|| self.bounds.link_paint_rect(self.style.font_size))
    }
}

/// Logical inline-axis geometry for one prepared line.
///
/// CSS Writing Modes defines inline layout in logical inline/block axes, while
/// PDF painting consumes physical coordinates. This geometry keeps CSS Text
/// alignment, indentation, and hanging punctuation in logical inline space
/// until each fragment, text group, or atomic inline box is converted to a
/// physical paint artifact:
/// <https://www.w3.org/TR/css-writing-modes-4/#abstract-box> and
/// <https://www.w3.org/TR/css-text-3/#text-align-property>.
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct InlineLineGeometry {
    pub(in crate::layout) writing_mode: WritingMode,
    pub(in crate::layout) direction: Direction,
    /// Offset from the block content edge to this line's logical inline start.
    /// Tabs use the content edge as their periodic-stop origin, rather than
    /// the potentially indented line start.
    pub(in crate::layout) inline_start_offset: f32,
    pub(in crate::layout) inline_start: f32,
    pub(in crate::layout) inline_size: f32,
    pub(in crate::layout) block_start: f32,
    /// Logical block-size of this line box, retained for its text paint
    /// groups after the physical block-start projection.
    pub(in crate::layout) line_block_size: f32,
    /// Block-axis trim applied to this selected line. The trim is stored on
    /// the line record rather than the paint group's style when an inline box
    /// is the source of the trim, so links and decorations can use the same
    /// content rectangle as the inline background.
    pub(in crate::layout) text_box_line_trim: TextBoxLineTrim,
}

/// Physical rectangle for an inline line-fragment paint item.
///
/// CSS Inline Layout first positions fragments in logical inline/block axes,
/// then CSS Writing Modes maps those fragments to physical coordinates. This
/// rectangle stores that resolved physical box in the current layout container
/// before it is projected into paint primitives:
/// <https://www.w3.org/TR/css-inline-3/#line-layout> and
/// <https://www.w3.org/TR/css-writing-modes-4/#abstract-box>.
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct PhysicalInlineRect {
    pub(in crate::layout) rect: InlineRect,
}

impl PhysicalInlineRect {
    pub(in crate::layout) fn new(rect: InlineRect) -> Self {
        Self {
            rect: InlineRect::new(
                rect.origin,
                InlineSize::new(rect.size.width.max(0.0), rect.size.height.max(0.0)),
            ),
        }
    }

    pub(in crate::layout) fn x(self) -> f32 {
        self.rect.origin.x
    }

    pub(in crate::layout) fn y(self) -> f32 {
        self.rect.origin.y
    }

    pub(in crate::layout) fn width(self) -> f32 {
        self.rect.size.width
    }

    pub(in crate::layout) fn height(self) -> f32 {
        self.rect.size.height
    }

    pub(in crate::layout) fn translated(self, offset: InlineVisualOffset) -> Self {
        if offset.is_zero() {
            return self;
        }
        Self::new(InlineRect::new(
            InlinePoint::new(self.x() + offset.x(), self.y() + offset.y()),
            self.rect.size,
        ))
    }

    pub(in crate::layout) fn paint_rect(self) -> PaintRect {
        PaintRect::new(
            PaintPoint::new(self.x(), self.y()),
            PaintSize::new(self.width(), self.height()),
        )
    }

    pub(in crate::layout) fn paint_clip(self) -> PaintClip {
        PaintClip::from_paint_rect(self.paint_rect())
    }
}

/// Baseline-origin geometry for one prepared shaped inline text group.
///
/// CSS Inline Layout positions text by a baseline point and an inline advance,
/// not by a full border box. The baseline origin is stored in resolved physical
/// inline formatting coordinates so painting, decoration, and link annotation
/// code all project through one typed boundary:
/// <https://www.w3.org/TR/css-inline-3/#baseline-tables> and
/// <https://www.w3.org/TR/css-text-3/#boundary-shaping>.
#[derive(Debug, Clone, Copy)]
pub(in crate::layout) struct PhysicalInlineTextBounds {
    pub(in crate::layout) baseline_origin: InlinePoint,
    pub(in crate::layout) inline_size: f32,
}

#[cfg(test)]
mod child_available_space_tests {
    use super::*;

    #[test]
    fn orthogonal_fallback_is_not_a_percentage_basis() {
        let space = ChildAvailableSpace::new(
            WritingMode::HorizontalTb,
            PhysicalContentWidth::new(content_box_pt(300.0)),
            true,
            None,
            PhysicalContentHeight::new(content_box_pt(200.0)),
        );

        assert_eq!(space.available_physical_height().points(), 200.0);
        assert!(!space.physical_height_percentage_basis().is_definite());
        assert!(
            !space
                .logical_inline_percentage_basis_for(WritingMode::VerticalRl)
                .is_definite()
        );
        assert_eq!(
            space.logical_inline_percentage_basis_for(WritingMode::HorizontalTb),
            PercentageBasis::definite(LogicalInlineContentSize::new(content_box_pt(300.0)))
        );
    }

    #[test]
    fn definite_perpendicular_size_projects_to_vertical_percentage_basis() {
        let space = ChildAvailableSpace::new(
            WritingMode::HorizontalTb,
            PhysicalContentWidth::new(content_box_pt(300.0)),
            true,
            Some(PhysicalContentHeight::new(content_box_pt(200.0))),
            PhysicalContentHeight::new(content_box_pt(500.0)),
        );

        assert_eq!(
            space.logical_inline_percentage_basis_for(WritingMode::VerticalLr),
            PercentageBasis::definite(LogicalInlineContentSize::new(content_box_pt(200.0)))
        );
    }

    #[test]
    fn auto_vertical_block_width_is_not_a_horizontal_percentage_basis() {
        let space = ChildAvailableSpace::new(
            WritingMode::VerticalLr,
            PhysicalContentWidth::new(content_box_pt(0.0)),
            false,
            None,
            PhysicalContentHeight::new(content_box_pt(500.0)),
        );

        assert!(
            !space
                .logical_inline_percentage_basis_for(WritingMode::HorizontalTb)
                .is_definite()
        );
    }

    #[test]
    fn scrollport_availability_stays_indefinite_for_percentages() {
        let space = ChildAvailableSpace::new(
            WritingMode::HorizontalTb,
            PhysicalContentWidth::new(content_box_pt(300.0)),
            true,
            None,
            PhysicalContentHeight::new(content_box_pt(500.0)),
        )
        .with_orthogonal_available_height(
            OrthogonalAvailableHeight::nearest_scroll_container(PhysicalContentHeight::new(
                content_box_pt(120.0),
            )),
        );

        assert_eq!(space.available_physical_height().points(), 120.0);
        assert!(matches!(
            space.orthogonal_available_height,
            OrthogonalAvailableHeight::NearestScrollContainer(_)
        ));
        assert!(
            !space
                .logical_inline_percentage_basis_for(WritingMode::VerticalRl)
                .is_definite()
        );
    }

    #[test]
    fn abspos_static_alignment_centers_both_physical_axes() {
        let alignment = AbsposStaticAlignment::new(
            PageTopRect::new(10.0, 80.0, 100.0, 60.0),
            WritingMode::HorizontalTb,
            Direction::Ltr,
            WritingMode::HorizontalTb,
            Direction::Ltr,
            css::SelfAlignment::new(SelfAlignmentKeyword::Center),
            css::SelfAlignment::new(SelfAlignmentKeyword::Center),
        );
        let containing_block =
            ContainingBlock::from_page_top_rect(PageTopRect::new(10.0, 80.0, 100.0, 60.0));

        let horizontal = alignment.horizontal_static_position(containing_block, 20.0, 0.0, 0.0);
        let vertical = alignment.vertical_static_start(containing_block, 20.0, 0.0, 0.0);

        assert_eq!(horizontal.left, 40.0);
        assert_eq!(horizontal.right, 40.0);
        assert_eq!(vertical, 20.0);
    }

    #[test]
    fn abspos_static_alignment_returns_horizontal_margin_box_insets() {
        let containing_block =
            ContainingBlock::from_page_top_rect(PageTopRect::new(10.0, 80.0, 100.0, 60.0));
        let start = AbsposStaticAlignment::new(
            containing_block.rect,
            WritingMode::HorizontalTb,
            Direction::Ltr,
            WritingMode::HorizontalTb,
            Direction::Ltr,
            css::SelfAlignment::new(SelfAlignmentKeyword::Start),
            css::SelfAlignment::NORMAL,
        )
        .horizontal_static_position(containing_block, 20.0, 7.0, 11.0);
        assert_eq!((start.left, start.right), (0.0, 62.0));

        let end = AbsposStaticAlignment::new(
            containing_block.rect,
            WritingMode::HorizontalTb,
            Direction::Ltr,
            WritingMode::HorizontalTb,
            Direction::Ltr,
            css::SelfAlignment::new(SelfAlignmentKeyword::End),
            css::SelfAlignment::NORMAL,
        )
        .horizontal_static_position(containing_block, 20.0, 7.0, 11.0);
        assert_eq!((end.left, end.right), (62.0, 0.0));
    }

    #[test]
    fn abspos_static_alignment_returns_vertical_margin_box_insets() {
        let containing_block =
            ContainingBlock::from_page_top_rect(PageTopRect::new(10.0, 80.0, 100.0, 60.0));
        let start = AbsposStaticAlignment::new(
            containing_block.rect,
            WritingMode::HorizontalTb,
            Direction::Ltr,
            WritingMode::HorizontalTb,
            Direction::Ltr,
            css::SelfAlignment::NORMAL,
            css::SelfAlignment::new(SelfAlignmentKeyword::Start),
        )
        .vertical_static_start(containing_block, 20.0, 7.0, 11.0);
        assert_eq!(start, 0.0);

        let end = AbsposStaticAlignment::new(
            containing_block.rect,
            WritingMode::HorizontalTb,
            Direction::Ltr,
            WritingMode::HorizontalTb,
            Direction::Ltr,
            css::SelfAlignment::NORMAL,
            css::SelfAlignment::new(SelfAlignmentKeyword::End),
        )
        .vertical_static_start(containing_block, 20.0, 7.0, 11.0);
        assert_eq!(end, 22.0);
    }

    #[test]
    fn abspos_static_alignment_maps_vertical_writing_inline_axis() {
        let alignment = AbsposStaticAlignment::new(
            PageTopRect::new(0.0, 100.0, 80.0, 120.0),
            WritingMode::VerticalLr,
            Direction::Ltr,
            WritingMode::VerticalLr,
            Direction::Ltr,
            css::SelfAlignment::new(SelfAlignmentKeyword::End),
            css::SelfAlignment::new(SelfAlignmentKeyword::Start),
        );
        let containing_block =
            ContainingBlock::from_page_top_rect(PageTopRect::new(0.0, 100.0, 80.0, 120.0));

        // In vertical-lr, physical Y is the logical inline axis; the inline
        // `end` therefore positions a 20pt subject at 100pt in a 120pt area.
        assert_eq!(
            alignment.vertical_static_start(containing_block, 20.0, 0.0, 0.0),
            100.0
        );
    }

    #[test]
    fn vertical_rtl_inline_static_rectangle_aligns_the_subject_bottom_to_inline_start() {
        let alignment = AbsposStaticAlignment::new(
            // In page-top coordinates the selected line's logical
            // inline-start is its physical bottom edge.
            PageTopRect::new(0.0, 80.0, 20.0, 0.0),
            WritingMode::VerticalLr,
            Direction::Rtl,
            WritingMode::VerticalLr,
            Direction::Ltr,
            css::SelfAlignment::NORMAL,
            css::SelfAlignment::NORMAL,
        );
        let containing_block =
            ContainingBlock::from_page_top_rect(PageTopRect::new(0.0, 200.0, 80.0, 120.0));

        // `normal` resolves to the static containing block's inline-start.
        // The 20pt subject therefore extends upward from the 80pt inline
        // edge, leaving its physical top at 100pt: `start = 200 - 100`.
        assert_eq!(
            alignment.vertical_static_start(containing_block, 20.0, 0.0, 0.0),
            100.0
        );
    }

    #[test]
    fn abspos_self_start_uses_the_subject_direction() {
        let alignment = AbsposStaticAlignment::new(
            PageTopRect::new(10.0, 80.0, 80.0, 0.0),
            WritingMode::HorizontalTb,
            Direction::Ltr,
            WritingMode::HorizontalTb,
            Direction::Rtl,
            css::SelfAlignment::new(SelfAlignmentKeyword::SelfStart),
            css::SelfAlignment::NORMAL,
        );
        let containing_block =
            ContainingBlock::from_page_top_rect(PageTopRect::new(0.0, 100.0, 100.0, 100.0));

        let position = alignment.horizontal_static_position(containing_block, 20.0, 0.0, 0.0);
        assert_eq!(position.left, 70.0);
        assert_eq!(position.right, 10.0);
    }

    #[test]
    fn degenerate_inline_static_rectangle_still_centers_on_the_line() {
        let alignment = AbsposStaticAlignment::new(
            PageTopRect::new(40.0, 80.0, 0.0, 25.0),
            WritingMode::HorizontalTb,
            Direction::Ltr,
            WritingMode::HorizontalTb,
            Direction::Ltr,
            css::SelfAlignment::NORMAL,
            css::SelfAlignment::new(SelfAlignmentKeyword::Center),
        );
        let containing_block =
            ContainingBlock::from_page_top_rect(PageTopRect::new(0.0, 100.0, 100.0, 100.0));

        assert_eq!(
            alignment.vertical_static_start(containing_block, 50.0, 0.0, 0.0),
            7.5
        );
    }

    #[test]
    fn inline_static_rectangle_end_alignment_uses_its_line_under_edge() {
        let alignment = AbsposStaticAlignment::new(
            // An inline source has a degenerate inline axis but spans the
            // selected line in the physical block axis.
            PageTopRect::new(40.0, 80.0, 0.0, 37.5),
            WritingMode::HorizontalTb,
            Direction::Ltr,
            WritingMode::HorizontalTb,
            Direction::Ltr,
            css::SelfAlignment::NORMAL,
            css::SelfAlignment::new(SelfAlignmentKeyword::End),
        );
        let containing_block =
            ContainingBlock::from_page_top_rect(PageTopRect::new(0.0, 80.0, 100.0, 37.5));

        // The aligned margin box starts at the line-under edge minus its
        // own size.  This value is consumed directly by the static inset
        // equation; no text-baseline replay may move it afterward.
        assert_eq!(
            alignment.vertical_static_start(containing_block, 15.0, 0.0, 0.0),
            22.5
        );
    }

    #[test]
    fn static_available_size_projects_the_selected_vertical_edge() {
        let alignment = AbsposStaticAlignment::new(
            PageTopRect::new(10.0, 80.0, 0.0, 0.0),
            WritingMode::HorizontalTb,
            Direction::Ltr,
            WritingMode::HorizontalTb,
            Direction::Ltr,
            css::SelfAlignment::NORMAL,
            css::SelfAlignment::new(SelfAlignmentKeyword::End),
        );
        let containing_block =
            ContainingBlock::from_page_top_rect(PageTopRect::new(0.0, 100.0, 100.0, 100.0));

        // A block-end-aligned zero-height static rectangle leaves the span
        // from that selected edge to the containing block's opposite edge.
        assert_eq!(
            alignment.available_outer_size(PhysicalAxis::Vertical, containing_block),
            Some(20.0)
        );
    }

    #[test]
    fn escaped_atom_positioning_keeps_outer_cb_and_static_axes_separate() {
        let actual_containing_block =
            ContainingBlock::from_page_top_rect(PageTopRect::new(48.0, 720.0, 500.0, 700.0))
                .on_page(3);
        let static_position = AtomicInlineStaticPosition::new(
            PageTopRect::new(0.0, 9_960.0, 120.0, 40.0),
            WritingModeAxes::new(WritingMode::HorizontalTb, Direction::Ltr),
        );
        let context = EscapedAtomPositioningContext {
            actual_containing_block,
            static_position,
        };

        assert_eq!(context.actual_containing_block, actual_containing_block);
        assert_eq!(context.actual_containing_block.origin_page_index, Some(3));
        assert_eq!(
            context.static_position.content_rect,
            PageTopRect::new(0.0, 9_960.0, 120.0, 40.0)
        );
        assert_eq!(
            context.static_position.axes,
            WritingModeAxes::new(WritingMode::HorizontalTb, Direction::Ltr)
        );

        let auto_axes = EscapedAtomReplay::for_positioned_box(
            context.actual_containing_block,
            false,
            true,
            true,
        )
        .resolve_from_capture_origin(PaintPoint::new(0.0, 9_940.0));
        assert_eq!(
            auto_axes.translation_to(PaintPoint::new(160.0, 640.0)),
            PaintTranslation::new(112.0, -9_300.0)
        );

        let explicit_axes = EscapedAtomReplay::for_positioned_box(
            context.actual_containing_block,
            false,
            false,
            false,
        )
        .resolve_from_capture_origin(PaintPoint::new(0.0, 9_940.0));
        assert_eq!(
            explicit_axes.translation_to(PaintPoint::new(160.0, 640.0)),
            PaintTranslation::identity()
        );
        assert_eq!(auto_axes.replay_page_index(7, 3), 7);
        assert_eq!(explicit_axes.replay_page_index(7, 3), 3);

        let atom_local_explicit = EscapedAtomReplay::for_positioned_box(
            context.actual_containing_block,
            true,
            false,
            false,
        )
        .resolve_from_capture_origin(PaintPoint::new(0.0, 9_940.0));
        assert_eq!(
            atom_local_explicit.translation_to(PaintPoint::new(160.0, 640.0)),
            PaintTranslation::new(160.0, -9_300.0)
        );
        assert_eq!(atom_local_explicit.replay_page_index(7, 3), 7);

        let rebased = atom_local_explicit
            .pending_in_enclosing_atomic_space()
            .resolve_from_capture_origin(PaintPoint::new(20.0, 8_000.0));
        assert_eq!(
            rebased.translation_to(PaintPoint::new(200.0, 500.0)),
            PaintTranslation::new(180.0, -7_500.0)
        );
    }

    #[test]
    fn escaped_atom_replay_uses_owner_specific_horizontal_sources() {
        let containing_block =
            ContainingBlock::from_page_top_rect(PageTopRect::new(40.0, 80.0, 50.0, 60.0));
        let capture_origin = PaintPoint::new(10.0, 70.0);
        let final_origin = PaintPoint::new(100.0, 20.0);

        let cases = [
            (false, false, PaintTranslation::identity()),
            (false, true, PaintTranslation::new(60.0, 0.0)),
            (true, false, PaintTranslation::new(90.0, -50.0)),
            (true, true, PaintTranslation::new(90.0, -50.0)),
        ];
        for (atom_owned, uses_static_x, expected) in cases {
            let replay = EscapedAtomReplay::for_positioned_box(
                containing_block,
                atom_owned,
                uses_static_x,
                atom_owned,
            )
            .resolve_from_capture_origin(capture_origin);
            assert_eq!(
                replay.translation_to(final_origin),
                expected,
                "atom_owned={atom_owned}, uses_static_x={uses_static_x}",
            );
        }
    }

    #[test]
    fn atomic_inline_static_position_projects_logical_axes() {
        let content_rect = PageTopRect::new(7.0, 91.0, 31.0, 47.0);
        for (writing_mode, direction, expected_area) in [
            (
                WritingMode::HorizontalTb,
                Direction::Ltr,
                PageTopRect::new(7.0, 91.0, 31.0, 0.0),
            ),
            (
                WritingMode::HorizontalTb,
                Direction::Rtl,
                PageTopRect::new(7.0, 91.0, 31.0, 0.0),
            ),
            (
                WritingMode::SidewaysRl,
                Direction::Ltr,
                PageTopRect::new(38.0, 91.0, 0.0, 47.0),
            ),
            (
                WritingMode::SidewaysRl,
                Direction::Rtl,
                PageTopRect::new(38.0, 91.0, 0.0, 47.0),
            ),
            (
                WritingMode::SidewaysLr,
                Direction::Ltr,
                PageTopRect::new(7.0, 91.0, 0.0, 47.0),
            ),
            (
                WritingMode::SidewaysLr,
                Direction::Rtl,
                PageTopRect::new(7.0, 91.0, 0.0, 47.0),
            ),
        ] {
            let source = AtomicInlineStaticPosition::new(
                content_rect,
                WritingModeAxes::new(writing_mode, direction),
            );
            let rectangle = source
                .in_atomic_space()
                .static_position_rectangle()
                .unwrap();
            assert_eq!(rectangle.area, expected_area);
            assert_eq!(rectangle.writing_mode, writing_mode);
            assert_eq!(rectangle.direction, direction);
        }
    }
}

#[cfg(test)]
mod inline_paint_scope_tests {
    use super::*;

    fn scope_decoration(scope_id: InlinePaintScopeId) -> InlineAncestorDecoration {
        let mut style = ComputedStyle::initial();
        style.opacity = css::Opacity::new_clamped(0.5).expect("finite opacity");
        InlineAncestorDecoration {
            style,
            hanging_edges: InlineHangingEdges::default(),
            paints_background_or_border: false,
            positioning_containing_block_id: None,
            paint_effect_scope_id: Some(scope_id),
        }
    }

    #[test]
    fn equal_opacity_siblings_remain_distinct_paint_scopes() {
        let left = scope_decoration(InlinePaintScopeId::allocate());
        let right = scope_decoration(InlinePaintScopeId::allocate());
        assert!(!inline_ancestor_decorations_have_same_text_paint_effect(
            &[left],
            &[right]
        ));
    }

    #[test]
    fn copied_scope_identity_survives_typographic_splitting() {
        let scope = InlinePaintScopeId::allocate();
        let decoration = scope_decoration(scope);
        let equivalent_decoration = decoration.clone();
        assert!(inline_ancestor_decorations_have_same_text_paint_effect(
            std::slice::from_ref(&decoration),
            std::slice::from_ref(&equivalent_decoration)
        ));
    }
}

#[cfg(test)]
mod inline_tracking_scope_tests {
    use super::*;

    fn scope_style() -> ComputedStyle {
        ComputedStyle::initial()
    }

    #[test]
    fn lowest_common_returns_an_identical_scope() {
        let scope = InlineTrackingScope::root(&scope_style());

        assert!(std::ptr::eq(
            InlineTrackingScope::lowest_common(&scope, &scope),
            scope.as_ref()
        ));
    }

    #[test]
    fn lowest_common_returns_the_ancestor_of_a_descendant() {
        let root = InlineTrackingScope::root(&scope_style());
        let child = InlineTrackingScope::child(Rc::clone(&root), &scope_style());
        let descendant = InlineTrackingScope::child(Rc::clone(&child), &scope_style());

        assert!(std::ptr::eq(
            InlineTrackingScope::lowest_common(&descendant, &child),
            child.as_ref()
        ));
    }

    #[test]
    fn lowest_common_returns_the_parent_of_sibling_scopes() {
        let root = InlineTrackingScope::root(&scope_style());
        let left = InlineTrackingScope::child(Rc::clone(&root), &scope_style());
        let right = InlineTrackingScope::child(Rc::clone(&root), &scope_style());

        assert!(std::ptr::eq(
            InlineTrackingScope::lowest_common(&left, &right),
            root.as_ref()
        ));
    }

    #[test]
    fn common_autospace_style_uses_the_innermost_shared_inline_scope() {
        let mut root_style = scope_style();
        root_style.font_size = 17.0;
        let mut child_style = root_style.clone();
        child_style.font_size = 43.0;
        let root = InlineTrackingScope::root(&root_style);
        let left = InlineTrackingScope::child(Rc::clone(&root), &child_style);
        let right = InlineTrackingScope::child(Rc::clone(&root), &child_style);

        assert_eq!(
            InlineTrackingScope::common_autospace_style(&left, &right).font_size,
            17.0
        );
        assert_eq!(
            InlineTrackingScope::common_autospace_style(&left, &left).font_size,
            43.0
        );
    }

    #[test]
    fn lowest_common_aligns_differently_nested_cousins() {
        let root = InlineTrackingScope::root(&scope_style());
        let left_branch = InlineTrackingScope::child(Rc::clone(&root), &scope_style());
        let left = InlineTrackingScope::child(left_branch, &scope_style());
        let right_branch = InlineTrackingScope::child(Rc::clone(&root), &scope_style());
        let right = InlineTrackingScope::child(
            InlineTrackingScope::child(right_branch, &scope_style()),
            &scope_style(),
        );

        assert!(std::ptr::eq(
            InlineTrackingScope::lowest_common(&left, &right),
            root.as_ref()
        ));
    }

    #[test]
    fn descendant_scope_retains_its_local_used_letter_spacing() {
        let mut tracked = scope_style();
        tracked.letter_spacing = crate::css::ComputedLengthPercentage::from_points(4.0);
        let root = InlineTrackingScope::root(&tracked);
        let descendant = InlineTrackingScope::child(root, &scope_style());

        assert_eq!(descendant.letter_spacing().points(), 0.0);
    }

    #[test]
    fn text_fit_scope_scales_percentage_tracking_but_not_fixed_tracking() {
        let mut percentage = scope_style();
        percentage.font_size = 20.0;
        percentage.letter_spacing = crate::css::ComputedLengthPercentage::from_percent(0.5);
        let percentage_scope = InlineTrackingScope::root(&percentage);
        assert_eq!(
            percentage_scope
                .scaled_for_text_fit(2.0)
                .letter_spacing()
                .points(),
            20.0
        );

        let mut fixed = scope_style();
        fixed.font_size = 20.0;
        fixed.letter_spacing = crate::css::ComputedLengthPercentage::from_points(10.0);
        let fixed_scope = InlineTrackingScope::root(&fixed);
        assert_eq!(
            fixed_scope
                .scaled_for_text_fit(2.0)
                .letter_spacing()
                .points(),
            10.0
        );
    }
}