nsh-js 0.7.1

QuickJS host: runtime setup, host APIs, op decoding and bytecode.
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
//! The virtualized, recycling list: `<List>` (the `list` of `nsh:rt`) and
//! the rows of Rust components that lay out the app's items (`ListView`).
//!
//! Only rows near the viewport exist: the core decides which and asks for
//! cells (`Host::bind_list`, answered here without JS), and reuses them: a
//! recycled cell gets a new index, its item accessor follows. Positions,
//! columns, sticky headers and viewability are native.

use std::{
    cell::RefCell,
    ffi::{CStr, CString, c_int},
    ptr,
    rc::Rc,
};

use nsh_core::{
    Command, EventKind, NodeId, Op, Prop, Tag,
    geometry::{Percentage, Points},
    list_diff::ListDiff,
};
use rquickjs::qjs;
use rustc_hash::FxHashMap;

use crate::{
    dom,
    reactive::{self, arg},
};

type JsValue = qjs::JSValue;
type JsContext = qjs::JSContext;

const UNDEFINED: JsValue = qjs::JS_UNDEFINED;

/// The host props a list forwards as they are (`viewport` first: the
/// mode decides how the core takes the others).
const FORWARDED: &[&str] = &[
    "viewport",
    "style",
    "testID",
    "horizontal",
    "scrollbar",
    "refreshing",
    "onRefresh",
    "pullValue",
    "refreshIndicator",
    "onLoadMore",
    "onLoadMoreAtStart",
    "onScrollEnd",
    "scrollValue",
    "keyboardDismissMode",
    "numColumns",
    "inverted",
    "alignment",
    "maintainVisibleContentPosition",
    "stickyHeaderIndices",
    "stickyHeaderOffset",
    "contentStyle",
    "contentClass",
    "viewabilityConfig",
    "pagingEnabled",
    "snapToInterval",
    "snapToOffsets",
    "snapToAlignment",
    "decelerationRate",
    "scrollable",
    "bounces",
    "scrollsToTop",
    "smoothWheel",
    "wheelLineHeight",
    "contentInset",
    "scrollbarInset",
    "contentOffset",
    "keyboardShouldPersistTaps",
    "scrollEventThrottle",
    "disableIntervalMomentum",
    "onScroll",
    "onScrollDragStart",
    "onScrollDragEnd",
    "onMomentumStart",
    "onMomentumEnd",
];

/// The props the list itself uses: every other prop the app passes (the
/// test id, accessibility, classes, touch and layout events, ...) goes to
/// the scroll view as it would on a `<Scroll>`, as React Native's
/// `FlatList` passes the rest to its `ScrollView`.
const OWN: &[&str] = &[
    "each",
    "children",
    "ref",
    "keyExtractor",
    "estimatedItemSize",
    "loadMoreThreshold",
    "loadMoreAtStartThreshold",
    "initialScrollIndex",
    "initialScrollAtEnd",
    "onViewableItemsChange",
    "header",
    "footer",
    "empty",
    "separator",
];

/// What the app passes a Rust component's rows (`listItemsProps` of the
/// JS glue): the data and the rows; the component lays them out.
pub(crate) const ITEMS_PROPS: &[&str] = &[
    "each",
    "children",
    "keyExtractor",
    "stickyHeaderIndices",
    "initialScrollIndex",
    "initialScrollAtEnd",
    "onViewableItemsChange",
    "viewabilityConfig",
    "refreshing",
    "onRefresh",
    "onLoadMore",
    "loadMoreThreshold",
    "header",
    "footer",
    "empty",
];

struct Cell {
    node: JsValue,
    /// The index signal.
    index: JsValue,
    owner: u32,
}

struct ListData {
    props: JsValue,
    node: JsValue,
    /// The items memo (`props.each`), which the cells' items read.
    items: JsValue,
    /// How the items changed, for the core.
    diffs: Vec<Rc<ListDiff>>,
    /// The owner the list was made under: cells are made as its roots.
    owner: u32,
    /// Cells by slot.
    cells: Vec<Option<Cell>>,
    /// Owners of the header and footer cells.
    extras: Vec<u32>,
    /// The owner of the empty cell while it shows: disposed with the list
    /// (its root is not owned by the list's owner).
    empty: Option<u32>,
    /// The viewable range reported last, and the latest.
    reported: (i64, i64),
    latest: (i64, i64),
    /// A pending `minimumViewTime` timer's id.
    timer: Option<f64>,
}

/// The lists' part of a context's state: each list by its node id.
#[derive(Default)]
pub(crate) struct Lists {
    map: RefCell<FxHashMap<NodeId, Box<ListData>>>,
}

impl Lists {
    /// Frees the values the lists hold (the state is unregistered).
    pub(crate) fn free_all(&mut self, raw: *mut JsContext) {
        for (_, data) in self.map.borrow_mut().drain() {
            free_data(raw, *data);
        }
    }
}

fn free_data(cx: *mut JsContext, data: ListData) {
    // SAFETY: values the list owned.
    unsafe {
        qjs::JS_FreeValue(cx, data.props);
        qjs::JS_FreeValue(cx, data.node);
        qjs::JS_FreeValue(cx, data.items);
        for cell in data.cells.into_iter().flatten() {
            qjs::JS_FreeValue(cx, cell.node);
            qjs::JS_FreeValue(cx, cell.index);
        }
    }
}

fn lists<'a>(cx: *mut JsContext) -> &'a Lists {
    // SAFETY: a projection of the state's field, by shared reference.
    unsafe { &(*crate::state::state(cx)).lists }
}

fn get(cx: *mut JsContext, obj: JsValue, key: &str) -> JsValue {
    let k = CString::new(key).unwrap_or_default();
    // SAFETY: a property read of a live value.
    unsafe {
        if !qjs::JS_IsObject(obj) {
            return UNDEFINED;
        }
        qjs::JS_GetPropertyStr(cx, obj, k.as_ptr())
    }
}

fn has(cx: *mut JsContext, obj: JsValue, key: &str) -> bool {
    // SAFETY: as `get`.
    unsafe {
        if !qjs::JS_IsObject(obj) {
            return false;
        }
        let k = CString::new(key).unwrap_or_default();
        let atom = qjs::JS_NewAtom(cx, k.as_ptr());
        let r = qjs::JS_HasProperty(cx, obj, atom);
        qjs::JS_FreeAtom(cx, atom);
        r == 1
    }
}

fn length(cx: *mut JsContext, array: JsValue) -> i64 {
    let mut len: i64 = 0;
    // SAFETY: reads a live value's length (0 for non-arrays).
    unsafe {
        if !qjs::JS_IsArray(array) || qjs::JS_GetLength(cx, array, &mut len) != 0 {
            return 0;
        }
    }
    len
}

fn native(
    cx: *mut JsContext,
    f: unsafe extern "C" fn(
        *mut JsContext,
        JsValue,
        c_int,
        *mut JsValue,
        c_int,
        *mut JsValue,
    ) -> JsValue,
    length: c_int,
    data: &mut [JsValue],
) -> JsValue {
    // SAFETY: the function keeps dups of `data`.
    unsafe {
        qjs::JS_NewCFunctionData(
            cx,
            Some(f),
            length,
            0,
            data.len() as c_int,
            data.as_mut_ptr(),
        )
    }
}

/// `list(props)`: a virtualized list of `props.each`, rendering a row with
/// `props.children(item, index)` per cell.
pub(crate) unsafe extern "C" fn list(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
) -> JsValue {
    match render(cx, arg(argc, argv, 0)) {
        Ok(node) => reactive::finish_value(cx, node),
        Err(e) => e,
    }
}

/// Renders a list for `props` (borrowed); the list's node (owned).
pub(crate) fn render(cx: *mut JsContext, props: JsValue) -> Result<JsValue, JsValue> {
    let node = dom::create_element(cx, Tag::List)?;
    let id = dom::node_id(cx, node).expect("a node");
    // SAFETY: dups the list owns.
    let data = Box::new(ListData {
        props: unsafe { qjs::JS_DupValue(cx, props) },
        node: unsafe { qjs::JS_DupValue(cx, node) },
        items: UNDEFINED,
        diffs: Vec::new(),
        owner: reactive::current_owner(cx),
        cells: Vec::new(),
        extras: Vec::new(),
        empty: None,
        reported: (-1, -1),
        latest: (-1, -1),
        timer: None,
    });
    lists(cx).map.borrow_mut().insert(id, data);
    let fail = |e: JsValue| {
        // SAFETY: ours.
        unsafe { qjs::JS_FreeValue(cx, node) };
        e
    };
    // The items: cells move with theirs, and the core learns how they
    // changed (by identity: the common start and end stay), so
    // measurements follow their items.
    let list_id = qjs::JS_NewFloat64(id as f64);
    let func = native(cx, items_run, 1, &mut [list_id, props]);
    let items = reactive::memo(cx, func, false);
    let func = native(cx, splice_run, 0, &mut [node, items, list_id]);
    match lists(cx).map.borrow_mut().get_mut(&id) {
        Some(d) => d.items = items,
        // SAFETY: ours (the list went meanwhile).
        None => unsafe { qjs::JS_FreeValue(cx, items) },
    }
    let r = reactive::render_effect(cx, func);
    // SAFETY: the effect keeps its own value.
    unsafe { qjs::JS_FreeValue(cx, r) };
    // The forwarded props, the estimated size, the end threshold and the
    // host props passed on.
    let rest = rest_names(cx, props).map_err(fail)?;
    // SAFETY: a new array of the previous values.
    let prev = unsafe { qjs::JS_NewArray(cx) };
    let func = native(cx, forward_run, 0, &mut [node, props, prev, rest]);
    // SAFETY: the function keeps dups.
    unsafe {
        qjs::JS_FreeValue(cx, prev);
        qjs::JS_FreeValue(cx, rest);
    }
    let r = reactive::render_effect(cx, func);
    unsafe { qjs::JS_FreeValue(cx, r) };
    // Header and footer cells (always rendered), and the empty one.
    for (role, key) in [("header", "header"), ("footer", "footer")] {
        if has(cx, props, key) {
            let owner = extra_cell(cx, id, role, key).map_err(fail)?;
            if let Some(d) = lists(cx).map.borrow_mut().get_mut(&id) {
                d.extras.push(owner);
            }
        }
    }
    if has(cx, props, "empty") {
        // SAFETY: a placeholder for the empty cell's state (owner, node).
        let state = unsafe { qjs::JS_NewArray(cx) };
        let func = native(cx, empty_run, 0, &mut [node, props, state]);
        unsafe { qjs::JS_FreeValue(cx, state) };
        let r = reactive::render_effect(cx, func);
        unsafe { qjs::JS_FreeValue(cx, r) };
    }
    if has(cx, props, "onViewableItemsChange") {
        let mut data = [qjs::JS_NewFloat64(id as f64)];
        let on = native(cx, on_viewable, 1, &mut data);
        let r = dom::set_handler(cx, id, EventKind::ViewableItemsChange, on);
        unsafe { qjs::JS_FreeValue(cx, on) };
        r.map_err(fail)?;
    }
    let initial = get(cx, props, "initialScrollIndex");
    let at_end = get(cx, props, "initialScrollAtEnd");
    // SAFETY: these live values are read and released before queuing the op.
    let initial_command = unsafe {
        let command = if qjs::JS_ToBool(cx, at_end) > 0 {
            Some(Command::ScrollToEnd { animated: false })
        } else if qjs::JS_IsNumber(initial) {
            let mut index = 0f64;
            qjs::JS_ToFloat64(cx, &mut index, initial);
            Some(Command::ScrollToIndex {
                index: index.max(0.0) as u32,
                animated: false,
                view_position: Percentage(0.0),
                view_offset: Points::ZERO,
            })
        } else {
            None
        };
        qjs::JS_FreeValue(cx, initial);
        qjs::JS_FreeValue(cx, at_end);
        command
    };
    if let Some(command) = initial_command {
        dom::push_op(cx, Op::Command { id, command }).map_err(fail)?;
    }
    let ref_ = get(cx, props, "ref");
    // SAFETY: a live value, called untracked with the node.
    unsafe {
        if qjs::JS_IsFunction(cx, ref_) {
            let mut args = [node];
            let r = reactive::untracked_with(cx, || {
                qjs::JS_Call(cx, ref_, UNDEFINED, 1, args.as_mut_ptr())
            });
            qjs::JS_FreeValue(cx, ref_);
            if qjs::JS_IsException(r) {
                return Err(fail(r));
            }
            qjs::JS_FreeValue(cx, r);
        } else {
            qjs::JS_FreeValue(cx, ref_);
        }
    }
    // Gone with its owner: the cells and the binding.
    let cleanup = native(cx, dispose, 0, &mut [qjs::JS_NewFloat64(id as f64)]);
    let mut args = [cleanup];
    // SAFETY: registers the cleanup on the current owner.
    unsafe {
        let r = reactive::on_cleanup(cx, UNDEFINED, 1, args.as_mut_ptr());
        qjs::JS_FreeValue(cx, r);
        qjs::JS_FreeValue(cx, cleanup);
    }
    Ok(node)
}

unsafe extern "C" fn dispose(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    let mut id = 0f64;
    // SAFETY: one data value, the list's id.
    unsafe { qjs::JS_ToFloat64(cx, &mut id, *data) };
    let Some(data) = lists(cx).map.borrow_mut().remove(&(id as NodeId)) else {
        return UNDEFINED;
    };
    for cell in data.cells.iter().flatten() {
        reactive::dispose_owner(cx, cell.owner);
    }
    for &owner in data.extras.iter().chain(&data.empty) {
        reactive::dispose_owner(cx, owner);
    }
    free_data(cx, *data);
    UNDEFINED
}

fn set(cx: *mut JsContext, node: JsValue, name: &str, value: JsValue) -> Result<(), JsValue> {
    let r = dom::set_prop_value(cx, node, name, value);
    // SAFETY: ours.
    unsafe { qjs::JS_FreeValue(cx, value) };
    r
}

/// A run of the items memo: the items, once the cells moved with theirs
/// (as the core moves them, and Rust lists' `move_rows`): otherwise each
/// shows the item now at its old index until it is bound again.
unsafe extern "C" fn items_run(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: two data values; values got are freed or returned.
    unsafe {
        let (list, props) = (*data, *data.add(1));
        let old = arg(argc, argv, 0);
        let next = get(cx, props, "each");
        if qjs::JS_IsException(next) {
            return next;
        }
        let (old_len, next_len) = (length(cx, old), length(cx, next));
        if old_len > 0 && !qjs::JS_IsStrictEqual(cx, old, next) {
            let max = old_len.min(next_len);
            // With a `keyExtractor`, rows are the same when their keys
            // are: apps that rebuild their rows (new objects, same keys)
            // keep the rows' measurements and the reader's place.
            let key_of = get(cx, props, "keyExtractor");
            let keyed = qjs::JS_IsFunction(cx, key_of);
            let key = |item: JsValue, i: i64| {
                let mut args = [qjs::JS_DupValue(cx, item), qjs::JS_NewFloat64(i as f64)];
                let k = qjs::JS_Call(cx, key_of, UNDEFINED, 2, args.as_mut_ptr());
                qjs::JS_FreeValue(cx, args[0]);
                k
            };
            let same = |i: i64, j: i64| {
                let a = qjs::JS_GetPropertyInt64(cx, old, i);
                let b = qjs::JS_GetPropertyInt64(cx, next, j);
                let mut s = qjs::JS_IsStrictEqual(cx, a, b);
                if !s && keyed {
                    let (ka, kb) = (key(a, i), key(b, j));
                    s = !qjs::JS_IsException(ka)
                        && !qjs::JS_IsException(kb)
                        && qjs::JS_IsStrictEqual(cx, ka, kb);
                    for k in [ka, kb] {
                        if qjs::JS_IsException(k) {
                            qjs::JS_FreeValue(cx, qjs::JS_GetException(cx));
                        } else {
                            qjs::JS_FreeValue(cx, k);
                        }
                    }
                }
                qjs::JS_FreeValue(cx, a);
                qjs::JS_FreeValue(cx, b);
                s
            };
            let mut start = 0;
            while start < max && same(start, start) {
                start += 1;
            }
            let mut end = 0;
            while end < max - start && same(old_len - 1 - end, next_len - 1 - end) {
                end += 1;
            }
            let removed = old_len - start - end;
            let inserted = next_len - start - end;
            let splice = || {
                ListDiff::splice(
                    old_len as u32,
                    start as u32,
                    removed as u32,
                    inserted as u32,
                )
            };
            // Rows on both sides of the change are matched by key: the rows
            // that stay keep their cells and measurements wherever they go
            // (one moved to the top, the rows it passed, a window of rows
            // that slides), and the viewport its rows.
            let diff = if removed > 0 && inserted > 0 {
                // The keys stay alive until they are compared: an object's
                // is its address, which a freed key's memory could reuse.
                let (mut atoms, mut held) = (Vec::new(), Vec::new());
                let mut keys = |array: JsValue, from: i64, to: i64| {
                    (from..to)
                        .map(|i| {
                            let item = qjs::JS_GetPropertyInt64(cx, array, i);
                            let k = if keyed {
                                key(item, i)
                            } else {
                                qjs::JS_DupValue(cx, item)
                            };
                            qjs::JS_FreeValue(cx, item);
                            let token = item_key(cx, k);
                            if qjs::JS_IsException(k) {
                                qjs::JS_FreeValue(cx, qjs::JS_GetException(cx));
                            } else {
                                held.push(k);
                            }
                            if let Some(ItemKey::Atom(atom)) = token {
                                atoms.push(atom);
                            }
                            token
                        })
                        .collect::<Vec<_>>()
                };
                let old_keys = keys(old, start, old_len - end);
                let next_keys = keys(next, start, next_len - end);
                let diff = ListDiff::new_partial(&old_keys, &next_keys)
                    .map(|d| d.widened(start as u32, end as u32));
                for atom in atoms {
                    qjs::JS_FreeAtom(cx, atom);
                }
                for k in held {
                    qjs::JS_FreeValue(cx, k);
                }
                diff.unwrap_or_else(splice)
            } else {
                splice()
            };
            let diff = Rc::new(diff);
            qjs::JS_FreeValue(cx, key_of);
            if removed > 0 || inserted > 0 {
                let mut id = 0f64;
                qjs::JS_ToFloat64(cx, &mut id, list);
                let indices: Vec<JsValue> =
                    match lists(cx).map.borrow_mut().get_mut(&(id as NodeId)) {
                        Some(d) => {
                            d.diffs.push(Rc::clone(&diff));
                            d.cells
                                .iter()
                                .flatten()
                                .map(|c| qjs::JS_DupValue(cx, c.index))
                                .collect()
                        }
                        None => Vec::new(),
                    };
                for index in indices {
                    // Where the cell's row is now (a removed row's cell keeps
                    // its index until it is bound).
                    if let Some(i) = reactive::peek_number(cx, index)
                        && i >= 0.0
                        && let Some((moved, _)) = diff.new_index(i as u32)
                        && moved != i as u32
                    {
                        reactive::set_signal(cx, index, qjs::JS_NewFloat64(moved as f64));
                    }
                    qjs::JS_FreeValue(cx, index);
                }
            }
        }
        next
    }
}

/// What `===` compares a row's key by, where it can be looked up: a string
/// by its atom (one per content), an object by identity (its address: the
/// key must stay alive while it is compared), a number by its value. Other
/// keys (a symbol, `NaN`) are never found again: such rows change as one
/// splice, as before.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum ItemKey {
    Atom(qjs::JSAtom),
    Object(usize),
    Number(u64),
}

/// `key`'s [`ItemKey`] (borrowed; an atom made is the caller's).
fn item_key(cx: *mut JsContext, key: JsValue) -> Option<ItemKey> {
    // SAFETY: inline tag and pointer reads of a live value, an atom made of
    // a string (owned by the caller) or a pending exception cleared.
    unsafe {
        if qjs::JS_IsObject(key) {
            return Some(ItemKey::Object(qjs::JS_VALUE_GET_PTR(key) as usize));
        }
        if qjs::JS_IsString(key) {
            let atom = qjs::JS_ValueToAtom(cx, key);
            if atom != qjs::JS_ATOM_NULL {
                return Some(ItemKey::Atom(atom));
            }
            qjs::JS_FreeValue(cx, qjs::JS_GetException(cx));
            return None;
        }
        if qjs::JS_IsNumber(key) {
            let mut n = 0f64;
            qjs::JS_ToFloat64(cx, &mut n, key);
            // `===`: NaN is no row's key twice; 0 and -0 are one.
            return (!n.is_nan()).then(|| ItemKey::Number(if n == 0.0 { 0 } else { n.to_bits() }));
        }
    }
    None
}

/// A run of the items effect: tells the core how the items changed and
/// their count.
unsafe extern "C" fn splice_run(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: three data values; values got are freed.
    unsafe {
        let (node, items, list) = (*data, *data.add(1), *data.add(2));
        let next = qjs::JS_Call(cx, items, UNDEFINED, 0, ptr::null_mut());
        if qjs::JS_IsException(next) {
            return next;
        }
        let len = length(cx, next);
        qjs::JS_FreeValue(cx, next);
        let mut id = 0f64;
        qjs::JS_ToFloat64(cx, &mut id, list);
        let diffs = lists(cx)
            .map
            .borrow_mut()
            .get_mut(&(id as NodeId))
            .map(|d| std::mem::take(&mut d.diffs))
            .unwrap_or_default();
        if let Some(id) = dom::node_id(cx, node) {
            for diff in diffs {
                let prop = Prop::ListDiff(diff);
                if let Err(e) = dom::push_op(cx, Op::SetProp { id, prop }) {
                    return e;
                }
            }
        }
        if let Err(e) = set(cx, node, "count", qjs::JS_NewFloat64(len as f64)) {
            return e;
        }
        UNDEFINED
    }
}

/// A run of the forwarding effect: sends the props that changed.
unsafe extern "C" fn forward_run(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: four data values; the array keeps dups of the values.
    unsafe {
        let (node, props, prev, rest) = (*data, *data.add(1), *data.add(2), *data.add(3));
        let names = FORWARDED.iter().map(|&n| (n, n)).chain([
            ("estimatedItemSize", "estimatedItemSize"),
            ("loadMoreThreshold", "loadMoreThreshold"),
            ("loadMoreAtStartThreshold", "loadMoreAtStartThreshold"),
        ]);
        let mut at = 0;
        for (wire, key) in names {
            if let Err(e) = forward(cx, node, props, prev, at, wire, key) {
                return e;
            }
            at += 1;
        }
        for i in 0..length(cx, rest) {
            let name = qjs::JS_GetPropertyInt64(cx, rest, i);
            let s = qjs::JS_ToCString(cx, name);
            qjs::JS_FreeValue(cx, name);
            if s.is_null() {
                return qjs::JS_EXCEPTION;
            }
            let result = match CStr::from_ptr(s).to_str() {
                Ok(key) => forward(cx, node, props, prev, at, key, key),
                Err(_) => Ok(()),
            };
            qjs::JS_FreeCString(cx, s);
            if let Err(e) = result {
                return e;
            }
            at += 1;
        }
        UNDEFINED
    }
}

/// Sends prop `wire` of the list (`props[key]`) when it changed from the
/// value kept at `prev[at]`.
fn forward(
    cx: *mut JsContext,
    node: JsValue,
    props: JsValue,
    prev: JsValue,
    at: u32,
    wire: &str,
    key: &str,
) -> Result<(), JsValue> {
    let mut value = get(cx, props, key);
    // SAFETY: inline checks and reads of live values; `prev` keeps the
    // value, the old one is freed.
    unsafe {
        if qjs::JS_IsException(value) {
            return Err(value);
        }
        if qjs::JS_IsUndefined(value) || qjs::JS_IsNull(value) {
            value = match wire {
                "estimatedItemSize" => qjs::JS_NewFloat64(50.0),
                "loadMoreThreshold" | "loadMoreAtStartThreshold" => qjs::JS_NewFloat64(1.0),
                _ => value,
            };
        }
        let old = qjs::JS_GetPropertyUint32(cx, prev, at);
        let first = qjs::JS_IsUndefined(old)
            && !matches!(
                wire,
                "estimatedItemSize" | "loadMoreThreshold" | "loadMoreAtStartThreshold"
            );
        let result = if qjs::JS_IsStrictEqual(cx, old, value) || first && qjs::JS_IsUndefined(value)
        {
            Ok(())
        } else {
            dom::set_prop_with_prev(cx, node, wire, value, old)
        };
        qjs::JS_FreeValue(cx, old);
        qjs::JS_SetPropertyUint32(cx, prev, at, value);
        result
    }
}

/// The names of the props in `props` (borrowed) the list passes on to its
/// scroll view (all but its own and the ones it forwards by name), as an
/// array (owned). Read once: compiled JSX gives a list the same props for
/// its whole life, their values change behind getters.
fn rest_names(cx: *mut JsContext, props: JsValue) -> Result<JsValue, JsValue> {
    // SAFETY: a new array; an enumeration of a live object's own names,
    // freed after use.
    unsafe {
        let out = qjs::JS_NewArray(cx);
        if !qjs::JS_IsObject(props) {
            return Ok(out);
        }
        let mut tab: *mut qjs::JSPropertyEnum = ptr::null_mut();
        let mut len: u32 = 0;
        if qjs::JS_GetOwnPropertyNames(
            cx,
            &mut tab,
            &mut len,
            props,
            (qjs::JS_GPN_STRING_MASK | qjs::JS_GPN_ENUM_ONLY) as c_int,
        ) != 0
        {
            qjs::JS_FreeValue(cx, out);
            return Err(qjs::JS_EXCEPTION);
        }
        let mut n = 0;
        for j in 0..len as usize {
            let name = qjs::JS_AtomToString(cx, (*tab.add(j)).atom);
            let s = qjs::JS_ToCString(cx, name);
            let pass = !s.is_null()
                && CStr::from_ptr(s)
                    .to_str()
                    .is_ok_and(|name| !OWN.contains(&name) && !FORWARDED.contains(&name));
            if !s.is_null() {
                qjs::JS_FreeCString(cx, s);
            }
            if pass {
                qjs::JS_SetPropertyUint32(cx, out, n, name);
                n += 1;
            } else {
                qjs::JS_FreeValue(cx, name);
            }
        }
        qjs::JS_FreePropertyEnum(cx, tab, len);
        Ok(out)
    }
}

/// A list slot's value: a component is called, an element used as is.
unsafe extern "C" fn slot_run(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: two data values (props, key); values got are freed.
    unsafe {
        let (props, key) = (*data, *data.add(1));
        let Some(key) = dom::string_arg(cx, key) else {
            return qjs::JS_EXCEPTION;
        };
        let value = get(cx, props, &key);
        slot(cx, value)
    }
}

/// `value` (owned) as a list slot renders it.
fn slot(cx: *mut JsContext, value: JsValue) -> JsValue {
    // `<If>` and `<Each>` are memos: called here, untracked, the slot would
    // keep their first value; the insert tracks them.
    let (signal, memo) = reactive::signal_kind(cx, value);
    // SAFETY: an inline check; a component is called untracked.
    unsafe {
        if qjs::JS_IsFunction(cx, value) && dom::node_id(cx, value).is_none() && !signal && !memo {
            let mut args = [qjs::JS_NewObject(cx)];
            let r = reactive::untracked_with(cx, || {
                qjs::JS_Call(cx, value, UNDEFINED, 1, args.as_mut_ptr())
            });
            qjs::JS_FreeValue(cx, args[0]);
            qjs::JS_FreeValue(cx, value);
            return r;
        }
    }
    value
}

/// A cell of role `role` (`header`, `footer`) showing `props[key]`, made as
/// a root under the list's owner; returns the root.
fn extra_cell(cx: *mut JsContext, id: NodeId, role: &str, key: &str) -> Result<u32, JsValue> {
    let (props, list, owner) = {
        let map = lists(cx).map.borrow();
        let d = &map[&id];
        (d.props, d.node, d.owner)
    };
    let (root, r) = reactive::with_root_under(cx, owner, || -> Result<(), JsValue> {
        let cell = dom::create_element(cx, Tag::Cell)?;
        let guard = Guard(cx, cell);
        set(cx, cell, "slot", new_string(cx, role))?;
        dom::insert_node(cx, list, cell, None)?;
        let key = new_string(cx, key);
        let reader = native(cx, slot_run, 0, &mut [props, key]);
        // SAFETY: ours.
        unsafe { qjs::JS_FreeValue(cx, key) };
        let r = dom::insert_value_at(cx, cell, reader, None);
        unsafe { qjs::JS_FreeValue(cx, reader) };
        drop(guard);
        r
    });
    r.map(|()| root)
}

/// A JS value freed when dropped.
struct Guard(*mut JsContext, JsValue);

impl Drop for Guard {
    fn drop(&mut self) {
        // SAFETY: ours.
        unsafe { qjs::JS_FreeValue(self.0, self.1) };
    }
}

fn new_string(cx: *mut JsContext, s: &str) -> JsValue {
    // SAFETY: a new string.
    unsafe { qjs::JS_NewStringLen(cx, s.as_ptr().cast(), s.len() as _) }
}

/// The empty cell's effect: shown while there are no items. Its state is
/// an array: [owner, cell node].
unsafe extern "C" fn empty_run(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: three data values; values got are freed.
    unsafe {
        let (list, props, state) = (*data, *data.add(1), *data.add(2));
        let each = get(cx, props, "each");
        let empty = length(cx, each) == 0;
        qjs::JS_FreeValue(cx, each);
        let shown = length(cx, state) > 0;
        if empty && !shown {
            let Some(id) = dom::node_id(cx, list) else {
                return UNDEFINED;
            };
            let owner = lists(cx).map.borrow().get(&id).map(|d| d.owner);
            let Some(owner) = owner else {
                return UNDEFINED;
            };
            let mut cell_node = UNDEFINED;
            let (root, r) = reactive::untracked_with(cx, || {
                reactive::with_root_under(cx, owner, || -> Result<(), JsValue> {
                    let cell = dom::create_element(cx, Tag::Cell)?;
                    cell_node = cell;
                    set(cx, cell, "slot", new_string(cx, "empty"))?;
                    dom::insert_node(cx, list, cell, None)?;
                    let key = new_string(cx, "empty");
                    let reader = native(cx, slot_run, 0, &mut [props, key]);
                    qjs::JS_FreeValue(cx, key);
                    let r = dom::insert_value_at(cx, cell, reader, None);
                    qjs::JS_FreeValue(cx, reader);
                    r
                })
            });
            if let Some(d) = lists(cx).map.borrow_mut().get_mut(&id) {
                d.empty = Some(root);
            }
            qjs::JS_SetPropertyUint32(cx, state, 0, qjs::JS_NewFloat64(root as f64));
            qjs::JS_SetPropertyUint32(cx, state, 1, cell_node);
            if let Err(e) = r {
                return e;
            }
        } else if !empty && shown {
            let owner = qjs::JS_GetPropertyUint32(cx, state, 0);
            let cell = qjs::JS_GetPropertyUint32(cx, state, 1);
            let mut root = 0f64;
            qjs::JS_ToFloat64(cx, &mut root, owner);
            if let Some(id) = dom::node_id(cx, list)
                && let Some(d) = lists(cx).map.borrow_mut().get_mut(&id)
            {
                d.empty = None;
            }
            reactive::dispose_owner(cx, root as u32);
            let r = dom::remove_node(cx, list, cell);
            qjs::JS_FreeValue(cx, cell);
            qjs::JS_FreeValue(cx, owner);
            qjs::JS_SetPropertyStr(cx, state, c"length".as_ptr(), qjs::JS_NewFloat64(0.0));
            if let Err(e) = r {
                return e;
            }
        }
        UNDEFINED
    }
}

/// Answers the core's request for rows: `(slot, item index)` pairs. `None`
/// when `list` is not one of these lists.
pub(crate) fn bind(
    cx: *mut JsContext,
    list: NodeId,
    binds: &[(u32, u32)],
) -> Option<Result<(), ()>> {
    if !lists(cx).map.borrow().contains_key(&list) {
        return None;
    }
    let mut failed = false;
    reactive::batch_with(cx, || {
        for &(slot, index) in binds {
            let existing = lists(cx)
                .map
                .borrow()
                .get(&list)
                .and_then(|d| d.cells.get(slot as usize))
                .and_then(|c| c.as_ref().map(|c| c.index));
            match existing {
                Some(signal) => {
                    if reactive::peek_number(cx, signal) != Some(index as f64) {
                        reactive::set_signal(cx, signal, qjs::JS_NewFloat64(index as f64));
                    }
                }
                // The data shrank after the core asked for this row: a new
                // cell has no previous item to fall back on, so make none.
                // The core unbinds the slot once it sees the new count.
                None if !in_range(cx, list, index) => {}
                None => {
                    if let Err(e) = make_cell(cx, list, slot, index) {
                        // SAFETY: the pending exception is reported below.
                        let _ = e;
                        failed = true;
                    }
                }
            }
        }
    });
    let r = reactive::finish_value(cx, UNDEFINED);
    // SAFETY: an inline tag check.
    if unsafe { qjs::JS_IsException(r) } {
        failed = true;
    }
    // After the batch: the cells' new content is in the queue already.
    for &(slot, index) in binds {
        let node = lists(cx)
            .map
            .borrow()
            .get(&list)
            .and_then(|d| d.cells.get(slot as usize))
            .and_then(|c| c.as_ref().map(|c| c.node));
        if let Some(node) = node
            && set(cx, node, "cellIndex", qjs::JS_NewFloat64(index as f64)).is_err()
        {
            failed = true;
        }
    }
    Some(if failed { Err(()) } else { Ok(()) })
}

/// Whether `index` is within the list's current data.
fn in_range(cx: *mut JsContext, list: NodeId, index: u32) -> bool {
    let Some(items) = lists(cx).map.borrow().get(&list).map(|d| d.items) else {
        return false;
    };
    // SAFETY: the items getter, called untracked; the result is freed.
    let each = reactive::untracked_with(cx, || unsafe {
        qjs::JS_Call(cx, items, UNDEFINED, 0, ptr::null_mut())
    });
    let len = length(cx, each);
    unsafe { qjs::JS_FreeValue(cx, each) };
    (index as i64) < len
}

/// A new cell for `slot`, showing item `first`.
fn make_cell(cx: *mut JsContext, list: NodeId, slot: u32, first: u32) -> Result<(), JsValue> {
    let (props, items, list_node, owner) = {
        let map = lists(cx).map.borrow();
        let d = &map[&list];
        (d.props, d.items, d.node, d.owner)
    };
    let mut made = None;
    let (root, r) = reactive::with_root_under(cx, owner, || -> Result<(), JsValue> {
        let index = reactive::new_signal(cx, qjs::JS_NewFloat64(first as f64));
        let item_fn = native(cx, item_run, 0, &mut [items, index]);
        let item = reactive::memo(cx, item_fn, false);
        let cell = dom::create_element(cx, Tag::Cell)?;
        made = Some((cell, index));
        set(cx, cell, "slot", qjs::JS_NewFloat64(slot as f64))?;
        dom::insert_node(cx, list_node, cell, None)?;
        let children = get(cx, props, "children");
        let mut args = [item, index];
        // SAFETY: the row function, called untracked; values are freed.
        let content = reactive::untracked_with(cx, || unsafe {
            qjs::JS_Call(cx, children, UNDEFINED, 2, args.as_mut_ptr())
        });
        unsafe {
            qjs::JS_FreeValue(cx, children);
            qjs::JS_FreeValue(cx, item);
            if qjs::JS_IsException(content) {
                return Err(content);
            }
        }
        let r = if has(cx, props, "separator") {
            // SAFETY: a placeholder for the separator once made.
            let holder = unsafe { qjs::JS_NewArray(cx) };
            let owner = qjs::JS_NewFloat64(reactive::current_owner(cx) as f64);
            let between = native(
                cx,
                separated_run,
                0,
                &mut [content, props, index, holder, owner],
            );
            unsafe { qjs::JS_FreeValue(cx, holder) };
            let r = dom::insert_value_at(cx, cell, between, None);
            unsafe { qjs::JS_FreeValue(cx, between) };
            r
        } else {
            dom::insert_value_at(cx, cell, content, None)
        };
        unsafe { qjs::JS_FreeValue(cx, content) };
        r
    });
    if let Some((node, index)) = made {
        let mut map = lists(cx).map.borrow_mut();
        match map.get_mut(&list) {
            Some(d) => {
                let slot = slot as usize;
                if d.cells.len() <= slot {
                    d.cells.resize_with(slot + 1, || None);
                }
                d.cells[slot] = Some(Cell {
                    node,
                    index,
                    owner: root,
                });
            }
            None => {
                drop(map);
                // SAFETY: ours (the list went meanwhile).
                unsafe {
                    qjs::JS_FreeValue(cx, node);
                    qjs::JS_FreeValue(cx, index);
                }
            }
        }
    }
    r
}

/// A cell's item: `items()[index()]`, or the last one past the end (the
/// data shrank before the core unbound the cell).
unsafe extern "C" fn item_run(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: two data values; values got are freed or returned.
    unsafe {
        let (items, index) = (*data, *data.add(1));
        let i = qjs::JS_Call(cx, index, UNDEFINED, 0, ptr::null_mut());
        let mut n = 0f64;
        qjs::JS_ToFloat64(cx, &mut n, i);
        qjs::JS_FreeValue(cx, i);
        let each = qjs::JS_Call(cx, items, UNDEFINED, 0, ptr::null_mut());
        let len = length(cx, each);
        let r = if n >= 0.0 && (n as i64) < len {
            qjs::JS_GetPropertyInt64(cx, each, n as i64)
        } else {
            qjs::JS_DupValue(cx, arg(argc, argv, 0))
        };
        qjs::JS_FreeValue(cx, each);
        r
    }
}

/// A row with a separator after it (before it in an inverted list), but
/// the last one.
unsafe extern "C" fn separated_run(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    // SAFETY: five data values; values got are freed or returned.
    unsafe {
        let (content, props, index, holder) = (*data, *data.add(1), *data.add(2), *data.add(3));
        let i = qjs::JS_Call(cx, index, UNDEFINED, 0, ptr::null_mut());
        let mut n = 0f64;
        qjs::JS_ToFloat64(cx, &mut n, i);
        qjs::JS_FreeValue(cx, i);
        let each = get(cx, props, "each");
        let len = length(cx, each);
        qjs::JS_FreeValue(cx, each);
        let component = get(cx, props, "separator");
        let shown =
            (n as i64) < len - 1 && !qjs::JS_IsNull(component) && !qjs::JS_IsUndefined(component);
        if !shown {
            qjs::JS_FreeValue(cx, component);
            return qjs::JS_DupValue(cx, content);
        }
        let mut separator = qjs::JS_GetPropertyUint32(cx, holder, 0);
        if qjs::JS_IsUndefined(separator) {
            let mut owner = 0f64;
            qjs::JS_ToFloat64(cx, &mut owner, *data.add(4));
            qjs::JS_FreeValue(cx, component);
            // The cached separator lives with the cell, not this rerunning
            // computation: so does what its getter makes (an `<If>`'s memo).
            separator = nsh_core::reactive::with_owner(reactive::Js(cx), owner as u32, || {
                slot(cx, get(cx, props, "separator"))
            });
            if qjs::JS_IsException(separator) {
                return separator;
            }
            qjs::JS_SetPropertyUint32(cx, holder, 0, qjs::JS_DupValue(cx, separator));
        } else {
            qjs::JS_FreeValue(cx, component);
        }
        let inverted = get(cx, props, "inverted");
        let inverted_now = reactive::untracked_with(cx, || qjs::JS_ToBool(cx, inverted) == 1);
        qjs::JS_FreeValue(cx, inverted);
        let mut pair = if inverted_now {
            [separator, qjs::JS_DupValue(cx, content)]
        } else {
            [qjs::JS_DupValue(cx, content), separator]
        };
        qjs::JS_NewArrayFrom(cx, 2, pair.as_mut_ptr())
    }
}

// --- Viewability ------------------------------------------------------------------

unsafe extern "C" fn on_viewable(
    cx: *mut JsContext,
    _this: JsValue,
    argc: c_int,
    argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    let mut id = 0f64;
    // SAFETY: one data value (the list id); the event's fields are read.
    unsafe { qjs::JS_ToFloat64(cx, &mut id, *data) };
    let id = id as NodeId;
    let event = arg(argc, argv, 0);
    let read = |key: &str| {
        let v = get(cx, event, key);
        let mut n = -1f64;
        // SAFETY: converting a live value; freed after.
        unsafe {
            qjs::JS_ToFloat64(cx, &mut n, v);
            qjs::JS_FreeValue(cx, v);
        }
        n as i64
    };
    let latest = (read("first"), read("last"));
    let props = {
        let mut map = lists(cx).map.borrow_mut();
        let Some(d) = map.get_mut(&id) else {
            return UNDEFINED;
        };
        d.latest = latest;
        // SAFETY: a dup for the reads below.
        unsafe { qjs::JS_DupValue(cx, d.props) }
    };
    let config = get(cx, props, "viewabilityConfig");
    let wait = get(cx, config, "minimumViewTime");
    let mut ms = 0f64;
    // SAFETY: values got are freed.
    unsafe {
        qjs::JS_ToFloat64(cx, &mut ms, wait);
        qjs::JS_FreeValue(cx, wait);
        qjs::JS_FreeValue(cx, config);
        qjs::JS_FreeValue(cx, props);
    }
    if ms.is_nan() || ms <= 0.0 {
        return report(cx, id);
    }
    // Reported once the range stayed `minimumViewTime`.
    let previous = lists(cx)
        .map
        .borrow_mut()
        .get_mut(&id)
        .and_then(|d| d.timer.take());
    let timers = |name: &CStr, args: &mut [JsValue]| -> JsValue {
        // SAFETY: calls a global timer function; values are freed.
        unsafe {
            let global = qjs::JS_GetGlobalObject(cx);
            let f = qjs::JS_GetPropertyStr(cx, global, name.as_ptr());
            let r = qjs::JS_Call(cx, f, UNDEFINED, args.len() as c_int, args.as_mut_ptr());
            qjs::JS_FreeValue(cx, f);
            qjs::JS_FreeValue(cx, global);
            r
        }
    };
    if let Some(timer) = previous {
        let r = timers(c"clearTimeout", &mut [qjs::JS_NewFloat64(timer)]);
        unsafe { qjs::JS_FreeValue(cx, r) };
    }
    let fire = native(cx, report_later, 0, &mut [qjs::JS_NewFloat64(id as f64)]);
    let timer = timers(c"setTimeout", &mut [fire, qjs::JS_NewFloat64(ms)]);
    let mut t = 0f64;
    // SAFETY: values made here are freed.
    unsafe {
        qjs::JS_FreeValue(cx, fire);
        qjs::JS_ToFloat64(cx, &mut t, timer);
        qjs::JS_FreeValue(cx, timer);
    }
    if let Some(d) = lists(cx).map.borrow_mut().get_mut(&id) {
        d.timer = Some(t);
    }
    UNDEFINED
}

unsafe extern "C" fn report_later(
    cx: *mut JsContext,
    _this: JsValue,
    _argc: c_int,
    _argv: *mut JsValue,
    _magic: c_int,
    data: *mut JsValue,
) -> JsValue {
    let mut id = 0f64;
    // SAFETY: one data value (the list id).
    unsafe { qjs::JS_ToFloat64(cx, &mut id, *data) };
    if let Some(d) = lists(cx).map.borrow_mut().get_mut(&(id as NodeId)) {
        d.timer = None;
    }
    report(cx, id as NodeId)
}

/// Calls `onViewableItemsChange` with the items now viewable and those
/// that changed, unless the range is the one reported last.
fn report(cx: *mut JsContext, id: NodeId) -> JsValue {
    let (props, (first, last), (prev_first, prev_last)) = {
        let mut map = lists(cx).map.borrow_mut();
        let Some(d) = map.get_mut(&id) else {
            return UNDEFINED;
        };
        if d.latest == d.reported {
            return UNDEFINED;
        }
        let r = (
            // SAFETY: a dup for the reads below.
            unsafe { qjs::JS_DupValue(cx, d.props) },
            d.latest,
            d.reported,
        );
        d.reported = d.latest;
        r
    };
    let each = get(cx, props, "each");
    let key_of = get(cx, props, "keyExtractor");
    let len = length(cx, each);
    // SAFETY: tokens are new objects; values got are freed or moved.
    let token = |index: i64, viewable: bool| -> JsValue {
        unsafe {
            let item = qjs::JS_GetPropertyInt64(cx, each, index);
            let key = if qjs::JS_IsFunction(cx, key_of) {
                let mut args = [item, qjs::JS_NewFloat64(index as f64)];
                qjs::JS_Call(cx, key_of, UNDEFINED, 2, args.as_mut_ptr())
            } else {
                let mut k = get(cx, item, "key");
                if qjs::JS_IsUndefined(k) || qjs::JS_IsNull(k) {
                    qjs::JS_FreeValue(cx, k);
                    k = get(cx, item, "id");
                }
                if qjs::JS_IsUndefined(k) || qjs::JS_IsNull(k) {
                    qjs::JS_FreeValue(cx, k);
                    k = qjs::JS_NewFloat64(index as f64);
                }
                let s = qjs::JS_ToString(cx, k);
                qjs::JS_FreeValue(cx, k);
                s
            };
            let o = qjs::JS_NewObject(cx);
            qjs::JS_SetPropertyStr(cx, o, c"item".as_ptr(), item);
            qjs::JS_SetPropertyStr(cx, o, c"key".as_ptr(), key);
            qjs::JS_SetPropertyStr(cx, o, c"index".as_ptr(), qjs::JS_NewFloat64(index as f64));
            qjs::JS_SetPropertyStr(
                cx,
                o,
                c"isViewable".as_ptr(),
                if viewable {
                    qjs::JS_TRUE
                } else {
                    qjs::JS_FALSE
                },
            );
            o
        }
    };
    let mut viewable = Vec::new();
    let mut changed = Vec::new();
    if first >= 0 {
        for i in first..=last.min(len - 1) {
            viewable.push(token(i, true));
            if i < prev_first || i > prev_last {
                changed.push(token(i, true));
            }
        }
    }
    if prev_first >= 0 {
        for i in prev_first..=prev_last.min(len - 1) {
            if i < first || i > last {
                changed.push(token(i, false));
            }
        }
    }
    // SAFETY: the info object takes the arrays; the handler is called and
    // values are freed.
    unsafe {
        let info = qjs::JS_NewObject(cx);
        let mut v = viewable;
        let mut c = changed;
        qjs::JS_SetPropertyStr(
            cx,
            info,
            c"viewableItems".as_ptr(),
            qjs::JS_NewArrayFrom(cx, v.len() as c_int, v.as_mut_ptr()),
        );
        qjs::JS_SetPropertyStr(
            cx,
            info,
            c"changed".as_ptr(),
            qjs::JS_NewArrayFrom(cx, c.len() as c_int, c.as_mut_ptr()),
        );
        let handler = get(cx, props, "onViewableItemsChange");
        let mut args = [info];
        let r = if qjs::JS_IsFunction(cx, handler) {
            qjs::JS_Call(cx, handler, UNDEFINED, 1, args.as_mut_ptr())
        } else {
            UNDEFINED
        };
        for v in [handler, info, each, key_of, props] {
            qjs::JS_FreeValue(cx, v);
        }
        r
    }
}

/// `nsh`'s `List` (its tags compile to `nsh:rt`'s `list`, the same
/// function).
pub(crate) const EXPORTS: &[crate::modules::Item] = &[(
    "List",
    crate::modules::Export::Function(list, 1),
    crate::modules::Ts::function(
        "A virtualized, recycling list on a native scroll view (or, with\n\
         `viewport=\"parent\"`, in the scroll view around it). Only rows near the\n\
         viewport exist; the native side decides which, and cells are reused.\n\
         Positions, columns, sticky headers and viewability are computed natively.\n\n\
         Rows are recycled: keep per-item state in your data (keyed by id), not in\n\
         signals created inside the row.",
        &["<T>(props: ListProps<T>): JSX.Element"],
    ),
)];

/// `List`'s types.
pub(crate) const TYPES: &str = r#"/** A component (`Header`) or an element (`<Header />`). */
export type ListSlot = (() => JSX.Element) | JSX.Element;

/** An item that became viewable or stopped being viewable. */
export interface ViewToken<T> {
  item: T;
  key: string;
  index: number;
  isViewable: boolean;
}

export interface ViewabilityConfig {
  /** How much of the viewport an item must cover to count as viewable, from 0 to 1. */
  viewAreaCoverageThreshold?: number;
  /** How much of an item must be visible, from 0 to 1. Without either threshold, any visible pixel counts. */
  itemVisibleThreshold?: number;
  /** Milliseconds items must stay viewable before they are reported. */
  minimumViewTime?: number;
}

/** A list's props: its own, and those of the scroll view it is (the test
 * id, accessibility, classes, touch and layout events, ...), which it
 * passes on as they are. */
export interface ListProps<T> extends Omit<ViewProps, "children" | "ref">, ScrollingHostProps, ListHostProps {
  each: readonly T[];
  /** Above the items, scrolling with them. */
  header?: ListSlot;
  /** Below the items, scrolling with them. */
  footer?: ListSlot;
  /** Shown instead of the items while `each` is empty. */
  empty?: ListSlot;
  /** Rendered between items (one column). */
  separator?: ListSlot;
  /** Scrolls to this item before the first frame. */
  initialScrollIndex?: number;
  /** Opens at the end before the first frame, following it while rows measure.
   * Short content stays at the top. Takes precedence over initialScrollIndex. */
  initialScrollAtEnd?: boolean;
  /** The item's key: changes are matched by it, so a row that moves keeps its cell (default: the item's
   * identity), and `onViewableItemsChange` tokens name the item by it (default: `item.key`, `item.id`, or the index). */
  keyExtractor?: (item: T, index: number) => string;
  onViewableItemsChange?: (info: { viewableItems: ViewToken<T>[]; changed: ViewToken<T>[] }) => void;
  style?: StyleProp<ViewStyle>;
  /** Padding and gaps of the content as classes (`p-*`, `gap-*`);
   * `contentStyle` wins over them. */
  contentClass?: string;
  /** The id UI tests find the list's scroll view by (`nsh test`'s `id:`, XCUITest, UI Automator). */
  testID?: string;
  /** How close to the end (in viewports) `onLoadMore` fires; default 1. */
  loadMoreThreshold?: number;
  /** The start came within `loadMoreAtStartThreshold` viewports, after the
   * user or a scroll command moved the list: load what comes before the
   * first item (a chat's newer messages). Once per approach. */
  onLoadMoreAtStart?: () => void;
  /** How close to the start (in viewports) `onLoadMoreAtStart` fires; default 1. */
  loadMoreAtStartThreshold?: number;
  ref?: ListRef | ((node: ListRef) => void);
  /** Renders one row. Called once per recycled cell; `item` and `index`
   * change when the cell is reused for another item. */
  children: (item: () => T, index: () => number) => JSX.Element;
}

/** What an app passes to a Rust component that lays out a list of rows
 * (an `Items` prop): the data and the rows; the component decides the
 * layout. */
export type ListItemsProps<T> = Pick<ListProps<T>, "each" | "children" | "keyExtractor" | "stickyHeaderIndices" | "initialScrollIndex" | "initialScrollAtEnd" | "onViewableItemsChange" | "viewabilityConfig" | "refreshing" | "onRefresh" | "onLoadMore" | "loadMoreThreshold" | "header" | "footer" | "empty">;
"#;

#[cfg(test)]
mod tests {
    use nsh_core::{
        Op, Prop,
        list_diff::{DiffRun, ListDiff},
    };

    use crate::{Host, HostOptions};

    #[test]
    fn initial_end_takes_precedence_and_false_preserves_the_index() {
        let host = Host::with_options(HostOptions::default()).unwrap();
        host.eval_source(r#"
            import { List } from "nsh";
            List({ each: [0], children: () => null, initialScrollAtEnd: true, initialScrollIndex: 0 });
            List({ each: [0], children: () => null, initialScrollAtEnd: false, initialScrollIndex: 7 });
            List({ each: [], children: () => null, initialScrollAtEnd: false });
        "#).unwrap();
        let mut ops = Vec::new();
        host.take_ops(&mut ops);
        let commands: Vec<_> = ops
            .into_iter()
            .filter_map(|op| match op {
                nsh_core::Op::Command { command, .. } => Some(command),
                _ => None,
            })
            .collect();
        assert!(matches!(
            commands.as_slice(),
            [
                nsh_core::Command::ScrollToEnd { animated: false },
                nsh_core::Command::ScrollToIndex {
                    index: 7,
                    animated: false,
                    ..
                },
            ]
        ));
    }

    #[test]
    fn cached_separators_keep_their_cell_owner() {
        let host = Host::with_options(HostOptions::default()).unwrap();
        host.with_raw(|raw| {
            // SAFETY: the host owns the live context for this closure.
            let cx = unsafe { rquickjs::Ctx::from_raw(std::ptr::NonNull::new_unchecked(raw)) };
            crate::reactive::install_globals(&cx);
        });
        host.eval_source(
            r#"
            import { List, signal, cleanup, effect } from "nsh";
            import { text } from "nsh:rt";
            const items = signal(["a", "b", "c", "d"].map(id => ({ id })));
            const color = signal("red");
            const state = globalThis.separators = { made: 0, cleaned: 0, colors: [], items, color };
            state.dispose = __nsh_reactive.createRoot(dispose => {
                List({
                    get each() { return items(); },
                    keyExtractor: item => item.id,
                    children: item => text(item().id),
                    separator: () => {
                        const id = state.made++;
                        cleanup(() => state.cleaned++);
                        effect(() => { state.colors[id] = color(); });
                        return text("-");
                    },
                });
                return dispose;
            });
            "#,
        )
        .unwrap();
        let mut ops = Vec::new();
        host.take_ops(&mut ops);
        let list = ops
            .iter()
            .find_map(|op| match op {
                nsh_core::Op::Create {
                    id,
                    tag: nsh_core::Tag::List,
                } => Some(*id),
                _ => None,
            })
            .unwrap();
        host.bind_list(list, &[(0, 0), (1, 1), (2, 2), (3, 3)]);
        let check = |source| {
            assert!(
                host.eval_script("separator-lifetime", source).unwrap(),
                "{source}"
            )
        };
        check("separators.made === 3 && separators.cleaned === 0");
        check(
            "separators.items.set(separators.items().map(item => ({...item}))); separators.cleaned === 0",
        );
        check("separators.color.set('blue'); separators.colors.join() === 'blue,blue,blue'");
        // Reordering and reusing a cell for the last row only hide its cached separator.
        check("separators.items.set([...separators.items()].reverse()); separators.cleaned === 0");
        host.bind_list(list, &[(0, 3), (1, 2), (2, 1), (3, 0)]);
        check("separators.made === 4 && separators.cleaned === 0");
        check("separators.items.set(separators.items().slice(0, 1)); separators.cleaned === 0");
        check(
            "separators.color.set('green'); separators.colors.join() === 'green,green,green,green'",
        );
        check(
            "separators.items.set(['a', 'b', 'c', 'd'].map(id => ({id}))); separators.made === 4",
        );
        host.bind_list(list, &[(0, 0), (1, 1), (2, 2), (3, 3)]);
        check("separators.made === 4 && separators.cleaned === 0");
        check("separators.dispose(); separators.cleaned === 4");
        check("separators.dispose(); separators.cleaned === 4");
        check(
            "separators.color.set('black'); separators.colors.join() === 'green,green,green,green'",
        );
    }

    /// Binds the core asked for before the data shrank: a new cell past the
    /// end is not made (its row would read `undefined`), a recycled one keeps
    /// its last item, and the slot binds normally once the data grows again.
    #[test]
    fn binds_past_the_end_after_the_data_shrank_make_no_cell() {
        let host = Host::with_options(HostOptions::default()).unwrap();
        host.eval_source(
            r#"
            import { List, mount, signal } from "nsh";
            import { text } from "nsh:rt";
            const all = Array.from({ length: 6 }, (_, i) => ({ id: `r${i}` }));
            const items = signal(all);
            const state = globalThis.shrink = { all, items, made: 0, undef: 0 };
            mount(() => List({
                get each() { return items(); },
                keyExtractor: item => item.id,
                children: item => {
                    state.made++;
                    return text(() => {
                        const it = item();
                        if (it === undefined) { state.undef++; return ""; }
                        return it.id;
                    });
                },
            }));
            "#,
        )
        .unwrap();
        let mut ops = Vec::new();
        host.take_ops(&mut ops);
        let list = ops
            .iter()
            .find_map(|op| match op {
                Op::Create {
                    id,
                    tag: nsh_core::Tag::List,
                } => Some(*id),
                _ => None,
            })
            .unwrap();
        let check = |source| assert!(host.eval_script("shrink", source).unwrap(), "{source}");
        host.bind_list(list, &[(0, 0), (1, 1)]);
        check("shrink.made === 2");
        // Shrunk, then the core's pending binds arrive: slots 2..4 are new.
        check("shrink.items.set(shrink.all.slice(0, 2)); true");
        host.bind_list(list, &[(1, 1), (2, 2), (3, 3), (4, 4)]);
        check("shrink.made === 2 && shrink.undef === 0");
        // Cleared: a recycled cell past the end keeps its last item.
        check("shrink.items.set([]); true");
        host.bind_list(list, &[(0, 3), (1, 4)]);
        check("shrink.made === 2 && shrink.undef === 0");
        // Grown again: the skipped slots get cells and existing ones rebind.
        check("shrink.items.set(shrink.all); true");
        host.bind_list(list, &[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]);
        check("shrink.made === 6 && shrink.undef === 0");
        // Scrolled: cells are reused for other rows, none made.
        host.bind_list(list, &[(0, 5), (1, 4)]);
        check("shrink.made === 6 && shrink.undef === 0");
    }

    /// A list's slots are its own: it makes each once and never passes
    /// them to its scroll view (as compiled JSX passes them: getters that
    /// make the slot's elements each time they are read).
    #[test]
    fn a_lists_slots_stay_with_the_list() {
        let host = Host::with_options(HostOptions::default()).unwrap();
        host.eval_source(
            "import { mount } from \"nsh\";\n\
             import { text } from \"nsh:rt\";\n\
             import { List } from \"nsh\";\n\
             mount(() => List({\n\
               each: [1, 2],\n\
               children: (n) => text(`Row ${n()}`),\n\
               get header() { return text(\"Head\"); },\n\
               get footer() { return text(\"Foot\"); },\n\
               get empty() { return text(\"None\"); },\n\
               get separator() { return () => text(\"-\"); },\n\
             }));",
        )
        .unwrap();
        for name in ["header", "footer", "empty", "separator"] {
            assert!(
                !host.warned(&format!("unsupported prop `{name}`")),
                "`{name}` went to the scroll view"
            );
        }
        let mut ops = Vec::new();
        host.take_ops(&mut ops);
        let made = |wanted: &str| {
            ops.iter()
                .filter(
                    |op| matches!(op, nsh_core::Op::CreateText { text, .. } if &**text == wanted),
                )
                .count()
        };
        assert_eq!((made("Head"), made("Foot")), (1, 1));
    }

    /// Rows rebuilt as new objects with the same keys are the same rows:
    /// appending one splices only the new row in.
    #[test]
    fn keyed_rows_rebuilt_with_the_same_keys_splice_only_the_new_row() {
        let host = Host::with_options(HostOptions::default()).unwrap();
        host.eval_source(
            r#"
            import { List, mount, signal } from "nsh";
            import { text } from "nsh:rt";
            const items = signal(["a", "b", "c"].map(id => ({ id })));
            globalThis.keyed = { items };
            mount(() => List({
                get each() { return items(); },
                keyExtractor: item => item.id,
                children: item => text(item().id),
            }));
            "#,
        )
        .unwrap();
        let mut ops = Vec::new();
        host.take_ops(&mut ops);
        ops.clear();
        assert!(
            host.eval_script(
                "keyed-append",
                "keyed.items.set([...keyed.items().map(i => ({...i})), {id: 'd'}]); true",
            )
            .unwrap()
        );
        host.take_ops(&mut ops);
        let diffs = diffs(&ops);
        assert_eq!(diffs.len(), 1, "{diffs:?}");
        assert_eq!(diffs[0].as_splice(), Some((3, 0, 1)), "{diffs:?}");
    }

    /// A window of rows that slides (the first dropped, one appended, rows
    /// rebuilt with the same keys) keeps every row it still shows, not one
    /// change over every row.
    #[test]
    fn a_sliding_window_of_keyed_rows_keeps_the_rows_it_shows() {
        let host = Host::with_options(HostOptions::default()).unwrap();
        host.eval_source(
            r#"
            import { List, mount, signal } from "nsh";
            import { text } from "nsh:rt";
            const items = signal(Array.from({ length: 240 }, (_, i) => ({ id: `r${i}` })));
            globalThis.window = { items, next: 240 };
            mount(() => List({
                get each() { return items(); },
                keyExtractor: item => item.id,
                children: item => text(item().id),
            }));
            "#,
        )
        .unwrap();
        let mut ops = Vec::new();
        host.take_ops(&mut ops);
        ops.clear();
        assert!(
            host.eval_script(
                "keyed-slide",
                "window.items.set([...window.items().slice(1).map(i => ({...i})), {id: `r${window.next++}`}]); true",
            )
            .unwrap()
        );
        host.take_ops(&mut ops);
        let diffs = diffs(&ops);
        assert_eq!(diffs.len(), 1, "{diffs:?}");
        assert_eq!(
            diffs[0].runs,
            [
                DiffRun::Kept { from: 1, len: 239 },
                DiffRun::Inserted { len: 1 }
            ],
        );
    }

    /// Keys that are new objects each time are never `===`: such rows are
    /// all new, however the engine reuses the memory of the keys it has
    /// read.
    #[test]
    fn keys_made_anew_as_objects_never_match() {
        let host = Host::with_options(HostOptions::default()).unwrap();
        host.eval_source(
            r#"
            import { List, mount, signal } from "nsh";
            import { text } from "nsh:rt";
            const items = signal(Array.from({ length: 240 }, (_, i) => ({ id: `r${i}` })));
            globalThis.window = { items, next: 240 };
            mount(() => List({
                get each() { return items(); },
                keyExtractor: item => ({ id: item.id }),
                children: item => text(item().id),
            }));
            "#,
        )
        .unwrap();
        let mut ops = Vec::new();
        host.take_ops(&mut ops);
        ops.clear();
        assert!(
            host.eval_script(
                "object-keys-slide",
                "window.items.set([...window.items().slice(1), {id: `r${window.next++}`}]); true",
            )
            .unwrap()
        );
        host.take_ops(&mut ops);
        let diffs = diffs(&ops);
        assert_eq!(diffs.len(), 1, "{diffs:?}");
        assert_eq!(diffs[0].as_splice(), Some((0, 240, 240)), "{diffs:?}");
    }

    /// A keyed row moved up is one move: the rows it passed stay, and the
    /// cells that show rows follow them to their new indices.
    #[test]
    fn a_keyed_row_moved_up_is_a_move() {
        let host = Host::with_options(HostOptions::default()).unwrap();
        host.eval_source(
            r#"
            import { List, mount, signal } from "nsh";
            import { text } from "nsh:rt";
            const items = signal(Array.from({ length: 12 }, (_, i) => ({ id: `r${i}` })));
            globalThis.moving = { items };
            mount(() => List({
                get each() { return items(); },
                keyExtractor: item => item.id,
                children: item => text(item().id),
            }));
            "#,
        )
        .unwrap();
        let mut ops = Vec::new();
        host.take_ops(&mut ops);
        ops.clear();
        assert!(
            host.eval_script(
                "keyed-move",
                "const rows = moving.items().map(i => ({...i})); \
                 rows.splice(2, 0, ...rows.splice(10, 1)); moving.items.set(rows); true",
            )
            .unwrap()
        );
        host.take_ops(&mut ops);
        let diffs = diffs(&ops);
        assert_eq!(diffs.len(), 1, "{diffs:?}");
        assert_eq!(
            diffs[0].runs,
            [
                DiffRun::Kept { from: 0, len: 2 },
                DiffRun::Moved { from: 10, len: 1 },
                DiffRun::Kept { from: 2, len: 8 },
                DiffRun::Kept { from: 11, len: 1 },
            ],
        );
    }

    fn diffs(ops: &[Op]) -> Vec<ListDiff> {
        ops.iter()
            .filter_map(|op| match op {
                Op::SetProp {
                    prop: Prop::ListDiff(diff),
                    ..
                } => Some((**diff).clone()),
                _ => None,
            })
            .collect()
    }
}