ps-blitz-dom 0.5.1

Blitz DOM implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
use crate::NodeTree;
use crate::events::{DragMode, ScrollAnimationState, handle_dom_event};
use crate::font_metrics::BlitzFontMetricsProvider;
use crate::layout::construct::ConstructionTask;
use crate::layout::damage::ALL_DAMAGE;
use crate::mutator::ViewportMut;
use crate::net::{
    Resource, ResourceHandler, ResourceLoadResponse, StylesheetHandler, StylesheetLoader,
};
use crate::node::{
    ImageData, NodeFlags, RasterImageData, SpecialElementData, Status, TextBrush, TextGranularity,
};
use crate::selection::TextSelection;
use crate::stylo_to_cursor_icon::stylo_to_cursor_icon;
use crate::traversal::TreeTraverser;
use crate::url::DocumentUrl;
use crate::util::ImageType;
use crate::{
    DEFAULT_CSS, DocumentConfig, DocumentMutator, DummyHtmlParserProvider, ElementData,
    EventDriver, HtmlParserProvider, Node, NodeData, NoopEventHandler, StyleThreading,
    TextNodeData,
};
use blitz_traits::devtools::DevtoolSettings;
use blitz_traits::events::{BlitzScrollEvent, DomEvent, DomEventData, HitResult, UiEvent};
use blitz_traits::navigation::{DummyNavigationProvider, NavigationProvider};
use blitz_traits::net::{AbortSignal, DummyNetProvider, NetProvider, Request};
use blitz_traits::node_id::NodeId;
use blitz_traits::shell::{ColorScheme, DummyShellProvider, ShellProvider, Viewport};
use cursor_icon::CursorIcon;
use linebender_resource_handle::Blob;
use markup5ever::{local_name, ns};
use parley::{FontContext, PlainEditorDriver};
use rustc_hash::FxHashSet;
use selectors::{Element, matching::QuirksMode};
use smallvec::SmallVec;
use std::any::Any;
use std::cell::RefCell;
use std::collections::{BTreeMap, Bound, HashMap, HashSet};
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::str::FromStr;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, RwLockReadGuard, RwLockWriteGuard};
use std::task::{Context as TaskContext, Waker};
use style::Atom;
use style::animation::{AnimationState, DocumentAnimationSet};
use style::attr::{AttrIdentifier, AttrValue};
use style::data::{ElementData as StyloElementData, ElementStyles};
use style::media_queries::MediaType;
use style::properties::ComputedValues;
use style::properties::style_structs::Font;
use style::queries::values::PrefersColorScheme;
use style::selector_parser::ServoElementSnapshot;
use style::servo::media_features::PointerCapabilities;
use style::servo_arc::Arc as ServoArc;
use style::values::GenericAtomIdent;
use style::values::computed::ui::CursorKind;
use style::values::computed::{Overflow, UserSelect};
use style::values::specified::box_::{DisplayInside, DisplayOutside};
use style::{
    device::Device,
    dom::{TDocument, TNode},
    media_queries::MediaList,
    selector_parser::SnapshotMap,
    shared_lock::{SharedRwLock, StylesheetGuards},
    stylesheets::{AllowImportRules, DocumentStyleSheet, Origin, Stylesheet},
    stylist::Stylist,
};
use thin_vec::ThinVec;
use url::Url;
use web_time::Instant;

#[cfg(feature = "parallel-construct")]
use thread_local::ThreadLocal;

pub enum DocGuard<'a> {
    Ref(&'a BaseDocument),
    RefCell(std::cell::Ref<'a, BaseDocument>),
    RwLock(RwLockReadGuard<'a, BaseDocument>),
    Mutex(MutexGuard<'a, BaseDocument>),
}

impl Deref for DocGuard<'_> {
    type Target = BaseDocument;
    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        match self {
            Self::Ref(base_document) => base_document,
            Self::RefCell(refcell_guard) => refcell_guard,
            Self::RwLock(rw_lock_read_guard) => rw_lock_read_guard,
            Self::Mutex(mutex_guard) => mutex_guard,
        }
    }
}

pub enum DocGuardMut<'a> {
    Ref(&'a mut BaseDocument),
    RefCell(std::cell::RefMut<'a, BaseDocument>),
    RwLock(RwLockWriteGuard<'a, BaseDocument>),
    Mutex(MutexGuard<'a, BaseDocument>),
}

impl Deref for DocGuardMut<'_> {
    type Target = BaseDocument;
    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        match self {
            Self::Ref(base_document) => base_document,
            Self::RefCell(refcell_guard) => refcell_guard,
            Self::RwLock(rw_lock_read_guard) => rw_lock_read_guard,
            Self::Mutex(mutex_guard) => mutex_guard,
        }
    }
}

impl DerefMut for DocGuardMut<'_> {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut Self::Target {
        match self {
            Self::Ref(base_document) => base_document,
            Self::RefCell(refcell_guard) => &mut *refcell_guard,
            Self::RwLock(rw_lock_read_guard) => &mut *rw_lock_read_guard,
            Self::Mutex(mutex_guard) => &mut *mutex_guard,
        }
    }
}

/// Abstraction over wrappers around [`BaseDocument`] to allow for them all to
/// be driven by [`blitz-shell`](https://docs.rs/blitz-shell)
pub trait Document: Any + 'static {
    fn inner(&self) -> DocGuard<'_>;
    fn inner_mut(&mut self) -> DocGuardMut<'_>;

    /// Update the [`Document`] in response to a [`UiEvent`] (click, keypress, etc)
    fn handle_ui_event(&mut self, event: UiEvent) {
        let mut doc = self.inner_mut();
        let mut driver = EventDriver::new(&mut *doc, NoopEventHandler);
        driver.handle_ui_event(event);
    }

    /// Poll any pending async operations, and flush changes to the underlying [`BaseDocument`]
    fn poll(&mut self, task_context: Option<TaskContext>) -> bool {
        // Default implementation does nothing
        let _ = task_context;
        false
    }

    /// Drain immediate work for a host's settle loop.
    ///
    /// Pass `run_timers = true` only on the first pass to allow one batch of
    /// due timer and animation callbacks. Subsequent passes must leave those
    /// callbacks scheduled while draining scripts and microtasks.
    ///
    /// Documents that execute timers must override this method. Wrappers that
    /// poll child documents must propagate the policy to their children.
    fn poll_for_settle(&mut self, task_context: Option<TaskContext>, run_timers: bool) -> bool {
        let _ = run_timers;
        self.poll(task_context)
    }

    /// Get the [`Document`]'s id
    fn id(&self) -> usize {
        self.inner().id
    }
}

/// What the pre-click activation steps changed, so a cancelled click can put
/// it back. Produced by [`BaseDocument::run_pre_click_activation`].
#[derive(Debug, Clone, PartialEq)]
pub struct PreClickActivation {
    /// Every node whose checkedness moved, paired with the value it held.
    previous: Vec<(NodeId, bool)>,
}

/// Escape text for inclusion in an HTML clipboard payload.
///
/// The five characters that would otherwise be read as markup. A selection is
/// document text, so a paragraph containing `a < b` must arrive as `a &lt; b`
/// rather than opening a tag in whatever receives the paste.
fn escape_html(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for ch in text.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            _ => out.push(ch),
        }
    }
    out
}

pub struct PlainDocument(pub BaseDocument);
impl Document for PlainDocument {
    fn inner(&self) -> DocGuard<'_> {
        DocGuard::Ref(&self.0)
    }
    fn inner_mut(&mut self) -> DocGuardMut<'_> {
        DocGuardMut::Ref(&mut self.0)
    }
}

impl Document for BaseDocument {
    fn inner(&self) -> DocGuard<'_> {
        DocGuard::Ref(self)
    }
    fn inner_mut(&mut self) -> DocGuardMut<'_> {
        DocGuardMut::Ref(self)
    }
}

impl Document for Rc<RefCell<BaseDocument>> {
    fn inner(&self) -> DocGuard<'_> {
        DocGuard::RefCell(self.borrow())
    }

    fn inner_mut(&mut self) -> DocGuardMut<'_> {
        DocGuardMut::RefCell(self.borrow_mut())
    }
}

pub enum DocumentEvent {
    ResourceLoad(ResourceLoadResponse),
    /// A navigation originating from within an iframe's sub-document
    /// (e.g. a link click), to be applied to the iframe identified by `node_id`.
    NavigateIframe {
        node_id: NodeId,
        url: Url,
    },
}

/// How urgently a document needs another animation frame.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum AnimationPacing {
    Idle,
    Caret,
    SlowCss,
    Interactive,
}

pub struct BaseDocument {
    /// ID of the document
    id: usize,

    // Config
    /// Base url for resolving linked resources (stylesheets, images, fonts, etc)
    pub(crate) url: DocumentUrl,
    // Devtool settings. Currently used to render debug overlays
    pub(crate) devtool_settings: DevtoolSettings,
    // Viewport details such as the dimensions, HiDPI scale, and zoom factor,
    pub(crate) viewport: Viewport,
    // Scroll within our viewport
    pub(crate) viewport_scroll: crate::Point<f64>,
    /// Changes recorded for a script's `MutationObserver`, or `None` while no
    /// observer is registered. See [`crate::DomMutation`].
    pub(crate) mutation_log: Option<Vec<crate::DomMutation>>,
    /// Content handler changes, independent of MutationObserver recording.
    inline_handler_changes: Vec<(NodeId, crate::QualName, Option<crate::node::AttrAtom>)>,
    /// Weak registrations make pages without live ranges pay only a branch.
    pub(crate) live_ranges: Vec<crate::range::WeakRange>,
    /// Script Selection shares the same live range object as getRangeAt().
    pub dom_selection: Option<crate::LiveRange>,
    /// CSS media type used to evaluate `@media` rules.
    pub(crate) media_type: MediaType,
    /// Strategy for Stylo's style traversal during `resolve`.
    pub(crate) style_threading: StyleThreading,
    /// Whether incremental layout is enabled for this document.
    pub(crate) incremental_layout: bool,
    /// How deeply this document is nested within other documents
    /// (0 for a root document). Used to limit `<iframe>` nesting depth.
    pub(crate) subdocument_depth: usize,

    // Events
    pub(crate) tx: Sender<DocumentEvent>,
    // rx will always be Some, except temporarily while processing events
    pub(crate) rx: Option<Receiver<DocumentEvent>>,

    /// A slotmap-backed tree of nodes
    ///
    /// We pin the tree to a guarantee to the nodes it creates that the tree is stable in memory.
    /// There is no way to create the tree - publicly or privately - that would invalidate that invariant.
    pub(crate) nodes: Box<NodeTree>,

    /// Batch cache invalidation across recursive subtree teardown.
    node_drop_depth: usize,
    /// `<details>` elements whose `open` attribute appeared or disappeared since the script
    /// runtime last took them, each with whether it was open before its first change. The
    /// HTML toggle task coalesces per element, so an element is listed once.
    details_toggles: Vec<(NodeId, bool)>,
    /// Bumped whenever the stylist device changes (viewport size, scale or colour scheme),
    /// so script can skip re-evaluating media queries while it stays the same.
    viewport_generation: u64,
    /// The inert document that owns every `<template>`'s contents, made on first use. It
    /// has no browsing context, so nothing in it is upgraded as a custom element.
    template_contents_owner: Option<NodeId>,
    dropped_node_ids: FxHashSet<NodeId>,
    dropped_node_parents: FxHashSet<NodeId>,
    /// Survivors that can still point at an id freed by this batch.
    ///
    /// Recorded while the node is still in the slab. The purge runs after a
    /// subtree drop has already removed those nodes, so the links have to be
    /// captured first.
    dropped_reference_owners: FxHashSet<NodeId>,

    /// The id of the root node (a Document node)
    pub(crate) root_node_id: NodeId,

    /// For each `position: fixed` node reparented onto the root element, the
    /// layout parent it was taken from.
    ///
    /// Hoisting gives a fixed node the viewport as its containing block, which
    /// is what CSS asks for. It must not also decide which stacking context the
    /// node paints in: that follows the box tree, and the two are independent.
    /// Without this record the node joins the root's stacking context, so a
    /// negative z-index fixed layer inside an `isolation: isolate` ancestor
    /// paints beneath every background between them and disappears.
    pub(crate) hoisted_fixed_parents: HashMap<NodeId, NodeId>,

    /// Authored child slots restored temporarily for static-position layout.
    pub(crate) hoisted_fixed_indices: HashMap<NodeId, usize>,

    /// Escaped absolute boxes whose explicit axes follow a containing block.
    pub(crate) abspos_placements: Vec<crate::layout::abspos::AbsposPlacement>,

    /// Maintained during the existing fixed/sticky walk on style or tree changes.
    pub(crate) abspos_candidates: Vec<crate::layout::abspos::AbsposCandidate>,
    pub(crate) abspos_candidate_ids: HashSet<NodeId>,
    pub(crate) abspos_inputs: HashMap<NodeId, crate::layout::abspos::AbsposInputs>,
    /// Candidates whose hypothetical layouts or styles were written this pass.
    pub(crate) abspos_written: HashSet<NodeId>,
    pub(crate) abspos_candidates_dirty: bool,
    pub(crate) abspos_layout_dirty: bool,
    /// Whether the normal root layout missed its PerformLayout cache.
    pub(crate) abspos_normal_layout: bool,

    /// Every `position: fixed` node whose containing block is the viewport,
    /// which is every one of them except those under a transformed ancestor.
    ///
    /// Collected by the walk that hoists them, and used by
    /// `resolve_fixed_positions` to hold them still while the page scrolls.
    pub(crate) fixed_nodes: Vec<NodeId>,

    /// The viewport scroll currently baked into those nodes' locations.
    ///
    /// One value for the whole document rather than one per node: the pin is
    /// the same displacement for every fixed box, because they all share the
    /// viewport as their containing block. Reset by `resolve_layout`, which
    /// rewrites the locations it was added to.
    pub(crate) fixed_scroll_offset: crate::Point<f64>,

    /// Every `position: sticky` node in the document, in tree order.
    ///
    /// Collected by the same walk that hoists fixed nodes, because both need
    /// one pre-order pass over the box tree and a second one would cost the
    /// same on every frame of every document, sticky or not. Tree order matters:
    /// a sticky box inside another sticky box is adjusted on top of its
    /// ancestor's adjustment, so the ancestor has to be settled first.
    pub(crate) sticky_nodes: Vec<NodeId>,

    /// For each sticky node, the offset currently baked into its
    /// `final_layout().location`.
    ///
    /// The adjustment is written into the box itself so that paint, hit testing
    /// and `absolute_position` cannot disagree about where the box is. That
    /// makes the pass non-idempotent unless it can recover the flow position it
    /// started from, which is what this records. Cleared by `resolve_layout`,
    /// which rewrites every location from taffy and so discards the offsets
    /// along with them.
    pub(crate) sticky_offsets: HashMap<NodeId, taffy::Point<f32>>,

    /// Stacking contexts holding a hoisted child that an ancestor clips.
    ///
    /// Collected while flushing styles so that `resolve_hoisted_clips` visits
    /// those contexts alone, rather than scanning every node in the document
    /// after every layout to find the handful that hoist anything at all.
    pub(crate) hoisted_clip_hosts: HashSet<NodeId>,

    /// Contexts with hoisted paint children, maintained by the style flush.
    pub(crate) hoisted_position_hosts: HashSet<NodeId>,

    // Stylo
    /// The Stylo engine
    pub(crate) stylist: Stylist,
    pub(crate) animations: DocumentAnimationSet,
    /// Monotonic animation clock used by the most recent resolve.
    ///
    /// Embedders may inspect or capture between window frames. A diagnostic
    /// caller historically passed `0.0` and rewound every CSS transition in
    /// the document; retaining the high-water mark makes that impossible at
    /// the document boundary.
    pub(crate) last_resolve_animation_time: f64,
    /// Stylo shared lock
    pub(crate) guard: SharedRwLock,
    /// Stylo invalidation map. We insert into this map prior to mutating nodes.
    pub(crate) snapshots: SnapshotMap,

    // Parley contexts
    /// A Parley font context
    pub(crate) font_ctx: Arc<Mutex<parley::FontContext>>,
    #[cfg(feature = "parallel-construct")]
    /// Thread-and-document-local copies to the font context
    pub(crate) thread_font_contexts: ThreadLocal<RefCell<Box<FontContext>>>,
    /// A Parley layout context
    pub(crate) layout_ctx: parley::LayoutContext<TextBrush>,

    /// The real (non-anonymous) node which is currently hovered (if any).
    /// This is never a layout-generated (anonymous) node, so it remains valid
    /// across box-tree reconstruction.
    pub(crate) hover_node_id: Option<NodeId>,
    /// The precise (may be anonymous) layout node under the pointer (if any).
    /// This can be invalidated by box-tree reconstruction, and is re-resolved against
    /// fresh layout at the end of every `resolve` pass.
    pub(crate) hover_hit_node_id: Option<NodeId>,
    /// Whether the node which is currently hovered is a text node/span
    pub(crate) hover_node_is_text: bool,
    /// The last known pointer position in client coordinates (viewport-relative, unscrolled).
    pub(crate) last_client_pointer_position: Option<taffy::Point<f32>>,
    /// Exact DOM target selected by semantic automation.
    ///
    /// Window pointers leave this empty and are re-hit-tested after layout.
    /// An inspector already resolved identity, so re-hit-testing its synthetic
    /// centre coordinate would silently replace that target with an overlap.
    pub(crate) semantic_hover_node_id: Option<NodeId>,
    /// The node which is currently focussed (if any)
    pub(crate) focus_node_id: Option<NodeId>,
    /// The node which is currently active (if any)
    pub(crate) active_node_id: Option<NodeId>,
    /// The node which recieved a mousedown event (if any)
    pub(crate) mousedown_node_id: Option<NodeId>,
    /// The last time a mousedown was made (for double-click detection)
    pub(crate) last_mousedown_time: Option<Instant>,
    /// The position where mousedown occurred (for selection drags and double-click detection)
    pub(crate) mousedown_position: taffy::Point<f32>,
    /// How many clicks have been made in quick succession
    pub(crate) click_count: u16,
    /// Whether we're currently in a text selection drag (moved 2px+ from mousedown)
    pub(crate) drag_mode: DragMode,
    /// The scrollbar thumb currently under the pointer, if any
    pub(crate) hovered_scrollbar: Option<crate::node::ScrollbarRef>,
    /// When each scroll container's overlay scrollbars were last shown
    /// (scrolled, or the pointer left the thumb); drives their fade-out
    pub(crate) scrollbar_activity: HashMap<NodeId, Instant>,
    /// Whether and what kind of scroll animation is currently in progress
    pub(crate) scroll_animation: ScrollAnimationState,

    /// Text selection state (for non-input text)
    pub(crate) text_selection: TextSelection,

    // TODO: collapse animating state into a bitflags
    /// Whether there are active CSS animations/transitions (so we should re-render every frame)
    pub(crate) has_active_animations: bool,
    /// Whether there is a `<canvas>` element in the DOM (so we should re-render every frame)
    pub(crate) has_canvas: bool,
    /// The most urgent animation cadence required by any subdocument.
    pub(crate) subdoc_animation_pacing: AnimationPacing,

    /// Map of id attribute values to node IDs for fast lookups.
    /// May contain multiple nodes for the same id: `get_element_by_id`
    /// returns the first in tree order.
    pub(crate) nodes_to_id: HashMap<String, SmallVec<[NodeId; 1]>>,
    /// Map of `<style>` and `<link>` node IDs to their associated stylesheet
    pub(crate) nodes_to_stylesheet: BTreeMap<NodeId, DocumentStyleSheet>,
    /// `<style>`/`<link>` nodes whose sheet is in the document Stylist. Shadow
    /// tree sheets live elsewhere, and Stylo panics on removing a sheet it
    /// does not hold.
    pub(crate) document_sheet_nodes: HashSet<NodeId>,
    /// The shadow root each shadow-tree `<style>`/`<link>` sheet was installed
    /// into. Unloading happens after the node is detached, when its root can
    /// no longer be found by walking up, so the owner is remembered here.
    #[cfg(feature = "shadow-dom")]
    pub(crate) shadow_sheet_roots: HashMap<NodeId, NodeId>,
    /// Stylesheets added by the useragent
    /// where the key is the hashed CSS
    pub(crate) ua_stylesheets: HashMap<String, DocumentStyleSheet>,
    /// Map from form control node ID's to their associated forms node ID's
    pub(crate) controls_to_form: HashMap<NodeId, NodeId>,
    /// Nodes that contain sub documents
    pub(crate) sub_document_nodes: HashSet<NodeId>,
    /// Load state (abort controller and in-flight request id) for each
    /// `<iframe>` element whose sub-document is loaded automatically
    pub(crate) iframe_loads: HashMap<NodeId, crate::iframe::IframeLoad>,
    /// Nodes whose layout construction is waiting for a later pass.
    pub(crate) deferred_construction_nodes: Vec<ConstructionTask>,
    /// Which parts of the document differ from the previously painted frame.
    ///
    /// Off unless a consumer asks for it, so a document that never questions
    /// its own frames does not pay to answer. See
    /// [`set_paint_damage_tracking`](Self::set_paint_damage_tracking).
    pub(crate) paint_damage: crate::paint_damage::PaintDamageTracker,

    /// Nodes that contain custom widgets
    #[cfg(feature = "custom-widget")]
    pub(crate) custom_widget_nodes: HashSet<NodeId>,
    /// Rendering resources allocated by custom widgets that should be deallocated during the next render
    #[cfg(feature = "custom-widget")]
    pub(crate) pending_resource_deallocations: Vec<anyrender::ResourceId>,

    /// Registry of custom element definitions keyed by tag name
    #[cfg(feature = "shadow-dom")]
    pub(crate) custom_element_registry: crate::node::CustomElementRegistry,
    /// Nodes that are shadow hosts (have an attached shadow root)
    #[cfg(feature = "shadow-dom")]
    pub(crate) shadow_host_nodes: HashSet<NodeId>,
    #[cfg(feature = "shadow-dom")]
    pub(crate) dirty_shadow_hosts: HashSet<NodeId>,
    #[cfg(feature = "shadow-dom")]
    pub(crate) pending_slot_changes: Vec<NodeId>,
    #[cfg(feature = "shadow-dom")]
    pub(crate) signaled_slots: HashSet<NodeId>,
    #[cfg(feature = "shadow-dom")]
    pub(crate) adopted_stylesheets: HashMap<NodeId, Vec<DocumentStyleSheet>>,
    /// Nodes that have an attached custom element controller
    #[cfg(feature = "shadow-dom")]
    pub(crate) custom_element_nodes: HashSet<NodeId>,
    /// Template element -> declarative shadow root, while that template is open
    /// on the parser stack. Stored here because each streaming sink call builds
    /// a new parser.
    #[cfg(feature = "shadow-dom")]
    pub(crate) declarative_template_shadows: HashMap<NodeId, NodeId>,

    /// Native candidate index and mutation reactions for JavaScript custom elements.
    pub(crate) script_custom_elements: crate::node::script_custom_element::Registry,

    /// Cache of loaded images, keyed by URL. Allows reusing images across multiple
    /// elements without re-fetching from the network.
    pub(crate) image_cache: HashMap<String, ImageData>,

    /// Tracks in-flight image requests. When an image is being fetched, additional
    /// requests for the same URL are queued here instead of starting new fetches.
    /// Value is a list of (node_id, image_type) pairs waiting for the image.
    pub(crate) pending_images: HashMap<String, Vec<(NodeId, ImageType)>>,

    // Tracks in-flight "critical" resources (e.g. stylesheets linked from the `<head>`),
    // keyed by request id
    pub(crate) pending_critical_resources: HashSet<usize>,

    pub(crate) web_fonts: Vec<Arc<crate::net::web_fonts::WebFont>>,
    pub(crate) font_epoch: usize,
    document_referrer: String,
    document_content_type: String,
    document_window_focused: bool,

    // Service providers
    /// Network provider. Can be used to fetch assets.
    pub net_provider: Arc<dyn NetProvider>,
    /// Navigation provider. Can be used to navigate to a new page (bubbles up the event
    /// on e.g. clicking a Link)
    pub navigation_provider: Arc<dyn NavigationProvider>,
    /// Shell provider. Can be used to request a redraw or set the cursor icon
    pub shell_provider: Arc<dyn ShellProvider>,
    /// HTML parser provider. Used to parse HTML for setInnerHTML
    pub html_parser_provider: Arc<dyn HtmlParserProvider>,
    /// Carried on every sub-resource `Request` this document issues; aborting
    /// it cancels all in-flight fetches tied to this document. Set via
    /// [`DocumentConfig::abort_signal`].
    pub(crate) abort_signal: Option<AbortSignal>,
}

pub(crate) fn make_device(
    viewport: &Viewport,
    media_type: MediaType,
    font_ctx: Arc<Mutex<FontContext>>,
) -> Device {
    let width = viewport.window_size.0 as f32 / viewport.scale();
    let height = viewport.window_size.1 as f32 / viewport.scale();
    let viewport_size = euclid::Size2D::new(width, height);
    let device_size = euclid::Size2D::new(width, height) * viewport.scale();
    let device_pixel_ratio = euclid::Scale::new(viewport.scale());

    Device::new(
        media_type,
        selectors::matching::QuirksMode::NoQuirks,
        viewport_size,
        device_size,
        device_pixel_ratio,
        Box::new(BlitzFontMetricsProvider { font_ctx }),
        ComputedValues::initial_values_with_font_override(Font::initial_values()),
        match viewport.color_scheme {
            ColorScheme::Light => PrefersColorScheme::Light,
            ColorScheme::Dark => PrefersColorScheme::Dark,
        },
        PointerCapabilities::default(),
        PointerCapabilities::default(),
    )
}

/// Whether layout reuses its caches, and how that can be overridden at runtime.
///
/// Incremental layout is on unless a caller or the environment turns it off.
///
/// The environment override exists so a single build can be measured both ways:
/// with it off every `resolve` clears the Taffy cache and re-shapes every inline
/// root from scratch, so comparing the two in separate binaries would also
/// compare two different compilations. `BLITZ_INCREMENTAL=0` forces the old
/// behaviour, `=1` forces the new one.
///
/// This used to fall back to `cfg!(feature = "incremental")`. That feature is
/// gone, replaced by `DocumentConfig::incremental`, and for a while afterwards
/// this function was never called at all: the config read
/// `unwrap_or(true)` directly, so `BLITZ_INCREMENTAL` was accepted and ignored.
fn incremental_layout_default() -> bool {
    !matches!(
        std::env::var("BLITZ_INCREMENTAL").ok().as_deref(),
        Some("0" | "false" | "off")
    )
}

impl BaseDocument {
    /// Create a new (empty) [`BaseDocument`] with the specified configuration
    pub fn new(config: DocumentConfig) -> Self {
        static ID_GENERATOR: AtomicUsize = AtomicUsize::new(1);

        let id = ID_GENERATOR.fetch_add(1, Ordering::SeqCst);

        let font_ctx = config
            .font_ctx
            .map(|mut font_ctx| {
                font_ctx.source_cache.make_shared();
                // font_ctx.collection.make_shared();
                font_ctx
            })
            .unwrap_or_else(|| {
                use parley::fontique::{Collection, CollectionOptions, SourceCache};
                let mut font_ctx = FontContext {
                    source_cache: SourceCache::new_shared(),
                    collection: Collection::new(CollectionOptions {
                        shared: false,
                        system_fonts: cfg!(all(
                            feature = "system-fonts",
                            not(target_arch = "wasm32")
                        )),
                    }),
                };
                font_ctx
                    .collection
                    .register_fonts(Blob::new(Arc::new(crate::BULLET_FONT) as _), None);
                font_ctx
            });
        let font_ctx = Arc::new(Mutex::new(font_ctx));
        if let Some(fallback) = config.family_fallback {
            crate::font_fallback::set(fallback);
        }

        // Make sure we turn on stylo features *before* creating the Stylist
        style_config::set_pref!("layout.grid.enabled", true);
        style_config::set_pref!("layout.unimplemented", true);
        style_config::set_pref!("layout.columns.enabled", true);
        style_config::set_pref!("layout.css.basic-shape-shape.enabled", true);
        style_config::set_pref!("layout.threads", -1);

        let viewport = config.viewport.unwrap_or_default();
        let media_type = config.media_type.unwrap_or_else(MediaType::screen);
        let device = make_device(&viewport, media_type.clone(), font_ctx.clone());
        let stylist = Stylist::new(device, QuirksMode::NoQuirks);
        let snapshots = SnapshotMap::new();
        let nodes = Box::new(NodeTree::new());
        let guard = SharedRwLock::new();
        let nodes_to_id = HashMap::new();

        let base_url = config
            .base_url
            .and_then(|url| DocumentUrl::from_str(&url).ok())
            .unwrap_or_default();

        let net_provider = config
            .net_provider
            .unwrap_or_else(|| Arc::new(DummyNetProvider));
        let navigation_provider = config
            .navigation_provider
            .unwrap_or_else(|| Arc::new(DummyNavigationProvider));
        let shell_provider = config
            .shell_provider
            .unwrap_or_else(|| Arc::new(DummyShellProvider));
        let html_parser_provider = config
            .html_parser_provider
            .unwrap_or_else(|| Arc::new(DummyHtmlParserProvider));

        let (tx, rx) = channel();

        let mut doc = Self {
            node_drop_depth: 0,
            details_toggles: Vec::new(),
            viewport_generation: 0,
            template_contents_owner: None,
            dropped_node_ids: FxHashSet::default(),
            dropped_node_parents: FxHashSet::default(),
            dropped_reference_owners: FxHashSet::default(),
            hoisted_fixed_parents: HashMap::new(),
            hoisted_fixed_indices: HashMap::new(),
            abspos_placements: Vec::new(),
            abspos_candidates: Vec::new(),
            abspos_candidate_ids: HashSet::new(),
            abspos_inputs: HashMap::new(),
            abspos_written: HashSet::new(),
            abspos_candidates_dirty: true,
            abspos_layout_dirty: true,
            abspos_normal_layout: false,
            fixed_nodes: Vec::new(),
            fixed_scroll_offset: crate::Point::ZERO,
            sticky_nodes: Vec::new(),
            sticky_offsets: HashMap::new(),
            hoisted_clip_hosts: HashSet::new(),
            hoisted_position_hosts: HashSet::new(),
            id,
            tx,
            rx: Some(rx),

            guard,
            nodes,
            root_node_id: NodeId::default(),
            stylist,
            animations: DocumentAnimationSet::default(),
            last_resolve_animation_time: 0.0,
            snapshots,
            nodes_to_id,
            viewport,
            media_type,
            style_threading: config.style_threading,
            incremental_layout: config
                .incremental
                .unwrap_or_else(incremental_layout_default),
            subdocument_depth: config.subdocument_depth,
            devtool_settings: DevtoolSettings::default(),
            viewport_scroll: crate::Point::ZERO,
            mutation_log: None,
            inline_handler_changes: Vec::new(),
            live_ranges: Vec::new(),
            dom_selection: None,
            url: base_url,
            ua_stylesheets: HashMap::new(),
            nodes_to_stylesheet: BTreeMap::new(),
            document_sheet_nodes: HashSet::new(),
            #[cfg(feature = "shadow-dom")]
            shadow_sheet_roots: HashMap::new(),
            font_ctx,
            #[cfg(feature = "parallel-construct")]
            thread_font_contexts: ThreadLocal::new(),
            layout_ctx: parley::LayoutContext::new(),

            hover_node_id: None,
            hover_hit_node_id: None,
            hover_node_is_text: false,
            last_client_pointer_position: None,
            semantic_hover_node_id: None,
            focus_node_id: None,
            active_node_id: None,
            mousedown_node_id: None,
            has_active_animations: false,
            subdoc_animation_pacing: AnimationPacing::Idle,
            has_canvas: false,
            sub_document_nodes: HashSet::new(),
            iframe_loads: HashMap::new(),

            #[cfg(feature = "custom-widget")]
            custom_widget_nodes: HashSet::new(),
            #[cfg(feature = "custom-widget")]
            pending_resource_deallocations: Vec::new(),

            #[cfg(feature = "shadow-dom")]
            custom_element_registry: crate::node::CustomElementRegistry::new(),
            #[cfg(feature = "shadow-dom")]
            shadow_host_nodes: HashSet::new(),
            #[cfg(feature = "shadow-dom")]
            dirty_shadow_hosts: HashSet::new(),
            #[cfg(feature = "shadow-dom")]
            pending_slot_changes: Vec::new(),
            #[cfg(feature = "shadow-dom")]
            signaled_slots: HashSet::new(),
            #[cfg(feature = "shadow-dom")]
            adopted_stylesheets: HashMap::new(),
            #[cfg(feature = "shadow-dom")]
            custom_element_nodes: HashSet::new(),
            #[cfg(feature = "shadow-dom")]
            declarative_template_shadows: HashMap::new(),

            deferred_construction_nodes: Vec::new(),
            paint_damage: Default::default(),
            script_custom_elements: Default::default(),
            image_cache: HashMap::new(),
            pending_images: HashMap::new(),
            pending_critical_resources: HashSet::new(),
            web_fonts: Vec::new(),
            font_epoch: 0,
            document_referrer: String::new(),
            document_content_type: String::from("text/html"),
            document_window_focused: false,
            controls_to_form: HashMap::new(),
            net_provider,
            navigation_provider,
            shell_provider,
            html_parser_provider,
            abort_signal: config.abort_signal,
            last_mousedown_time: None,
            mousedown_position: taffy::Point::ZERO,
            click_count: 0,
            drag_mode: DragMode::None,
            hovered_scrollbar: None,
            scrollbar_activity: HashMap::new(),
            scroll_animation: ScrollAnimationState::None,
            text_selection: TextSelection::default(),
        };

        // Initialise document with root Document node
        doc.root_node_id = doc.create_node(NodeData::Document(Box::default()));
        doc.root_node_mut().flags.insert(NodeFlags::IS_IN_DOCUMENT);

        match config.ua_stylesheets {
            Some(stylesheets) => {
                for ss in &stylesheets {
                    doc.add_user_agent_stylesheet(ss);
                }
            }
            None => doc.add_user_agent_stylesheet(DEFAULT_CSS),
        }

        // Stylo data on the root node container is needed to render the node
        let stylo_element_data = StyloElementData {
            styles: ElementStyles {
                primary: Some(
                    ComputedValues::initial_values_with_font_override(Font::initial_values())
                        .to_arc(),
                ),
                ..Default::default()
            },
            ..Default::default()
        };
        let stylo_data = doc.root_node_mut().stylo_element_data_mut();
        *stylo_data.ensure_init_mut() = stylo_element_data;

        doc
    }

    /// Set the Document's networking provider
    pub fn set_net_provider(&mut self, net_provider: Arc<dyn NetProvider>) {
        self.net_provider = net_provider;
    }

    /// Set the Document's navigation provider
    pub fn set_navigation_provider(&mut self, navigation_provider: Arc<dyn NavigationProvider>) {
        self.navigation_provider = navigation_provider;
    }

    /// Set the Document's shell provider
    pub fn set_shell_provider(&mut self, shell_provider: Arc<dyn ShellProvider>) {
        self.shell_provider = shell_provider;
    }

    /// Set the Document's html parser provider
    pub fn set_html_parser_provider(&mut self, html_parser_provider: Arc<dyn HtmlParserProvider>) {
        self.html_parser_provider = html_parser_provider;
    }

    /// Set base url for resolving linked resources (stylesheets, images, fonts, etc)
    pub fn set_base_url(&mut self, url: &str) {
        self.url = DocumentUrl::from(Url::parse(url).unwrap());
    }

    pub fn guard(&self) -> &SharedRwLock {
        &self.guard
    }

    pub fn tree(&self) -> &NodeTree {
        &self.nodes
    }

    pub fn id(&self) -> usize {
        self.id
    }

    /// Wrapper around [`crate::net::stamped_request`]. Use the free function
    /// when `&self` would conflict with a held `&mut` borrow on a field.
    pub(crate) fn build_request(&self, url: url::Url) -> Request {
        crate::net::with_referrer(
            crate::net::stamped_request(url, self.abort_signal.as_ref()),
            self.url(),
        )
    }

    pub fn favicon_url(&self) -> Option<String> {
        self.tree().iter().find_map(|(_, node)| {
            let data = &node.data;
            if !data.is_element_with_tag_name(&local_name!("link")) {
                return None;
            }
            let rel = data.attr(local_name!("rel"))?;
            if !rel
                .split_ascii_whitespace()
                .any(|v| v.eq_ignore_ascii_case("icon"))
            {
                return None;
            }
            data.attr(local_name!("href")).map(|s| s.to_string())
        })
    }

    pub fn get_node(&self, node_id: NodeId) -> Option<&Node> {
        self.nodes.get(node_id)
    }

    pub fn get_node_mut(&mut self, node_id: NodeId) -> Option<&mut Node> {
        self.nodes.get_mut(node_id)
    }

    pub fn get_focussed_node_id(&self) -> Option<NodeId> {
        self.focus_node_id
            .or(self.try_root_element().map(|el| el.id))
    }

    pub fn mutate<'doc>(&'doc mut self) -> DocumentMutator<'doc> {
        DocumentMutator::new(self)
    }

    pub fn handle_dom_event<F: FnMut(DomEvent)>(
        &mut self,
        event: &mut DomEvent,
        dispatch_event: F,
    ) {
        handle_dom_event(self, event, dispatch_event)
    }

    pub fn as_any_mut(&mut self) -> &mut dyn Any {
        self
    }

    /// Find the label's bound input elements:
    /// the element id referenced by the "for" attribute of a given label element
    /// or the first input element which is nested in the label
    /// Note that although there should only be one bound element,
    /// we return all possibilities instead of just the first
    /// in order to allow the caller to decide which one is correct
    pub fn label_bound_input_element(&self, label_node_id: NodeId) -> Option<&Node> {
        let label_element = self.nodes[label_node_id].element_data()?;
        if let Some(target_element_dom_id) = label_element.attr(local_name!("for")) {
            TreeTraverser::new(self)
                .filter_map(|id| {
                    let node = self.get_node(id)?;
                    let element_data = node.element_data()?;
                    if element_data.name.local != local_name!("input") {
                        return None;
                    }
                    let id = element_data.id.as_ref()?;
                    if *id == *target_element_dom_id {
                        Some(node)
                    } else {
                        None
                    }
                })
                .next()
        } else {
            TreeTraverser::new_with_root(self, label_node_id)
                .filter_map(|child_id| {
                    let node = self.get_node(child_id)?;
                    let element_data = node.element_data()?;
                    if element_data.name.local == local_name!("input") {
                        Some(node)
                    } else {
                        None
                    }
                })
                .next()
        }
    }

    /// The checkedness a click changed, kept so the click's *canceled
    /// activation steps* can put it back when a listener calls
    /// `preventDefault()`.
    ///
    /// A radio carries its whole set, because selecting one clears the others.
    pub fn run_pre_click_activation(&mut self, target: NodeId) -> Option<PreClickActivation> {
        let node_id = crate::events::pointer::checkable_activation_target(self, target)?;
        let el = self.get_node(node_id)?.data.downcast_element()?;
        let is_radio = el.attr(local_name!("type")) == Some("radio");

        if !is_radio {
            let previous = el.checkbox_input_checked()?;
            let el = self.get_node_mut(node_id)?.data.downcast_element_mut()?;
            Self::toggle_checkbox(el);
            return Some(PreClickActivation {
                previous: vec![(node_id, previous)],
            });
        }

        let radio_set = el.attr(local_name!("name")).map(str::to_string);
        let Some(radio_set) = radio_set else {
            let previous = el.checkbox_input_checked()?;
            let el = self.get_node_mut(node_id)?.data.downcast_element_mut()?;
            *el.checkbox_input_checked_mut()? = true;
            return Some(PreClickActivation {
                previous: vec![(node_id, previous)],
            });
        };

        // Recorded *while* selecting rather than before it. Selecting one radio
        // clears every other in the set, so cancelling has to restore all of
        // them, and reading them first meant walking the whole arena twice for
        // one press. The membership test is `toggle_radio`'s, deliberately: two
        // predicates that disagreed would restore a different set than the one
        // that changed.
        //
        // That predicate is name plus "has checkbox state", which is neither
        // scoped to `type=radio` nor to a form owner. Wrong per HTML, and
        // longstanding; matching it here keeps this change to the ordering it
        // is about.
        let mut previous: Vec<(NodeId, bool)> = Vec::new();
        for (id, node) in self.nodes.iter_mut() {
            let Some(el) = node.data.downcast_element_mut() else {
                continue;
            };
            if el.attr(local_name!("name")) != Some(&*radio_set) {
                continue;
            }
            let Some(is_checked) = el.checkbox_input_checked_mut() else {
                continue;
            };
            previous.push((id, *is_checked));
            *is_checked = id == node_id;
        }
        Some(PreClickActivation { previous })
    }

    /// Undo [`Self::run_pre_click_activation`]. The click's *canceled
    /// activation steps*.
    pub fn undo_pre_click_activation(&mut self, activation: PreClickActivation) {
        for (node_id, was_checked) in activation.previous {
            let Some(node) = self.get_node_mut(node_id) else {
                continue;
            };
            let Some(el) = node.data.downcast_element_mut() else {
                continue;
            };
            if let Some(is_checked) = el.checkbox_input_checked_mut() {
                *is_checked = was_checked;
            }
        }
    }

    pub fn toggle_checkbox(el: &mut ElementData) -> bool {
        let Some(is_checked) = el.checkbox_input_checked_mut() else {
            return false;
        };
        *is_checked = !*is_checked;

        *is_checked
    }

    pub fn toggle_radio(&mut self, radio_set_name: String, target_radio_id: NodeId) {
        for (i, node) in self.nodes.iter_mut() {
            if let Some(node_data) = node.data.downcast_element_mut() {
                if node_data.attr(local_name!("name")) == Some(&radio_set_name) {
                    let was_clicked = i == target_radio_id;
                    let Some(is_checked) = node_data.checkbox_input_checked_mut() else {
                        continue;
                    };
                    *is_checked = was_clicked;
                }
            }
        }
    }

    /// Toggle the `open` attribute of a `<details>` element, expanding or
    /// collapsing it. This is the default action triggered when the element's
    /// first `<summary>` child is activated.
    pub fn toggle_details_open(&mut self, details_id: NodeId) {
        use crate::qual_name;

        let node = &self.nodes[details_id];
        if !node.data.is_element_with_tag_name(&local_name!("details")) {
            return;
        }
        let is_open = node.data.has_attr(local_name!("open"));

        // Note: HTML attributes are in the empty (null) namespace, so the
        // QualName must not use the html namespace here, else it won't match
        // an `open` attribute created by the HTML parser.
        let mut mutator = self.mutate();
        if is_open {
            mutator.clear_attribute(details_id, qual_name!("open"));
        } else {
            mutator.set_attribute(details_id, qual_name!("open"), "");
        }
        drop(mutator);

        self.shell_provider.request_redraw();
    }

    pub fn set_style_property(&mut self, node_id: NodeId, name: &str, value: &str) {
        let node = &mut self.nodes[node_id];
        let did_change = node.element_data_mut().unwrap().set_style_property(
            name,
            value,
            &self.guard,
            self.url.url_extra_data(),
        );
        if did_change {
            node.mark_style_attr_updated();
        }
    }

    pub fn remove_style_property(&mut self, node_id: NodeId, name: &str) {
        let node = &mut self.nodes[node_id];
        let did_change = node.element_data_mut().unwrap().remove_style_property(
            name,
            &self.guard,
            self.url.url_extra_data(),
        );
        if did_change {
            node.mark_style_attr_updated();
        }
    }

    pub fn sub_document_node_ids(&self) -> Vec<NodeId> {
        self.sub_document_nodes.iter().copied().collect()
    }

    /// Install the effective navigation referrer and response MIME type.
    pub fn set_navigation_metadata(&mut self, request: &Request, content_type: Option<&str>) {
        self.document_referrer = request
            .headers
            .get(blitz_traits::net::http::header::REFERER)
            .and_then(|value| value.to_str().ok())
            .and_then(|value| Url::parse(value).ok())
            .map(|mut url| {
                let _ = url.set_username("");
                let _ = url.set_password(None);
                url.set_fragment(None);
                url.to_string()
            })
            .unwrap_or_default();
        self.document_content_type = content_type
            .and_then(|value| value.split(';').next())
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .unwrap_or("text/html")
            .to_ascii_lowercase();
    }

    pub fn referrer(&self) -> &str {
        &self.document_referrer
    }

    pub fn content_type(&self) -> &str {
        &self.document_content_type
    }

    pub fn window_focused(&self) -> bool {
        self.document_window_focused
    }

    /// Hosts must deliver focus changes on the document's owning thread.
    pub fn set_window_focused(&mut self, focused: bool) {
        self.document_window_focused = focused;
        for id in self.sub_document_node_ids() {
            if let Some(child) = self
                .get_node_mut(id)
                .and_then(|node| node.element_data_mut())
                .and_then(|element| element.sub_doc_data_mut())
            {
                child.inner_mut().set_window_focused(focused);
            }
        }
    }

    /// 0 is standards, 1 is limited quirks, and 2 is quirks.
    pub fn set_document_quirks_mode(&mut self, mode: u8) {
        if let NodeData::Document(data) = &mut self.root_node_mut().data {
            data.quirks_mode = mode;
        }
    }

    pub fn compat_mode(&self) -> &'static str {
        if matches!(&self.root_node().data, NodeData::Document(data) if data.quirks_mode == 2) {
            "BackCompat"
        } else {
            "CSS1Compat"
        }
    }

    pub fn begin_document_stream(&mut self) {
        self.reset_web_fonts();
        self.pending_critical_resources.clear();
        self.pending_images.clear();
        self.set_document_quirks_mode(0);
    }

    pub fn set_sub_document(&mut self, node_id: NodeId, mut sub_document: Box<dyn Document>) {
        sub_document
            .inner_mut()
            .set_window_focused(self.document_window_focused);
        self.nodes[node_id]
            .element_data_mut()
            .unwrap()
            .set_sub_document(sub_document);
        self.sub_document_nodes.insert(node_id);
    }

    pub fn remove_sub_document(&mut self, node_id: NodeId) {
        self.nodes[node_id]
            .element_data_mut()
            .unwrap()
            .remove_sub_document();
        self.sub_document_nodes.remove(&node_id);
        if let Some(load) = self.iframe_loads.remove(&node_id) {
            load.abort_controller.abort();
        }
    }

    /// Poll all sub-documents (see [`Document::poll`]), allowing them to make progress
    /// on any pending async operations (e.g. JavaScript timers). Hosts which poll a
    /// wrapper around a [`BaseDocument`] should call this from their `poll` implementation.
    ///
    /// Returns `true` if any sub-document reported changes.
    pub fn poll_subdocuments(&mut self, waker: Option<&Waker>) -> bool {
        self.poll_subdocuments_inner(waker, None)
    }

    /// Propagate a settle pass's timer policy to every child document.
    pub fn poll_subdocuments_for_settle(
        &mut self,
        waker: Option<&Waker>,
        run_timers: bool,
    ) -> bool {
        self.poll_subdocuments_inner(waker, Some(run_timers))
    }

    fn poll_subdocuments_inner(
        &mut self,
        waker: Option<&Waker>,
        settle_timers: Option<bool>,
    ) -> bool {
        let mut has_changes = false;
        let node_ids: Vec<NodeId> = self.sub_document_nodes.iter().copied().collect();
        for node_id in node_ids {
            let Some(sub_doc) = self
                .nodes
                .get_mut(node_id)
                .and_then(|node| node.subdoc_mut())
            else {
                continue;
            };
            let task_context = waker.map(TaskContext::from_waker);
            has_changes |= match settle_timers {
                Some(run_timers) => sub_doc.poll_for_settle(task_context, run_timers),
                None => sub_doc.poll(task_context),
            };
        }
        has_changes
    }

    #[cfg(feature = "custom-widget")]
    pub fn custom_widget_node_ids(&self) -> Vec<NodeId> {
        self.custom_widget_nodes.iter().copied().collect()
    }

    #[cfg(feature = "custom-widget")]
    pub fn take_pending_resource_deallocations(&mut self) -> Vec<anyrender::ResourceId> {
        std::mem::take(&mut self.pending_resource_deallocations)
    }

    #[cfg(feature = "custom-widget")]
    pub fn set_custom_widget(&mut self, node_id: NodeId, widget: Box<dyn crate::Widget>) {
        self.nodes[node_id]
            .element_data_mut()
            .unwrap()
            .set_custom_widget(widget);
        self.custom_widget_nodes.insert(node_id);
    }

    #[cfg(feature = "custom-widget")]
    pub fn remove_custom_widget(&mut self, node_id: NodeId) {
        let resources_to_deallocate = self.nodes[node_id]
            .element_data_mut()
            .unwrap()
            .remove_custom_widget();
        self.pending_resource_deallocations
            .extend_from_slice(&resources_to_deallocate);
        self.custom_widget_nodes.remove(&node_id);
    }

    /// Mutable access to the custom element registry. Use
    /// [`CustomElementRegistry::define`](crate::node::CustomElementRegistry::define)
    /// to register custom elements by tag name.
    #[cfg(feature = "shadow-dom")]
    pub fn custom_elements_mut(&mut self) -> &mut crate::node::CustomElementRegistry {
        &mut self.custom_element_registry
    }

    /// Register a custom element definition against a tag name (analogous to
    /// `customElements.define`).
    #[cfg(feature = "shadow-dom")]
    pub fn define_custom_element(
        &mut self,
        name: markup5ever::LocalName,
        definition: crate::node::CustomElementDefinition,
    ) {
        self.custom_element_registry.define(name, definition);
    }

    /// The node ids of all shadow hosts in the document.
    #[cfg(feature = "shadow-dom")]
    pub fn shadow_host_node_ids(&self) -> Vec<NodeId> {
        self.shadow_host_nodes.iter().copied().collect()
    }

    /// If `host_id` is a shadow host, returns the node id of its shadow root.
    #[cfg(feature = "shadow-dom")]
    pub fn shadow_root_id(&self, host_id: NodeId) -> Option<NodeId> {
        self.get_node(host_id)
            .and_then(|node| node.shadow_root_id())
    }

    /// Attach a shadow root to the given host element, returning the node id of
    /// the newly-created shadow root. If the host already has a shadow root, its
    /// existing shadow root id is returned unchanged.
    #[cfg(feature = "shadow-dom")]
    pub fn attach_shadow(&mut self, host_id: NodeId, mode: crate::node::ShadowRootMode) -> NodeId {
        if let Some(existing) = self.nodes[host_id].shadow_root_id() {
            return existing;
        }

        let shadow_root_id = self.create_node(NodeData::ShadowRoot(
            crate::node::ShadowRootData::new(host_id, mode),
        ));

        // The shadow root's parent is the host. It is *not* added to the host's
        // `children` list (which holds light-DOM children); it is referenced via
        // the host's `ElementData::shadow_root` field instead.
        self.nodes[shadow_root_id].parent = Some(host_id);
        self.nodes[shadow_root_id].owner_document = self.nodes[host_id].owner_document;
        if self.nodes[host_id].flags.is_in_document() {
            self.nodes[shadow_root_id]
                .flags
                .insert(NodeFlags::IS_IN_DOCUMENT);
        }

        self.nodes[host_id]
            .element_data_mut()
            .expect("Shadow host must be an element")
            .shadow_root = Some(shadow_root_id);
        self.shadow_host_nodes.insert(host_id);
        self.dirty_shadow_hosts.insert(host_id);
        self.nodes[host_id].set_restyle_hint(
            style::invalidation::element::restyle_hints::RestyleHint::restyle_subtree(),
        );

        // Host needs its box tree rebuilt to account for the shadow tree.
        self.nodes[host_id].insert_damage(ALL_DAMAGE);
        self.nodes[host_id].mark_ancestors_dirty();

        shadow_root_id
    }

    /// HTML elements that `Element.attachShadow` accepts.
    ///
    /// Hyphenated names are included, matching the existing script binding.
    /// `template` is not a host.
    #[cfg(feature = "shadow-dom")]
    pub fn element_can_be_shadow_host(element: &ElementData) -> bool {
        let tag = element.name.local.as_ref();
        element.name.ns == ns!(html)
            && (tag.contains('-')
                || matches!(
                    tag,
                    "article"
                        | "aside"
                        | "blockquote"
                        | "body"
                        | "div"
                        | "footer"
                        | "h1"
                        | "h2"
                        | "h3"
                        | "h4"
                        | "h5"
                        | "h6"
                        | "header"
                        | "main"
                        | "nav"
                        | "p"
                        | "section"
                        | "span"
                ))
    }

    /// Attach a declarative shadow root, or return false and leave the template
    /// as a normal template.
    ///
    /// Failure is the host being missing, not a shadow host, or already having
    /// a root. Success records the template so parsed children land in the root.
    #[cfg(feature = "shadow-dom")]
    pub fn try_attach_declarative_shadow(
        &mut self,
        host_id: NodeId,
        template_id: NodeId,
        mode: crate::node::ShadowRootMode,
        clonable: bool,
        serializable: bool,
        delegates_focus: bool,
    ) -> bool {
        let can_attach = self.nodes.get(host_id).is_some_and(|node| {
            node.element_data().is_some_and(|element| {
                Self::element_can_be_shadow_host(element) && element.shadow_root.is_none()
            })
        });
        if !can_attach {
            return false;
        }
        let root_id = self.attach_shadow(host_id, mode);
        if let Some(root) = self.nodes[root_id].shadow_root_data_mut() {
            root.declarative = true;
            root.clonable = clonable;
            root.serializable = serializable;
            root.delegates_focus = delegates_focus;
        }
        self.declarative_template_shadows
            .insert(template_id, root_id);
        true
    }

    /// Detach (and drop) the shadow root of the given host element, if any.
    #[cfg(feature = "shadow-dom")]
    pub fn detach_shadow(&mut self, host_id: NodeId) {
        let shadow_root_id = self.nodes[host_id]
            .element_data_mut()
            .and_then(|el| el.shadow_root.take());
        if let Some(shadow_root_id) = shadow_root_id {
            self.drop_node_ignoring_parent(shadow_root_id);
            self.shadow_host_nodes.remove(&host_id);
            self.dirty_shadow_hosts.remove(&host_id);
            self.nodes[host_id].flattened_children = None;
            self.nodes[host_id].set_restyle_hint(
                style::invalidation::element::restyle_hints::RestyleHint::restyle_subtree(),
            );
            self.nodes[host_id].insert_damage(ALL_DAMAGE);
            self.nodes[host_id].mark_ancestors_dirty();
        }
    }

    /// Attach a custom element controller to the given node.
    #[cfg(feature = "shadow-dom")]
    pub fn set_custom_element(
        &mut self,
        node_id: NodeId,
        controller: Box<dyn crate::node::CustomElement>,
    ) {
        use crate::node::{CustomElementData, SpecialElementData};
        self.nodes[node_id]
            .element_data_mut()
            .expect("Custom element host must be an element")
            .special_data = SpecialElementData::CustomElement(CustomElementData::new(controller));
        self.custom_element_nodes.insert(node_id);
    }

    /// Detach the custom element controller from the given node (without running
    /// the `disconnected` callback). Returns the controller if present.
    #[cfg(feature = "shadow-dom")]
    pub fn take_custom_element(
        &mut self,
        node_id: NodeId,
    ) -> Option<Box<dyn crate::node::CustomElement>> {
        use crate::node::SpecialElementData;
        self.custom_element_nodes.remove(&node_id);
        let element = self.nodes[node_id].element_data_mut()?;
        if matches!(element.special_data, SpecialElementData::CustomElement(_)) {
            if let SpecialElementData::CustomElement(mut data) = element.special_data.take() {
                return data.controller.take();
            }
        }
        None
    }

    pub fn root_node(&self) -> &Node {
        &self.nodes[self.root_node_id]
    }

    pub fn root_node_mut(&mut self) -> &mut Node {
        &mut self.nodes[self.root_node_id]
    }

    /// Ask this document to work out which regions differ between frames.
    ///
    /// Off by default. A consumer that turns it on is charged one pass over the
    /// node list per [`resolve`](Self::resolve) - a pass `resolve` already makes
    /// to clear damage - plus a hash lookup and a rectangle comparison per node.
    /// Nothing else in the document reads the result, so leaving it off costs a
    /// single branch.
    ///
    /// The consumer this exists for is a `backdrop-filter` cache. Blurring what
    /// is behind an element costs a render pass and a filter every frame, and
    /// the only way that stops being permanent is to skip the elements whose
    /// input has not changed. Turning this on is what makes that question
    /// answerable.
    ///
    /// The first frame after enabling reports everything as changed, because
    /// there is no previous frame to compare against.
    pub fn set_paint_damage_tracking(&mut self, enabled: bool) {
        self.paint_damage.set_enabled(enabled);
    }

    /// Whether [`set_paint_damage_tracking`](Self::set_paint_damage_tracking) is on.
    pub fn paint_damage_tracking(&self) -> bool {
        self.paint_damage.is_enabled()
    }

    /// What changed since the previously resolved frame.
    ///
    /// Empty when tracking is off, which is indistinguishable from "nothing
    /// changed" and deliberately so: a consumer that has not asked for the
    /// question to be answered must not read the empty answer as a licence to
    /// reuse a cache. Check
    /// [`paint_damage_tracking`](Self::paint_damage_tracking) first.
    pub fn paint_damage(&self) -> &crate::paint_damage::PaintDamage {
        self.paint_damage.damage()
    }

    pub fn try_root_element(&self) -> Option<&Node> {
        TDocument::as_node(&self.root_node()).first_element_child()
    }

    pub fn root_element(&self) -> &Node {
        TDocument::as_node(&self.root_node())
            .first_element_child()
            .unwrap()
            .as_element()
            .unwrap()
    }

    pub fn create_node(&mut self, node_data: NodeData) -> NodeId {
        let tree_ptr = self.nodes.as_mut() as *mut NodeTree;
        let guard = self.guard.clone();
        let is_document = matches!(node_data, NodeData::Document(_));
        let id = self
            .nodes
            .insert_with_key(|id| Node::new(tree_ptr, id, guard, node_data));
        if !is_document {
            self.nodes[id].owner_document = Some(self.root_node_id);
        }
        self.register_script_custom_element(id);
        if let Some(attributes) = self.nodes[id]
            .element_data()
            .and_then(|element| element.inline_event_attributes.as_deref())
        {
            self.inline_handler_changes.extend(
                attributes
                    .iter()
                    .map(|attr| (id, attr.name.clone(), Some(attr.value.clone()))),
            );
        }
        id
    }

    pub fn add_to_document_id_map(&mut self, document_id: NodeId, id: &str, node_id: NodeId) {
        if document_id == self.root_node_id || id.is_empty() {
            return;
        }
        let Some(node) = self.get_node_mut(document_id) else {
            return;
        };
        let NodeData::Document(data) = &mut node.data else {
            return;
        };
        let candidates = data.ids.entry(id.to_owned()).or_default();
        if !candidates.contains(&node_id) {
            candidates.push(node_id);
        }
    }

    pub fn remove_from_document_id_map(&mut self, document_id: NodeId, id: &str, node_id: NodeId) {
        if document_id == self.root_node_id {
            return;
        }
        let Some(node) = self.get_node_mut(document_id) else {
            return;
        };
        let NodeData::Document(data) = &mut node.data else {
            return;
        };
        if let Some(candidates) = data.ids.get_mut(id) {
            candidates.retain(|candidate| *candidate != node_id);
            if candidates.is_empty() {
                data.ids.remove(id);
            }
        }
    }

    /// Indexed lookup scoped to one document. Parent child-list membership
    /// excludes removed nodes, template contents, and shadow trees.
    pub fn get_element_by_id_in(&self, document_id: NodeId, id: &str) -> Option<NodeId> {
        if document_id == self.root_node_id {
            return self.get_element_by_id(id);
        }
        if id.is_empty() {
            return None;
        }
        let NodeData::Document(data) = &self.get_node(document_id)?.data else {
            return None;
        };
        data.ids
            .get(id)?
            .iter()
            .filter_map(|candidate| {
                let mut current = *candidate;
                let mut path = Vec::new();
                while current != document_id {
                    let node = self.get_node(current)?;
                    let parent_id = node.parent?;
                    let parent = self.get_node(parent_id)?;
                    path.push(parent.index_of_child(current)?);
                    current = parent_id;
                }
                path.reverse();
                Some((path, *candidate))
            })
            .min_by(|left, right| left.0.cmp(&right.0))
            .map(|(_, node_id)| node_id)
    }

    /// Nodes that still hold a link to `node_id` after it leaves the document.
    ///
    /// Direct parents are recorded separately and force reconstruction. This
    /// collects everyone else the old document-wide pass would have mutated:
    /// surviving layout children (their `layout_parent` still points here),
    /// anonymous blocks that list the id without being its DOM parent, shadow
    /// slots and hosts, the authored parent of a hoisted fixed box, and
    /// ancestors whose inline layout, list marker, table grid, or stacking
    /// context stores a descendant id. Ancestors inside `removed` are not
    /// walked; detachment does not clean lists on nodes that are themselves
    /// going away.
    fn collect_live_reference_owners(
        nodes: &NodeTree,
        hoisted_fixed_parents: &HashMap<NodeId, NodeId>,
        removed: &FxHashSet<NodeId>,
        node_id: NodeId,
        candidates: &mut FxHashSet<NodeId>,
    ) {
        fn push_survivor(
            removed: &FxHashSet<NodeId>,
            candidates: &mut FxHashSet<NodeId>,
            id: NodeId,
        ) {
            if !removed.contains(&id) {
                candidates.insert(id);
            }
        }

        let (removed_is_text, dom_parent, layout_parent, seeds) = {
            let Some(node) = nodes.get(node_id) else {
                return;
            };
            let mut seeds: SmallVec<[NodeId; 8]> = SmallVec::new();
            {
                let borrowed = node.layout_children.borrow();
                if let Some(children) = borrowed.as_ref() {
                    seeds.extend(children.iter().copied());
                }
            }
            seeds.extend(node.children.iter().copied());
            seeds.extend(node.anonymous_blocks.iter().copied());
            seeds.extend(node.before());
            seeds.extend(node.after());
            #[cfg(feature = "shadow-dom")]
            {
                seeds.extend(node.assigned_slot);
                seeds.extend(
                    node.element_data()
                        .and_then(|element| element.assigned_slot),
                );
                if let Some(assigned) = node.assigned_nodes.as_ref() {
                    seeds.extend(assigned.iter().copied());
                }
                if let Some(root) = node.shadow_root_data() {
                    seeds.push(root.host);
                }
            }
            (
                node.is_text_node(),
                node.parent,
                node.layout_parent.get(),
                seeds,
            )
        };

        for parent_id in [dom_parent, layout_parent].into_iter().flatten() {
            let Some(parent) = nodes.get(parent_id) else {
                continue;
            };
            let anons: SmallVec<[NodeId; 4]> = parent.anonymous_blocks.iter().copied().collect();
            for anon in anons {
                let Some(anon_node) = nodes.get(anon) else {
                    continue;
                };
                let listed = anon_node
                    .children
                    .iter()
                    .any(|child| removed.contains(child))
                    || anon_node
                        .layout_children
                        .borrow()
                        .as_ref()
                        .is_some_and(|children| {
                            children.iter().any(|child| removed.contains(child))
                        });
                if listed {
                    push_survivor(removed, candidates, anon);
                }
            }
        }
        for id in seeds {
            push_survivor(removed, candidates, id);
        }

        let mut stack: SmallVec<[NodeId; 16]> = SmallVec::new();
        if let Some(id) = dom_parent {
            if !removed.contains(&id) {
                stack.push(id);
            }
        }
        if let Some(id) = layout_parent {
            if !removed.contains(&id) {
                stack.push(id);
            }
        }
        if let Some(origin) = hoisted_fixed_parents.get(&node_id).copied() {
            // Hoist drops the layout edge before paint children are rebuilt, so
            // the authored parent can still name the fixed box.
            push_survivor(removed, candidates, origin);
            if !removed.contains(&origin) {
                stack.push(origin);
            }
        }

        let mut seen: SmallVec<[NodeId; 16]> = SmallVec::new();
        seen.push(node_id);
        while let Some(id) = stack.pop() {
            if seen.contains(&id) {
                continue;
            }
            seen.push(id);
            let Some(ancestor) = nodes.get(id) else {
                continue;
            };
            let stacking = ancestor.stacking_context.as_ref().is_some_and(|context| {
                context.children.iter().any(|child| {
                    removed.contains(&child.node_id)
                        || child
                            .clip_ancestors
                            .iter()
                            .any(|clip| removed.contains(clip))
                })
            });
            let inline_or_list = ancestor.element_data().is_some_and(|element| {
                element.inline_layout_data.is_some() || element.list_item_data.is_some()
            });
            // Table grids store cells, rows, and row groups, never text nodes.
            let table_root = !removed_is_text && ancestor.flags.is_table_root();
            #[cfg(feature = "shadow-dom")]
            let shadow_hit = {
                let mut hit = ancestor
                    .flattened_children
                    .as_ref()
                    .is_some_and(|children| children.iter().any(|child| removed.contains(child)))
                    || ancestor.assigned_nodes.as_ref().is_some_and(|assigned| {
                        assigned.iter().any(|child| removed.contains(child))
                    });
                if let Some(root) = ancestor.shadow_root_data() {
                    let host = root.host;
                    hit = hit
                        || root.slots.iter().any(|slot| removed.contains(slot))
                        || root
                            .slottables
                            .iter()
                            .any(|slottable| removed.contains(slottable))
                        || root
                            .stylesheet_nodes
                            .iter()
                            .any(|sheet| removed.contains(sheet));
                    stack.push(host);
                }
                hit
            };
            #[cfg(not(feature = "shadow-dom"))]
            let shadow_hit = false;
            if stacking || inline_or_list || table_root || shadow_hit {
                push_survivor(removed, candidates, id);
            }
            if let Some(parent) = ancestor.parent {
                stack.push(parent);
            }
            if let Some(parent) = ancestor.layout_parent.get() {
                stack.push(parent);
            }
        }
    }

    /// Stacking-context hosts are few, and a fixed box can paint in one that
    /// is not a layout ancestor of its current parent. Visit a host only when
    /// its hoisted list actually names a removed id.
    fn collect_stacking_context_owners(
        nodes: &NodeTree,
        position_hosts: &HashSet<NodeId>,
        clip_hosts: &HashSet<NodeId>,
        removed: &FxHashSet<NodeId>,
        candidates: &mut FxHashSet<NodeId>,
    ) {
        for host in position_hosts.iter().chain(clip_hosts.iter()).copied() {
            if removed.contains(&host) {
                continue;
            }
            let Some(node) = nodes.get(host) else {
                continue;
            };
            let Some(context) = node.stacking_context.as_ref() else {
                continue;
            };
            let references = context.children.iter().any(|child| {
                removed.contains(&child.node_id)
                    || child
                        .clip_ancestors
                        .iter()
                        .any(|clip| removed.contains(clip))
            });
            if references {
                candidates.insert(host);
            }
        }
    }

    /// Remove detached or freed ids from every persistent rendering cache.
    ///
    /// DOM ancestry alone cannot find the owners: fixed boxes can belong to
    /// the root's layout list and another ancestor's stacking context, while
    /// inline boxes and table cells have additional flattened representations.
    /// Invalidate those owners before this mutation returns. Hidden subtrees
    /// retain caches, so leaving cleanup until resolve is insufficient.
    ///
    /// Only those owners are visited. A pass over every node made each
    /// `textContent` write rescan the whole document.
    pub(crate) fn invalidate_node_references(
        &mut self,
        removed: &FxHashSet<NodeId>,
        mut parents: FxHashSet<NodeId>,
        extra_owners: FxHashSet<NodeId>,
    ) {
        if removed.is_empty() {
            return;
        }

        fn layout_references_removed(
            layout: &parley::Layout<TextBrush>,
            removed: &FxHashSet<NodeId>,
        ) -> bool {
            layout
                .inline_boxes()
                .iter()
                .any(|ibox| removed.contains(&NodeId::from_u64(ibox.id)))
                || layout.styles().iter().any(|style| {
                    removed.contains(&style.brush.id)
                        || style
                            .brush
                            .text_node
                            .is_some_and(|id| removed.contains(&id))
                })
        }

        // An anonymous origin can disappear while its hoisted fixed box
        // survives. Reconstruct the root edge too, so construction can give
        // that box a current authored origin.
        for (&id, &origin) in &self.hoisted_fixed_parents {
            if removed.contains(&id) || removed.contains(&origin) {
                if let Some(node) = self.nodes.get(id) {
                    parents.extend(node.layout_parent.get());
                }
            }
        }

        let mut candidates: FxHashSet<NodeId> = FxHashSet::with_capacity_and_hasher(
            parents.len() + extra_owners.len() + removed.len(),
            Default::default(),
        );
        for &id in &parents {
            if !removed.contains(&id) {
                candidates.insert(id);
            }
        }
        for id in extra_owners {
            if !removed.contains(&id) {
                candidates.insert(id);
            }
        }
        for &id in removed {
            let detach = self
                .nodes
                .get(id)
                .and_then(|node| node.layout_parent.get())
                .is_some_and(|parent| !removed.contains(&parent));
            if detach {
                candidates.insert(id);
            }
            if self.nodes.contains_key(id) {
                Self::collect_live_reference_owners(
                    &self.nodes,
                    &self.hoisted_fixed_parents,
                    removed,
                    id,
                    &mut candidates,
                );
            }
        }
        Self::collect_stacking_context_owners(
            &self.nodes,
            &self.hoisted_position_hosts,
            &self.hoisted_clip_hosts,
            removed,
            &mut candidates,
        );

        self.fixed_nodes.retain(|id| !removed.contains(id));
        self.sticky_nodes.retain(|id| !removed.contains(id));
        self.sticky_offsets.retain(|id, _| !removed.contains(id));
        self.hoisted_fixed_parents
            .retain(|id, origin| !removed.contains(id) && !removed.contains(origin));
        let fixed_parents = &self.hoisted_fixed_parents;
        self.hoisted_fixed_indices
            .retain(|id, _| fixed_parents.contains_key(id));
        self.hoisted_clip_hosts.retain(|id| !removed.contains(id));
        self.hoisted_position_hosts
            .retain(|id| !removed.contains(id));

        // These snapshots contain both box ids and containing-block/parent
        // ids. Discard the complete snapshots rather than retaining inputs
        // computed against a box tree that has just changed.
        self.abspos_placements.clear();
        self.abspos_candidates.clear();
        self.abspos_candidate_ids.clear();
        self.abspos_inputs.clear();
        self.abspos_written.clear();
        self.abspos_candidates_dirty = true;
        self.abspos_layout_dirty = true;

        let mut dirty = FxHashSet::default();
        for id in candidates {
            let Some(node) = self.nodes.get_mut(id) else {
                continue;
            };
            // Detached nodes still owned by script keep their internal box
            // tree, but must lose any edge back into the live layout tree.
            if removed.contains(&id) {
                if node
                    .layout_parent
                    .get()
                    .is_some_and(|parent| !removed.contains(&parent))
                {
                    node.layout_parent.set(None);
                }
                continue;
            }

            let mut reconstruct = parents.contains(&id);
            reconstruct |= node
                .layout_children
                .get_mut()
                .as_ref()
                .is_some_and(|children| children.iter().any(|id| removed.contains(id)));
            let mut repaint = node
                .paint_children
                .get_mut()
                .as_ref()
                .is_some_and(|children| children.iter().any(|id| removed.contains(id)));

            let old_anonymous_count = node.anonymous_blocks.len();
            node.anonymous_blocks.retain(|id| !removed.contains(id));
            reconstruct |= old_anonymous_count != node.anonymous_blocks.len();
            if node.is_anonymous() {
                let old_child_count = node.children.len();
                node.children.retain(|id| !removed.contains(id));
                reconstruct |= old_child_count != node.children.len();
            }
            if node
                .layout_parent
                .get()
                .is_some_and(|parent| removed.contains(&parent))
            {
                node.layout_parent.set(None);
                reconstruct = true;
            }

            if let Some(context) = node.stacking_context.as_mut() {
                let old_count = context.children.len();
                context.children.retain(|child| {
                    !removed.contains(&child.node_id)
                        && !child.clip_ancestors.iter().any(|id| removed.contains(id))
                });
                if old_count != context.children.len() {
                    // Filtering changes the split between negative and
                    // non-negative children as well as the content bounds.
                    context.sort();
                    context.content_area = taffy::Rect::ZERO;
                    repaint = true;
                }
            }

            #[cfg(feature = "shadow-dom")]
            {
                for children in [
                    node.flattened_children.as_mut(),
                    node.assigned_nodes.as_mut(),
                ]
                .into_iter()
                .flatten()
                {
                    let old_count = children.len();
                    children.retain(|id| !removed.contains(id));
                    reconstruct |= old_count != children.len();
                }
                if node.assigned_slot.is_some_and(|id| removed.contains(&id)) {
                    node.assigned_slot = None;
                    reconstruct = true;
                }
                if let Some(root) = node.shadow_root_data_mut() {
                    let old_count = root.slots.len() + root.slottables.len();
                    root.slots.retain(|id| !removed.contains(id));
                    root.slottables.retain(|id| !removed.contains(id));
                    root.stylesheet_nodes.retain(|id| !removed.contains(id));
                    reconstruct |= old_count != root.slots.len() + root.slottables.len();
                }
            }

            let mut table_removed = false;
            if let Some(element) = node.data.downcast_element_mut() {
                for pseudo in [&mut element.before, &mut element.after] {
                    if pseudo.is_some_and(|id| removed.contains(&id)) {
                        *pseudo = None;
                        reconstruct = true;
                    }
                }
                if element
                    .inline_layout_data
                    .as_ref()
                    .is_some_and(|inline| layout_references_removed(&inline.layout, removed))
                {
                    element.inline_layout_data = None;
                    reconstruct = true;
                }
                if element
                    .list_item_data
                    .as_ref()
                    .is_some_and(|item| match &item.position {
                        crate::node::ListItemLayoutPosition::Outside(layout) => {
                            layout_references_removed(layout, removed)
                        }
                        crate::node::ListItemLayoutPosition::Inside => false,
                    })
                {
                    element.list_item_data = None;
                    reconstruct = true;
                }
                if let SpecialElementData::TableRoot(context) = &element.special_data {
                    table_removed = context.references_removed_nodes(removed);
                }
                if table_removed {
                    element.special_data = SpecialElementData::None;
                    reconstruct = true;
                }
                #[cfg(feature = "shadow-dom")]
                if element
                    .assigned_slot
                    .is_some_and(|id| removed.contains(&id))
                {
                    element.assigned_slot = None;
                    reconstruct = true;
                }
            }
            if table_removed {
                node.flags.remove(NodeFlags::IS_TABLE_ROOT);
            }

            if reconstruct || repaint {
                node.layout_children.get_mut().take();
                node.paint_children.get_mut().take();
                if let Some(element) = node.data.downcast_element_mut() {
                    element.inline_layout_data = None;
                }
                dirty.insert(id);
            }
        }

        // Clear ancestor layout caches immediately, including ancestors that
        // the next incremental traversal would otherwise skip. Follow both
        // trees and tolerate parents already freed by a root-first drop.
        let mut stack: Vec<NodeId> = dirty.iter().copied().collect();
        let mut visited = FxHashSet::default();
        while let Some(id) = stack.pop() {
            if !visited.insert(id) || removed.contains(&id) {
                continue;
            }
            let Some(node) = self.nodes.get_mut(id) else {
                continue;
            };
            stack.extend(node.parent);
            stack.extend(node.layout_parent.get());
            #[cfg(feature = "shadow-dom")]
            {
                stack.extend(node.assigned_slot);
                if let Some(root) = node.shadow_root_data() {
                    stack.push(root.host);
                }
            }
            node.set_dirty_descendants();
            if node.stylo_element_data_opt().is_some() {
                node.insert_damage(if dirty.contains(&id) {
                    ALL_DAMAGE
                } else {
                    crate::layout::damage::ONLY_RELAYOUT
                        | style::selector_parser::RestyleDamage::REPAINT
                });
                node.cache_mut().clear();
            }
            if let Some(inline) = node
                .data
                .downcast_element_mut()
                .and_then(|element| element.inline_layout_data.as_mut())
            {
                inline.content_widths = None;
            }
        }

        #[cfg(feature = "shadow-dom")]
        {
            let nodes = &self.nodes;
            self.shadow_host_nodes.retain(|id| nodes.contains_key(*id));
            self.dirty_shadow_hosts.retain(|id| nodes.contains_key(*id));
            self.pending_slot_changes
                .retain(|id| nodes.contains_key(*id));
            self.signaled_slots.retain(|id| nodes.contains_key(*id));
            self.dirty_shadow_hosts
                .extend(self.shadow_host_nodes.iter().copied());
        }

        self.controls_to_form
            .retain(|control, form| !removed.contains(control) && !removed.contains(form));
        if !dirty.is_empty() {
            self.shell_provider.request_redraw();
        }

        // PaintDamage deliberately keeps old rectangles until resolve so
        // pixels formerly occupied by removed boxes are included in damage.
    }

    fn purge_dropped_node_references(&mut self) {
        if self.node_drop_depth != 0 || self.dropped_node_ids.is_empty() {
            return;
        }
        let removed = std::mem::take(&mut self.dropped_node_ids);
        let parents = std::mem::take(&mut self.dropped_node_parents);
        let owners = std::mem::take(&mut self.dropped_reference_owners);
        self.invalidate_node_references(&removed, parents, owners);
    }

    /// Remove a node from the node tree, clearing interaction state and
    /// invalidating rendering references before the surrounding drop returns.
    pub(crate) fn remove_node_from_tree(&mut self, node_id: NodeId) -> Option<Node> {
        self.clear_interaction_state_for_removed_node(node_id);
        let indexed = self.get_node(node_id).and_then(|node| {
            Some((
                node.owner_document?,
                node.element_data()?.id.as_ref()?.to_string(),
            ))
        });
        if let Some((document_id, id)) = indexed {
            self.remove_from_document_id_map(document_id, &id, node_id);
        }
        self.forget_script_custom_element(node_id);
        if self.nodes.contains_key(node_id) {
            self.dropped_node_ids.insert(node_id);
            let mut owners = FxHashSet::default();
            Self::collect_live_reference_owners(
                &self.nodes,
                &self.hoisted_fixed_parents,
                &self.dropped_node_ids,
                node_id,
                &mut owners,
            );
            self.dropped_reference_owners.extend(owners);
        }
        let node = self.nodes.remove(node_id);
        if let Some(node) = &node {
            self.dropped_node_parents.extend(
                [node.parent, node.layout_parent.get()]
                    .into_iter()
                    .flatten(),
            );
            self.purge_dropped_node_references();
        }
        node
    }

    /// The nearest element ancestor of `node_id` that is still in the
    /// document. Used to retarget hover/active state when the node they
    /// reference is removed. Tolerates already-removed ancestors (subtree
    /// teardown proceeds root-first) by giving up and returning `None`.
    fn nearest_surviving_element_ancestor(&self, node_id: NodeId) -> Option<NodeId> {
        let mut current = self.get_node(node_id)?.parent;
        while let Some(id) = current {
            let node = self.get_node(id)?;
            if node.is_element() && node.flags.is_in_document() {
                return Some(id);
            }
            current = node.parent;
        }
        None
    }

    /// Clear any interaction state (hover/active/focus/mousedown/selection/
    /// drag/scrollbar) that references `node_id`, which is being removed from
    /// the document, running the usual teardown steps. `node_id` must still be
    /// present in the slab.
    ///
    /// This matches browser semantics (WebKit `hoveredElementDidDetach` /
    /// `elementInActiveChainDidDetach`, Blink `HoveredElementDetached` /
    /// `ActiveChainNodeDetached`):
    /// - Hover and active retarget to the nearest surviving element ancestor
    ///   as a *transient bridge*: the HOVER/ACTIVE element-state bits along
    ///   the surviving chain stay lit (no one-frame gap in `:hover`/`:active`
    ///   styling), and the subsequent hover diff can unset exactly the right
    ///   bits. Hover is then re-resolved against the pointer position by
    ///   [`Self::refresh_hover`] at the end of the next resolve pass (the
    ///   analogue of WebKit's "fake mouse move"), which corrects the bridge
    ///   value — including cases where the removed node overflowed its
    ///   ancestor's box, so the ancestor was never truly under the pointer.
    /// - Focus resets to the body (encoded as `None`), running blur
    ///   side-effects (clearing focus element state and disabling IME for
    ///   text inputs).
    pub(crate) fn clear_interaction_state_for_removed_node(&mut self, node_id: NodeId) {
        if !self.nodes.contains_key(node_id) {
            return;
        }

        if self.hover_node_id == Some(node_id) {
            self.hover_node_id = self.nearest_surviving_element_ancestor(node_id);
            self.hover_node_is_text = false;
        }
        if self.hover_hit_node_id == Some(node_id) {
            self.hover_hit_node_id = None;
        }
        if self.semantic_hover_node_id == Some(node_id) {
            self.semantic_hover_node_id = None;
        }
        if self.active_node_id == Some(node_id) {
            self.active_node_id = self.nearest_surviving_element_ancestor(node_id);
        }
        if self.focus_node_id == Some(node_id) {
            let shell_provider = self.shell_provider.clone();
            self.nodes[node_id].blur(shell_provider);
            self.focus_node_id = None;
        }
        if self.mousedown_node_id == Some(node_id) {
            self.mousedown_node_id = None;
        }
        if self.text_selection.anchor.node_or_parent == Some(node_id)
            || self.text_selection.focus.node_or_parent == Some(node_id)
        {
            self.text_selection.clear();
        }
        if self
            .hovered_scrollbar
            .is_some_and(|scrollbar| scrollbar.node_id == node_id)
        {
            self.hovered_scrollbar = None;
        }
        let drag_references_node = match &self.drag_mode {
            DragMode::Panning(state) => state.target == node_id,
            DragMode::ScrollbarDrag(state) => state.scrollbar.node_id == node_id,
            DragMode::Selecting | DragMode::None => false,
        };
        if drag_references_node {
            self.drag_mode = DragMode::None;
        }
        if matches!(
            &self.scroll_animation,
            ScrollAnimationState::Fling(state) if state.target == node_id
        ) {
            self.scroll_animation = ScrollAnimationState::None;
        }
        self.scrollbar_activity.remove(&node_id);

        // The form-owner map is keyed by control id and was never pruned, so a
        // page that re-renders its fields grew an entry per render, every one
        // of them a freed slot. Nothing dereferences those any more, but an
        // unbounded map keyed on dead ids is a leak either way.
        self.controls_to_form.remove(&node_id);
    }

    pub(crate) fn drop_node_ignoring_parent(&mut self, node_id: NodeId) -> Option<Node> {
        self.drop_node_ignoring_parent_with(node_id, &mut |_| {})
    }

    /// Like [`Self::drop_node_ignoring_parent`], but calls `on_drop` with the id of
    /// every dropped node (the node itself and all of its descendants).
    pub(crate) fn drop_node_ignoring_parent_with(
        &mut self,
        node_id: NodeId,
        on_drop: &mut dyn FnMut(NodeId),
    ) -> Option<Node> {
        self.node_drop_depth += 1;
        let mut node = self.remove_node_from_tree(node_id);
        if let Some(node) = &mut node {
            on_drop(node_id);
            if let Some(before) = node.before() {
                self.drop_node_ignoring_parent_with(before, on_drop);
            }
            if let Some(after) = node.after() {
                self.drop_node_ignoring_parent_with(after, on_drop);
            }

            for &child in &node.children {
                self.drop_node_ignoring_parent_with(child, on_drop);
            }
            if let Some(contents) = node
                .element_data()
                .and_then(|element| element.template_contents)
            {
                self.drop_node_ignoring_parent_with(contents, on_drop);
            }

            // Anonymous blocks live only in the slab, so deallocate the ones this
            // node owns rather than leaking them.
            for &anon_id in &node.anonymous_blocks {
                self.deallocate_anonymous_block(anon_id);
            }

            // Drop any attached shadow root (its children are dropped recursively
            // via the recursive call below).
            #[cfg(feature = "shadow-dom")]
            if let Some(shadow_root_id) = node.shadow_root_id() {
                self.shadow_host_nodes.remove(&node_id);
                self.dirty_shadow_hosts.remove(&node_id);
                self.custom_element_nodes.remove(&node_id);
                self.drop_node_ignoring_parent_with(shadow_root_id, on_drop);
            }
        }
        self.node_drop_depth -= 1;
        self.purge_dropped_node_references();
        node
    }

    /// Deallocate an anonymous block created in a previous construction
    /// round, along with any anonymous blocks nested within it.
    pub(crate) fn deallocate_anonymous_block(&mut self, anon_id: NodeId) {
        // The block may already have been removed from the slab (e.g. a
        // whitespace-only anonymous block dropped during construction).
        if !self.nodes.contains_key(anon_id) {
            return;
        }

        // Free any anonymous blocks that this block owns before removing it.
        self.node_drop_depth += 1;
        let nested = std::mem::take(&mut self.nodes[anon_id].anonymous_blocks);
        for nested_id in nested {
            self.deallocate_anonymous_block(nested_id);
        }

        self.remove_node_from_tree(anon_id);
        self.node_drop_depth -= 1;
        self.purge_dropped_node_references();
    }

    pub fn create_text_node(&mut self, text: &str) -> NodeId {
        let content = text.to_string();
        let data = NodeData::Text(TextNodeData::new(content));
        self.create_node(data)
    }

    pub fn deep_clone_node(&mut self, node_id: NodeId) -> NodeId {
        // Load existing node
        let node = &self.nodes[node_id];
        let mut data = node.data.clone();

        match &mut data {
            NodeData::Element(elem) | NodeData::AnonymousBlock(elem) => {
                if let Some(arc) = elem.style_attribute.as_mut() {
                    let read_guard = self.guard().read();
                    let block = arc.read_with(&read_guard);
                    *arc = ServoArc::new(self.guard().wrap(block.clone()));
                }
            }
            _ => {}
        }

        let children = node.children.clone();
        #[cfg(feature = "shadow-dom")]
        let shadow_source = node.shadow_root_id();
        let template_contents = node
            .element_data()
            .and_then(|element| element.template_contents);
        let owner_document = node.owner_document;
        let markup = node.markup.clone();
        let inert_script = node
            .flags
            .contains(crate::node::NodeFlags::IS_PARSER_INERT_SCRIPT);

        // Create new node
        let new_node_id = self.create_node(data);
        self.nodes[new_node_id].owner_document = owner_document;
        self.nodes[new_node_id].markup = markup;
        self.nodes[new_node_id]
            .flags
            .set(crate::node::NodeFlags::IS_PARSER_INERT_SCRIPT, inert_script);
        if let Some(document_id) = owner_document {
            let id = self.nodes[new_node_id]
                .element_data()
                .and_then(|element| element.id.as_ref())
                .map(ToString::to_string);
            if let Some(id) = id {
                self.add_to_document_id_map(document_id, &id, new_node_id);
            }
        }
        if let Some(contents) = template_contents {
            let cloned_contents = self.deep_clone_node(contents);
            self.nodes[new_node_id]
                .element_data_mut()
                .expect("template clone must be an element")
                .template_contents = Some(cloned_contents);
        }

        // Recursively clone children
        let new_children: ThinVec<NodeId> = children
            .into_iter()
            .map(|child_id| self.deep_clone_node(child_id))
            .collect();
        for &child_id in &new_children {
            self.nodes[child_id].parent = Some(new_node_id);
            self.attach_script_custom_element_subtree(child_id, new_node_id);
        }
        self.nodes[new_node_id].children = new_children;

        // Only a shadow root that opted into `clonable` is copied. Imperative
        // roots keep the previous behavior of not cloning.
        #[cfg(feature = "shadow-dom")]
        if let Some(source_root) = shadow_source {
            let clonable = self
                .nodes
                .get(source_root)
                .and_then(|node| node.shadow_root_data())
                .is_some_and(|root| root.clonable);
            if clonable {
                let mode = self.nodes[source_root].shadow_root_data().unwrap().mode;
                let serializable = self.nodes[source_root]
                    .shadow_root_data()
                    .unwrap()
                    .serializable;
                let delegates_focus = self.nodes[source_root]
                    .shadow_root_data()
                    .unwrap()
                    .delegates_focus;
                let declarative = self.nodes[source_root]
                    .shadow_root_data()
                    .unwrap()
                    .declarative;
                let shadow_children = self.nodes[source_root].children.clone();
                let new_root = self.attach_shadow(new_node_id, mode);
                if let Some(root) = self.nodes[new_root].shadow_root_data_mut() {
                    root.clonable = true;
                    root.serializable = serializable;
                    root.delegates_focus = delegates_focus;
                    root.declarative = declarative;
                }
                let cloned_shadow_children: ThinVec<NodeId> = shadow_children
                    .into_iter()
                    .map(|child_id| self.deep_clone_node(child_id))
                    .collect();
                for &child_id in &cloned_shadow_children {
                    self.nodes[child_id].parent = Some(new_root);
                    self.attach_script_custom_element_subtree(child_id, new_root);
                }
                self.nodes[new_root].children = cloned_shadow_children;
            }
        }

        new_node_id
    }

    pub(crate) fn remove_and_drop_pe(&mut self, node_id: NodeId) -> Option<Node> {
        fn remove_pe_ignoring_parent(doc: &mut BaseDocument, node_id: NodeId) -> Option<Node> {
            let mut node = doc.remove_node_from_tree(node_id);
            if let Some(node) = &mut node {
                for &child in &node.children {
                    remove_pe_ignoring_parent(doc, child);
                }
                for &anon_id in &node.anonymous_blocks {
                    doc.deallocate_anonymous_block(anon_id);
                }
            }
            node
        }

        self.node_drop_depth += 1;
        let node = remove_pe_ignoring_parent(self, node_id);

        // Update child_idx values
        if let Some(parent_id) = node.as_ref().and_then(|node| node.parent) {
            let parent = &mut self.nodes[parent_id];
            parent.children.retain(|id| *id != node_id);
        }

        self.node_drop_depth -= 1;
        self.purge_dropped_node_references();
        node
    }

    pub(crate) fn resolve_url(&self, raw: &str) -> url::Url {
        self.url.resolve_relative(raw).unwrap_or_else(|| {
            panic!(
                "to be able to resolve {raw} with the base_url: {:?}",
                *self.url
            )
        })
    }

    /// Navigate to `raw`, resolved against this document's base URL.
    ///
    /// The same route a link click takes, exposed so that script can reach it:
    /// `location.assign`, `location.replace` and `location.reload` had nowhere
    /// to go, because `resolve_url` and the navigation provider are both
    /// internal to this crate. Returns `false` when `raw` will not resolve,
    /// so the caller can report that rather than navigate somewhere wrong.
    pub fn navigate_to_url(&self, raw: &str) -> bool {
        let Some(url) = self.url.resolve_relative(raw) else {
            return false;
        };
        self.navigation_provider
            .navigate_to(blitz_traits::navigation::NavigationOptions::new(
                url,
                None,
                self.id(),
            ));
        true
    }

    /// This document's URL, as a page's `location.href` reads it.
    pub fn current_url(&self) -> String {
        self.url.to_string()
    }

    pub fn print_tree(&self) {
        crate::util::walk_tree(0, self.root_node());
    }

    pub fn print_subtree(&self, node_id: NodeId) {
        crate::util::walk_tree(0, &self.nodes[node_id]);
    }

    pub fn reload_resource_by_href(&mut self, href_to_reload: &str) {
        for &node_id in self.nodes_to_stylesheet.keys() {
            let node = &self.nodes[node_id];
            let Some(element) = node.element_data() else {
                continue;
            };

            if element.name.local == local_name!("link") {
                if let Some(href) = element.attr(local_name!("href")) {
                    // println!("Node {node_id} {href} {href_to_reload} {} {}", resolved_href.as_str(), resolved_href.as_str() == url_to_reload);
                    if href == href_to_reload {
                        let resolved_href = self.resolve_url(href);
                        self.net_provider.fetch(
                            self.id(),
                            self.build_request(resolved_href.clone()),
                            ResourceHandler::boxed(
                                self.tx.clone(),
                                self.id,
                                Some(node_id),
                                self.shell_provider.clone(),
                                StylesheetHandler {
                                    source_url: resolved_href,
                                    guard: self.guard.clone(),
                                    net_provider: self.net_provider.clone(),
                                    abort_signal: self.abort_signal.clone(),
                                },
                            ),
                        );
                    }
                }
            }
        }
    }

    pub fn process_style_element(&mut self, target_id: NodeId) {
        let css = self.nodes[target_id].text_content();
        let css = html_escape::decode_html_entities(&css);
        let sheet = self.make_stylesheet(&css, Origin::Author);
        self.add_stylesheet_for_node(sheet, target_id);
    }

    pub fn remove_user_agent_stylesheet(&mut self, contents: &str) {
        if let Some(sheet) = self.ua_stylesheets.remove(contents) {
            self.stylist.remove_stylesheet(sheet, &self.guard.read());
        }
    }

    /// The document's base URL
    pub fn url(&self) -> &url::Url {
        &self.url
    }

    /// Iterate over the author stylesheets (from `<style>` and `<link>` nodes)
    /// currently associated with this document
    pub fn author_stylesheets(&self) -> impl Iterator<Item = &DocumentStyleSheet> {
        self.nodes_to_stylesheet.values()
    }

    /// Iterate over the user-agent stylesheets currently associated with this document
    pub fn useragent_stylesheets(&self) -> impl Iterator<Item = &DocumentStyleSheet> {
        self.ua_stylesheets.values()
    }

    pub fn add_user_agent_stylesheet(&mut self, css: &str) {
        let sheet = self.make_stylesheet(css, Origin::UserAgent);
        self.ua_stylesheets.insert(css.to_string(), sheet.clone());
        self.stylist.append_stylesheet(sheet, &self.guard.read());
    }

    pub fn make_stylesheet(&self, css: impl AsRef<str>, origin: Origin) -> DocumentStyleSheet {
        let data = Stylesheet::from_str(
            css.as_ref(),
            self.url.url_extra_data(),
            origin,
            ServoArc::new(self.guard.wrap(MediaList::empty())),
            self.guard.clone(),
            Some(&StylesheetLoader {
                tx: self.tx.clone(),
                doc_id: self.id,
                net_provider: self.net_provider.clone(),
                shell_provider: self.shell_provider.clone(),
                abort_signal: self.abort_signal.clone(),
            }),
            None,
            QuirksMode::NoQuirks,
            AllowImportRules::Yes,
        );

        DocumentStyleSheet(ServoArc::new(data))
    }

    pub fn upsert_stylesheet_for_node(&mut self, node_id: NodeId) {
        let raw_styles = self.nodes[node_id].text_content();
        let sheet = self.make_stylesheet(raw_styles, Origin::Author);
        self.add_stylesheet_for_node(sheet, node_id);
    }

    pub fn add_stylesheet_for_node(&mut self, stylesheet: DocumentStyleSheet, node_id: NodeId) {
        self.platform_initial_sheet_media(&stylesheet, node_id);
        #[cfg(feature = "shadow-dom")]
        if let Some(root_id) = self.containing_shadow_root(node_id) {
            // A sheet that moved from the document into a shadow tree leaves
            // the document Stylist first.
            if self.document_sheet_nodes.remove(&node_id)
                && let Some(old) = self.nodes_to_stylesheet.get(&node_id).cloned()
            {
                self.stylist.remove_stylesheet(old, &self.guard.read());
            }
            self.install_shadow_stylesheet(root_id, node_id, stylesheet);
            return;
        }

        let old = self.nodes_to_stylesheet.insert(node_id, stylesheet.clone());

        if let Some(old) = old
            && self.document_sheet_nodes.contains(&node_id)
        {
            self.stylist.remove_stylesheet(old, &self.guard.read())
        }
        self.document_sheet_nodes.insert(node_id);

        // Fetch @font-face fonts
        crate::net::fetch_font_face(
            self.tx.clone(),
            self.id,
            Some(node_id),
            &stylesheet.0,
            &self.net_provider,
            &self.shell_provider,
            &self.guard.read(),
            self.abort_signal.as_ref(),
            &mut self.web_fonts,
            self.font_epoch,
        );

        // Store data on element
        let element = &mut self.nodes[node_id].element_data_mut().unwrap();
        element.special_data = SpecialElementData::Stylesheet(stylesheet.clone());

        // TODO: Nodes could potentially get reused so ordering by node_id might be wrong.
        // Only sheets the document Stylist holds can be an insertion point: shadow-root sheets are
        // in `nodes_to_stylesheet` too, and stylo panics on a `before` sheet it does not have.
        let insertion_point = self
            .nodes_to_stylesheet
            .range((Bound::Excluded(node_id), Bound::Unbounded))
            .find(|(id, _)| self.document_sheet_nodes.contains(id))
            .map(|(_, sheet)| sheet);

        if let Some(insertion_point) = insertion_point {
            self.stylist.insert_stylesheet_before(
                stylesheet,
                insertion_point.clone(),
                &self.guard.read(),
            )
        } else {
            self.stylist
                .append_stylesheet(stylesheet, &self.guard.read())
        }
    }

    pub fn handle_messages(&mut self) {
        // Remove event Reciever from the Document so that we can process events
        // without holding a borrow to the Document
        let rx = self.rx.take().unwrap();

        while let Ok(msg) = rx.try_recv() {
            self.handle_message(msg);
        }

        // Put Reciever back
        self.rx = Some(rx);
    }

    pub fn handle_message(&mut self, msg: DocumentEvent) {
        match msg {
            DocumentEvent::ResourceLoad(resource) => self.load_resource(resource),
            DocumentEvent::NavigateIframe { node_id, url } => self.navigate_iframe(node_id, url),
        }
    }

    /// Whether the Document has pending requests for "critical" resources (that should block rendering)
    pub fn has_pending_critical_resources(&self) -> bool {
        !self.pending_critical_resources.is_empty()
    }

    /// How many distinct image URLs are still being fetched.
    ///
    /// Images are deliberately not "critical" resources, so they never block
    /// rendering. An embedder that needs a settled page (a screenshot, a test,
    /// a print) has no other way to tell an image that is still in flight from
    /// one that will never arrive.
    pub fn pending_image_count(&self) -> usize {
        self.pending_images.len()
    }

    pub fn load_resource(&mut self, res: ResourceLoadResponse) {
        self.pending_critical_resources.remove(&res.request_id);

        let resource = match res.result {
            Ok(resource) => resource,
            Err(err) => {
                if let Some(url) = res.resolved_url.as_ref() {
                    let waiting_nodes = self.pending_images.remove(url).unwrap_or_default();
                    #[cfg(feature = "tracing")]
                    tracing::warn!(
                        url = url.as_str(),
                        waiting_nodes = waiting_nodes.len(),
                        error = err.as_str(),
                        "Resource load failed"
                    );
                    #[cfg(not(feature = "tracing"))]
                    let _ = (waiting_nodes, err);
                } else {
                    #[cfg(feature = "tracing")]
                    tracing::warn!(error = err.as_str(), "Resource load failed (no url)");
                    #[cfg(not(feature = "tracing"))]
                    let _ = err;
                }
                return;
            }
        };

        let (resource, font_ticket) = match resource {
            Resource::TrackedFont(bytes, overrides, ticket) => {
                if ticket.css && ticket.epoch != self.font_epoch {
                    ticket.finish(false);
                    return;
                }
                (Resource::Font(bytes, overrides), Some(ticket))
            }
            resource => (resource, None),
        };
        if matches!(&resource, Resource::Css(_) | Resource::Font(_, _))
            && res.node_id.is_some_and(|id| {
                self.get_node(id)
                    .is_none_or(|node| !node.flags.is_in_document())
            })
        {
            if let Some(ticket) = font_ticket {
                ticket.finish(false);
            }
            return;
        }

        match resource {
            Resource::Css(css) => {
                let node_id = res.node_id.unwrap();
                self.add_stylesheet_for_node(css, node_id);
            }
            Resource::ImportSheet(import_rule, sheet) => {
                // The write that used to happen on the network worker. Here it
                // is on the thread that owns styling, so it cannot collide
                // with a concurrent read of the same lock.
                //
                // Scoped, because the `@font-face` scan below needs a read of
                // the same lock and this is an `AtomicRefCell`: holding the
                // write across it would deadlock against itself rather than
                // wait.
                {
                    let mut guard = self.guard.write();
                    import_rule.write_with(&mut guard).stylesheet =
                        style::stylesheets::import_rule::ImportSheet::Sheet(sheet.clone());
                }

                // The same scan `add_stylesheet_for_node` does for a top-level
                // sheet. An imported sheet may declare fonts too, and until now
                // nothing fetched them from a thread allowed to read the lock.
                crate::net::fetch_font_face(
                    self.tx.clone(),
                    self.id,
                    res.node_id,
                    &sheet,
                    &self.net_provider,
                    &self.shell_provider,
                    &self.guard.read(),
                    self.abort_signal.as_ref(),
                    &mut self.web_fonts,
                    self.font_epoch,
                );
            }
            Resource::Image(_kind, width, height, image_data) => {
                // Create the ImageData and cache it
                let image = ImageData::Raster(RasterImageData::new(width, height, image_data));

                let Some(url) = res.resolved_url.as_ref() else {
                    return;
                };

                self.apply_loaded_image(url, image);
            }
            #[cfg(feature = "svg")]
            Resource::Svg(_kind, svg) => {
                // Create the ImageData and cache it
                let image = ImageData::Svg(svg);

                let Some(url) = res.resolved_url.as_ref() else {
                    return;
                };

                self.apply_loaded_image(url, image);
            }
            Resource::DocumentSrc(html) => {
                let Some(node_id) = res.node_id else {
                    return;
                };
                self.apply_iframe_html(node_id, res.request_id, res.resolved_url, &html);
            }
            Resource::Font(bytes, overrides) => {
                let font = Blob::new(Arc::new(bytes));

                // Build a `FontInfoOverride` from the `@font-face` descriptors
                // captured during stylesheet parsing. Without this, parley
                // reads the family name from the TTF's own metadata, which
                // means CSS `font-family: 'Avenir Book'` won't match a font
                // file that internally identifies as `Avenir 45 Book`.
                let weight_override = overrides.weight.map(parley::fontique::FontWeight::new);
                let info_override = parley::fontique::FontInfoOverride {
                    family_name: overrides.family_name.as_deref(),
                    weight: weight_override,
                    style: overrides.style,
                    ..Default::default()
                };

                // TODO: Investigate eliminating double-box
                let mut global_font_ctx = self.font_ctx.lock().unwrap();
                let registered = global_font_ctx
                    .collection
                    .register_fonts(font.clone(), Some(info_override));
                let registered = !registered.is_empty();

                #[cfg(feature = "parallel-construct")]
                {
                    rayon::broadcast(|_ctx| {
                        let mut font_ctx = self
                            .thread_font_contexts
                            .get_or(|| RefCell::new(Box::new(global_font_ctx.clone())))
                            .borrow_mut();
                        font_ctx
                            .collection
                            .register_fonts(font.clone(), Some(info_override));
                    });
                }
                drop(global_font_ctx);

                // TODO: see if we can only invalidate if resolved fonts may have changed
                self.invalidate_inline_contexts();
                if let Some(ticket) = font_ticket {
                    ticket.finish(registered);
                }
            }
            Resource::TrackedFont(..) => unreachable!("tracked font was normalized"),
            Resource::None => {
                // Do nothing
            }
        }
    }

    /// Cache a loaded image and apply it to all nodes waiting on it
    /// (`<img>` elements, `background-image` layers and `mask-image` layers).
    fn apply_loaded_image(&mut self, url: &str, image: ImageData) {
        // Get all nodes waiting for this image
        let waiting_nodes = self.pending_images.remove(url).unwrap_or_default();

        #[cfg(feature = "tracing")]
        tracing::info!(
            "Image {url} loaded, applying to {} nodes",
            waiting_nodes.len()
        );

        // Cache the image
        self.image_cache.insert(url.to_string(), image.clone());

        // Apply to all waiting nodes
        for (node_id, image_type) in waiting_nodes {
            let Some(node) = self.get_node_mut(node_id) else {
                continue;
            };

            match image_type {
                ImageType::Image => {
                    node.element_data_mut().unwrap().special_data =
                        SpecialElementData::Image(Box::new(image.clone()));

                    // Clear layout cache
                    node.cache_mut().clear();
                    node.insert_damage(ALL_DAMAGE);
                }
                ImageType::Background(idx) | ImageType::Mask(idx) => {
                    let layer_image = node.element_data_mut().and_then(|el| {
                        let images = match image_type {
                            ImageType::Background(_) => &mut el.background_images,
                            ImageType::Mask(_) => &mut el.mask_images,
                            ImageType::Image => unreachable!(),
                        };
                        images.get_mut(idx)
                    });
                    if let Some(Some(layer_image)) = layer_image {
                        layer_image.status = Status::Ok;
                        layer_image.image = image.clone();
                    }
                }
            }
        }
    }

    pub fn snapshot_node(&mut self, node_id: NodeId) {
        let node = &mut self.nodes[node_id];

        // Do not snapshot nodes that have never been styled. A snapshot records an element's
        // pre-mutation state so a restyle can diff selector matches then-vs-now. An element
        // that has never been styled has no "then" to diff against. Snapshotting it anyway
        // makes Stylo's invalidation unwrap its (absent) primary style and panic.
        let has_been_styled = node.primary_styles().is_some();
        if !has_been_styled {
            return;
        }

        let opaque_node_id = TNode::opaque(&&*node);
        node.set_has_snapshot(true);
        node.snapshot_handled()
            .store(false, std::sync::atomic::Ordering::SeqCst);

        // TODO: handle invalidations other than hover
        if let Some(_existing_snapshot) = self.snapshots.get_mut(&opaque_node_id) {
            // Do nothing
            // TODO: update snapshot
        } else {
            let attrs: Option<Vec<_>> = node.attrs().map(|attrs| {
                attrs
                    .iter()
                    .map(|attr| {
                        let ident = AttrIdentifier {
                            local_name: GenericAtomIdent(attr.name.local.clone()),
                            name: GenericAtomIdent(attr.name.local.clone()),
                            namespace: GenericAtomIdent(attr.name.ns.clone()),
                            prefix: None,
                        };

                        let value = if attr.name.local == local_name!("id") {
                            AttrValue::Atom(Atom::from(&*attr.value))
                        } else if attr.name.local == local_name!("class") {
                            let classes = attr
                                .value
                                .split_ascii_whitespace()
                                .map(Atom::from)
                                .collect();
                            // Stylo's `AttrValue` owns a `String`, so the atom
                            // is materialised here. This is the one place
                            // interning is paid back out, and it is bounded:
                            // once per snapshotted attribute, not per element
                            // per frame.
                            AttrValue::TokenList(OnceLock::from(attr.value.to_string()), classes)
                        } else {
                            AttrValue::String(attr.value.to_string())
                        };

                        (ident, value)
                    })
                    .collect()
            });

            let changed_attrs = attrs
                .as_ref()
                .map(|attrs| attrs.iter().map(|attr| attr.0.name.clone()).collect())
                .unwrap_or_default();

            self.snapshots.insert(
                opaque_node_id,
                ServoElementSnapshot {
                    state: Some(*node.element_state()),
                    attrs,
                    changed_attrs,
                    class_changed: true,
                    id_changed: true,
                    other_attributes_changed: true,
                },
            );
        }
    }

    /// Preserve the original attributes and accumulate names changed before traversal.
    pub(crate) fn snapshot_attribute(&mut self, node_id: NodeId, name: &markup5ever::LocalName) {
        self.snapshot_node(node_id);
        let opaque_node_id = TNode::opaque(&&self.nodes[node_id]);
        if let Some(snapshot) = self.snapshots.get_mut(&opaque_node_id) {
            let changed_attr = GenericAtomIdent(name.clone());
            if !snapshot.changed_attrs.contains(&changed_attr) {
                snapshot.changed_attrs.extend(std::iter::once(changed_attr));
            }
        }
    }

    /// Snapshot a node and act on it, if it is still there.
    ///
    /// Tolerant of a node that has gone, because the ids reaching this are
    /// remembered across events — focus, hover, the last press — and the node
    /// they name can be removed between one event and the next. Indexing
    /// directly turned that ordinary case into a panic inside an event handler.
    pub fn snapshot_node_and(&mut self, node_id: NodeId, cb: impl FnOnce(&mut Node)) {
        if !self.nodes.contains_key(node_id) {
            return;
        }
        self.snapshot_node(node_id);
        cb(&mut self.nodes[node_id]);
    }

    // Takes (x, y) co-ordinates (relative to the )
    pub fn hit(&self, x: f32, y: f32) -> Option<HitResult> {
        self.hit_with_scrollbar(x, y).0
    }

    /// Walk up the tree to the nearest DOM node whose id is stable across
    /// box-tree reconstruction, so canonicalized interaction state never goes
    /// stale.
    ///
    /// Layout-generated nodes (anonymous blocks and `::before`/`::after`
    /// pseudo-elements, both stored as anonymous blocks) get new ids on every
    /// reconstruction, so we skip any anonymous node *and* a non-anonymous node
    /// whose parent is anonymous (the pseudo's text content). The first
    /// non-anonymous node with a non-anonymous parent is a real DOM node; the
    /// root element's `Document` parent guarantees termination.
    ///
    /// Returns `None` if `node_id` (or an ancestor) no longer exists.
    pub fn nearest_non_anonymous_ancestor(&self, node_id: NodeId) -> Option<NodeId> {
        // Recurse up the tree keeping a window of the current node and its
        // parent, advancing one step per iteration so each node is looked up
        // exactly once.
        let mut node = self.get_node(node_id)?;
        loop {
            let parent = match node.parent {
                Some(parent_id) => self.get_node(parent_id)?,
                None => return Some(node.id),
            };
            if !node.is_anonymous() && !parent.is_anonymous() {
                return Some(node.id);
            }
            node = parent;
        }
    }

    pub fn focus_next_node(&mut self) -> Option<NodeId> {
        let focussed_node_id = self.get_focussed_node_id()?;
        let id = self.next_node(&self.nodes[focussed_node_id], |node| node.is_focussable())?;
        self.set_focus_to(id);
        Some(id)
    }

    /// Move focus to the previous focussable node in the document
    pub fn focus_prev_node(&mut self) -> Option<NodeId> {
        let focussed_node_id = self.get_focussed_node_id()?;
        let id = self.prev_node(&self.nodes[focussed_node_id], |node| node.is_focussable())?;
        self.set_focus_to(id);
        Some(id)
    }

    /// Clear the focussed node
    pub fn clear_focus(&mut self) {
        if let Some(id) = self.focus_node_id {
            let shell_provider = self.shell_provider.clone();
            self.snapshot_node_and(id, |node| node.blur(shell_provider));
            self.focus_node_id = None;
        }
    }

    pub fn set_mousedown_node_id(&mut self, node_id: Option<NodeId>) {
        self.mousedown_node_id = node_id.and_then(|id| self.nearest_non_anonymous_ancestor(id));
    }
    pub fn set_focus_to(&mut self, focus_node_id: NodeId) -> bool {
        let Some(focus_node_id) = self.nearest_non_anonymous_ancestor(focus_node_id) else {
            return false;
        };
        if Some(focus_node_id) == self.focus_node_id {
            return false;
        }

        #[cfg(feature = "tracing")]
        tracing::info!("Focussed node {focus_node_id}");

        let shell_provider = self.shell_provider.clone();

        // Remove focus from the old node
        if let Some(id) = self.focus_node_id {
            self.snapshot_node_and(id, |node| node.blur(shell_provider.clone()));
        }

        // Focus the new node
        self.snapshot_node_and(focus_node_id, |node| node.focus(shell_provider));

        self.focus_node_id = Some(focus_node_id);

        true
    }

    pub fn active_node(&mut self) -> bool {
        let Some(hover_node_id) = self.get_hover_node_id() else {
            return false;
        };

        if let Some(active_node_id) = self.active_node_id {
            if active_node_id == hover_node_id {
                return true;
            }
            self.unactive_node();
        }

        // hover_node_id is canonicalized when stored, so this always holds.
        debug_assert!(
            self.get_node(hover_node_id)
                .is_some_and(|node| !node.is_anonymous()),
            "interaction state must reference DOM nodes, not layout-generated nodes"
        );
        let active_node_id = Some(hover_node_id);

        let node_path = self.maybe_node_layout_ancestors(active_node_id);
        for &id in node_path.iter() {
            self.snapshot_node_and(id, |node| node.active());
        }

        self.active_node_id = active_node_id;

        true
    }

    pub fn unactive_node(&mut self) -> bool {
        let Some(active_node_id) = self.active_node_id.take() else {
            return false;
        };

        let node_path = self.maybe_node_layout_ancestors(Some(active_node_id));
        for &id in node_path.iter() {
            self.snapshot_node_and(id, |node| node.unactive());
        }

        true
    }

    /// The scrollbar thumb currently under the pointer, if any.
    pub fn hovered_scrollbar(&self) -> Option<crate::node::ScrollbarRef> {
        self.hovered_scrollbar
    }

    /// The scrollbar thumb currently being dragged, if any.
    pub fn scrollbar_drag_target(&self) -> Option<crate::node::ScrollbarRef> {
        match &self.drag_mode {
            DragMode::ScrollbarDrag(state) => Some(state.scrollbar),
            _ => None,
        }
    }

    /// The current opacity of `node_id`'s overlay scrollbars. They show at
    /// full opacity on scroll and fade out after a delay (Chromium's overlay
    /// timings); the pointer resting on a thumb, or dragging it, holds them
    /// visible.
    pub fn scrollbar_opacity(&self, node_id: NodeId) -> f32 {
        let interacting = |scrollbar: &crate::node::ScrollbarRef| scrollbar.node_id == node_id;
        if self.hovered_scrollbar.as_ref().is_some_and(interacting)
            || self
                .scrollbar_drag_target()
                .as_ref()
                .is_some_and(interacting)
        {
            return 1.0;
        }
        self.scrollbar_activity.get(&node_id).map_or(1.0, |last| {
            crate::node::scrollbar::opacity_at(last.elapsed())
        })
    }

    /// Show `node_id`'s overlay scrollbars at full opacity and restart their
    /// fade-out delay.
    pub(crate) fn show_scrollbars(&mut self, node_id: NodeId) {
        if cfg!(feature = "scrollbars") {
            self.scrollbar_activity.insert(node_id, Instant::now());
        }
    }

    /// Whether any overlay scrollbars are awaiting or animating their
    /// fade-out (so frames must keep rendering until they finish).
    fn scrollbars_animating(&self) -> bool {
        use crate::node::scrollbar::{FADE_DELAY, FADE_DURATION};
        self.scrollbar_activity
            .values()
            .any(|last| last.elapsed() < FADE_DELAY + FADE_DURATION)
    }

    /// [`hit`](Self::hit), also resolving the innermost overlay scrollbar
    /// thumb under the point (shares the traversal, so it costs nothing
    /// extra).
    pub(crate) fn hit_with_scrollbar(
        &self,
        x: f32,
        y: f32,
    ) -> (Option<HitResult>, Option<crate::node::ScrollbarRef>) {
        if TDocument::as_node(&self.root_node())
            .first_element_child()
            .is_none()
        {
            #[cfg(feature = "tracing")]
            tracing::warn!("No DOM - not resolving hit test");
            return (None, None);
        }
        let mut scrollbar = None;
        let hit = self
            .root_element()
            .hit_inner(x, y, self.viewport().scale_f64(), &mut scrollbar);
        (hit, scrollbar)
    }

    pub fn set_hover_to(&mut self, x: f32, y: f32) -> bool {
        self.semantic_hover_node_id = None;
        // Record the pointer position in client (unscrolled) coordinates so
        // that `refresh_hover` can re-resolve hover state after layout or
        // scroll changes.
        self.last_client_pointer_position = Some(taffy::Point {
            x: x - self.viewport_scroll.x as f32,
            y: y - self.viewport_scroll.y as f32,
        });

        let (hit, hovered_scrollbar) = self.hit_with_scrollbar(x, y);
        // A faded-out thumb is not interactive: pointer moves never fade
        // overlay scrollbars back in (only scrolling shows them).
        let hovered_scrollbar =
            hovered_scrollbar.filter(|scrollbar| self.scrollbar_opacity(scrollbar.node_id) > 0.0);
        // Scrollbar-thumb hover is part of hover state: track it here so a
        // pointer crossing a thumb restyles it even when the hit node (the
        // content under the overlay thumb) is unchanged.
        let scrollbar_changed = hovered_scrollbar != self.hovered_scrollbar;
        if scrollbar_changed {
            // Entering a thumb restores full opacity mid-fade; leaving one
            // restarts the fade-out delay.
            for scrollbar in [self.hovered_scrollbar, hovered_scrollbar]
                .into_iter()
                .flatten()
            {
                self.show_scrollbars(scrollbar.node_id);
            }
        }
        self.hovered_scrollbar = hovered_scrollbar;

        // Store both the precise layout node that was hit (transient: used for
        // cursor/style queries) and its canonical DOM target (persistent: must
        // not reference layout-generated nodes, whose ids die on box-tree
        // reconstruction).
        let hit_node_id = hit.map(|hit| hit.node_id);
        let hover_node_id = hit_node_id.and_then(|id| self.nearest_non_anonymous_ancestor(id));
        let new_is_text = hit.map(|hit| hit.is_text).unwrap_or(false);

        self.apply_hover_target(hit_node_id, hover_node_id, new_is_text, scrollbar_changed)
    }

    /// Move the authored hover state to an already-resolved DOM node.
    ///
    /// Semantic automation has selected a node by identity already. Repeating
    /// hit testing at its centre can choose an overlapping child or overlay,
    /// especially inside nested scrollers, and makes `Hover { node_id }`
    /// target something other than the requested node. Pointer coordinates are
    /// still recorded for event payloads and later layout refreshes.
    pub fn set_hover_to_node(&mut self, node_id: NodeId, x: f32, y: f32) -> bool {
        self.semantic_hover_node_id = Some(node_id);
        self.last_client_pointer_position = Some(taffy::Point {
            x: x - self.viewport_scroll.x as f32,
            y: y - self.viewport_scroll.y as f32,
        });

        let hovered_scrollbar = self.hovered_scrollbar.take();
        let scrollbar_changed = hovered_scrollbar.is_some();
        if let Some(scrollbar) = hovered_scrollbar {
            self.show_scrollbars(scrollbar.node_id);
        }
        let hover_node_id = self.nearest_non_anonymous_ancestor(node_id);
        self.apply_hover_target(Some(node_id), hover_node_id, false, scrollbar_changed)
    }

    fn apply_hover_target(
        &mut self,
        hit_node_id: Option<NodeId>,
        hover_node_id: Option<NodeId>,
        new_is_text: bool,
        scrollbar_changed: bool,
    ) -> bool {
        let hit_changed =
            hit_node_id != self.hover_hit_node_id || new_is_text != self.hover_node_is_text;
        self.hover_hit_node_id = hit_node_id;
        self.hover_node_is_text = new_is_text;

        // Return early if the new node is the same as the already-hovered node
        if hover_node_id == self.hover_node_id {
            if hit_changed {
                // The canonical target is unchanged (so no restyle is needed)
                // but the precise hit node changed, which can change the cursor
                // (e.g. moving between text and non-text within one element).
                self.shell_provider.set_cursor(self.get_cursor());
            }
            return scrollbar_changed;
        }

        let old_node_path = self.maybe_node_layout_ancestors(self.hover_node_id);
        let new_node_path = self.maybe_node_layout_ancestors(hover_node_id);
        let same_count = old_node_path
            .iter()
            .zip(&new_node_path)
            .take_while(|(o, n)| o == n)
            .count();
        for &id in old_node_path.iter().skip(same_count) {
            self.snapshot_node_and(id, |node| node.unhover());
        }
        for &id in new_node_path.iter().skip(same_count) {
            self.snapshot_node_and(id, |node| node.hover());
        }

        self.hover_node_id = hover_node_id;

        // Update the cursor
        self.shell_provider.set_cursor(self.get_cursor());

        // Request redraw
        self.shell_provider.request_redraw();

        true
    }

    pub fn clear_hover(&mut self) -> bool {
        // The pointer is no longer over the document, so stop re-resolving
        // hover state against it.
        self.last_client_pointer_position = None;
        self.semantic_hover_node_id = None;
        self.hover_hit_node_id = None;

        let Some(hover_node_id) = self.hover_node_id else {
            return false;
        };

        let old_node_path = self.maybe_node_layout_ancestors(Some(hover_node_id));
        for &id in old_node_path.iter() {
            self.snapshot_node_and(id, |node| node.unhover());
        }

        self.hover_node_id = None;
        self.hover_node_is_text = false;

        // Update the cursor
        self.shell_provider.set_cursor(self.get_cursor());

        // Request redraw
        self.shell_provider.request_redraw();

        true
    }

    /// Re-resolve hover state against the current layout using the last known
    /// pointer position.
    ///
    /// TODO: synthesizing pointerenter/pointerleave DOM events for
    /// hover changes caused by layout shifts.
    pub fn refresh_hover(&mut self) -> bool {
        if let Some(node_id) = self.semantic_hover_node_id {
            if self.get_node(node_id).is_some() {
                let hover_node_id = self.nearest_non_anonymous_ancestor(node_id);
                return self.apply_hover_target(Some(node_id), hover_node_id, false, false);
            }
            self.semantic_hover_node_id = None;
        }
        let Some(pos) = self.last_client_pointer_position else {
            return false;
        };
        let x = pos.x + self.viewport_scroll.x as f32;
        let y = pos.y + self.viewport_scroll.y as f32;
        self.set_hover_to(x, y)
    }

    pub fn get_hover_node_id(&self) -> Option<NodeId> {
        self.hover_node_id
    }

    pub fn get_mousedown_node_id(&self) -> Option<NodeId> {
        self.mousedown_node_id
    }

    pub fn set_viewport(&mut self, viewport: Viewport) {
        let scale_has_changed = viewport.scale_f64() != self.viewport.scale_f64();
        self.viewport = viewport;
        self.set_stylist_device(make_device(
            &self.viewport,
            self.media_type.clone(),
            self.font_ctx.clone(),
        ));
        self.scroll_viewport_by(0.0, 0.0); // Clamp scroll offset

        if scale_has_changed {
            self.invalidate_inline_contexts();
            self.shell_provider.request_redraw();
        }
    }

    /// Returns the current CSS media type used to evaluate `@media` rules.
    pub fn media_type(&self) -> &MediaType {
        &self.media_type
    }

    /// Sets the CSS media type used to evaluate `@media` rules (e.g. `screen` or `print`)
    /// and rebuilds the stylist device so updated rules apply on the next restyle.
    pub fn set_media_type(&mut self, media_type: MediaType) {
        if self.media_type == media_type {
            return;
        }
        self.media_type = media_type;
        self.set_stylist_device(make_device(
            &self.viewport,
            self.media_type.clone(),
            self.font_ctx.clone(),
        ));
    }

    pub fn viewport(&self) -> &Viewport {
        &self.viewport
    }

    pub fn viewport_mut(&mut self) -> ViewportMut<'_> {
        ViewportMut::new(self)
    }

    pub fn zoom_by(&mut self, increment: f32) {
        *self.viewport.zoom_mut() += increment;
        self.set_viewport(self.viewport.clone());
    }

    pub fn zoom_to(&mut self, zoom: f32) {
        *self.viewport.zoom_mut() = zoom;
        self.set_viewport(self.viewport.clone());
    }

    pub fn get_viewport(&self) -> Viewport {
        self.viewport.clone()
    }

    /// Returns whether incremental layout is currently enabled for this document.
    pub fn incremental_layout(&self) -> bool {
        self.incremental_layout
    }

    /// Enables or disables incremental layout for this document.
    pub fn set_incremental_layout(&mut self, enabled: bool) {
        self.incremental_layout = enabled;
    }

    pub fn devtools(&self) -> &DevtoolSettings {
        &self.devtool_settings
    }

    pub fn devtools_mut(&mut self) -> &mut DevtoolSettings {
        &mut self.devtool_settings
    }

    pub fn subdoc(&self, node_id: NodeId) -> Option<&dyn Document> {
        self.get_node(node_id)
            .and_then(|node| node.element_data())
            .and_then(|el| el.sub_doc_data())
    }

    pub fn subdoc_mut(&mut self, node_id: NodeId) -> Option<&mut dyn Document> {
        self.get_node_mut(node_id)
            .and_then(|node| node.element_data_mut())
            .and_then(|el| el.sub_doc_data_mut())
    }

    pub fn is_animating(&self) -> bool {
        #[cfg(feature = "custom-widget")]
        let custom_widget_is_animating = self.custom_widget_nodes.iter().any(|&node_id| {
            self.nodes[node_id]
                .element_data()
                .and_then(|el| el.custom_widget_data())
                .is_some_and(|data| data.widget.requires_redraw())
        });
        #[cfg(not(feature = "custom-widget"))]
        let custom_widget_is_animating = false;

        let animating = self.has_canvas
            | self.has_active_animations
            | (self.subdoc_animation_pacing != AnimationPacing::Idle)
            | custom_widget_is_animating
            | (self.scroll_animation != ScrollAnimationState::None)
            | self.scrollbars_animating();

        if animating && crate::debug::animation_reasons_enabled() {
            crate::debug::report_animation_reasons(
                self.id(),
                self.has_canvas,
                self.has_active_animations,
                self.subdoc_animation_pacing != AnimationPacing::Idle,
                custom_widget_is_animating,
                self.scroll_animation != ScrollAnimationState::None,
                self.scrollbars_animating(),
                self.animating_node_names().as_deref(),
            );
        }

        animating
    }

    /// Return the cadence class for the next animation-only frame.
    ///
    /// CSS animations are commonly decorative and can use a lower cadence.
    /// Canvas, scrolling and custom widgets remain at the interactive cadence.
    pub fn animation_pacing(&self) -> AnimationPacing {
        let focused_text_input = self.focus_node_id.is_some_and(|node_id| {
            self.nodes
                .get(node_id)
                .and_then(|node| node.element_data())
                .is_some_and(|element| element.text_input_data().is_some())
        });
        #[cfg(feature = "custom-widget")]
        let custom_widget_is_animating = self.custom_widget_nodes.iter().any(|&node_id| {
            self.nodes[node_id]
                .element_data()
                .and_then(|el| el.custom_widget_data())
                .is_some_and(|data| data.widget.requires_redraw())
        });
        #[cfg(not(feature = "custom-widget"))]
        let custom_widget_is_animating = false;

        if self.has_canvas
            || custom_widget_is_animating
            || self.scroll_animation != ScrollAnimationState::None
            || self.scrollbars_animating()
        {
            AnimationPacing::Interactive
        } else if self.has_active_animations {
            const SLOW_ANIMATION_SECONDS: f64 = 2.0;
            let sets = self.animations.sets.read();
            let has_fast_animation_or_transition = sets.values().any(|set| {
                set.transitions.iter().any(|transition| {
                    matches!(
                        transition.state,
                        AnimationState::Pending | AnimationState::Running
                    )
                }) || set.animations.iter().any(|animation| {
                    matches!(
                        animation.state,
                        AnimationState::Pending | AnimationState::Running
                    ) && animation.duration < SLOW_ANIMATION_SECONDS
                })
            });
            if has_fast_animation_or_transition {
                AnimationPacing::Interactive
            } else {
                AnimationPacing::SlowCss
            }
        } else if focused_text_input {
            AnimationPacing::Caret
        } else if self.subdoc_animation_pacing != AnimationPacing::Idle {
            self.subdoc_animation_pacing
        } else {
            AnimationPacing::Idle
        }
    }

    /// Which elements Stylo currently holds animations or transitions for.
    ///
    /// Only built when the diagnostic is switched on: a frame loop that will
    /// not settle is otherwise very hard to attribute, because
    /// `has_active_animations` is one bool for the whole document and says
    /// nothing about which element is keeping it true.
    fn animating_node_names(&self) -> Option<String> {
        if !self.has_active_animations {
            return None;
        }
        let sets = self.animations.sets.read();
        let mut described: Vec<String> = sets
            .iter()
            .filter(|(_, state)| state.needs_animation_ticks())
            .filter_map(|(key, state)| {
                let node_id = NodeId::from_u64(key.node.id() as u64);
                let node = self.nodes.get(node_id)?;
                let element = node.element_data()?;
                let name = element
                    .attr(local_name!("id"))
                    .map(|id| format!("#{id}"))
                    .or_else(|| {
                        element
                            .attr(local_name!("class"))
                            .and_then(|c| c.split_ascii_whitespace().next())
                            .map(|c| format!(".{c}"))
                    })
                    .unwrap_or_else(|| element.name.local.to_string());
                Some(format!(
                    "{name}(anim={},trans={},in_doc={})",
                    state.animations.len(),
                    state.transitions.len(),
                    node.flags.is_in_document(),
                ))
            })
            .collect();
        described.sort();
        described.truncate(12);
        Some(described.join(" "))
    }

    /// Update the device and reset the stylist to process the new size
    pub fn set_stylist_device(&mut self, device: Device) {
        self.viewport_generation = self.viewport_generation.wrapping_add(1);
        // Viewport units become pixels at cascade time, from this device.
        // Compare before `device` is moved into the stylist.
        let previous_viewport = self.stylist.device().au_viewport_size();
        let next_viewport = device.au_viewport_size();

        // Seed the new device with the root element's current style and font-relative
        // unit state (used to resolve rem/rlh/rex/rch/rcap/ric units). Stylo only
        // updates this state when the root element's style *changes* during a restyle,
        // so a freshly-built device would otherwise resolve these units against the
        // default font-size (16px) until the root's font-size next changes.
        let root_styles = self
            .try_root_element()
            .and_then(|root| root.primary_styles());
        if let Some(root_style) = root_styles.as_deref() {
            device.set_root_style(root_style);

            let font = root_style.get_font();
            let font_size = font.clone_font_size().computed_size();
            device.set_root_font_size(root_style.effective_zoom.unzoom(font_size.px()));

            let line_height = device
                .calc_line_height(font, root_style.writing_mode, None)
                .0;
            device.set_root_line_height(root_style.effective_zoom.unzoom(line_height.px()));
        }
        drop(root_styles);

        let origins = {
            let guard = &self.guard;
            let guards = StylesheetGuards {
                author: &guard.read(),
                ua_or_user: &guard.read(),
            };
            self.stylist.set_device(device, &guards)
        };
        self.stylist.force_stylesheet_origins_dirty(origins);
        #[cfg(feature = "shadow-dom")]
        for host_id in self.shadow_host_node_ids() {
            if let Some(root_id) = self.shadow_root_id(host_id) {
                self.invalidate_shadow_styles(root_id);
            }
        }

        // `Stylist::set_device` reports media-query changes only. A CSS-pixel
        // change still has to recascade `vh`/`vw` (including on `::before`)
        // and lay out again: the initial containing block changed, and
        // incremental layout otherwise keeps the boxes from the previous
        // viewport. Capture builds the document at 0x0 and installs the real
        // viewport here, on the way into the next `resolve`.
        if previous_viewport != next_viewport {
            self.abspos_layout_dirty = true;
            let invalidated = self
                .try_root_element()
                .is_some_and(|root| style::invalidation::viewport_units::invalidate(root));
            if invalidated {
                self.shell_provider.request_redraw();
            }
        }
    }

    pub fn stylist_device(&mut self) -> &Device {
        self.stylist.device()
    }

    /// The cursor to show, where `None` means `cursor: none` — hide it.
    ///
    /// `None` is an answer, not the absence of one. The shell hides the pointer
    /// when it sees `None`, so every path that means "nothing to say here" must
    /// return `Default` instead. Returning `None` from those made the pointer
    /// vanish as it crossed into page content, which is the shape this used to
    /// have: three `?`s that each meant "no opinion" and all read as "hide".
    pub fn get_cursor(&self) -> Option<CursorIcon> {
        // Prefer the precise hit node: `cursor` and `user-select` may be set on
        // a pseudo-element or resolved on an anonymous box, and text hits carry
        // is_text via the hit node. Fall back to the canonical hover node if
        // the hit node has been removed (it is transient across resolves).
        let node_id = self
            .hover_hit_node_id
            .filter(|&id| self.nodes.contains_key(id))
            .or(self.get_hover_node_id());
        let Some(node_id) = node_id else {
            return Some(CursorIcon::Default);
        };
        let node = &self.nodes[node_id];

        if let Some(subdoc) = node.subdoc().map(|doc| doc.inner()) {
            // Only delegate when the sub-document has hover state of its own.
            // Without this check an embedded document that has not been hovered
            // yet answers `None` — meaning "I have no hover node" — and the
            // pointer disappears the moment it enters the page area, which is
            // every page in a browser built on sub-documents.
            if subdoc.hover_hit_node_id.is_some() || subdoc.get_hover_node_id().is_some() {
                return subdoc.get_cursor();
            }
            return Some(CursorIcon::Default);
        }

        let Some(style) = node.primary_styles() else {
            return Some(CursorIcon::Default);
        };
        let user_select = style.clone_user_select();
        let keyword = style.clone_cursor().keyword;

        // Return cursor from style if it is non-auto
        if keyword != CursorKind::Auto {
            return stylo_to_cursor_icon(keyword);
        }

        // Return text cursor for text inputs
        if node
            .element_data()
            .is_some_and(|e| e.text_input_data().is_some())
        {
            return Some(CursorIcon::Text);
        }

        // Use "pointer" cursor if any ancestor is a link
        let mut maybe_node = Some(node);
        while let Some(node) = maybe_node {
            if node.is_link() {
                return Some(CursorIcon::Pointer);
            }

            maybe_node = node.layout_parent.get().map(|node_id| node.with(node_id));
        }

        // Return text cursor for text nodes
        if self.hover_node_is_text {
            return Some(match user_select {
                UserSelect::Text | UserSelect::All | UserSelect::Auto => CursorIcon::Text,
                UserSelect::None => CursorIcon::Default,
            });
        }

        // Else fallback to default cursor
        Some(CursorIcon::Default)
    }

    pub fn scroll_node_by<F: FnMut(DomEvent)>(
        &mut self,
        node_id: NodeId,
        x: f64,
        y: f64,
        dispatch_event: F,
    ) {
        self.scroll_node_by_has_changed(node_id, x, y, dispatch_event);
    }

    /// Scroll a node by given x and y
    /// Will bubble scrolling up to parent node once it can no longer scroll further
    /// If we're already at the root node, bubbles scrolling up to the viewport
    ///
    /// A `position: sticky` box is held against the edge of the scrollport it
    /// lives in, so the boxes have to be re-adjusted here rather than only in
    /// `resolve`: a wheel event does not necessarily produce a style and layout
    /// pass, and a header that only unstuck on the next restyle is a header
    /// that visibly lags the scroll.
    pub fn scroll_node_by_has_changed<F: FnMut(DomEvent)>(
        &mut self,
        node_id: NodeId,
        x: f64,
        y: f64,
        dispatch_event: F,
    ) -> bool {
        let has_changed = self.scroll_node_by_inner(node_id, x, y, dispatch_event);
        if has_changed {
            self.resolve_positioned_scroll();
        }
        has_changed
    }

    fn scroll_node_by_inner<F: FnMut(DomEvent)>(
        &mut self,
        node_id: NodeId,
        x: f64,
        y: f64,
        mut dispatch_event: F,
    ) -> bool {
        // Per the CSS overflow propagation rules, the root element's overflow (and usually
        // the <body>'s) is applied to the viewport, and the element itself must not have
        // a scrolling mechanism of its own. So scrolls that reach the root element are
        // forwarded to the viewport rather than scrolling the root element itself.
        if self.try_root_element().is_some_and(|el| el.id == node_id) {
            let has_changed = self.scroll_viewport_by_has_changed(x, y);
            if has_changed {
                let layout = *self.root_element().final_layout();
                let scale = self.viewport.scale() as f64;
                let event = BlitzScrollEvent {
                    scroll_top: self.viewport_scroll.y,
                    scroll_left: self.viewport_scroll.x,
                    scroll_width: layout.size.width.max(layout.content_size.width) as i32,
                    scroll_height: layout.size.height.max(layout.content_size.height) as i32,
                    client_width: (self.viewport.window_size.0 as f64 / scale) as i32,
                    client_height: (self.viewport.window_size.1 as f64 / scale) as i32,
                };
                dispatch_event(DomEvent::new(node_id, DomEventData::Scroll(event)));
            }
            return has_changed;
        }

        let Some(node) = self.nodes.get_mut(node_id) else {
            return false;
        };

        // Text inputs scroll their own internal text content rather than using the generic
        // overflow mechanism: single-line inputs scroll horizontally, multi-line inputs scroll
        // vertically. Any delta the input cannot consume is bubbled up to an ancestor scroller.
        if node
            .element_data()
            .is_some_and(|el| el.text_input_data().is_some())
        {
            let parent = node.parent;
            let content_box_width = node.final_layout().content_box_width();
            let content_box_height = node.final_layout().content_box_height();
            let input = node
                .element_data_mut()
                .and_then(|el| el.text_input_data_mut())
                .unwrap();

            let (bubble_x, bubble_y) = if input.is_multiline {
                (
                    x,
                    input.scroll_by(y as f32, content_box_width, content_box_height) as f64,
                )
            } else {
                (
                    input.scroll_by(x as f32, content_box_width, content_box_height) as f64,
                    y,
                )
            };

            let has_changed = bubble_x != x || bubble_y != y;

            if bubble_x != 0.0 || bubble_y != 0.0 {
                let bubbled = if let Some(parent) = parent {
                    self.scroll_node_by_inner(parent, bubble_x, bubble_y, dispatch_event)
                } else {
                    self.scroll_viewport_by_has_changed(bubble_x, bubble_y)
                };
                return bubbled | has_changed;
            }

            return has_changed;
        }

        let (can_x_scroll, can_y_scroll) = node
            .primary_styles()
            .map(|styles| {
                (
                    matches!(styles.clone_overflow_x(), Overflow::Scroll | Overflow::Auto),
                    matches!(styles.clone_overflow_y(), Overflow::Scroll | Overflow::Auto),
                )
            })
            .unwrap_or((false, false));

        let initial = *node.scroll_offset();
        let new_x = node.scroll_offset().x - x;
        let new_y = node.scroll_offset().y - y;

        let mut bubble_x = 0.0;
        let mut bubble_y = 0.0;

        let scroll_width = node.final_layout().scroll_width() as f64;
        let scroll_height = node.final_layout().scroll_height() as f64;

        // Handle sub document case
        if let Some(mut sub_doc) = node.subdoc_mut().map(|doc| doc.inner_mut()) {
            let has_changed = if let Some(hover_node_id) = sub_doc.get_hover_node_id() {
                sub_doc.scroll_node_by_has_changed(hover_node_id, x, y, dispatch_event)
            } else {
                sub_doc.scroll_viewport_by_has_changed(x, y)
            };

            // TODO: propagate remaining scroll to parent
            return has_changed;
        }

        // If we're past our scroll bounds, transfer remainder of scrolling to parent/viewport
        if !can_x_scroll {
            bubble_x = x
        } else if new_x < 0.0 {
            bubble_x = -new_x;
            node.scroll_offset_mut().x = 0.0;
        } else if new_x > scroll_width {
            bubble_x = scroll_width - new_x;
            node.scroll_offset_mut().x = scroll_width;
        } else {
            node.scroll_offset_mut().x = new_x;
        }

        if !can_y_scroll {
            bubble_y = y
        } else if new_y < 0.0 {
            bubble_y = -new_y;
            node.scroll_offset_mut().y = 0.0;
        } else if new_y > scroll_height {
            bubble_y = scroll_height - new_y;
            node.scroll_offset_mut().y = scroll_height;
        } else {
            node.scroll_offset_mut().y = new_y;
        }

        let has_changed = *node.scroll_offset() != initial;

        if has_changed {
            let layout = *node.final_layout();
            let event = BlitzScrollEvent {
                scroll_top: node.scroll_offset().y,
                scroll_left: node.scroll_offset().x,
                scroll_width: layout.scroll_width() as i32,
                scroll_height: layout.scroll_height() as i32,
                client_width: layout.size.width as i32,
                client_height: layout.size.height as i32,
            };

            dispatch_event(DomEvent::new(node_id, DomEventData::Scroll(event)));
        }

        let parent = node.parent;
        if has_changed {
            self.show_scrollbars(node_id);
        }

        if bubble_x != 0.0 || bubble_y != 0.0 {
            if let Some(parent) = parent {
                return self.scroll_node_by_inner(parent, bubble_x, bubble_y, dispatch_event)
                    | has_changed;
            } else {
                return self.scroll_viewport_by_has_changed(bubble_x, bubble_y) | has_changed;
            }
        }

        has_changed
    }

    pub fn scroll_viewport_by(&mut self, x: f64, y: f64) {
        self.scroll_viewport_by_has_changed(x, y);
    }

    /// Scroll the viewport by the given values
    pub fn scroll_viewport_by_has_changed(&mut self, x: f64, y: f64) -> bool {
        // The viewport scrolls the root element's scrollable overflow, which includes both
        // the root element itself and any content which overflows it (e.g. when the root
        // element has a fixed height but its content is taller). A document without a root
        // element has no scrollable content, so its content size is zero.
        let (content_width, content_height) = match self.try_root_element() {
            Some(root) => {
                let root_layout = root.final_layout();
                (
                    root_layout.size.width.max(root_layout.content_size.width) as f64,
                    root_layout.size.height.max(root_layout.content_size.height) as f64,
                )
            }
            None => (0.0, 0.0),
        };
        let new_scroll = (self.viewport_scroll.x - x, self.viewport_scroll.y - y);
        let window_width = self.viewport.window_size.0 as f64 / self.viewport.scale() as f64;
        let window_height = self.viewport.window_size.1 as f64 / self.viewport.scale() as f64;

        let initial = self.viewport_scroll;
        self.viewport_scroll.x =
            f64::max(0.0, f64::min(new_scroll.0, content_width - window_width));
        self.viewport_scroll.y =
            f64::max(0.0, f64::min(new_scroll.1, content_height - window_height));

        let has_changed = self.viewport_scroll != initial;
        if has_changed {
            // The viewport is the scrollport a page-level sticky box is held
            // against, and the containing block a fixed box is pinned to, so
            // both move with this and not with the next relayout. See
            // `resolve_sticky_positions` and `resolve_fixed_positions`.
            self.resolve_positioned_scroll();
        }
        has_changed
    }

    pub fn scroll_by(
        &mut self,
        anchor_node_id: Option<NodeId>,
        scroll_x: f64,
        scroll_y: f64,
        dispatch_event: &mut dyn FnMut(DomEvent),
    ) -> bool {
        if let Some(anchor_node_id) = anchor_node_id {
            self.scroll_node_by_has_changed(anchor_node_id, scroll_x, scroll_y, dispatch_event)
        } else {
            self.scroll_viewport_by_has_changed(scroll_x, scroll_y)
        }
    }

    pub fn viewport_scroll(&self) -> crate::Point<f64> {
        self.viewport_scroll
    }

    pub fn set_viewport_scroll(&mut self, scroll: crate::Point<f64>) {
        self.viewport_scroll = scroll;
    }

    /// Find the node targeted by a URL fragment (the `#...` part of a URL).
    ///
    /// Per the HTML spec, this is the element whose `id` matches the fragment, falling
    /// back to the first `<a>` element whose `name` attribute matches.
    pub fn get_fragment_target(&self, fragment: &str) -> Option<NodeId> {
        if let Some(node_id) = self.get_element_by_id(fragment) {
            return Some(node_id);
        }

        // Fall back to a named anchor: `<a name="...">`
        self.nodes.iter().find_map(|(id, node)| {
            let el = node.element_data()?;
            (el.name.local == local_name!("a") && el.attr(local_name!("name")) == Some(fragment))
                .then_some(id)
        })
    }

    /// Scroll the viewport so that the given node is aligned with the top of the viewport.
    /// Scroll the nearest scroll container at or above `node_id`.
    ///
    /// "Scroll this panel" is the operation callers actually want, and
    /// `scroll_node_by` only moves the node itself, so naming any inner element
    /// silently did nothing. Wheel events are no help either: they are
    /// delivered to whatever the document last saw hovered, which an injected
    /// pointer move does not set, so an automated caller had no way to scroll
    /// anything at all.
    /// The nearest scroll container at or above `node_id`, if there is one.
    pub fn nearest_scroll_container(&self, node_id: NodeId) -> Option<NodeId> {
        let mut current = Some(node_id);
        for _ in 0..64 {
            let id = current?;
            let node = self.nodes.get(id)?;
            if node.style().overflow.x.is_scroll_container()
                || node.style().overflow.y.is_scroll_container()
            {
                return Some(id);
            }
            current = node.parent;
        }
        None
    }

    pub fn scroll_nearest_container_by(&mut self, node_id: NodeId, x: f64, y: f64) -> bool {
        self.scroll_nearest_container_by_with_events(node_id, x, y, |_| {})
    }

    pub fn scroll_nearest_container_by_with_events<F: FnMut(DomEvent)>(
        &mut self,
        node_id: NodeId,
        x: f64,
        y: f64,
        mut dispatch_event: F,
    ) -> bool {
        let mut current = Some(node_id);
        for _ in 0..64 {
            let Some(id) = current else { break };
            let Some(node) = self.nodes.get(id) else {
                break;
            };
            let scrolls = node.style().overflow.x.is_scroll_container()
                || node.style().overflow.y.is_scroll_container();
            if scrolls {
                self.scroll_node_by(id, x, y, &mut dispatch_event);
                return true;
            }
            current = node.parent;
        }
        self.scroll_viewport_by(x, y);
        false
    }

    pub fn scroll_to_node(&mut self, node_id: NodeId) {
        self.scroll_to_node_with_events(node_id, |_| {});
    }

    pub fn scroll_to_node_with_events<F: FnMut(DomEvent)>(
        &mut self,
        node_id: NodeId,
        dispatch_event: F,
    ) {
        self.scroll_to_node_aligned_with_events(node_id, false, dispatch_event);
    }

    /// Reveal a node near the centre of each scrollport and the viewport.
    ///
    /// Semantic input uses this placement so fixed or sticky chrome cannot
    /// cover the point an automation client will drive. Ordinary DOM
    /// `scrollIntoView` and fragment navigation retain their start alignment.
    pub fn scroll_to_node_centered_with_events<F: FnMut(DomEvent)>(
        &mut self,
        node_id: NodeId,
        dispatch_event: F,
    ) {
        self.scroll_to_node_aligned_with_events(node_id, true, dispatch_event);
    }

    fn scroll_to_node_aligned_with_events<F: FnMut(DomEvent)>(
        &mut self,
        node_id: NodeId,
        centered: bool,
        mut dispatch_event: F,
    ) {
        // Semantic snapshots expose visible text as addressable nodes, but a
        // text node does not own a Taffy layout box. `absolute_position` and
        // the scrolling calculations below require one, so resolve such a
        // target to its nearest layout ancestor first. Without this, asking an
        // automation client to reveal a label panics the entire host at
        // `Node::final_layout` instead of scrolling the label's box into view.
        let mut scroll_target = Some(node_id);
        let node_id = loop {
            let Some(candidate) = scroll_target else {
                return;
            };
            let Some(node) = self.nodes.get(candidate) else {
                return;
            };
            if matches!(
                node.data,
                NodeData::Element(_) | NodeData::AnonymousBlock(_) | NodeData::Document(_)
            ) {
                break candidate;
            }
            scroll_target = node.layout_parent.get().or(node.parent);
        };

        // Every scroll container between the node and the root, innermost
        // first. Scrolling only the viewport is not `scrollIntoView`: it does
        // nothing at all for a node inside a nested scroller, which is what an
        // application's own scrolling panes are.
        //
        // This was not academic. A transcript pane held its "Show 12 earlier
        // messages" button at y=-9463 and neither wheel events, Page Up nor
        // this call moved it by a single pixel, so a layout bug that only
        // appears further up the thread could not be reached from outside the
        // app at all. Every measurement of it had to come from a human
        // scrolling by hand and saying "now".
        let mut chain = Vec::new();
        let mut current = self.nodes.get(node_id).and_then(|node| node.parent);
        while let Some(id) = current {
            let Some(node) = self.nodes.get(id) else {
                break;
            };
            let scrolls = node.style().overflow.x.is_scroll_container()
                || node.style().overflow.y.is_scroll_container();
            if scrolls {
                chain.push(id);
            }
            current = node.parent;
        }

        // Innermost first: scrolling an outer container moves the inner one, so
        // the inner offsets have to be settled before the outer ones are
        // measured, and each step re-reads the node's position.
        for container in chain {
            let Some(node) = self.nodes.get(node_id) else {
                return;
            };
            let target = node.absolute_position(0.0, 0.0);
            let Some(scroller) = self.nodes.get(container) else {
                continue;
            };
            let box_ = scroller.absolute_position(0.0, 0.0);
            let layout = scroller.final_layout();
            let target_layout = node.final_layout();
            // `scroll_node_by` subtracts its delta from the offset. Semantic
            // automation centres the target to avoid chrome; DOM behavior
            // keeps its historical start alignment.
            let (dx, dy) = if centered {
                (
                    f64::from(
                        box_.x + layout.size.width / 2.0
                            - (target.x + target_layout.size.width / 2.0),
                    ),
                    f64::from(
                        box_.y + layout.size.height / 2.0
                            - (target.y + target_layout.size.height / 2.0),
                    ),
                )
            } else {
                (f64::from(box_.x - target.x), f64::from(box_.y - target.y))
            };
            self.scroll_node_by(container, dx, dy, &mut dispatch_event);
        }

        // `absolute_position` gives the node's position in document space (it does not
        // account for the viewport scroll), so it is the scroll offset we want to land on.
        let Some(node) = self.nodes.get(node_id) else {
            return;
        };
        let target = node.absolute_position(0.0, 0.0);
        let current = self.viewport_scroll;
        let (desired_x, desired_y) = if centered {
            let target_layout = node.final_layout();
            let scale = self.viewport.scale();
            let viewport_width = self.viewport.window_size.0 as f32 / scale;
            let viewport_height = self.viewport.window_size.1 as f32 / scale;
            (
                f64::from(target.x + target_layout.size.width / 2.0 - viewport_width / 2.0)
                    .max(0.0),
                f64::from(target.y + target_layout.size.height / 2.0 - viewport_height / 2.0)
                    .max(0.0),
            )
        } else {
            (f64::from(target.x), f64::from(target.y))
        };

        // `scroll_viewport_by` subtracts the delta from the current scroll
        // offset, so pass current minus the centred destination.
        let dx = current.x - desired_x;
        let dy = current.y - desired_y;
        if let Some(root) = self.try_root_element().map(|element| element.id) {
            self.scroll_node_by(root, dx, dy, dispatch_event);
        } else {
            self.scroll_viewport_by(dx, dy);
        }
    }

    /// Scroll to the element targeted by the given URL fragment (the `#...` part of a URL).
    ///
    /// An empty fragment (or a `top` fragment that matches no element) scrolls to the top
    /// of the document, matching browser behaviour. Returns `true` if a scroll target was
    /// found.
    pub fn scroll_to_fragment(&mut self, fragment: &str) -> bool {
        // Fragments are percent-encoded in URLs (e.g. `%20`); decode before matching.
        let decoded = percent_encoding::percent_decode_str(fragment)
            .decode_utf8_lossy()
            .into_owned();

        if !decoded.is_empty() {
            if let Some(node_id) = self.get_fragment_target(&decoded) {
                self.scroll_to_node(node_id);
                return true;
            }
        }

        // An empty fragment, or the special "top" fragment when no matching element exists,
        // scrolls to the top of the document.
        if decoded.is_empty() || decoded.eq_ignore_ascii_case("top") {
            let current = self.viewport_scroll;
            self.scroll_viewport_by(current.x, current.y);
            return true;
        }

        false
    }

    /// SVG graphics bounds in the element's user coordinate system.
    /// Callers must flush layout before reading, as for client rectangles.
    pub fn get_svg_bbox(&self, node_id: NodeId) -> Option<BoundingRect> {
        #[cfg(feature = "svg")]
        {
            self.svg_user_bbox(node_id)
        }
        #[cfg(not(feature = "svg"))]
        {
            let _ = node_id;
            None
        }
    }

    /// Computes the size and position of the `Node` relative to the viewport
    pub fn get_client_bounding_rect(&self, node_id: NodeId) -> Option<BoundingRect> {
        #[cfg(feature = "svg")]
        if let Some(root) = self.svg_geometry_root(node_id) {
            return self.svg_client_rect(root, node_id);
        }

        // Non-atomic inline elements have no layout box of their own: return
        // the union of their per-line-box fragment rects.
        if let Some(rects) = self.inline_fragment_rects(node_id) {
            let rects: Vec<_> = rects
                .into_iter()
                .map(|rect| self.transformed_client_rect(node_id, rect))
                .collect();
            let x0 = rects.iter().map(|r| r.x).fold(f64::INFINITY, f64::min);
            let y0 = rects.iter().map(|r| r.y).fold(f64::INFINITY, f64::min);
            let x1 = rects
                .iter()
                .map(|r| r.x + r.width)
                .fold(f64::NEG_INFINITY, f64::max);
            let y1 = rects
                .iter()
                .map(|r| r.y + r.height)
                .fold(f64::NEG_INFINITY, f64::max);
            return match rects.is_empty() {
                true => None,
                false => Some(BoundingRect {
                    x: x0,
                    y: y0,
                    width: x1 - x0,
                    height: y1 - y0,
                }),
            };
        }

        let node = self.get_node(node_id)?;
        if !matches!(
            node.data,
            NodeData::Element(_) | NodeData::AnonymousBlock(_) | NodeData::Document(_)
        ) {
            return None;
        }
        let pos = node.absolute_position(0.0, 0.0);

        Some(self.transformed_client_rect(
            node_id,
            BoundingRect {
                x: pos.x as f64 - self.viewport_scroll.x,
                y: pos.y as f64 - self.viewport_scroll.y,
                width: node.unrounded_layout().size.width as f64,
                height: node.unrounded_layout().size.height as f64,
            },
        ))
    }

    /// Map the layout rectangle through the same two-dimensional transforms as paint.
    /// Layout coordinates deliberately exclude transforms; CSSOM client rectangles do not.
    pub(crate) fn transformed_client_rect(
        &self,
        node_id: NodeId,
        rect: BoundingRect,
    ) -> BoundingRect {
        let mut matrix = kurbo::Affine::IDENTITY;
        let mut current = self.get_node(node_id);
        let scale = self.viewport.scale_f64();
        while let Some(node) = current {
            if matches!(
                node.data,
                NodeData::Element(_) | NodeData::AnonymousBlock(_) | NodeData::Document(_)
            ) && let Some(transform) = *node.transform()
            {
                let [a, b, c, d, e, f] = transform.as_coeffs();
                let css_transform = kurbo::Affine::new([a, b, c, d, e / scale, f / scale]);
                let origin = node.absolute_position(0.0, 0.0);
                let translate = kurbo::Affine::translate((
                    origin.x as f64 - self.viewport_scroll.x,
                    origin.y as f64 - self.viewport_scroll.y,
                ));
                matrix = translate * css_transform * translate.inverse() * matrix;
            }
            current = node
                .layout_parent
                .get()
                .or(node.parent)
                .and_then(|id| self.get_node(id));
        }
        let transformed = matrix.transform_rect_bbox(kurbo::Rect::new(
            rect.x,
            rect.y,
            rect.x + rect.width,
            rect.y + rect.height,
        ));
        BoundingRect {
            x: transformed.x0,
            y: transformed.y0,
            width: transformed.width(),
            height: transformed.height(),
        }
    }

    /// Computes the sizes and positions of the `Node`'s box fragments relative to the
    /// viewport (CSSOM `getClientRects()` semantics). Nodes with their own layout box
    /// return a single rect. Non-atomic inline elements (which are laid out as style
    /// spans within an inline root's text layout) return one rect per line box.
    pub fn node_client_rects(&self, node_id: NodeId) -> Vec<BoundingRect> {
        #[cfg(feature = "svg")]
        if self.svg_geometry_root(node_id).is_some() {
            return self.get_client_bounding_rect(node_id).into_iter().collect();
        }
        match self.inline_fragment_rects(node_id) {
            Some(rects) => rects
                .into_iter()
                .map(|rect| self.transformed_client_rect(node_id, rect))
                .collect(),
            None => self.get_client_bounding_rect(node_id).into_iter().collect(),
        }
    }

    /// Computes per-line-box fragment rects for a non-atomic inline element by walking
    /// the containing inline root's text layout. Returns `None` for nodes that have
    /// their own layout box (which should use `get_client_bounding_rect` instead).
    /// Report inline elements whose fragment rects lie outside the inline root
    /// that owns them. `BLITZ_TRACE_INLINE=1`, once per resolve.
    ///
    /// A non-atomic inline element has no layout box of its own: its geometry
    /// is read back out of the containing inline root's text layout on demand.
    /// So "the chip is 900px to the right of its block" is a statement about
    /// that text layout, and the only way to see it is from in here, with both
    /// the fragment and the root in hand. Every earlier attempt to chase this
    /// from outside was reading a number the engine computes on the fly and
    /// could not say where it came from.
    pub(crate) fn trace_escaped_inline_fragments(&self) {
        static TRACE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
        if !*TRACE.get_or_init(|| std::env::var_os("BLITZ_TRACE_INLINE").is_some()) {
            return;
        }
        let mut reported = 0;
        for (id, node) in self.nodes.iter() {
            if !node.is_element() {
                continue;
            }
            let Some(rects) = self.inline_fragment_rects(id) else {
                continue;
            };
            let Some(root) = node.inline_root_ancestor() else {
                continue;
            };
            let root_layout = root.final_layout();
            let root_pos = root.absolute_position(0.0, 0.0);
            let root_right =
                root_pos.x as f64 + root_layout.size.width as f64 - self.viewport_scroll.x;
            for rect in &rects {
                if rect.x + rect.width > root_right + 1.0 {
                    reported += 1;
                    if reported <= 12 {
                        eprintln!(
                            "escaped-fragment node={id:?} rect=[{:.1},{:.1} {:.1}x{:.1}] \
root={:?} root_right={root_right:.1} root_w={:.1} lines={} layout_scale={:.2} vp_scale={:.2} layout_w={:.1}",
                            rect.x,
                            rect.y,
                            rect.width,
                            rect.height,
                            root.id,
                            root_layout.size.width,
                            root.element_data()
                                .and_then(|e| e.inline_layout_data.as_ref())
                                .map(|i| i.layout.len())
                                .unwrap_or(0),
                            root.element_data()
                                .and_then(|e| e.inline_layout_data.as_ref())
                                .map(|i| i.layout.scale())
                                .unwrap_or(0.0),
                            self.viewport.scale(),
                            root.element_data()
                                .and_then(|e| e.inline_layout_data.as_ref())
                                .map(|i| i.layout.width())
                                .unwrap_or(0.0),
                        );
                    }
                    break;
                }
            }
        }
        if reported > 0 {
            eprintln!("escaped-fragment total={reported}");
        }

        // The opposite failure, and the one that reads as "first load is
        // broken": lines broken far narrower than the box they sit in, so a
        // paragraph comes out as a column of one or two words inside a
        // full-width bubble. Nothing escapes, so the check above never sees it.
        let mut narrow = 0;
        for (id, node) in self.nodes.iter() {
            let Some(inline) = node
                .data
                .downcast_element()
                .and_then(|element| element.inline_layout_data.as_ref())
            else {
                continue;
            };
            let box_width = node.final_layout().size.width as f64 * self.viewport.scale() as f64;
            let broken_at = inline.layout.width() as f64;
            // Only interesting when the text had more to give: a short string
            // legitimately measures narrower than its box.
            let full = inline.layout.calculate_content_widths().max as f64;
            if box_width > 40.0 && broken_at < box_width * 0.6 && full > box_width * 0.9 {
                narrow += 1;
                if narrow <= 12 {
                    eprintln!(
                        "narrow-break node={id:?} broken_at={broken_at:.1} box={box_width:.1} \
                         max_content={full:.1} lines={} text={:?}",
                        inline.layout.len(),
                        inline.text.chars().take(40).collect::<String>(),
                    );
                }
            }
        }
        if narrow > 0 {
            eprintln!("narrow-break total={narrow}");
        }
    }

    pub fn inline_fragment_rects(&self, node_id: NodeId) -> Option<Vec<BoundingRect>> {
        use parley::PositionedLayoutItem;

        let node = self.get_node(node_id)?;

        // Text and non-atomic inline elements live in the inline root's glyph
        // runs rather than owning layout boxes.
        let is_text = node.is_text_node();
        if !is_text {
            if !node.is_element() || node.flags.is_inline_root() {
                return None;
            }
            let display = node.primary_styles()?.clone_display();
            if !(display.outside() == DisplayOutside::Inline
                && display.inside() == DisplayInside::Flow)
            {
                return None;
            }
        }

        let inline_root = node.inline_root_ancestor()?;
        let inline_layout = inline_root.element_data()?.inline_layout_data.as_ref()?;
        let layout = &inline_layout.layout;
        let scale = layout.scale() as f64;

        // Walk up the DOM parent chain from `id` to check whether it is (or is
        // inside) the target node, stopping at the inline root.
        let is_in_target = |mut id: NodeId| -> bool {
            loop {
                if id == node_id {
                    return true;
                }
                if id == inline_root.id {
                    return false;
                }
                match self.get_node(id).and_then(|n| n.parent) {
                    Some(parent) => id = parent,
                    None => return false,
                }
            }
        };

        // Fragment rects are relative to the inline root's content box.
        let root_layout = inline_root.final_layout();
        let root_pos = inline_root.absolute_position(0.0, 0.0);
        let origin_x = root_pos.x as f64
            + (root_layout.padding.left + root_layout.border.left) as f64
            - self.viewport_scroll.x;
        let origin_y = root_pos.y as f64
            + (root_layout.padding.top + root_layout.border.top) as f64
            - self.viewport_scroll.y;

        let mut rects: Vec<BoundingRect> = Vec::new();
        for line in layout.lines() {
            let line_metrics = line.metrics();
            // Union all of the target's fragments on this line into a single rect
            let mut line_rect: Option<(f64, f64, f64, f64)> = None;
            let mut add = |x0: f64, y0: f64, x1: f64, y1: f64| {
                line_rect = Some(match line_rect {
                    Some((lx0, ly0, lx1, ly1)) => {
                        (lx0.min(x0), ly0.min(y0), lx1.max(x1), ly1.max(y1))
                    }
                    None => (x0, y0, x1, y1),
                });
            };

            for item in line.items() {
                match item {
                    PositionedLayoutItem::GlyphRun(glyph_run) => {
                        let brush = glyph_run.style().brush;
                        let matches = if is_text {
                            brush.text_node == Some(node_id)
                        } else {
                            is_in_target(brush.id)
                        };
                        if !matches {
                            continue;
                        }
                        let x0 = glyph_run.offset() as f64;
                        let x1 = x0 + glyph_run.advance() as f64;
                        // Use the line box's block extent rather than the
                        // run's font ascent/descent: fonts with small
                        // typographic metrics would otherwise produce rects
                        // that clip the rendered glyphs. This matches the
                        // geometry used for text selection highlights.
                        let y0 = line_metrics.block_min_coord as f64;
                        let y1 = line_metrics.block_max_coord as f64;
                        add(x0, y0, x1, y1);
                    }
                    PositionedLayoutItem::InlineBox(inline_box) => {
                        if is_text || !is_in_target(NodeId::from_u64(inline_box.id)) {
                            continue;
                        }
                        let x0 = inline_box.x as f64;
                        let y0 = inline_box.y as f64;
                        add(
                            x0,
                            y0,
                            x0 + inline_box.width as f64,
                            y0 + inline_box.height as f64,
                        );
                    }
                }
            }

            if let Some((x0, y0, x1, y1)) = line_rect {
                rects.push(BoundingRect {
                    x: origin_x + x0 / scale,
                    y: origin_y + y0 / scale,
                    width: (x1 - x0) / scale,
                    height: (y1 - y0) / scale,
                });
            }
        }

        Some(rects)
    }

    pub fn find_title_node(&self) -> Option<&Node> {
        TreeTraverser::new(self)
            .find(|node_id| {
                let node = &self.nodes[*node_id];
                let Some(element) = node.element_data() else {
                    return false;
                };
                if element.name.ns != ns!(html) || element.name.local != local_name!("title") {
                    return false;
                }
                node.parent
                    .and_then(|parent_id| self.nodes.get(parent_id))
                    .and_then(Node::element_data)
                    .is_some_and(|parent| {
                        parent.name.ns == ns!(html) && parent.name.local == local_name!("head")
                    })
            })
            .map(|node_id| &self.nodes[node_id])
    }

    pub fn with_text_input(
        &mut self,
        node_id: NodeId,
        cb: impl FnOnce(PlainEditorDriver<TextBrush>),
    ) {
        let Some(node) = self.nodes.get_mut(node_id) else {
            return;
        };

        if let Some(text_input) = node
            .element_data_mut()
            .and_then(|el| el.text_input_data_mut())
        {
            let mut font_ctx = self.font_ctx.lock().unwrap();
            let layout_ctx = &mut self.layout_ctx;
            let driver = text_input.editor.driver(&mut font_ctx, layout_ctx);
            cb(driver)
        }
    }

    /// Recompute the scroll offset of the text input at `node_id` (if any) so that its caret
    /// remains visible within the input's content box.
    pub(crate) fn clamp_text_input_scroll(&mut self, node_id: NodeId) {
        let Some(node) = self.nodes.get_mut(node_id) else {
            return;
        };

        let content_box_width = node.final_layout().content_box_width();
        let content_box_height = node.final_layout().content_box_height();

        if let Some(text_input) = node
            .element_data_mut()
            .and_then(|el| el.text_input_data_mut())
        {
            text_input.clamp_scroll_offset(content_box_width, content_box_height);
        }
    }

    pub(crate) fn compute_has_canvas(&self) -> bool {
        TreeTraverser::new(self).any(|node_id| {
            let node = &self.nodes[node_id];
            let Some(element) = node.element_data() else {
                return false;
            };
            if element.name.local == local_name!("canvas") && element.has_attr(local_name!("src")) {
                return true;
            }

            false
        })
    }

    // Text selection methods

    /// Find the text position (inline_root_id, byte_offset) at a given point.
    /// Uses hit() for proper coordinate transformation, then finds the inline root
    /// and byte offset.
    pub fn find_text_position(&self, x: f32, y: f32) -> Option<(NodeId, usize)> {
        let hit = self.hit(x, y)?;
        let hit_node = self.get_node(hit.node_id)?;
        let inline_root = hit_node.inline_root_ancestor()?;
        let byte_offset = inline_root.text_offset_at_point(hit.x, hit.y)?;
        Some((inline_root.id, byte_offset))
    }

    /// Find the word or line at a point, as `(inline_root_id, start, end)`.
    ///
    /// The multi-click counterpart of
    /// [`find_text_position`](Self::find_text_position): that one answers where
    /// a caret goes, this one answers what a double or triple click selects.
    pub fn find_text_range(
        &self,
        x: f32,
        y: f32,
        granularity: TextGranularity,
    ) -> Option<(NodeId, usize, usize)> {
        let hit = self.hit(x, y)?;
        let hit_node = self.get_node(hit.node_id)?;
        let inline_root = hit_node.inline_root_ancestor()?;
        let range = inline_root.text_range_at_point(hit.x, hit.y, granularity)?;
        Some((inline_root.id, range.start, range.end))
    }

    /// Set the text selection range (creates a new selection from anchor to focus)
    pub fn set_text_selection(
        &mut self,
        anchor_node: NodeId,
        anchor_offset: usize,
        focus_node: NodeId,
        focus_offset: usize,
    ) {
        self.dom_selection = None;
        self.text_selection =
            TextSelection::new(anchor_node, anchor_offset, focus_node, focus_offset);

        // For anonymous blocks, switch to storing parent+sibling_index (stable reference)
        if let (Some(parent), Some(idx)) = self.anonymous_block_location(anchor_node) {
            self.text_selection
                .anchor
                .set_anonymous(parent, idx, anchor_offset);
        }
        if let (Some(parent), Some(idx)) = self.anonymous_block_location(focus_node) {
            self.text_selection
                .focus
                .set_anonymous(parent, idx, focus_offset);
        }
    }

    /// Get the parent ID and sibling index for a node if it's an anonymous block.
    /// Returns (None, None) for non-anonymous blocks.
    fn anonymous_block_location(&self, node_id: NodeId) -> (Option<NodeId>, Option<usize>) {
        let Some(node) = self.get_node(node_id) else {
            return (None, None);
        };

        if !node.is_anonymous() {
            return (None, None);
        }

        let Some(parent_id) = node.parent else {
            return (None, None);
        };

        let Some(parent) = self.get_node(parent_id) else {
            return (Some(parent_id), None);
        };

        let layout_children = parent.layout_children.borrow();
        let Some(children) = layout_children.as_ref() else {
            return (Some(parent_id), None);
        };

        // Find the index of this anonymous block among siblings
        let mut anon_index = 0;
        for &child_id in children.iter() {
            if child_id == node_id {
                return (Some(parent_id), Some(anon_index));
            }
            if self.get_node(child_id).is_some_and(|n| n.is_anonymous()) {
                anon_index += 1;
            }
        }

        (Some(parent_id), None)
    }

    /// Clear the text selection
    pub fn clear_text_selection(&mut self) {
        self.dom_selection = None;
        self.text_selection.clear();
    }

    /// Update the selection focus point (used during mouse drag to extend selection).
    pub fn update_selection_focus(&mut self, focus_node: NodeId, focus_offset: usize) {
        self.dom_selection = None;
        // For anonymous blocks, store parent+sibling_index; otherwise store node directly
        if let (Some(parent), Some(idx)) = self.anonymous_block_location(focus_node) {
            self.text_selection
                .focus
                .set_anonymous(parent, idx, focus_offset);
        } else {
            self.text_selection.set_focus(focus_node, focus_offset);
        }
    }

    /// Extend text selection to the given point. Returns true if selection was updated.
    /// This is a convenience method that combines find_text_position and update_selection_focus.
    pub fn extend_text_selection_to_point(&mut self, x: f32, y: f32) -> bool {
        if !self.text_selection.anchor.is_some() {
            return false;
        }

        if let Some((node, offset)) = self.find_text_position(x, y) {
            self.update_selection_focus(node, offset);
            self.shell_provider.request_redraw();
            true
        } else {
            false
        }
    }

    /// Find the Nth anonymous block under a parent.
    fn find_anonymous_block_by_index(
        &self,
        parent_id: NodeId,
        target_index: usize,
    ) -> Option<NodeId> {
        let parent = self.get_node(parent_id)?;
        let layout_children = parent.layout_children.borrow();
        let children = layout_children.as_ref()?;

        children
            .iter()
            .filter(|&&child_id| self.get_node(child_id).is_some_and(|n| n.is_anonymous()))
            .nth(target_index)
            .copied()
    }

    /// Check if there is an active (non-empty) text selection
    pub fn has_text_selection(&self) -> bool {
        self.dom_selection.as_ref().map_or_else(
            || self.text_selection.is_active(),
            |range| !range.bounds().collapsed(),
        )
    }

    /// Get the selected text content, supporting selection across multiple inline roots.
    pub fn get_selected_text(&self) -> Option<String> {
        if let Some(range) = &self.dom_selection {
            let text = self.range_string(range.bounds());
            return (!text.is_empty()).then_some(text);
        }
        let ranges = self.get_text_selection_ranges();
        if ranges.is_empty() {
            return None;
        }

        let mut result = String::new();
        for (node_id, start, end) in &ranges {
            let node = self.get_node(*node_id)?;
            let element_data = node.element_data()?;
            let inline_layout = element_data.inline_layout_data.as_ref()?;

            if *end > inline_layout.text.len() {
                continue;
            }

            if !result.is_empty() {
                result.push(' ');
            }
            result.push_str(&inline_layout.text[*start..*end]);
        }

        if result.is_empty() {
            None
        } else {
            Some(result)
        }
    }

    /// The selection as HTML, for a clipboard that can carry formatting.
    ///
    /// The same ranges [`Self::get_selected_text`] walks, with each one wrapped
    /// in the tag of the element it came from, so bold stays bold and a code
    /// span stays a code span when it lands in another application. Pasting
    /// formatted text out of a Blitz window was impossible before this: plain
    /// text was the only payload ever written.
    ///
    /// Only the element's own tag is reproduced, not its ancestors or its
    /// styles. That is deliberate: a paste should carry the structure the author
    /// wrote, not this window's theme, and dragging a `class` into another
    /// application's document would reference styles that do not exist there.
    pub fn get_selected_html(&self) -> Option<String> {
        let ranges = self.get_text_selection_ranges();
        if ranges.is_empty() {
            return None;
        }

        let mut result = String::new();
        for (node_id, start, end) in &ranges {
            let Some(node) = self.get_node(*node_id) else {
                continue;
            };
            let Some(element_data) = node.element_data() else {
                continue;
            };
            let Some(inline_layout) = element_data.inline_layout_data.as_ref() else {
                continue;
            };
            if *end > inline_layout.text.len() {
                continue;
            }

            if !result.is_empty() {
                result.push(' ');
            }

            let tag = element_data.name.local.as_ref();
            let fragment = escape_html(&inline_layout.text[*start..*end]);
            // A block tag around a fragment of a paragraph would be wrong: the
            // range is a run of text, and the element it belongs to may be only
            // partly selected. Inline tags carry meaning a paste should keep;
            // anything else contributes its text and nothing more.
            if matches!(
                tag,
                "b" | "strong" | "i" | "em" | "code" | "kbd" | "mark" | "s" | "u" | "sub" | "sup"
            ) {
                result.push_str(&format!("<{tag}>{fragment}</{tag}>"));
            } else {
                result.push_str(&fragment);
            }
        }

        if result.is_empty() {
            None
        } else {
            Some(result)
        }
    }

    /// Get all selection ranges as Vec<(node_id, start_offset, end_offset)>.
    /// Returns empty vec if no selection.
    pub fn get_text_selection_ranges(&self) -> Vec<(NodeId, usize, usize)> {
        if let Some(range) = &self.dom_selection {
            return self.range_layout_ranges(range.bounds());
        }
        let lookup = |parent_id, idx| self.find_anonymous_block_by_index(parent_id, idx);

        let anchor_node = match self.text_selection.anchor.resolve_node_id(lookup) {
            Some(id) => id,
            None => return Vec::new(),
        };
        let focus_node = match self.text_selection.focus.resolve_node_id(lookup) {
            Some(id) => id,
            None => return Vec::new(),
        };

        // Guard against stale selection endpoints: nodes may have been removed from
        // the document (e.g. by script) since the selection was made.
        let node_is_in_doc = |node_id: NodeId| {
            self.nodes
                .get(node_id)
                .is_some_and(|node| node.flags.is_in_document())
        };
        if !node_is_in_doc(anchor_node) || !node_is_in_doc(focus_node) {
            return Vec::new();
        }

        // Single node selection
        if anchor_node == focus_node {
            let start = self
                .text_selection
                .anchor
                .offset
                .min(self.text_selection.focus.offset);
            let end = self
                .text_selection
                .anchor
                .offset
                .max(self.text_selection.focus.offset);

            if start == end {
                return Vec::new();
            }
            return vec![(anchor_node, start, end)];
        }

        // Multi-node selection: collect all inline roots between anchor and focus
        let inline_roots = self.collect_inline_roots_in_range(anchor_node, focus_node);
        if inline_roots.is_empty() {
            return Vec::new();
        }

        // Determine document order using the collected inline_roots order
        // (inline_roots is already in document order from first to last)
        let first_in_roots = inline_roots[0];

        let (first_node, first_offset, last_node, last_offset) =
            if first_in_roots == anchor_node || (first_in_roots != focus_node) {
                // anchor is first (or neither endpoint is in roots, which shouldn't happen)
                (
                    anchor_node,
                    self.text_selection.anchor.offset,
                    focus_node,
                    self.text_selection.focus.offset,
                )
            } else {
                // focus is first
                (
                    focus_node,
                    self.text_selection.focus.offset,
                    anchor_node,
                    self.text_selection.anchor.offset,
                )
            };

        let mut ranges = Vec::with_capacity(inline_roots.len());

        for &node_id in &inline_roots {
            let Some(node) = self.get_node(node_id) else {
                continue;
            };
            let Some(element_data) = node.element_data() else {
                continue;
            };
            let Some(inline_layout) = element_data.inline_layout_data.as_ref() else {
                continue;
            };

            let text_len = inline_layout.text.len();

            if node_id == first_node && node_id == last_node {
                let start = first_offset.min(last_offset);
                let end = first_offset.max(last_offset);
                if start < end && end <= text_len {
                    ranges.push((node_id, start, end));
                }
            } else if node_id == first_node {
                if first_offset < text_len {
                    ranges.push((node_id, first_offset, text_len));
                }
            } else if node_id == last_node {
                if last_offset > 0 && last_offset <= text_len {
                    ranges.push((node_id, 0, last_offset));
                }
            } else if text_len > 0 {
                ranges.push((node_id, 0, text_len));
            }
        }

        ranges
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BoundingRect {
    pub x: f64,
    pub y: f64,
    pub width: f64,
    pub height: f64,
}

/// The record of changes a script's `MutationObserver` reads. See
/// [`crate::DomMutation`] for what is recorded and why.
impl BaseDocument {
    /// Note a `<details open>` presence change for the toggle event. `present` is whether the
    /// attribute exists after this write.
    pub(crate) fn record_details_open(
        &mut self,
        node_id: NodeId,
        name: &markup5ever::QualName,
        present: bool,
    ) {
        if name.local != local_name!("open") || !name.ns.is_empty() {
            return;
        }
        let Some(element) = self.nodes[node_id].element_data() else {
            return;
        };
        if element.name.local != local_name!("details") || element.name.ns != ns!(html) {
            return;
        }
        let was_open = element.attr(local_name!("open")).is_some();
        if was_open != present && !self.details_toggles.iter().any(|(id, _)| *id == node_id) {
            self.details_toggles.push((node_id, was_open));
        }
    }

    /// The inert document template contents belong to.
    pub(crate) fn template_contents_owner(&mut self) -> NodeId {
        if let Some(owner) = self.template_contents_owner {
            return owner;
        }
        let mut data = crate::node::DocumentData::default();
        data.content_type = "text/html";
        let owner = self.create_node(NodeData::Document(Box::new(data)));
        self.template_contents_owner = Some(owner);
        owner
    }

    /// Changes whenever the device media queries are evaluated against changes.
    pub fn viewport_generation(&self) -> u64 {
        self.viewport_generation
    }

    /// The `<details>` toggles recorded since the last call, each with its old open state.
    pub fn take_details_toggles(&mut self) -> Vec<(NodeId, bool)> {
        std::mem::take(&mut self.details_toggles)
    }

    /// Update the raw content handler state at the attribute mutation boundary.
    /// Equal-value writes still replace a compiled or script-assigned handler.
    pub(crate) fn record_inline_handler_attribute(
        &mut self,
        node_id: NodeId,
        name: &crate::QualName,
        value: Option<&str>,
    ) {
        if name.ns != markup5ever::ns!() || !name.local.as_ref().starts_with("on") {
            return;
        }
        let Some(element) = self
            .nodes
            .get_mut(node_id)
            .and_then(|node| node.element_data_mut())
        else {
            return;
        };
        let value = value.map(crate::node::AttrAtom::from);
        if let Some(value) = &value {
            let attributes = element
                .inline_event_attributes
                .get_or_insert_with(|| Box::new(Vec::new()));
            if let Some(attribute) = attributes
                .iter_mut()
                .find(|attribute| attribute.name.local == name.local)
            {
                attribute.name = name.clone();
                attribute.value = value.clone();
            } else {
                attributes.push(crate::node::Attribute {
                    name: name.clone(),
                    value: value.clone(),
                });
            }
        } else {
            let Some(attributes) = element.inline_event_attributes.as_mut() else {
                return;
            };
            let Some(index) = attributes
                .iter()
                .position(|attribute| attribute.name.local == name.local)
            else {
                return;
            };
            attributes.remove(index);
            if attributes.is_empty() {
                element.inline_event_attributes = None;
            }
        }
        self.inline_handler_changes
            .push((node_id, name.clone(), value));
    }

    /// Take content handler changes in mutation order.
    pub fn take_inline_handler_changes(
        &mut self,
    ) -> Vec<(NodeId, crate::QualName, Option<crate::node::AttrAtom>)> {
        std::mem::take(&mut self.inline_handler_changes)
    }

    /// Start or stop recording changes. Stopping discards what was recorded
    /// and not yet taken.
    pub fn set_recording_mutations(&mut self, recording: bool) {
        match (recording, self.mutation_log.is_some()) {
            (true, false) => self.mutation_log = Some(Vec::new()),
            (false, true) => self.mutation_log = None,
            _ => {}
        }
    }

    /// Whether changes are being recorded.
    pub fn is_recording_mutations(&self) -> bool {
        self.mutation_log.is_some()
    }

    /// Take every change recorded since the last call, oldest first.
    pub fn take_mutations(&mut self) -> Vec<crate::DomMutation> {
        self.mutation_log
            .as_mut()
            .map(std::mem::take)
            .unwrap_or_default()
    }

    pub(crate) fn record_mutation(&mut self, mutation: crate::DomMutation) {
        if let Some(log) = self.mutation_log.as_mut() {
            if log.len() < crate::mutation_record::MUTATION_LOG_CAP {
                log.push(mutation);
            }
        }
    }

    /// Where `node_id` sits among its siblings: its parent and the siblings on
    /// either side, as a child-list record reports them.
    pub(crate) fn sibling_context(
        &self,
        node_id: NodeId,
    ) -> Option<(NodeId, Option<NodeId>, Option<NodeId>)> {
        let parent_id = self.nodes.get(node_id)?.parent?;
        let siblings = &self.nodes.get(parent_id)?.children;
        let index = siblings.iter().position(|id| *id == node_id)?;
        let previous = index.checked_sub(1).map(|i| siblings[i]);
        let next = siblings.get(index + 1).copied();
        Some((parent_id, previous, next))
    }
}

impl AsRef<BaseDocument> for BaseDocument {
    fn as_ref(&self) -> &BaseDocument {
        self
    }
}

impl AsMut<BaseDocument> for BaseDocument {
    fn as_mut(&mut self) -> &mut BaseDocument {
        self
    }
}

#[cfg(test)]
mod hover_state_tests {
    use super::*;
    use crate::{Attribute, qual_name};
    use blitz_traits::shell::ColorScheme;

    /// Build `<html><body style="margin:0"><div style="width:300px">some text
    /// <div style="height:50px"></div></div></body></html>` manually (the HTML
    /// parser lives in blitz-html, which would be a circular dev-dependency).
    /// The bare text next to a block sibling gets wrapped in an anonymous
    /// block, which becomes the inline root: text hits report the anonymous
    /// block as the hit node.
    fn make_doc() -> (BaseDocument, NodeId) {
        let mut doc = BaseDocument::new(DocumentConfig {
            viewport: Some(Viewport::new(400, 300, 1.0, ColorScheme::Light)),
            ..Default::default()
        });
        let root_id = doc.root_node().id;
        let style = |value: &str| Attribute {
            name: qual_name!("style"),
            value: value.into(),
        };

        let mut mutator = doc.mutate();
        let html = mutator.create_element(qual_name!("html"), vec![]);
        let body = mutator.create_element(qual_name!("body"), vec![style("margin:0")]);
        let container = mutator.create_element(qual_name!("div"), vec![style("width:300px")]);
        let text = mutator.create_text_node("some text");
        let block = mutator.create_element(qual_name!("div"), vec![style("height:50px")]);
        mutator.append_children(container, &[text, block]);
        mutator.append_children(body, &[container]);
        mutator.append_children(html, &[body]);
        mutator.append_children(root_id, &[html]);
        drop(mutator);

        doc.resolve(0.0);
        (doc, container)
    }

    /// Whether text laid out with a real (non-zero-metric) font. Without the
    /// `system-fonts` feature text measures 0x0 and text hits are impossible,
    /// making these tests vacuous.
    fn text_has_size(doc: &BaseDocument, container: NodeId) -> bool {
        doc.nodes[container].final_layout().size.height > 50.0
    }

    /// Regression test: hovering bare text wrapped in an anonymous block must
    /// report a text cursor. The hit node for such text is the anonymous
    /// inline root itself, while the *stored* hover target is canonicalized to
    /// the containing element — the cursor must be derived from the precise
    /// hit node, not the canonical target.
    #[test]
    fn hovering_text_in_anonymous_block_reports_text_cursor() {
        let (mut doc, container) = make_doc();
        if !text_has_size(&doc, container) {
            eprintln!("skipping: no usable font (text measures 0x0)");
            return;
        }

        doc.set_hover_to(5.0, 8.0);
        assert!(doc.hover_node_is_text, "expected a text hit");
        let hit_id = doc.hover_hit_node_id.expect("expected a hit node");
        assert!(
            doc.nodes[hit_id].is_anonymous(),
            "expected the hit node to be the anonymous inline root"
        );
        assert_eq!(
            doc.get_hover_node_id(),
            Some(container),
            "expected the stored hover target to be the containing element"
        );
        assert_eq!(doc.get_cursor(), Some(CursorIcon::Text));
    }

    #[test]
    fn semantic_hover_keeps_the_resolved_node_instead_of_hit_testing_again() {
        let (mut doc, container) = make_doc();

        // This coordinate is outside the 300px-wide container. A coordinate
        // hit test therefore cannot select it, but semantic automation has
        // already selected the container by id and must preserve that target.
        doc.set_hover_to_node(container, 350.0, 250.0);

        assert_eq!(doc.get_hover_node_id(), Some(container));
        assert_eq!(doc.hover_hit_node_id, Some(container));

        doc.resolve(0.0);
        assert_eq!(
            doc.get_hover_node_id(),
            Some(container),
            "a resolve must not turn semantic identity back into a coordinate hit"
        );
    }

    /// Hovering the empty region of the anonymous block (right of the text) is
    /// not a text hit: default cursor, same canonical hover target.
    #[test]
    fn hovering_anonymous_block_whitespace_reports_default_cursor() {
        let (mut doc, container) = make_doc();
        if !text_has_size(&doc, container) {
            eprintln!("skipping: no usable font (text measures 0x0)");
            return;
        }

        doc.set_hover_to(250.0, 8.0);
        assert!(!doc.hover_node_is_text);
        assert_eq!(doc.get_hover_node_id(), Some(container));
        assert_eq!(doc.get_cursor(), Some(CursorIcon::Default));
    }
}

#[cfg(test)]
mod control_scroll_tests {
    use super::*;
    use crate::{Attribute, qual_name};
    use blitz_traits::shell::ColorScheme;

    #[test]
    fn controlled_scroll_dispatches_the_dom_scroll_event() {
        let mut doc = BaseDocument::new(DocumentConfig {
            viewport: Some(Viewport::new(400, 300, 1.0, ColorScheme::Light)),
            ..Default::default()
        });
        let root_id = doc.root_node().id;
        let style = |value: &str| Attribute {
            name: qual_name!("style"),
            value: value.into(),
        };

        let mut mutator = doc.mutate();
        let html = mutator.create_element(qual_name!("html"), vec![]);
        let body = mutator.create_element(qual_name!("body"), vec![style("margin:0")]);
        let scroller = mutator.create_element(
            qual_name!("div"),
            vec![style("width:200px;height:100px;overflow-y:scroll")],
        );
        let spacer = mutator.create_element(qual_name!("div"), vec![style("height:400px")]);
        let target = mutator.create_element(qual_name!("button"), vec![style("height:40px")]);
        let target_text = mutator.create_text_node("Reveal me");
        mutator.append_children(target, &[target_text]);
        mutator.append_children(scroller, &[spacer, target]);
        mutator.append_children(body, &[scroller]);
        mutator.append_children(html, &[body]);
        mutator.append_children(root_id, &[html]);
        drop(mutator);
        doc.resolve(0.0);

        // The manual mutator deliberately bypasses the HTML/style parser used
        // by loaded documents. Give the fixture explicit post-layout geometry
        // so this unit test isolates event forwarding rather than CSS parsing.
        doc.nodes[html].final_layout_mut().size.height = 300.0;
        doc.nodes[html].final_layout_mut().content_size.height = 600.0;
        doc.nodes[target].final_layout_mut().location.y = 400.0;

        let mut events = Vec::new();
        // A semantic client may target the exposed text rather than its
        // element. Text has no `final_layout`, so this also pins the host-crash
        // regression from revealing a named label.
        doc.scroll_to_node_centered_with_events(target_text, |event| events.push(event));

        assert!(
            (doc.viewport_scroll.y - 270.0).abs() < 0.1,
            "the 40px target should be centred in the 300px viewport"
        );
        assert!(
            events
                .iter()
                .any(|event| { event.target == html && event.name() == "scroll" })
        );
    }
}

#[cfg(test)]
mod font_face_override_tests {
    use super::*;
    use crate::net::{FontFaceOverrides, Resource, ResourceLoadResponse};

    /// Regression-pin for the `@font-face` descriptor-honouring fix.
    ///
    /// The bug was that `Resource::Font` carried only the raw font bytes,
    /// so `load_resource` registered fonts with `info_override = None` and
    /// parley fell back to the TTF's internal `name` table. After the fix,
    /// `Resource::Font` carries `FontFaceOverrides` and `load_resource`
    /// builds a `FontInfoOverride` from them — meaning a CSS-declared
    /// `font-family` alias wins over the file's own metadata.
    ///
    /// We drive `load_resource` directly with a fabricated response rather
    /// than go through HTML parsing → `fetch_font_face`, because the
    /// downstream HTML parser lives in `blitz-html` (would be a circular
    /// crate dependency). The mapping from `@font-face` descriptors into
    /// `FontFaceOverrides` is covered by the unit tests in `net.rs`; this
    /// test pins the load-side of the pipeline.
    #[test]
    fn font_face_overrides_alias_family_name() {
        const ALIAS: &str = "AliasedFamily";

        let mut document = BaseDocument::new(DocumentConfig::default());

        // Sanity: the alias name is not registered before we feed the font.
        {
            let mut ctx = document.font_ctx.lock().unwrap();
            assert!(
                ctx.collection.family_id(ALIAS).is_none(),
                "alias must not exist before registration",
            );
        }

        // Drive `load_resource` with a `Resource::Font` whose overrides
        // assert the CSS-side family name. We use the bullet font as a
        // valid font payload — its internal `name` table is irrelevant to
        // the assertion; what matters is whether the override wins.
        let response = ResourceLoadResponse {
            request_id: 0,
            node_id: None,
            resolved_url: Some(String::from("test://aliased-family")),
            result: Ok(Resource::Font(
                blitz_traits::net::Bytes::from_static(crate::BULLET_FONT),
                FontFaceOverrides {
                    family_name: Some(String::from(ALIAS)),
                    weight: Some(800.0),
                    style: Some(parley::fontique::FontStyle::Italic),
                },
            )),
        };
        document.load_resource(response);

        // The override must have taken effect: parley's `Collection` now
        // resolves the CSS-declared alias to a registered family.
        let mut ctx = document.font_ctx.lock().unwrap();
        let family_id = ctx
            .collection
            .family_id(ALIAS)
            .expect("CSS-declared family name should be registered as a family alias");
        let resolved_name = ctx
            .collection
            .family_name(family_id)
            .expect("family id should resolve back to a name");
        assert_eq!(
            resolved_name, ALIAS,
            "registered family should report the CSS-declared name, \
             not the font file's internal `name` table entry",
        );
    }
}

#[cfg(test)]
mod clipboard_html_tests {
    use super::escape_html;

    /// A selection is document text, so markup characters in it are content.
    /// Unescaped, `a < b` opens a tag in whatever receives the paste.
    #[test]
    fn markup_characters_in_a_selection_are_escaped() {
        assert_eq!(
            escape_html("a < b && c > d"),
            "a &lt; b &amp;&amp; c &gt; d"
        );
    }

    /// The ampersand has to go first, or escaping the others re-escapes the
    /// entities just written and `<` arrives as `&amp;lt;`.
    #[test]
    fn an_ampersand_is_not_double_escaped() {
        assert_eq!(escape_html("&lt;"), "&amp;lt;");
    }

    /// Ordinary prose is left exactly as it is, including the apostrophes and
    /// quotes that a paste should carry through unchanged.
    #[test]
    fn prose_is_untouched() {
        assert_eq!(escape_html("it's \"fine\""), "it's &quot;fine&quot;");
    }
}