day-pieces 0.6.2

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

//! Data-driven structure pieces: `when` (conditional), `each` (keyed children from a fixed
//! sequence), `list` (a reactive, diffed collection), and the scoped `environment` context
//! (`with_environment` / `environment`).

use std::cell::{Cell, RefCell};
use std::collections::HashSet;
use std::hash::Hash;
use std::rc::Rc;

use day_core::*;
use day_reactive::{AnyBinding, Binding, Scope, Signal, watch};
use day_spec::props::*;

use crate::{Decorate, Decorated, IntoReactive, IntoText, MenuEntry, Reactive, TextSource};
use day_spec::{Event, Proposal, Rect, Size, kinds};

// ---------------------------------------------------------------------------
// Structure: when / each (§5.3–§5.4)
// ---------------------------------------------------------------------------

/// Reactive conditional subtree. The anchor is a layout-transparent group; the active arm
/// lives in its own child scope, disposed on switch (§4.3).
///
/// A bare `when` builds nothing while the condition is false. Chain
/// [`otherwise`](When::otherwise) for the either/or case:
///
/// ```ignore
/// when(move || ok.get(), || label("Saved")).otherwise(|| label("Failed"))
/// ```
///
/// Prefer a binding to a flip when both arms are the same widget with different content:
/// `label(move || if ok.get() { "Saved" } else { "Failed" })` keeps one native label alive and
/// costs one setter call, where a `when` swap destroys and recreates native widgets.
pub fn when<P: Piece>(
    cond: impl Fn() -> bool + 'static,
    build_arm: impl Fn() -> P + 'static,
) -> When {
    When {
        cond: Rc::new(cond),
        then: Rc::new(move || AnyPiece::new(build_arm())),
        otherwise: None,
    }
}

/// A conditional subtree, optionally with an else arm. Built by [`when`].
pub struct When {
    cond: Rc<dyn Fn() -> bool>,
    then: Rc<dyn Fn() -> AnyPiece>,
    otherwise: Option<Rc<dyn Fn() -> AnyPiece>>,
}

#[day_macros::builder(WhenBuilder)]
impl When {
    /// The arm built while the condition is false. Without it, false means "no subtree".
    ///
    /// The two arms need not return the same `Piece` type; each is erased to [`AnyPiece`] here.
    /// Exactly one arm is mounted at a time, in its own child scope, so flipping disposes the
    /// outgoing arm's signals, bindings, and handlers before the incoming arm builds (§4.3).
    pub fn otherwise<P: Piece>(mut self, build_arm: impl Fn() -> P + 'static) -> Self {
        self.otherwise = Some(Rc::new(move || AnyPiece::new(build_arm())));
        self
    }
}

impl Piece for When {
    fn build(self, cx: &mut BuildCx) -> RNode {
        let anchor = cx.layout_only(
            Rc::new(PassThrough),
            Flex {
                is_group: true,
                ..Default::default()
            },
            Boundary::No,
        );
        let state: Rc<RefCell<Option<Scope>>> = Rc::new(RefCell::new(None));
        // The scope this `when` is built in, captured here because `mount` below runs from a
        // reaction, and a reaction re-runs with no scope of its own, so `Scope::child()` there
        // would parent the incoming arm to the root scope. That misplaces the arm in two ways:
        // it is no longer owned by the subtree it visually belongs to, and an ambient value an
        // ancestor provided is no longer above it, so `environment`/`Ambient::ambient` inside a
        // re-mounted arm cannot see it (docs/state.md).
        let owner = Scope::current();
        let When {
            cond,
            then,
            otherwise,
        } = self;

        let mount = {
            let state = state.clone();
            move |on: bool| {
                // Same lifetime hazard as `each`'s sync, and the same answer; see the note there.
                if !with_tree(|t| t.node_exists(anchor)) {
                    return;
                }
                // Unmount whatever is up before building the incoming arm: with two arms, every
                // flip is a swap, and the outgoing scope must be disposed before its replacement
                // builds so a rebuilt arm never observes the old arm's still-live bindings.
                if let Some(scope) = state.borrow_mut().take() {
                    scope.dispose();
                    // Remove everything under the anchor.
                    while with_tree(|t| t.child_count(anchor)) > 0 {
                        let child = with_tree(|t| t.first_child(anchor));
                        match child {
                            Some(c) => with_tree(|t| t.remove_subtree(c)),
                            None => break,
                        }
                    }
                }
                let arm = if on { Some(&then) } else { otherwise.as_ref() };
                if let Some(arm) = arm {
                    let scope = owner.enter(Scope::child);
                    scope.enter(|| {
                        let mut cx = BuildCx::new(anchor);
                        let _ = arm().build(&mut cx);
                    });
                    *state.borrow_mut() = Some(scope);
                }
            }
        };

        let initial = {
            let cond = cond.clone();
            day_reactive::untrack(move || cond())
        };
        mount(initial);
        watch(
            move || cond(),
            move |now, old| {
                if Some(now) != old {
                    mount(*now);
                }
            },
        );
        anchor
    }
}

/// Build a row's pieces in a scope of their own, inside the scope that owns the row's slot.
///
/// Disposal runs children first, and a scope frees its signals before it runs its cleanups. A
/// row's teardown reaches back through the slot (a text field seals the edit in progress with
/// `Binding::write_teardown`, and a model slot resolves its row through its key signal), so
/// the slot has to outlive every cleanup the row registered. With the row one scope down, its
/// cleanups run while the slot's signals still stand.
fn in_row_scope<R>(build: impl FnOnce() -> R) -> R {
    Scope::child().enter(build)
}

/// A `Copy` handle to one keyed item's state: the unified `each`/`list` contract (§5.4).
pub struct ItemSlot<T: 'static, K: 'static> {
    sig: Signal<T>,
    key: Signal<K>,
}

impl<T: 'static, K: 'static> Clone for ItemSlot<T, K> {
    fn clone(&self) -> Self {
        *self
    }
}
impl<T: 'static, K: 'static> Copy for ItemSlot<T, K> {}

impl<T: Clone + 'static, K: Clone + 'static> ItemSlot<T, K> {
    /// Tracked whole-item read. **Read it inside a reactive closure**, e.g.
    /// `label(move || slot.get())`, not eagerly. A recycling [`list()`] rebinds one physical row to
    /// many items, and only bindings that read the slot reactively update on rebind; an eager
    /// `let name = slot.get()` freezes the row at its first item.
    pub fn get(self) -> T {
        self.sig.get()
    }
    /// Tracked read via a projection. Read it inside a reactive closure (see [`get`](Self::get)).
    pub fn with<R>(self, f: impl FnOnce(&T) -> R) -> R {
        self.sig.with(f)
    }
    /// Tracked field projection (equality-gating happens in the binding layer). Read it inside a
    /// reactive closure (see [`get`](Self::get)) so recycled rows update on rebind.
    pub fn field<V: Clone>(self, f: impl FnOnce(&T) -> V) -> V {
        self.sig.with(f)
    }
    /// Tracked identity read, so reactive ids and row actions follow cell recycling.
    /// Read inside a closure, just like [`get`](Self::get).
    pub fn key(self) -> K {
        self.key.get()
    }
}

// ---------------------------------------------------------------------------
// keyed / switch / load / adaptive: the structure idioms every app re-derived (§5.3)
// ---------------------------------------------------------------------------

/// A subtree keyed by a value: rebuilt when the key changes, left alone while it does not
/// (so focus and local state survive), nothing while it is `None`.
///
/// ```ignore
/// keyed(move || scene.selected.get(), |id| editor(id))
/// ```
///
/// `key` is one tracked read, compared with `PartialEq` on every change. The outgoing subtree's
/// scope is disposed before the incoming one builds, which aborts its pending tasks and
/// subscriptions, exactly as [`when`] does. This is what `each` over a one-item list stood in
/// for; for an either/or on a `bool`, [`when`] reads better.
pub fn keyed<K, P>(
    key: impl Fn() -> Option<K> + 'static,
    build: impl Fn(&K) -> P + 'static,
) -> Keyed<K>
where
    K: PartialEq + Clone + 'static,
    P: Piece,
{
    Keyed {
        key: Rc::new(key),
        build: Rc::new(move |k| AnyPiece::new(build(k))),
    }
}

/// One tracked read, one arm (docs/state.md): a subtree per value of `selector`, rebuilt when
/// the value changes. The arm closure usually matches, so its arms erase with `.any()`:
///
/// ```ignore
/// switch(move || tab.get(), |t| match t {
///     Tab::Body => body_pane().any(),
///     Tab::Headers => headers_pane().any(),
/// })
/// ```
///
/// Revisiting a value builds its arm afresh; inactive arms are not kept alive. State that must
/// survive a switch belongs in the model, not the subtree. Replaces runs of sibling
/// `when(move || tab.get() == …, …)`.
pub fn switch<K, P>(selector: impl Fn() -> K + 'static, arm: impl Fn(&K) -> P + 'static) -> Keyed<K>
where
    K: PartialEq + Clone + 'static,
    P: Piece,
{
    keyed(move || Some(selector()), arm)
}

/// The piece [`keyed`] and [`switch`] build: an anchor whose single child subtree follows a key.
pub struct Keyed<K: 'static> {
    key: Rc<dyn Fn() -> Option<K>>,
    build: Rc<dyn Fn(&K) -> AnyPiece>,
}

impl<K: PartialEq + Clone + 'static> Piece for Keyed<K> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        let anchor = cx.layout_only(
            Rc::new(PassThrough),
            Flex {
                is_group: true,
                ..Default::default()
            },
            Boundary::No,
        );
        // Captured for the same reason `When::build` captures it: the watch below runs with no
        // scope of its own, and the incoming subtree must be owned by this piece's subtree and
        // see its ambient values (docs/state.md).
        let owner = Scope::current();
        let Keyed { key, build } = self;
        let live: Rc<RefCell<Option<Scope>>> = Rc::new(RefCell::new(None));
        let mount = {
            let live = live.clone();
            move |k: &Option<K>| {
                if !with_tree(|t| t.node_exists(anchor)) {
                    return;
                }
                // The outgoing subtree first, so a rebuilt arm never observes the old arm's
                // still-live bindings.
                if let Some(scope) = live.borrow_mut().take() {
                    scope.dispose();
                    while with_tree(|t| t.child_count(anchor)) > 0 {
                        match with_tree(|t| t.first_child(anchor)) {
                            Some(c) => with_tree(|t| t.remove_subtree(c)),
                            None => break,
                        }
                    }
                }
                if let Some(k) = k {
                    let scope = owner.enter(Scope::child);
                    scope.enter(|| {
                        let mut cx = BuildCx::new(anchor);
                        let _ = build(k).build(&mut cx);
                    });
                    *live.borrow_mut() = Some(scope);
                }
            }
        };
        let initial = {
            let key = key.clone();
            day_reactive::untrack(move || key())
        };
        mount(&initial);
        // `watch` compares with `PartialEq`: an unchanged key never reaches `mount`.
        watch(
            move || key(),
            move |now, old| {
                if Some(now) != old {
                    mount(now);
                }
            },
        );
        anchor
    }
}

/// Where a [`load`] reads its state: a [`Resource`](day_reactive::Resource), a
/// `Signal<Load<T>>`, or a closure. The marker is the same E0119 dodge as [`IntoText`].
pub trait LoadSource<T: 'static, M>: 'static {
    fn into_load_reader(self) -> Rc<dyn Fn() -> day_reactive::Load<T>>;
}

/// Marker for a [`Resource`](day_reactive::Resource).
pub struct ResourceMark;

impl<T: Clone + 'static> LoadSource<T, ResourceMark> for day_reactive::Resource<T> {
    fn into_load_reader(self) -> Rc<dyn Fn() -> day_reactive::Load<T>> {
        Rc::new(move || self.signal().get())
    }
}

impl<T: Clone + 'static> LoadSource<T, crate::SignalMark> for Signal<day_reactive::Load<T>> {
    fn into_load_reader(self) -> Rc<dyn Fn() -> day_reactive::Load<T>> {
        Rc::new(move || self.get())
    }
}

impl<T: 'static, F: Fn() -> day_reactive::Load<T> + 'static> LoadSource<T, crate::FnMark> for F {
    fn into_load_reader(self) -> Rc<dyn Fn() -> day_reactive::Load<T>> {
        Rc::new(self)
    }
}

/// The loaded value, handed to a [`load`]'s ready arm: `get()` is a tracked read that follows
/// `Ready(a)` to `Ready(b)` in place, without rebuilding the arm. `Copy`, like a signal.
pub struct Loaded<T: 'static> {
    source: Rc<dyn Fn() -> day_reactive::Load<T>>,
    last: Rc<RefCell<T>>,
}

impl<T: 'static> Clone for Loaded<T> {
    fn clone(&self) -> Self {
        Loaded {
            source: self.source.clone(),
            last: self.last.clone(),
        }
    }
}

impl<T: Clone + 'static> Loaded<T> {
    /// The value, tracked: inside a label or a binding this follows a reload's new value.
    /// While the state is between values (loading again, or failed) the last ready value is
    /// returned, so the arm never sees a hole.
    pub fn get(&self) -> T {
        if let day_reactive::Load::Ready(v) = (self.source)() {
            *self.last.borrow_mut() = v.clone();
            v
        } else {
            self.last.borrow().clone()
        }
    }
    /// A tracked read through a projection, without cloning the whole value.
    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
        let v = self.get();
        f(&v)
    }
}

/// The three states of an async load as three subtrees (docs/async.md): the ready arm, and
/// optional [`loading`](LoadPiece::loading) and [`failed`](LoadPiece::failed) arms (nothing is
/// built for a state without an arm). Arms rebuild only when the *variant* changes; a new
/// ready value updates the ready arm in place through [`Loaded::get`].
///
/// ```ignore
/// load(stations, |s| station_list(s))
///     .loading(spinner)
///     .failed(|e| label(e.to_string()).secondary())
/// ```
///
/// Whether a refetch passes through `Loading` is the [`Resource`](day_reactive::Resource)'s
/// policy; an app that wants its stale content shown during a refresh keeps the last value in
/// its own state and the ready arm reads it.
pub fn load<T, P, M>(
    state: impl LoadSource<T, M>,
    ready: impl Fn(Loaded<T>) -> P + 'static,
) -> LoadPiece<T>
where
    T: Clone + 'static,
    P: Piece,
{
    LoadPiece {
        source: state.into_load_reader(),
        ready: Rc::new(move |v| AnyPiece::new(ready(v))),
        loading: None,
        failed: None,
    }
}

/// The piece [`load`] builds.
pub struct LoadPiece<T: 'static> {
    source: Rc<dyn Fn() -> day_reactive::Load<T>>,
    ready: Rc<dyn Fn(Loaded<T>) -> AnyPiece>,
    loading: Option<Rc<dyn Fn() -> AnyPiece>>,
    failed: Option<FailedArm>,
}

/// A [`load`]'s failed arm: the error in, the subtree out.
type FailedArm = Rc<dyn Fn(&(dyn std::error::Error + 'static)) -> AnyPiece>;

impl<T: Clone + 'static> LoadPiece<T> {
    /// The subtree shown while loading (a spinner, a skeleton).
    pub fn loading<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
        self.loading = Some(Rc::new(move || AnyPiece::new(build())));
        self
    }
    /// The subtree shown after a failure, given the error.
    pub fn failed<P: Piece>(
        mut self,
        build: impl Fn(&(dyn std::error::Error + 'static)) -> P + 'static,
    ) -> Self {
        self.failed = Some(Rc::new(move |e| AnyPiece::new(build(e))));
        self
    }
}

/// Which arm a [`load`] shows: the variant alone, so a new ready value is an update, not a swap.
#[derive(Clone, Copy, PartialEq, Eq)]
enum LoadArm {
    Loading,
    Ready,
    Failed,
}

impl<T: Clone + 'static> Piece for LoadPiece<T> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        let LoadPiece {
            source,
            ready,
            loading,
            failed,
        } = self;
        let arm_source = source.clone();
        let error_source = source.clone();
        keyed(
            move || {
                Some(match arm_source() {
                    day_reactive::Load::Loading => LoadArm::Loading,
                    day_reactive::Load::Ready(_) => LoadArm::Ready,
                    day_reactive::Load::Failed(_) => LoadArm::Failed,
                })
            },
            move |arm| match arm {
                LoadArm::Loading => loading.as_ref().map(|f| f()),
                LoadArm::Failed => {
                    failed
                        .as_ref()
                        .and_then(|f| match day_reactive::untrack(|| error_source()) {
                            day_reactive::Load::Failed(e) => Some(f(&*e)),
                            _ => None,
                        })
                }
                LoadArm::Ready => match day_reactive::untrack(|| source()) {
                    day_reactive::Load::Ready(v) => Some(ready(Loaded {
                        source: source.clone(),
                        last: Rc::new(RefCell::new(v)),
                    })),
                    _ => None,
                },
            },
        )
        .build(cx)
    }
}

/// A stack that is a row on a regular width and a column on a compact one, re-laid out (never
/// rebuilt) as the window crosses the breakpoint, so its children keep their state. The
/// shape a label-plus-control-plus-result line wants, where wrapping members independently
/// would tear apart what reads as one sentence.
///
/// ```ignore
/// adaptive((label(t), slider(v), label(move || v.get().to_string()))).spacing(Space::S)
/// ```
///
/// Stacked, the children align leading: they read as a control and the line it produced, and
/// a centered member floats away from what it belongs to. `at` (default
/// [`WidthClass::Compact`](day_spec::WidthClass::Compact)) is the widest class that stacks.
pub fn adaptive<C: PieceSeq>(children: C) -> Adaptive<C> {
    Adaptive {
        children,
        spacing: 0.0,
        at: day_spec::WidthClass::Compact,
        align: CrossAlign::Center,
    }
}

/// The piece [`adaptive`] builds.
pub struct Adaptive<C: PieceSeq> {
    children: C,
    spacing: f64,
    at: day_spec::WidthClass,
    align: CrossAlign,
}

#[day_macros::builder(AdaptiveBuilder)]
impl<C: PieceSeq> Adaptive<C> {
    /// The gap between children, in either arrangement: a [`Space`](crate::Space) step or points.
    pub fn spacing(mut self, s: impl Into<f64>) -> Self {
        self.spacing = s.into();
        self
    }
    /// The widest [`WidthClass`](day_spec::WidthClass) at which the children stack.
    pub fn stack_at(mut self, at: day_spec::WidthClass) -> Self {
        self.at = at;
        self
    }
    /// The cross-axis alignment while the children sit in a row (default centered, as a
    /// [`row`](crate::row)); stacked, they always align leading.
    pub fn align(mut self, a: crate::VAlign) -> Self {
        self.align = match a {
            crate::VAlign::Top => CrossAlign::Leading,
            crate::VAlign::Center => CrossAlign::Center,
            crate::VAlign::Bottom => CrossAlign::Trailing,
            crate::VAlign::FirstBaseline => CrossAlign::FirstBaseline,
        };
        self
    }
}

/// The adaptive stack's layout: a [`StackLayout`] whose axis is a cell the size-class watch
/// flips, so a crossing is a relayout of the same nodes.
struct AdaptiveLayout {
    axis: std::cell::Cell<Axis>,
    spacing: f64,
    row_align: CrossAlign,
}

impl AdaptiveLayout {
    fn stack(&self) -> StackLayout {
        let axis = self.axis.get();
        StackLayout {
            axis,
            spacing: self.spacing,
            align: match axis {
                Axis::Vertical => CrossAlign::Leading,
                Axis::Horizontal => self.row_align,
            },
        }
    }
}

impl Layout for AdaptiveLayout {
    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
        self.stack().measure(cx, children, p)
    }
    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
        self.stack().place(cx, children, bounds)
    }
    fn baseline(&self, cx: &mut dyn LayoutOps, children: &[RNode], size: Size) -> Option<f64> {
        self.stack().baseline(cx, children, size)
    }
}

impl<C: PieceSeq> Piece for Adaptive<C> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        let at = self.at;
        let stacked = move || size_class().is_some_and(|c| c.width <= at);
        let layout = Rc::new(AdaptiveLayout {
            axis: std::cell::Cell::new(if day_reactive::untrack(stacked) {
                Axis::Vertical
            } else {
                Axis::Horizontal
            }),
            spacing: self.spacing,
            row_align: self.align,
        });
        let node = cx.native(
            kinds::CONTAINER,
            &ContainerProps::default(),
            layout.clone(),
            Flex::default(),
            Boundary::No,
        );
        cx.under(node, |cx| self.children.build_each(cx));
        // Crossing the breakpoint flips the axis and re-lays the same children out.
        watch(stacked, move |now: &bool, _| {
            layout.axis.set(if *now {
                Axis::Vertical
            } else {
                Axis::Horizontal
            });
            day_core::invalidate_size(node);
        });
        node
    }
}

// ---------------------------------------------------------------------------
// Row sources: where `each` and `list` get their rows (§5.4, docs/list.md)
// ---------------------------------------------------------------------------

/// Where a collection's rows come from. [`each`]`(source, row)` and [`list()`]`(source, row)`
/// accept anything implementing this: plain data via [`items`]`(closure, key_of)`, or (with
/// the `model` feature) a day-model store directly (collection order) or
/// `store.rows(projection)` (a tracked display projection of key ids).
pub trait RowSource {
    /// What a row builder receives.
    type Slot: Copy + 'static;
    /// What selection callbacks hand the app.
    type Ref: 'static;
    type Conn: RowConn<Slot = Self::Slot, Ref = Self::Ref>;
    fn connect(self) -> Self::Conn;
}

/// One collection's live connection to its data, held for the life of the `each`/`list` that
/// [`RowSource::connect`]ed it.
pub trait RowConn: 'static {
    type Slot: Copy + 'static;
    type Ref: 'static;

    /// Refresh the snapshot and return the display rows as identity tokens. A tracked read: the
    /// enclosing watch re-runs exactly when something this read depends on changes; for a
    /// store source that is the collection's shape (or the projection's own reads), never the
    /// fields a row merely displays.
    fn refresh(&self) -> Vec<u64>;
    /// Row count of the current snapshot (no tracking).
    fn len(&self) -> usize;
    fn is_empty(&self) -> bool {
        self.len() == 0
    }
    /// Identity token of row `index` in the current snapshot.
    fn token_at(&self, index: usize) -> u64;
    /// The current tokens, no refresh and no tracking; the reorder/delete echo compares these.
    fn tokens_now(&self) -> Vec<u64>;
    /// A fresh slot for row `index` (`None` on a stale mid-animation pull). Call inside the
    /// row's scope: plain-data slots allocate their signals here.
    fn slot_at(&self, index: usize) -> Option<Self::Slot>;
    /// Point an existing slot at row `index`: the recycle write.
    fn rebind(&self, slot: &Self::Slot, index: usize);
    /// The selection currency for row `index`.
    fn select_ref(&self, index: usize) -> Option<Self::Ref>;
    /// Whether row values reach existing rows only through reload→rebind. Plain-data rows say
    /// true (their slots hold copies); store rows say false (values flow through the store's
    /// per-field notifications), which lets `list` skip the native reload entirely when the
    /// row set is unchanged.
    fn values_flow_by_reload(&self) -> bool;
    /// What changed since the last refresh, if the source can say precisely: sequential
    /// row deltas a host can animate. `None` means unknown: the list reloads, which is
    /// always correct. Only sources that maintain their set incrementally (a live query)
    /// answer `Some`.
    fn take_row_events(&self) -> Option<Vec<day_spec::props::RowDelta>> {
        None
    }
    /// Rotate the snapshot for a committed native move (display indices).
    fn commit_move(&self, from: usize, to: usize);
    /// Drop a row from the snapshot for a committed native delete.
    fn commit_delete(&self, index: usize);
}

/// Plain-data rows: an items closure plus a key function, as in
/// `list(items(model::ordered, |i: &Item| i.id), row_view)`.
pub fn items<T, K>(
    f: impl Fn() -> Vec<T> + 'static,
    key_of: impl Fn(&T) -> K + 'static,
) -> Items<T, K>
where
    T: Clone + 'static,
    K: Clone + Hash + 'static,
{
    Items {
        f: Rc::new(f),
        key_of: Rc::new(key_of),
    }
}

/// The plain-data [`RowSource`] built by [`items`].
pub struct Items<T: 'static, K: 'static> {
    f: Rc<dyn Fn() -> Vec<T>>,
    key_of: Rc<dyn Fn(&T) -> K>,
}

impl<T: Clone + 'static, K: Clone + Hash + 'static> RowSource for Items<T, K> {
    type Slot = ItemSlot<T, K>;
    type Ref = K;
    type Conn = ItemsConn<T, K>;
    fn connect(self) -> ItemsConn<T, K> {
        ItemsConn {
            f: self.f,
            key_of: self.key_of,
            snapshot: RefCell::new(Vec::new()),
            tokens: RefCell::new(Vec::new()),
        }
    }
}

/// [`Items`]' connection: the current data snapshot the slots read from.
pub struct ItemsConn<T: 'static, K: 'static> {
    f: Rc<dyn Fn() -> Vec<T>>,
    key_of: Rc<dyn Fn(&T) -> K>,
    snapshot: RefCell<Vec<T>>,
    tokens: RefCell<Vec<u64>>,
}

impl<T: Clone + 'static, K: Clone + Hash + 'static> RowConn for ItemsConn<T, K> {
    type Slot = ItemSlot<T, K>;
    type Ref = K;

    fn refresh(&self) -> Vec<u64> {
        let its = (self.f)();
        let toks: Vec<u64> = its.iter().map(|t| key_token(&(self.key_of)(t))).collect();
        *self.snapshot.borrow_mut() = its;
        *self.tokens.borrow_mut() = toks.clone();
        toks
    }
    fn len(&self) -> usize {
        self.snapshot.borrow().len()
    }
    fn token_at(&self, index: usize) -> u64 {
        self.tokens.borrow().get(index).copied().unwrap_or(0)
    }
    fn tokens_now(&self) -> Vec<u64> {
        self.tokens.borrow().clone()
    }
    fn slot_at(&self, index: usize) -> Option<ItemSlot<T, K>> {
        let item = self.snapshot.borrow().get(index).cloned()?;
        let key = (self.key_of)(&item);
        Some(ItemSlot {
            sig: Signal::new(item),
            key: Signal::new(key),
        })
    }
    fn rebind(&self, slot: &ItemSlot<T, K>, index: usize) {
        let Some(item) = self.snapshot.borrow().get(index).cloned() else {
            return; // stale recycle index: skip, the next bind corrects it
        };
        slot.key.set((self.key_of)(&item));
        slot.sig.set(item);
    }
    fn select_ref(&self, index: usize) -> Option<K> {
        self.snapshot.borrow().get(index).map(|t| (self.key_of)(t))
    }
    fn values_flow_by_reload(&self) -> bool {
        true
    }
    fn commit_move(&self, from: usize, to: usize) {
        let mut snap = self.snapshot.borrow_mut();
        let mut toks = self.tokens.borrow_mut();
        if from >= snap.len() || to >= snap.len() {
            return;
        }
        let item = snap.remove(from);
        snap.insert(to, item);
        let tok = toks.remove(from);
        toks.insert(to, tok);
    }
    fn commit_delete(&self, index: usize) {
        let mut snap = self.snapshot.borrow_mut();
        let mut toks = self.tokens.borrow_mut();
        if index >= snap.len() {
            return;
        }
        snap.remove(index);
        toks.remove(index);
    }
}

struct EachRow<S: 'static> {
    token: u64,
    slot: S,
    scope: Scope,
    root: RNode,
}

/// Reactive keyed collection (§5.4): keyed diff, per-key child scopes, slot rebinds for
/// surviving rows, debug key-uniqueness assertion. Takes any [`RowSource`].
pub fn each<S, P>(source: S, build_row: impl Fn(S::Slot) -> P + 'static) -> impl Piece
where
    S: RowSource + 'static,
    P: Piece,
{
    piece_fn(move |cx| {
        let anchor = cx.layout_only(
            Rc::new(PassThrough),
            Flex {
                is_group: true,
                ..Default::default()
            },
            Boundary::No,
        );
        // The scope this `each` is built in. `sync` below runs from a reaction, where
        // `Scope::child()` would parent a new row to the root scope instead of to this piece;
        // see the same capture in `When::build` for why that matters (docs/state.md).
        let owner = Scope::current();
        let conn = Rc::new(source.connect());
        let rows: Rc<RefCell<Vec<EachRow<S::Slot>>>> = Rc::new(RefCell::new(Vec::new()));
        let build_row = Rc::new(build_row);

        let sync = {
            let rows = rows.clone();
            let conn = conn.clone();
            let build_row = build_row.clone();
            move |tokens: &Vec<u64>| {
                // The reaction driving this closure can outlive the subtree it builds into: a
                // page swapped out of a nav, a `when` arm closed above us, and the anchor is gone
                // while the reaction is still subscribed. Building into a removed parent panics in
                // `Tree::attach`, and that panic is contained at the native event boundary, which
                // abandons the rest of the drain, so every reaction queued behind it is skipped
                // and the UI stops updating until something rebuilds it. An anchor that is no
                // longer in the tree has nothing to sync, so leave quietly.
                if !with_tree(|t| t.node_exists(anchor)) {
                    return;
                }
                if cfg!(debug_assertions) {
                    let mut seen = HashSet::new();
                    for k in tokens {
                        assert!(seen.insert(*k), "day: duplicate key in `each` diff");
                    }
                }
                let mut old = std::mem::take(&mut *rows.borrow_mut());
                let mut next: Vec<EachRow<S::Slot>> = Vec::with_capacity(tokens.len());
                for (index, tok) in tokens.iter().enumerate() {
                    if let Some(pos) = old.iter().position(|r| r.token == *tok) {
                        let row = old.remove(pos);
                        // Surviving row: one rebind (plain data refreshes the slot's copy;
                        // a store slot is a no-op when the key is unchanged).
                        conn.rebind(&row.slot, index);
                        next.push(row);
                    } else {
                        let scope = owner.enter(Scope::child);
                        let built = scope.enter(|| {
                            let slot = conn.slot_at(index)?;
                            let mut cx = BuildCx::new(anchor);
                            Some((slot, in_row_scope(|| build_row(slot).build(&mut cx))))
                        });
                        match built {
                            Some((slot, root)) => next.push(EachRow {
                                token: *tok,
                                slot,
                                scope,
                                root,
                            }),
                            None => scope.dispose(),
                        }
                    }
                }
                // Removals.
                for row in old {
                    row.scope.dispose();
                    with_tree(|t| t.remove_subtree(row.root));
                }
                // Order: reattach in the new sequence.
                let order: Vec<RNode> = next.iter().map(|r| r.root).collect();
                with_tree(|t| t.reorder_children(anchor, order));
                *rows.borrow_mut() = next;
            }
        };

        let initial = {
            let conn = conn.clone();
            day_reactive::untrack(move || conn.refresh())
        };
        sync(&initial);
        let conn2 = conn.clone();
        watch(move || conn2.refresh(), move |new, _| sync(new));
        anchor
    })
}

// ---------------------------------------------------------------------------
// `list`: native recycling list (docs/list.md, §10)
// ---------------------------------------------------------------------------

/// Stable u64 identity token for a key, for the native list's diffing.
fn key_token<K: Hash>(k: &K) -> u64 {
    use std::hash::Hasher;
    let mut h = std::collections::hash_map::DefaultHasher::new();
    k.hash(&mut h);
    h.finish()
}

/// A native recycling list: the platform widget owns scrolling + cell reuse; Day builds each
/// visible row once and *rebinds* it as cells recycle. Takes any [`RowSource`]; shares the row
/// contract with [`each`], so migrating a collection between them is a one-word change.
pub struct List<S: RowSource> {
    source: Option<S>,
    build_row: Rc<dyn Fn(S::Slot) -> AnyPiece>,
    row_height: RowHeight,
    on_select: Option<Rc<dyn Fn(S::Ref)>>,
    on_activate: Option<Rc<dyn Fn(S::Ref)>>,
    on_selection: Option<SelectionFn<S::Ref>>,
    multi_select: bool,
    selected_rows: Option<Rc<dyn Fn() -> Vec<usize>>>,
    selection: Option<ListSelection<S::Ref>>,
    scroll_to_end: Option<day_reactive::Trigger>,
    scroll_to_row: Option<AnyBinding<Option<usize>>>,
    first_visible_row: Option<AnyBinding<usize>>,
    stick_to_bottom: bool,
    reorder: Option<Reorder>,
    delete: Option<Delete>,
    swipe_leading: Option<SwipeProvider>,
    swipe_trailing: Option<SwipeProvider>,
    separators: Option<bool>,
    editing: crate::Reactive<bool>,
    sections: Option<ListSections<S::Slot>>,
}

/// [`List::sections`]: each item's section key (by index, hashed to a token) and the header
/// builder, which receives the slot of its section's first item.
struct ListSections<Slot> {
    key: Rc<dyn Fn(usize) -> u64>,
    header: Rc<dyn Fn(Slot) -> AnyPiece>,
}

/// The full-set selection callback, aliased for the field above.
type SelectionFn<R> = Rc<dyn Fn(Vec<R>)>;

/// A row reference that names its row by a key: what [`List::selection`] binds. A day-model
/// store's rows (an `Elem`) answer their key, which is also the row's identity token.
pub trait SelectionKey {
    fn selection_key(&self) -> u64;
}

/// [`List::selection`]'s two directions: the key to select (a tracked read) and the write that
/// reports the user's choice.
struct ListSelection<R> {
    key: Rc<dyn Fn() -> Option<u64>>,
    write: Rc<dyn Fn(Option<u64>)>,
    key_of: Rc<dyn Fn(&R) -> u64>,
}

// ---------------------------------------------------------------------------
// List items (docs/list.md "List items")
// ---------------------------------------------------------------------------

/// A list item's leading glyph: an app vector, which may follow a signal, or a standard symbol.
#[derive(Clone)]
enum ItemIcon {
    Vector(Reactive<day_spec::VectorName>),
    Symbol(day_spec::Symbol),
}

impl ItemIcon {
    /// The glyph as the spec names it; `tracked` subscribes a reactive vector.
    fn spec(&self, tracked: bool) -> day_spec::Icon {
        match self {
            ItemIcon::Vector(r) => {
                let name = if tracked { r.get() } else { r.get_untracked() };
                day_spec::Icon::Image(name.as_str().to_owned())
            }
            ItemIcon::Symbol(s) => day_spec::Icon::Symbol(*s),
        }
    }
}

/// A list row's standard content, built by [`list_item`] (docs/list.md "List items").
pub struct ListItem {
    title: TextSource,
    subtitle: Option<TextSource>,
    detail: Option<TextSource>,
    icon: Option<ItemIcon>,
    icon_tint: Option<Reactive<day_spec::Color>>,
    checked: Option<Reactive<bool>>,
}

/// A list row's standard content: a leading icon, a title, an optional subtitle and trailing
/// detail, and a check mark, drawn the way the platform draws its own list rows (docs/list.md
/// "List items"). UIKit shows it with the cell's default content configuration, Android as a
/// Material list item, AppKit as a table cell's image and text, GTK as a row box; elsewhere
/// the piece composes the same parts. Each part may follow a signal, and changes in place, so
/// a recycled row tracks its item.
///
/// ```ignore
/// list(scene.items.rows(keys), move |slot| {
///     list_item(move || slot.name().read())
///         .icon(move || slot.kind().read().icon())
///         .icon_tint(move || slot.tint().read().color())
///         .checked(move || slot.done().read())
/// })
/// ```
pub fn list_item<M>(title: impl IntoText<M>) -> ListItem {
    ListItem {
        title: title.into_text(),
        subtitle: None,
        detail: None,
        icon: None,
        icon_tint: None,
        checked: None,
    }
}

#[day_macros::builder(ListItemBuilder)]
impl ListItem {
    /// A second line under the title, in the platform's secondary style.
    pub fn subtitle<M>(mut self, text: impl IntoText<M>) -> Self {
        self.subtitle = Some(text.into_text());
        self
    }
    /// Trailing text, such as a count or a value, in the platform's secondary style.
    pub fn detail<M>(mut self, text: impl IntoText<M>) -> Self {
        self.detail = Some(text.into_text());
        self
    }
    /// The leading glyph: an app vector (`res::vectors::…`), drawn as a template in the
    /// foreground color unless [`Self::icon_tint`] names one. A signal or closure swaps it in
    /// place.
    pub fn icon<M>(mut self, name: impl IntoReactive<day_spec::VectorName, M>) -> Self {
        self.icon = Some(ItemIcon::Vector(name.into_reactive()));
        self
    }
    /// The leading glyph as a standard symbol.
    pub fn symbol(mut self, symbol: day_spec::Symbol) -> Self {
        self.icon = Some(ItemIcon::Symbol(symbol));
        self
    }
    /// The leading glyph's color.
    pub fn icon_tint<M>(mut self, color: impl IntoReactive<day_spec::Color, M>) -> Self {
        self.icon_tint = Some(color.into_reactive());
        self
    }
    /// A trailing check mark while `on` holds: the platform's mark for a chosen or completed
    /// row, announced as selected.
    pub fn checked<M>(mut self, on: impl IntoReactive<bool, M>) -> Self {
        self.checked = Some(on.into_reactive());
        self
    }
}

impl Piece for ListItem {
    fn build(self, cx: &mut BuildCx) -> RNode {
        if day_core::capability(day_spec::Cap::ListItem) == day_spec::Support::Native {
            self.build_native(cx)
        } else {
            self.compose().build(cx)
        }
    }
}

impl ListItem {
    /// The platform's own row content (`kinds::LIST_ITEM`), each part patched in place.
    fn build_native(self, cx: &mut BuildCx) -> RNode {
        let text = |t: &Option<TextSource>| t.as_ref().map(TextSource::initial).unwrap_or_default();
        let props = ListItemProps {
            title: self.title.initial(),
            subtitle: text(&self.subtitle),
            detail: text(&self.detail),
            icon: self.icon.as_ref().map(|i| i.spec(false)),
            icon_tint: self.icon_tint.as_ref().map(Reactive::get_untracked),
            checked: self.checked.as_ref().is_some_and(Reactive::get_untracked),
        };
        // The platform's whole row: it sizes its own height (docs/list.md "Row metrics").
        let node = cx.leaf(
            kinds::LIST_ITEM,
            &props,
            Flex {
                grow_w: true,
                whole_row: true,
                ..Default::default()
            },
        );
        let patch = move |p: ListItemPatch, size: bool| {
            with_tree(|t| t.patch(node, Box::new(p), size));
        };
        let bind_text =
            |src: Option<TextSource>, seed: String, make: fn(String) -> ListItemPatch| {
                if let Some(src @ TextSource::Dyn(_)) = src {
                    day_reactive::bind_seeded(
                        seed,
                        move || src.resolve(),
                        move |t: &String| patch(make(t.clone()), true),
                    );
                }
            };
        bind_text(Some(self.title), props.title, ListItemPatch::Title);
        bind_text(self.subtitle, props.subtitle, ListItemPatch::Subtitle);
        bind_text(self.detail, props.detail, ListItemPatch::Detail);
        if let Some(icon @ ItemIcon::Vector(Reactive::Dyn(_))) = self.icon {
            day_reactive::bind_seeded(
                props.icon,
                move || Some(icon.spec(true)),
                move |i| patch(ListItemPatch::Icon(i.clone()), false),
            );
        }
        if let Some(tint @ Reactive::Dyn(_)) = self.icon_tint {
            day_reactive::bind_seeded(
                props.icon_tint,
                move || Some(tint.get()),
                move |c| patch(ListItemPatch::IconTint(*c), false),
            );
        }
        if let Some(on @ Reactive::Dyn(_)) = self.checked {
            day_reactive::bind_seeded(
                props.checked,
                move || on.get(),
                move |b: &bool| patch(ListItemPatch::Checked(*b), true),
            );
        }
        node
    }

    /// The same parts from plain pieces, where the toolkit has no row content of its own.
    fn compose(self) -> impl Piece {
        use crate::{column, image, label, row, vector, when};
        let tint = self.icon_tint;
        let leading = self.icon.map(move |icon| match icon {
            ItemIcon::Vector(src) => {
                let glyph = vector(move || src.get()).template();
                match tint {
                    Some(t) => glyph
                        .tint(move || t.get())
                        .decorative()
                        .frame(20.0, 20.0)
                        .any(),
                    None => glyph.decorative().frame(20.0, 20.0).any(),
                }
            }
            ItemIcon::Symbol(sym) => match sym.outline_svg() {
                Some(svg) => image(svg.into_bytes()).template().frame(20.0, 20.0).any(),
                None => crate::spacer().frame(20.0, 20.0).any(),
            },
        });
        let titles = column((
            label(self.title),
            self.subtitle
                .map(|t| label(t).font(day_spec::Font::Footnote).secondary()),
        ))
        .spacing(2.0)
        .align(crate::HAlign::Leading)
        .grow_w();
        let detail = self.detail.map(|t| label(t).secondary());
        let checked = self.checked.clone();
        let mark = checked.map(|on| {
            when(
                move || on.get(),
                || {
                    let svg = day_spec::Symbol::Check.outline_svg().unwrap_or_default();
                    image(svg.into_bytes())
                        .template()
                        .decorative()
                        .frame(16.0, 16.0)
                },
            )
        });
        let selected = self.checked;
        row((leading, titles, detail, mark))
            .spacing(crate::Space::M)
            .align(crate::VAlign::Center)
            .grow_w()
            .a11y(move |a| match selected {
                Some(on) => a.selected(move || on.get()),
                None => a,
            })
    }
}

/// A row's swipe-action offer, aliased for the fields above: called with the row index at
/// gesture time, so the actions reflect the row's current state (docs/list.md).
type SwipeProvider = Rc<dyn Fn(usize) -> Vec<SwipeAction>>;

/// One button in a row's swipe-action offer (docs/list.md): what the platform reveals as the
/// user drags a row aside, built by [`swipe_action`]. Holds the label, the styling hints the
/// backend maps onto its own affordance, and the handler the activation runs.
pub struct SwipeAction {
    label: TextSource,
    destructive: bool,
    tint: Option<day_spec::Color>,
    symbol: Option<day_spec::Symbol>,
    handler: Rc<dyn Fn()>,
}

/// Build a swipe action with `label` (a literal, a `res::str::…` text, a signal or a closure;
/// resolved in the current locale each time the offer is pulled). Chain
/// [`destructive`](SwipeAction::destructive) or [`tint`](SwipeAction::tint) for styling and
/// [`action`](SwipeAction::action) for the work; an action without a handler still reveals and
/// dismisses, but does nothing.
pub fn swipe_action<M>(label: impl IntoText<M>) -> SwipeAction {
    SwipeAction {
        label: label.into_text(),
        destructive: false,
        tint: None,
        symbol: None,
        handler: Rc::new(|| {}),
    }
}

impl SwipeAction {
    /// Mark the action destructive: the platform styles it as such (red, on the Apple
    /// toolkits) and may animate the row away on activation.
    pub fn destructive(mut self) -> Self {
        self.destructive = true;
        self
    }
    /// The button's background color, where the platform honors one. Left unset, the platform
    /// picks its own default (gray, with red for destructive actions, on the Apple toolkits).
    pub fn tint(mut self, color: day_spec::Color) -> Self {
        self.tint = Some(color);
        self
    }
    /// A glyph for the button where the platform draws one: above the label on macOS, in
    /// place of it on iOS (docs/list.md). The label still matters: it is the accessibility
    /// name, and the platforms without a glyph slot show it alone.
    pub fn symbol(mut self, symbol: day_spec::Symbol) -> Self {
        self.symbol = Some(symbol);
        self
    }
    /// The work an activation runs. Called on the main thread at the next event drain, never
    /// inside the native gesture callback; the row index is the one the offer was pulled for,
    /// so capture what the action needs when building it.
    pub fn action(mut self, f: impl Fn() + 'static) -> Self {
        self.handler = Rc::new(f);
        self
    }
}

/// Drag-to-reorder for a [`list()`] (docs/list.md): the handler that applies a committed move,
/// an optional guard consulted while the drag is live, and whether the gesture is offered
/// right now. A list is reorderable exactly when it carries one of these
/// (`list(..).reorderable(Reorder::new(f))`).
///
/// The platform's own mechanism does the dragging (the macOS drop gap, the iOS long-press
/// lift, Android's `ItemTouchHelper`) where the backend supports it (probe `Cap::ListReorder`;
/// docs/list.md has the matrix).
#[derive(Clone)]
pub struct Reorder {
    moved: Rc<dyn Fn(usize, usize)>,
    guard: Option<Rc<dyn Fn(usize, usize) -> ReorderVerdict>>,
    enabled: Reactive<bool>,
}

impl Reorder {
    /// `moved(from, to)` runs after a committed move: row `from` now sits at row `to`. Apply the
    /// same rotation to the backing data (`let it = v.remove(from); v.insert(to, it);`), and
    /// persist it if the order should survive a relaunch. Runs on the main thread at the next
    /// event drain, never inside the native drop callback.
    pub fn new(moved: impl Fn(usize, usize) + 'static) -> Reorder {
        Reorder {
            moved: Rc::new(moved),
            guard: None,
            enabled: Reactive::Const(true),
        }
    }
    /// Veto or override drops while the drag is live: called synchronously from the native
    /// validate hook with `(from, proposed_to)`. Return [`ReorderVerdict::Deny`] to refuse,
    /// [`ReorderVerdict::Retarget`] to accept at a different index (a "pinned rows" pattern), or
    /// [`ReorderVerdict::Allow`] to accept as proposed (the default without a guard). Keep it
    /// pure (read state, decide, return); it runs inside the platform's drag callback.
    pub fn guard(mut self, g: impl Fn(usize, usize) -> ReorderVerdict + 'static) -> Reorder {
        self.guard = Some(Rc::new(g));
        self
    }
    /// Whether the gesture is offered right now (default `true`): a constant or a reactive
    /// `bool`, read when the platform asks whether a drag may begin, so an edit mode or a
    /// loading state can withhold it without rebuilding the list.
    pub fn enabled<M>(mut self, on: impl IntoReactive<bool, M>) -> Reorder {
        self.enabled = on.into_reactive();
        self
    }
}

/// Swipe-to-delete for a [`list()`] (docs/list.md): the handler that applies a committed delete,
/// the label the platform puts on its affordance, an optional per-row guard, and whether the
/// gesture is offered right now. A list is deletable exactly when it carries one of these
/// (`list(..).deletable(Delete::new(f))`).
///
/// The platform's delete gesture does the work (the iOS trailing swipe action, Android's
/// `ItemTouchHelper` swipe, ArkUI's `ListItem` swipe action) where the backend supports it
/// (probe `Cap::ListDelete`). The desktop toolkits answer `Unsupported`, so a list that must be
/// editable everywhere pairs this with an explicit control (a menu item or a button).
#[derive(Clone)]
pub struct Delete {
    deleted: Rc<dyn Fn(usize)>,
    label: Option<TextSource>,
    guard: Option<Rc<dyn Fn(usize) -> bool>>,
    enabled: Reactive<bool>,
}

impl Delete {
    /// `deleted(index)` runs after a committed delete: row `index` is gone. Apply the same
    /// removal to the backing data (`v.remove(index)`), and persist it if the change should
    /// survive a relaunch. Runs on the main thread at the next event drain, never inside the
    /// native swipe callback.
    pub fn new(deleted: impl Fn(usize) + 'static) -> Delete {
        Delete {
            deleted: Rc::new(deleted),
            label: None,
            guard: None,
            enabled: Reactive::Const(true),
        }
    }
    /// The word the platform puts on its delete affordance (`res::str::delete()`). Resolved in
    /// the locale current when the list builds. Left unset, each backend falls back to a trash
    /// glyph rather than shipping an English word into every locale.
    pub fn label<M>(mut self, text: impl IntoText<M>) -> Delete {
        self.label = Some(text.into_text());
        self
    }
    /// Protect individual rows: called synchronously before the affordance is offered, so a row
    /// that answers `false` shows no delete action rather than one that fails on use. Keep it
    /// pure; it runs inside the platform's swipe callback.
    pub fn guard(mut self, g: impl Fn(usize) -> bool + 'static) -> Delete {
        self.guard = Some(Rc::new(g));
        self
    }
    /// Whether the gesture is offered right now (default `true`): a constant or a reactive
    /// `bool`, read when the platform asks whether a row may be deleted.
    pub fn enabled<M>(mut self, on: impl IntoReactive<bool, M>) -> Delete {
        self.enabled = on.into_reactive();
        self
    }
}

/// A reorder guard's verdict on a proposed row move (docs/list.md): consulted synchronously from
/// the native drag's validate hook, so the affordance (gap, insertion mark, forbidden cursor)
/// reflects the answer while the user is still dragging.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReorderVerdict {
    /// Accept the drop where proposed.
    Allow,
    /// Refuse the drop (the row springs back; most backends show a forbidden cursor live).
    Deny,
    /// Accept the drop, but at this row index instead of the proposed one.
    Retarget(usize),
}

/// Build a recycling list from a [`RowSource`] and a row builder:
/// `list(items(rows_fn, key_of), row_view)` for plain data, `list(store, row_view)` (or
/// `list(store.rows(projection), …)`) for a day-model store.
pub fn list<S, P>(source: S, build_row: impl Fn(S::Slot) -> P + 'static) -> List<S>
where
    S: RowSource + 'static,
    P: Piece,
{
    List {
        source: Some(source),
        build_row: Rc::new(move |slot| AnyPiece::new(build_row(slot))),
        row_height: RowHeight::Automatic,
        on_select: None,
        on_activate: None,
        on_selection: None,
        multi_select: false,
        selected_rows: None,
        selection: None,
        scroll_to_end: None,
        scroll_to_row: None,
        first_visible_row: None,
        stick_to_bottom: false,
        reorder: None,
        delete: None,
        swipe_leading: None,
        swipe_trailing: None,
        separators: None,
        editing: crate::Reactive::Const(false),
        sections: None,
    }
}

#[day_macros::builder(ListBuilder<S>)]
impl<S: RowSource + 'static> List<S> {
    /// Row sizing: `Uniform(h)` (fastest) or `Automatic` (self-sizing).
    pub fn row_height(mut self, h: RowHeight) -> Self {
        self.row_height = h;
        self
    }
    /// Open, play, or otherwise activate a row. Desktop lists use double-click or Enter;
    /// touch lists use a tap. Selection callbacks remain independent.
    pub fn on_activate(mut self, f: impl Fn(S::Ref) + 'static) -> Self {
        self.on_activate = Some(Rc::new(f));
        self
    }

    /// Called with the selected row when the native list reports a selection: the key for a
    /// plain-data source, the row's `Elem` handle for a store source.
    pub fn on_select(mut self, f: impl Fn(S::Ref) + 'static) -> Self {
        self.on_select = Some(Rc::new(f));
        self
    }
    /// Allow selecting several rows at once, where the toolkit supports it (docs/list.md has
    /// the matrix; single-selection backends fall back to one row at a time). Every selection
    /// change calls [`Self::on_selection`] with the full set of selected rows.
    pub fn multi_select(mut self) -> Self {
        self.multi_select = true;
        self
    }
    /// Called with the full set of selected rows (row order, empty = cleared) whenever the
    /// selection changes: the multi-select analogue of [`Self::on_select`]. Also fired by
    /// single-selection backends with a one-element (or empty) set.
    pub fn on_selection(mut self, f: impl Fn(Vec<S::Ref>) + 'static) -> Self {
        self.on_selection = Some(Rc::new(f));
        self
    }
    /// Reactively sync the native selection to `rows` (row indices; empty clears). Re-runs
    /// whenever the closure's tracked reads change; the toolkit applies the sync without
    /// re-emitting a selection event. Drive it from app state to build "Clear selection".
    pub fn selected_rows(mut self, rows: impl Fn() -> Vec<usize> + 'static) -> Self {
        self.selected_rows = Some(Rc::new(rows));
        self
    }
    /// Two-way single selection by key, for a list of day-model store rows: `selected` holds
    /// the selected row's key (`None` for no selection). A row the user picks writes its key,
    /// clearing the selection writes `None`, and a key the app writes selects that row and
    /// scrolls it into view, following the row through inserts and moves.
    ///
    /// ```ignore
    /// list(scene.items, row_view).selection(scene.selected)
    /// ```
    pub fn selection(mut self, selected: impl Binding<Option<u64>>) -> Self
    where
        S::Ref: SelectionKey,
    {
        let selected = AnyBinding::new(selected);
        self.selection = Some(ListSelection {
            key: Rc::new(move || selected.get()),
            write: Rc::new(move |key| selected.set_if_changed(key)),
            key_of: Rc::new(|row: &S::Ref| row.selection_key()),
        });
        self
    }
    /// Scroll the list so its last row is fully visible whenever `trigger` fires, e.g. a chat
    /// timeline sticking to the newest message. Fire it with [`day_reactive::Trigger::notify`]
    /// after appending. No-op while the list is empty. The scroll targets the native list
    /// (`NSTableView`/`UITableView`/`GtkListView`/`QListView`/`RecyclerView`), so it respects the
    /// platform's own scroll physics.
    pub fn scroll_to_end(mut self, trigger: day_reactive::Trigger) -> Self {
        self.scroll_to_end = Some(trigger);
        self
    }
    /// Best-effort auto-stick: after a data reload, scroll to the end so freshly appended rows stay
    /// visible. Convenience over [`Self::scroll_to_end`] for feeds that always follow the newest
    /// row; for finer control (only stick when the user is already near the bottom) drive
    /// `scroll_to_end` from your own logic instead. Off by default.
    pub fn stick_to_bottom(mut self) -> Self {
        self.stick_to_bottom = true;
        self
    }

    /// Programmatic scroll-to-row (docs/list.md): set the signal to `Some(row)` and the native
    /// list scrolls that row into view, realizing it if it was virtualized away: the row rail's
    /// counterpart to `scroll(...).scroll_target(...)`. The signal is left as written; setting
    /// the same row again re-fires. Takes a `Signal<Option<usize>>` or any other binding.
    pub fn scroll_to_row(mut self, target: impl Binding<Option<usize>>) -> Self {
        self.scroll_to_row = Some(AnyBinding::new(target));
        self
    }

    /// The first actually visible article/item index, reported by native scrolling into
    /// `first` (a `Signal<usize>` or any other binding). Use with a heading overlay for
    /// floating group headers. No periodic timer is used.
    pub fn first_visible_row(mut self, first: impl Binding<usize>) -> Self {
        self.first_visible_row = Some(AnyBinding::new(first));
        self
    }

    /// Let the user drag rows into a new order (docs/list.md): the list is reorderable exactly
    /// when it carries a [`Reorder`], whose handler applies the move to the app's data.
    ///
    /// ```ignore
    /// list(rows, row_view)
    ///     .reorderable(Reorder::new(move |from, to| scene.move_item(from, to)).guard(keep_pinned))
    /// ```
    pub fn reorderable(mut self, reorder: Reorder) -> Self {
        self.reorder = Some(reorder);
        self
    }

    /// Let the user delete rows with the platform's delete gesture (docs/list.md): the list is
    /// deletable exactly when it carries a [`Delete`], whose handler applies the removal to the
    /// app's data.
    ///
    /// ```ignore
    /// list(rows, row_view)
    ///     .deletable(Delete::new(move |i| scene.remove_at(i)).label(res::str::delete()))
    /// ```
    pub fn deletable(mut self, delete: Delete) -> Self {
        self.delete = Some(delete);
        self
    }

    /// Offer swipe actions on the row's leading edge, the reading-direction start, where the
    /// platform reveals them as the user drags the row aside (probe `Cap::ListSwipeActions`;
    /// docs/list.md has the matrix; a backend without the affordance shows nothing, so pair
    /// each action with an explicit control for the rest). `provider` runs at gesture time
    /// with the row index, so the offer can reflect the row's current state ("Mark as Read"
    /// vs "Mark as Unread"). Keep it pure and fast; it runs inside the platform's swipe
    /// callback; the actions' handlers run later, at the event drain. A full swipe across
    /// activates the edge's first action.
    pub fn swipe_leading(mut self, provider: impl Fn(usize) -> Vec<SwipeAction> + 'static) -> Self {
        self.swipe_leading = Some(Rc::new(provider));
        self
    }

    /// Offer swipe actions on the row's trailing edge, the reading-direction end. Same
    /// contract as [`swipe_leading`](Self::swipe_leading).
    pub fn swipe_trailing(
        mut self,
        provider: impl Fn(usize) -> Vec<SwipeAction> + 'static,
    ) -> Self {
        self.swipe_trailing = Some(Rc::new(provider));
        self
    }

    /// Draw a separator under each row. It is the host's separator, drawn at the row boundary
    /// and never by row content (docs/list.md): it aligns with the native selection and stays
    /// put while a macOS/iOS swipe slides the row past it, exactly as Mail's separators do.
    /// Unset, each platform keeps its default (iOS draws them, the desktops don't); see
    /// [`Self::no_separators`] for the other override. A backend without a separator mechanism
    /// ignores this (the docs matrix says which); don't re-create the old hand-drawn hairline
    /// there. Rows separate by their pitch.
    pub fn separators(mut self) -> Self {
        self.separators = Some(true);
        self
    }

    /// Draw no separator between rows, on a platform whose default draws one (iOS).
    pub fn no_separators(mut self) -> Self {
        self.separators = Some(false);
        self
    }

    /// Group the rows into sections, each opened by a header row (docs/list.md "Sections").
    /// `key` runs with each row index when the rows change and names the row's section: a new
    /// section, and a header, starts wherever the key differs from the row before, so sort the
    /// rows by section first. `header` builds a section's header from the slot of its first
    /// row, the same slot a row builder gets, and rebinds it as its cell recycles.
    ///
    /// Headers are the platform's own: macOS group rows and UIKit section headers, which pin
    /// to the top of the list while their section scrolls under them; the other toolkits pin
    /// a copy of the current header the same way (`Cap::ListSections`). A header is never
    /// selected, activated or swiped, and row indices everywhere (selection, swipe offers,
    /// `selected_rows`, `scroll_to_row`, `first_visible_row`) still count rows only. A header
    /// sizes to its content even when the rows are `Uniform`.
    ///
    /// A row drags only within its own section, the platforms' rule for grouped tables: a
    /// drop past either end of the section lands at that end, and the `reorderable` guard
    /// sees row indices. A sectioned list offers no native swipe-to-delete, since deleting a
    /// section's last row would take its header with it.
    ///
    /// ```ignore
    /// list(items(move || articles.get(), |a| a.id), article_row)
    ///     .sections(
    ///         move |i| articles.with(|a| a[i].feed_id),
    ///         |slot| label(move || slot.field(|a| a.feed_title.clone())),
    ///     )
    /// ```
    pub fn sections<K: Hash, P: Piece>(
        mut self,
        key: impl Fn(usize) -> K + 'static,
        header: impl Fn(S::Slot) -> P + 'static,
    ) -> Self {
        self.sections = Some(ListSections {
            key: Rc::new(move |i| key_token(&key(i))),
            header: Rc::new(move |slot| AnyPiece::new(header(slot))),
        });
        self
    }

    /// Put the list in the platform's editing mode (docs/list.md): on iOS, the rows show
    /// their delete controls (where a [`Delete`] offers one) and reorder grips (where a
    /// [`Reorder`] moves them), and a tap still activates
    /// the row. Reactive, so an Edit/Done button can toggle it, and the change animates.
    ///
    /// Probe `Cap::ListEditing`. The other toolkits have no separate editing mode: their
    /// rows drag, swipe and open menus as they are, so the list renders as if this were off.
    pub fn editing<M>(mut self, on: impl crate::IntoReactive<bool, M>) -> Self {
        self.editing = on.into_reactive();
        self
    }
}

/// The driver's build closure for a row or a section header: build `builder`'s piece from a
/// slot for item `index` in its own scope, and rebind that slot as the cell recycles.
fn slot_builder<C: RowConn>(
    conn: Rc<C>,
    builder: Rc<dyn Fn(C::Slot) -> AnyPiece>,
) -> Box<dyn Fn(usize, RNode) -> BuiltRow> {
    Box::new(move |index, anchor| {
        let scope = Scope::child();
        let conn = conn.clone();
        let builder = builder.clone();
        let rebind = scope.enter(move || {
            // Native callbacks can deliver a stale index mid-animation; an out-of-range pull
            // yields an empty row instead of panicking.
            let Some(slot) = conn.slot_at(index) else {
                return Rc::new(|_: usize| {}) as Rc<dyn Fn(usize)>;
            };
            let mut rowcx = BuildCx::new(anchor);
            in_row_scope(|| builder(slot).build(&mut rowcx));
            // Rebind on recycle: point the slot at the cell's new row.
            Rc::new(move |i: usize| conn.rebind(&slot, i)) as Rc<dyn Fn(usize)>
        });
        BuiltRow { scope, rebind }
    })
}

impl<S: RowSource + 'static> Piece for List<S> {
    fn build(mut self, cx: &mut BuildCx) -> RNode {
        let props = ListProps {
            activatable: self.on_activate.is_some(),
            row_height: self.row_height,
            selectable: self.on_select.is_some()
                || self.on_selection.is_some()
                || self.selection.is_some()
                || self.on_activate.is_some(),
            multi_select: self.multi_select,
            // A sectioned list reorders within a section but offers no native delete (see
            // `sections`); the scripted path still reaches the driver.
            reorderable: self.reorder.is_some(),
            deletable: self.delete.is_some() && self.sections.is_none(),
            delete_label: self
                .delete
                .as_ref()
                .and_then(|d| d.label.as_ref())
                .map(TextSource::initial)
                .unwrap_or_default(),
            swipe_actions: self.swipe_leading.is_some() || self.swipe_trailing.is_some(),
            separators: self.separators,
            editing: self.editing.get_untracked(),
            sections: self.sections.is_some(),
        };
        let node = cx.leaf(
            kinds::LIST,
            &props,
            Flex {
                grow_w: true,
                grow_h: true,
                ..Default::default()
            },
        );

        // The source's live connection: the data-source's view of the world, refreshed by the
        // watch below. The native host queries it synchronously; the driver's build/rebind
        // closures read the same snapshot.
        let conn = Rc::new(self.source.take().expect("List built once").connect());
        // A sectioned list's keys, one per row of the snapshot: computed with it, and rotated
        // with it by a committed move, so day-core's header rows always match the rows.
        let section_keys: Rc<RefCell<Vec<u64>>> = Rc::new(RefCell::new(Vec::new()));
        let key_of_row = self.sections.as_ref().map(|s| s.key.clone());
        let refresh = {
            let (conn, keys, key_of_row) = (conn.clone(), section_keys.clone(), key_of_row.clone());
            Rc::new(move || {
                let tokens = conn.refresh();
                if let Some(key) = &key_of_row {
                    *keys.borrow_mut() = (0..conn.len()).map(|i| key(i)).collect();
                }
                (tokens, keys.borrow().clone())
            })
        };
        // After a committed native move/delete, the token order the app's own data update is
        // expected to echo back. When the refresh below sees exactly this order, the native rows
        // already sit in it (the gesture animated them there): take the data, skip the reload.
        let pending_echo: Rc<RefCell<Option<Vec<u64>>>> = Rc::new(RefCell::new(None));

        if let Some(activate) = self.on_activate.clone() {
            let conn = conn.clone();
            cx.on(node, move |event| {
                if let Event::ListActivated(row) = event
                    && let Some(reference) = conn.select_ref(*row)
                {
                    activate(reference);
                }
            });
        }

        // Selection → refs (translate the native row indices through the snapshot). A
        // single-selection report also feeds `on_selection` as a one-element set, so an app
        // tracking the full selection works unchanged on single-selection backends.
        if self.on_select.is_some() || self.on_selection.is_some() {
            let (on_select, on_selection) = (self.on_select.clone(), self.on_selection.clone());
            let conn = conn.clone();
            cx.on(node, move |ev| match ev {
                Event::SelectionChanged(i) => {
                    if let Some(f) = &on_select
                        && let Some(r) = conn.select_ref(*i as usize)
                    {
                        f(r);
                    }
                    if let Some(f) = &on_selection {
                        f(conn.select_ref(*i as usize).into_iter().collect());
                    }
                }
                Event::SelectionSet(rows) => {
                    if let Some(f) = &on_selection {
                        f(rows
                            .iter()
                            .filter_map(|i| conn.select_ref(*i as usize))
                            .collect());
                    }
                }
                _ => {}
            });
        }

        // A `.selection` binding: the user's choice writes the key back. `user_pick` remembers
        // it, so the apply below neither re-selects nor scrolls the row the user just chose.
        // `apply` selects the bound key's row in the current snapshot (the rows the native list
        // shows), and scrolls to it once after the app writes a key; a key whose row has not
        // reached the snapshot yet stays pending until the reload that brings it.
        let user_pick: Rc<Cell<Option<Option<u64>>>> = Rc::new(Cell::new(None));
        let reveal = Rc::new(Cell::new(false));
        let apply_selection: Option<Rc<dyn Fn()>> = self.selection.as_ref().map(|sel| {
            let (key, conn, reveal) = (sel.key.clone(), conn.clone(), reveal.clone());
            Rc::new(move || {
                let wanted = day_reactive::untrack(|| key());
                let row = wanted.and_then(|k| conn.tokens_now().iter().position(|t| *t == k));
                let scroll = row.filter(|_| reveal.replace(false));
                // Posted, like `selected_rows`: a toolkit may still be applying the reload
                // that brought the row.
                day_reactive::on_main(move || {
                    day_core::list_set_selected(node, row.into_iter().collect());
                    if let Some(row) = scroll {
                        list_scroll_to_row(node, row);
                    }
                });
            }) as Rc<dyn Fn()>
        });
        if let Some(sel) = &self.selection {
            let (write, key_of) = (sel.write.clone(), sel.key_of.clone());
            let (conn, pick) = (conn.clone(), user_pick.clone());
            cx.on(node, move |ev| {
                let row = match ev {
                    Event::SelectionChanged(i) => conn.select_ref(*i as usize),
                    Event::SelectionSet(rows) => {
                        rows.first().and_then(|i| conn.select_ref(*i as usize))
                    }
                    _ => return,
                };
                let key = row.as_ref().map(|r| key_of(r));
                pick.set(Some(key));
                write(key);
            });
        }

        // A committed native move, deferred to the event drain (never run inside the platform's
        // drop callback): hand the app the same (from, to) the native side animated.
        if let Some(on_reorder) = self.reorder.as_ref().map(|r| r.moved.clone()) {
            cx.on(node, move |ev| {
                if let Event::ListReorder { from, to } = ev {
                    on_reorder(*from, *to);
                }
            });
        }

        // A committed native delete, deferred to the event drain (never run inside the
        // platform's swipe callback): hand the app the row the native side animated away.
        if let Some(on_delete) = self.delete.as_ref().map(|d| d.deleted.clone()) {
            cx.on(node, move |ev| {
                if let Event::ListDelete(index) = ev {
                    on_delete(*index);
                }
            });
        }

        // An activated swipe action, deferred to the event drain. The handlers live in
        // `SwipeAction`s the provider builds fresh per gesture, so re-pull the offer here to
        // find the one the user pressed. The provider is the single source of both the offer
        // and its handlers, and a state change between reveal and activation resolves to the
        // action the row now offers at that position.
        if self.swipe_leading.is_some() || self.swipe_trailing.is_some() {
            let (leading, trailing) = (self.swipe_leading.clone(), self.swipe_trailing.clone());
            cx.on(node, move |ev| {
                if let Event::ListSwipe {
                    index,
                    edge,
                    action,
                } = ev
                {
                    let provider = match edge {
                        day_spec::SwipeEdge::Leading => leading.as_ref(),
                        day_spec::SwipeEdge::Trailing => trailing.as_ref(),
                    };
                    if let Some(p) = provider
                        && let Some(a) = p(*index).get(*action)
                    {
                        (a.handler)();
                    }
                }
            });
        }

        // The type-erased driver day-core drives on cell pulls.
        if let Some(signal) = self.first_visible_row {
            cx.on(node, move |event| {
                if let Event::Custom { tag, num, text } = event
                    && (*tag == "day-list-first-visible"
                        || (tag.is_empty() && text == "day-list-first-visible"))
                    && num.is_finite()
                    && *num >= 0.0
                {
                    signal.set_if_changed(*num as usize);
                }
            });
        }
        let driver = ListDriver {
            track_viewport: self.first_visible_row.is_some(),
            row_height: self.row_height,
            len: {
                let conn = conn.clone();
                Box::new(move || conn.len())
            },
            token_at: {
                let conn = conn.clone();
                Box::new(move |i| conn.token_at(i))
            },
            build: slot_builder(conn.clone(), self.build_row.clone()),
            sections: self.sections.as_ref().map(|sections| ListSectionsDriver {
                key_at: {
                    let keys = section_keys.clone();
                    Box::new(move |i| keys.borrow().get(i).copied().unwrap_or_default())
                },
                build: slot_builder(conn.clone(), sections.header.clone()),
            }),
            delete: self.delete.as_ref().map(|delete| ListDeleteDriver {
                // Availability first (`Delete::enabled`), then the row's own guard.
                can_delete: {
                    let (guard, enabled) = (delete.guard.clone(), delete.enabled.clone());
                    Box::new(move |i| {
                        enabled.get_untracked() && guard.as_ref().is_none_or(|g| g(i))
                    })
                },
                // Commit: drop the row from the snapshot now (subsequent len/token_at/bind_row
                // serve the shorter list while the native removal animates), arm the echo skip,
                // and defer the app's callback.
                deleted: {
                    let (conn, echo, keys) =
                        (conn.clone(), pending_echo.clone(), section_keys.clone());
                    Box::new(move |index| {
                        if index >= conn.len() {
                            return;
                        }
                        conn.commit_delete(index);
                        if index < keys.borrow().len() {
                            keys.borrow_mut().remove(index);
                        }
                        *echo.borrow_mut() = Some(conn.tokens_now());
                        enqueue_event(rnode_to_id(node), Event::ListDelete(index));
                    })
                },
            }),
            reorder: self.reorder.as_ref().map(|reorder| ListReorderDriver {
                // The guard's verdict, encoded for the synchronous `can_move` callback:
                // accepted index or -1. Availability (`Reorder::enabled`) is asked first.
                can_move: {
                    let (guard, enabled) = (reorder.guard.clone(), reorder.enabled.clone());
                    Box::new(move |from, to| {
                        if !enabled.get_untracked() {
                            return -1;
                        }
                        match guard.as_ref().map(|g| g(from, to)) {
                            None | Some(ReorderVerdict::Allow) => to as i64,
                            Some(ReorderVerdict::Deny) => -1,
                            Some(ReorderVerdict::Retarget(i)) => i as i64,
                        }
                    })
                },
                // Commit: rotate the snapshot now (subsequent len/token_at/bind_row serve the
                // new order while the native move animates), arm the echo skip, and defer the
                // app's callback through the event queue.
                moved: {
                    let (conn, echo, keys) =
                        (conn.clone(), pending_echo.clone(), section_keys.clone());
                    Box::new(move |from, to| {
                        if from >= conn.len() || to >= conn.len() {
                            return;
                        }
                        conn.commit_move(from, to);
                        {
                            let mut keys = keys.borrow_mut();
                            if from < keys.len() && to < keys.len() {
                                let k = keys.remove(from);
                                keys.insert(to, k);
                            }
                        }
                        *echo.borrow_mut() = Some(conn.tokens_now());
                        enqueue_event(rnode_to_id(node), Event::ListReorder { from, to });
                    })
                },
            }),
            swipe: (self.swipe_leading.is_some() || self.swipe_trailing.is_some()).then(|| {
                ListSwipeDriver {
                    // The offer, stripped to data: labels + styling go to the toolkit; the
                    // handlers stay here, found again by index when the activation drains.
                    actions_at: {
                        let (leading, trailing) =
                            (self.swipe_leading.clone(), self.swipe_trailing.clone());
                        Box::new(move |i, edge| {
                            let provider = match edge {
                                day_spec::SwipeEdge::Leading => leading.as_ref(),
                                day_spec::SwipeEdge::Trailing => trailing.as_ref(),
                            };
                            provider.map_or_else(Vec::new, |p| {
                                p(i).iter()
                                    .map(|a| day_spec::ListSwipeAction {
                                        label: a.label.resolve(),
                                        destructive: a.destructive,
                                        tint: a.tint,
                                        symbol: a.symbol,
                                    })
                                    .collect()
                            })
                        })
                    },
                    // Commit: defer the app's handler through the event queue (never run it
                    // inside the native gesture callback).
                    performed: {
                        let conn = conn.clone();
                        Box::new(move |index, edge, action| {
                            if index >= conn.len() {
                                return;
                            }
                            enqueue_event(
                                rnode_to_id(node),
                                Event::ListSwipe {
                                    index,
                                    edge,
                                    action,
                                },
                            );
                        })
                    },
                }
            }),
        };
        install_list(node, driver);

        // Keep the snapshot current and tell the native host to re-query on changes. The compute
        // is the tracked refresh; for a store source whose values flow through per-field
        // notifications, an unchanged row set skips the native reload entirely: a field edit
        // costs the one control it patched, not a visible-rows rebind.
        {
            let (conn, echo, stick) = (conn.clone(), pending_echo.clone(), self.stick_to_bottom);
            let reselect = apply_selection.clone();
            let initial = {
                let refresh = refresh.clone();
                day_reactive::untrack(move || refresh())
            };
            // The native host attached against an empty snapshot (install_list ran before this
            // prime), so tell it the real row set now: reload, without the auto-scroll a later
            // sticky change gets. Skipping this rendered every list blank until its first data
            // change, while the synthetic rail kept passing: the walkthrough drove the driver
            // directly and never noticed.
            list_reload(node);
            let last: RefCell<(Vec<u64>, Vec<u64>)> = RefCell::new(initial);
            watch(
                move || refresh(),
                move |rows: &(Vec<u64>, Vec<u64>), _| {
                    let toks = &rows.0;
                    let pending = pending_echo.borrow_mut().take();
                    let is_echo = pending.as_ref().is_some_and(|e| e == toks);
                    // A row moving to another section changes its header rows, not its tokens.
                    let unchanged = !conn.values_flow_by_reload() && *last.borrow() == *rows;
                    *last.borrow_mut() = rows.clone();
                    if !is_echo && pending.is_some() {
                        // The native rows took a move or delete the app answered with some
                        // other order. The source's deltas describe the change from its order
                        // before the gesture, not from the rows on screen: reload instead.
                        let _ = conn.take_row_events();
                        list_reload(node);
                        if let Some(apply) = &reselect {
                            apply();
                        }
                    } else if !is_echo && !unchanged {
                        match conn.take_row_events() {
                            Some(deltas) if !deltas.is_empty() => list_splice(node, deltas),
                            Some(_) => {}
                            None => list_reload(node),
                        }
                        if stick {
                            list_scroll_to_end(node);
                        }
                        // A reload drops the native selection; put the bound row back.
                        if let Some(apply) = &reselect {
                            apply();
                        }
                    } else {
                        // Consume events the host must not see twice (its own echo, or a
                        // change whose set landed identical).
                        let _ = conn.take_row_events();
                    }
                },
            );
            let _ = echo;
        }

        // Imperative scroll-to-end: each `trigger.notify()` re-runs this watch (the trigger's
        // signal is the only tracked dep), whose callback scrolls the native list to its last row.
        // `watch` never fires for the initial run, so building the list does not force a scroll.
        if let Some(trigger) = self.scroll_to_end {
            watch(
                move || trigger.track(),
                move |_: &(), _| list_scroll_to_end(node),
            );
        }

        // Programmatic scroll-to-row: every `Some(row)` write scrolls that row into view
        // (`watch` fires per write, so repeats of the same row re-fire; the initial build never
        // scrolls).
        if let Some(sig) = self.scroll_to_row {
            watch(
                move || sig.get(),
                move |row: &Option<usize>, _| {
                    if let Some(row) = row {
                        list_scroll_to_row(node, *row);
                    }
                },
            );
        }

        // A reactive editing mode patches on change; the props carried the initial state.
        if let editing @ crate::Reactive::Dyn(_) =
            std::mem::replace(&mut self.editing, crate::Reactive::Const(false))
        {
            watch(
                move || editing.get(),
                move |on: &bool, old| {
                    if old.is_some() {
                        list_set_editing(node, *on);
                    }
                },
            );
        }

        // `.selection`: every key the app writes selects its row and scrolls it into view (once
        // the row is in the snapshot; see `apply`). The initial key and the user's own pick
        // select without scrolling.
        if let (Some(sel), Some(apply)) = (self.selection.take(), apply_selection) {
            let first = Cell::new(true);
            day_reactive::bind(
                move || (sel.key)(),
                move |key: &Option<u64>| {
                    let initial = first.replace(false);
                    // The user's own pick is applied too, unscrolled: a list with no selection of
                    // its own (Android's RecyclerView) paints only what Day records, and a native
                    // list re-selecting the row it shows is a no-op.
                    let picked = user_pick.take() == Some(*key);
                    reveal.set(!initial && !picked && key.is_some());
                    apply();
                },
            );
        }

        // An explicit selection binding owns the initial selection too. Reader layouts may
        // remount a list with an already-selected model item; skipping the initial apply
        // leaves the native table unselected until a later model change.
        if let Some(rows) = self.selected_rows {
            day_reactive::bind(
                move || rows(),
                move |rows: &Vec<usize>| {
                    // Selection and the row source may depend on the same model signal.
                    // Let the source publish/reload its snapshot before selecting its indexes.
                    let rows = rows.clone();
                    day_reactive::on_main(move || day_core::list_set_selected(node, rows));
                },
            );
        }
        node
    }
}

// ---------------------------------------------------------------------------
// Model-driven rows (feature "model", docs/model.md): a day-model store as a RowSource
// ---------------------------------------------------------------------------

#[cfg(feature = "model")]
mod model_rows {
    use super::*;
    use day_model::{Elem, Identified, Keyed, Source, Store};

    /// One recycled row's connection to its store: the slot a model list's row builder
    /// receives. `Copy`, and a day-model [`Source`], so `#[derive(Observable)]` accessors hang
    /// off it. `text_field(slot.name())` binds two-way and follows the slot to its next row
    /// when the cell recycles, because the slot resolves its row on every operation.
    pub struct ModelSlot<T: 'static> {
        store: Store<Keyed<T>>,
        cur: Signal<u64>,
    }

    impl<T> Clone for ModelSlot<T> {
        fn clone(&self) -> Self {
            *self
        }
    }
    impl<T> Copy for ModelSlot<T> {}

    impl<T: Identified + Clone + 'static> ModelSlot<T> {
        /// A slot pointed at `key`, for row sources implemented outside this crate (a live
        /// query). Application code receives slots from `list`/`each` instead.
        pub fn for_key(store: Store<Keyed<T>>, key: u64) -> ModelSlot<T> {
            ModelSlot {
                store,
                cur: Signal::new(key),
            }
        }
        /// The recycle write, for external row sources: point this slot at another key.
        pub fn rebind_key(&self, key: u64) {
            self.cur.set_if_changed(key);
        }
    }

    impl<T: Identified + 'static> ModelSlot<T> {
        /// The row's key right now, tracked, so a closure reading it follows recycling
        /// (a context-menu action captures the slot and acts on whichever row the cell shows
        /// when it runs).
        pub fn key(self) -> u64 {
            self.cur.get()
        }
        /// The current row as a plain element handle, for `exists()` guards or handing to
        /// code outside the row. Tracked via the slot, so it follows recycling too.
        pub fn item(self) -> Elem<T> {
            self.store.elem(self.cur.get())
        }
        fn elem_now(self) -> Elem<T> {
            self.store.elem(self.cur.get_untracked())
        }
    }

    impl<T: Identified + 'static> Source<T> for ModelSlot<T> {
        // The slot's location is wherever the cell currently sits, hence `DYNAMIC`.
        const DYNAMIC: bool = true;
        fn track_extra(self) {
            self.cur.track();
        }
        fn path(self) -> day_model::Path {
            self.elem_now().path()
        }
        fn node(self) -> day_model::NodeId {
            self.elem_now().node()
        }
        fn components(self, out: &mut Vec<u64>) {
            self.elem_now().components(out);
        }
        fn with_value_untracked<R>(self, f: impl FnOnce(Option<&T>) -> R) -> R {
            self.elem_now().with_value_untracked(f)
        }
        fn update_value(self, f: impl FnOnce(&mut T)) -> bool {
            self.elem_now().update_value(f)
        }
        fn bump_version(self) {
            self.elem_now().bump_version();
        }
    }

    /// A store row names itself by its key, so a store list binds [`List::selection`].
    impl<T: Identified + 'static> SelectionKey for Elem<T> {
        fn selection_key(&self) -> u64 {
            self.key()
        }
    }

    /// A store IS a row source: collection order, rows keyed by the store's own keys.
    impl<T: Identified + Clone + 'static> RowSource for Store<Keyed<T>> {
        type Slot = ModelSlot<T>;
        type Ref = Elem<T>;
        type Conn = StoreConn<T>;
        fn connect(self) -> StoreConn<T> {
            StoreConn {
                store: self,
                rows: None,
                keys: RefCell::new(Vec::new()),
            }
        }
    }

    /// A display projection over a store: `store.rows(move || ordered_keys())`. The projection
    /// is a tracked read of key ids: read only the fields the order depends on, and a write to
    /// any other field cannot re-run it.
    pub struct Rows<T: 'static> {
        store: Store<Keyed<T>>,
        f: Rc<dyn Fn() -> Vec<u64>>,
    }

    impl<T: Identified + Clone + 'static> RowSource for Rows<T> {
        type Slot = ModelSlot<T>;
        type Ref = Elem<T>;
        type Conn = StoreConn<T>;
        fn connect(self) -> StoreConn<T> {
            StoreConn {
                store: self.store,
                rows: Some(self.f),
                keys: RefCell::new(Vec::new()),
            }
        }
    }

    /// `store.rows(projection)`: the display-ordered row source for [`list()`]/[`each`].
    pub trait StoreRows<T: 'static> {
        fn rows(self, f: impl Fn() -> Vec<u64> + 'static) -> Rows<T>;
    }

    impl<T: Identified + Clone + 'static> StoreRows<T> for Store<Keyed<T>> {
        fn rows(self, f: impl Fn() -> Vec<u64> + 'static) -> Rows<T> {
            Rows {
                store: self,
                f: Rc::new(f),
            }
        }
    }

    /// The store connection: its snapshot is the display keys; no item is ever cloned.
    pub struct StoreConn<T: 'static> {
        store: Store<Keyed<T>>,
        rows: Option<Rc<dyn Fn() -> Vec<u64>>>,
        keys: RefCell<Vec<u64>>,
    }

    impl<T: Identified + Clone + 'static> RowConn for StoreConn<T> {
        type Slot = ModelSlot<T>;
        type Ref = Elem<T>;

        fn refresh(&self) -> Vec<u64> {
            let keys = match &self.rows {
                Some(f) => f(),
                None => self.store.keys(),
            };
            *self.keys.borrow_mut() = keys.clone();
            keys
        }
        fn len(&self) -> usize {
            self.keys.borrow().len()
        }
        fn token_at(&self, index: usize) -> u64 {
            self.keys.borrow().get(index).copied().unwrap_or(0)
        }
        fn tokens_now(&self) -> Vec<u64> {
            self.keys.borrow().clone()
        }
        fn slot_at(&self, index: usize) -> Option<ModelSlot<T>> {
            let key = self.keys.borrow().get(index).copied()?;
            Some(ModelSlot {
                store: self.store,
                cur: Signal::new(key),
            })
        }
        fn rebind(&self, slot: &ModelSlot<T>, index: usize) {
            if let Some(key) = self.keys.borrow().get(index).copied() {
                // Values flow through the store's own notifications; the rebind is only the
                // key, and an unchanged key is a no-op.
                slot.cur.set_if_changed(key);
            }
        }
        fn select_ref(&self, index: usize) -> Option<Elem<T>> {
            let key = self.keys.borrow().get(index).copied()?;
            Some(self.store.elem(key))
        }
        fn values_flow_by_reload(&self) -> bool {
            false
        }
        fn commit_move(&self, from: usize, to: usize) {
            let mut keys = self.keys.borrow_mut();
            if from >= keys.len() || to >= keys.len() {
                return;
            }
            let k = keys.remove(from);
            keys.insert(to, k);
        }
        fn commit_delete(&self, index: usize) {
            let mut keys = self.keys.borrow_mut();
            if index >= keys.len() {
                return;
            }
            keys.remove(index);
        }
    }

    /// A hierarchy over a store: `store.tree(children_of)` (docs/tree.md). The projection
    /// maps a parent key (`None` = the root) to its ordered child keys, a tracked read, so
    /// re-parenting or re-ordering writes re-run it; tokens are the store's keys.
    pub struct StoreTree<T: 'static> {
        store: Store<Keyed<T>>,
        children: Rc<dyn Fn(Option<u64>) -> Vec<u64>>,
    }

    /// `store.tree(children_of)`: the hierarchical source for [`super::tree`].
    pub trait StoreTrees<T: 'static> {
        fn tree(self, children: impl Fn(Option<u64>) -> Vec<u64> + 'static) -> StoreTree<T>;
    }

    impl<T: Identified + Clone + 'static> StoreTrees<T> for Store<Keyed<T>> {
        fn tree(self, children: impl Fn(Option<u64>) -> Vec<u64> + 'static) -> StoreTree<T> {
            StoreTree {
                store: self,
                children: Rc::new(children),
            }
        }
    }

    impl<T: Identified + Clone + 'static> super::NodeSource for StoreTree<T> {
        type Slot = ModelSlot<T>;
        type Key = u64;
        type Conn = StoreTreeConn<T>;
        fn connect(self) -> StoreTreeConn<T> {
            StoreTreeConn {
                store: self.store,
                children: self.children,
                shape: RefCell::new(super::TreeShape::default()),
            }
        }
    }

    /// [`StoreTree`]'s connection: the derived shape; values flow through the store's own
    /// per-field notifications, so an unchanged shape skips the native reload entirely.
    pub struct StoreTreeConn<T: 'static> {
        store: Store<Keyed<T>>,
        children: Rc<dyn Fn(Option<u64>) -> Vec<u64>>,
        shape: RefCell<super::TreeShape>,
    }

    impl<T: Identified + Clone + 'static> super::TreeConn for StoreTreeConn<T> {
        type Slot = ModelSlot<T>;
        type Key = u64;

        fn refresh(&self) -> Vec<(u64, Option<u64>)> {
            let mut shape = super::TreeShape::default();
            let mut seen = HashSet::new();
            // Depth-first from the root, children pushed in reverse so walk order is
            // display order. `seen` guards a malformed parent graph from looping.
            let mut stack: Vec<(Option<u64>, u64)> = (self.children)(None)
                .into_iter()
                .rev()
                .map(|k| (None, k))
                .collect();
            while let Some((parent, key)) = stack.pop() {
                if !seen.insert(key) {
                    debug_assert!(false, "day: cycle or duplicate key in store tree");
                    continue;
                }
                shape.tokens.push(key);
                shape.parents.insert(key, parent);
                shape.children.entry(parent).or_default().push(key);
                for child in (self.children)(Some(key)).into_iter().rev() {
                    stack.push((Some(key), child));
                }
            }
            let fp = shape.fingerprint();
            *self.shape.borrow_mut() = shape;
            fp
        }
        fn tokens_now(&self) -> Vec<u64> {
            self.shape.borrow().tokens.clone()
        }
        fn children_len(&self, parent: Option<u64>) -> usize {
            self.shape
                .borrow()
                .children
                .get(&parent)
                .map(|v| v.len())
                .unwrap_or(0)
        }
        fn child_token(&self, parent: Option<u64>, index: usize) -> u64 {
            self.shape
                .borrow()
                .children
                .get(&parent)
                .and_then(|v| v.get(index).copied())
                .unwrap_or(0)
        }
        fn parent_of(&self, token: u64) -> Option<Option<u64>> {
            self.shape.borrow().parents.get(&token).copied()
        }
        fn key_of(&self, token: u64) -> Option<u64> {
            self.shape
                .borrow()
                .parents
                .contains_key(&token)
                .then_some(token)
        }
        fn token_of(&self, key: &u64) -> u64 {
            *key
        }
        fn slot_for(&self, token: u64) -> Option<ModelSlot<T>> {
            self.shape
                .borrow()
                .parents
                .contains_key(&token)
                .then(|| ModelSlot::for_key(self.store, token))
        }
        fn rebind(&self, slot: &ModelSlot<T>, token: u64) {
            slot.rebind_key(token);
        }
        fn values_flow_by_reload(&self) -> bool {
            false
        }
    }
}

#[cfg(feature = "model")]
pub use model_rows::{ModelSlot, Rows, StoreRows, StoreTree, StoreTreeConn, StoreTrees};

// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---

// ---------------------------------------------------------------------------
// `tree`: native hierarchical tree (docs/tree.md)
// ---------------------------------------------------------------------------

pub use day_spec::MoveVerdict;

/// A hierarchical row source for [`tree`]: the [`RowSource`] idea grown a parent per row.
/// Two implementations: [`branches`] (plain data) and a day-model store's
/// `store.tree(children_of)` (feature `model`).
pub trait NodeSource {
    /// What a row builder receives.
    type Slot: Copy + 'static;
    /// The app's identity currency: what selection, moves and expansion speak.
    type Key: Clone + Hash + Eq + 'static;
    type Conn: TreeConn<Slot = Self::Slot, Key = Self::Key>;
    fn connect(self) -> Self::Conn;
}

/// One tree's live connection to its data, held for the life of the [`tree`] that connected
/// it. All hierarchy queries are TOKEN-addressed (docs/tree.md): `None` = the root level.
pub trait TreeConn: 'static {
    type Slot: Copy + 'static;
    type Key: Clone + Hash + Eq + 'static;

    /// Refresh the snapshot and return the tree's shape: `(token, parent)` pairs in walk
    /// order. A tracked read: the enclosing watch re-runs exactly when something this read
    /// depends on changes.
    fn refresh(&self) -> Vec<(u64, Option<u64>)>;
    /// Every token in the current snapshot, walk order, no refresh and no tracking.
    fn tokens_now(&self) -> Vec<u64>;
    fn children_len(&self, parent: Option<u64>) -> usize;
    fn child_token(&self, parent: Option<u64>, index: usize) -> u64;
    /// `Some(parent)` for a known token (`Some(None)` = a root row), `None` for an unknown one.
    fn parent_of(&self, token: u64) -> Option<Option<u64>>;
    fn key_of(&self, token: u64) -> Option<Self::Key>;
    /// The token a key maps to (pure: no snapshot lookup).
    fn token_of(&self, key: &Self::Key) -> u64;
    /// A fresh slot for `token` (`None` on a stale mid-animation pull). Call inside the
    /// row's scope: plain-data slots allocate their signals here.
    fn slot_for(&self, token: u64) -> Option<Self::Slot>;
    /// Point an existing slot at `token`: the recycle write.
    fn rebind(&self, slot: &Self::Slot, token: u64);
    /// Whether row VALUES reach existing rows only through reload→rebind (see
    /// [`RowConn::values_flow_by_reload`]).
    fn values_flow_by_reload(&self) -> bool;
}

/// Plain-data tree rows: a flat items closure, a key per item, and a parent key per item
/// (`None` = a root row), as in `tree(branches(model::all, |n| n.id, |n| n.parent), row_view)`.
/// Children keep the items' own relative order; an item whose parent key is absent from the
/// set is treated as a root row rather than dropped.
pub fn branches<T, K>(
    f: impl Fn() -> Vec<T> + 'static,
    key_of: impl Fn(&T) -> K + 'static,
    parent_of: impl Fn(&T) -> Option<K> + 'static,
) -> Branches<T, K>
where
    T: Clone + 'static,
    K: Clone + Hash + Eq + 'static,
{
    Branches {
        f: Rc::new(f),
        key_of: Rc::new(key_of),
        parent_of: Rc::new(parent_of),
    }
}

/// A parent-key extractor (aliased for the fields below; clippy's type-complexity bound).
type ParentOf<T, K> = Rc<dyn Fn(&T) -> Option<K>>;

/// The plain-data [`NodeSource`] built by [`branches`].
pub struct Branches<T: 'static, K: 'static> {
    f: Rc<dyn Fn() -> Vec<T>>,
    key_of: Rc<dyn Fn(&T) -> K>,
    parent_of: ParentOf<T, K>,
}

impl<T: Clone + 'static, K: Clone + Hash + Eq + 'static> NodeSource for Branches<T, K> {
    type Slot = ItemSlot<T, K>;
    type Key = K;
    type Conn = BranchesConn<T, K>;
    fn connect(self) -> BranchesConn<T, K> {
        BranchesConn {
            f: self.f,
            key_of: self.key_of,
            parent_of: self.parent_of,
            snapshot: RefCell::new(Vec::new()),
            shape: RefCell::new(TreeShape::default()),
        }
    }
}

/// The derived children/parent indexes both connections maintain per refresh.
#[derive(Default)]
struct TreeShape {
    /// Walk-order tokens (parents before their children for a well-formed set).
    tokens: Vec<u64>,
    children: std::collections::HashMap<Option<u64>, Vec<u64>>,
    parents: std::collections::HashMap<u64, Option<u64>>,
    /// token → index into the flat snapshot (plain-data sources only).
    index_of: std::collections::HashMap<u64, usize>,
}

impl TreeShape {
    fn fingerprint(&self) -> Vec<(u64, Option<u64>)> {
        self.tokens
            .iter()
            .map(|t| (*t, self.parents.get(t).copied().flatten()))
            .collect()
    }
}

/// [`Branches`]' connection: the current data snapshot plus its derived shape.
pub struct BranchesConn<T: 'static, K: 'static> {
    f: Rc<dyn Fn() -> Vec<T>>,
    key_of: Rc<dyn Fn(&T) -> K>,
    parent_of: ParentOf<T, K>,
    snapshot: RefCell<Vec<T>>,
    shape: RefCell<TreeShape>,
}

impl<T: Clone + 'static, K: Clone + Hash + Eq + 'static> TreeConn for BranchesConn<T, K> {
    type Slot = ItemSlot<T, K>;
    type Key = K;

    fn refresh(&self) -> Vec<(u64, Option<u64>)> {
        let its = (self.f)();
        let mut shape = TreeShape::default();
        let toks: Vec<u64> = its.iter().map(|t| key_token(&(self.key_of)(t))).collect();
        let present: HashSet<u64> = toks.iter().copied().collect();
        for (i, item) in its.iter().enumerate() {
            let tok = toks[i];
            // A parent key outside the set roots the row rather than dropping it.
            let parent = (self.parent_of)(item)
                .map(|k| key_token(&k))
                .filter(|p| present.contains(p));
            shape.tokens.push(tok);
            shape.parents.insert(tok, parent);
            shape.children.entry(parent).or_default().push(tok);
            shape.index_of.insert(tok, i);
        }
        *self.snapshot.borrow_mut() = its;
        let fp = shape.fingerprint();
        *self.shape.borrow_mut() = shape;
        fp
    }
    fn tokens_now(&self) -> Vec<u64> {
        self.shape.borrow().tokens.clone()
    }
    fn children_len(&self, parent: Option<u64>) -> usize {
        self.shape
            .borrow()
            .children
            .get(&parent)
            .map(|v| v.len())
            .unwrap_or(0)
    }
    fn child_token(&self, parent: Option<u64>, index: usize) -> u64 {
        self.shape
            .borrow()
            .children
            .get(&parent)
            .and_then(|v| v.get(index).copied())
            .unwrap_or(0)
    }
    fn parent_of(&self, token: u64) -> Option<Option<u64>> {
        self.shape.borrow().parents.get(&token).copied()
    }
    fn key_of(&self, token: u64) -> Option<K> {
        let idx = self.shape.borrow().index_of.get(&token).copied()?;
        self.snapshot.borrow().get(idx).map(|t| (self.key_of)(t))
    }
    fn token_of(&self, key: &K) -> u64 {
        key_token(key)
    }
    fn slot_for(&self, token: u64) -> Option<ItemSlot<T, K>> {
        let idx = self.shape.borrow().index_of.get(&token).copied()?;
        let item = self.snapshot.borrow().get(idx).cloned()?;
        let key = (self.key_of)(&item);
        Some(ItemSlot {
            sig: Signal::new(item),
            key: Signal::new(key),
        })
    }
    fn rebind(&self, slot: &ItemSlot<T, K>, token: u64) {
        let Some(idx) = self.shape.borrow().index_of.get(&token).copied() else {
            return; // stale recycle token: skip, the next bind corrects it
        };
        let Some(item) = self.snapshot.borrow().get(idx).cloned() else {
            return;
        };
        slot.key.set((self.key_of)(&item));
        slot.sig.set(item);
    }
    fn values_flow_by_reload(&self) -> bool {
        true
    }
}

/// A native hierarchical tree (docs/tree.md): rows nest, disclose, and drag to a new parent.
/// The platform widget owns scrolling, disclosure and cell reuse; Day builds each visible row
/// once and *rebinds* it as cells recycle ([`list()`]'s contract, token-addressed). Gate its UI
/// on `Cap::Tree`: a backend without tree support renders nothing.
/// Drag-to-move for a [`tree`] (docs/tree.md): the handler that applies a committed
/// re-parent, an optional guard consulted while the drag is live, and whether the gesture is
/// offered right now. A tree is movable exactly when it carries one of these
/// (`tree(..).movable(Move::new(f))`). The [`list()`] counterpart is [`Reorder`].
pub struct Move<K: 'static> {
    moved: TreeMoveFn<K>,
    guard: Option<TreeGuardFn<K>>,
    enabled: Reactive<bool>,
}

impl<K: 'static> Move<K> {
    /// `moved(key, parent, index)` runs after a committed move: `key` now sits under `parent`
    /// (`None` = the root) at `index` (`None` = dropped onto the parent: append). Apply the
    /// same re-parent to the backing data; its refresh reloads the tree. Runs at the next event
    /// drain, never inside the native drop callback.
    pub fn new(moved: impl Fn(K, Option<K>, Option<usize>) + 'static) -> Move<K> {
        Move {
            moved: Rc::new(moved),
            guard: None,
            enabled: Reactive::Const(true),
        }
    }
    /// Veto drops while the drag is live. The structural refusals (a row into itself, into
    /// its own descendant, into a leaf) are built in; this guard adds the app's own. Keep it
    /// pure: it runs inside the platform's drag callback.
    pub fn guard(
        mut self,
        g: impl Fn(&K, Option<&K>, Option<usize>) -> MoveVerdict + 'static,
    ) -> Move<K> {
        self.guard = Some(Rc::new(g));
        self
    }
    /// Whether the gesture is offered right now (default `true`): a constant or a reactive
    /// `bool`, read when the platform asks whether a drag may begin.
    pub fn enabled<M>(mut self, on: impl IntoReactive<bool, M>) -> Move<K> {
        self.enabled = on.into_reactive();
        self
    }
}

pub struct TreePiece<S: NodeSource> {
    source: Option<S>,
    build_row: Rc<dyn Fn(S::Slot) -> AnyPiece>,
    row_height: RowHeight,
    indent: Option<f64>,
    section_headers: bool,
    on_expansion: Option<ExpansionFn<S::Key>>,
    expanded: Option<AnyBinding<HashSet<S::Key>>>,
    expandable: Option<KeyPredicate<S::Key>>,
    selected: Option<Rc<dyn Fn() -> Vec<S::Key>>>,
    on_selection: Option<SelectionKeysFn<S::Key>>,
    multi_select: bool,
    movable: bool,
    on_move: Option<TreeMoveFn<S::Key>>,
    move_guard: Option<TreeGuardFn<S::Key>>,
    type_ahead: Option<KeyTextFn<S::Key>>,
    reveal: Option<AnyBinding<Option<S::Key>>>,
    row_id: Option<KeyIdFn<S::Key>>,
    row_menu: Option<RowMenuEntriesFn<S::Key>>,
}

/// The committed-move callback, aliased for the field above.
type ExpansionFn<K> = Rc<dyn Fn(K, bool)>;
type TreeMoveFn<K> = Rc<dyn Fn(K, Option<K>, Option<usize>)>;
/// The live move guard, aliased for the field above.
type TreeGuardFn<K> = Rc<dyn Fn(&K, Option<&K>, Option<usize>) -> MoveVerdict>;
/// A per-key yes/no rule (`.expandable`), aliased for the field above.
type KeyPredicate<K> = Rc<dyn Fn(&K) -> bool>;
/// The full-selection callback (`.on_selection`), aliased for the field above.
type SelectionKeysFn<K> = Rc<dyn Fn(Vec<K>)>;
/// A per-key string (`.type_ahead`), aliased for the field above.
type KeyTextFn<K> = Rc<dyn Fn(&K) -> String>;
/// A registered identity per tree row, reevaluated on recycle.
type KeyIdFn<K> = Rc<dyn Fn(&K) -> day_core::ElementId>;
/// A row's summon-time context-menu builder (`.row_context_menu`), aliased for the field above.
type RowMenuEntriesFn<K> = Rc<dyn Fn(&K) -> Vec<MenuEntry>>;

/// Build a hierarchical tree from a [`NodeSource`] and a row builder:
/// `tree(branches(items_fn, key_of, parent_of), row_view)` for plain data,
/// `tree(store.tree(children_of), row_view)` for a day-model store.
pub fn tree<S, P>(source: S, build_row: impl Fn(S::Slot) -> P + 'static) -> TreePiece<S>
where
    S: NodeSource + 'static,
    P: Piece,
{
    TreePiece {
        source: Some(source),
        build_row: Rc::new(move |slot| AnyPiece::new(build_row(slot))),
        row_height: RowHeight::Automatic,
        indent: None,
        section_headers: false,
        on_expansion: None,
        expanded: None,
        expandable: None,
        selected: None,
        on_selection: None,
        multi_select: false,
        movable: false,
        on_move: None,
        move_guard: None,
        type_ahead: None,
        reveal: None,
        row_id: None,
        row_menu: None,
    }
}

#[day_macros::builder(TreeBuilder<S>)]
impl<S: NodeSource + 'static> TreePiece<S> {
    /// Row sizing: `Uniform(h)` (fastest) or `Automatic` (self-sizing).
    pub fn row_height(mut self, h: RowHeight) -> Self {
        self.row_height = h;
        self
    }
    /// Indentation per depth level, in points (unset = the platform's default step).
    pub fn indent(mut self, pts: f64) -> Self {
        self.indent = Some(pts);
        self
    }
    /// Render a two-level source as sections. Root branches are headings and cannot be
    /// selected; root leaves remain ordinary rows. Children must be leaves. This enables
    /// native ExpandableListView on Android, where arbitrary-depth trees are composed.
    pub fn section_headers(mut self) -> Self {
        self.section_headers = true;
        self
    }
    /// Reports an actual user/scripting disclosure change with the stable application key.
    /// Programmatic writes to `expanded` do not echo this callback.
    pub fn on_expansion(mut self, f: impl Fn(S::Key, bool) + 'static) -> Self {
        self.on_expansion = Some(Rc::new(f));
        self
    }
    /// The app-owned expansion set (docs/tree.md): the user's disclosure clicks update it,
    /// and the app writing it discloses/collapses the native rows. Persist it (or don't);
    /// it is plain state.
    pub fn expanded(mut self, set: impl Binding<HashSet<S::Key>>) -> Self {
        self.expanded = Some(AnyBinding::new(set));
        self
    }
    /// Which rows can hold children at all: what draws (or omits) the disclosure, and which
    /// rows a drop may land on. Defaults to "has children right now", which draws no
    /// disclosure on an empty group; a source with real branch/leaf kinds should say so.
    pub fn expandable(mut self, f: impl Fn(&S::Key) -> bool + 'static) -> Self {
        self.expandable = Some(Rc::new(f));
        self
    }
    /// Reactively sync the native selection to these keys (empty clears). Point it and
    /// [`Self::on_selection`] at one signal and selection is two-way, shared with anything
    /// else reading the same state.
    pub fn selected(mut self, f: impl Fn() -> Vec<S::Key> + 'static) -> Self {
        self.selected = Some(Rc::new(f));
        self
    }
    /// Called with the full selected key set (empty = cleared) whenever the user changes the
    /// selection.
    pub fn on_selection(mut self, f: impl Fn(Vec<S::Key>) + 'static) -> Self {
        self.on_selection = Some(Rc::new(f));
        self
    }
    /// Allow selecting several rows at once, where the toolkit supports it.
    pub fn multi_select(mut self) -> Self {
        self.multi_select = true;
        self
    }
    /// Let the user drag rows to a new parent/position with the platform's native mechanism,
    /// where the backend supports it (probe `Cap::TreeMove`): the tree is movable exactly when
    /// it carries a [`Move`], whose handler re-parents the app's data.
    ///
    /// ```ignore
    /// tree(nodes, row_view).movable(Move::new(move |key, parent, index| store.reparent(key, parent, index)))
    /// ```
    pub fn movable(mut self, mv: Move<S::Key>) -> Self {
        self.movable = true;
        self.on_move = Some(mv.moved);
        // Availability first (`Move::enabled`), then the app's guard, then the structural
        // refusals the driver adds.
        let enabled = mv.enabled;
        let guard = mv.guard;
        self.move_guard = Some(Rc::new(move |k: &S::Key, p: Option<&S::Key>, i| {
            if !enabled.get_untracked() {
                return MoveVerdict::Deny;
            }
            match &guard {
                Some(g) => g(k, p, i),
                None => MoveVerdict::Allow,
            }
        }));
        self
    }
    /// The row's type-ahead string (docs/tree.md): what native type-select matches against.
    /// Unset rows don't participate.
    pub fn type_ahead(mut self, f: impl Fn(&S::Key) -> String + 'static) -> Self {
        self.type_ahead = Some(Rc::new(f));
        self
    }
    /// Programmatic reveal: set the signal to `Some(key)` and the row scrolls into view with
    /// every ancestor expanded (through [`Self::expanded`], so the app sees the change).
    pub fn reveal(mut self, target: impl Binding<Option<S::Key>>) -> Self {
        self.reveal = Some(AnyBinding::new(target));
        self
    }
    /// A dayscript element id per row, from its key (docs/tree.md): re-applied on every
    /// recycle, so `tap`/`assert_text` address the row wherever its cell currently sits. It
    /// is also what the `expand:`/`tree_move:` steps resolve rows by.
    pub fn row_id(mut self, f: impl Fn(&S::Key) -> day_core::ElementId + 'static) -> Self {
        self.row_id = Some(Rc::new(f));
        self
    }
    /// A per-row context menu, built when the menu is summoned (docs/menus.md "Dynamic context
    /// menus"): right-click on desktop, long-press on touch. The closure receives the
    /// row's key and returns the menu to show; it may adjust the app's selection first (the
    /// convention: a summon outside the current selection selects that row). An empty
    /// result shows nothing for that row.
    pub fn row_context_menu(mut self, f: impl Fn(&S::Key) -> Vec<MenuEntry> + 'static) -> Self {
        self.row_menu = Some(Rc::new(f));
        self
    }

    /// The composed tree (docs/tree.md M2): on a backend without a native tree widget, the
    /// same piece flattens its visible rows onto [`list()`]; indentation and the disclosure
    /// chevron are day pieces inside each row, and selection rides the list's own machinery.
    /// The [`TreeDriver`] still installs on the returned node, so the dayscript
    /// `expand:`/`tree_move:` steps drive the composed tree exactly as they drive a native
    /// one (`attach_tree` is the no-op default off the native path; nothing pulls cells).
    fn build_composed(mut self, cx: &mut BuildCx) -> RNode {
        /// Disclosure column width, and the default per-depth indent where the platform
        /// offers no native step to inherit.
        const CHEVRON_W: f64 = 18.0;
        const DEFAULT_INDENT: f64 = 14.0;

        let conn = Rc::new(self.source.take().expect("TreePiece built once").connect());
        // Expansion state: the app's key set when it owns one, else this token set. Both are
        // signals, so the flattener below re-runs on every disclosure however it arrives:
        // a chevron tap, the app writing its set, or a synthetic `expand:` step.
        let open_sig: Signal<HashSet<u64>> = Signal::new(HashSet::new());
        let expanded_sig = self.expanded;

        // Tracked when read inside a reactive closure.
        let is_open: Rc<dyn Fn(u64) -> bool> = {
            let conn = conn.clone();
            match expanded_sig {
                Some(sig) => Rc::new(move |t| match conn.key_of(t) {
                    Some(k) => sig.with(|s| s.contains(&k)),
                    None => false,
                }),
                None => Rc::new(move |t| open_sig.with(|s| s.contains(&t))),
            }
        };
        let set_open: Rc<dyn Fn(u64, bool)> = {
            let (conn, is_open, changed) =
                (conn.clone(), is_open.clone(), self.on_expansion.clone());
            Rc::new(move |t, on| {
                if day_reactive::untrack(|| is_open(t)) == on {
                    return;
                }
                let Some(key) = conn.key_of(t) else {
                    return;
                };
                if let Some(sig) = expanded_sig {
                    sig.update(|s| {
                        if on {
                            s.insert(key.clone());
                        } else {
                            s.remove(&key);
                        }
                    });
                } else {
                    open_sig.update(|s| {
                        if on {
                            s.insert(t);
                        } else {
                            s.remove(&t);
                        }
                    });
                }
                if let Some(f) = &changed {
                    f(key, on);
                }
            })
        };

        // "Can hold children": the app's branch/leaf rule, or "has children right now".
        let expandable_of: Rc<dyn Fn(u64) -> bool> = {
            let (conn, f) = (conn.clone(), self.expandable.clone());
            Rc::new(move |tok| match &f {
                Some(f) => conn.key_of(tok).map(|k| f(&k)).unwrap_or(false),
                None => conn.children_len(Some(tok)) > 0,
            })
        };

        // The visible rows, in display order: a refresh (the tracked shape read) plus a DFS
        // that descends only into expanded rows. This is the list's row set.
        fn visible<C: TreeConn + ?Sized>(
            conn: &C,
            is_open: &dyn Fn(u64) -> bool,
            parent: Option<u64>,
            depth: u16,
            out: &mut Vec<(u64, u16)>,
        ) {
            for i in 0..conn.children_len(parent) {
                let t = conn.child_token(parent, i);
                out.push((t, depth));
                if is_open(t) {
                    visible(conn, is_open, Some(t), depth + 1, out);
                }
            }
        }
        let flatten: Rc<dyn Fn() -> Vec<(u64, u16)>> = {
            let (conn, is_open) = (conn.clone(), is_open.clone());
            Rc::new(move || {
                let _shape = conn.refresh();
                let mut rows = Vec::new();
                visible(&*conn, &*is_open, None, 0, &mut rows);
                rows
            })
        };

        // Each physical row: indent shell → chevron + the user's row content. The rebind
        // watch re-points the user's slot, the depth cell, and the dayscript id whenever
        // the list recycles this cell onto another row.
        let step = self.indent.unwrap_or(DEFAULT_INDENT);
        let build_row = {
            let (conn, user_row, row_id) =
                (conn.clone(), self.build_row.clone(), self.row_id.clone());
            let (is_open, expandable_of, set_open) =
                (is_open.clone(), expandable_of.clone(), set_open.clone());
            let row_menu = self.row_menu.clone();
            move |slot: ItemSlot<(u64, u16), u64>| -> AnyPiece {
                let (token0, depth0) = day_reactive::untrack(|| slot.get());
                let Some(user_slot) = conn.slot_for(token0) else {
                    // A stale mid-reload pull: an empty row instead of a panic.
                    return AnyPiece::new(crate::spacer());
                };
                let depth = Rc::new(std::cell::Cell::new(depth0 as f64));
                let chevron = {
                    let (is_open, expandable_of) = (is_open.clone(), expandable_of.clone());
                    let (set_open, is_open_tap) = (set_open.clone(), is_open.clone());
                    let expandable_tap = expandable_of.clone();
                    crate::label(move || {
                        let t = slot.get().0;
                        // The full-size triangles (U+25BC/25B6), not the small â–¾/â–¸ forms:
                        // HarmonyOS Sans ships no glyph for the small ones; they rendered
                        // as nothing at all on harmony-arkui.
                        if expandable_of(t) {
                            if is_open(t) { "â–¼" } else { "â–¶" }
                        } else {
                            ""
                        }
                        .to_string()
                    })
                    .align(TextAlign::Center)
                    .width(CHEVRON_W)
                    .on_tap(move || {
                        let t = day_reactive::untrack(|| slot.get().0);
                        if expandable_tap(t) {
                            set_open(t, !day_reactive::untrack(|| is_open_tap(t)));
                        }
                    })
                };
                let content = crate::row((chevron, user_row(user_slot)));
                let shell = TreeRowShell {
                    depth: depth.clone(),
                    step,
                    content: AnyPiece::new(content),
                }
                .tweak({
                    let (conn, row_id) = (conn.clone(), row_id.clone());
                    move |n| {
                        let id_conn = conn.clone();
                        let set_ids = move |tok: u64| {
                            if let Some(rid) = &row_id
                                && let Some(k) = id_conn.key_of(tok)
                            {
                                with_tree(|t| t.set_id(n, rid(&k).as_str().to_owned()));
                            }
                        };
                        set_ids(token0);
                        watch(
                            move || slot.get(),
                            move |(tok, d), _| {
                                conn.rebind(&user_slot, *tok);
                                depth.set(*d as f64);
                                set_ids(*tok);
                            },
                        );
                    }
                });
                match &row_menu {
                    // The ordinary decorator: the dom backend arms its listener, and the
                    // composed presenter answers the summon. The key is read when the menu is
                    // summoned, so a recycled cell asks about the row it currently shows.
                    Some(f) => {
                        let (conn, f) = (conn.clone(), f.clone());
                        AnyPiece::new(shell.context_menu(move |_p: day_spec::Point| {
                            match conn.key_of(day_reactive::untrack(|| slot.get().0)) {
                                Some(k) => f(&k),
                                None => Vec::new(),
                            }
                        }))
                    }
                    None => AnyPiece::new(shell),
                }
            }
        };

        let section_header: Rc<dyn Fn(u64) -> bool> = {
            let (conn, expandable, sections) =
                (conn.clone(), expandable_of.clone(), self.section_headers);
            Rc::new(move |t| sections && conn.parent_of(t) == Some(None) && expandable(t))
        };
        let scroll_sig: Signal<Option<usize>> = Signal::new(None);
        let mut lst = list(
            items(
                {
                    let flatten = flatten.clone();
                    move || flatten()
                },
                |r: &(u64, u16)| r.0,
            ),
            build_row,
        )
        .row_height(self.row_height)
        .apply_if(self.multi_select, |l| l.multi_select())
        .scroll_to_row(scroll_sig);
        // A composed list may report a heading click. Reapply the last destination
        // selection even when the app's signal did not change, so headers never stay lit.
        let selected_tokens = Signal::new(Vec::<u64>::new());
        let selection_revision = Signal::new(0u64);
        if self.on_selection.is_some() || (self.section_headers && self.selected.is_some()) {
            let conn = conn.clone();
            let header = section_header.clone();
            let callback = self.on_selection.clone();
            lst = lst.on_selection(move |toks: Vec<u64>| {
                if toks.iter().any(|t| header(*t)) {
                    selection_revision.update(|r| *r += 1);
                    return;
                }
                selected_tokens.set(toks.clone());
                if let Some(f) = &callback {
                    f(toks.iter().filter_map(|t| conn.key_of(*t)).collect());
                }
            });
        }
        let mut repair_selection: Option<Rc<dyn Fn() -> Vec<usize>>> = None;
        if self.selected.is_some() || (self.section_headers && self.on_selection.is_some()) {
            let (conn, flatten, selected) = (conn.clone(), flatten.clone(), self.selected.clone());
            let section_header = section_header.clone();
            let rows: Rc<dyn Fn() -> Vec<usize>> = Rc::new(move || {
                let rows = flatten();
                let want: HashSet<u64> = match &selected {
                    Some(sel) => sel().iter().map(|k| conn.token_of(k)).collect(),
                    None => selected_tokens.get().into_iter().collect(),
                };
                rows.iter()
                    .enumerate()
                    .filter(|(_, r)| want.contains(&r.0) && !section_header(r.0))
                    .map(|(i, _)| i)
                    .collect()
            });
            repair_selection = Some(rows.clone());
            lst = lst.selected_rows(move || rows());
        }
        let node = lst.build(cx);
        if let Some(rows) = repair_selection {
            day_reactive::bind(
                move || selection_revision.get(),
                move |revision| {
                    if *revision != 0 {
                        let rows = day_reactive::untrack(|| rows());
                        day_reactive::on_main(move || day_core::list_set_selected(node, rows));
                    }
                },
            );
        }

        // Synthetic events (the dayscript `expand:` step, `tree_try_move`'s commit) land on
        // this node exactly as native ones land on a native tree.
        {
            let (on_move, conn_ev, set_open) =
                (self.on_move.clone(), conn.clone(), set_open.clone());
            cx.on(node, move |ev| match ev {
                Event::TreeExpanded { token, expanded } => set_open(*token, *expanded),
                Event::TreeMove {
                    token,
                    parent,
                    index,
                } => {
                    if let Some(f) = &on_move
                        && let Some(key) = conn_ev.key_of(*token)
                    {
                        f(key, parent.and_then(|p| conn_ev.key_of(p)), *index);
                    }
                }
                _ => {}
            });
        }

        // The driver: what `expand:`/`tree_move:` resolve rows and route moves through.
        let driver = TreeDriver {
            section_header: {
                let f = section_header.clone();
                Box::new(move |t| f(t))
            },
            row_height: self.row_height,
            children_len: {
                let conn = conn.clone();
                Box::new(move |p| conn.children_len(p))
            },
            child_token: {
                let conn = conn.clone();
                Box::new(move |p, i| conn.child_token(p, i))
            },
            expandable: {
                let f = expandable_of.clone();
                Box::new(move |t| f(t))
            },
            expanded: {
                let is_open = is_open.clone();
                Box::new(move |t| day_reactive::untrack(|| is_open(t)))
            },
            // Never pulled: no toolkit attaches to the composed tree, so no cell binds
            // arrive. The list's own driver owns the physical rows.
            build: Box::new(|_tok, _anchor| TreeBuiltRow {
                scope: Scope::child(),
                rebind: Rc::new(|_| {}),
            }),
            type_select_text: Box::new(|_| String::new()),
            resolve_row: {
                let (conn, row_id) = (conn.clone(), self.row_id.clone());
                Box::new(move |id| {
                    let rid = row_id.as_ref()?;
                    conn.tokens_now().into_iter().find(|t| {
                        conn.key_of(*t)
                            .map(|k| rid(&k).as_str() == id)
                            .unwrap_or(false)
                    })
                })
            },
            row_menu: None,
            moves: self.movable.then(|| {
                let can = {
                    let (conn, expandable_of, guard) =
                        (conn.clone(), expandable_of.clone(), self.move_guard.clone());
                    move |tok: u64, parent: Option<u64>, index: Option<usize>| {
                        let Some(key) = conn.key_of(tok) else {
                            return MoveVerdict::Deny;
                        };
                        let parent_key = match parent {
                            Some(p) => {
                                if p == tok || !expandable_of(p) {
                                    return MoveVerdict::Deny;
                                }
                                let mut cur = Some(p);
                                while let Some(c) = cur {
                                    if c == tok {
                                        return MoveVerdict::Deny;
                                    }
                                    cur = conn.parent_of(c).flatten();
                                }
                                match conn.key_of(p) {
                                    Some(k) => Some(k),
                                    None => return MoveVerdict::Deny,
                                }
                            }
                            None => None,
                        };
                        match &guard {
                            Some(g) => g(&key, parent_key.as_ref(), index),
                            None => MoveVerdict::Allow,
                        }
                    }
                };
                let can_commit = can.clone();
                TreeMovesDriver {
                    can_move: Box::new(can),
                    moved: Box::new(move |t, p, i| {
                        if can_commit(t, p, i) == MoveVerdict::Deny {
                            return;
                        }
                        enqueue_event(
                            rnode_to_id(node),
                            Event::TreeMove {
                                token: t,
                                parent: p,
                                index: i,
                            },
                        );
                    }),
                }
            }),
        };
        install_tree(node, driver);

        // Reveal: expand every ancestor through the app-visible state, then scroll the
        // list to the row's flattened index.
        if let Some(sig) = self.reveal {
            let (conn, set_open, flatten) = (conn.clone(), set_open.clone(), flatten.clone());
            watch(
                move || sig.get(),
                move |key: &Option<S::Key>, _| {
                    let Some(key) = key else { return };
                    let tok = conn.token_of(key);
                    let mut cur = conn.parent_of(tok).flatten();
                    while let Some(p) = cur {
                        set_open(p, true);
                        cur = conn.parent_of(p).flatten();
                    }
                    let row = day_reactive::untrack(|| flatten())
                        .iter()
                        .position(|r| r.0 == tok);
                    if let Some(row) = row {
                        scroll_sig.set(Some(row));
                    }
                },
            );
        }

        node
    }
}

/// The composed tree row's indentation (docs/tree.md M2): offsets its single child by the
/// row's current depth × step. Depth lives in a `Cell` the rebind watch writes before the
/// cell's relayout, so a recycled row re-indents without rebuilding.
struct TreeIndent {
    depth: Rc<std::cell::Cell<f64>>,
    step: f64,
}

impl Layout for TreeIndent {
    fn measure(&self, cx: &mut dyn LayoutOps, children: &[RNode], p: Proposal) -> Size {
        let pad = self.depth.get() * self.step;
        let child_p = Proposal::new(p.width.map(|w| (w - pad).max(0.0)), p.height);
        let s = match children.first() {
            Some(&c) => cx.measure_child(c, child_p),
            None => Size::ZERO,
        };
        Size::new(s.width + pad, s.height)
    }
    fn place(&self, cx: &mut dyn LayoutOps, children: &[RNode], bounds: Rect) {
        if let Some(&c) = children.first() {
            let pad = (self.depth.get() * self.step).min(bounds.size.width);
            let inner = Size::new(bounds.size.width - pad, bounds.size.height);
            let _ = cx.measure_child(c, Proposal::exact(inner));
            cx.place_child(c, Rect::new(pad, 0.0, inner.width, inner.height));
        }
    }
}

/// One composed tree row: the [`TreeIndent`] wrapper around the chevron + user content,
/// grown to the cell's width so selection and taps span the row.
struct TreeRowShell {
    depth: Rc<std::cell::Cell<f64>>,
    step: f64,
    content: AnyPiece,
}

impl Piece for TreeRowShell {
    fn build(self, cx: &mut BuildCx) -> RNode {
        // Native, not layout-only: the row's dayscript id and its `.context_menu_fn` listener
        // both need a realized element to land on (a11y identifier; the dom's `contextmenu`
        // arm). A transparent container, like the decorators' layer nodes.
        let w = cx.native(
            kinds::CONTAINER,
            &ContainerProps {
                background: None,
                corner_radius: 0.0,
                clips: false,
                role: None,
            },
            Rc::new(TreeIndent {
                depth: self.depth,
                step: self.step,
            }),
            Flex {
                grow_w: true,
                ..Default::default()
            },
            Boundary::No,
        );
        cx.under(w, |cx| {
            let _ = self.content.build(cx);
        });
        w
    }
}

impl<S: NodeSource + 'static> Piece for TreePiece<S> {
    fn build(mut self, cx: &mut BuildCx) -> RNode {
        // No native tree widget → the composed tree: the same piece contract flattened onto
        // [`list()`] (docs/tree.md M2). `Emulated` and `Unsupported` both take this path; the
        // composition needs nothing beyond the list machinery every backend carries.
        // Two-level-only native controls (Android) provide single selection. A
        // multi-select section source uses the full-tree path, composed where necessary.
        let cap = if self.section_headers && !self.multi_select {
            day_spec::Cap::TreeSections
        } else {
            day_spec::Cap::Tree
        };
        if day_core::capability(cap) != day_spec::Support::Native {
            return self.build_composed(cx);
        }
        let props = TreeProps {
            section_headers: self.section_headers,
            row_height: self.row_height,
            selectable: self.selected.is_some() || self.on_selection.is_some(),
            multi_select: self.multi_select,
            movable: self.movable,
            indent: self.indent,
        };
        let node = cx.leaf(
            kinds::TREE,
            &props,
            Flex {
                grow_w: true,
                grow_h: true,
                ..Default::default()
            },
        );

        let conn = Rc::new(self.source.take().expect("TreePiece built once").connect());

        // The driver's (and flattener's) view of expansion: token-keyed, updated from native
        // disclosure events and from every programmatic patch this piece issues, so it is
        // right whether or not the app owns an expansion signal.
        let open_tokens: Rc<RefCell<HashSet<u64>>> = Rc::new(RefCell::new(HashSet::new()));

        // "Can hold children": the app's branch/leaf rule, or "has children right now".
        let expandable_of: Rc<dyn Fn(u64) -> bool> = {
            let (conn, f) = (conn.clone(), self.expandable.clone());
            Rc::new(move |tok| match &f {
                Some(f) => conn.key_of(tok).map(|k| f(&k)).unwrap_or(false),
                None => conn.children_len(Some(tok)) > 0,
            })
        };

        let section_header: Rc<dyn Fn(u64) -> bool> = {
            let (conn, expandable, sections) =
                (conn.clone(), expandable_of.clone(), self.section_headers);
            Rc::new(move |t| sections && conn.parent_of(t) == Some(None) && expandable(t))
        };
        // Native events → app state.
        {
            let (on_selection, expanded_sig) = (self.on_selection.clone(), self.expanded);
            let (on_move, conn_ev, open) =
                (self.on_move.clone(), conn.clone(), open_tokens.clone());
            let changed = self.on_expansion.clone();
            let header = section_header.clone();
            cx.on(node, move |ev| match ev {
                Event::TreeSelection(tokens) => {
                    if let Some(f) = &on_selection {
                        f(tokens
                            .iter()
                            .filter(|t| !header(**t))
                            .filter_map(|t| conn_ev.key_of(*t))
                            .collect());
                    }
                }
                Event::TreeExpanded { token, expanded } => {
                    let Some(key) = conn_ev.key_of(*token) else {
                        return;
                    };
                    let was = expanded_sig
                        .map(|sig| day_reactive::untrack(|| sig.with(|s| s.contains(&key))))
                        .unwrap_or_else(|| open.borrow().contains(token));
                    if was == *expanded {
                        return;
                    }
                    match &expanded_sig {
                        // The app's set follows the disclosure, and the expansion watch
                        // derives the patch. The record does not move here: for a native
                        // click the patch is a redundant no-op, and for a synthetic event
                        // (the dayscript `expand:` step) it is the very thing that discloses
                        // the row; pre-moving the record swallowed it.
                        Some(sig) => {
                            if let Some(key) = conn_ev.key_of(*token) {
                                sig.update(|set| {
                                    if *expanded {
                                        set.insert(key.clone());
                                    } else {
                                        set.remove(&key);
                                    }
                                });
                            }
                        }
                        // No app signal: this record IS the expansion state.
                        // The native tree is told too: a no-op after a native click, and for a
                        // synthetic event (the dayscript `expand:` step) the disclosure itself,
                        // which recording alone never showed.
                        None => {
                            if *expanded {
                                open.borrow_mut().insert(*token);
                            } else {
                                open.borrow_mut().remove(token);
                            }
                            day_core::tree_set_expanded(node, *token, *expanded);
                        }
                    }
                    if let Some(f) = &changed {
                        f(key, *expanded);
                    }
                }
                Event::TreeMove {
                    token,
                    parent,
                    index,
                } => {
                    if let Some(f) = &on_move
                        && let Some(key) = conn_ev.key_of(*token)
                    {
                        f(key, parent.and_then(|p| conn_ev.key_of(p)), *index);
                    }
                }
                _ => {}
            });
        }

        // The type-erased driver day-core drives on cell pulls (docs/tree.md).
        let driver = TreeDriver {
            section_header: {
                let f = section_header.clone();
                Box::new(move |t| f(t))
            },
            row_height: self.row_height,
            children_len: {
                let conn = conn.clone();
                Box::new(move |p| conn.children_len(p))
            },
            child_token: {
                let conn = conn.clone();
                Box::new(move |p, i| conn.child_token(p, i))
            },
            expandable: {
                let f = expandable_of.clone();
                Box::new(move |t| f(t))
            },
            expanded: {
                let open = open_tokens.clone();
                Box::new(move |t| open.borrow().contains(&t))
            },
            build: {
                let (conn, build_row, row_id) =
                    (conn.clone(), self.build_row.clone(), self.row_id.clone());
                Box::new(move |token, anchor| {
                    let scope = Scope::child();
                    let (conn, build_row, row_id) =
                        (conn.clone(), build_row.clone(), row_id.clone());
                    let rebind = scope.enter(move || {
                        // Native callbacks can deliver a stale token mid-animation; an
                        // unknown pull yields an empty row instead of panicking.
                        let Some(slot) = conn.slot_for(token) else {
                            return Rc::new(|_: u64| {}) as Rc<dyn Fn(u64)>;
                        };
                        let mut rowcx = BuildCx::new(anchor);
                        let root = build_row(slot).build(&mut rowcx);
                        if let Some(rid) = &row_id
                            && let Some(k) = conn.key_of(token)
                        {
                            with_tree(|t| t.set_id(root, rid(&k).as_str().to_owned()));
                        }
                        // Rebind on recycle: point the slot (and the row's element id) at
                        // the cell's new row.
                        Rc::new(move |tok: u64| {
                            conn.rebind(&slot, tok);
                            if let Some(rid) = &row_id
                                && let Some(k) = conn.key_of(tok)
                            {
                                with_tree(|t| t.set_id(root, rid(&k).as_str().to_owned()));
                            }
                        }) as Rc<dyn Fn(u64)>
                    });
                    TreeBuiltRow { scope, rebind }
                })
            },
            type_select_text: {
                let (conn, f) = (conn.clone(), self.type_ahead.clone());
                Box::new(move |tok| match &f {
                    Some(f) => conn.key_of(tok).map(|k| f(&k)).unwrap_or_default(),
                    None => String::new(),
                })
            },
            resolve_row: {
                let (conn, row_id) = (conn.clone(), self.row_id.clone());
                Box::new(move |id| {
                    let rid = row_id.as_ref()?;
                    conn.tokens_now().into_iter().find(|t| {
                        conn.key_of(*t)
                            .map(|k| rid(&k).as_str() == id)
                            .unwrap_or(false)
                    })
                })
            },
            row_menu: self.row_menu.clone().map(|f| {
                // Per-summon lowering in its own scope, disposed when the next summon (or
                // the tree's teardown) replaces it: the `context_menu_fn` rule.
                let conn = conn.clone();
                let last: Rc<RefCell<Option<Scope>>> = Rc::default();
                {
                    let last = last.clone();
                    Scope::current().on_cleanup(move || {
                        if let Some(s) = last.borrow_mut().take() {
                            s.dispose();
                        }
                    });
                }
                Box::new(move |tok: u64| {
                    let Some(key) = conn.key_of(tok) else {
                        return Vec::new();
                    };
                    if let Some(s) = last.borrow_mut().take() {
                        s.dispose();
                    }
                    let scope = Scope::child();
                    let items = scope.enter(|| crate::menus::lower_menu_scoped(f(&key)));
                    *last.borrow_mut() = Some(scope);
                    items
                }) as day_core::tree_driver::RowMenuFn
            }),
            moves: self.movable.then(|| {
                // The live verdict: structural refusals first (a row into itself, into its
                // own descendant, into a leaf, or addressing anything unknown), then the
                // app's guard.
                let can = {
                    let (conn, expandable_of, guard) =
                        (conn.clone(), expandable_of.clone(), self.move_guard.clone());
                    move |tok: u64, parent: Option<u64>, index: Option<usize>| {
                        let Some(key) = conn.key_of(tok) else {
                            return MoveVerdict::Deny;
                        };
                        let parent_key = match parent {
                            Some(p) => {
                                if p == tok || !expandable_of(p) {
                                    return MoveVerdict::Deny;
                                }
                                // Walk p's ancestors: dropping into one's own subtree.
                                let mut cur = Some(p);
                                while let Some(c) = cur {
                                    if c == tok {
                                        return MoveVerdict::Deny;
                                    }
                                    cur = conn.parent_of(c).flatten();
                                }
                                match conn.key_of(p) {
                                    Some(k) => Some(k),
                                    None => return MoveVerdict::Deny,
                                }
                            }
                            None => None,
                        };
                        match &guard {
                            Some(g) => g(&key, parent_key.as_ref(), index),
                            None => MoveVerdict::Allow,
                        }
                    }
                };
                let can_commit = can.clone();
                TreeMovesDriver {
                    can_move: Box::new(can),
                    // Commit: defer the app's callback through the event queue; its own data
                    // write drives the reload (docs/tree.md).
                    moved: Box::new(move |t, p, i| {
                        if can_commit(t, p, i) == MoveVerdict::Deny {
                            return;
                        }
                        enqueue_event(
                            rnode_to_id(node),
                            Event::TreeMove {
                                token: t,
                                parent: p,
                                index: i,
                            },
                        );
                    }),
                }
            }),
        };
        install_tree(node, driver);

        // Prime the snapshot, tell the native host, and re-assert expansion + selection by
        // token after every shape change (docs/tree.md: a reload must not silently collapse
        // the tree or drop its selection).
        let apply_expansion = {
            let (conn, open) = (conn.clone(), open_tokens.clone());
            let expanded_sig = self.expanded;
            move || {
                let desired: HashSet<u64> = match &expanded_sig {
                    Some(sig) => {
                        let conn = &conn;
                        sig.get_untracked()
                            .iter()
                            .map(|k| conn.token_of(k))
                            .collect()
                    }
                    None => open.borrow().clone(),
                };
                let present: HashSet<u64> = conn.tokens_now().into_iter().collect();
                // Parents before children: a backend may not record a disclosure for a row
                // whose ancestor is still collapsed.
                let mut ordered: Vec<u64> = desired
                    .iter()
                    .filter(|t| present.contains(t))
                    .copied()
                    .collect();
                let depth_of = |mut t: u64| {
                    let mut d = 0usize;
                    while let Some(Some(p)) = conn.parent_of(t) {
                        d += 1;
                        t = p;
                    }
                    d
                };
                ordered.sort_by_key(|t| depth_of(*t));
                for t in ordered {
                    tree_set_expanded(node, t, true);
                }
                open.borrow_mut().clone_from(&desired);
            }
        };
        let apply_selection = {
            let (conn, selected) = (conn.clone(), self.selected.clone());
            move || {
                if let Some(sel) = &selected {
                    let keys = day_reactive::untrack(|| sel());
                    let toks: Vec<u64> = keys.iter().map(|k| conn.token_of(k)).collect();
                    tree_set_selected(node, toks);
                }
            }
        };
        {
            let conn2 = conn.clone();
            let initial = {
                let conn = conn.clone();
                day_reactive::untrack(move || conn.refresh())
            };
            // The native host attached against an empty snapshot: tell it the real node set
            // now, then disclose the initially-expanded rows (see the list's prime for why
            // skipping this renders blank while the synthetic rail keeps passing).
            tree_reload(node);
            apply_expansion();
            apply_selection();
            let last: RefCell<Vec<(u64, Option<u64>)>> = RefCell::new(initial);
            let (apply_expansion, apply_selection) =
                (apply_expansion.clone(), apply_selection.clone());
            let conn3 = conn.clone();
            watch(
                move || conn2.refresh(),
                move |shape: &Vec<(u64, Option<u64>)>, _| {
                    let unchanged = !conn3.values_flow_by_reload() && *last.borrow() == *shape;
                    *last.borrow_mut() = shape.clone();
                    if unchanged {
                        return;
                    }
                    tree_reload(node);
                    apply_expansion();
                    apply_selection();
                },
            );
        }

        // App expansion signal → native disclosure (delta patches; redundant ones no-op).
        if let Some(sig) = self.expanded {
            let (conn, open) = (conn.clone(), open_tokens.clone());
            watch(
                move || sig.get(),
                move |set: &HashSet<S::Key>, _| {
                    let desired: HashSet<u64> = set.iter().map(|k| conn.token_of(k)).collect();
                    let current = open.borrow().clone();
                    for t in desired.difference(&current) {
                        tree_set_expanded(node, *t, true);
                    }
                    for t in current.difference(&desired) {
                        tree_set_expanded(node, *t, false);
                    }
                    open.borrow_mut().clone_from(&desired);
                },
            );
        }

        // Programmatic selection sync (`watch`, so the initial build doesn't clobber a
        // toolkit-default selection; the prime above already applied it once).
        if let Some(sel) = self.selected.clone() {
            let conn = conn.clone();
            watch(
                move || sel(),
                move |keys: &Vec<S::Key>, _| {
                    let toks: Vec<u64> = keys.iter().map(|k| conn.token_of(k)).collect();
                    tree_set_selected(node, toks);
                },
            );
        }

        // Reveal: expand every ancestor (native + the app's signal), then scroll.
        if let Some(sig) = self.reveal {
            let (conn, open, expanded_sig) = (conn.clone(), open_tokens.clone(), self.expanded);
            watch(
                move || sig.get(),
                move |key: &Option<S::Key>, _| {
                    let Some(key) = key else { return };
                    let tok = conn.token_of(key);
                    let mut ancestors = Vec::new();
                    let mut cur = conn.parent_of(tok).flatten();
                    while let Some(p) = cur {
                        ancestors.push(p);
                        cur = conn.parent_of(p).flatten();
                    }
                    for p in ancestors.iter().rev() {
                        tree_set_expanded(node, *p, true);
                        open.borrow_mut().insert(*p);
                        if let Some(sig) = &expanded_sig
                            && let Some(k) = conn.key_of(*p)
                        {
                            sig.update(|set| {
                                set.insert(k.clone());
                            });
                        }
                    }
                    tree_reveal(node, tok);
                },
            );
        }

        node
    }
}

// ---------------------------------------------------------------------------
// The test host (docs/testing.md)
// ---------------------------------------------------------------------------

/// The root of an app's test build: `content` normally, and while `day test` drives a GUI
/// case, that case's page alone, built fresh for the case and disposed when the next one
/// starts. One page mounted at a time is what keeps one case's ids, signals and resident
/// native views out of the next one's way.
///
/// ```ignore
/// pub fn root() -> impl Piece {
///     day::test_host(|| my_app_root())
/// }
/// ```
///
/// A panic while the case's page is built is caught here and reported as the case's failure;
/// the host shows the message in its place.
pub fn test_host<P: Piece>(content: impl Fn() -> P + 'static) -> impl Piece {
    let content = Rc::new(content);
    piece_fn(move |cx| {
        // Bumped whenever the engine changes the active case: a new key is a new `each` row,
        // so the old page's scope is disposed and the new one builds from scratch.
        let generation = Signal::new(0u64);
        day_core::conformance::set_host(Some(Rc::new(move || generation.update(|g| *g += 1))));
        Scope::current().on_cleanup(|| day_core::conformance::set_host(None));
        each(
            items(move || vec![generation.get()], |g: &u64| *g),
            move |_| match day_core::conformance::active() {
                Some(case) => guarded_page(case),
                None => AnyPiece::new(content()),
            },
        )
        .build(cx)
    })
}

/// A case's page, built with a panic caught and recorded rather than taking the app down.
/// Also what a browsing view of the cases shows (the conformance app's navigation).
pub fn guarded_page(case: day_core::conformance::Case) -> AnyPiece {
    AnyPiece::new(piece_fn(move |cx| {
        let built = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            case.build_page().map(|page| page.build(&mut *cx))
        }));
        match built {
            Ok(Some(root)) => root,
            Ok(None) => crate::label("").build(cx),
            Err(payload) => {
                let message = day_core::conformance::panic_message(payload.as_ref());
                day_core::conformance::note_page_panic(message.clone());
                crate::label(format!("panicked: {message}")).build(cx)
            }
        }
    }))
}

#[cfg(feature = "conformance")]
pub(crate) mod conformance {
    use day_core::conformance::{Case, Drive, Fail};
    use day_geometry::Insets;
    use day_reactive::Signal;
    use day_spec::props::RowHeight;
    use day_spec::{Cap, Font, kinds};

    use crate::*;

    /// A list of the given names, each row a label with the id `row:<name>`.
    fn names_list(names: Signal<Vec<String>>) -> List<Items<String, String>> {
        list(
            items(move || names.get(), |n: &String| n.clone()),
            |row: ItemSlot<String, String>| {
                // A reactive id, before the padding: a recycled cell rebinds to other rows, and
                // the id must name the label rather than its wrapper.
                label(move || row.get())
                    .id_of(move || day_core::id!(conformance_row, row.get()))
                    .padding(Insets::symmetric(12.0, 6.0))
            },
        )
        .row_height(RowHeight::Uniform(32.0))
    }

    fn names(list: &[&str]) -> Signal<Vec<String>> {
        Signal::new(list.iter().map(|s| s.to_string()).collect())
    }

    /// A list item realizes as the platform's own row content (docs/list.md "List items"),
    /// and its check mark follows its source in place.
    #[day_macros::test(day_core)]
    fn list_items_show_their_parts() -> Case {
        Case::new()
            .proves(kinds::LIST_ITEM)
            .proves_cap(Cap::ListItem)
            .requires(Cap::ListItem)
            .page(|| {
                let done = Signal::new(false);
                let rows = names(&["Milk", "Bread"]);
                column((
                    button("Done")
                        .action(move || done.update(|d| *d = !*d))
                        .id(day_core::id!(toggle_done)),
                    list(
                        items(move || rows.get(), |n: &String| n.clone()),
                        move |row: ItemSlot<String, String>| {
                            list_item(move || row.get())
                                .subtitle("aisle 4")
                                .checked(move || done.get())
                                .id_of(move || day_core::id!(conformance_item, row.get()))
                        },
                    )
                    .height(200.0),
                ))
            })
            .drive(|d: Drive| async move {
                d.assert_visible("conformance_item:Milk").await?;
                d.tap("toggle_done").await?;
                d.assert_visible("conformance_item:Bread").await
            })
    }

    /// A list realizes a native cell for each row, showing the row's content.
    #[day_macros::test(day_core)]
    fn list_rows_realize() -> Case {
        Case::new()
            .proves_duty("attach_list")
            .proves_duty("adopt")
            .proves(kinds::LIST)
            .proves(kinds::LIST_CELL)
            .page(|| {
                names_list(names(&["Alpha", "Beta", "Gamma"]))
                    .id(day_core::id!(list))
                    .height(200.0)
            })
            .drive(|d: Drive| async move {
                d.assert_text("conformance_row:Alpha", "Alpha").await?;
                d.assert_text("conformance_row:Gamma", "Gamma").await
            })
    }

    /// A row added to the source appears in the native list; one removed goes away.
    #[day_macros::test(day_core)]
    fn list_follows_source() -> Case {
        Case::new()
            .proves_duty("release")
            .proves(kinds::LIST)
            .page(|| {
                let rows = names(&["Alpha", "Beta"]);
                column((
                    button("Add")
                        .action(move || rows.update(|v| v.push("Delta".into())))
                        .id(day_core::id!(add)),
                    button("Drop")
                        .action(move || rows.update(|v| v.retain(|n| n != "Alpha")))
                        .id(day_core::id!(drop)),
                    names_list(rows).id(day_core::id!(list)).height(200.0),
                ))
            })
            .drive(|d: Drive| async move {
                d.assert_missing("conformance_row:Delta").await?;
                d.tap("add").await?;
                d.assert_text("conformance_row:Delta", "Delta").await?;
                d.tap("drop").await?;
                d.assert_missing("conformance_row:Alpha").await?;
                d.assert_text("conformance_row:Beta", "Beta").await
            })
    }

    /// Synthetic fixture: appending and scrolling in one event must apply the native insert
    /// before scrolling. UIKit used to scroll against its old count and throw an exception.
    #[day_macros::test(day_core)]
    fn list_append_then_scroll() -> Case {
        Case::new()
            .proves(kinds::LIST)
            .page(|| {
                let rows = names(&[]);
                let scroll = Signal::new(None);
                column((
                    button("Append").id(day_core::id!(append)).action(move || {
                        rows.update(|rows| rows.push(format!("Item {}", rows.len())));
                        scroll.set(Some(rows.with(|rows| rows.len() - 1)));
                    }),
                    names_list(rows)
                        .scroll_to_row(scroll)
                        .id(day_core::id!(list))
                        .height(120.0),
                ))
            })
            .drive(|d: Drive| async move {
                // Start empty, then grow past the viewport to prove the scroll actually runs.
                for index in 0..8 {
                    d.tap("append").await?;
                    d.assert_visible(&format!("conformance_row:Item%20{index}"))
                        .await?;
                }
                Ok(())
            })
    }

    /// The rows of the self-sizing fixture, in order: key, font, text.
    const SIZED: [(&str, Font, &str); 5] = [
        ("small", Font::Caption2, "Small print"),
        ("large", Font::LargeTitle, "Large"),
        ("body", Font::Body, "Body text"),
        (
            "wrap",
            Font::Footnote,
            "A footnote long enough to wrap onto three lines or more in a narrow list, \
             whatever the platform's type scale, so its row is several lines tall",
        ),
        ("end", Font::Body, "End"),
    ];

    /// The text the `body` row grows to: several lines at any platform's type scale.
    const GROWN: &str = "Body text that grew long enough to wrap onto several lines, \
        the way a row does when its content changes after it was first sized";

    /// A self-sizing list of [`SIZED`] rows, each a bare label with the id `sized:<key>`, so
    /// the label's frame is the row's whole height. `grown` swaps the `body` row's text.
    fn sized_list(grown: Signal<bool>) -> List<Items<&'static str, &'static str>> {
        list(
            items(|| SIZED.iter().map(|r| r.0).collect(), |k: &&str| *k),
            move |slot: ItemSlot<&'static str, &'static str>| {
                // A label's font is fixed at build, and cells recycle: one arm per font, only
                // the slot's own one built.
                let arm = |key: &'static str, font: Font, text: &'static str| {
                    when(
                        move || slot.get() == key,
                        move || {
                            label(move || {
                                if key == "body" && grown.get() {
                                    GROWN.to_string()
                                } else {
                                    text.to_string()
                                }
                            })
                            .font(font)
                            .id_of(move || day_core::id!(sized, slot.get()))
                        },
                    )
                };
                let [a, b, c, d, e] = SIZED;
                column((
                    arm(a.0, a.1, a.2),
                    arm(b.0, b.1, b.2),
                    arm(c.0, c.1, c.2),
                    arm(d.0, d.1, d.2),
                    arm(e.0, e.1, e.2),
                ))
                .spacing(0.0)
            },
        )
        .row_height(RowHeight::Automatic)
        .no_separators()
    }

    /// One `sized:` row as laid out: its label's Day height, the height Day gave the row around
    /// it, and the row's native top, in window points.
    struct SizedRow {
        key: &'static str,
        content: f64,
        row: f64,
        top: f64,
    }

    /// Every `sized:` row, in row order.
    ///
    /// The row's height is its cell anchor's Day frame, not the label's: Day lays a row inside
    /// the platform's margins and holds it at the platform's minimum height (docs/list.md "Row
    /// metrics"), so a caption row is taller than its text by more than a large-title row is.
    fn sized_rows() -> Result<Vec<SizedRow>, Fail> {
        day_core::try_with_tree(|t| {
            SIZED
                .iter()
                .map(|(key, ..)| {
                    let id = format!("sized:{key}");
                    let node = t
                        .find_by_id(&id)
                        .ok_or_else(|| Fail(format!("no element {id:?}")))?;
                    let content = t
                        .node_frame(node)
                        .ok_or_else(|| Fail(format!("{id:?} has no Day frame")))?;
                    let mut anchor = node;
                    while t.node_kind(anchor) != Some(kinds::LIST_CELL) {
                        anchor = t
                            .parent_of(anchor)
                            .ok_or_else(|| Fail(format!("{id:?} is not inside a list cell")))?;
                    }
                    let row = t
                        .node_frame(anchor)
                        .ok_or_else(|| Fail(format!("{id:?}'s row has no Day frame")))?;
                    let native = t
                        .read_native(node)
                        .and_then(|n| n.frame)
                        .ok_or_else(|| Fail(format!("{id:?} has no native frame")))?;
                    Ok(SizedRow {
                        key,
                        content: content.size.height,
                        row: row.size.height,
                        top: native.origin.y,
                    })
                })
                .collect()
        })
        .unwrap_or_else(|| Err(Fail("the tree is busy".into())))
    }

    /// Every row is as tall as Day laid it: the next row's content starts one row height below
    /// this one's, give or take a chrome allowance (a GTK row's theme padding) that every row
    /// shares. A row the platform held at a fixed height either clips its content (the next row
    /// starts too soon) or leaves a gap that differs from row to row.
    ///
    /// Measured content top to content top, and Day centers content in a row taller than it,
    /// so each pitch also carries half the difference between the two rows' spare height.
    fn rows_fit() -> Result<Vec<(&'static str, f64)>, Fail> {
        let rows = sized_rows()?;
        let spare = |r: &SizedRow| (r.row - r.content) / 2.0;
        let expected = |a: &SizedRow, b: &SizedRow| a.row - spare(a) + spare(b);
        let chrome = (rows[1].top - rows[0].top) - expected(&rows[0], &rows[1]);
        for pair in rows.windows(2) {
            let (this, next) = (&pair[0], &pair[1]);
            let pitch = next.top - this.top;
            if pitch + 0.5 < this.content {
                return Err(Fail(format!(
                    "row {:?} is {:.1} tall but the next row starts {pitch:.1} below it: the \
                     native row clips its content",
                    this.key, this.content
                )));
            }
            let want = expected(this, next) + chrome;
            if (pitch - want).abs() > 1.5 {
                return Err(Fail(format!(
                    "row {:?} holds {:.1} of content in a {:.1} row, and the next row starts \
                     {pitch:.1} below it where {want:.1} was expected (the first row's chrome \
                     allowance is {chrome:.1}): the native row did not take its content's height",
                    this.key, this.content, this.row
                )));
            }
        }
        Ok(rows.into_iter().map(|r| (r.key, r.content)).collect())
    }

    fn height_of(rows: &[(&str, f64)], key: &str) -> f64 {
        rows.iter().find(|r| r.0 == key).map_or(0.0, |r| r.1)
    }

    /// An `Automatic` list sizes each row to its content: small and large text, a wrapped
    /// paragraph, and a row whose text grows and shrinks after it was first sized.
    #[day_macros::test(day_core)]
    fn list_rows_size_to_content() -> Case {
        Case::new()
            .proves(kinds::LIST)
            .proves(kinds::LIST_CELL)
            .page(|| {
                let grown = Signal::new(false);
                column((
                    button("Grow")
                        .action(move || grown.update(|g| *g = !*g))
                        .id(day_core::id!(grow)),
                    sized_list(grown)
                        .id(day_core::id!(list))
                        .width(240.0)
                        .height(480.0),
                ))
            })
            .drive(|d: Drive| async move {
                d.assert_visible("sized:end").await?;
                d.shot("sized-rows").await?;
                let rows = rows_fit()?;
                // The fixture means what it says: the type sizes differ, and the paragraph
                // wrapped at the list's width.
                let (small, large) = (height_of(&rows, "small"), height_of(&rows, "large"));
                d.check(
                    large > small * 1.5,
                    "a large-title row is taller than a caption row",
                )?;
                let body = height_of(&rows, "body");
                d.check(
                    height_of(&rows, "wrap") > body * 1.5,
                    "the footnote wrapped",
                )?;
                // A row re-laid at a new height after it was first sized.
                d.tap("grow").await?;
                d.wait_idle().await?;
                d.pause(0.3).await?;
                d.shot("sized-rows-grown").await?;
                let grew = rows_fit()?;
                d.check(height_of(&grew, "body") > body * 1.5, "the body row grew")?;
                d.tap("grow").await?;
                d.wait_idle().await?;
                d.pause(0.3).await?;
                let shrank = rows_fit()?;
                d.check(
                    (height_of(&shrank, "body") - body).abs() < 1.0,
                    "the body row shrank back",
                )
            })
    }

    /// Selecting a row reports its key; activating one reports its key too.
    #[day_macros::test(day_core)]
    fn list_select_and_activate() -> Case {
        Case::new()
            .proves(kinds::LIST)
            .page(|| {
                let picked = Signal::new(String::new());
                let opened = Signal::new(String::new());
                column((
                    label(move || format!("picked {}", picked.get())).id(day_core::id!(picked)),
                    label(move || format!("opened {}", opened.get())).id(day_core::id!(opened)),
                    names_list(names(&["Alpha", "Beta", "Gamma"]))
                        .on_select(move |k| picked.set(k))
                        .on_activate(move |k| opened.set(k))
                        .id(day_core::id!(list))
                        .height(200.0),
                ))
            })
            .drive(|d: Drive| async move {
                d.select("list", 1).await?;
                d.assert_text("picked", "picked Beta").await?;
                d.activate("list", 2).await?;
                d.assert_text("opened", "opened Gamma").await
            })
    }

    /// A committed reorder reaches the app, which moves the row in its source.
    #[day_macros::test(day_core)]
    fn list_reorder_moves_row() -> Case {
        Case::new()
            .proves(kinds::LIST)
            .page(|| {
                let rows = names(&["Alpha", "Beta", "Gamma"]);
                column((
                    label(move || rows.get().join(",")).id(day_core::id!(order)),
                    names_list(rows)
                        .reorderable(Reorder::new(move |from, to| {
                            rows.update(|v| {
                                let item = v.remove(from);
                                v.insert(to.min(v.len()), item);
                            })
                        }))
                        .id(day_core::id!(list))
                        .height(200.0),
                ))
            })
            .drive(|d: Drive| async move {
                d.reorder("list", 0, 2).await?;
                d.assert_text("order", "Beta,Gamma,Alpha").await?;
                d.assert_text("conformance_row:Alpha", "Alpha").await
            })
    }

    /// A deleted row reaches the app, and the native list drops it.
    #[day_macros::test(day_core)]
    fn list_delete_row() -> Case {
        Case::new()
            .proves(kinds::LIST)
            .page(|| {
                let rows = names(&["Alpha", "Beta", "Gamma"]);
                column((
                    label(move || rows.get().join(",")).id(day_core::id!(order)),
                    names_list(rows)
                        .deletable(Delete::new(move |at| {
                            rows.update(|v| {
                                v.remove(at);
                            })
                        }))
                        .id(day_core::id!(list))
                        .height(200.0),
                ))
            })
            .drive(|d: Drive| async move {
                d.delete_row("list", 1).await?;
                d.assert_text("order", "Alpha,Gamma").await?;
                d.assert_missing("conformance_row:Beta").await
            })
    }

    /// A row's trailing swipe action runs its work for that row.
    #[day_macros::test(day_core)]
    fn list_swipe_action() -> Case {
        Case::new()
            .proves(kinds::LIST)
            .page(|| {
                let rows = names(&["Alpha", "Beta", "Gamma"]);
                let flagged = Signal::new(String::new());
                column((
                    label(move || format!("flagged {}", flagged.get())).id(day_core::id!(flagged)),
                    names_list(rows)
                        .swipe_trailing(move |at| {
                            let name = rows.get_untracked()[at].clone();
                            vec![swipe_action("Flag").action(move || flagged.set(name.clone()))]
                        })
                        .id(day_core::id!(list))
                        .height(200.0),
                ))
            })
            .drive(|d: Drive| async move {
                d.swipe_row("list", 2, false, 0).await?;
                d.assert_text("flagged", "flagged Gamma").await
            })
    }

    /// Scrolling a long list to a row realizes it, even where rows are recycled.
    #[day_macros::test(day_core)]
    fn list_scroll_to_row() -> Case {
        Case::new()
            .proves(kinds::LIST)
            .page(|| {
                let rows: Signal<Vec<String>> =
                    Signal::new((0..300).map(|n| format!("Row {n}")).collect());
                let jump: Signal<Option<usize>> = Signal::new(None);
                column((
                    button("Jump")
                        .action(move || jump.set(Some(250)))
                        .id(day_core::id!(jump)),
                    names_list(rows)
                        .scroll_to_row(jump)
                        .id(day_core::id!(list))
                        .height(200.0),
                ))
            })
            .drive(|d: Drive| async move {
                d.assert_missing("conformance_row:Row%20250").await?;
                d.tap("jump").await?;
                d.assert_text("conformance_row:Row%20250", "Row 250").await
            })
    }

    /// Counts the rows a list has alive: one per row built, one less per row disposed. A
    /// guard rides in each row's label closure, which the row's scope owns, so a cell the
    /// host merely pooled still counts (its row is intact and rebinds) and a cell the host
    /// discarded stops counting once `ListSource::release` disposed its row.
    struct RowAlive(std::rc::Rc<std::cell::Cell<usize>>);

    impl RowAlive {
        fn new(live: &std::rc::Rc<std::cell::Cell<usize>>) -> Self {
            live.set(live.get() + 1);
            RowAlive(live.clone())
        }
    }

    impl Drop for RowAlive {
        fn drop(&mut self) {
            self.0.set(self.0.get().saturating_sub(1));
        }
    }

    /// The most rows a five-row viewport may have alive once the host has settled: its own
    /// pool and nothing visited earlier. The pools measured: AppKit 5, Qt 21 (the viewport plus
    /// two overscans), the mock 20, Android and UIKit a few dozen, and GtkListView 205: it
    /// keeps up to 200 spare items by design (`GTK_LIST_VIEW_MAX_LIST_ITEMS`) and rebinds them.
    /// A leak grows with every row visited instead, and the cases visit many more rows than
    /// this, so the bound stays tight against it.
    const ROWS_ALIVE_BOUND: usize = 256;

    /// Distant jumps keep a bounded number of rows alive and rebind their actions.
    #[day_macros::test(day_core)]
    fn list_recycles_distant_rows() -> Case {
        let built = std::rc::Rc::new(std::cell::Cell::new(0usize));
        let live = std::rc::Rc::new(std::cell::Cell::new(0usize));
        let (count, alive) = (built.clone(), live.clone());
        Case::new()
            .proves(kinds::LIST)
            .proves_cap(Cap::ListRecycling)
            // 180 jumps, each settled by a bounded wait: 5 s on GTK, 19 s on Qt, 57 s on
            // the iOS simulator.
            .timeout(180.0)
            .requires_support("native list recycling", || {
                if day_core::capability(Cap::ListRecycling) == day_spec::Support::Native {
                    day_spec::Support::Native
                } else {
                    day_spec::Support::Unsupported
                }
            })
            .page(move || {
                count.set(0);
                alive.set(0);
                let (count, alive) = (count.clone(), alive.clone());
                let rows = Signal::new((0..4000).collect::<Vec<usize>>());
                let jump = Signal::new(None);
                let next = Signal::new(40usize);
                let pressed = Signal::new(String::new());
                column((
                    button("Far").id(day_core::id!(far)).action(move || {
                        jump.set(Some(next.get_untracked()));
                        next.update(|n| *n += 40);
                    }),
                    button("Back")
                        .id(day_core::id!(back))
                        .action(move || jump.set(Some(0))),
                    label(move || pressed.get()).id(day_core::id!(pressed)),
                    list(items(move || rows.get(), |n: &usize| *n), move |slot| {
                        count.set(count.get() + 1);
                        let guard = RowAlive::new(&alive);
                        button(move || {
                            let _ = &guard;
                            format!("Row {}", slot.get())
                        })
                        .id_of(move || day_core::id!(conformance_row, slot.key()))
                        .action(move || pressed.set(format!("Pressed {}", slot.get())))
                    })
                    .row_height(RowHeight::Uniform(32.0))
                    .scroll_to_row(jump)
                    .height(160.0),
                ))
            })
            .drive(move |d: Drive| {
                let (built, live) = (built.clone(), live.clone());
                async move {
                    d.assert_text("conformance_row:0", "Row 0").await?;
                    // Distinct regions: retaining a cell for every visited index must fail.
                    // Row 1, not row 0, is the one that must go: GtkListView keeps its
                    // focused item's widget realized wherever the view scrolls, and row 0
                    // holds the focus here (the first item at start, then every `back` tap).
                    // Ninety regions out and back: some nine hundred rows visited, so a host
                    // that keeps a row per visited cell overshoots `ROWS_ALIVE_BOUND` several
                    // times over, where every pool measured stays under it.
                    for row in (40..=3600).step_by(40) {
                        d.tap("far").await?;
                        d.assert_text(&format!("conformance_row:{row}"), &format!("Row {row}"))
                            .await?;
                        d.assert_missing("conformance_row:1").await?;
                        d.tap(&format!("conformance_row:{row}")).await?;
                        d.assert_text("pressed", &format!("Pressed {row}")).await?;
                        d.tap("back").await?;
                        d.assert_text("conformance_row:0", "Row 0").await?;
                        d.tap("conformance_row:0").await?;
                        d.assert_text("pressed", "Pressed 0").await?;
                    }
                    // Settled: a host that releases discarded cells on a later turn (a
                    // posted dealloc, a teardown held for a borrow) has had it.
                    d.wait_idle().await?;
                    d.pause(0.3).await?;
                    d.check(
                        live.get() <= ROWS_ALIVE_BOUND,
                        &format!(
                            "{} rows alive after 180 jumps of a five-row viewport ({} built): \
                             discarded cells keep their rows",
                            live.get(),
                            built.get()
                        ),
                    )
                }
            })
    }

    /// Shrinking, regrowing, reordering and jumping discard cells by every path a host has;
    /// the rows built in them go with them, and no row answers for a cell it no longer has.
    #[day_macros::test(day_core)]
    fn list_releases_discarded_rows() -> Case {
        const TOTAL: usize = 3000;
        const STRIDE: usize = 1237;
        let built = std::rc::Rc::new(std::cell::Cell::new(0usize));
        let live = std::rc::Rc::new(std::cell::Cell::new(0usize));
        let (count, alive) = (built.clone(), live.clone());
        Case::new()
            .proves(kinds::LIST)
            .proves_cap(Cap::ListRecycling)
            .timeout(90.0)
            .requires_support("native list recycling", || {
                if day_core::capability(Cap::ListRecycling) == day_spec::Support::Native {
                    day_spec::Support::Native
                } else {
                    day_spec::Support::Unsupported
                }
            })
            .page(move || {
                count.set(0);
                alive.set(0);
                let (count, alive) = (count.clone(), alive.clone());
                let rows = Signal::new((0..TOTAL).collect::<Vec<usize>>());
                let jump = Signal::new(None);
                let at = Signal::new(0usize);
                let pressed = Signal::new(String::new());
                column((
                    // A stride coprime with the count walks the whole list in a scattered
                    // order, so consecutive jumps never share a cell.
                    button("Far").id(day_core::id!(far)).action(move || {
                        let next = (at.get_untracked() + STRIDE) % TOTAL;
                        at.set(next);
                        jump.set(Some(next));
                    }),
                    // Five rows fill the viewport exactly, so after the shrink every row is on
                    // screen wherever the host clamps its scroll offset.
                    button("Shrink")
                        .id(day_core::id!(shrink))
                        .action(move || rows.set((0..5).collect())),
                    button("Regrow")
                        .id(day_core::id!(regrow))
                        .action(move || rows.set((0..TOTAL).collect())),
                    // The same rows in a new order: a reload that keeps every token.
                    button("Rotate")
                        .id(day_core::id!(rotate))
                        .action(move || rows.update(|r| r.rotate_left(7))),
                    label(move || pressed.get()).id(day_core::id!(pressed)),
                    list(items(move || rows.get(), |n: &usize| *n), move |slot| {
                        count.set(count.get() + 1);
                        let guard = RowAlive::new(&alive);
                        button(move || {
                            let _ = &guard;
                            format!("Row {}", slot.get())
                        })
                        .id_of(move || day_core::id!(conformance_row, slot.key()))
                        .action(move || pressed.set(format!("Pressed {}", slot.get())))
                    })
                    .row_height(RowHeight::Uniform(32.0))
                    .scroll_to_row(jump)
                    .height(160.0),
                ))
            })
            .drive(move |d: Drive| {
                let (built, live) = (built.clone(), live.clone());
                async move {
                    d.assert_text("conformance_row:0", "Row 0").await?;
                    let (mut at, mut rotation) = (0usize, 0usize);
                    // The key of the row at index `i` after `rotation` left-rotations.
                    let key_at = |i: usize, rotation: usize| (i + rotation) % TOTAL;
                    for _ in 0..10 {
                        // A jump lands, and the row it lands on works.
                        at = (at + STRIDE) % TOTAL;
                        d.tap("far").await?;
                        let key = key_at(at, rotation);
                        d.assert_text(&format!("conformance_row:{key}"), &format!("Row {key}"))
                            .await?;
                        d.tap(&format!("conformance_row:{key}")).await?;
                        d.assert_text("pressed", &format!("Pressed {key}")).await?;
                        // Two jumps back to back: the second one wins.
                        d.tap("far").await?;
                        d.tap("far").await?;
                        at = (at + 2 * STRIDE) % TOTAL;
                        let key = key_at(at, rotation);
                        d.assert_text(&format!("conformance_row:{key}"), &format!("Row {key}"))
                            .await?;
                        // Shrinking under the viewport discards the rows past the new end;
                        // none of them may still answer.
                        d.tap("shrink").await?;
                        d.assert_text("conformance_row:3", "Row 3").await?;
                        if key >= 5 {
                            d.assert_missing(&format!("conformance_row:{key}")).await?;
                        }
                        d.tap("regrow").await?;
                        // The same set in a new order (regrowing restored the original one),
                        // then a jump into it.
                        d.tap("rotate").await?;
                        rotation = 7;
                        at = (at + STRIDE) % TOTAL;
                        d.tap("far").await?;
                        let key = key_at(at, rotation);
                        d.assert_text(&format!("conformance_row:{key}"), &format!("Row {key}"))
                            .await?;
                    }
                    d.wait_idle().await?;
                    d.pause(0.3).await?;
                    d.check(
                        live.get() <= ROWS_ALIVE_BOUND,
                        &format!(
                            "{} rows alive after the churn ({} built): discarded cells keep \
                             their rows",
                            live.get(),
                            built.get()
                        ),
                    )
                }
            })
    }

    /// Emptying a scrolled list releases old ids; repopulating it can scroll again.
    #[day_macros::test(day_core)]
    fn list_shrink_and_regrow() -> Case {
        Case::new()
            .proves(kinds::LIST)
            .page(|| {
                let rows = Signal::new((0..300).map(|n| format!("Row {n}")).collect());
                let jump = Signal::new(None);
                column((
                    button("Jump")
                        .id(day_core::id!(jump))
                        .action(move || jump.set(Some(250))),
                    button("Clear")
                        .id(day_core::id!(clear))
                        .action(move || rows.set(Vec::new())),
                    button("Restore")
                        .id(day_core::id!(restore))
                        .action(move || {
                            rows.set(vec!["New first".into(), "New last".into()]);
                            jump.set(Some(1));
                        }),
                    names_list(rows).scroll_to_row(jump).height(160.0),
                ))
            })
            .drive(|d: Drive| async move {
                d.tap("jump").await?;
                d.assert_text("conformance_row:Row%20250", "Row 250")
                    .await?;
                d.tap("clear").await?;
                d.assert_missing("conformance_row:Row%20250").await?;
                d.tap("restore").await?;
                d.assert_text("conformance_row:New%20first", "New first")
                    .await?;
                d.assert_text("conformance_row:New%20last", "New last")
                    .await
            })
    }

    type Node = (String, Option<String>);

    /// A tree over `(name, parent)` rows, each row a label with the id `row:<name>`; the tree's
    /// own row ids are the names, which `expand` and `tree_move` address.
    fn names_tree(rows: Signal<Vec<Node>>) -> TreePiece<Branches<Node, String>> {
        tree(
            branches(
                move || rows.get(),
                |n: &Node| n.0.clone(),
                |n: &Node| n.1.clone(),
            ),
            |row: ItemSlot<Node, String>| {
                label(move || row.get().0)
                    .id_of(move || day_core::id!(conformance_row, row.get().0))
                    .padding(Insets::symmetric(8.0, 4.0))
            },
        )
        .row_height(RowHeight::Uniform(28.0))
        .row_id(|k: &String| day_core::id!(tree_row, k))
    }

    fn fruit() -> Signal<Vec<Node>> {
        let n = |name: &str, parent: Option<&str>| (name.to_string(), parent.map(str::to_owned));
        Signal::new(vec![
            n("Fruit", None),
            n("Apple", Some("Fruit")),
            n("Pear", Some("Fruit")),
            n("Nuts", None),
        ])
    }

    /// A tree shows its root rows, and disclosing a row shows its children.
    #[day_macros::test(day_core)]
    fn tree_rows_disclose() -> Case {
        Case::new()
            .proves_duty("attach_tree")
            .proves_cap(Cap::Tree)
            .proves(kinds::TREE)
            .requires(Cap::Tree)
            .page(|| names_tree(fruit()).id(day_core::id!(tree)).height(240.0))
            .drive(|d: Drive| async move {
                d.assert_text("conformance_row:Fruit", "Fruit").await?;
                d.assert_text("conformance_row:Nuts", "Nuts").await?;
                d.assert_missing("conformance_row:Apple").await?;
                d.expand("tree", "tree_row:Fruit", true).await?;
                d.assert_text("conformance_row:Apple", "Apple").await?;
                d.expand("tree", "tree_row:Fruit", false).await?;
                d.assert_missing("conformance_row:Apple").await
            })
    }

    /// The expanded set is app state: rows it names start disclosed.
    #[day_macros::test(day_core)]
    fn tree_expanded_signal() -> Case {
        Case::new()
            .proves(kinds::TREE)
            .requires(Cap::Tree)
            .page(|| {
                let open = Signal::new(std::collections::HashSet::from(["Fruit".to_string()]));
                names_tree(fruit())
                    .expanded(open)
                    .id(day_core::id!(tree))
                    .height(240.0)
            })
            .drive(|d: Drive| async move { d.assert_text("conformance_row:Pear", "Pear").await })
    }

    /// Synthetic fixture strings. Restoration has no callback echo; filtering preserves
    /// key-based state. This case runs on native and composed section implementations.
    #[day_macros::test(day_core)]
    fn tree_section_expansion_contract() -> Case {
        Case::new()
            .proves_duty("attach_tree")
            .proves_cap(Cap::TreeSections)
            .proves(kinds::TREE)
            .requires(Cap::TreeSections)
            .page(|| {
                let rows = fruit();
                let open = Signal::new(std::collections::HashSet::from(["Fruit".to_owned()]));
                let changes = Signal::new(0usize);
                column((
                    label(move || {
                        format!("{}:{}", open.with(|s| s.contains("Fruit")), changes.get())
                    })
                    .id(day_core::id!(state)),
                    button("restore")
                        .id(day_core::id!(restore))
                        .action(move || {
                            open.set(std::collections::HashSet::from(["Fruit".to_owned()]))
                        }),
                    button("filter")
                        .id(day_core::id!(filter))
                        .action(move || rows.update(|r| r.retain(|n| n.0 != "Apple"))),
                    names_tree(rows)
                        .section_headers()
                        .expanded(open)
                        .on_expansion(move |_, _| changes.update(|n| *n += 1))
                        .id(day_core::id!(tree))
                        .height(240.0),
                ))
            })
            .drive(|d: Drive| async move {
                d.assert_text("state", "true:0").await?;
                d.assert_text("conformance_row:Apple", "Apple").await?;
                d.expand("tree", "tree_row:Fruit", false).await?;
                d.assert_text("state", "false:1").await?;
                d.assert_missing("conformance_row:Apple").await?;
                d.expand("tree", "tree_row:Fruit", false).await?;
                d.assert_text("state", "false:1").await?;
                d.tap("filter").await?;
                d.assert_missing("conformance_row:Pear").await?;
                d.tap("restore").await?;
                d.assert_text("conformance_row:Pear", "Pear").await?;
                d.assert_text("state", "true:1").await
            })
    }

    /// A committed move reaches the app, which re-parents the row in its source.
    #[day_macros::test(day_core)]
    fn tree_move_reparents() -> Case {
        Case::new()
            .proves_cap(Cap::TreeMove)
            .proves(kinds::TREE)
            .requires(Cap::Tree)
            .page(|| {
                let rows = fruit();
                let open = Signal::new(std::collections::HashSet::from([
                    "Fruit".to_string(),
                    "Nuts".to_string(),
                ]));
                column((
                    label(move || {
                        rows.get()
                            .iter()
                            .map(|(n, p)| format!("{n}<{}", p.clone().unwrap_or_default()))
                            .collect::<Vec<_>>()
                            .join(",")
                    })
                    .id(day_core::id!(shape)),
                    // "Nuts" has no children, so it takes a dropped row only as a declared folder.
                    names_tree(rows)
                        .expanded(open)
                        .expandable(|k: &String| k == "Fruit" || k == "Nuts")
                        .movable(Move::new(move |key, parent, _at| {
                            rows.update(|v| {
                                if let Some(n) = v.iter_mut().find(|n| n.0 == key) {
                                    n.1 = parent;
                                }
                            })
                        }))
                        .id(day_core::id!(tree))
                        .height(240.0),
                ))
            })
            .drive(|d: Drive| async move {
                d.tree_move("tree", "tree_row:Pear", Some("tree_row:Nuts"), None)
                    .await?;
                d.assert_text("shape", "Fruit<,Apple<Fruit,Pear<Nuts,Nuts<")
                    .await?;
                d.assert_text("conformance_row:Pear", "Pear").await
            })
    }
}