ps-blitz-script 0.3.0-beta.4

JavaScript execution for Blitz using the Boa engine
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
//! Tests for the JavaScript DOM APIs exposed by blitz-script

use blitz_dom::{Document, DocumentConfig};
use blitz_script::ScriptDocument;

#[derive(Clone)]
struct PollProbe {
    inner: std::rc::Rc<std::cell::RefCell<blitz_dom::BaseDocument>>,
    polls: std::rc::Rc<std::cell::Cell<usize>>,
}

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

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

    fn poll(&mut self, _cx: Option<std::task::Context<'_>>) -> bool {
        self.polls.set(self.polls.get() + 1);
        true
    }
}

#[test]
fn script_document_polls_mounted_subdocuments() {
    use blitz_dom::Document as _;

    let mut outer = ScriptDocument::from_html(
        r#"<web-view id="page"></web-view>"#,
        blitz_dom::DocumentConfig::default(),
    );
    outer.execute_scripts();
    let page = outer
        .inner()
        .get_element_by_id("page")
        .expect("fixture page host");
    let polls = std::rc::Rc::new(std::cell::Cell::new(0));
    let probe = PollProbe {
        inner: std::rc::Rc::new(std::cell::RefCell::new(blitz_dom::BaseDocument::new(
            blitz_dom::DocumentConfig::default(),
        ))),
        polls: std::rc::Rc::clone(&polls),
    };
    outer.inner_mut().set_sub_document(page, Box::new(probe));

    assert!(outer.poll(None));
    assert_eq!(
        polls.get(),
        1,
        "the Solid chrome must drive its page document"
    );
}
use blitz_traits::events::{DomEvent, DomEventData};
use blitz_traits::shell::{ColorScheme, Viewport};
use keyboard_types::Modifiers;
use std::sync::{Arc, Mutex};

fn doc_from_html(html: &str) -> ScriptDocument {
    let mut doc = ScriptDocument::from_html(html, DocumentConfig::default());
    doc.execute_scripts();
    doc
}

fn text_of_selector(doc: &ScriptDocument, selector: &str) -> String {
    let inner = doc.inner();
    let node_id = inner
        .query_selector(selector)
        .unwrap()
        .unwrap_or_else(|| panic!("no node matching {selector}"));
    inner.get_node(node_id).unwrap().text_content()
}

#[test]
fn pointer_capture_methods_retarget_pointer_events() {
    let mut doc = doc_from_html(
        r#"
        <html><body>
            <button id="capture">capture</button><div id="other"></div><div id="out"></div>
            <script>
                const capture = document.getElementById("capture");
                const out = document.getElementById("out");
                capture.addEventListener("pointerdown", (event) => {
                    capture.setPointerCapture(event.pointerId);
                    out.textContent = `down:${event.pointerId}:${capture.hasPointerCapture(event.pointerId)}`;
                });
                capture.addEventListener("pointermove", (event) => {
                    out.textContent += `|move:${event.pointerId}`;
                    capture.releasePointerCapture(event.pointerId);
                });
            </script>
        </body></html>
        "#,
    );

    let (capture_id, other_id, pointer) = {
        let inner = doc.inner();
        let capture_id = inner.query_selector("#capture").unwrap().unwrap();
        let other_id = inner.query_selector("#other").unwrap().unwrap();
        let pointer = match inner
            .get_node(capture_id)
            .unwrap()
            .synthetic_click_event(Modifiers::empty())
        {
            DomEventData::Click(pointer) => pointer,
            _ => unreachable!(),
        };
        (capture_id, other_id, pointer)
    };

    doc.dispatch_dom_event(DomEvent::new(
        capture_id,
        DomEventData::PointerDown(pointer.clone()),
    ));
    doc.dispatch_dom_event(DomEvent::new(other_id, DomEventData::PointerMove(pointer)));

    assert_eq!(text_of_selector(&doc, "#out"), "down:1:true|move:1");
}

#[test]
fn matches_and_closest_follow_the_element_ancestor_chain() {
    let doc = doc_from_html(
        r#"
        <div id="root" data-drag><button><span id="target">target</span></button></div>
        <div id="out"></div>
        <script>
            const target = document.getElementById("target");
            const closest = target.closest("[data-drag]");
            document.getElementById("out").textContent = [
                target.matches("span"),
                target.matches("button"),
                closest && closest.id,
                target.closest("[data-missing]") === null,
            ].join("|");
        </script>
        "#,
    );
    assert_eq!(text_of_selector(&doc, "#out"), "true|false|root|true");
}

#[test]
fn executes_inline_scripts() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <div id="root"></div>
            <script>
                const el = document.createElement("h1");
                el.textContent = "Hello from JS";
                document.getElementById("root").appendChild(el);
            </script>
        </body></html>
        "#,
    );
    assert_eq!(text_of_selector(&doc, "#root > h1"), "Hello from JS");
}

#[test]
fn scripts_run_in_document_order_and_share_globals() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <div id="root"></div>
            <script>globalThis.counter = 1;</script>
            <script>globalThis.counter += 1;</script>
            <script>
                document.getElementById("root").textContent = `counter = ${counter}`;
            </script>
        </body></html>
        "#,
    );
    assert_eq!(text_of_selector(&doc, "#root"), "counter = 2");
}

#[test]
fn history_tracks_state_and_same_origin_urls() {
    let mut doc = ScriptDocument::from_html(
        r#"
        <html><body>
            <div id="out"></div>
            <script>
                const initialState = history.state;
                history.replaceState({ ...history.state, depth: 0 }, "");
                history.pushState({ page: 1 }, "", "/components?group=forms#input");
                const pushed = [history.length, history.state.page, location.pathname, location.search, location.hash];
                history.back();
                const restored = [history.state.depth, location.pathname, location.search, location.hash];
                document.getElementById("out").textContent = [initialState === null, ...pushed, ...restored].join("|");
            </script>
        </body></html>
        "#,
        DocumentConfig {
            base_url: Some("tauri://localhost/".into()),
            ..DocumentConfig::default()
        },
    );
    doc.execute_scripts();
    assert_eq!(
        text_of_selector(&doc, "#out"),
        "true|2|1|/components|?group=forms|#input|0|/||"
    );
}

#[test]
fn window_dimensions_follow_the_current_viewport() {
    let mut doc = ScriptDocument::from_html(
        r#"<div id="out"></div><script>
            document.getElementById("out").textContent =
                [innerWidth, innerHeight, outerWidth, outerHeight, devicePixelRatio].join("|");
        </script>"#,
        DocumentConfig {
            viewport: Some(Viewport::new(800, 600, 2.0, ColorScheme::Light)),
            ..DocumentConfig::default()
        },
    );
    doc.execute_scripts();
    assert_eq!(text_of_selector(&doc, "#out"), "400|300|400|300|2");

    doc.inner_mut()
        .set_viewport(Viewport::new(1000, 700, 2.0, ColorScheme::Light));
    doc.eval(
        r#"document.getElementById("out").textContent =
            [innerWidth, innerHeight, outerWidth, outerHeight, devicePixelRatio].join("|");"#,
    );
    assert_eq!(text_of_selector(&doc, "#out"), "500|350|500|350|2");
}

#[test]
fn element_scroll_metrics_and_offsets_follow_layout() {
    let mut doc = ScriptDocument::from_html(
        r#"
        <div id="strip" style="width: 100px; height: 50px; overflow: auto">
            <div style="width: 300px; height: 150px"></div>
        </div>
        "#,
        DocumentConfig {
            viewport: Some(Viewport::new(400, 200, 1.0, ColorScheme::Light)),
            ..DocumentConfig::default()
        },
    );
    doc.execute_scripts();
    doc.inner_mut().resolve(0.0);

    let metrics = doc
        .eval_json(
            r#"
            const strip = document.getElementById("strip");
            const child = strip.children[0];
            strip.scrollLeft = 80;
            strip.scrollTop = 30;
            ({
                clientWidth: strip.clientWidth,
                clientHeight: strip.clientHeight,
                scrollWidth: strip.scrollWidth,
                scrollHeight: strip.scrollHeight,
                scrollLeft: strip.scrollLeft,
                scrollTop: strip.scrollTop,
                stripLeft: strip.getBoundingClientRect().left,
                stripTop: strip.getBoundingClientRect().top,
                childLeft: child.getBoundingClientRect().left,
                childTop: child.getBoundingClientRect().top,
            })
            "#,
        )
        .expect("scroll metrics should evaluate");

    assert_eq!(
        metrics,
        serde_json::json!({
            "clientWidth": 100.0,
            "clientHeight": 50.0,
            "scrollWidth": 300.0,
            "scrollHeight": 150.0,
            "scrollLeft": 80.0,
            "scrollTop": 30.0,
            "stripLeft": 8.0,
            "stripTop": 8.0,
            "childLeft": -72.0,
            "childTop": -22.0,
        })
    );
}

#[test]
fn window_ipc_forwards_messages_to_the_embedder() {
    let received = Arc::new(Mutex::new(Vec::new()));
    let received_by_handler = Arc::clone(&received);
    let mut doc = ScriptDocument::from_html(
        r#"<script>window.ipc.postMessage(JSON.stringify({ cmd: "greet", value: 42 }));</script>"#,
        DocumentConfig::default(),
    );
    doc.set_ipc_handler(move |body| received_by_handler.lock().unwrap().push(body));
    doc.execute_scripts();

    assert_eq!(
        received.lock().unwrap().as_slice(),
        [r#"{"cmd":"greet","value":42}"#]
    );
}

#[test]
fn dom_tree_manipulation() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <ul id="list"><li id="a">a</li><li id="c">c</li></ul>
            <script>
                const list = document.getElementById("list");
                const b = document.createElement("li");
                b.textContent = "b";
                list.insertBefore(b, document.getElementById("c"));

                // Move "a" to the end, then remove it
                const a = document.getElementById("a");
                list.appendChild(a);
                list.removeChild(a);

                const summary = document.createElement("div");
                summary.id = "summary";
                summary.textContent = [...list.childNodes].map((li) => li.textContent).join(",");
                document.body.appendChild(summary);
            </script>
        </body></html>
        "#,
    );
    assert_eq!(text_of_selector(&doc, "#summary"), "b,c");
    assert_eq!(text_of_selector(&doc, "#list"), "bc");
}

#[test]
fn attributes_and_properties() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <div id="box" class="before" data-x="1"></div>
            <script>
                const box = document.getElementById("box");
                const results = [];
                results.push(box.getAttribute("class"));
                box.className = "after";
                results.push(box.getAttribute("class"));
                results.push(box.hasAttribute("data-x"));
                box.removeAttribute("data-x");
                results.push(box.hasAttribute("data-x"));
                box.setAttribute("title", "hello");
                results.push(box.getAttribute("title"));

                const out = document.createElement("div");
                out.id = "out";
                out.textContent = results.join("|");
                document.body.appendChild(out);
            </script>
        </body></html>
        "#,
    );
    assert_eq!(
        text_of_selector(&doc, "#out"),
        "before|after|true|false|hello"
    );
}

#[test]
fn dataset_reflects_data_attributes() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <div id="box" data-user-id="42"></div>
            <script>
                const box = document.getElementById("box");
                const sameObject = box.dataset === box.dataset;
                const initial = box.dataset.userId;
                box.dataset.colorMode = "dark";
                const reflected = box.getAttribute("data-color-mode");
                const present = "colorMode" in box.dataset;
                const keys = Object.keys(box.dataset).sort().join(",");
                delete box.dataset.userId;
                const removed = !box.hasAttribute("data-user-id");
                const out = document.createElement("div");
                out.id = "dataset-out";
                out.textContent = [sameObject, initial, reflected, present, keys, removed].join("|");
                document.body.appendChild(out);
            </script>
        </body></html>
        "#,
    );
    assert_eq!(
        text_of_selector(&doc, "#dataset-out"),
        "true|42|dark|true|colorMode,userId|true"
    );
}

#[test]
fn class_list_reflects_the_class_attribute() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <div id="box" class="one two"></div>
            <script>
                const box = document.getElementById("box");
                const sameObject = box.classList === box.classList;
                box.classList.add("three", "one");
                const forcedOff = box.classList.toggle("two", false);
                const toggledOn = box.classList.toggle("four");
                const replaced = box.classList.replace("three", "five");
                box.classList.remove("one");
                const out = document.createElement("div");
                out.id = "class-list-out";
                out.textContent = [
                    sameObject,
                    forcedOff,
                    toggledOn,
                    replaced,
                    box.className,
                    box.classList.length,
                    box.classList.item(0),
                    box.classList.contains("five"),
                    String(box.classList),
                ].join("|");
                document.body.appendChild(out);
            </script>
        </body></html>
        "#,
    );
    assert_eq!(
        text_of_selector(&doc, "#class-list-out"),
        "true|false|true|true|five four|2|five|true|five four"
    );
}

#[test]
fn structured_clone_copies_supported_values_and_cycles() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <script>
                const source = {
                    nested: { value: 7 },
                    list: [1, 2],
                    date: new Date("2024-01-02T03:04:05Z"),
                    map: new Map([["key", { value: 9 }]]),
                    set: new Set(["a", "b"]),
                };
                source.self = source;
                const copy = structuredClone(source);
                copy.nested.value = 8;
                const out = document.createElement("div");
                out.id = "clone-out";
                out.textContent = [
                    copy !== source,
                    copy.self === copy,
                    source.nested.value,
                    copy.nested.value,
                    copy.list.join(","),
                    copy.date.toISOString(),
                    copy.map.get("key").value,
                    [...copy.set].join(","),
                ].join("|");
                document.body.appendChild(out);
            </script>
        </body></html>
        "#,
    );
    assert_eq!(
        text_of_selector(&doc, "#clone-out"),
        "true|true|7|8|1,2|2024-01-02T03:04:05.000Z|9|a,b"
    );
}

#[test]
fn web_crypto_fills_integer_typed_arrays() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <script>
                const values = new Uint32Array(2);
                const returned = crypto.getRandomValues(values);
                const nullPrototype = Object.create(null);
                const out = document.createElement("div");
                out.id = "crypto-out";
                out.textContent = [
                    typeof crypto.getRandomValues,
                    returned === values,
                    values.length,
                    Number.isInteger(values[0]),
                    Object.getPrototypeOf(nullPrototype) === null,
                ].join("|");
                document.body.appendChild(out);
            </script>
        </body></html>
        "#,
    );
    assert_eq!(
        text_of_selector(&doc, "#crypto-out"),
        "function|true|2|true|true"
    );
}

#[test]
fn query_selectors() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <div class="item">one</div>
            <div class="item special">two</div>
            <section><div class="item">three</div></section>
            <script>
                const out = document.createElement("div");
                out.id = "out";
                const all = document.querySelectorAll(".item").length;
                const special = document.querySelector(".item.special").textContent;
                const scoped = document.querySelector("section").querySelectorAll(".item").length;
                out.textContent = `${all}|${special}|${scoped}`;
                document.body.appendChild(out);
            </script>
        </body></html>
        "#,
    );
    assert_eq!(text_of_selector(&doc, "#out"), "3|two|1");
}

#[test]
fn inner_html() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <div id="root"><span>old</span></div>
            <script>
                const root = document.getElementById("root");
                root.innerHTML = "<p class='msg'>new <b>content</b></p>";
            </script>
        </body></html>
        "#,
    );
    assert_eq!(text_of_selector(&doc, "#root .msg"), "new content");
    let inner = doc.inner();
    assert!(inner.query_selector("#root span").unwrap().is_none());
}

#[test]
fn template_content_exposes_parsed_children() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <script>
                const template = document.createElement("template");
                template.innerHTML = "<span class='from-template'>hello</span>";
                const clone = template.content.firstChild.cloneNode(true);
                document.body.appendChild(clone);
            </script>
        </body></html>
        "#,
    );

    assert_eq!(text_of_selector(&doc, ".from-template"), "hello");
}

#[test]
fn document_import_node_supports_solid_custom_element_templates() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <script>
                // Solid uses importNode rather than cloneNode for templates
                // whose root is a custom element. Chuzz's page host is a
                // <web-view>, so opening a second tab takes this exact path.
                const template = document.createElement("template");
                template.innerHTML = "<web-view data-tab='2'><span>page</span></web-view>";
                const clone = document.importNode(template.content.firstChild, true);
                document.body.appendChild(clone);
            </script>
        </body></html>
        "#,
    );

    assert_eq!(text_of_selector(&doc, "web-view[data-tab='2']"), "page");
}

#[test]
fn click_event_listeners() {
    let mut doc = doc_from_html(
        r#"
        <html><body>
            <button id="btn">Click me</button>
            <div id="out">unclicked</div>
            <script>
                let clicks = 0;
                const btn = document.getElementById("btn");
                btn.addEventListener("click", (event) => {
                    clicks += 1;
                    const out = document.getElementById("out");
                    out.textContent = `clicked ${clicks} times; target=${event.target.tagName}; ct=${event.currentTarget.id}`;
                });
            </script>
        </body></html>
        "#,
    );

    let click_event = {
        let inner = doc.inner();
        let btn_id = inner.query_selector("#btn").unwrap().unwrap();
        DomEvent::new(
            btn_id,
            inner
                .get_node(btn_id)
                .unwrap()
                .synthetic_click_event(Modifiers::empty()),
        )
    };
    doc.dispatch_dom_event(click_event.clone());
    assert_eq!(
        text_of_selector(&doc, "#out"),
        "clicked 1 times; target=BUTTON; ct=btn"
    );
    doc.dispatch_dom_event(click_event);
    assert_eq!(
        text_of_selector(&doc, "#out"),
        "clicked 2 times; target=BUTTON; ct=btn"
    );
}

#[test]
fn click_events_bubble_to_document() {
    let mut doc = doc_from_html(
        r#"
        <html><body>
            <button id="btn">Click me</button>
            <div id="out">unhandled</div>
            <script>
                document.addEventListener("click", (event) => {
                    document.getElementById("out").textContent =
                        `${event.target.tagName}|${event.currentTarget === document}`;
                });
            </script>
        </body></html>
        "#,
    );

    let click_event = {
        let inner = doc.inner();
        let btn_id = inner.query_selector("#btn").unwrap().unwrap();
        DomEvent::new(
            btn_id,
            inner
                .get_node(btn_id)
                .unwrap()
                .synthetic_click_event(Modifiers::empty()),
        )
    };
    doc.dispatch_dom_event(click_event);

    assert_eq!(text_of_selector(&doc, "#out"), "BUTTON|true");
}

#[test]
fn click_events_expose_the_composed_path() {
    let mut doc = doc_from_html(
        r#"
        <html><body>
            <div id="outer"><button id="btn">Click me</button></div>
            <div id="out">missing</div>
            <script>
                const btn = document.getElementById("btn");
                btn.addEventListener("click", (event) => {
                    const path = event.composedPath();
                    document.getElementById("out").textContent = [
                        path[0] === btn,
                        path.indexOf(document) >= 0,
                        path[path.length - 1] === window,
                    ].join("|");
                });
            </script>
        </body></html>
        "#,
    );

    let click_event = {
        let inner = doc.inner();
        let btn_id = inner.query_selector("#btn").unwrap().unwrap();
        DomEvent::new(
            btn_id,
            inner
                .get_node(btn_id)
                .unwrap()
                .synthetic_click_event(Modifiers::empty()),
        )
    };
    doc.dispatch_dom_event(click_event);

    assert_eq!(text_of_selector(&doc, "#out"), "true|true|true");
}

#[test]
fn click_events_bubble_and_stop_propagation() {
    let mut doc = doc_from_html(
        r#"
        <html><body>
            <div id="outer"><div id="middle"><button id="inner">hi</button></div></div>
            <div id="out"></div>
            <script>
                const log = [];
                const record = (name) => () => {
                    log.push(name);
                    document.getElementById("out").textContent = log.join(",");
                };
                document.getElementById("outer").addEventListener("click", record("outer"));
                document.getElementById("middle").addEventListener("click", (event) => {
                    record("middle")();
                    event.stopPropagation();
                });
                document.getElementById("inner").addEventListener("click", record("inner"));
            </script>
        </body></html>
        "#,
    );

    let click_event = {
        let inner = doc.inner();
        let btn_id = inner.query_selector("#inner").unwrap().unwrap();
        DomEvent::new(
            btn_id,
            inner
                .get_node(btn_id)
                .unwrap()
                .synthetic_click_event(Modifiers::empty()),
        )
    };
    doc.dispatch_dom_event(click_event);

    // "outer" should not be reached because "middle" stops propagation
    assert_eq!(text_of_selector(&doc, "#out"), "inner,middle");
}

#[test]
fn microtasks_run_after_script_execution() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <div id="out">pending</div>
            <script>
                Promise.resolve()
                    .then(() => "microtask")
                    .then((value) => {
                        document.getElementById("out").textContent = value;
                    });
            </script>
        </body></html>
        "#,
    );
    assert_eq!(text_of_selector(&doc, "#out"), "microtask");
}

#[test]
fn timers_run_on_poll() {
    let mut doc = doc_from_html(
        r#"
        <html><body>
            <div id="out">pending</div>
            <script>
                setTimeout((suffix) => {
                    document.getElementById("out").textContent = "timer ran " + suffix;
                }, 5, "with args");
            </script>
        </body></html>
        "#,
    );

    assert_eq!(text_of_selector(&doc, "#out"), "pending");
    std::thread::sleep(std::time::Duration::from_millis(20));
    let ran = doc.poll(None);
    assert!(ran);
    assert_eq!(text_of_selector(&doc, "#out"), "timer ran with args");
}

#[test]
fn request_animation_frame_runs_on_poll() {
    let mut doc = doc_from_html(
        r#"
        <html><body>
            <div id="out">pending</div>
            <script>
                requestAnimationFrame(() => {
                    document.getElementById("out").textContent = "frame";
                });
            </script>
        </body></html>
        "#,
    );

    std::thread::sleep(std::time::Duration::from_millis(30));
    doc.poll(None);
    assert_eq!(text_of_selector(&doc, "#out"), "frame");
}

#[test]
fn input_value_property() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <input id="field" value="initial">
            <div id="out"></div>
            <script>
                const field = document.getElementById("field");
                const before = field.value;
                field.value = "updated";
                document.getElementById("out").textContent = `${before}|${field.value}`;
            </script>
        </body></html>
        "#,
    );
    assert_eq!(text_of_selector(&doc, "#out"), "initial|updated");
}

#[test]
fn constructed_events_dispatch_and_bubble() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <input id="field">
            <div id="out"></div>
            <script>
                const field = document.getElementById("field");
                const out = document.getElementById("out");
                field.addEventListener("input", (event) => {
                    out.textContent = [
                        event instanceof Event,
                        event.target.id,
                        event.bubbles,
                        event.cancelable,
                        event.composed,
                        event.isTrusted,
                        event.currentTarget.id,
                    ].join("|");
                    event.preventDefault();
                });
                document.addEventListener("input", () => out.textContent += "|document");
                const accepted = field.dispatchEvent(new Event("input", {
                    bubbles: true,
                    cancelable: true,
                    composed: true,
                }));
                out.textContent += `|${accepted}`;
            </script>
        </body></html>
        "#,
    );
    assert_eq!(
        text_of_selector(&doc, "#out"),
        "true|field|true|true|true|false|field|document|false"
    );
}

#[test]
fn dom_interface_instanceof_checks_match_node_types_and_tags() {
    let doc = doc_from_html(
        r#"
        <html><head></head><body>
            <input id="field"><div id="out"></div>
            <script>
                const head = document.querySelector("head");
                const body = document.body;
                const field = document.getElementById("field");
                document.getElementById("out").textContent = [
                    document instanceof Node,
                    document instanceof Document,
                    document instanceof HTMLDocument,
                    body instanceof Node,
                    body instanceof Element,
                    body instanceof HTMLElement,
                    body instanceof HTMLBodyElement,
                    body instanceof HTMLHeadElement,
                    head instanceof HTMLHeadElement,
                    field instanceof HTMLInputElement,
                    field instanceof HTMLTextAreaElement,
                ].join("|");
            </script>
        </body></html>
        "#,
    );
    assert_eq!(
        text_of_selector(&doc, "#out"),
        "true|true|true|true|true|true|true|false|true|true|false"
    );
}

#[test]
fn compare_document_position_reports_tree_order_and_containment() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <main id="parent"><span id="first"></span><span id="second"></span></main>
            <div id="out"></div>
            <script>
                const parent = document.getElementById("parent");
                const first = document.getElementById("first");
                const second = document.getElementById("second");
                document.getElementById("out").textContent = [
                    first.compareDocumentPosition(first),
                    first.compareDocumentPosition(second),
                    second.compareDocumentPosition(first),
                    parent.compareDocumentPosition(first),
                    first.compareDocumentPosition(parent),
                    Node.DOCUMENT_POSITION_FOLLOWING,
                    Node.DOCUMENT_POSITION_PRECEDING,
                    Node.DOCUMENT_POSITION_CONTAINED_BY,
                    Node.DOCUMENT_POSITION_CONTAINS,
                ].join("|");
            </script>
        </body></html>
        "#,
    );
    assert_eq!(text_of_selector(&doc, "#out"), "0|4|2|20|10|4|2|16|8");
}

#[test]
fn checkbox_click_fires_input_and_change_events() {
    let mut doc = doc_from_html(
        r#"
        <html><body>
            <input type="checkbox" id="check">
            <div id="out"></div>
            <script>
                const check = document.getElementById("check");
                const log = [];
                check.addEventListener("input", () => log.push(`input:${check.checked}`));
                check.addEventListener("change", () => {
                    log.push(`change:${check.checked}`);
                    document.getElementById("out").textContent = log.join(",");
                });
            </script>
        </body></html>
        "#,
    );

    // Resolve style/layout: this constructs the checkbox's internal state
    // (as would happen before rendering in a windowed application)
    doc.inner_mut().resolve(0.0);

    let click_event = {
        let inner = doc.inner();
        let check_id = inner.query_selector("#check").unwrap().unwrap();
        DomEvent::new(
            check_id,
            inner
                .get_node(check_id)
                .unwrap()
                .synthetic_click_event(Modifiers::empty()),
        )
    };
    doc.dispatch_dom_event(click_event);
    assert_eq!(text_of_selector(&doc, "#out"), "input:true,change:true");
}

#[test]
fn dom_content_loaded_and_window_load_fire() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <div id="out"></div>
            <script>
                const log = [];
                document.addEventListener("DOMContentLoaded", () => log.push("dcl"));
                window.addEventListener("load", () => {
                    log.push("load");
                    document.getElementById("out").textContent = log.join(",");
                });
            </script>
        </body></html>
        "#,
    );
    assert_eq!(text_of_selector(&doc, "#out"), "dcl,load");
}

#[test]
fn on_event_idl_properties_are_dispatched() {
    let mut doc = doc_from_html(
        r#"
        <html><body>
            <button id="btn">go</button>
            <div id="out"></div>
            <script>
                document.getElementById("btn").onclick = (event) => {
                    document.getElementById("out").textContent = `onclick:${event.type}`;
                };
            </script>
        </body></html>
        "#,
    );

    let click_event = {
        let inner = doc.inner();
        let btn_id = inner.query_selector("#btn").unwrap().unwrap();
        DomEvent::new(
            btn_id,
            inner
                .get_node(btn_id)
                .unwrap()
                .synthetic_click_event(Modifiers::empty()),
        )
    };
    doc.dispatch_dom_event(click_event);
    assert_eq!(text_of_selector(&doc, "#out"), "onclick:click");
}

#[test]
fn node_wrappers_have_stable_identity() {
    let doc = doc_from_html(
        r##"
        <html><body>
            <div id="root"><span id="child">x</span></div>
            <div id="out"></div>
            <script>
                const root1 = document.getElementById("root");
                const root2 = document.querySelector("#root");
                root1.expando = "kept";
                const sameObject = root1 === root2;
                const viaParent = document.getElementById("child").parentNode;
                document.getElementById("out").textContent =
                    `${sameObject}|${viaParent === root1}|${viaParent.expando}`;
            </script>
        </body></html>
        "##,
    );
    assert_eq!(text_of_selector(&doc, "#out"), "true|true|kept");
}

#[test]
fn style_bindings() {
    let doc = doc_from_html(
        r#"
        <html><body>
            <div id="box" style="color: red;"></div>
            <div id="out"></div>
            <script>
                const box = document.getElementById("box");
                const before = box.style.cssText;
                box.style.setProperty("background-color", "blue");
                const bg = box.style.getPropertyValue("background-color");
                document.getElementById("out").textContent = `${before}|${bg}`;
            </script>
        </body></html>
        "#,
    );
    assert_eq!(text_of_selector(&doc, "#out"), "color: red;|blue");
}

#[test]
fn eval_json_returns_embedder_friendly_results() {
    let mut doc = doc_from_html("<html><body></body></html>");

    let result = doc
        .eval_json("({ greeting: 'hello', count: 2 })")
        .expect("script should evaluate");

    assert_eq!(
        result,
        serde_json::json!({ "greeting": "hello", "count": 2 })
    );
}

#[test]
fn embedder_poll_hook_runs_after_document_scripts() {
    let mut doc = ScriptDocument::from_html(
        r#"
        <div id="out">waiting</div>
        <script>window.fromDocument = "ready";</script>
        "#,
        DocumentConfig::default(),
    );
    doc.set_poll_hook(|document, _| {
        document.eval(
            "document.getElementById('out').textContent = window.fromDocument + ' from hook';",
        );
        true
    });

    assert!(doc.poll(None));
    assert_eq!(text_of_selector(&doc, "#out"), "ready from hook");
}

#[test]
fn assigning_a_style_property_reaches_the_document() {
    // `element.style.height = "70px"` was a no-op.
    //
    // `CSSStyleDeclaration` in a browser carries a named accessor for every CSS
    // property. This binding defined only `cssText`, `setProperty`,
    // `removeProperty` and `getPropertyValue`, and `element.style` returned a
    // fresh object per access, so the assignment set a plain JS property on a
    // throwaway object and was discarded without a word.
    //
    // What it cost: the composer measures its content and writes its own
    // height, so an autosizing prompt grew its container and never grew the
    // field inside it. The text went to a second line that could not be seen.
    let mut doc = ScriptDocument::from_html(
        r#"<div id="box" style="color: red">text</div>"#,
        DocumentConfig::default(),
    );
    doc.execute_scripts();

    let result = doc
        .eval_json(
            r#"
            const box = document.getElementById("box");
            box.style.height = "70px";
            box.style.maxHeight = "120px";
            const before = box.getAttribute("style");
            box.style.height = "";
            ({
              attr: before,
              readBack: box.style.maxHeight,
              afterClear: box.getAttribute("style"),
              apiStillWorks: (() => {
                box.style.setProperty("width", "40px");
                return box.style.getPropertyValue("width");
              })(),
            })
            "#,
        )
        .expect("style assignment should evaluate");

    let attr = result["attr"].as_str().unwrap_or_default();
    assert!(
        attr.contains("height: 70px"),
        "height must reach the style attribute: {result}"
    );
    // camelCase becomes kebab-case, or the declaration is not CSS.
    assert!(
        attr.contains("max-height: 120px"),
        "maxHeight must be written as max-height: {result}"
    );
    assert_eq!(
        result["readBack"].as_str(),
        Some("120px"),
        "a property must read back: {result}"
    );
    assert!(
        !result["afterClear"]
            .as_str()
            .unwrap_or_default()
            .contains("height: 70px"),
        "assigning an empty string must remove the declaration: {result}"
    );
    assert_eq!(
        result["apiStillWorks"].as_str(),
        Some("40px"),
        "setProperty and getPropertyValue must not be shadowed by the proxy: {result}"
    );
}

#[test]
fn a_fixed_overlay_appended_by_script_covers_the_viewport() {
    // How every modal in an embedding app is opened: build the backdrop, move
    // it under `body`, let `position: fixed; inset: 0` size it. If the append
    // does not re-run layout against the viewport the backdrop keeps whatever
    // box it was measured with while detached, and the dialog paints as a strip
    // across the top of the window instead of covering it.
    let mut doc = ScriptDocument::from_html(
        r#"
        <style>
          html, body { height: 100%; margin: 0 }
          .overlay { position: fixed; top: 0; right: 0; bottom: 0; left: 0 }
        </style>
        <div id="app" style="height: 40px"></div>
        "#,
        DocumentConfig {
            viewport: Some(Viewport::new(800, 600, 1.0, ColorScheme::Light)),
            ..DocumentConfig::default()
        },
    );
    doc.execute_scripts();
    doc.inner_mut().resolve(0.0);

    let rect = doc
        .eval_json(
            r#"
            const overlay = document.createElement("div");
            overlay.className = "overlay";
            document.body.appendChild(overlay);
            const box = overlay.getBoundingClientRect();
            ({ width: box.width, height: box.height, top: box.top, left: box.left })
            "#,
        )
        .expect("overlay geometry should evaluate");

    assert_eq!(
        rect,
        serde_json::json!({ "width": 800.0, "height": 600.0, "top": 0.0, "left": 0.0 })
    );
}

#[test]
fn appending_an_attached_node_moves_it_rather_than_sharing_it() {
    // `appendChild` on a node that already has a parent is a *move*: the DOM
    // detaches it first. A modal that relocates its own subtree under `body` to
    // escape a containing block relies on exactly that. Leaving the node in both
    // child lists lays it out twice, once in flow where it came from, which is
    // how a full-screen backdrop paints as a strip across the old parent.
    let mut doc = ScriptDocument::from_html(
        r#"<div id="host"><div id="panel">panel</div></div>"#,
        DocumentConfig {
            viewport: Some(Viewport::new(800, 600, 1.0, ColorScheme::Light)),
            ..DocumentConfig::default()
        },
    );
    doc.execute_scripts();
    doc.inner_mut().resolve(0.0);

    let moved = doc
        .eval_json(
            r#"
            const panel = document.getElementById("panel");
            document.body.appendChild(panel);
            ({
                hostChildren: document.getElementById("host").children.length,
                parentIsBody: panel.parentNode === document.body,
                bodyHasPanelOnce:
                    Array.prototype.filter.call(document.body.children, (c) => c.id === "panel").length,
            })
            "#,
        )
        .expect("reparent should evaluate");

    assert_eq!(
        moved,
        serde_json::json!({
            "hostChildren": 0,
            "parentIsBody": true,
            "bodyHasPanelOnce": 1,
        })
    );
}

#[test]
fn parent_node_append_moves_a_subtree_and_takes_strings() {
    // `document.body.append(node)` is how a dialog escapes an ancestor that
    // would otherwise be the containing block for its `position: fixed`
    // backdrop. Without `append` the call threw, the lifecycle hook that made
    // it unwound, and the dialog stayed where it was built — the backdrop then
    // painted inside that ancestor as a strip rather than over the window.
    let mut doc = ScriptDocument::from_html(
        r#"<div id="host"><div id="panel">panel</div></div><div id="sink"></div>"#,
        DocumentConfig {
            viewport: Some(Viewport::new(800, 600, 1.0, ColorScheme::Light)),
            ..DocumentConfig::default()
        },
    );
    doc.execute_scripts();
    doc.inner_mut().resolve(0.0);

    let result = doc
        .eval_json(
            r#"
            const panel = document.getElementById("panel");
            const sink = document.getElementById("sink");
            sink.append(panel, " tail");
            const list = document.createElement("div");
            list.append("b", "c");
            list.prepend("a");
            document.body.append(list);
            const wiped = document.createElement("div");
            wiped.append("gone");
            wiped.replaceChildren("kept");
            ({
                hostChildren: document.getElementById("host").children.length,
                sinkText: sink.textContent,
                listText: list.textContent,
                wipedText: wiped.textContent,
            })
            "#,
        )
        .expect("append should evaluate");

    assert_eq!(
        result,
        serde_json::json!({
            "hostChildren": 0,
            "sinkText": "panel tail",
            "listText": "abc",
            "wipedText": "kept",
        })
    );
}
/// A shell that records what script asked it to put on the clipboard.
#[derive(Default)]
struct RecordingClipboard {
    written: Mutex<Vec<String>>,
}

impl blitz_traits::shell::ShellProvider for RecordingClipboard {
    fn set_clipboard_text(&self, text: String) -> Result<(), blitz_traits::shell::ClipboardError> {
        self.written.lock().unwrap().push(text);
        Ok(())
    }
}

#[test]
fn navigator_clipboard_write_text_reaches_the_shell() {
    // Every "copy" button in an embedding app goes through this one call. With
    // no `navigator.clipboard` the property lookup threw, the usual try/catch
    // swallowed it, and the button reported success while copying nothing.
    let clipboard = Arc::new(RecordingClipboard::default());
    let mut doc = ScriptDocument::from_html(
        r#"<div id="out"></div>"#,
        DocumentConfig {
            viewport: Some(Viewport::new(400, 200, 1.0, ColorScheme::Light)),
            ..DocumentConfig::default()
        },
    );
    doc.inner_mut().set_shell_provider(clipboard.clone());
    doc.execute_scripts();

    doc.eval(
        r#"navigator.clipboard
             .writeText("session-4f21")
             .then(() => { document.getElementById("out").textContent = "copied" });"#,
    );
    doc.poll(None);

    assert_eq!(*clipboard.written.lock().unwrap(), vec!["session-4f21"]);
    assert_eq!(text_of_selector(&doc, "#out"), "copied");
}
#[test]
fn document_get_selection_is_callable_when_nothing_is_selected() {
    // The failure this guards is not a wrong value, it is a thrown TypeError:
    // `document.getSelection` was undefined, so calling it aborted whichever
    // copy or keydown handler reached for it, and the visible symptom was a
    // button that did nothing at all.
    let mut doc = ScriptDocument::from_html(
        r#"<p id="body">some text</p>"#,
        DocumentConfig {
            viewport: Some(Viewport::new(400, 200, 1.0, ColorScheme::Light)),
            ..DocumentConfig::default()
        },
    );
    doc.execute_scripts();
    doc.inner_mut().resolve(0.0);

    let state = doc
        .eval_json(
            r#"
            const selection = document.getSelection();
            ({
                text: selection.toString(),
                rangeCount: selection.rangeCount,
                collapsed: selection.isCollapsed,
                optionalChain: document.getSelection()?.toString() ?? "",
                restoreIsSafe: (() => {
                    const previous = selection.rangeCount ? selection.getRangeAt(0) : null;
                    selection.removeAllRanges();
                    if (previous) selection.addRange(previous);
                    return true;
                })(),
            })
            "#,
        )
        .expect("getSelection should evaluate");

    assert_eq!(
        state,
        serde_json::json!({
            "text": "",
            "rangeCount": 0,
            "collapsed": true,
            "optionalChain": "",
            "restoreIsSafe": true,
        })
    );
}
#[test]
fn box_metrics_are_reported_in_unzoomed_css_pixels() {
    // `scrollHeight` is defined in CSS pixels, so a zoomed element must report
    // the same number an unzoomed one would. Returning the zoomed layout height
    // breaks the standard autosize idiom — measure `scrollHeight`, write it back
    // into `style.height` — because the write is zoomed a second time and the
    // element grows by the zoom factor on every pass. `getBoundingClientRect`
    // is the exception and stays in zoomed viewport coordinates.
    let mut doc = ScriptDocument::from_html(
        r#"
        <div id="root" style="zoom: 2">
            <div id="box" style="width: 100px; height: 50px; overflow: auto">
                <div style="width: 300px; height: 150px"></div>
            </div>
        </div>
        "#,
        DocumentConfig {
            viewport: Some(Viewport::new(2000, 1000, 1.0, ColorScheme::Light)),
            ..DocumentConfig::default()
        },
    );
    doc.execute_scripts();
    doc.inner_mut().resolve(0.0);

    let metrics = doc
        .eval_json(
            r#"
            const box = document.getElementById("box");
            box.scrollLeft = 80;
            box.scrollTop = 30;
            ({
                clientWidth: box.clientWidth,
                clientHeight: box.clientHeight,
                scrollWidth: box.scrollWidth,
                scrollHeight: box.scrollHeight,
                scrollLeft: box.scrollLeft,
                scrollTop: box.scrollTop,
                rectHeight: box.getBoundingClientRect().height,
            })
            "#,
        )
        .expect("zoomed box metrics should evaluate");

    assert_eq!(
        metrics,
        serde_json::json!({
            "clientWidth": 100.0,
            "clientHeight": 50.0,
            "scrollWidth": 300.0,
            "scrollHeight": 150.0,
            "scrollLeft": 80.0,
            "scrollTop": 30.0,
            "rectHeight": 100.0,
        })
    );
}

#[test]
fn repeated_resolves_do_not_grow_the_document() {
    // The document must not get bigger just because it was laid out again.
    //
    // It did: box construction builds fresh anonymous blocks each pass and the
    // previous ones were only ever referenced by the list being overwritten, so
    // they stayed in the slab forever. One recorded session grew from 14 nodes
    // to 22,353 at a steady +11 per resolve, and resolve time climbed past
    // 80ms — which is what a window that grows slower the longer it is open,
    // until its controls stop answering, looks like from the inside.
    let mut doc = ScriptDocument::from_html(
        r#"
        <style>
          .row { display: flex; align-items: center; gap: 8px }
          .row::after { content: "!" }
        </style>
        <div class="row">text <b>bold</b> and <i>more</i> text</div>
        <div class="row">second <span>row</span> of content</div>
        "#,
        DocumentConfig {
            viewport: Some(Viewport::new(800, 600, 1.0, ColorScheme::Light)),
            ..DocumentConfig::default()
        },
    );
    doc.execute_scripts();

    doc.inner_mut().resolve(0.0);
    let settled = doc.inner().tree().len();

    for _ in 0..20 {
        // Damage the whole tree, as a non-incremental pass does.
        doc.inner_mut()
            .set_viewport(Viewport::new(800, 600, 1.0, ColorScheme::Light));
        doc.inner_mut().resolve(0.0);
    }

    let after = doc.inner().tree().len();
    assert_eq!(
        after,
        settled,
        "twenty resolves added {} nodes; construction is leaking anonymous boxes",
        after as i64 - settled as i64
    );
}

#[test]
fn custom_elements_define_upgrades_existing_elements() {
    // Before this, `customElements` did not exist at all, so
    // `customElements.define(...)` threw a ReferenceError out of whatever
    // module ran it. A framework that registers its components at import time
    // loses that entire module, and the page renders as unstyled markup.
    let mut doc = ScriptDocument::from_html(
        r#"<div id="host"><my-card id="a"></my-card><my-card id="b"></my-card></div>"#,
        DocumentConfig::default(),
    );
    doc.execute_scripts();

    let result = doc
        .eval_json(
            r#"
            let connected = 0;
            class MyCard extends HTMLElement {
              connectedCallback() { connected += 1; this.setAttribute("upgraded", "yes"); }
              label() { return "card:" + this.id; }
            }
            customElements.define("my-card", MyCard);

            const a = document.getElementById("a");
            ({
              // The class's methods reach the element.
              label: a.label(),
              // connectedCallback ran once per existing element.
              connected,
              // and it could touch the DOM.
              attr: a.getAttribute("upgraded"),
              // the registry answers lookups both ways
              got: customElements.get("my-card") === MyCard,
              name: customElements.getName(MyCard),
              missing: customElements.get("not-defined") === undefined,
            })
            "#,
        )
        .expect("customElements.define should evaluate");

    assert_eq!(
        result["label"].as_str(),
        Some("card:a"),
        "the class's methods must reach the element: {result}"
    );
    assert_eq!(
        result["connected"].as_i64(),
        Some(2),
        "connectedCallback must run once per existing element: {result}"
    );
    assert_eq!(
        result["attr"].as_str(),
        Some("yes"),
        "connectedCallback must be able to mutate the element: {result}"
    );
    assert_eq!(result["got"].as_bool(), Some(true), "get: {result}");
    assert_eq!(
        result["name"].as_str(),
        Some("my-card"),
        "getName: {result}"
    );
    assert_eq!(result["missing"].as_bool(), Some(true), "get: {result}");
}

#[test]
fn custom_elements_rejects_a_name_without_a_dash() {
    // The dash is what keeps the custom element namespace disjoint from HTML's,
    // so a name without one is a TypeError rather than a silent no-op.
    let mut doc = ScriptDocument::from_html("<div></div>", DocumentConfig::default());
    doc.execute_scripts();

    let result = doc
        .eval_json(
            r#"
            const attempt = (name) => {
              try { customElements.define(name, class extends HTMLElement {}); return "ok"; }
              catch (e) { return e.constructor.name; }
            };
            ({ bare: attempt("card"), dashed: attempt("my-card"),
               twice: attempt("my-card") })
            "#,
        )
        .expect("should evaluate");

    assert_eq!(result["bare"].as_str(), Some("TypeError"), "{result}");
    assert_eq!(result["dashed"].as_str(), Some("ok"), "{result}");
    assert_eq!(
        result["twice"].as_str(),
        Some("TypeError"),
        "defining the same name twice must throw: {result}"
    );
}

#[test]
fn a_custom_element_created_after_define_is_upgraded_on_insertion() {
    // The other half of upgrading. Frameworks define their components at import
    // time and create the elements later, so an upgrade pass that only visited
    // what was already in the document would miss every element that matters.
    let mut doc = ScriptDocument::from_html(r#"<div id="host"></div>"#, DocumentConfig::default());
    doc.execute_scripts();

    let result = doc
        .eval_json(
            r#"
            const seen = [];
            class MyChip extends HTMLElement {
              connectedCallback() { seen.push(this.getAttribute("label")); }
            }
            customElements.define("my-chip", MyChip);

            const host = document.getElementById("host");
            const first = document.createElement("my-chip");
            first.setAttribute("label", "one");
            host.appendChild(first);

            const second = document.createElement("my-chip");
            second.setAttribute("label", "two");
            host.append(second);

            ({ seen, isInstance: first instanceof MyChip, count: host.children.length })
            "#,
        )
        .expect("should evaluate");

    assert_eq!(
        result["seen"],
        serde_json::json!(["one", "two"]),
        "connectedCallback must run on insertion, for appendChild and append: {result}"
    );
    assert_eq!(
        result["isInstance"].as_bool(),
        Some(true),
        "an upgraded element must be an instance of its class: {result}"
    );
    assert_eq!(result["count"].as_i64(), Some(2), "{result}");
}

#[test]
fn a_scroller_does_not_stay_parked_past_content_that_shrank() {
    // Scroll to the bottom, then remove content. The offset was clamped when
    // the gesture happened and never re-checked, so it stayed beyond the new
    // end and the view sat in space the content no longer reaches: dismiss a
    // panel while scrolled down and its height is gone from under you, leaving
    // a band of nothing above the edge.
    let mut doc = ScriptDocument::from_html(
        r#"
        <style>
          body { margin: 0 }
          #pane { height: 100px; overflow-y: auto }
          .block { height: 100px }
        </style>
        <div id="pane">
          <div class="block">one</div>
          <div class="block">two</div>
          <div class="block" id="doomed">three</div>
        </div>
        "#,
        DocumentConfig {
            viewport: Some(Viewport::new(400, 300, 1.0, ColorScheme::Light)),
            ..DocumentConfig::default()
        },
    );
    doc.execute_scripts();
    doc.inner_mut().resolve(0.0);

    let scrolled = doc
        .eval_json(
            r#"
            (() => {
              const pane = document.getElementById("pane");
              pane.scrollTop = 1000;
              return { top: pane.scrollTop, height: pane.scrollHeight };
            })()
            "#,
        )
        .expect("scroll should evaluate");
    assert_eq!(
        scrolled["top"].as_f64(),
        Some(200.0),
        "parked at the end: {scrolled}"
    );

    doc.eval(r#"document.getElementById("doomed").remove();"#);
    doc.inner_mut().resolve(0.0);

    let after = doc
        .eval_json(
            r#"
            (() => {
              const pane = document.getElementById("pane");
              return { top: pane.scrollTop, height: pane.scrollHeight };
            })()
            "#,
        )
        .expect("scroll should evaluate");

    assert_eq!(
        after["height"].as_f64(),
        Some(200.0),
        "the removed block's height should be gone: {after}"
    );
    assert_eq!(
        after["top"].as_f64(),
        Some(100.0),
        "the offset must come back to the new end, not stay past it: {after}"
    );
}

#[test]
fn a_shrink_to_fit_box_grows_when_its_text_does() {
    // The agent bubble's exact shape: a flex column item that is itself a flex
    // column, `align-self: flex-start` so it is as wide as its own content,
    // clamped by a max-width. Text arrives a token at a time while the agent
    // writes, so the width it settles on has to keep up with the text.
    //
    // The measurement behind that width is cached and is not keyed on the text.
    // If a text change does not invalidate it the bubble keeps the width it had
    // for its first line, and every later word paints outside it: text spilling
    // past the right edge of its own background.
    let mut doc = ScriptDocument::from_html(
        r#"
        <style>
          body { margin: 0; width: 900px; font: 16px monospace }
          #column { display: flex; flex-direction: column }
          #bubble {
            display: flex;
            flex-direction: column;
            align-self: flex-start;
            max-width: 88%;
          }
        </style>
        <div style="width: 900px"><div id="column"><div id="bubble"><div id="text">short</div></div></div></div>
        "#,
        DocumentConfig {
            viewport: Some(Viewport::new(900, 600, 1.0, ColorScheme::Light)),
            ..DocumentConfig::default()
        },
    );
    doc.execute_scripts();
    doc.inner_mut().resolve(0.0);

    let sizes = doc
        .eval_json(
            r#"
            const bubble = document.getElementById("bubble");
            const text = document.getElementById("text");
            const before = bubble.clientWidth;
            const probe = { column: document.getElementById("column").clientWidth,
                            bubbleH: bubble.clientHeight,
                            textH: document.getElementById("text").clientHeight };
            text.textContent = "short and then a good deal more text arrived here";
            ({ before, width: bubble.clientWidth, scroll: bubble.scrollWidth,
               textWidth: text.clientWidth, textScroll: text.scrollWidth, probe })
            "#,
        )
        .expect("bubble geometry should evaluate");

    let before = sizes["before"].as_f64().expect("before");
    let width = sizes["width"].as_f64().expect("width");
    let scroll = sizes["scroll"].as_f64().expect("scroll");

    assert!(
        before > 0.0,
        "the bubble should size itself to its first line: {sizes}"
    );
    assert!(
        width > before,
        "the bubble should grow with its text: {sizes}"
    );
    assert!(
        scroll <= width + 0.5,
        "text must not overflow the box that sizes itself to it: {sizes}"
    );
}

#[test]
fn a_textarea_answers_its_height_without_a_document_resolve() {
    // What typing costs. An autosizing composer measures `scrollHeight` on
    // every keystroke; every geometry read flushes layout so the answer covers
    // pending mutations; and that flush is a full `doc.resolve`, measured at
    // 19.16ms of a 21.55ms keystroke.
    //
    // The document is never resolved between the mutation and the read below,
    // so the height can only come from the editor's own layout. Getting the
    // right answer here is what makes skipping the flush safe.
    let mut doc = ScriptDocument::from_html(
        r#"
        <style>
          body { margin: 0; width: 400px; font: 16px monospace }
          textarea {
            width: 300px; border: 0; padding: 0;
            font: 16px monospace; line-height: 20px;
            overflow-y: auto; overflow-wrap: anywhere;
          }
        </style>
        <textarea id="field" rows="1" wrap="soft"></textarea>
        "#,
        DocumentConfig {
            viewport: Some(Viewport::new(400, 300, 1.0, ColorScheme::Light)),
            ..DocumentConfig::default()
        },
    );
    doc.execute_scripts();
    doc.inner_mut().resolve(0.0);

    let one_row = doc
        .eval_json(r#"(() => document.getElementById("field").scrollHeight)()"#)
        .expect("empty height")
        .as_f64()
        .expect("number");

    // Type, and read back without resolving in between.
    let grown = doc
        .eval_json(
            r#"
            (() => {
              const field = document.getElementById("field");
              field.value = "j;alksjf;laskj;lkjs;flsajdslaj;slkfjs;lfkjj;".repeat(6);
              return field.scrollHeight;
            })()
            "#,
        )
        .expect("grown height")
        .as_f64()
        .expect("number");

    assert!(one_row > 0.0, "an empty field still measures one row");
    assert!(
        grown >= one_row * 3.0,
        "the wrapped height has to be visible to the very next read, with no \
         resolve between: one_row={one_row}, grown={grown}"
    );
}

#[test]
fn a_textarea_measures_the_same_on_a_hidpi_display() {
    // CSS pixels do not depend on the display. A textarea 300px wide holding
    // the same text has the same client width and the same scroll height on a
    // 1x monitor and a 2x one, because both are CSS-pixel quantities.
    //
    // Why this is a separate test and not a parameter on the others: every
    // textarea test in this file builds its viewport at scale 1.0, which is the
    // one scale at which a device-pixel/CSS-pixel confusion cannot show. The
    // suite therefore agreed the wrapping was fixed while the app on a retina
    // display still wrapped its composer at half the box width, expanding to a
    // second line at roughly half a line of typing.
    fn geometry(scale: f32) -> (f64, f64) {
        let mut doc = ScriptDocument::from_html(
            r#"
            <style>
              body { margin: 0; width: 400px; font: 16px monospace }
              textarea {
                width: 300px; border: 0; padding: 0;
                font: 16px monospace; line-height: 20px;
                overflow-y: auto; overflow-wrap: anywhere;
              }
            </style>
            <textarea id="field" rows="1" wrap="soft"></textarea>
            "#,
            DocumentConfig {
                viewport: Some(Viewport::new(400, 300, scale, ColorScheme::Light)),
                ..DocumentConfig::default()
            },
        );
        doc.execute_scripts();
        doc.inner_mut().resolve(0.0);

        let sizes = doc
            .eval_json(
                r#"
                const field = document.getElementById("field");
                field.value = "the quick brown fox jumps over the lazy dog, twice over";
                ({ width: field.clientWidth, height: field.scrollHeight })
                "#,
            )
            .expect("textarea geometry should evaluate");
        (
            sizes["width"].as_f64().expect("width"),
            sizes["height"].as_f64().expect("height"),
        )
    }

    let (width_1x, height_1x) = geometry(1.0);
    let (width_2x, height_2x) = geometry(2.0);

    assert_eq!(
        width_1x, width_2x,
        "a 300px box is 300 CSS pixels wide on any display: 1x={width_1x}, 2x={width_2x}"
    );
    assert_eq!(
        height_1x, height_2x,
        "the same text in the same box wraps to the same height on any display, \
         so a mismatch means the editor was handed a width or read a height in \
         device pixels: 1x={height_1x}, 2x={height_2x}"
    );
}

#[test]
fn a_textarea_reports_a_smaller_height_when_its_text_shrinks() {
    // The other half of autosizing. A field that grows must also come back
    // down, and it cannot if the measurement it is driven by is floored at the
    // size it currently has: that makes the height a high-water mark, so
    // clearing the text leaves the box several lines tall with nothing in it.
    let mut doc = ScriptDocument::from_html(
        r#"
        <style>
          body { margin: 0; width: 400px; font: 16px monospace }
          textarea {
            width: 300px; border: 0; padding: 0;
            font: 16px monospace; line-height: 20px;
            overflow-y: auto; overflow-wrap: anywhere;
          }
        </style>
        <textarea id="field" rows="1" wrap="soft"></textarea>
        "#,
        DocumentConfig {
            viewport: Some(Viewport::new(400, 300, 1.0, ColorScheme::Light)),
            ..DocumentConfig::default()
        },
    );
    doc.execute_scripts();
    doc.inner_mut().resolve(0.0);

    // Drive it exactly as the composer does: measure, write the measurement
    // into the height, lay out, repeat. The height has to settle on the text,
    // and it has to come back down when the text does.
    doc.eval(
        r#"(() => {
             const field = document.getElementById("field");
             field.value = "j;alksjf;laskj;lkjs;flsajdslaj;slkfjs;lfkjj;".repeat(6);
           })()"#,
    );
    doc.inner_mut().resolve(0.0);
    doc.eval(
        r#"(() => {
             const field = document.getElementById("field");
             globalThis.grown = field.scrollHeight;
             field.style.height = globalThis.grown + "px";
           })()"#,
    );
    doc.inner_mut().resolve(0.0);

    doc.eval(r#"document.getElementById("field").value = "j";"#);
    doc.inner_mut().resolve(0.0);

    let sizes = doc
        .eval_json(
            r#"
            (() => {
              const field = document.getElementById("field");
              return { grown: globalThis.grown, shrunk: field.scrollHeight };
            })()
            "#,
        )
        .expect("textarea geometry should evaluate");

    let grown = sizes["grown"].as_f64().expect("grown");
    let shrunk = sizes["shrunk"].as_f64().expect("shrunk");

    assert!(
        grown > 60.0,
        "long text should measure several rows: {sizes}"
    );
    assert!(
        shrunk < grown / 2.0,
        "one character must not still measure the height of the old text: {sizes}"
    );
}

#[test]
fn a_textarea_wraps_its_text_and_reports_the_height_it_needs() {
    // Two halves of the same gap. The editor behind a textarea was built with
    // `set_width(None)` and never told the box's width, so `wrap="soft"` had
    // nothing to act on: a long line walked out past the right edge and became
    // invisible. And because the measured height was `rows * line-height`
    // regardless of content, `scrollHeight` never exceeded one row, so the
    // measure-and-grow idiom every autosizing composer uses could not grow it.
    let mut doc = ScriptDocument::from_html(
        r#"
        <style>
          body { margin: 0; width: 400px; font: 16px monospace }
          textarea {
            width: 300px;
            border: 0;
            padding: 0;
            font: 16px monospace;
            line-height: 20px;
            overflow-y: auto;
            /* What the composer sets, so an unbroken run of characters wraps
               rather than walking off the edge. */
            overflow-wrap: anywhere;
          }
        </style>
        <textarea id="field" rows="1" wrap="soft"></textarea>
        "#,
        DocumentConfig {
            viewport: Some(Viewport::new(400, 300, 1.0, ColorScheme::Light)),
            ..DocumentConfig::default()
        },
    );
    doc.execute_scripts();
    doc.inner_mut().resolve(0.0);

    let sizes = doc
        .eval_json(
            r#"
            const field = document.getElementById("field");
            const empty = field.scrollHeight;
            field.value = "j;alksjf;laskj;lkjs;flsajdslaj;slkjfs;lfkjj;".repeat(6);
            ({ empty, filled: field.scrollHeight, width: field.clientWidth })
            "#,
        )
        .expect("textarea geometry should evaluate");

    let empty = sizes["empty"].as_f64().expect("empty");
    let filled = sizes["filled"].as_f64().expect("filled");
    let width = sizes["width"].as_f64().expect("width");

    assert_eq!(
        width, 300.0,
        "the box keeps the width it was given: {sizes}"
    );
    assert!(empty > 0.0, "an empty field is still one row tall: {sizes}");
    assert!(
        filled >= empty * 3.0,
        "long text must wrap into several rows rather than run off the edge: {sizes}"
    );
}

#[test]
fn removing_the_focused_node_does_not_poison_later_focus() {
    // Dismissing a panel is a click on a control inside it, so at the moment
    // its subtree is removed that control is both the focused node and the node
    // the press landed on. Neither id was cleared, and the next focus change
    // blurs the old one by indexing the slab: vacant and it panics inside the
    // event handler, reused and the blur lands on an unrelated element with
    // focus routing quietly wrong from then on. Either way the window stops
    // answering clicks until something forces a full rebuild.
    let mut doc = ScriptDocument::from_html(
        r#"<div id="panel"><button id="dismiss">x</button></div><button id="other">other</button>"#,
        DocumentConfig {
            viewport: Some(Viewport::new(400, 300, 1.0, ColorScheme::Light)),
            ..DocumentConfig::default()
        },
    );
    doc.execute_scripts();
    doc.inner_mut().resolve(0.0);

    doc.eval(r#"document.getElementById("dismiss").focus();"#);
    let dismissed = doc
        .inner()
        .query_selector("#dismiss")
        .unwrap()
        .expect("the dismiss button exists");
    assert_eq!(doc.inner().get_focussed_node_id(), Some(dismissed));

    // The control removes the panel it lives in, taking itself with it.
    doc.eval(r#"document.getElementById("panel").remove();"#);
    doc.inner_mut().resolve(0.0);
    let focused = doc.inner().get_focussed_node_id();
    assert_ne!(
        focused,
        Some(dismissed),
        "focus must not survive the node it was on"
    );
    // Whatever holds focus now has to be a node that still exists: the point is
    // that nothing later dereferences a dead slab slot.
    if let Some(focused) = focused {
        assert!(
            doc.inner().get_node(focused).is_some(),
            "focus points at a node that is gone: {focused}"
        );
    }

    // The next interaction must be ordinary, not a panic.
    doc.eval(r#"document.getElementById("other").focus();"#);
    let other = doc
        .inner()
        .query_selector("#other")
        .unwrap()
        .expect("the other button exists");
    assert_eq!(doc.inner().get_focussed_node_id(), Some(other));
}

#[test]
fn editing_an_existing_text_node_relays_out_its_container() {
    // The streaming path, which nothing else here covers.
    //
    // Solid does not replace a text node per token; it writes the new string
    // into the one already there, so `element.textContent = ...` is the wrong
    // route to test with. That takes the branch which removes children and
    // creates a fresh node. Writing `.data` on the text node itself is what a
    // streaming reply actually does, and it is the only thing that reaches
    // `BaseDocument::set_node_text`.
    //
    // Worth stating plainly because it was measured: before this test, that
    // function had zero coverage across the DOM suite, while carrying the
    // damage decision for every token the agent writes.
    let mut doc = ScriptDocument::from_html(
        r#"
        <style>
          body { margin: 0; width: 900px; font: 16px monospace }
          #column { display: flex; flex-direction: column }
          #bubble { display: flex; flex-direction: column; align-self: flex-start; max-width: 88% }
        </style>
        <div style="width: 900px"><div id="column"><div id="bubble">short</div></div></div>
        "#,
        DocumentConfig {
            viewport: Some(Viewport::new(900, 600, 1.0, ColorScheme::Light)),
            ..DocumentConfig::default()
        },
    );
    doc.execute_scripts();
    doc.inner_mut().resolve(0.0);

    let sizes = doc
        .eval_json(
            r#"
            const bubble = document.getElementById("bubble");
            const node = bubble.firstChild;
            const before = bubble.clientWidth;
            const kind = node.nodeType;
            node.data = "short and then a good deal more text arrived here";
            ({ before, kind, width: bubble.clientWidth, scroll: bubble.scrollWidth })
            "#,
        )
        .expect("bubble geometry should evaluate");

    assert_eq!(
        sizes["kind"].as_f64(),
        Some(3.0),
        "the edit must land on a text node, or it takes a different path: {sizes}"
    );
    let before = sizes["before"].as_f64().expect("before");
    let width = sizes["width"].as_f64().expect("width");
    let scroll = sizes["scroll"].as_f64().expect("scroll");
    assert!(
        before > 0.0,
        "the box sizes itself to its first text: {sizes}"
    );
    assert!(
        width > before,
        "editing the text node in place must relay out its container: {sizes}"
    );
    assert!(
        scroll <= width + 0.5,
        "text must not overflow the box that sizes itself to it: {sizes}"
    );
}

/// A script element appended by script has to run.
///
/// `execute_scripts` is a single pass over the markup the parser produced, so
/// only scripts present in the original HTML ever ran. Every loader that
/// injects its bundle at runtime — CDN failover, analytics, lazy chunks — was
/// therefore dropped on the floor, and silently: no error, just a page that
/// never builds.
///
/// nofilter.io is the case this was found on. Its bundle is declared as
/// `<script data-src>` and appended by an inline bootstrap, and because the
/// bootstrap awaits the new element's `load` event before removing a
/// `body{display:none}` rule, a script that never runs leaves a blank white
/// window rather than a partial page.
#[test]
fn a_script_element_appended_by_script_runs() {
    let mut doc = doc_from_html(
        r#"
        <html><body>
            <div id="out">not-run</div>
            <script>
                const injected = document.createElement("script");
                injected.textContent =
                    "document.getElementById('out').textContent = 'ran'";
                document.head.appendChild(injected);
            </script>
        </body></html>
        "#,
    );
    // The append happens while the first pass is still running, so the new
    // script is picked up on the next turn of the loop rather than inline.
    doc.poll(None);

    assert_eq!(text_of_selector(&doc, "#out"), "ran");
}

/// The same, for a script with a `src`, and its `load` event.
///
/// The `src` form is the one real loaders use, and the `load` event is what
/// they wait on: nofilter.io resolves a promise in `onload` and only then
/// unhides the body, so a fetch that runs without firing the event is still a
/// blank page.
#[test]
fn an_appended_script_with_a_src_is_fetched_and_reports_load() {
    struct CannedScripts;
    impl blitz_script::ScriptFetcher for CannedScripts {
        fn fetch(&self, url: &blitz_traits::net::Url) -> Result<String, blitz_script::FetchError> {
            if url.as_str().ends_with("/app.mjs") {
                Ok("document.getElementById('out').textContent = 'bundle'".to_owned())
            } else {
                Err(blitz_script::FetchError::InvalidData("unexpected".into()))
            }
        }
    }

    let mut doc = ScriptDocument::from_html(
        r#"
        <html><body>
            <div id="out">not-run</div>
            <div id="loaded">no</div>
            <script>
                const injected = document.createElement("script");
                injected.onload = function () {
                    document.getElementById('loaded').textContent = 'yes';
                };
                injected.src = "https://example.com/app.mjs";
                document.head.appendChild(injected);
            </script>
        </body></html>
        "#,
        DocumentConfig {
            base_url: Some("https://example.com/".to_owned()),
            ..Default::default()
        },
    )
    .with_fetcher(CannedScripts);
    doc.execute_scripts();
    doc.poll(None);

    assert_eq!(text_of_selector(&doc, "#out"), "bundle");
    assert_eq!(
        text_of_selector(&doc, "#loaded"),
        "yes",
        "the loader waits on this event before it will show the page"
    );
}