nsh-core 0.6.1

Platform-independent core: shadow tree, styles, layout and mount instructions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
//! Virtualized list state: item sizes, offsets, the render window and cell
//! recycling. Pure bookkeeping; the core feeds it measurements and scroll
//! offsets and applies its decisions to the tree.
//!
//! Positions are computed along the list's main axis in *natural*
//! coordinates (distance from the start of the content: padding, header,
//! items, footer). An inverted list lays the same content out from the end
//! of the scroll view (item 0 at the bottom) and keeps its distance from
//! the end while content changes, like React Native's inverted lists.
//!
//! # Binding cells
//!
//! The window (Fenwick prefix sums over rows) renders one extra screen above
//! and below the viewport. The core asks JS to bind cells with
//! `__nsh_list(listId, [slot, index, …])`; JS updates a cell's content inside
//! `batch` and then sets its `cellIndex` to confirm, and only confirmed cells
//! are measured and positioned. New cells are created with their first
//! index. The engine runs at most 8 "bind → JS → layout" rounds per frame,
//! merged into one batch.
//!
//! A slot remembers the item JS was last asked to show (`requested`), so
//! what is still to bind is always derived from the current assignment:
//! nothing stale is queued. Cells whose item moved (a splice) learn their
//! new index in the same commit, and so does every cell in the viewport and
//! ahead of it in the scroll direction, as far as the next few frames of
//! the scroll go ([`URGENT_STEPS`]): the rows bound now reach the screen a
//! frame or two later, after the engine's turn and the main thread's. A list with `paced` set (the
//! runtime's) leaves the rest of the overscan pending: the engine binds it
//! with `take_paced`, nearest the leading edge first, as its per-turn
//! budget allows, and asks for a display frame while some is left.
//!
//! Row-local state travels with recycled cells, so
//! apps keep it outside, keyed by id. Unbound cells keep their last content:
//! the core moves those in the render window out of sight (never with a NaN
//! frame; cells never placed are skipped) and hides them from touches and
//! screen readers until they are placed again (`Core::set_spare`). An item
//! shows in one cell at most: a cell whose item went reads the item now at
//! its old index, which is its own unless another cell moved there with
//! it; then the components' lists let its content go before it reads
//! there, and it is the first cell a new item takes. The
//! header, footer and empty placeholder are cells with a role
//! (`slot="header"`, ...) and are never recycled. Each cell is a Taffy root
//! of its own (its width follows the list's cross axis), so scrolling
//! relays out dirty cells only.
//!
//! # Scroll commands
//!
//! `scrollToEnd` / `scrollToIndex` resolve with estimated sizes for rows
//! never rendered, so the first offset is off. Their target stays pinned:
//! after each round of measurements the list follows it (`follow_pin`),
//! retargeting an animated scroll in flight, until the rows in the
//! viewport are measured, the user scrolls away or the items change. The
//! End key of the desktops and the web is one of them (`Core::key_scrolled`):
//! the platform animates to the end it knows, the list follows the real
//! one, and any other scroll key leaves the target. An animated scroll
//! that moves away from its target once every scroll the core issued is
//! applied was taken over by the user (a wheel, a drag, the scroll bar).
//!
//! # In its parent's viewport
//!
//! A list with `viewport="parent"` has no scroll view of its own: it lies in
//! its parent's layout at its full length (a layout-only Taffy child, the
//! spacer, is `content_len` long) and is virtualized against the nearest
//! scroll view around it on its axis, or the root view it is in
//! ([`Outer`]). The core feeds the state that view's offset less the
//! list's start in its content (negative while the list starts below the
//! viewport's start) and that view's viewport, so the window, `onLoadMore`
//! and viewability work in the list's coordinates as they do for a list
//! of its own. The scroll view moves only for changes wholly above the top
//! of its viewport, as a browser's scroll anchoring does: rows measured or
//! spliced above the first visible row while the list's start is scrolled
//! past. Inverted lists and `maintainVisibleContentPosition` need a scroll
//! view of their own and are off. Sticky rows stick to the view's viewport:
//! their ranges are in its offsets, and the last one stops at the end of
//! the list's content, as CSS `position: sticky` stops at its container's.

use rustc_hash::FxHashMap;

use crate::{
    fenwick::Fenwick,
    list_diff::ListDiff,
    ops::{CellSlot, ListAlignment, ListContentStyle, Viewability},
};

/// How far beyond the viewport cells are kept rendered, in viewports.
const OVERSCAN: f32 = 1.0;
/// How many of the scroll's recent steps ahead of the viewport bind with
/// the window, not paced: the rows a commit binds show a frame after the
/// report at best (the engine's turn, then the main thread's), two or three
/// when either is busy, and a fling's steps grow and come unevenly (wheel
/// notches, touchpad events bunched into frames). Rows enter this span a
/// step's worth per frame however long it is, so a longer one costs only
/// when a scroll speeds up.
const URGENT_STEPS: f32 = 4.0;
/// What the step [`ListState::urgent_span`] reads keeps of a longer one
/// before it, per report, while the scroll goes the same way: one slow
/// frame between fast ones does not shrink the span.
const LEAD_DECAY: f32 = 0.75;
/// Default `loadMoreThreshold`, in viewports.
const END_THRESHOLD: f32 = 1.0;
/// Default `loadMoreAtStartThreshold`, in viewports.
const START_THRESHOLD: f32 = 1.0;

/// Which of a list's load-more events a window update raises
/// ([`ListState::update_window`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(super) struct Edges {
    /// `onLoadMore`: the end came near.
    pub(super) end: bool,
    /// `onLoadMoreAtStart`: the start came near.
    pub(super) start: bool,
}

/// A recycling slot: one cell node, bound to at most one item.
#[derive(Debug, Clone, Copy)]
pub(super) struct Slot {
    /// Cell node key (`u32::MAX` until the runtime created the cell).
    pub(super) cell: u32,
    /// Item this slot is assigned to.
    pub(super) index: Option<u32>,
    /// Item the cell's content currently shows (confirmed by the runtime).
    pub(super) rendered: Option<u32>,
    /// Item the runtime was last asked to show in this slot (its cell's
    /// index); `None` before the first request or when that item is gone.
    pub(super) requested: Option<u32>,
    /// Item the cell's frame was last placed for: a cell placed for
    /// another one appears there rather than moving from that row's place
    /// under a layout animation (`core/list_motion.rs`).
    pub(super) placed: Option<u32>,
    /// The cell's content was bound to an item that went, and the item now
    /// at its index is another cell's (or there is none): it shows nothing
    /// (a component's list let its content go), or that other cell's item.
    /// Such a cell is the first a new item takes
    /// ([`ListState::adopt_orphans`]).
    pub(super) stale: bool,
}

impl Slot {
    /// True when the cell shows its assigned item, so its size and
    /// position belong to that item.
    pub(super) fn ready(&self) -> Option<u32> {
        match (self.index, self.rendered) {
            (Some(i), Some(r)) if i == r && self.cell != u32::MAX => Some(i),
            _ => None,
        }
    }
}

/// A non-recycled cell: the header, footer or empty placeholder.
#[derive(Debug, Clone, Copy)]
pub(super) struct Extra {
    /// Cell node key, or `u32::MAX`.
    pub(super) cell: u32,
    /// Measured main-axis size (0 until measured).
    pub(super) size: f32,
}

impl Extra {
    const NONE: Self = Self {
        cell: u32::MAX,
        size: 0.0,
    };

    fn present(&self) -> bool {
        self.cell != u32::MAX
    }
}

/// Which extra cell.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum ExtraKind {
    Header = 0,
    Footer = 1,
    Empty = 2,
}

/// Where the blocks of a list's content start, in natural coordinates.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct Blocks {
    pub(super) header: f32,
    /// The first item row (or the empty placeholder).
    pub(super) body: f32,
    pub(super) footer: f32,
    /// Content length: everything plus the end padding.
    pub(super) total: f32,
}

/// A scroll the core asked the platform for, not yet reflected in the
/// offsets it reports.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum PendingScroll {
    By(f32),
    To(f32),
}

/// Where the platform's reported `offset` ends up once the `pending`
/// scrolls (issued, not applied yet) are applied.
pub(super) fn replay(offset: f32, pending: &[(u32, PendingScroll)]) -> f32 {
    let mut at = offset;
    for &(_, scroll) in pending {
        match scroll {
            PendingScroll::By(d) => at += d,
            PendingScroll::To(t) => at = t,
        }
    }
    at
}

/// The step [`ListState::urgent_span`] reads after the platform reported a
/// move of `step` (natural coordinates): the move itself, unless a longer
/// recent one in the same direction outlasts it, decayed by [`LEAD_DECAY`].
/// A jump (longer than the viewport) is not kept: the steps after it bind
/// ahead again at once.
fn next_lead(lead: f32, step: f32, viewport: f32) -> f32 {
    let kept = lead.abs() * LEAD_DECAY;
    if step.signum() == lead.signum() && lead.abs() <= viewport && kept > step.abs() {
        lead.signum() * kept
    } else {
        step
    }
}

/// The view a `viewport="parent"` list is virtualized against: the
/// nearest scroll view around it on its axis, or the root view it is in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Outer {
    /// The view's node key.
    pub(super) view: u32,
    /// It scrolls (a scroll view or a list); a root view does not.
    pub(super) scrolls: bool,
    /// Views between the list and it: lists nearer theirs are updated
    /// first, so a list in a cell of another sees the cell placed.
    pub(super) depth: u32,
}

/// What parent mode turns off ([`ListState::set_parent`]), kept to give
/// back.
#[derive(Debug)]
struct SetAside {
    inverted: bool,
    follow_end: Option<f32>,
    alignment: ListAlignment,
}

/// Props a list in its parent's viewport ignores, each warned of once.
pub(super) mod ignored {
    pub(crate) const INVERTED: u16 = 1 << 0;
    pub(crate) const FOLLOW_END: u16 = 1 << 1;
    pub(crate) const ALIGNMENT: u16 = 1 << 2;
    pub(crate) const ON_SCROLL: u16 = 1 << 3;
    pub(crate) const SCROLL_VALUE: u16 = 1 << 4;
    pub(crate) const REFRESH: u16 = 1 << 5;
    pub(crate) const BEHAVIOR: u16 = 1 << 6;
    pub(crate) const SCROLLBAR: u16 = 1 << 7;
    /// `viewport` changed after the list was made.
    pub(crate) const VIEWPORT: u16 = 1 << 8;
}

/// What a list scroll command asked to show: kept after the command, so
/// the offset follows the target while the cells around it are measured
/// (estimated sizes put the first offset off).
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum PinTarget {
    /// `scrollToEnd`.
    End,
    /// `scrollToIndex`.
    Index {
        index: u32,
        view_position: f32,
        view_offset: f32,
    },
}

/// A pinned scroll target and the offset the list was last sent to for
/// it.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Pin {
    target: PinTarget,
    at: f32,
    /// An animated scroll the platform has not finished: the pin follows
    /// by retargeting it.
    animating: bool,
    /// While animating: the nearest to `at` the platform reported the
    /// list since `at` was set, with every scroll the core issued applied
    /// (infinite before the first such report). The animation only comes
    /// nearer: a report farther away is the user taking over (a wheel, a
    /// drag, the scroll bar).
    nearest: f32,
}

/// How a pinned list follows its target (`ListState::follow_pin`).
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum Follow {
    /// Already there.
    Stay,
    /// Scroll by this much now (with the anchoring `ScrollBy`).
    By(f32),
    /// Retarget the animated scroll to this offset.
    To(f32),
}

/// How far a reported offset may be from a pinned one and still count as
/// the same (platforms round offsets to pixels).
const PIN_SLACK: f32 = 1.0;

/// A sticky cell's range of travel, as scroll offsets along the main axis:
/// from `start` it moves with the scroll offset, as far as `end` (by
/// `clamp(offset - start, 0, end - start)` from where the cell is laid out;
/// without a sticky offset, `start` is that position).
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) struct StickyRange {
    pub(super) cell: u32,
    pub(super) start: f32,
    pub(super) end: f32,
    /// An animated value it sticks further from the viewport's start by.
    pub(super) offset: Option<crate::animation::NodeId>,
}

#[derive(Debug)]
pub(super) struct ListState {
    pub(super) count: u32,
    estimated: f32,
    /// Items per row (`numColumns`).
    pub(super) columns: u32,
    /// Measured main-axis sizes of items; NaN = not measured yet.
    sizes: Vec<f32>,
    /// Row sizes (the largest item of each row) plus the gap after the row.
    rows: Fenwick,
    pub(super) slots: Vec<Slot>,
    by_index: FxHashMap<u32, u32>,
    free: Vec<u32>,
    pub(super) extras: [Extra; 3],
    /// Padding and gaps: `contentStyle`, else `contentClass`'s.
    pub(super) content: ListContentStyle,
    /// `contentStyle` as set.
    content_style: ListContentStyle,
    /// What `contentClass` sets.
    content_class: ListContentStyle,
    pub(super) horizontal: bool,
    /// Shown mirrored (a horizontal list right to left): laid out left to
    /// right, so the content's left padding is its main axis' end.
    mirrored: bool,
    pub(super) inverted: bool,
    /// `maintainVisibleContentPosition`'s `autoscrollToBottomThreshold`:
    /// a list that is not inverted follows the end of its content while
    /// it is within this distance of it.
    pub(super) follow_end: Option<f32>,
    /// Where the list rests ([`ListAlignment`]; an inverted list ignores it).
    pub(super) alignment: ListAlignment,
    /// `stickyHeaderIndices`, sorted.
    pub(super) sticky: Vec<u32>,
    /// Items kept rendered wherever they are (`Core::sync_kept`): those
    /// holding the keyboard focus, an open overlay or an end of a text
    /// selection, which must outlive scrolling away.
    kept: Vec<u32>,
    /// `stickyHeaderOffset`: sticky items stick this far from the
    /// viewport's start.
    sticky_offset: f32,
    /// `stickyHeaderOffset` as an animated value: added to `sticky_offset`
    /// by the platforms as they pin (a header that moves).
    sticky_node: Option<crate::animation::NodeId>,
    /// Sticky ranges last sent to the platform.
    pub(super) sent_sticky: Vec<StickyRange>,
    pub(super) viewability: Viewability,
    /// Last reported viewable items (`first..=last`).
    pub(super) viewable: Option<(u32, u32)>,
    /// `loadMoreThreshold`, in viewports.
    pub(super) end_threshold: f32,
    /// A row grows under a scoped layout animation in this commit
    /// ([`ListState::anchor_end`] does not follow the end it moves).
    pub(super) revealing: bool,
    /// `loadMoreAtStartThreshold`, in viewports.
    pub(super) start_threshold: f32,
    /// Main-axis scroll offset reported by the platform (content
    /// coordinates).
    pub(super) offset: f32,
    /// Main-axis size of the list viewport (from layout).
    pub(super) viewport: f32,
    /// Window, bindings or positions need recomputing.
    pub(super) dirty: bool,
    /// Cross-axis size the cells were last laid out at.
    pub(super) cells_cross: f32,
    load_more_at: Option<u32>,
    /// The count `onLoadMoreAtStart` last fired at while the viewport has
    /// stayed near the start; cleared when it leaves.
    load_more_at_start: Option<u32>,
    /// The list listens to `onLoadMoreAtStart`: an inverted one keeps its
    /// visible rows in place when scrolled away from its start, so the
    /// pages it loads there arrive out of sight (`keeps_visible_rows`).
    pub(super) loads_at_start: bool,
    /// The user or a scroll command moved the list: until then the start
    /// it opens at is not an approach (`onLoadMoreAtStart`).
    moved_by_scroll: bool,
    /// `content_len - viewport` when the offset was last anchored
    /// (inverted lists and `follow_end`; NaN before the first layout).
    anchored_end: f32,
    /// What this layout's measurements asked to scroll so far (the `kept`
    /// that `anchor_end` gets), not yet in `offset`.
    measured_scroll: f32,
    /// Scrolls issued to the platform (`ScrollBy` items and `ScrollTo`
    /// commands); platforms count the ones they applied.
    issued: u32,
    /// Issued scrolls by number, oldest first, until a report shows them
    /// applied.
    pending: Vec<(u32, PendingScroll)>,
    /// Cells whose item moved to another index (a splice): the runtime
    /// learns their new index with the next bindings.
    moved: Vec<(u32, u32)>,
    /// The items changed (a splice, a new count) since the core last
    /// hid the cells without an item: the rows those show may be gone.
    pub(super) items_changed: bool,
    /// Binds of overscan cells wait for the engine's budget
    /// ([`Self::take_paced`]); the rest bind with the window.
    pub(super) paced: bool,
    /// The scroll step the platform reported last, in natural coordinates
    /// (its sign is the scroll direction), or a longer recent one in the
    /// same direction, decayed ([`LEAD_DECAY`]). The core's own moves
    /// (anchoring a splice, measured rows, following a pin) are not steps.
    lead: f32,
    /// Scroll that keeps the visible content in place after a splice or a
    /// change of columns.
    splice_anchor: f32,
    /// The target of the last scroll command, until it is reached with
    /// measured cells or the user scrolls away.
    pin: Option<Pin>,
    /// The animated `scrollToEnd`s the End key queued for the list that
    /// the next update resolves (`Core::key_scrolled`), by their place among
    /// the list's queued commands: another scroll key before that takes
    /// them back.
    pub(super) key_ends: Vec<u32>,
    /// The item the last change of columns kept at the top: while its row
    /// is still the first visible one, the next change keeps it rather than
    /// the row's first item, so resizing back and forth does not drift.
    columns_anchor: Option<u32>,
    /// `viewport="parent"`: virtualized against the view around it.
    pub(super) parent: bool,
    /// The parent mode's view, once found.
    pub(super) outer: Option<Outer>,
    /// Parent mode: where the list's content starts in its view's content
    /// (NaN until placed).
    outer_start: f32,
    /// Parent mode: the list offsets its view can scroll to.
    limits: (f32, f32),
    /// Parent mode: the spacer that gives the list its length in layout,
    /// and the length it was given.
    pub(super) spacer: Option<(taffy::NodeId, f32)>,
    /// What parent mode turned off (`inverted`, `follow_end`), given back
    /// if the list goes back to its own scroll view before it is made.
    set_aside: Option<Box<SetAside>>,
    /// Ignored props set ([`ignored`] bits), and those already warned of.
    pub(super) ignored: u16,
    pub(super) warned: u16,
}

impl ListState {
    pub(super) fn new() -> Self {
        Self {
            count: 0,
            estimated: 50.0,
            columns: 1,
            sizes: Vec::new(),
            rows: Fenwick::default(),
            slots: Vec::new(),
            by_index: FxHashMap::default(),
            free: Vec::new(),
            extras: [Extra::NONE; 3],
            mirrored: false,
            content: ListContentStyle::default(),
            content_style: ListContentStyle::default(),
            content_class: ListContentStyle::default(),
            horizontal: false,
            inverted: false,
            follow_end: None,
            alignment: ListAlignment::Top,
            sticky: Vec::new(),
            kept: Vec::new(),
            sticky_offset: 0.0,
            sticky_node: None,
            sent_sticky: Vec::new(),
            viewability: Viewability::default(),
            viewable: None,
            end_threshold: END_THRESHOLD,
            revealing: false,
            start_threshold: START_THRESHOLD,
            offset: 0.0,
            viewport: 0.0,
            dirty: true,
            cells_cross: f32::NAN,
            load_more_at: None,
            load_more_at_start: None,
            loads_at_start: false,
            moved_by_scroll: false,
            anchored_end: f32::NAN,
            measured_scroll: 0.0,
            issued: 0,
            pending: Vec::new(),
            moved: Vec::new(),
            items_changed: false,
            paced: false,
            lead: 0.0,
            splice_anchor: 0.0,
            pin: None,
            key_ends: Vec::new(),
            columns_anchor: None,
            parent: false,
            outer: None,
            outer_start: f32::NAN,
            limits: (0.0, 0.0),
            spacer: None,
            set_aside: None,
            ignored: 0,
            warned: 0,
        }
    }

    /// Switches to (or from) virtualizing against the view around the
    /// list. What needs a scroll view of its own is turned off and noted
    /// as ignored.
    pub(super) fn set_parent(&mut self, parent: bool) {
        if parent == self.parent {
            return;
        }
        self.parent = parent;
        self.outer = None;
        self.outer_start = f32::NAN;
        self.pin = None;
        self.dirty = true;
        self.anchored_end = f32::NAN;
        if parent {
            let set_aside = SetAside {
                inverted: std::mem::take(&mut self.inverted),
                follow_end: self.follow_end.take(),
                alignment: std::mem::take(&mut self.alignment),
            };
            if set_aside.inverted {
                self.ignored |= ignored::INVERTED;
            }
            if set_aside.follow_end.is_some() {
                self.ignored |= ignored::FOLLOW_END;
            }
            if set_aside.alignment != ListAlignment::Top {
                self.ignored |= ignored::ALIGNMENT;
            }
            self.set_aside = Some(Box::new(set_aside));
        } else if let Some(set_aside) = self.set_aside.take() {
            let SetAside {
                inverted,
                follow_end,
                alignment,
            } = *set_aside;
            self.inverted = inverted;
            self.follow_end = follow_end;
            self.alignment = alignment;
        }
    }

    /// Parent mode: the list starts at `start` of its view's content, the
    /// view is at `offset` with a viewport of `viewport`, and scrolls as
    /// far as `max`; `settled`: none of the scrolls the core issued to it
    /// is pending. Returns whether the list's window moved.
    pub(super) fn set_outer(
        &mut self,
        start: f32,
        offset: f32,
        viewport: f32,
        max: f32,
        settled: bool,
    ) -> bool {
        let shift = start - self.outer_start;
        if shift != 0.0
            && !shift.is_nan()
            && let Some(pin) = &mut self.pin
        {
            // What moved the list in its view is no scroll of the user's.
            pin.at -= shift;
        }
        self.outer_start = start;
        self.limits = (-start, (max - start).max(-start));
        let resized = viewport != self.viewport;
        self.viewport = viewport;
        let before = self.offset;
        self.moved_to(offset - start, settled);
        resized || before != self.offset
    }

    /// `offset` within the offsets the list can be scrolled to.
    pub(super) fn clamped(&self, offset: f32) -> f32 {
        let (min, max) = self.offset_limits();
        offset.clamp(min, max)
    }

    /// The offsets the list can be scrolled to: its own content's, or in
    /// parent mode its view's, in the list's coordinates.
    fn offset_limits(&self) -> (f32, f32) {
        if self.parent {
            self.limits
        } else {
            (0.0, (self.content_len() - self.viewport).max(0.0))
        }
    }

    /// The items changed: `removed` items at `at` were replaced by
    /// `inserted` new ones. Measurements and cells follow the items that
    /// stay, and when the change is above the first visible item of a list
    /// scrolled past its start, the visible content keeps its place
    /// ([`Self::visible_anchor`]).
    pub(super) fn splice(&mut self, at: u32, removed: u32, inserted: u32) {
        let at = at.min(self.count);
        let removed = removed.min(self.count - at);
        if removed == 0 && inserted == 0 {
            return;
        }
        self.items_changed = true;
        // The visible content keeps its place instead.
        self.pin = None;
        let anchor = self
            .visible_anchor()
            .filter(|&(index, _)| index >= at + removed)
            .map(|(index, from_top)| (index - removed + inserted, from_top));
        let natural_before = self.natural_offset();
        let end = (at + removed) as usize;
        self.sizes.splice(
            at as usize..end,
            std::iter::repeat_n(f32::NAN, inserted as usize),
        );
        self.count = self.count - removed + inserted;
        self.follow_items(|i: u32| -> Option<u32> {
            if i < at {
                Some(i)
            } else if i >= at + removed {
                Some(i - removed + inserted)
            } else {
                None
            }
        });
        if removed == 0 && at + inserted == self.count {
            // Appended: the rows before stay as they are.
            self.resize_rows(at);
        } else {
            self.rebuild_offsets();
        }
        self.after_items_changed(anchor, natural_before);
    }

    /// The items changed by key ([`ListDiff`]): each item that stays keeps
    /// its measurement and its cell (the content, the state in it, the
    /// focus) wherever it goes, the items it passes too; only new items
    /// need a cell, and only gone ones free theirs. The first visible item
    /// that kept its order keeps its place, as for a splice: one that moved
    /// away leaves the rows around it where they were.
    pub(super) fn reorder(&mut self, diff: &ListDiff) {
        if diff.old_len != self.count {
            // Not a change of these items: all of them are new.
            self.splice(0, self.count, diff.new_len);
            return;
        }
        if let Some((at, removed, inserted)) = diff.as_splice() {
            self.splice(at, removed, inserted);
            return;
        }
        self.items_changed = true;
        self.pin = None;
        let anchor = self.visible_anchor().and_then(|(first, _)| {
            let top = self.natural_offset();
            let bottom = top + self.viewport;
            (first..self.count)
                .take_while(|&i| self.item_at(i) < bottom)
                .find_map(|i| match diff.new_index(i) {
                    Some((to, false)) => Some((to, self.item_at(i) - top)),
                    _ => None,
                })
        });
        let natural_before = self.natural_offset();
        let mut sizes = Vec::with_capacity(diff.new_len as usize);
        for run in &diff.runs {
            let len = run.len() as usize;
            match run.from().and_then(|from| {
                let from = from as usize;
                self.sizes.get(from..from + len)
            }) {
                Some(measured) => sizes.extend_from_slice(measured),
                None => sizes.resize(sizes.len() + len, f32::NAN),
            }
        }
        self.sizes = sizes;
        self.count = diff.new_len;
        let indices = diff.new_indices();
        self.follow_items(|i| indices.get(i as usize).copied().flatten());
        self.kept.sort_unstable();
        self.rebuild_offsets();
        self.after_items_changed(anchor, natural_before);
    }

    /// The runtime never got the binds of `slots` (their items changed
    /// first): each cell shows what it showed before them, and the window
    /// asks again.
    pub(super) fn unrequest(&mut self, slots: &[u32]) {
        for &slot in slots {
            if let Some(s) = self.slots.get_mut(slot as usize) {
                s.requested = s.rendered;
            }
        }
    }

    /// The items moved as `shift` says (an item's new index, `None` when it
    /// is gone): the cells, the items kept rendered and the rows the
    /// runtime is told follow them.
    fn follow_items(&mut self, shift: impl Fn(u32) -> Option<u32>) {
        self.kept = self.kept.iter().filter_map(|&i| shift(i)).collect();
        self.by_index.clear();
        // New indices not sent yet (items that moved before): the runtime
        // is told where they are now, or nothing for a cell that shows no
        // item of its own any more.
        let unsent = std::mem::take(&mut self.moved);
        // Cells whose item went, with the index their content still reads
        // and whether it showed that item.
        let mut orphans = Vec::new();
        for (slot, s) in self.slots.iter_mut().enumerate() {
            s.placed = s.placed.and_then(&shift);
            let index = s.index.and_then(&shift);
            let Some(new) = index else {
                if s.index.take().is_some() {
                    self.free.push(slot as u32);
                } else if let (Some(r), Some(n)) = (s.requested, s.requested.and_then(&shift))
                    && s.rendered == Some(r)
                {
                    // A free cell still showing an item that stays follows
                    // it (the runtime is told), so the item gets it back.
                    s.requested = Some(n);
                    s.rendered = Some(n);
                    if n != r {
                        self.moved.push((slot as u32, n));
                    }
                    continue;
                }
                // Its item went: its content follows the new data at its
                // old index, and shows the item now there (below). Else it
                // is bound again before it shows.
                if let Some(r) = s.requested.take()
                    && shift(r).is_none()
                {
                    orphans.push((slot, r, s.rendered == Some(r)));
                }
                s.rendered = None;
                continue;
            };
            s.index = Some(new);
            s.rendered = s.rendered.and_then(&shift);
            // The runtime's index for the cell follows its item at once, or
            // its content shows the item now at the old index.
            match s.requested.map(|r| (r, shift(r))) {
                Some((r, Some(n))) => {
                    s.requested = Some(n);
                    if n != r {
                        self.moved.push((slot as u32, n));
                    }
                }
                Some((r, None)) => {
                    orphans.push((slot, r, false));
                    s.requested = None;
                    s.rendered = None;
                }
                None => {}
            }
            self.by_index.insert(new, slot as u32);
        }
        if !orphans.is_empty() {
            self.adopt_orphans(orphans);
        }
        for (slot, _) in unsent {
            if let Some(n) = self.slots[slot as usize].requested
                && !self.moved.iter().any(|&(s, _)| s == slot)
            {
                self.moved.push((slot, n));
            }
        }
        self.free.sort_unstable();
        self.free.dedup();
    }

    /// Cells whose item went (`(slot, index, shown)`: the index their
    /// content reads, and whether it showed the item there) show the item
    /// now at that index. One no other cell shows is that item's (it takes
    /// the cell back as it is, as a spare cell's); one another cell shows
    /// too (an item moved there with its cell) shows nothing, as do those
    /// past the end: the components' lists let its content go before it
    /// reads there (`move_rows` in `core/components.rs`, by the same rule),
    /// and it is the first a new item takes ([`Slot::stale`]).
    fn adopt_orphans(&mut self, orphans: Vec<(usize, u32, bool)>) {
        let mut shown: Vec<u32> = self.slots.iter().filter_map(|s| s.requested).collect();
        shown.sort_unstable();
        for (slot, r, was_shown) in orphans {
            let s = &mut self.slots[slot];
            if r < self.count && shown.binary_search(&r).is_err() {
                s.requested = Some(r);
                s.rendered = was_shown.then_some(r);
                s.stale = false;
            } else {
                s.stale = true;
            }
        }
    }

    /// After the items changed: the first visible item (`anchor`: its new
    /// index and where it showed) keeps its place, from a natural offset of
    /// `natural_before`.
    fn after_items_changed(&mut self, anchor: Option<(u32, f32)>, natural_before: f32) {
        if self.load_more_at.is_some() {
            self.load_more_at = None;
        }
        if let Some((moved_to, from_top)) = anchor {
            if self.inverted {
                // `anchor_end` restores the natural offset the list had;
                // the visible rows need it moved by as much as they did.
                let delta = (self.item_at(moved_to) - from_top).max(0.0) - natural_before;
                self.offset -= delta;
                self.splice_anchor -= delta;
            } else {
                self.keep_in_place(moved_to, from_top);
            }
        }
    }

    /// The first visible item and where it is in the viewport, for a
    /// change that should keep it in place: only while the list is
    /// scrolled past its start, as a browser's scroll anchoring. At the
    /// start, rows that arrive above the first show and push it down (a
    /// filter widened, a feed's new post), unless the list loads pages at
    /// its start: the page it prepends must not show, or the next would be
    /// asked for at once. An inverted list at its start (item 0 in view at
    /// the bottom) keeps its distance from the end instead, so what
    /// arrives there shows. In its parent's viewport, only while the
    /// list's start is scrolled past (when it shows, the content below it
    /// moves instead).
    fn visible_anchor(&self) -> Option<(u32, f32)> {
        (self.count > 0
            && self.viewport > 0.0
            && self.keeps_visible_rows()
            && (self.offset > 0.0 || (!self.parent && self.loads_at_start)))
            .then(|| {
                let top = self.natural_offset();
                let body = self.blocks().body;
                let row = self.rows.find((top - body).max(0.0) as f64) as u32;
                let index = (row * self.columns).min(self.count - 1);
                (index, self.item_at(index) - top)
            })
    }

    /// The row the viewport starts in, by its first item, and how far
    /// past the row's start the viewport starts, in natural coordinates
    /// (`ref.measureScrollPosition()`); `None` without items or a
    /// viewport. Before the first row (a header, padding) it is item 0, a
    /// negative distance away.
    pub(super) fn scroll_position(&self) -> Option<(u32, f32)> {
        if self.count == 0 || self.viewport <= 0.0 {
            return None;
        }
        let top = self.natural_offset();
        let body = self.blocks().body;
        let row = (self.rows.find((top - body).max(0.0) as f64) as u32).min(self.row_count() - 1);
        let index = (row * self.columns).min(self.count - 1);
        Some((index, top - self.item_at(index)))
    }

    /// Scrolls so item `index` starts `from_top` below the viewport's start
    /// again (a list that is not inverted).
    fn keep_in_place(&mut self, index: u32, from_top: f32) {
        let delta = self.item_at(index) - from_top - self.natural_offset();
        self.offset += delta;
        self.splice_anchor += delta;
    }

    /// Whether changes before the viewport keep the visible rows in place:
    /// always for lists that are not inverted. Inverted ones keep their
    /// distance from the end (the bottom), unless they load at their start
    /// (`onLoadMoreAtStart`, which opts in) and are laid out and scrolled
    /// away from it: at the start they keep showing item 0 (a chat's newest
    /// message).
    fn keeps_visible_rows(&self) -> bool {
        self.keeps_visible_rows_at(self.natural_offset())
    }

    /// [`ListState::keeps_visible_rows`] with the viewport at `natural`.
    fn keeps_visible_rows_at(&self, natural: f32) -> bool {
        !self.inverted
            || (self.loads_at_start && !self.anchored_end.is_nan() && natural > PIN_SLACK)
    }

    /// Where the viewport starts in natural coordinates while a layout
    /// measures its cells, counting what the measurements so far moved the
    /// visible rows by: the layout scrolls by that only once it measured
    /// every cell, and a row above the viewport that earlier rows pushed
    /// down is still above it. An inverted list's `content_len` already
    /// holds what this layout changed (a page spliced at its end, rows
    /// measured above the viewport) before `anchor_end` moves the offset to
    /// match, so it counts from the end it last anchored to.
    fn measuring_natural_offset(&self) -> f32 {
        if self.inverted && !self.anchored_end.is_nan() {
            self.anchored_end - self.offset - self.measured_scroll
        } else if self.inverted {
            self.natural_offset()
        } else {
            self.natural_offset() + self.measured_scroll
        }
    }

    /// The scroll a splice asked for, once.
    pub(super) fn take_splice_anchor(&mut self) -> f32 {
        std::mem::take(&mut self.splice_anchor)
    }

    /// Records a `ScrollBy` sent to the platform.
    pub(super) fn issue_scroll_by(&mut self, delta: f32) {
        self.issued += 1;
        self.pending.push((self.issued, PendingScroll::By(delta)));
    }

    /// Records a `ScrollTo` sent to the platform.
    pub(super) fn issue_scroll_to(&mut self, offset: f32) {
        self.issued += 1;
        self.pending.push((self.issued, PendingScroll::To(offset)));
    }

    /// The platform reports its offset after applying `applied` of the
    /// issued scrolls: scrolls it has not applied yet still count, so a
    /// report that predates them does not move the window backwards.
    pub(super) fn reported(&mut self, offset: f32, applied: u32) {
        self.pending.retain(|&(n, _)| n > applied);
        let at = replay(offset, &self.pending);
        self.moved_to(at, self.pending.is_empty());
    }

    /// No scroll the core issued is waiting for the platform.
    pub(super) fn settled(&self) -> bool {
        self.pending.is_empty()
    }

    /// The list is at `at`; `settled`: with every scroll the core issued
    /// applied, so a pinned target the list is away from was left by the
    /// user.
    fn moved_to(&mut self, at: f32, settled: bool) {
        if at != self.offset {
            let step = at - self.offset;
            let step = if self.inverted { -step } else { step };
            self.lead = next_lead(self.lead, step, self.viewport);
            if (at - self.offset).abs() > PIN_SLACK {
                // Not a platform's rounding: the user scrolled.
                self.moved_by_scroll = true;
            }
            self.offset = at;
            self.dirty = true;
        }
        if let Some(pin) = &mut self.pin
            && settled
        {
            if (at - pin.at).abs() <= PIN_SLACK {
                if pin.animating {
                    // Landed: a correction may follow.
                    pin.animating = false;
                    self.dirty = true;
                }
            } else if !pin.animating {
                // The user scrolled away.
                self.pin = None;
            } else {
                let distance = (at - pin.at).abs();
                if distance > pin.nearest + PIN_SLACK {
                    // Away from where the animation goes: the user took
                    // over.
                    self.pin = None;
                } else {
                    pin.nearest = pin.nearest.min(distance);
                }
            }
        }
    }

    /// Keeps following `target` after a scroll command sent the list to
    /// `offset` (animated or not); `None` (a plain offset) ends the pin.
    pub(super) fn pin(&mut self, target: Option<PinTarget>, offset: f32, animated: bool) {
        // The app scrolled the list (`initialScrollIndex` too): where it
        // lands may be near the start.
        self.moved_by_scroll = true;
        self.pin = target.map(|target| Pin {
            target,
            at: offset,
            animating: animated,
            nearest: f32::INFINITY,
        });
    }

    /// Whether the list's End key follows its end (`Core::key_scrolled`):
    /// not in its parent's viewport (the key moves the view around it),
    /// nor inverted (End shows its first items).
    pub(super) fn follows_end_key(&self) -> bool {
        !self.parent && !self.inverted
    }

    /// Whether the list follows its end (`scrollToEnd` or End).
    pub(super) fn follows_end(&self) -> bool {
        matches!(
            self.pin,
            Some(Pin {
                target: PinTarget::End,
                ..
            })
        )
    }

    /// The user scrolled away from the target the list followed.
    pub(super) fn unpin(&mut self) {
        self.pin = None;
    }

    /// The content offset for `target` with the sizes known now.
    pub(super) fn target_offset(&self, target: PinTarget) -> f32 {
        match target {
            PinTarget::End => self.end_offset(),
            PinTarget::Index {
                index,
                view_position,
                view_offset,
            } => self.offset_for_index(index, view_position, view_offset),
        }
    }

    /// After measurements: where a pinned list goes for its target, which
    /// moved as estimated sizes became real ones. The pin ends once the
    /// list is there and every item in the viewport is measured (nothing
    /// visible can move it any more).
    pub(super) fn follow_pin(&mut self, anchored: f32) -> Follow {
        let Some(mut pin) = self.pin else {
            return Follow::Stay;
        };
        if self.viewport <= 0.0 {
            return Follow::Stay;
        }
        let target = self.target_offset(pin.target);
        if pin.animating {
            // The platform moves an animation in flight along with the
            // anchoring scroll; the web moves only where it goes, so the
            // list may report itself farther from there by as much.
            pin.at += anchored;
            pin.nearest += anchored.abs();
            let follow = if (target - pin.at).abs() > PIN_SLACK {
                pin.at = target;
                // The retargeted animation comes nearer from where it is.
                pin.nearest = f32::INFINITY;
                Follow::To(target)
            } else {
                Follow::Stay
            };
            self.pin = Some(pin);
            return follow;
        }
        let delta = target - self.offset;
        if delta != 0.0 {
            self.jump(target);
        }
        pin.at = target;
        self.pin = (!self.viewport_measured()).then_some(pin);
        if delta == 0.0 {
            Follow::Stay
        } else {
            Follow::By(delta)
        }
    }

    /// Whether a scroll command's target is still followed.
    #[cfg(test)]
    pub(super) fn pinned(&self) -> bool {
        self.pin.is_some()
    }

    /// Whether every item overlapping the viewport has its measured size.
    fn viewport_measured(&self) -> bool {
        let start = self.natural_offset();
        self.items_in(start, start + self.viewport)
            .is_none_or(|(first, last)| {
                self.sizes[first as usize..=last as usize]
                    .iter()
                    .all(|s| !s.is_nan())
            })
    }

    // --- Geometry ----------------------------------------------------------

    fn effective(&self, i: usize) -> f32 {
        let s = self.sizes[i];
        if s.is_nan() { self.estimated } else { s }
    }

    fn row_count(&self) -> u32 {
        self.count.div_ceil(self.columns)
    }

    fn row_of(&self, i: u32) -> u32 {
        i / self.columns
    }

    /// Size of row `r`: its largest item.
    fn row_size(&self, r: u32) -> f32 {
        let start = (r * self.columns) as usize;
        let end = (start + self.columns as usize).min(self.sizes.len());
        (start..end).map(|i| self.effective(i)).fold(0.0, f32::max)
    }

    /// The gap between rows along the main axis.
    fn main_gap(&self) -> f32 {
        if self.horizontal {
            self.content.column_gap.0
        } else {
            self.content.row_gap.0
        }
    }

    /// The gap between columns.
    pub(super) fn cross_gap(&self) -> f32 {
        if self.horizontal {
            self.content.row_gap.0
        } else {
            self.content.column_gap.0
        }
    }

    /// Padding at the start / end of the main axis and of the cross axis.
    fn main_padding(&self) -> (f32, f32) {
        let p = &self.content.padding;
        if self.horizontal && self.mirrored {
            (p.right.0, p.left.0)
        } else if self.horizontal {
            (p.left.0, p.right.0)
        } else {
            (p.top.0, p.bottom.0)
        }
    }

    pub(super) fn cross_padding(&self) -> (f32, f32) {
        let p = &self.content.padding;
        if self.horizontal {
            (p.top.0, p.bottom.0)
        } else {
            (p.left.0, p.right.0)
        }
    }

    fn rows_changed(&mut self) {
        self.dirty = true;
    }

    fn rebuild_offsets(&mut self) {
        let gap = self.main_gap() as f64;
        let rows = (0..self.row_count()).map(|r| self.row_size(r) as f64 + gap);
        self.rows = Fenwick::from_sizes(rows.collect::<Vec<_>>().into_iter());
        self.dirty = true;
    }

    /// The offsets after the items past the first `old` were appended or
    /// dropped: only the rows at the end change, so a feed that grows a
    /// row at a time costs O(log n) each, not a rebuild of every row.
    fn resize_rows(&mut self, old: u32) {
        let columns = self.columns;
        let old_rows = old.div_ceil(columns) as usize;
        if self.rows.len() != old_rows {
            self.rebuild_offsets();
            return;
        }
        let rows = self.row_count() as usize;
        let gap = self.main_gap() as f64;
        // The last row kept may have gained or lost items: its size again.
        let kept = old_rows.min(rows);
        self.rows.truncate(kept);
        if kept > 0 {
            let last = kept - 1;
            let now = self.row_size(last as u32) as f64 + gap;
            let was = self.rows.prefix(kept) - self.rows.prefix(last);
            if now != was {
                self.rows.add(last, now - was);
            }
        }
        for r in kept..rows {
            self.rows.push(self.row_size(r as u32) as f64 + gap);
        }
        self.dirty = true;
    }

    /// Length of the item rows (no trailing gap).
    fn items_len(&self) -> f32 {
        if self.count == 0 {
            0.0
        } else {
            self.rows.total() as f32 - self.main_gap()
        }
    }

    /// Start of each block of content, in natural coordinates.
    pub(super) fn blocks(&self) -> Blocks {
        let gap = self.main_gap();
        let (start, end) = self.main_padding();
        let [header, footer, empty] = &self.extras;
        let mut at = start;
        let mut any = false;
        let mut place = |present: bool, size: f32| {
            if !present {
                return at;
            }
            if any {
                at += gap;
            }
            any = true;
            let here = at;
            at += size;
            here
        };
        let header_at = place(header.present(), header.size);
        let body_at = if self.count > 0 {
            place(true, self.items_len())
        } else {
            place(empty.present(), empty.size)
        };
        let footer_at = place(footer.present(), footer.size);
        Blocks {
            header: header_at,
            body: body_at,
            footer: footer_at,
            total: at + end,
        }
    }

    /// Total content length along the main axis (what the platform
    /// scrolls).
    pub(super) fn content_len(&self) -> f32 {
        let total = self.blocks().total;
        if self.inverted || self.bottom() {
            total.max(self.viewport)
        } else {
            total
        }
    }

    /// Content coordinate of a span at natural position `at` of length
    /// `size`.
    pub(super) fn to_content(&self, at: f32, size: f32) -> f32 {
        if self.inverted {
            self.content_len() - at - size
        } else {
            at + self.leading()
        }
    }

    /// The viewport's start in natural coordinates.
    fn natural_offset(&self) -> f32 {
        if self.inverted {
            self.content_len() - self.offset - self.viewport
        } else {
            self.offset - self.leading()
        }
    }

    /// Rests at the end of its content (`alignment="bottom"`).
    fn bottom(&self) -> bool {
        self.alignment == ListAlignment::Bottom && !self.inverted
    }

    /// The free space before content shorter than a bottom-aligned list's
    /// viewport, which keeps its rows at the bottom.
    fn leading(&self) -> f32 {
        if self.bottom() {
            (self.viewport - self.blocks().total).max(0.0)
        } else {
            0.0
        }
    }

    /// Natural position of item `i` (its row's start).
    pub(super) fn item_at(&self, i: u32) -> f32 {
        self.blocks().body + self.rows.prefix(self.row_of(i) as usize) as f32
    }

    /// Size and position of each cell across the main axis: `(offset,
    /// size)` of column `col`. On a terminal's grid of `cell` points
    /// across, every column is as many whole Cells (the share rounded
    /// down, the Cells left over after the last column): rounded each on
    /// its own, they would run into the padding at the end.
    pub(super) fn column(&self, cross: f32, col: u32, cell: Option<f32>) -> (f32, f32) {
        let (start, end) = self.cross_padding();
        let gap = self.cross_gap();
        let n = self.columns as f32;
        let mut width = ((cross - start - end - gap * (n - 1.0)) / n).max(0.0);
        if let Some(cell) = cell.filter(|&c| c > 0.0) {
            width = (width / cell + 1e-3).floor() * cell;
        }
        (start + col as f32 * (width + gap), width)
    }

    /// The cross-axis span of extras: the content width inside padding.
    pub(super) fn full_width(&self, cross: f32) -> (f32, f32) {
        let (start, end) = self.cross_padding();
        (start, (cross - start - end).max(0.0))
    }

    /// Main-axis size of item `i`'s row.
    pub(super) fn row_extent(&self, i: u32) -> f32 {
        self.row_size(self.row_of(i))
    }

    pub(super) fn column_of(&self, i: u32) -> u32 {
        i % self.columns
    }

    // --- Updates -----------------------------------------------------------

    pub(super) fn set_count(&mut self, count: u32) {
        if count == self.count {
            return;
        }
        self.count = count;
        self.items_changed = true;
        // The rows past the end went: a cell that showed one shows whatever
        // comes there next only once bound again.
        for s in &mut self.slots {
            if s.requested.is_some_and(|r| r >= count) {
                s.requested = None;
                s.rendered = None;
                s.stale = true;
            }
            if s.placed.is_some_and(|p| p >= count) {
                s.placed = None;
            }
        }
        let old = self.sizes.len() as u32;
        self.sizes.resize(count as usize, f32::NAN);
        self.resize_rows(old);
        if self.load_more_at.is_some_and(|c| c != count) {
            self.load_more_at = None;
        }
    }

    pub(super) fn set_estimated(&mut self, estimated: f32) {
        if estimated > 0.0 && estimated != self.estimated {
            // Rows not measured above the viewport change length: what is
            // visible stays where it is.
            let anchor = self.visible_anchor().filter(|_| !self.inverted);
            self.estimated = estimated;
            self.rebuild_offsets();
            if let Some((index, from_top)) = anchor {
                self.keep_in_place(index, from_top);
            }
        }
    }

    /// Whether the cells change width: they are laid out again
    /// (`Core::layout_cells`), which only runs in a turn that lays out.
    pub(super) fn set_columns(&mut self, columns: u32) -> bool {
        let columns = columns.max(1);
        if columns != self.columns {
            // The first visible item stays where it is (a window resized to
            // fit more or fewer columns), not the offset: at the old offset
            // the rows show other items.
            let anchor = self.visible_anchor().filter(|_| !self.inverted).map(
                |(index, from_top)| match self.columns_anchor {
                    Some(kept) if kept < self.count && self.row_of(kept) == self.row_of(index) => {
                        (kept, from_top)
                    }
                    _ => (index, from_top),
                },
            );
            self.columns_anchor = anchor.map(|(index, _)| index);
            self.columns = columns;
            // Cells change width: their sizes are measured again.
            self.sizes.fill(f32::NAN);
            self.cells_cross = f32::NAN;
            self.rebuild_offsets();
            if let Some((index, from_top)) = anchor {
                self.keep_in_place(index, from_top);
            }
            true
        } else {
            false
        }
    }

    /// `contentStyle`: it wins over `contentClass` when set. Whether the
    /// cells change width, as [`Self::set_columns`].
    pub(super) fn set_content(&mut self, content: ListContentStyle) -> bool {
        self.content_style = content;
        self.apply_content()
    }

    /// What `contentClass` sets. Whether the cells change width, as
    /// [`Self::set_columns`].
    pub(super) fn set_class_content(&mut self, content: ListContentStyle) -> bool {
        self.content_class = content;
        self.apply_content()
    }

    fn apply_content(&mut self) -> bool {
        let content = if self.content_style != ListContentStyle::default() {
            self.content_style
        } else {
            self.content_class
        };
        if content != self.content {
            let cross_changed = self.cross_padding() != {
                let p = &content.padding;
                if self.horizontal {
                    (p.top.0, p.bottom.0)
                } else {
                    (p.left.0, p.right.0)
                }
            } || self.cross_gap()
                != if self.horizontal {
                    content.row_gap.0
                } else {
                    content.column_gap.0
                };
            self.content = content;
            if cross_changed {
                self.cells_cross = f32::NAN;
            }
            self.rebuild_offsets();
            cross_changed
        } else {
            false
        }
    }

    pub(super) fn set_horizontal(&mut self, horizontal: bool) {
        if horizontal != self.horizontal {
            self.horizontal = horizontal;
            self.sizes.fill(f32::NAN);
            self.rebuild_offsets();
        }
    }

    /// Whether it shows mirrored (horizontal, right to left): its left and
    /// right content padding keep their sides on screen.
    pub(super) fn set_mirrored(&mut self, mirrored: bool) {
        if mirrored != self.mirrored {
            self.mirrored = mirrored;
            let p = &self.content.padding;
            if self.horizontal && p.left != p.right {
                self.rebuild_offsets();
            }
        }
    }

    pub(super) fn set_inverted(&mut self, inverted: bool) {
        if self.parent {
            self.ignored |= if inverted { ignored::INVERTED } else { 0 };
            return;
        }
        if inverted != self.inverted {
            self.inverted = inverted;
            self.anchored_end = f32::NAN;
            self.dirty = true;
        }
    }

    pub(super) fn set_follow_end(&mut self, threshold: Option<f32>) {
        if self.parent {
            self.ignored |= if threshold.is_some() {
                ignored::FOLLOW_END
            } else {
                0
            };
            return;
        }
        if threshold != self.follow_end {
            self.follow_end = threshold;
            self.anchored_end = f32::NAN;
            self.dirty = true;
        }
    }

    pub(super) fn set_alignment(&mut self, alignment: ListAlignment) {
        if self.parent {
            self.ignored |= if alignment == ListAlignment::Top {
                0
            } else {
                ignored::ALIGNMENT
            };
            return;
        }
        if alignment != self.alignment {
            self.alignment = alignment;
            self.anchored_end = f32::NAN;
            self.dirty = true;
        }
    }

    /// Keeps `items` rendered outside the window (none: only the window's).
    pub(super) fn set_kept(&mut self, mut items: Vec<u32>) {
        items.sort_unstable();
        items.dedup();
        if items != self.kept {
            self.kept = items;
            self.dirty = true;
        }
    }

    pub(super) fn set_sticky(&mut self, mut sticky: Vec<u32>) {
        sticky.sort_unstable();
        sticky.dedup();
        if sticky != self.sticky {
            self.sticky = sticky;
            self.dirty = true;
        }
    }

    /// `stickyHeaderOffset` as an animated value.
    pub(super) fn set_sticky_node(&mut self, node: Option<crate::animation::NodeId>) {
        if node != self.sticky_node {
            self.sticky_node = node;
            self.dirty = true;
        }
    }

    /// `stickyHeaderOffset`.
    pub(super) fn set_sticky_offset(&mut self, offset: f32) {
        let offset = if offset.is_finite() { offset } else { 0.0 };
        if offset != self.sticky_offset {
            self.sticky_offset = offset;
            self.dirty = true;
        }
    }

    /// Records a measured size. Returns the change if the item lies
    /// entirely before the viewport (the caller scrolls by it so the
    /// visible content stays put).
    pub(super) fn measured(&mut self, i: u32, size: f32) -> f32 {
        let idx = i as usize;
        if idx >= self.sizes.len() || self.sizes[idx] == size {
            return 0.0;
        }
        let row = self.row_of(i);
        let before = self.row_size(row);
        let row_start = self.item_at(i);
        let natural = self.measuring_natural_offset();
        let above_viewport = row_start < natural && row_start + before <= natural;
        let keep = above_viewport && self.keeps_visible_rows_at(natural);
        self.sizes[idx] = size;
        let delta = self.row_size(row) - before;
        if delta != 0.0 {
            self.rows.add(row as usize, delta as f64);
        }
        self.dirty = true;
        let scroll = self.before_viewport_changed(keep, delta, natural);
        self.measured_scroll += scroll;
        scroll
    }

    /// The scroll that keeps the visible rows in place after something
    /// before the viewport changed by `delta` (at natural offset `natural`
    /// before the change), when `keep`. An inverted list cancels what
    /// `anchor_end` will scroll to keep its distance from the end, without
    /// going past its start.
    fn before_viewport_changed(&self, keep: bool, delta: f32, natural: f32) -> f32 {
        match (keep, self.inverted) {
            (false, _) => 0.0,
            (true, false) => delta,
            (true, true) => -delta.max(-natural),
        }
    }

    /// Records the size of an extra cell; returns the anchoring change as
    /// [`ListState::measured`] does.
    pub(super) fn measured_extra(&mut self, kind: ExtraKind, size: f32) -> f32 {
        let blocks = self.blocks();
        let natural = self.measuring_natural_offset();
        let keeps = self.keeps_visible_rows_at(natural);
        let extra = &mut self.extras[kind as usize];
        if extra.size == size {
            return 0.0;
        }
        let delta = size - extra.size;
        extra.size = size;
        self.rows_changed();
        let at = match kind {
            ExtraKind::Header => blocks.header,
            ExtraKind::Footer => blocks.footer,
            ExtraKind::Empty => blocks.body,
        };
        // An extra entirely before the viewport's start (not one that was
        // empty at the top, with the list at the top); inverted lists at
        // their start keep their distance from the end (`anchor_end`).
        let old_end = at + size - delta;
        let keep = keeps && at < natural && old_end <= natural;
        let scroll = self.before_viewport_changed(keep, delta, natural);
        self.measured_scroll += scroll;
        scroll
    }

    /// Inverted lists keep their distance from the end of the content:
    /// returns how far to scroll after content or viewport changes (and
    /// starts at the end). Bottom-aligned lists start at the end too, and
    /// like other lists with `follow_end` stay at the end
    /// when the end moves away while they are within the threshold of it
    /// (a growing last item, a shrinking viewport); scrolled further up,
    /// they keep what is visible (content grows below it).
    ///
    /// `kept` is how far this commit's measurements moved the offset to keep
    /// the visible rows in place: that move says nothing about where the user
    /// is, so a list at its end is still at its end.
    pub(super) fn anchor_end(&mut self, kept: f32) -> f32 {
        self.measured_scroll = 0.0;
        let revealing = std::mem::take(&mut self.revealing);
        if self.viewport <= 0.0 {
            return 0.0;
        }
        let end = (self.content_len() - self.viewport).max(0.0);
        if !self.inverted {
            let bottom = self.bottom();
            let threshold = match self.follow_end {
                Some(threshold) => threshold,
                None if bottom => PIN_SLACK,
                None => return 0.0,
            };
            if bottom && !self.anchored_end.is_nan() && self.last_row_being_measured() {
                // One scroll, to where the row really ends: scrolling by
                // its estimate first would overshoot and be clamped back.
                self.anchored_end += kept;
                return 0.0;
            }
            let was = std::mem::replace(&mut self.anchored_end, end);
            // A bottom-aligned list opens at its end, without a scroll
            // command to pin and follow while its rows are measured.
            let opening = bottom && was.is_nan();
            let distance = was - (self.offset - kept);
            // Rows above the viewport shrinking while visible ones grow can
            // leave the end where it was and the offset short of it.
            // A negative distance is native overscroll, not a row falling
            // short of the end. Let the platform finish its drag and bounce
            // instead of sending a competing ScrollBy on every report.
            let settle = bottom && (0.0..=PIN_SLACK).contains(&distance);
            if !opening && (was.is_nan() || distance > threshold || (end <= was && !settle)) {
                return 0.0;
            }
            // A row growing under its own layout animation: the scroll
            // would land at once while the row slides open, so the content
            // above jumps. The list keeps its place, the row grows below
            // the viewport, as it does further from the end (#2218).
            if revealing && !opening && end > was {
                return 0.0;
            }
            let delta = end - self.offset;
            self.offset = end;
            return delta;
        }
        let delta = if self.anchored_end.is_nan() {
            end - self.offset
        } else {
            end - self.anchored_end
        };
        self.anchored_end = end;
        self.offset += delta;
        delta
    }

    /// The last row is not measured yet but will be: the window reaches it.
    fn last_row_being_measured(&self) -> bool {
        let Some(last) = self.count.checked_sub(1) else {
            return false;
        };
        self.sizes[last as usize].is_nan()
            && self.item_at(last) < self.natural_offset() + self.viewport * (1.0 + OVERSCAN)
    }

    /// The platform is about to scroll to `offset` (a command): the window
    /// follows it right away, and inverted lists anchor to it.
    pub(super) fn jump(&mut self, offset: f32) {
        self.offset = offset;
        if self.inverted {
            self.anchored_end = (self.content_len() - self.viewport).max(0.0);
        }
        self.dirty = true;
    }

    /// The content offset that shows item `index` at `view_position` (0:
    /// start of the viewport, 1: end) shifted by `view_offset`, clamped to
    /// the content.
    pub(super) fn offset_for_index(&self, index: u32, view_position: f32, view_offset: f32) -> f32 {
        let index = index.min(self.count.saturating_sub(1));
        let size = self.row_size(self.row_of(index));
        let at = self.to_content(self.item_at(index), size);
        let free = self.viewport - size;
        let offset = if self.inverted {
            // Mirrored like the inverted list itself.
            at - (1.0 - view_position) * free + view_offset
        } else {
            at - view_position * free - view_offset
        };
        let (min, max) = self.offset_limits();
        offset.clamp(min, max)
    }

    pub(super) fn end_offset(&self) -> f32 {
        if self.inverted {
            0.0
        } else if self.parent {
            // The list's end at the end of the viewport.
            let (min, max) = self.limits;
            (self.content_len() - self.viewport).clamp(min, max)
        } else {
            (self.content_len() - self.viewport).max(0.0)
        }
    }

    // --- Cells -------------------------------------------------------------

    pub(super) fn add_slot_cell(&mut self, slot: CellSlot, cell: u32) {
        let s = match slot {
            CellSlot::Item(s) => s as usize,
            CellSlot::Header => return self.set_extra(ExtraKind::Header, cell),
            CellSlot::Footer => return self.set_extra(ExtraKind::Footer, cell),
            CellSlot::Empty => return self.set_extra(ExtraKind::Empty, cell),
        };
        if s >= self.slots.len() {
            self.slots.resize(
                s + 1,
                Slot {
                    cell: u32::MAX,
                    index: None,
                    rendered: None,
                    requested: None,
                    placed: None,
                    stale: false,
                },
            );
        }
        self.slots[s].cell = cell;
        self.slots[s].stale = false;
        self.dirty = true;
    }

    fn set_extra(&mut self, kind: ExtraKind, cell: u32) {
        self.extras[kind as usize] = Extra { cell, size: 0.0 };
        self.dirty = true;
    }

    pub(super) fn remove_cell(&mut self, cell: u32) {
        for slot in &mut self.slots {
            if slot.cell == cell {
                slot.cell = u32::MAX;
                slot.rendered = None;
                slot.requested = None;
                slot.placed = None;
                slot.stale = false;
                self.dirty = true;
            }
        }
        for extra in &mut self.extras {
            if extra.cell == cell {
                *extra = Extra::NONE;
                self.dirty = true;
            }
        }
    }

    /// Item `index`'s cell is placed for it. True when it was placed for
    /// another item before, or never: it shows a new row there.
    pub(super) fn place(&mut self, index: u32) -> bool {
        let Some(&slot) = self.by_index.get(&index) else {
            return true;
        };
        let s = &mut self.slots[slot as usize];
        s.placed.replace(index) != Some(index)
    }

    /// Cell `cell` was moved out of sight: it shows no row's place.
    pub(super) fn unplace(&mut self, cell: u32) {
        if let Some(s) = self.slots.iter_mut().find(|s| s.cell == cell) {
            s.placed = None;
        }
    }

    pub(super) fn rendered(&mut self, cell: u32, index: u32) {
        if let Some(slot) = self.slots.iter_mut().find(|s| s.cell == cell) {
            slot.rendered = Some(index);
            self.dirty = true;
        }
    }

    // --- Window ------------------------------------------------------------

    /// Item range `first..=last` of rows overlapping the natural span
    /// `[start, end]`, or `None`.
    fn items_in(&self, start: f32, end: f32) -> Option<(u32, u32)> {
        if self.count == 0 {
            return None;
        }
        let body = self.blocks().body;
        if end < body || start > body + self.items_len() {
            return None;
        }
        let first_row = self.rows.find((start - body).max(0.0) as f64) as u32;
        let last_row =
            (self.rows.find((end - body).max(0.0) as f64) as u32).min(self.row_count() - 1);
        let first = first_row * self.columns;
        let last = ((last_row + 1) * self.columns - 1).min(self.count - 1);
        Some((first, last))
    }

    /// The span of content (main axis, content coordinates) whose items
    /// are rendered: the viewport and the overscan around it.
    pub(super) fn render_window(&self) -> (f32, f32) {
        let overscan = self.viewport * OVERSCAN;
        (
            self.offset - overscan,
            self.offset + self.viewport + overscan,
        )
    }

    /// The sticky item currently pinned to the viewport's start (or its
    /// sticky offset from it): the last one that starts before that.
    pub(super) fn active_sticky(&self) -> Option<u32> {
        if !self.sticky_enabled() {
            return None;
        }
        let at = self.natural_offset() + self.sticky_offset;
        let mut active = None;
        for &s in &self.sticky {
            if s >= self.count || self.item_at(s) > at {
                break;
            }
            active = Some(s);
        }
        active
    }

    /// Sticky items need one column and a list that is not inverted (as in
    /// React Native).
    pub(super) fn sticky_enabled(&self) -> bool {
        !self.sticky.is_empty() && self.columns == 1 && !self.inverted
    }

    /// The travel range of sticky item `index`: from where it reaches the
    /// sticky offset from the viewport's start to where the next sticky item
    /// pushes it out.
    ///
    /// In its parent's viewport, the range is in the offsets of the view
    /// around the list, and the last sticky item stops where its bottom
    /// meets the end of the list's content.
    pub(super) fn sticky_range(&self, index: u32, cell: u32, size: f32) -> StickyRange {
        let start = self.item_at(index) - self.sticky_offset;
        let next = self
            .sticky
            .get(self.sticky.partition_point(|&s| s <= index))
            .filter(|&&s| s < self.count);
        let end = match next {
            Some(&n) => (self.item_at(n) - size - self.sticky_offset).max(start),
            None if self.parent => {
                let end = self.blocks().total - self.main_padding().1;
                (end - size - self.sticky_offset).max(start)
            }
            None => f32::INFINITY,
        };
        if self.parent {
            let at = self.outer_start;
            return StickyRange {
                cell,
                start: at + start,
                end: at + end,
                offset: self.sticky_node,
            };
        }
        StickyRange {
            cell,
            start,
            end,
            offset: self.sticky_node,
        }
    }

    /// Recomputes the render window. `(slot, index)` bindings due now are
    /// pushed to `binds`: cells whose item moved, and new ones in the
    /// viewport or just ahead of it (all of them unless `paced`). Returns
    /// the load-more events to raise.
    pub(super) fn update_window(&mut self, binds: &mut Vec<(u32, u32)>) -> Edges {
        self.dirty = false;
        // Cells whose item moved: the runtime learns their new index (cheap:
        // the cell shows the same item) before anything else binds.
        binds.append(&mut self.moved);
        if self.count == 0 || self.viewport <= 0.0 {
            for slot in 0..self.slots.len() {
                self.unbind(slot as u32);
            }
            return Edges::default();
        }
        let at = self.natural_offset();
        let overscan = self.viewport * OVERSCAN;
        let range = self.items_in(at - overscan, at + self.viewport + overscan);
        let sticky = self.active_sticky();
        // And the one before it: scrolled back, it shows at once, pushed by
        // the pinned one, before a round of binding could render it.
        let before = sticky.and_then(|s| {
            self.sticky[..self.sticky.partition_point(|&p| p < s)]
                .last()
                .copied()
        });
        let kept = std::mem::take(&mut self.kept);
        let wanted = |i: u32| {
            range.is_some_and(|(f, l)| (f..=l).contains(&i))
                || sticky == Some(i)
                || before == Some(i)
                || kept.contains(&i)
        };

        for slot in 0..self.slots.len() as u32 {
            if let Some(i) = self.slots[slot as usize].index
                && !wanted(i)
            {
                self.unbind(slot);
            }
        }
        // First the items whose own cell is free and still shows them (the
        // window shrank and grew back: a dock showed and went, the window
        // was resized): they take it back as it is, nothing to make again.
        // Then the rest, each in any free cell. Cells that show no item of
        // their own (`Slot::stale`; data changes leave them, scrolling none)
        // show another cell's in the runtime's lists: those go first, to
        // show it once. A component's list let their content go: those go
        // last, after the cells that still show an item, which are bound
        // again rather than made.
        let stale = (self.free.iter()).any(|&s| self.slots[s as usize].stale);
        let first = self.paced;
        let bind = |this: &mut Self, i: u32, own: bool| {
            if this.by_index.contains_key(&i) {
                return;
            }
            let slots = &this.slots;
            let shows = |s: &u32| {
                let s = &slots[*s as usize];
                s.rendered == Some(i) && s.requested == Some(i)
            };
            let own_slot = this.free.iter().rposition(shows);
            let slot = match own_slot {
                Some(at) => this.free.remove(at),
                None if own => return,
                None => match stale
                    .then(|| {
                        let mut free = this.free.iter();
                        free.rposition(|s| slots[*s as usize].stale == first)
                    })
                    .flatten()
                    .map(|at| this.free.remove(at))
                    .or_else(|| this.free.pop())
                {
                    Some(slot) => slot,
                    None => {
                        this.slots.push(Slot {
                            cell: u32::MAX,
                            index: None,
                            rendered: None,
                            requested: None,
                            placed: None,
                            stale: false,
                        });
                        this.slots.len() as u32 - 1
                    }
                },
            };
            this.slots[slot as usize].index = Some(i);
            this.by_index.insert(i, slot);
        };
        let count = self.count;
        let passes: &[bool] = if self.free.is_empty() {
            &[false]
        } else {
            &[true, false]
        };
        for &own in passes {
            if let Some((first, last)) = range {
                for i in first..=last {
                    bind(self, i, own);
                }
            }
            for s in [before, sticky].into_iter().flatten() {
                bind(self, s, own);
            }
            for &i in kept.iter().filter(|&&i| i < count) {
                bind(self, i, own);
            }
        }
        let (start, end) = self.urgent_span(at);
        let new = binds.len();
        for slot in 0..self.slots.len() {
            let s = self.slots[slot];
            let Some(i) = s.index else { continue };
            if s.requested == Some(i) {
                continue;
            }
            if !self.paced
                || sticky == Some(i)
                || before == Some(i)
                || kept.contains(&i)
                || self.item_overlaps(i, start, end)
            {
                self.slots[slot].requested = Some(i);
                self.slots[slot].stale = false;
                binds.push((slot as u32, i));
            }
        }
        binds[new..].sort_unstable_by_key(|b| b.1);
        self.kept = kept;

        let total = self.blocks().total;
        let near_end = at + self.viewport >= total - self.viewport * self.end_threshold;
        let mut edges = Edges::default();
        if near_end && self.load_more_at != Some(self.count) {
            self.load_more_at = Some(self.count);
            edges.end = true;
        }
        // Once per approach: again only after the viewport left the start,
        // or when the items changed while it stayed there (a page that did
        // not fill the threshold). Not where the list opens, unless the
        // user or a scroll command moved it.
        let near_start = at <= self.viewport * self.start_threshold;
        if !near_start {
            self.load_more_at_start = None;
        } else if self.moved_by_scroll && self.load_more_at_start != Some(self.count) {
            self.load_more_at_start = Some(self.count);
            edges.start = true;
        }
        edges
    }

    /// The span (natural coordinates) whose cells bind with the window:
    /// the viewport, and ahead of it in the scroll direction
    /// [`URGENT_STEPS`] steps (what the next frames of a fling show, by the
    /// time the rows bound now do). A step longer than the viewport is a
    /// jump: only the viewport.
    fn urgent_span(&self, at: f32) -> (f32, f32) {
        let step = self.lead.abs();
        let ahead = if step <= self.viewport {
            (URGENT_STEPS * step).min(self.viewport * OVERSCAN)
        } else {
            0.0
        };
        if self.lead > 0.0 {
            (at, at + self.viewport + ahead)
        } else {
            (at - ahead, at + self.viewport)
        }
    }

    /// Whether item `i`'s row overlaps `start..end` (natural coordinates).
    fn item_overlaps(&self, i: u32, start: f32, end: f32) -> bool {
        let top = self.item_at(i);
        top < end && top + self.row_size(self.row_of(i)) > start
    }

    /// Whether cells wait for [`Self::take_paced`].
    pub(super) fn has_paced(&self) -> bool {
        self.slots
            .iter()
            .any(|s| s.index.is_some() && s.index != s.requested)
    }

    /// Up to `max` of the cells waiting to bind, nearest the viewport first
    /// on the side the list scrolls towards, then the other side; pushed to
    /// `binds`. Returns how many. The engine takes one at a time (it checks
    /// its budget after each), so this picks the nearest by a scan of the
    /// slots instead of sorting them.
    pub(super) fn take_paced(&mut self, max: usize, binds: &mut Vec<(u32, u32)>) -> usize {
        let mut taken = 0;
        while taken < max {
            let Some((slot, i)) = self.nearest_waiting() else {
                break;
            };
            self.slots[slot as usize].requested = Some(i);
            self.slots[slot as usize].stale = false;
            binds.push((slot, i));
            taken += 1;
        }
        taken
    }

    /// The waiting cell [`Self::take_paced`] binds next: `(slot, index)`.
    fn nearest_waiting(&self) -> Option<(u32, u32)> {
        let at = self.natural_offset();
        let (top, bottom) = (at, at + self.viewport);
        let forward = self.lead >= 0.0;
        let mut best: Option<((bool, f32), u32, u32)> = None;
        for (slot, s) in self.slots.iter().enumerate() {
            let Some(i) = s.index else { continue };
            if s.requested == Some(i) {
                continue;
            }
            let start = self.item_at(i);
            let (distance, below) = if start >= bottom {
                (start - bottom, true)
            } else {
                let end = start + self.row_size(self.row_of(i));
                ((top - end).max(0.0), false)
            };
            // The side behind waits for the side ahead.
            let key = (below != forward, distance);
            if best.is_none_or(|(b, ..)| key.0.cmp(&b.0).then(key.1.total_cmp(&b.1)).is_lt()) {
                best = Some((key, slot as u32, i));
            }
        }
        best.map(|(_, slot, i)| (slot, i))
    }

    fn unbind(&mut self, slot: u32) {
        if let Some(i) = self.slots[slot as usize].index.take() {
            self.by_index.remove(&i);
            self.free.push(slot);
        }
    }

    /// The viewable items under the list's viewability rules (React
    /// Native's `ViewabilityHelper`): `first..=last`, or `None`.
    pub(super) fn viewable_items(&self) -> Option<(u32, u32)> {
        if self.viewport <= 0.0 {
            return None;
        }
        let top = self.natural_offset();
        let bottom = top + self.viewport;
        let (first, last) = self.items_in(top, bottom)?;
        let viewable = |row: u32| {
            let start = self.item_at(row * self.columns);
            let size = self.row_size(row);
            let end = start + size;
            if start >= top && end <= bottom {
                return true;
            }
            let pixels = (end.min(bottom) - start.max(top)).max(0.0);
            let (share, threshold) = match (
                self.viewability.view_area_coverage_threshold,
                self.viewability.item_visible_threshold,
            ) {
                (Some(t), _) => (pixels / self.viewport, t.0),
                (None, Some(t)) => (pixels / size.max(f32::EPSILON), t.0),
                (None, None) => return pixels > 0.0,
            };
            if threshold > 0.0 {
                share >= threshold
            } else {
                pixels > 0.0
            }
        };
        let (mut first_row, mut last_row) = (self.row_of(first), self.row_of(last));
        while first_row <= last_row && !viewable(first_row) {
            first_row += 1;
        }
        while last_row >= first_row && !viewable(last_row) {
            if last_row == 0 {
                return None;
            }
            last_row -= 1;
        }
        (first_row <= last_row).then(|| {
            (
                first_row * self.columns,
                ((last_row + 1) * self.columns - 1).min(self.count - 1),
            )
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        geometry::{Percentage, px},
        props::EdgeInsets,
    };

    fn list(count: u32, estimated: f32, viewport: f32) -> ListState {
        let mut l = ListState::new();
        l.set_estimated(estimated);
        l.set_count(count);
        l.viewport = viewport;
        l
    }

    #[test]
    fn appending_and_dropping_rows_matches_a_rebuild() {
        for columns in [1, 3] {
            let mut l = list(0, 30.0, 400.0);
            l.set_columns(columns);
            l.content.row_gap = px(4.0);
            let check = |l: &mut ListState| {
                let rows = l.rows.clone();
                l.rebuild_offsets();
                assert_eq!(rows.len(), l.rows.len());
                for r in 0..=rows.len() {
                    assert!((rows.prefix(r) - l.rows.prefix(r)).abs() < 1e-6, "row {r}");
                }
            };
            for c in 1..40 {
                l.set_count(c);
                l.measured(c - 1, 20.0 + (c % 5) as f32 * 7.0);
                check(&mut l);
            }
            for _ in 0..10 {
                l.splice(l.count, 0, 2);
                check(&mut l);
            }
            for c in [55, 31, 30, 7, 0, 5] {
                l.set_count(c);
                check(&mut l);
            }
        }
    }

    #[test]
    fn window_covers_viewport_plus_overscan() {
        let mut l = list(1000, 50.0, 400.0);
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        // [0, 800] at 50 per item -> items 0..=16.
        assert_eq!(binds.len(), 17);
        assert_eq!(binds[0], (0, 0));

        // Scroll down a screen: items scrolled far above are recycled.
        l.offset = 2000.0;
        binds.clear();
        l.update_window(&mut binds);
        let indices: Vec<u32> = binds.iter().map(|b| b.1).collect();
        assert_eq!(indices.first(), Some(&32));
        assert_eq!(indices.last(), Some(&56));
        // Slots were reused, not grown without bound.
        assert!(l.slots.len() <= 25 + 17, "{}", l.slots.len());
    }

    #[test]
    fn measurements_shift_offsets_and_anchor_above_viewport() {
        let mut l = list(100, 50.0, 400.0);
        l.offset = 1000.0;
        // Item 0 is above the viewport: growing it must scroll by the same.
        assert_eq!(l.measured(0, 80.0), 30.0);
        assert_eq!(l.item_at(1), 80.0);
        assert_eq!(l.blocks().total, 100.0 * 50.0 + 30.0);
        // Item 30 is in view: no anchoring.
        assert_eq!(l.measured(30, 10.0), 0.0);
    }

    /// Rows above the viewport measured in one layout, in any order: each
    /// is judged against where the viewport will be once the rows measured
    /// before it moved it, so all of them keep the visible rows in place.
    #[test]
    fn rows_measured_above_the_viewport_together_all_anchor() {
        for order in [[47, 48, 49], [49, 48, 47], [48, 49, 47]] {
            let mut l = list(100, 50.0, 400.0);
            l.offset = 2500.0;
            // Item 50 starts the viewport.
            assert_eq!(l.item_at(50), 2500.0);
            let scroll: f32 = order.iter().map(|&i| l.measured(i, 200.0)).sum();
            assert_eq!(scroll, 450.0, "{order:?}");
            l.offset += scroll;
            l.anchor_end(scroll);
            assert_eq!(l.item_at(50) - l.natural_offset(), 0.0, "{order:?}");
        }
    }

    #[test]
    fn load_more_fires_once_per_count() {
        let mut l = list(10, 50.0, 400.0);
        let mut binds = Vec::new();
        assert!(
            l.update_window(&mut binds).end,
            "500 px of content in a 400 px viewport"
        );
        assert!(!l.update_window(&mut binds).end);
        l.set_count(20);
        l.offset = 600.0;
        assert!(l.update_window(&mut binds).end);
    }

    #[test]
    fn load_more_at_start_fires_once_per_approach_after_a_scroll() {
        let mut l = list(100, 50.0, 400.0);
        let mut binds = Vec::new();
        // Where the list opens is not an approach.
        assert!(!l.update_window(&mut binds).start);
        // The user scrolls away, then back within a viewport of the start.
        l.reported(2000.0, 0);
        assert!(!l.update_window(&mut binds).start);
        l.reported(300.0, 0);
        assert!(l.update_window(&mut binds).start);
        // Once: scrolling on near the start fires nothing more.
        l.reported(100.0, 0);
        assert!(!l.update_window(&mut binds).start);
        // A page arrives at the start: the visible rows keep their place,
        // still within the threshold, so the list asks again.
        l.splice(0, 0, 2);
        assert_eq!(l.offset, 200.0);
        assert!(l.update_window(&mut binds).start);
        assert!(!l.update_window(&mut binds).start);
        // Out and back in: a new approach.
        l.reported(1500.0, 0);
        assert!(!l.update_window(&mut binds).start);
        l.reported(0.0, 0);
        assert!(l.update_window(&mut binds).start);
        // The threshold, in viewports.
        let mut t = list(100, 50.0, 400.0);
        t.start_threshold = 0.25;
        t.reported(150.0, 0);
        assert!(!t.update_window(&mut binds).start);
        t.reported(100.0, 0);
        assert!(t.update_window(&mut binds).start);
    }

    #[test]
    fn load_more_at_start_fires_where_a_scroll_command_lands() {
        // `initialScrollIndex` near the start: the app put the list there.
        let mut l = list(100, 50.0, 400.0);
        let target = PinTarget::Index {
            index: 2,
            view_position: 0.0,
            view_offset: 0.0,
        };
        let offset = l.target_offset(target);
        l.pin(Some(target), offset, false);
        l.jump(offset);
        let mut binds = Vec::new();
        assert!(l.update_window(&mut binds).start);
    }

    #[test]
    fn bottom_aligned_lists_stay_at_their_end_as_rows_above_are_measured() {
        let mut l = list(100, 50.0, 400.0);
        l.set_alignment(ListAlignment::Bottom);
        l.anchor_end(0.0);
        let end = l.content_len() - 400.0;
        assert_eq!(l.offset, end);
        // A row above the viewport comes out shorter and a visible one taller,
        // by the same amount: the end stays, and the offset must too.
        let kept = l.measured(50, 30.0);
        assert_eq!(kept, -20.0);
        assert_eq!(l.measured(99, 70.0), 0.0);
        l.offset += kept;
        let scroll = l.anchor_end(kept);
        assert_eq!(l.content_len() - 400.0, end);
        assert_eq!(kept + scroll, 0.0);
        assert_eq!(l.offset, end);
        // A kept move while the appended last row is being measured does not
        // lose the end either.
        l.splice(100, 0, 1);
        l.take_splice_anchor();
        let kept = l.measured(51, 30.0);
        l.offset += kept;
        assert_eq!(l.anchor_end(kept), 0.0, "waits for the row's real size");
        l.measured(100, 34.0);
        assert_eq!(l.anchor_end(0.0), 34.0);
        assert_eq!(l.offset, l.content_len() - 400.0);
        // Scrolled up, the same measurements leave it where the user put it.
        let up = l.content_len() - 400.0 - 500.0;
        l.reported(up, 0);
        let kept = l.measured(52, 30.0);
        l.offset += kept;
        assert_eq!(l.anchor_end(kept), 0.0);
        assert_eq!(l.offset, up + kept);
    }

    #[test]
    fn bottom_aligned_lists_rest_at_their_end() {
        let on_screen = |l: &ListState, i: u32| l.to_content(l.item_at(i), 50.0) - l.offset;
        let mut l = list(100, 50.0, 400.0);
        l.set_alignment(ListAlignment::Bottom);
        // Opens at the end, its window there in the same commit.
        assert_eq!(l.anchor_end(0.0), 4600.0);
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        assert!(binds.iter().any(|&(_, i)| i == 99));
        assert!(!binds.iter().any(|&(_, i)| i == 0));
        // Appending moves no row in the content: one scroll follows.
        let row = l.to_content(l.item_at(90), 50.0);
        l.splice(100, 0, 1);
        assert_eq!(l.take_splice_anchor(), 0.0);
        assert_eq!(l.anchor_end(0.0), 0.0, "waits for the row's real size");
        assert_eq!(l.measured(100, 34.0), 0.0);
        assert_eq!(l.anchor_end(0.0), 34.0);
        assert_eq!(l.to_content(l.item_at(90), 50.0), row);
        // So does the last row growing (a reply streaming in).
        let anchor = l.measured(100, 80.0);
        assert_eq!(anchor + l.anchor_end(0.0), 46.0);
        assert_eq!(l.to_content(l.item_at(90), 50.0), row);
        // Older rows above the viewport leave what shows in place.
        let before = on_screen(&l, 95);
        l.splice(0, 0, 10);
        let scrolled = l.take_splice_anchor();
        assert_eq!(scrolled, 500.0);
        assert_eq!(l.anchor_end(0.0), 0.0);
        assert_eq!(on_screen(&l, 105), before);
        // Scrolled up, growth below leaves it alone; back at the end, it
        // follows again.
        let end = l.content_len() - 400.0;
        l.reported(end - 500.0, 0);
        l.splice(l.count, 0, 1);
        l.take_splice_anchor();
        assert_eq!(l.anchor_end(0.0), 0.0);
        l.measured(l.count - 1, 50.0);
        l.anchor_end(0.0);
        l.reported(l.content_len() - 400.0, 0);
        l.splice(l.count, 0, 1);
        l.take_splice_anchor();
        assert_eq!(l.anchor_end(0.0), 0.0);
        l.measured(l.count - 1, 50.0);
        assert_eq!(l.anchor_end(0.0), 50.0);
        // A page too long for the window to reach its last row follows by
        // the estimate, or the row would never be measured.
        l.splice(l.count, 0, 100);
        assert_eq!(l.anchor_end(0.0), 5000.0);
    }

    #[test]
    fn bottom_aligned_list_preserves_native_bottom_bounce() {
        let mut l = list(20, 50.0, 400.0);
        l.set_alignment(ListAlignment::Bottom);
        l.follow_end = Some(80.0);
        for i in 0..20 {
            l.measured(i, 50.0);
        }
        l.anchor_end(0.0);
        // UIKit reports offsets beyond the end during a drag and spring back.
        // Layout must not send a competing scroll back to the content edge.
        for overshoot in [0.25, 10.0, 30.0, 60.0, 30.0, 10.0, 0.25, 0.0] {
            l.reported(600.0 + overshoot, 0);
            assert_eq!(l.anchor_end(0.0), 0.0, "overshoot {overshoot}");
            assert_eq!(l.offset, 600.0 + overshoot);
        }
    }

    #[test]
    fn bottom_aligned_lists_keep_short_content_at_the_bottom() {
        let mut l = list(2, 50.0, 400.0);
        l.set_alignment(ListAlignment::Bottom);
        assert_eq!(l.anchor_end(0.0), 0.0);
        assert_eq!(l.content_len(), 400.0);
        assert_eq!(l.to_content(l.item_at(0), 50.0), 300.0);
        assert_eq!(l.to_content(l.item_at(1), 50.0), 350.0);
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        assert_eq!(binds.len(), 2);
        // A row more: they rise, with nothing to scroll.
        l.splice(2, 0, 1);
        assert_eq!(l.anchor_end(0.0), 0.0);
        assert_eq!(l.to_content(l.item_at(0), 50.0), 250.0);
    }

    #[test]
    fn inverted_lists_load_at_their_start_and_keep_the_visible_rows() {
        let mut l = list(100, 50.0, 400.0);
        l.set_inverted(true);
        l.loads_at_start = true;
        l.anchor_end(0.0);
        let mut binds = Vec::new();
        // Opens at its start (item 0 at the bottom): no event.
        assert!(!l.update_window(&mut binds).start);
        // Scrolled up, then back down to 200 px from the start.
        l.reported(5000.0 - 400.0 - 1000.0, 0);
        assert!(!l.update_window(&mut binds).start);
        l.reported(5000.0 - 400.0 - 200.0, 0);
        assert!(l.update_window(&mut binds).start);
        // Newer items arrive before item 0: the rows on screen stay.
        let on_screen = |l: &ListState, i: u32| l.to_content(l.item_at(i), 50.0) - l.offset;
        let before = on_screen(&l, 4);
        l.splice(0, 0, 4);
        let scrolled = l.take_splice_anchor() + l.anchor_end(0.0);
        assert_eq!(scrolled, 0.0);
        assert_eq!(on_screen(&l, 8), before);
        // So does their measuring.
        let offset = l.offset;
        let anchor = l.measured(0, 80.0);
        l.offset += anchor;
        assert_eq!(anchor + l.anchor_end(0.0), 0.0);
        assert_eq!(l.offset, offset);
        // At the start, what arrives there shows (a chat's new message).
        let mut c = list(100, 50.0, 400.0);
        c.set_inverted(true);
        c.loads_at_start = true;
        c.anchor_end(0.0);
        c.splice(0, 0, 1);
        c.take_splice_anchor();
        c.anchor_end(0.0);
        assert_eq!(c.natural_offset(), 0.0);
        // Without `onLoadMoreAtStart`, an inverted list keeps its distance
        // from the end wherever it is, as it always did.
        let mut d = list(100, 50.0, 400.0);
        d.set_inverted(true);
        d.anchor_end(0.0);
        d.reported(5000.0 - 400.0 - 200.0, 0);
        d.splice(0, 0, 4);
        assert_eq!(d.take_splice_anchor(), 0.0);
        d.anchor_end(0.0);
        assert_eq!(d.natural_offset(), 200.0);
    }

    #[test]
    fn shrinking_count_unbinds() {
        let mut l = list(100, 50.0, 400.0);
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        l.set_count(3);
        binds.clear();
        l.update_window(&mut binds);
        assert_eq!(l.slots.iter().filter(|s| s.index.is_some()).count(), 3);
    }

    #[test]
    fn a_terminal_s_columns_are_whole_equal_cells() {
        // 9 columns in 1360pt (170 Cells) padded a Cell each side, 2 Cells
        // apart: 16.9 Cells each, rounded down. Each rounded on its own,
        // the last would end in the padding.
        let mut l = list(90, 50.0, 1000.0);
        l.set_columns(9);
        l.content.padding.left = crate::Points(8.0);
        l.content.padding.right = crate::Points(8.0);
        l.content.column_gap = crate::Points(16.0);
        assert_eq!(l.column(1360.0, 1, Some(8.0)), (8.0 + 128.0 + 16.0, 128.0));
        let (x, width) = l.column(1360.0, 8, Some(8.0));
        assert!(x + width <= 1360.0 - 8.0, "the last inside the padding");
    }

    #[test]
    fn columns_share_rows() {
        let mut l = list(10, 50.0, 1000.0);
        l.set_columns(3);
        // 4 rows of 50.
        assert_eq!(l.blocks().total, 200.0);
        assert_eq!(l.item_at(4), 50.0);
        assert_eq!(l.column_of(4), 1);
        // A row is as tall as its tallest item.
        l.measured(4, 80.0);
        assert_eq!(l.item_at(6), 130.0);
        assert_eq!(l.column(320.0, 2, None), (320.0 * 2.0 / 3.0, 320.0 / 3.0));
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        assert_eq!(binds.len(), 10);
    }

    #[test]
    fn a_mirrored_horizontal_list_keeps_its_left_padding_on_the_left() {
        // Laid out left to right and shown mirrored: the left padding is the
        // end of its main axis, so it shows on the left.
        let mut l = list(3, 50.0, 1000.0);
        l.set_horizontal(true);
        l.set_content(ListContentStyle {
            padding: EdgeInsets {
                left: px(16.0),
                ..EdgeInsets::default()
            },
            ..ListContentStyle::default()
        });
        assert_eq!(l.blocks().body, 16.0);
        l.set_mirrored(true);
        assert_eq!(l.blocks().body, 0.0);
        assert_eq!(l.blocks().total, 3.0 * 50.0 + 16.0);
    }

    #[test]
    fn padding_gaps_and_extras() {
        let mut l = list(3, 50.0, 1000.0);
        l.set_content(ListContentStyle {
            padding: EdgeInsets {
                top: px(10.0),
                right: px(16.0),
                bottom: px(20.0),
                left: px(16.0),
            },
            row_gap: px(8.0),
            column_gap: px(0.0),
        });
        l.add_slot_cell(CellSlot::Header, 7);
        l.measured_extra(ExtraKind::Header, 30.0);
        l.add_slot_cell(CellSlot::Footer, 8);
        l.measured_extra(ExtraKind::Footer, 40.0);
        let b = l.blocks();
        assert_eq!(b.header, 10.0);
        assert_eq!(b.body, 10.0 + 30.0 + 8.0);
        // Three items with two gaps between them.
        assert_eq!(b.footer, b.body + 3.0 * 50.0 + 2.0 * 8.0 + 8.0);
        assert_eq!(b.total, b.footer + 40.0 + 20.0);
        assert_eq!(l.full_width(400.0), (16.0, 368.0));
        // No items: the empty placeholder takes their place.
        l.set_count(0);
        l.add_slot_cell(CellSlot::Empty, 9);
        l.measured_extra(ExtraKind::Empty, 100.0);
        let b = l.blocks();
        assert_eq!(b.footer, b.body + 100.0 + 8.0);
    }

    #[test]
    fn the_scroll_position_is_the_row_at_the_viewports_start_and_the_depth_into_it() {
        assert_eq!(list(0, 50.0, 400.0).scroll_position(), None);
        // A header, then rows 50 points apart with 8-point gaps.
        let mut l = list(100, 50.0, 400.0);
        l.set_content(ListContentStyle {
            row_gap: px(8.0),
            ..ListContentStyle::default()
        });
        l.add_slot_cell(CellSlot::Header, 7);
        l.measured_extra(ExtraKind::Header, 30.0);
        assert_eq!(l.scroll_position(), Some((0, -38.0)));
        l.measured(1, 90.0);
        // In row 2, 5 points in.
        l.offset = 38.0 + 58.0 + 98.0 + 5.0;
        assert_eq!(l.scroll_position(), Some((2, 5.0)));
        // In the gap after row 2: past its size.
        l.offset = 38.0 + 58.0 + 98.0 + 52.0;
        assert_eq!(l.scroll_position(), Some((2, 52.0)));
        // Rows of three: the row's first item.
        l.set_columns(3);
        l.offset = 38.0 + 58.0 + 10.0;
        assert_eq!(l.scroll_position(), Some((3, 10.0)));
        // An inverted list counts from item 0 at the bottom.
        let mut l = list(100, 50.0, 400.0);
        l.set_inverted(true);
        l.anchor_end(0.0);
        assert_eq!(l.scroll_position(), Some((0, 0.0)));
        l.offset -= 120.0;
        assert_eq!(l.scroll_position(), Some((2, 20.0)));
    }

    #[test]
    fn lists_follow_the_end_within_the_threshold() {
        let mut l = list(100, 50.0, 400.0);
        l.set_follow_end(Some(10.0));
        assert_eq!(l.anchor_end(0.0), 0.0, "starts where it is");
        // At the end: the last item grows by 30, the list follows.
        l.offset = 5000.0 - 400.0;
        l.measured(99, 80.0);
        assert_eq!(l.anchor_end(0.0), 30.0);
        assert_eq!(l.offset, 5030.0 - 400.0);
        // Scrolled up: it grows below what is visible, which stays.
        l.offset = 1000.0;
        l.measured(99, 120.0);
        assert_eq!(l.anchor_end(0.0), 0.0);
        assert_eq!(l.offset, 1000.0);
        // Without the option, nothing follows.
        let mut m = list(100, 50.0, 400.0);
        m.anchor_end(0.0);
        m.offset = 5000.0 - 400.0;
        m.measured(99, 80.0);
        assert_eq!(m.anchor_end(0.0), 0.0);
    }

    #[test]
    fn inverted_lists_start_at_the_end_and_keep_their_distance_from_it() {
        let mut l = list(100, 50.0, 400.0);
        l.set_inverted(true);
        // Starts scrolled to the end; item 0 is at the bottom.
        assert_eq!(l.anchor_end(0.0), 5000.0 - 400.0);
        assert_eq!(l.to_content(l.item_at(0), 50.0), 4950.0);
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        assert_eq!(binds.first().map(|b| b.1), Some(0));
        assert!(binds.iter().all(|b| b.1 <= 16));
        // Older items load (appended): the visible content stays put.
        l.set_count(120);
        assert_eq!(l.anchor_end(0.0), 1000.0);
        assert_eq!(l.offset, 5600.0);
        assert_eq!(l.to_content(l.item_at(0), 50.0), 5950.0);
        // A short list sits at the bottom.
        let mut s = list(2, 50.0, 400.0);
        s.set_inverted(true);
        s.anchor_end(0.0);
        assert_eq!(s.offset, 0.0);
        assert_eq!(s.to_content(s.item_at(0), 50.0), 350.0);
    }

    #[test]
    fn sticky_items_stick_at_their_offset() {
        let mut l = list(100, 50.0, 400.0);
        l.set_sticky(vec![0, 30]);
        l.set_sticky_offset(20.0);
        // Ranges are scroll offsets: item 0 is pinned 20 from the top from
        // the start (pushed down by 20), item 30 from 1480 on; 30 pushes 0
        // out when it reaches 0's end, 50 below the offset.
        assert_eq!(
            l.sticky_range(0, 1, 50.0),
            StickyRange {
                cell: 1,
                start: -20.0,
                end: 1430.0,
                offset: None,
            }
        );
        assert_eq!(l.sticky_range(30, 2, 50.0).start, 1480.0);
        // The pinned item is the last one that reached the offset.
        l.offset = 1470.0;
        assert_eq!(l.active_sticky(), Some(0));
        l.offset = 1480.0;
        assert_eq!(l.active_sticky(), Some(30));
        // Without it again: as before.
        l.set_sticky_offset(0.0);
        assert_eq!(l.sticky_range(0, 1, 50.0).start, 0.0);
        assert_eq!(l.active_sticky(), Some(0));
        // A negative offset sticks items partly out of view.
        l.set_sticky_offset(-10.0);
        assert_eq!(l.sticky_range(30, 2, 50.0).start, 1510.0);
    }

    #[test]
    fn sticky_items_stay_rendered_and_travel_until_the_next() {
        let mut l = list(100, 50.0, 400.0);
        l.set_sticky(vec![30, 0]);
        l.offset = 1000.0;
        assert_eq!(l.active_sticky(), Some(0));
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        assert!(binds.iter().any(|b| b.1 == 0), "{binds:?}");
        assert_eq!(
            l.sticky_range(0, 1, 50.0),
            StickyRange {
                cell: 1,
                start: 0.0,
                end: 1450.0,
                offset: None,
            }
        );
        assert_eq!(l.sticky_range(30, 1, 50.0).end, f32::INFINITY);
        l.offset = 1600.0;
        assert_eq!(l.active_sticky(), Some(30));
    }

    #[test]
    fn the_sticky_item_before_the_pinned_one_stays_rendered() {
        let mut l = list(100, 50.0, 400.0);
        l.set_sticky(vec![0, 30, 60]);
        // 60 is pinned; 30 starts at 1500, far above the rendered window.
        l.offset = 3200.0;
        assert_eq!(l.active_sticky(), Some(60));
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        let bound = |l: &ListState, i: u32| l.slots.iter().any(|s| s.index == Some(i));
        assert!(bound(&l, 60) && bound(&l, 30), "{binds:?}");
        assert!(!bound(&l, 0));
        // Scrolled back into 30's rows: 30 is pinned and 0 waits above it.
        l.offset = 2000.0;
        binds.clear();
        l.update_window(&mut binds);
        assert!(bound(&l, 30) && bound(&l, 0), "{binds:?}");
        assert!(!bound(&l, 60));
    }

    #[test]
    fn viewability_thresholds() {
        let mut l = list(100, 100.0, 400.0);
        l.offset = 50.0;
        // Any visible pixel: items 0..=4.
        assert_eq!(l.viewable_items(), Some((0, 4)));
        l.viewability.item_visible_threshold = Some(Percentage(0.6));
        assert_eq!(l.viewable_items(), Some((1, 3)));
        l.viewability.item_visible_threshold = Some(Percentage(0.5));
        assert_eq!(l.viewable_items(), Some((0, 4)));
    }

    #[test]
    fn stale_offset_reports_keep_pending_scrolls() {
        let mut l = list(100, 50.0, 400.0);
        l.offset = 500.0;
        l.issue_scroll_by(30.0);
        // Reported before the platform applied the shift.
        l.reported(500.0, 0);
        assert_eq!(l.offset, 530.0);
        l.issue_scroll_to(1000.0);
        l.reported(531.0, 1);
        assert_eq!(l.offset, 1000.0);
        l.reported(1002.0, 2);
        assert_eq!(l.offset, 1002.0);
        assert!(l.pending.is_empty());
    }

    #[test]
    fn extras_at_the_top_do_not_scroll_the_list() {
        let mut l = list(0, 50.0, 400.0);
        l.add_slot_cell(CellSlot::Empty, 3);
        assert_eq!(l.measured_extra(ExtraKind::Empty, 65.0), 0.0);
        let mut l = list(100, 50.0, 400.0);
        l.add_slot_cell(CellSlot::Header, 3);
        assert_eq!(l.measured_extra(ExtraKind::Header, 30.0), 0.0);
        // Scrolled past it: the visible content keeps its place.
        l.offset = 500.0;
        assert_eq!(l.measured_extra(ExtraKind::Header, 40.0), 10.0);
        // Inverted lists anchor to their end instead.
        l.set_inverted(true);
        assert_eq!(l.measured_extra(ExtraKind::Header, 50.0), 0.0);
    }

    #[test]
    fn splices_keep_measurements_cells_and_the_visible_content() {
        let mut l = list(100, 50.0, 400.0);
        let mut binds = Vec::new();
        l.offset = 1000.0;
        l.update_window(&mut binds);
        for (slot, index) in binds.drain(..) {
            l.add_slot_cell(CellSlot::Item(slot), 100 + slot);
            l.rendered(100 + slot, index);
        }
        l.measured(25, 80.0);
        // Three items arrive at the top: item 20 (the first visible) keeps
        // its place on screen.
        let before = l.item_at(20) - l.offset;
        l.splice(0, 0, 3);
        assert_eq!(l.count, 103);
        assert_eq!(l.item_at(23) - l.offset, before);
        assert_eq!(l.take_splice_anchor(), 150.0);
        // Item 25's measurement moved with it.
        assert_eq!(l.row_extent(28), 80.0);
        // Cells follow their items, and the runtime is told.
        l.update_window(&mut binds);
        assert!(binds.iter().any(|&(_, i)| i == 28));
        assert!(l.slots.iter().any(|s| s.ready() == Some(28)));
        // A change below the viewport moves nothing.
        let offset = l.offset;
        l.splice(90, 2, 0);
        assert_eq!(l.offset, offset);
        assert_eq!(l.count, 101);
    }

    /// A list of `count` rows at `offset` with every cell of its window
    /// made (cell `100 + slot`) and showing its row.
    fn with_cells(count: u32, offset: f32) -> ListState {
        let mut l = list(count, 50.0, 400.0);
        l.offset = offset;
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        for (slot, index) in binds {
            l.add_slot_cell(CellSlot::Item(slot), 100 + slot);
            l.rendered(100 + slot, index);
        }
        l
    }

    /// Each cell and the row it shows.
    fn shown(l: &ListState) -> Vec<(u32, u32)> {
        let mut shown: Vec<_> = l
            .slots
            .iter()
            .filter_map(|s| Some((s.cell, s.ready()?)))
            .collect();
        shown.sort_unstable();
        shown
    }

    /// Rows `0..count` with row `from` moved to `to`.
    fn moved_row(count: u32, from: usize, to: usize) -> (Vec<u32>, Vec<u32>) {
        let old: Vec<u32> = (0..count).collect();
        let mut new = old.clone();
        let row = new.remove(from);
        new.insert(to, row);
        (old, new)
    }

    #[test]
    fn a_moved_row_and_the_rows_it_passed_keep_their_cells() {
        let mut l = with_cells(100, 0.0);
        l.measured(3, 80.0);
        let before = shown(&l);
        let slots = l.slots.len();
        let (old, new) = moved_row(100, 10, 2);
        let diff = ListDiff::new(&old, &new).unwrap();
        l.reorder(&diff);
        // Every cell shows the row it showed, at the row's new index.
        let follow = |(cell, i): (u32, u32)| (cell, diff.new_index(i).unwrap().0);
        assert_eq!(
            shown(&l),
            before.into_iter().map(follow).collect::<Vec<_>>()
        );
        // Measurements went with their rows.
        assert_eq!(l.row_extent(4), 80.0);
        assert_eq!(l.row_extent(3), 50.0);
        // The runtime only learns the new indices: no cell is made or bound
        // to another row.
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        assert_eq!(l.slots.len(), slots);
        for &(slot, index) in &binds {
            assert_eq!(l.slots[slot as usize].rendered, Some(index), "{binds:?}");
        }
        let mut moved: Vec<u32> = binds.iter().map(|b| b.1).collect();
        moved.sort_unstable();
        assert_eq!(moved, (2..=10).collect::<Vec<_>>());
        // At its start the list stays there: the row shows at the top.
        assert_eq!((l.offset, l.take_splice_anchor()), (0.0, 0.0));
    }

    #[test]
    fn moves_inserts_and_removes_keep_the_rows_that_stay() {
        let mut l = with_cells(100, 0.0);
        let before = shown(&l);
        // Row 5 goes, row 1000 arrives at the top, row 12 moves to 3.
        let old: Vec<u32> = (0..100).collect();
        let mut new: Vec<u32> = old.iter().copied().filter(|&k| k != 5 && k != 12).collect();
        new.insert(0, 1000);
        new.insert(3, 12);
        let diff = ListDiff::new(&old, &new).unwrap();
        l.reorder(&diff);
        assert_eq!(l.count, 100);
        let kept: Vec<_> = before
            .iter()
            .filter_map(|&(cell, i)| Some((cell, diff.new_index(i)?.0)))
            .collect();
        assert_eq!(shown(&l), kept);
        // The gone row's cell is free; the new row takes a cell.
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        let new_row = binds.iter().find(|b| b.1 == 0).expect("the new row binds");
        assert_eq!(l.slots[new_row.0 as usize].rendered, None);
        assert_eq!(
            binds
                .iter()
                .filter(|b| l.slots[b.0 as usize].rendered != Some(b.1))
                .count(),
            1
        );
    }

    #[test]
    fn rows_out_of_the_window_move_their_measurements_and_cells() {
        let moves = || {
            // Row 2 moves past the window, row 60 (never shown) to the end.
            let old: Vec<u32> = (0..100).collect();
            let mut new: Vec<u32> = old.iter().copied().filter(|&k| k != 2 && k != 60).collect();
            new.insert(80, 2);
            new.push(60);
            ListDiff::new(&old, &new).unwrap()
        };
        let mut l = with_cells(100, 0.0);
        l.measured(60, 90.0);
        let slots = l.slots.len();
        l.reorder(&moves());
        assert_eq!(l.row_extent(99), 90.0);
        assert_eq!(l.row_extent(59), 50.0);
        // Row 2's cell, out of the window, shows the row that came in.
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        assert_eq!(l.slots.len(), slots);
        // A row that holds the focus keeps its cell wherever it goes.
        let mut l = with_cells(100, 0.0);
        let slot = l.by_index[&2];
        l.set_kept(vec![2]);
        l.reorder(&moves());
        binds.clear();
        l.update_window(&mut binds);
        assert_eq!(l.slots[slot as usize].ready(), Some(80));
        assert_eq!(l.slots.len(), slots + 1, "the row that came in");
        assert!(binds.iter().all(|b| b.0 != slot || b.1 == 80), "{binds:?}");
    }

    #[test]
    fn repeated_keys_pair_up_and_keep_their_cells() {
        let mut l = with_cells(12, 0.0);
        let before = shown(&l);
        let old = [7, 7, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11];
        let new = [1, 7, 2, 7, 3, 4, 5, 6, 8, 9, 10, 11];
        let diff = ListDiff::new(&old, &new).unwrap();
        l.reorder(&diff);
        let follow = |(cell, i): (u32, u32)| (cell, diff.new_index(i).unwrap().0);
        let mut expected: Vec<_> = before.into_iter().map(follow).collect();
        expected.sort_unstable();
        assert_eq!(shown(&l), expected);
        // A diff of other rows than the list's: all of them are new.
        l.reorder(&ListDiff::new(&[1, 2], &[2, 1]).unwrap());
        assert_eq!(l.count, 2);
        assert!(shown(&l).is_empty());
    }

    #[test]
    fn moves_keep_the_first_visible_row_in_place() {
        // Row 20 at the top, 10 points scrolled into it.
        let mut l = with_cells(100, 1010.0);
        let first = l.item_at(20) - l.offset;
        // A row below moves to the top: row 20 (now 21) stays on screen.
        let (old, new) = moved_row(100, 50, 0);
        l.reorder(&ListDiff::new(&old, &new).unwrap());
        assert_eq!(l.item_at(21) - l.offset, first);
        assert_eq!(l.take_splice_anchor(), 50.0);
        // The first visible row itself moves to the top: the rows after it
        // stay where they were, rather than following it.
        let next = l.item_at(22) - l.offset;
        let (old, new) = moved_row(100, 21, 0);
        l.reorder(&ListDiff::new(&old, &new).unwrap());
        assert_eq!(l.item_at(22) - l.offset, next);
        // A row above moves below the viewport: the visible rows stay.
        let (old, new) = moved_row(100, 3, 90);
        l.reorder(&ListDiff::new(&old, &new).unwrap());
        assert_eq!(l.item_at(21) - l.offset, next);
        assert_eq!(l.take_splice_anchor(), -50.0);
    }

    #[test]
    fn a_change_of_columns_keeps_the_first_visible_item_in_place() {
        let mut l = list(90, 50.0, 400.0);
        l.set_columns(9);
        // Row 4 (items 36 to 44) at the top.
        l.offset = 200.0;
        assert_eq!(l.item_at(36) - l.offset, 0.0);
        // Five columns: item 36 is in row 7, and still at the top.
        l.set_columns(5);
        assert_eq!(l.item_at(36), 350.0);
        assert_eq!(l.offset, 350.0);
        assert_eq!(l.take_splice_anchor(), 150.0);
        // Back to nine: item 36 again, not the first of the row it was in
        // (35), so resizing back and forth does not drift.
        l.set_columns(9);
        assert_eq!(l.offset, 200.0);
        l.set_columns(7);
        l.set_columns(4);
        l.set_columns(9);
        assert_eq!(l.offset, 200.0);
        // A new estimate for the rows not measured keeps it too.
        l.set_estimated(60.0);
        assert_eq!(l.offset, 240.0);
        l.set_estimated(50.0);
        // Scrolled to another row, its first item is kept.
        l.offset = 100.0;
        l.set_columns(5);
        assert_eq!(l.offset, 50.0 * (18 / 5) as f32);
        // At the top it stays at the top.
        let mut l = list(90, 50.0, 400.0);
        l.set_columns(9);
        l.set_columns(5);
        assert_eq!(l.offset, 0.0);
    }

    #[test]
    fn paced_lists_bind_the_viewport_now_and_the_overscan_ahead_first() {
        let mut l = list(1000, 50.0, 400.0);
        l.paced = true;
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        let now: Vec<u32> = binds.iter().map(|b| b.1).collect();
        assert_eq!(now, (0..8).collect::<Vec<_>>(), "the viewport");
        assert!(l.has_paced());
        binds.clear();
        assert_eq!(l.take_paced(3, &mut binds), 3);
        assert_eq!(binds.iter().map(|b| b.1).collect::<Vec<_>>(), [8, 9, 10]);
        while l.take_paced(100, &mut binds) > 0 {}
        assert!(!l.has_paced());

        // The platform reports the scroll: scrolling up by 50, the
        // viewport and four steps above it bind now; the rest above comes
        // before what is below.
        l.reported(2000.0, 0);
        l.update_window(&mut binds);
        while l.take_paced(100, &mut binds) > 0 {}
        l.reported(1950.0, 0);
        binds.clear();
        l.update_window(&mut binds);
        // 1600..2800 was bound already; 1550..1600 is new and, above
        // 1750, waits.
        assert_eq!(binds, []);
        // A jump binds its viewport only.
        l.reported(5000.0, 0);
        l.update_window(&mut binds);
        let now: Vec<u32> = binds.iter().map(|b| b.1).collect();
        assert_eq!(now, (100..108).collect::<Vec<_>>());
        // A step up before the overscan bound: the viewport (4975..5375)
        // and four steps ahead (4875..4975) bind now ...
        l.reported(4975.0, 0);
        binds.clear();
        l.update_window(&mut binds);
        let now: Vec<u32> = binds.iter().map(|b| b.1).collect();
        assert_eq!(now, (97..100).collect::<Vec<_>>());
        // ... the rest above before what is below.
        binds.clear();
        l.take_paced(3, &mut binds);
        assert_eq!(binds.iter().map(|b| b.1).collect::<Vec<_>>(), [96, 95, 94]);
    }

    /// Uneven steps (wheel notches, touchpad events bunched into frames)
    /// bind as far ahead as the fast ones while the scroll goes on the same
    /// way; a turn or a jump starts over from the step itself.
    #[test]
    fn a_fast_step_keeps_the_rows_ahead_binding_through_slow_ones() {
        assert_eq!(next_lead(0.0, 80.0, 400.0), 80.0);
        assert_eq!(next_lead(80.0, 20.0, 400.0), 60.0);
        assert_eq!(next_lead(60.0, 100.0, 400.0), 100.0);
        assert_eq!(next_lead(100.0, -20.0, 400.0), -20.0);
        assert_eq!(next_lead(-20.0, -10.0, 400.0), -15.0);
        // After a jump, the next step binds ahead of the viewport again.
        assert_eq!(next_lead(3000.0, 20.0, 400.0), 20.0);

        let mut l = list(1000, 50.0, 400.0);
        l.paced = true;
        let mut binds = Vec::new();
        l.reported(1000.0, 0);
        l.update_window(&mut binds);
        while l.take_paced(100, &mut binds) > 0 {}
        // A step of 100, then one of 10: the span ahead of the viewport is
        // four steps of the 75 kept, 300, not of the 10.
        l.reported(1100.0, 0);
        l.update_window(&mut binds);
        l.reported(1110.0, 0);
        binds.clear();
        l.update_window(&mut binds);
        assert!(binds.is_empty(), "{binds:?}");
        assert_eq!(l.urgent_span(l.natural_offset()), (1110.0, 1810.0));
    }

    /// A list at its start shows the rows that arrive above its first one,
    /// as a browser does; scrolled past it, the visible rows keep their
    /// place; loading pages at its start, they keep it there too.
    #[test]
    fn a_list_at_its_start_shows_the_rows_inserted_above_the_first() {
        let mut l = list(10, 50.0, 400.0);
        l.splice(0, 0, 3);
        assert_eq!((l.offset, l.take_splice_anchor()), (0.0, 0.0));
        l.offset = 100.0;
        l.splice(0, 0, 2);
        assert_eq!((l.offset, l.take_splice_anchor()), (200.0, 100.0));
        // The page a list loads at its start prepends must not show, or
        // the list would ask for the next at once.
        let mut l = list(10, 50.0, 400.0);
        l.loads_at_start = true;
        l.splice(0, 0, 3);
        assert_eq!((l.offset, l.take_splice_anchor()), (150.0, 150.0));
    }

    #[test]
    fn splices_tell_bound_cells_their_index_and_forget_gone_items() {
        let mut l = list(100, 50.0, 400.0);
        l.paced = true;
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        for &(slot, index) in &binds {
            l.add_slot_cell(CellSlot::Item(slot), 100 + slot);
            l.rendered(100 + slot, index);
        }
        // Overscan cells wait; one row arrives at the top.
        l.splice(0, 0, 1);
        binds.clear();
        l.update_window(&mut binds);
        // Every bound cell learns its new index, at once, and the new row
        // binds with them: the list is at its start, so the row shows. The
        // cells waiting below still wait: nothing of the user's moved.
        let now: Vec<u32> = binds.iter().map(|b| b.1).collect();
        assert_eq!(now, [1, 2, 3, 4, 5, 6, 7, 8, 0], "{binds:?}");
        assert!(l.has_paced());
        // The data shrinks under the cells still waiting: none is asked
        // for an item that is gone.
        l.splice(3, 98, 0);
        binds.clear();
        l.update_window(&mut binds);
        while l.take_paced(100, &mut binds) > 0 {}
        assert!(binds.iter().all(|&(_, i)| i < 3), "{binds:?}");
    }

    #[test]
    fn an_animated_pin_ends_when_the_list_moves_away_from_it() {
        let mut l = list(100, 50.0, 400.0);
        l.pin(Some(PinTarget::End), 4600.0, true);
        l.issue_scroll_to(4600.0);
        l.reported(3000.0, 1);
        l.reported(3500.0, 1);
        // Rows above measured: the web moves only where the animation
        // goes, not where the list is.
        l.measured(0, 150.0);
        assert_eq!(l.follow_pin(100.0), Follow::Stay);
        l.issue_scroll_by(100.0);
        l.reported(3500.0, 2);
        assert!(l.pinned(), "anchoring is no move away");
        l.reported(3900.0, 2);
        assert!(l.pinned());
        // A wheel turns it back.
        l.reported(3700.0, 2);
        assert!(!l.pinned());
    }

    #[test]
    fn pins_follow_until_landed_measured_or_scrolled_away() {
        let mut l = list(100, 50.0, 400.0);
        // An animated scroll to the end: retargeted when the end moves,
        // corrected once it landed.
        l.pin(Some(PinTarget::End), 4600.0, true);
        l.issue_scroll_to(4600.0);
        l.measured(99, 90.0);
        assert_eq!(l.follow_pin(0.0), Follow::To(4640.0));
        l.issue_scroll_to(4640.0);
        l.reported(3000.0, 2);
        assert!(l.pinned(), "in flight");
        l.reported(4640.0, 2);
        l.measured(98, 60.0);
        assert_eq!(l.follow_pin(0.0), Follow::By(10.0));
        assert_eq!(l.offset, 4650.0);
        assert!(l.pinned(), "rows in the viewport not measured yet");
        // The user scrolls away: the pin ends.
        l.reported(4000.0, 2);
        assert!(!l.pinned());
        // Splices end it too.
        l.pin(Some(PinTarget::End), 4650.0, false);
        l.splice(0, 1, 0);
        assert!(!l.pinned());
    }

    /// A list in its parent's viewport, 100 rows of 50, starting `start`
    /// down a page of `max + 400` in a 400 pt viewport scrolled to
    /// `offset`.
    fn in_page(start: f32, offset: f32, max: f32) -> ListState {
        let mut l = list(100, 50.0, 0.0);
        l.set_parent(true);
        l.set_outer(start, offset, 400.0, max, true);
        l
    }

    fn bound(l: &ListState) -> Vec<u32> {
        let mut bound: Vec<u32> = l.slots.iter().filter_map(|s| s.index).collect();
        bound.sort_unstable();
        bound
    }

    #[test]
    fn in_a_page_the_window_is_the_viewport_over_the_list() {
        // The list starts 100 below the viewport's top: its offset is
        // -100, and the rows from its start to 700 (the viewport and the
        // overscan below it) render.
        let mut l = in_page(100.0, 0.0, 4700.0);
        assert_eq!(l.offset, -100.0);
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        assert_eq!(bound(&l), (0..=14).collect::<Vec<_>>());
        // Entirely below the viewport and its overscan: nothing.
        let mut l = in_page(1000.0, 0.0, 4700.0);
        l.update_window(&mut binds);
        assert!(bound(&l).is_empty());
        // Scrolled past: nothing either.
        let mut l = in_page(0.0, 5500.0, 6000.0);
        l.update_window(&mut binds);
        assert!(bound(&l).is_empty());
    }

    #[test]
    fn in_a_page_load_more_fires_as_the_lists_end_nears() {
        // 20 rows (1000) below a 1000 pt header.
        let mut l = list(20, 50.0, 0.0);
        l.set_parent(true);
        let mut binds = Vec::new();
        for (offset, fires) in [(0.0, false), (1100.0, false), (1300.0, true)] {
            l.set_outer(1000.0, offset, 400.0, 1600.0, true);
            assert_eq!(l.update_window(&mut binds).end, fires, "at {offset}");
        }
    }

    #[test]
    fn in_a_page_only_changes_above_the_viewport_scroll_it() {
        // The list's start shows: rows growing move what is below them.
        let mut l = in_page(100.0, 0.0, 4700.0);
        assert_eq!(l.measured(0, 80.0), 0.0);
        l.splice(0, 0, 3);
        assert_eq!(l.take_splice_anchor(), 0.0);
        // Scrolled 1000 into it: a row above the viewport keeps the visible
        // rows in place, one in it does not.
        let mut l = in_page(100.0, 1100.0, 4700.0);
        assert_eq!(l.offset, 1000.0);
        assert_eq!(l.measured(2, 80.0), 30.0);
        assert_eq!(l.measured(25, 80.0), 0.0);
        l.splice(0, 0, 2);
        assert_eq!(l.take_splice_anchor(), 100.0);
    }

    #[test]
    fn in_a_page_scroll_targets_are_clamped_by_the_page() {
        // The page scrolls 4700: from the list's start, 100 down, it
        // reaches -100 to 4600 of the list.
        let l = in_page(100.0, 0.0, 4700.0);
        assert_eq!(l.offset_for_index(10, 0.0, 0.0), 500.0);
        assert_eq!(l.offset_for_index(99, 0.0, 0.0), 4600.0);
        assert_eq!(l.offset_for_index(0, 1.0, 0.0), -100.0);
        // The end of the list at the end of the viewport.
        assert_eq!(l.end_offset(), 4600.0);
        assert_eq!(l.clamped(-500.0), -100.0);
    }

    #[test]
    fn in_a_page_what_needs_a_scroll_view_of_its_own_is_off() {
        let mut l = list(100, 50.0, 400.0);
        l.set_inverted(true);
        l.set_sticky(vec![0]);
        l.set_parent(true);
        // Sticky rows stay: they stick to the view around the list.
        assert!(!l.inverted && l.sticky_enabled());
        assert_eq!(l.ignored, ignored::INVERTED);
        l.set_follow_end(Some(10.0));
        assert_eq!(l.follow_end, None);
        assert_ne!(l.ignored & ignored::FOLLOW_END, 0);
    }

    #[test]
    fn back_to_its_own_scroll_view_a_list_gets_back_what_parent_mode_set_aside() {
        let mut l = list(100, 50.0, 400.0);
        l.set_inverted(true);
        l.set_follow_end(Some(10.0));
        l.set_parent(true);
        l.set_parent(false);
        assert!(l.inverted);
        assert_eq!(l.follow_end, Some(10.0));
    }

    #[test]
    fn in_a_page_sticky_rows_travel_in_the_pages_offsets_to_the_lists_end() {
        // 100 rows of 50 from 100 down the page; rows 0 and 30 stick 20
        // below its top.
        let mut l = in_page(100.0, 0.0, 4700.0);
        l.set_sticky(vec![0, 30]);
        l.set_sticky_offset(20.0);
        // Row 0 sticks from 80 (its 100 less 20) until row 30 pushes it out.
        assert_eq!(
            l.sticky_range(0, 1, 50.0),
            StickyRange {
                cell: 1,
                start: 80.0,
                end: 100.0 + 1500.0 - 50.0 - 20.0,
                offset: None,
            }
        );
        // The last one stops with its bottom at the list's end (5100).
        let last = l.sticky_range(30, 2, 50.0);
        assert_eq!(last.start, 100.0 + 1500.0 - 20.0);
        assert_eq!(last.end, 100.0 + 5000.0 - 50.0 - 20.0);
        // Pinned in list coordinates, as in a list of its own.
        l.set_outer(100.0, 1700.0, 400.0, 4700.0, true);
        assert_eq!(l.active_sticky(), Some(30));
    }

    #[test]
    fn in_a_page_a_pin_survives_the_list_moving_in_the_page() {
        let mut l = in_page(100.0, 600.0, 4700.0);
        l.pin(
            Some(PinTarget::Index {
                index: 10,
                view_position: 0.0,
                view_offset: 0.0,
            }),
            500.0,
            false,
        );
        // A header above the list grows by 40: the page did not scroll,
        // the list moved.
        l.set_outer(140.0, 600.0, 400.0, 4740.0, true);
        assert!(l.pinned());
        // The user scrolls.
        l.set_outer(140.0, 900.0, 400.0, 4740.0, true);
        assert!(!l.pinned());
    }

    #[test]
    fn scroll_to_index() {
        let mut l = list(100, 50.0, 400.0);
        assert_eq!(l.offset_for_index(10, 0.0, 0.0), 500.0);
        assert_eq!(l.offset_for_index(10, 0.5, 0.0), 500.0 - 175.0);
        assert_eq!(l.offset_for_index(99, 0.0, 0.0), 5000.0 - 400.0);
        l.set_inverted(true);
        // Item 0 at the bottom of the viewport.
        assert_eq!(l.offset_for_index(0, 0.0, 0.0), 4600.0);
    }

    /// Binds the window and confirms what it asked, as the runtime does:
    /// the cells it made, by slot.
    fn bind_all(l: &mut ListState, binds: &mut Vec<(u32, u32)>) {
        binds.clear();
        l.update_window(binds);
        for &(slot, index) in binds.iter() {
            if l.slots[slot as usize].cell == u32::MAX {
                l.add_slot_cell(CellSlot::Item(slot), 100 + slot);
            }
            l.rendered(100 + slot, index);
        }
    }

    #[test]
    fn items_take_back_the_free_cell_that_still_shows_them() {
        let mut l = list(100, 50.0, 400.0);
        let mut binds = Vec::new();
        l.offset = 1000.0;
        bind_all(&mut l, &mut binds);
        let cells = |l: &ListState| -> Vec<(u32, u32)> {
            let mut c: Vec<_> = l
                .slots
                .iter()
                .filter_map(|s| s.index.map(|i| (i, s.cell)))
                .collect();
            c.sort_unstable();
            c
        };
        let before = cells(&l);
        // The viewport shrinks (a panel shows below the list), then grows
        // back: the rows at the edges leave the window, then return.
        l.viewport = 200.0;
        bind_all(&mut l, &mut binds);
        assert!(cells(&l).len() < before.len());
        l.viewport = 400.0;
        bind_all(&mut l, &mut binds);
        assert_eq!(cells(&l), before, "each row is back in its own cell");
        assert!(binds.is_empty(), "nothing to bind again: {binds:?}");
        // Scrolled a little, the window gives other rows the free cells.
        l.offset = 1200.0;
        bind_all(&mut l, &mut binds);
        assert!(!binds.is_empty());
    }

    #[test]
    fn free_cells_follow_their_items_through_splices() {
        let mut l = list(100, 50.0, 400.0);
        let mut binds = Vec::new();
        l.offset = 1000.0;
        bind_all(&mut l, &mut binds);
        let cell_of =
            |l: &ListState, i: u32| l.slots.iter().find(|s| s.index == Some(i)).map(|s| s.cell);
        let last = l.slots.iter().filter_map(|s| s.index).max().unwrap();
        let own = cell_of(&l, last).unwrap();
        // The window shrinks: the last row's cell is free, still showing it.
        l.viewport = 200.0;
        bind_all(&mut l, &mut binds);
        assert_eq!(cell_of(&l, last), None);
        // Two rows arrive at the top: the free cell is told its row's new
        // index, and gets it back when the window grows again.
        l.splice(0, 0, 2);
        binds.clear();
        l.update_window(&mut binds);
        let slot = l.slots.iter().position(|s| s.cell == own).unwrap() as u32;
        assert!(binds.contains(&(slot, last + 2)), "{binds:?}");
        l.viewport = 400.0;
        bind_all(&mut l, &mut binds);
        assert_eq!(cell_of(&l, last + 2), Some(own));
        assert!(!binds.iter().any(|&(s, _)| s == slot), "{binds:?}");
        // A free cell whose row went shows the row now at its index, which
        // no other cell shows: that row takes it back as it is.
        l.viewport = 200.0;
        bind_all(&mut l, &mut binds);
        assert_eq!(cell_of(&l, last + 2), None);
        l.splice(last + 2, 1, 0);
        let s = l.slots[slot as usize];
        assert_eq!(
            (s.rendered, s.requested, s.stale),
            (Some(last + 2), Some(last + 2), false)
        );
        l.viewport = 400.0;
        bind_all(&mut l, &mut binds);
        assert_eq!(cell_of(&l, last + 2), Some(own));
        assert!(!binds.iter().any(|&(s, _)| s == slot), "{binds:?}");
        // One whose index a row moved to with its own cell shows nothing of
        // its own: it is bound again before it shows.
        l.viewport = 200.0;
        bind_all(&mut l, &mut binds);
        let spare = |l: &ListState, i: u32| {
            (l.slots.iter())
                .position(|s| s.index.is_none() && s.requested == Some(i))
                .unwrap()
        };
        let (before, mine) = (spare(&l, last + 1), spare(&l, last + 2));
        l.splice(last + 1, 1, 0);
        let s = l.slots[before];
        assert_eq!((s.rendered, s.requested, s.stale), (None, None, true));
        let s = l.slots[mine];
        assert_eq!((s.rendered, s.requested), (Some(last + 1), Some(last + 1)));
    }

    #[test]
    fn kept_items_stay_rendered_out_of_the_window() {
        let mut l = list(100, 50.0, 400.0);
        l.set_kept(vec![2]);
        l.offset = 3000.0;
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        let bound = |l: &ListState, i: u32| l.slots.iter().any(|s| s.index == Some(i));
        assert!(bound(&l, 2), "{binds:?}");
        assert!(!bound(&l, 3));
        // An item inserted before it moves it along.
        l.splice(0, 0, 1);
        binds.clear();
        l.update_window(&mut binds);
        assert!(bound(&l, 3) && !bound(&l, 2), "{binds:?}");
        l.set_kept(Vec::new());
        binds.clear();
        l.update_window(&mut binds);
        assert!(!bound(&l, 3));
    }

    /// An inverted chat scrolled into its history (rows 84..92 on screen),
    /// laid out as the core lays it out: measurements, then the splice's
    /// scroll, then `anchor_end`. Returns where row 84 is on screen.
    fn inverted_history(loads_at_start: bool) -> ListState {
        let mut l = list(100, 50.0, 400.0);
        l.set_inverted(true);
        l.loads_at_start = loads_at_start;
        l.anchor_end(0.0);
        l.reported(400.0, 0);
        l
    }

    fn lay_out(l: &mut ListState, measured: &[(u32, f32)]) {
        let mut kept = 0.0;
        for &(i, size) in measured {
            kept += l.measured(i, size);
        }
        l.offset += kept;
        // As the core: the splice already moved the offset.
        let spliced = l.take_splice_anchor();
        l.anchor_end(kept + spliced);
    }

    #[test]
    fn follow_end_list_near_its_start_keeps_a_page_prepended_above() {
        // #1459: a chat that loads older pages at its start, with
        // `maintainVisibleContentPosition`, must not follow the end when a
        // page lands above the reader.
        let mut l = list(12, 66.0, 449.0);
        l.follow_end = Some(100.0);
        lay_out(&mut l, &(0..12).map(|i| (i, 66.0)).collect::<Vec<_>>());
        l.reported(30.0, 0);
        lay_out(&mut l, &[]);
        let before = l.to_content(l.item_at(0), 66.0) - l.offset;
        l.splice(0, 0, 6);
        lay_out(&mut l, &(0..6).map(|i| (i, 66.0)).collect::<Vec<_>>());
        let end = l.content_len() - l.viewport;
        assert!(
            l.offset < end - 100.0,
            "offset {} followed the end {end}",
            l.offset
        );
        assert_eq!(l.to_content(l.item_at(6), 66.0) - l.offset, before);
    }

    fn on_screen(l: &ListState, i: u32) -> f32 {
        l.to_content(l.item_at(i), 50.0) - l.offset
    }

    #[test]
    fn inverted_page_and_row_above_viewport_measured_in_one_layout() {
        // #1238: a page of older rows and a row above the viewport (in the
        // overscan) taking its height in the same layout.
        let mut l = inverted_history(true);
        let before = on_screen(&l, 84);
        l.splice(100, 0, 10);
        lay_out(&mut l, &[(93, 80.0)]);
        assert_eq!(on_screen(&l, 84), before);
    }

    #[test]
    fn inverted_page_and_row_above_viewport_in_separate_layouts() {
        let mut l = inverted_history(true);
        let before = on_screen(&l, 84);
        l.splice(100, 0, 10);
        lay_out(&mut l, &[]);
        assert_eq!(on_screen(&l, 84), before);
        lay_out(&mut l, &[(93, 80.0)]);
        assert_eq!(on_screen(&l, 84), before);
    }

    #[test]
    fn inverted_page_with_rows_below_and_above_viewport_in_one_layout() {
        // A row below the viewport grows too: the visible rows still stay.
        let mut l = inverted_history(true);
        let before = on_screen(&l, 84);
        l.splice(100, 0, 10);
        lay_out(&mut l, &[(80, 80.0), (93, 80.0)]);
        assert_eq!(on_screen(&l, 84), before);
    }

    #[test]
    fn inverted_without_load_more_at_start_keeps_its_distance_from_the_end() {
        let mut l = inverted_history(false);
        let distance = l.content_len() - l.offset;
        l.splice(100, 0, 10);
        lay_out(&mut l, &[(93, 80.0), (80, 80.0)]);
        // Row 80, below the viewport, moves the visible rows up by its
        // growth, as a list that keeps its distance from the end does.
        assert_eq!(l.content_len() - l.offset, distance);
    }

    #[test]
    fn inverted_at_its_start_follows_the_newest_row() {
        let mut l = inverted_history(true);
        l.reported(l.anchored_end, 0);
        l.splice(100, 0, 10);
        lay_out(&mut l, &[(0, 80.0), (8, 80.0)]);
        // Still at the end: item 0 shows at the bottom.
        assert_eq!(l.offset, l.content_len() - l.viewport);
    }

    #[test]
    fn list_not_inverted_keeps_rows_when_rows_above_are_measured() {
        let mut l = list(100, 50.0, 400.0);
        l.reported(1000.0, 0);
        let at = |l: &ListState| l.item_at(25) - l.offset;
        let before = at(&l);
        l.splice(100, 0, 10);
        lay_out(&mut l, &[(15, 80.0), (30, 80.0)]);
        assert_eq!(at(&l), before);
    }
}

#[cfg(test)]
mod perf {
    use std::time::Instant;

    use super::*;

    /// `cargo test -p nsh-core --release perf -- --ignored --nocapture`
    #[test]
    #[ignore]
    fn list_costs() {
        let n = 100_000u32;
        let mut l = ListState::new();
        l.set_estimated(40.0);
        l.viewport = 800.0;
        // Append one row at a time (a log / chat feed).
        let t = Instant::now();
        for c in 1..=n {
            l.set_count(c);
        }
        eprintln!("append 1-by-1 to {n}: {:?}", t.elapsed());
        let t = Instant::now();
        for c in 0..20_000u32 {
            l.splice(l.count, 0, 1);
            let _ = c;
        }
        eprintln!("splice-append 20k: {:?}", t.elapsed());
        let mut binds = Vec::new();
        l.update_window(&mut binds);
        for (slot, i) in binds.drain(..) {
            l.rendered(slot, i);
        }
        let t = Instant::now();
        let frames = 20_000;
        for f in 0..frames {
            l.offset = (f as f32) * 7.0;
            l.update_window(&mut binds);
            for (slot, i) in binds.drain(..) {
                l.rendered(slot, i);
                l.measured(i, 44.0);
            }
        }
        eprintln!("scroll frame avg: {:?}", t.elapsed() / frames);
    }
}