day-core 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
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! The realized tree: nodes own native handles (or are layout-only), a reactive scope, and
//! layout state. One `Tree<B>` per process, installed thread-local; bindings and event
//! handlers reach it through [`with_tree`], and tree methods never run user code, so the
//! single-borrow discipline holds (§3.3, §8.3).

use std::any::Any;
use std::cell::{Cell, RefCell};
use std::collections::{HashMap, VecDeque};
use std::rc::Rc;

use day_reactive::Scope;
use day_spec::*;
use slotmap::{Key, KeyData, SlotMap, new_key_type};

use crate::layout::{Alignment, CrossAlign, Layout, PassThrough};

new_key_type! {
    /// Realized-node key. `NodeId` (the spec-boundary id) is its FFI encoding.
    pub struct RNode;
}

pub fn rnode_to_id(n: RNode) -> NodeId {
    NodeId(n.data().as_ffi())
}
pub fn id_to_rnode(id: NodeId) -> RNode {
    RNode::from(KeyData::from_ffi(id.0))
}

/// Read-only layout facts a parent may consult about a child (§7.2 ChildRef).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct Flex {
    /// Wants to fill the horizontal / vertical axis when offered space.
    pub grow_w: bool,
    pub grow_h: bool,
    /// Sized after its rigid siblings in a column, against the height they leave (a
    /// `.max_height` cap): it gives way to them on a short screen, but unlike `grow_h` it never
    /// makes the column fill what it is offered.
    pub yields_h: bool,
    /// Takes all remaining main-axis space in a stack.
    pub is_spacer: bool,
    /// Layout-transparent group (`when`/`each` anchors): stacks lay out its children inline.
    pub is_group: bool,
    /// Grid facts (docs/grid.md): consulted only by `GridLayout`; inert everywhere else.
    pub grid: GridFacts,
    /// The node is the platform's whole list row (a native `kinds::LIST_ITEM`): it sizes the
    /// row's height itself, so a list cell gives it only the side margins (docs/list.md "Row
    /// metrics").
    pub whole_row: bool,
}

/// Per-node grid facts (docs/grid.md), carried on [`Flex`]: the shipped form of the §7.2
/// ChildRef facts surface. Set at build time by `grid_row` and the `.grid_span`/`.grid_align`
/// modifiers; only `GridLayout` reads them.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct GridFacts {
    /// The node is a `grid_row` carrier: its children are that row's cells.
    pub is_row: bool,
    /// Row-only: vertical alignment override for the row's cells.
    pub row_valign: Option<CrossAlign>,
    /// Cell-only: columns spanned (0 = unset = 1).
    pub col_span: u16,
    /// Cell-only: alignment override within the cell rect.
    pub align: Option<Alignment>,
}

/// Cached last-applied props for the dayscript element index (§14.2).
#[derive(Clone, Debug, Default)]
pub struct NodeProbe {
    pub text: String,
    pub value: f64,
    pub flag: bool,
    pub selected: i64,
    /// A picker's option labels, so `text` can follow the selection through either patch:
    /// the label is what the control shows, and the index alone cannot reconstruct it.
    pub options: Vec<String>,
    pub enabled: bool,
    /// Native keyboard focus, mirrored from `Event::FocusChanged` (docs/focus.md).
    pub focused: bool,
}

pub struct NodeData<H> {
    pub kind: PieceKind,
    pub handle: Option<H>,
    pub parent: RNode,
    pub children: Vec<RNode>,
    pub layout: Rc<dyn Layout>,
    pub flex: Flex,
    pub scope: Scope,
    pub id: Option<String>,
    /// The id a recycled cell's node carried before subtree recycling parked it
    /// (docs/list.md). A pooled row must stop answering lookups while it is hidden, but its
    /// next bind may show the same row content again (a slot write of an unchanged value,
    /// which fires no reactive `id_of` and re-runs no static `.id()`), so the parked id is what
    /// `restore_subtree_ids` hands back on rebind.
    pub parked_id: Option<String>,
    /// Accumulated accessibility annotations (§13): merged from the piece default, `.a11y()`,
    /// and `.id()`. Stored so each `set_a11y` re-applies the full picture and `a11y_audit`
    /// (§14.2) can diff the native tree against Day's own expectation.
    pub a11y: day_spec::A11yProps,
    // --- layout state (§7.4) ---
    pub cache: Vec<((u64, u64), Size)>,
    /// The last `(size, first baseline)` this node answered (docs/baseline.md). One slot, not a
    /// list: a baseline is asked for at the size the row already settled on, so the query
    /// repeats at one size per pass. Invalidated with `needs_measure`, alongside `cache`.
    pub baseline_cache: Option<((u64, u64), Option<f64>)>,
    pub probe: NodeProbe,
    pub needs_measure: bool,
    /// Placement dirt reaches the root even through measure boundaries. Recycled cell
    /// subtrees are detached from the window tree, so their sweep must see this bit.
    pub needs_layout: bool,
    pub last_native_frame: Option<Rect>,
    pub is_boundary: bool,
    /// Scroll-content size reported by `ScrollLayout` (§7.6); scroll nodes only. Cached so
    /// `scroll_to_target` can compose edge targets (bottom = content minus viewport).
    pub scroll_content: Option<Size>,
    /// Node-scoped implicit animation (`.animation(anim)`, §8.4): when set, this node's property
    /// patches and frame changes animate even outside a `with_animation`. The ambient animation
    /// (`with_animation`) takes precedence when both are present.
    pub implicit_anim: Option<day_spec::AnimSpec>,
    /// A `.tweak` closure (or a per-toolkit ext modifier, which routes through it) ran against
    /// this node's handle (docs/tweaks.md). Read by `set_node_selectable`: a backing swap would
    /// discard that work, which warrants a loud warning rather than silent loss.
    pub tweaked: bool,
}

/// An event handler registered on a realized node.
pub type EventHandler = Rc<dyn Fn(&Event)>;

/// The recording/telemetry observer installed via [`set_event_observer`] (§14.6): called with
/// every dispatched `(NodeId, Event)`, in queue order, before the app receives it.
pub type EventObserver = dyn Fn(NodeId, &Event);

/// `TreeOps::open_window_root`'s answer: the tree-level face of
/// [`day_spec::WindowOpenReply`], carrying the adopted (or parked) root node.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum WindowRootReply {
    /// The native window exists; `root` is its adopted boundary root, laid out already.
    Open(RNode),
    /// Native creation is in flight; `root` is parked, with no handle and no layout, until
    /// `TreeOps::adopt_window_root` completes it.
    Pending(RNode),
    /// The toolkit cannot open windows; fall back to the cover tier.
    Unsupported,
}

/// One realized window: an adopted boundary root plus the content size it lays out at.
///
/// `windows[0]` starts as the app's first window (the `ready` root container) and later entries
/// are opened through `open_window_root` (docs/windows.md), but the first slot is not
/// privileged: it can close like any other, after which `windows[0]` is the oldest
/// window still open, which is what `root()` then answers. The list is never emptied; see
/// `remove_window_root`.
struct WindowEntry {
    root: RNode,
    size: Size,
}

/// A node's context menu as the app gave it: fixed items, or a provider asked per summon.
#[derive(Clone)]
enum ContextMenuModel {
    Items(Vec<day_spec::MenuItem>),
    Provider(day_spec::ContextMenuFn),
}

pub struct Tree<B: Toolkit> {
    mounted_id_families: std::collections::BTreeSet<String>,
    pub toolkit: B,
    nodes: SlotMap<RNode, NodeData<B::Handle>>,
    windows: Vec<WindowEntry>,
    layout_dirty: bool,
    handlers: HashMap<RNode, Vec<EventHandler>>,
    /// The gesture kinds each node asked the toolkit for (`enable_gesture`): where a gesture
    /// addressed to a descendant is redirected (see `dispatch_to_node`).
    gestures: HashMap<RNode, Vec<day_spec::GestureKind>>,
    /// A decorated piece's own node, mapped to the outermost node its modifiers wrapped it in
    /// (`set_element_outer`): how far a gesture addressed to that node may climb.
    element_outer: HashMap<RNode, RNode>,
    // (kind, handle): the kind rides along so the drain can offer a satellite piece its
    // `release` hook before the backend frees the handle (§15.2).
    release_queue: Vec<(day_spec::PieceKind, B::Handle)>,
    /// Recycling-list state keyed by list node (docs/list.md, §10).
    lists: HashMap<RNode, crate::list::ListState>,
    trees: HashMap<RNode, crate::tree_driver::TreeState>,
    /// Each node's context menu as the app gave it, keyed by the node the modifier named (and
    /// the native root it landed on, where that differs): what the dayscript `context_menu`
    /// step reads, since the toolkit keeps its own copy in native form.
    context_menus: HashMap<RNode, ContextMenuModel>,
    /// Count of nodes carrying an implicit `.animation` (§8.4). Gates the `resolve_anim` ancestor
    /// walk: zero ⇒ non-`with_animation` patches skip it entirely (the common, O(1) path).
    implicit_anim_count: usize,
}

impl<B: Toolkit> Tree<B> {
    /// Drop the element ids of `anchor`'s whole subtree: the recycle write shared by tree
    /// and list cells (a pooled cell keeps its nodes; only the dayscript identity must go).
    /// Park every id under `anchor` so the (pooled, hidden) cell stops answering lookups. The
    /// ids are kept, not dropped: `restore_subtree_ids` brings them back on the next bind.
    fn clear_subtree_ids(&mut self, anchor: RNode) {
        let mut stack = vec![anchor];
        while let Some(n) = stack.pop() {
            if let Some(d) = self.nodes.get_mut(n) {
                if let Some(id) = d.id.take() {
                    d.parked_id = Some(id);
                }
                stack.extend(d.children.iter().copied());
            }
        }
    }

    /// The inverse of `clear_subtree_ids`, run when a pooled cell is bound again: every node
    /// that still has no id takes its parked one back. A node whose reactive `id_of` already
    /// re-fired keeps the fresh id, and the parked copy is dropped either way.
    fn restore_subtree_ids(&mut self, anchor: RNode) {
        let mut stack = vec![anchor];
        while let Some(n) = stack.pop() {
            if let Some(d) = self.nodes.get_mut(n) {
                if let Some(id) = d.parked_id.take()
                    && d.id.is_none()
                {
                    d.id = Some(id);
                }
                stack.extend(d.children.iter().copied());
            }
        }
    }

    pub fn new(toolkit: B, root_handle: B::Handle, window_size: Size) -> Self {
        let mut nodes = SlotMap::with_key();
        let root = nodes.insert(NodeData {
            kind: kinds::CONTAINER,
            handle: Some(root_handle),
            parent: RNode::null(),
            children: Vec::new(),
            layout: Rc::new(PassThrough),
            flex: Flex::default(),
            scope: Scope::root(),
            id: None,
            parked_id: None,
            a11y: Default::default(),
            cache: Vec::new(),
            baseline_cache: None,
            probe: NodeProbe::default(),
            needs_measure: true,
            needs_layout: true,
            last_native_frame: None,
            scroll_content: None,
            implicit_anim: None,
            tweaked: false,
            is_boundary: true,
        });
        Tree {
            mounted_id_families: Default::default(),
            toolkit,
            nodes,
            windows: vec![WindowEntry {
                root,
                size: window_size,
            }],
            layout_dirty: true,
            handlers: HashMap::new(),
            gestures: HashMap::new(),
            element_outer: HashMap::new(),
            release_queue: Vec::new(),
            lists: HashMap::new(),
            trees: HashMap::new(),
            context_menus: HashMap::new(),
            implicit_anim_count: 0,
        }
    }

    /// Create a node whose native handle is a foreign cell adopted from a recycling list host:
    /// the same "wrap an externally-owned handle" trick the window root uses (docs/list.md).
    pub(crate) fn create_cell_anchor(
        &mut self,
        handle: B::Handle,
        scope: Scope,
        layout: Rc<dyn Layout>,
    ) -> RNode {
        self.nodes.insert(NodeData {
            kind: kinds::LIST_CELL,
            handle: Some(handle),
            parent: RNode::null(),
            children: Vec::new(),
            layout,
            flex: Flex::default(),
            scope,
            id: None,
            parked_id: None,
            a11y: Default::default(),
            cache: Vec::new(),
            baseline_cache: None,
            probe: NodeProbe::default(),
            needs_measure: true,
            needs_layout: true,
            last_native_frame: None,
            scroll_content: None,
            implicit_anim: None,
            tweaked: false,
            is_boundary: true,
        })
    }

    pub fn root(&self) -> RNode {
        self.windows[0].root
    }

    pub(crate) fn node(&self, n: RNode) -> Option<&NodeData<B::Handle>> {
        self.nodes.get(n)
    }
    pub(crate) fn node_mut(&mut self, n: RNode) -> Option<&mut NodeData<B::Handle>> {
        self.nodes.get_mut(n)
    }

    /// The animation intent for a change to `node` (§8.4): the ambient `with_animation` if one is
    /// in scope, else the nearest `.animation` on `node` or an ancestor (SwiftUI-style
    /// propagation). `None` ⇒ the change applies instantly. The ancestor walk is skipped entirely
    /// when no implicit animations exist anywhere (`implicit_anim_count == 0`).
    pub(crate) fn resolve_anim(&self, node: RNode) -> Option<day_spec::AnimSpec> {
        // Reduced motion (the user's setting, or a scripted run's fast mode): every property
        // and frame animation lands at its destination (docs/accessibility.md).
        if crate::reduce_motion_now() {
            return None;
        }
        if let Some(a) = crate::anim::current_anim() {
            return Some(a);
        }
        if self.implicit_anim_count == 0 {
            return None;
        }
        let mut cur = node;
        loop {
            let n = self.nodes.get(cur)?;
            if n.implicit_anim.is_some() {
                return n.implicit_anim;
            }
            if n.parent == cur {
                return None;
            }
            cur = n.parent;
        }
    }

    /// Nearest ancestor (or self) with a native handle.
    fn native_ancestor(&self, mut n: RNode) -> RNode {
        loop {
            let Some(node) = self.nodes.get(n) else {
                // Stale node: fall back to the primary window's root (harmless, since the
                // caller is about to no-op against it).
                return self.windows[0].root;
            };
            if node.handle.is_some() {
                return n;
            }
            n = node.parent;
        }
    }

    /// In-order native descendants of `container` (its native children, not descending into them).
    fn native_descendants(&self, container: RNode, out: &mut Vec<RNode>) {
        let Some(node) = self.nodes.get(container) else {
            return;
        };
        for &c in &node.children {
            match self.nodes.get(c) {
                Some(cd) if cd.handle.is_some() => out.push(c),
                Some(_) => self.native_descendants(c, out),
                None => {}
            }
        }
    }

    /// Index that `child`'s first native node occupies (or will occupy) among `ancestor`'s
    /// native children: an in-order walk counting native roots before reaching `child`'s subtree.
    fn native_index_for(&self, ancestor: RNode, target: RNode) -> usize {
        fn walk<B: Toolkit>(tree: &Tree<B>, n: RNode, target: RNode, count: &mut usize) -> bool {
            if n == target {
                return true;
            }
            let Some(node) = tree.nodes.get(n) else {
                return false;
            };
            if node.handle.is_some() && n != target {
                // A native node counts as one slot; do not descend (its children are inside it).
                *count += 1;
                return false;
            }
            for &c in &node.children {
                if walk(tree, c, target, count) {
                    return true;
                }
            }
            false
        }
        let mut count = 0;
        let Some(anc) = self.nodes.get(ancestor) else {
            return 0;
        };
        for &c in &anc.children {
            if c == target || self.subtree_contains(c, target) {
                // Count native roots in this subtree before target.
                let mut cnt = count;
                walk(self, c, target, &mut cnt);
                return cnt;
            }
            let mut roots = Vec::new();
            match self.nodes.get(c) {
                Some(cd) if cd.handle.is_some() => count += 1,
                Some(_) => {
                    self.native_descendants(c, &mut roots);
                    count += roots.len();
                }
                None => {}
            }
        }
        count
    }

    fn subtree_contains(&self, root: RNode, target: RNode) -> bool {
        if root == target {
            return true;
        }
        let Some(node) = self.nodes.get(root) else {
            return false;
        };
        node.children
            .iter()
            .any(|&c| self.subtree_contains(c, target))
    }

    /// Attach `child` under `parent` at child-list `index`, wiring native insertion.
    fn attach_impl(&mut self, parent: RNode, child: RNode, index: usize) {
        {
            let p = self
                .nodes
                .get_mut(parent)
                .expect("attach to missing parent");
            let idx = index.min(p.children.len());
            p.children.insert(idx, child);
        }
        self.nodes
            .get_mut(child)
            .expect("attach missing child")
            .parent = parent;
        // Native wiring: every native root inside `child`'s subtree inserts under the nearest
        // native ancestor at its in-order position.
        let ancestor = self.native_ancestor(parent);
        let anc_handle = self.nodes[ancestor]
            .handle
            .clone()
            .expect("native ancestor");
        let mut roots = Vec::new();
        match self.nodes.get(child) {
            Some(cd) if cd.handle.is_some() => roots.push(child),
            Some(_) => self.native_descendants(child, &mut roots),
            None => {}
        }
        for r in roots {
            let idx = self.native_index_for(ancestor, r);
            let h = self.nodes[r].handle.clone().unwrap();
            self.toolkit.insert(&anc_handle, &h, idx);
        }
        self.mark_needs_measure_impl(parent);
    }

    fn remove_subtree_impl(&mut self, node: RNode) {
        // Detach native roots from their native ancestor, queue every handle for release,
        // drop handler entries, then remove the node records.
        let parent = self
            .nodes
            .get(node)
            .map(|n| n.parent)
            .unwrap_or(RNode::null());
        if let Some(p) = self.nodes.get_mut(parent) {
            p.children.retain(|&c| c != node);
        }
        // A realized node may be owned outside a window (for example an audio session).
        // It has no native parent until inserted. native_ancestor(null) falls back to the
        // primary root, which must not receive a remove for a widget it never contained.
        let anc_handle = if parent.is_null() {
            None
        } else {
            let ancestor = self.native_ancestor(parent);
            self.nodes.get(ancestor).and_then(|n| n.handle.clone())
        };
        let mut roots = Vec::new();
        match self.nodes.get(node) {
            Some(nd) if nd.handle.is_some() => roots.push(node),
            Some(_) => self.native_descendants(node, &mut roots),
            None => {}
        }
        if let Some(anc_handle) = anc_handle {
            for r in &roots {
                let h = self.nodes[*r].handle.clone().unwrap();
                self.toolkit.remove(&anc_handle, &h);
            }
        }
        self.collect_and_release(node);
        if parent.is_null() {
            self.layout_dirty = true;
        } else {
            self.mark_needs_measure_impl(parent);
        }
    }

    /// Remove `start` and its whole day subtree from the node table: dispose list-cell
    /// scopes, drop handler entries, queue every handle for release, decrement the
    /// implicit-animation count. Shared by [`Self::remove_subtree_impl`] and
    /// `remove_window_root` so the bookkeeping cannot drift between them.
    fn collect_and_release(&mut self, start: RNode) {
        let mut stack = vec![start];
        while let Some(n) = stack.pop() {
            // A list node's per-cell row subtrees live in scopes owned by the list machinery
            // (not the node tree): dispose them with the node, or their bindings (e.g. a
            // localized row label) outlive the list and patch freed native cells on the
            // next locale/theme change (a use-after-free on raw-pointer backends like Qt).
            self.context_menus.remove(&n);
            if let Some(list) = self.lists.remove(&n) {
                for (_, cell) in list.cells {
                    cell.scope.dispose();
                    // The cell's day subtree lives outside the node tree (anchored to a
                    // native cell, not a list child): remove it with the list, or its nodes
                    // linger as zombies: stale element ids that hijack `find_by_id`, and
                    // handlers whose captured signals are disposed so every press no-ops.
                    stack.push(cell.anchor);
                }
            }
            // Tree cells follow the identical rule (docs/tree.md).
            if let Some(tree) = self.trees.remove(&n) {
                for (_, cell) in tree.cells {
                    cell.scope.dispose();
                    stack.push(cell.anchor);
                }
            }
            let Some(data) = self.nodes.remove(n) else {
                continue;
            };
            self.handlers.remove(&n);
            self.gestures.remove(&n);
            self.element_outer.remove(&n);
            if data.implicit_anim.is_some() {
                self.implicit_anim_count = self.implicit_anim_count.saturating_sub(1);
            }
            if let Some(h) = data.handle {
                // …but a cell anchor's handle is not day's to free: it is the native list host's
                // cell, borrowed through `adopt` (§15.3), and the host frees its cell pool
                // when the host is released. Queuing it here deletes it a second time: heap
                // corruption on the raw-pointer backends (xaml/qt). Dropping the handle still
                // balances whatever `adopt` retained (AppKit/UIKit/GTK/Android refcounts).
                if data.kind != kinds::LIST_CELL {
                    self.release_queue.push((data.kind, h));
                }
            }
            stack.extend(data.children);
        }
    }

    fn mark_needs_measure_impl(&mut self, node: RNode) {
        let mut cur = node;
        let mut measure = true;
        while let Some(n) = self.nodes.get_mut(cur) {
            n.needs_layout = true;
            if measure {
                n.needs_measure = true;
                n.cache.clear();
            }
            if n.is_boundary {
                measure = false;
            }
            if n.parent.is_null() {
                break;
            }
            cur = n.parent;
        }
        self.layout_dirty = true;
    }

    /// Forget every cached measurement under `node`, `node` included. The opposite walk from
    /// [`Self::mark_needs_measure_impl`]: a cell re-laid at a new width (`list_layout_cell_width`,
    /// `tree_layout_cell_width`) has to measure its whole row afresh, or a `grow` child keeps the
    /// size it was given at the old width, is placed at that width again, and its own children
    /// stay put; a trailing control then sits past the row's new edge.
    fn invalidate_subtree(&mut self, node: RNode) {
        let mut stack = vec![node];
        while let Some(cur) = stack.pop() {
            if let Some(n) = self.nodes.get_mut(cur) {
                n.needs_measure = true;
                n.cache.clear();
                stack.extend(n.children.iter().copied());
            }
        }
    }

    /// Lay the list cell `key`'s row out at `width` × its `RowHeight`: the one place a list row
    /// is placed, shared by the first-approximation pass (`list_layout_cell`) and the backend's
    /// correction (`list_layout_cell_width`).
    fn layout_list_cell_at(&mut self, node: RNode, key: usize, width: f64) {
        let Some(state) = self.lists.get(&node) else {
            return;
        };
        let (anchor, stale, header) = match state.cells.get(&key) {
            Some(b) if b.active => (b.anchor, b.laid_width != Some(width), b.header),
            _ => return,
        };
        // A section header sizes to its content in every list: a `Uniform` pitch is the
        // items' (docs/list.md "Sections").
        let row_height = if header {
            day_spec::props::RowHeight::Automatic
        } else {
            state.driver.row_height
        };
        // A new width: nothing measured at the old one may survive, or a `grow` child keeps it.
        // The same width again (the dirty-cell sweep re-lays every bound cell on every pass)
        // keeps the row's measurement cache; re-measuring every row's text each pass is what
        // made a 500-row list's binds take whole seconds (the sweep runs once per bind).
        if stale {
            self.invalidate_subtree(anchor);
            if let Some(b) = self
                .lists
                .get_mut(&node)
                .and_then(|s| s.cells.get_mut(&key))
            {
                b.laid_width = Some(width);
            }
        }
        let height = match row_height {
            day_spec::props::RowHeight::Uniform(h) => h,
            day_spec::props::RowHeight::Automatic => {
                crate::layout::measure_node(self, anchor, Proposal::new(Some(width), None)).height
            }
        };
        let previous = self
            .lists
            .get_mut(&node)
            .and_then(|s| s.cells.get_mut(&key))
            .and_then(|b| b.laid_height.replace(height));
        // A self-sizing row the host already sized has a new height: say so, or the native row
        // keeps the old one and its content clips or leaves a gap. The first layout needs no
        // patch: the host reads `cell_height` right after `bind_row` returns.
        if previous.is_some_and(|p| (p - height).abs() > 0.25)
            && let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone())
        {
            self.toolkit.update(
                &handle,
                kinds::LIST,
                &day_spec::props::ListPatch::RowSizeInvalidated { cell: key, height } as &dyn Any,
                None,
            );
        }
        crate::layout::place_node(
            self,
            anchor,
            Rect::new(0.0, 0.0, width, height),
            Point::ZERO,
            true,
        );
        // Placed: the dirty-cell sweep need not lay this row again until something in it
        // changes; placement dirt reaches this anchor even through a nested measure boundary.
        // Left set, the sweep re-laid every bound cell of every list on every layout pass.
        self.nodes[anchor].needs_measure = false;
    }

    /// The tree twin of [`Self::layout_list_cell_at`]: lay tree cell `key`'s row out at `width`
    /// × its `RowHeight`, keeping the row's measurement cache unless the width changed.
    fn layout_tree_cell_at(&mut self, node: RNode, key: usize, width: f64) {
        let Some(state) = self.trees.get(&node) else {
            return;
        };
        let (anchor, stale) = match state.cells.get(&key) {
            Some(b) => (b.anchor, b.laid_width != Some(width)),
            None => return,
        };
        let row_height = state.driver.row_height;
        let native_height = state.cells.get(&key).and_then(|b| b.native_height);
        if stale {
            self.invalidate_subtree(anchor);
            if let Some(b) = self
                .trees
                .get_mut(&node)
                .and_then(|s| s.cells.get_mut(&key))
            {
                b.laid_width = Some(width);
            }
        }
        let height = native_height.unwrap_or_else(|| match row_height {
            day_spec::props::RowHeight::Uniform(h) => h,
            day_spec::props::RowHeight::Automatic => {
                crate::layout::measure_node(self, anchor, Proposal::new(Some(width), None)).height
            }
        });
        if let Some(b) = self
            .trees
            .get_mut(&node)
            .and_then(|s| s.cells.get_mut(&key))
        {
            b.laid_height = Some(height);
        }
        crate::layout::place_node(
            self,
            anchor,
            Rect::new(0.0, 0.0, width, height),
            Point::ZERO,
            true,
        );
        self.nodes[anchor].needs_measure = false;
    }

    fn layout_now(&mut self) {
        // Every window lays out independently at its own size; the release queue drains
        // once, after all of them (a released handle may be referenced by no window).
        for i in 0..self.windows.len() {
            let (root, size) = (self.windows[i].root, self.windows[i].size);
            let p = Proposal::exact(size);
            crate::layout::measure_node(self, root, p);
            crate::layout::place_node(self, root, Rect::from_size(size), Point::ZERO, true);
        }
        // Bound list cells live outside the window trees: their anchors are parentless
        // boundaries, laid out at bind time, so the window pass above never reaches them.
        // Placement dirt reaches a cell's anchor even when measurement invalidation stops at
        // a nested fixed frame. Sweep the marked cells so newly inserted descendants receive
        // frames and a row label that grew mid-edit does not keep its stale frame.
        let dirty_cells: Vec<(RNode, usize)> = self
            .lists
            .iter()
            .flat_map(|(list, state)| {
                state.cells.iter().filter_map(|(key, cell)| {
                    if !cell.active {
                        return None;
                    }
                    self.nodes
                        .get(cell.anchor)
                        .filter(|n| n.needs_layout)
                        .map(|_| (*list, *key))
                })
            })
            .collect();
        let dirty_tree_cells: Vec<(RNode, usize)> = self
            .trees
            .iter()
            .flat_map(|(tree, state)| {
                state.cells.iter().filter_map(|(key, cell)| {
                    self.nodes
                        .get(cell.anchor)
                        .filter(|n| n.needs_layout)
                        .map(|_| (*tree, *key))
                })
            })
            .collect();
        for (tree, key) in dirty_tree_cells {
            self.tree_layout_cell(tree, key);
        }
        for (list, key) in dirty_cells {
            self.list_layout_cell(list, key);
        }
        let queue = std::mem::take(&mut self.release_queue);
        for (kind, h) in queue {
            // The piece's own teardown runs first, while the handle is still valid: it may read
            // the native view to unregister an observer. `release` then frees it (§15.2).
            self.toolkit.release_piece(kind, &h);
            self.toolkit.release(h);
        }
    }
}

// ---------------------------------------------------------------------------
// Object-safe tree surface for pieces / bindings / handlers
// ---------------------------------------------------------------------------

/// A programmatic scroll destination (§7.6, docs/scroll.md). Edges are axis extremes
/// (`Top`/`Bottom` vertical, `Leading`/`Trailing` horizontal, i.e. start/end in layout direction);
/// `Offset` pins the viewport origin to a content-space point (clamped by the platform);
/// `Id` reveals the element with that dayscript id inside its nearest enclosing scroll.
#[derive(Clone, Debug, PartialEq)]
pub enum ScrollTarget {
    Top,
    Bottom,
    Leading,
    Trailing,
    Offset(Point),
    Id(String),
}

pub trait TreeOps {
    // The parameter list mirrors NodeData's fields one-to-one; grouping them into a
    // params struct would just move the same list behind a constructor.
    #[allow(clippy::too_many_arguments)]
    fn create_node(
        &mut self,
        kind: PieceKind,
        props: &dyn Any,
        layout: Rc<dyn Layout>,
        flex: Flex,
        native: bool,
        is_boundary: bool,
        scope: Scope,
    ) -> RNode;
    fn attach(&mut self, parent: RNode, child: RNode);
    /// Move an existing subtree without disposing its scope or native handles.
    fn reparent(&mut self, child: RNode, parent: RNode) -> bool;
    fn native_window_tabs(&self) -> bool;
    fn native_document_tabs(&self) -> bool;
    fn group_windows(&mut self, roots: &[RNode]);
    fn window_tab_order(&self, root: RNode) -> Vec<day_spec::NodeId>;

    fn attach_at(&mut self, parent: RNode, child: RNode, index: usize);
    fn reorder_children(&mut self, parent: RNode, order: Vec<RNode>);
    fn remove_subtree(&mut self, node: RNode);
    /// Whether `node` still exists (diagnostics: stale-id probes).
    fn node_exists(&self, node: RNode) -> bool;
    /// Whether the platform renders in dark appearance (see `Toolkit::dark_mode`).
    fn dark_mode(&mut self) -> bool;
    /// Whether the user asked for less motion (see `Toolkit::reduce_motion`).
    fn reduce_motion(&mut self) -> bool;
    /// Apply an app-level appearance override (see `Toolkit::set_appearance`).
    fn set_appearance(&mut self, dark: Option<bool>);
    /// Put a badge on the app icon (see `Toolkit::set_app_badge`, docs/badge.md).
    fn set_app_badge(&mut self, badge: &day_spec::AppBadge);
    fn on_event(&mut self, node: RNode, h: EventHandler);
    fn handlers_for(&self, node: RNode) -> Vec<EventHandler>;
    /// The node itself if it has a native view, else the one a chain of single-child
    /// layout-only wrappers leads down to: the descent `enable_gesture` and `set_focusable`
    /// make, for a modifier that has to reach the view (`Decorate::on_key`'s key mark).
    fn native_view_of(&self, node: RNode) -> Option<RNode>;
    /// The layout-only wrappers directly above `node` (single child, no native view), nearest
    /// first: the same element as `node`, where an id or a modifier often sits.
    fn wrappers_above(&self, node: RNode) -> Vec<RNode>;
    /// The node a `kind` gesture addressed to `node` is delivered to: `node` itself when it
    /// enabled that gesture, else the nearest node above it, within the same element, that did
    /// (where a `.padding(..).on_tap(..)` registered its handler), else `None`. The element's
    /// nodes are those its modifiers wrapped it in (`set_element_outer`), native containers
    /// such as `.background(..)` included, plus any layout-only wrappers directly above. What
    /// makes a dayscript step by id reach the handler the way a native gesture on the inner
    /// view reaches the recognizer on its superview.
    fn gesture_target(&self, node: RNode, kind: day_spec::GestureKind) -> Option<RNode>;
    /// Record that a decorated piece's own node `inner` sits inside wrappers up to `outer`: the
    /// span one element's modifiers built, which `gesture_target` climbs. A no-op when the two
    /// are the same node.
    fn set_element_outer(&mut self, inner: RNode, outer: RNode);
    fn set_id(&mut self, node: RNode, id: String);
    /// Families attached at least once, including subsequently disposed/recycled nodes.
    fn mounted_id_families(&self) -> Vec<String>;
    /// Merge non-default grid cell facts onto a node's [`Flex`]: what the `.grid_span`/
    /// `.grid_align` modifiers call (docs/grid.md). Called at build time, before the first layout.
    fn set_grid_facts(&mut self, node: RNode, facts: GridFacts);
    /// Give a wrapper that takes its size from `inner` (an overlay host) the inner node's
    /// [`Flex::whole_row`], so a decorated platform row still reads as one to its list cell.
    fn forward_whole_row(&mut self, wrapper: RNode, inner: RNode);
    fn set_a11y(&mut self, node: RNode, a11y: A11yProps);
    /// Speak `text` through the screen reader (`Toolkit::announce`, docs/accessibility.md).
    fn announce(&mut self, text: &str, urgent: bool);
    /// Attach a native gesture recognizer to `node` (docs/shapes.md): the backend then emits
    /// `Event::Tap/LongPress/Drag` for it. The node must have a native handle.
    fn enable_gesture(&mut self, node: RNode, kind: day_spec::GestureKind);
    /// Move native keyboard focus to (or away from) `node` (docs/focus.md).
    fn focus_node(&mut self, node: RNode, focused: bool);
    /// Opt a container into the platform's focus system (docs/focus.md); what
    /// `Decorate::focusable` calls. The node must have a native view somewhere under it.
    fn set_focusable(&mut self, node: RNode, focusable: bool);
    /// Mirror a `FocusChanged` event into the node's dayscript probe (pump-only).
    fn set_probe_focused(&mut self, node: RNode, focused: bool);
    /// Record which row of a nav host is current, on the `kinds::NAV` host that `.id()` tags
    /// (docs/navigation.md). The host's `NavPatch::Select` carries a resident-page index
    /// (visit order, which only coincides with row order when every page is built up front), so
    /// the nav host reports the row index here instead. `None` = nothing selected (`-1`).
    fn set_probe_selected(&mut self, node: RNode, selected: Option<usize>);
    /// Record an external piece's current value in the node's dayscript probe, both the
    /// numeric form (`assert_value`) and its display text (`assert_text`). The core patch
    /// inspection only knows the builtin patch types, so a satellite piece (a stepper, a
    /// rating) reports its own state through this instead (docs/extending.md).
    fn set_probe_value(&mut self, node: RNode, value: f64, text: String);
    fn set_app_menu(&mut self, items: Vec<day_spec::MenuItem>);
    fn set_context_menu(&mut self, node: RNode, items: Vec<day_spec::MenuItem>);
    /// Edit `root`'s window toolbar (docs/toolbars.md). `root` is a window root: the primary
    /// root or one returned by `open_window_root`.
    /// `false` when the toolkit did not apply it (the root has no native handle yet, or the
    /// toolkit has no bar for it).
    fn edit_window_toolbar(&mut self, root: RNode, ops: Vec<day_spec::ToolbarOp>) -> bool;
    /// Apply a targeted change to one item of `root`'s toolbar; `false` as above.
    fn patch_window_toolbar(&mut self, root: RNode, patch: day_spec::ToolbarPatch) -> bool;
    /// Programmatic scroll (§7.6, docs/scroll.md): resolve `target` against a scroll node's
    /// content/viewport and drive `Toolkit::scroll_to`. Returns false when `node` isn't a
    /// realized scroll, or a supported native navigation menu with a top/bottom target
    /// (the caller reports the miss; dayscript retries).
    fn scroll_to_target(&mut self, node: RNode, target: &ScrollTarget, animated: bool) -> bool;
    /// Scroll the nearest enclosing scroll ancestor so `node`'s frame is visible (minimal
    /// scroll, `scrollRectToVisible` semantics). False when no scroll ancestor exists.
    fn scroll_reveal(&mut self, node: RNode, animated: bool) -> bool;
    fn patch(&mut self, node: RNode, patch: Box<dyn Any>, affects_size: bool);
    fn replay(&mut self, node: RNode, ops: Vec<DrawOp>);
    fn request_frame(&mut self, root: RNode, cb: day_spec::FrameCallback) -> day_spec::CancelFrame;
    /// Set (or clear) a node's implicit `.animation` (§8.4): subsequent property patches and frame
    /// changes on this node (or its descendants) animate with `anim` even outside a
    /// `with_animation`.
    fn set_implicit_anim(&mut self, node: RNode, anim: Option<day_spec::AnimSpec>);
    /// Apply an animatable opacity (0..1) to `node`'s native handle (§8.4), animating if an
    /// animation is in scope. No-op if the node has no handle.
    fn set_node_opacity(&mut self, node: RNode, opacity: f64);
    /// Apply an animatable [`Transform`] to `node`'s native handle (§8.4): the cheap movement/
    /// scaling channel that never relayouts. No-op if the node has no handle.
    fn set_node_transform(&mut self, node: RNode, t: day_spec::Transform);
    /// Make `node`'s text user-selectable (the `.selectable()` modifier). One-shot and unmanaged;
    /// No-op if the node has no handle.
    fn set_node_selectable(&mut self, node: RNode, selectable: bool);
    /// Apply a text field's [`InputTraits`](day_spec::InputTraits) (docs/textfield.md).
    /// Idempotent; called again with the whole set when a reactive member changes. No-op if
    /// the node has no handle.
    fn set_node_input_traits(&mut self, node: RNode, traits: &day_spec::InputTraits);
    /// Shape the pointer over `node` (the `.cursor()` modifier, docs/cursor.md). Idempotent;
    /// called again when a reactive cursor changes. No-op if the node has no handle.
    fn set_node_cursor(&mut self, node: RNode, cursor: day_spec::Cursor);
    /// Make `node` move its window when dragged, like a title bar (`.window_drag_region()`,
    /// docs/window-chrome.md).
    fn set_node_drag_region(&mut self, node: RNode, drag: bool);
    /// Record that a `.tweak` closure ran against `node`'s current handle (docs/tweaks.md), so
    /// a later backing swap (`set_node_selectable` on a toolkit that rebuilds the widget) can
    /// warn about the discarded work instead of losing it silently.
    fn note_node_tweaked(&mut self, node: RNode) {
        let _ = node;
    }
    fn mark_needs_measure(&mut self, node: RNode);
    fn mark_layout_dirty(&mut self);
    /// Forget every measurement Day holds and re-lay every bound list and tree row: the system
    /// text size changed ([`crate::note_text_size_changed`]), so every text measurement is
    /// stale, and a cached one would keep each label at its old size.
    fn invalidate_all_measurements(&mut self);
    fn layout_if_needed(&mut self);
    fn set_window_size(&mut self, s: Size);
    /// Report the app's current route to the backend (`Toolkit::set_route`); web-dom mirrors
    /// it into the URL hash (docs/navigation.md). Called by the turn-end route sync when the
    /// route actually changed.
    fn set_route(&mut self, route: &str);
    fn child_count(&self, node: RNode) -> usize;
    fn first_child(&self, node: RNode) -> Option<RNode>;
    /// `node`'s parent, `None` at a root: the window root, or a list cell's anchor, whose
    /// parent is the native cell rather than a Day node.
    fn parent_of(&self, node: RNode) -> Option<RNode>;
    fn node_kind(&self, node: RNode) -> Option<PieceKind>;
    /// The app-authored `.id()` string on `node` (`find_by_id`'s inverse), or `None` for an id-less
    /// or disposed node. Backs the free [`id_of`], the recorder's NodeId → id lookup (§14.6).
    fn node_id(&self, node: RNode) -> Option<String>;
    /// A clone of the node's native handle boxed as `Any` (None for layout-only or disposed
    /// nodes). TreeOps is object-safe, so the generic `Toolkit::Handle` can't appear here;
    /// toolkit ext modules downcast to their concrete Handle type. This is the tweaks door
    /// (docs/tweaks.md): cloning is cheap on every backend (a retain / gobject ref / GlobalRef
    /// clone / Copy pointer) and the clone never outlives the native widget's own refcounting.
    fn node_handle_any(&self, node: RNode) -> Option<Box<dyn Any>>;
    fn node_frame(&self, node: RNode) -> Option<Rect>;
    fn node_probe(&self, node: RNode) -> Option<NodeProbe>;
    /// The node's accumulated accessibility annotations (§13): `a11y_audit`'s expectation.
    fn node_a11y(&self, node: RNode) -> Option<A11yProps>;
    /// The node's actual native state (`a11y_audit` diffs it against `node_a11y`, and
    /// `assert_native` against the probe).
    fn read_native(&self, node: RNode) -> Option<day_spec::NativeSnapshot>;
    /// For every node with an `.id()` and a native handle: `(id, kind, expected, actual)`, the
    /// raw material for the `a11y_audit` step (§14.2). Comparison/policy lives in day-script.
    fn a11y_nodes(&self) -> Vec<(String, PieceKind, A11yProps, day_spec::NativeSnapshot)>;
    fn find_by_id(&self, id: &str) -> Option<RNode>;
    /// Show/hide the sidebar pane of the navigation host `host`: what the sidebar affordance
    /// a `nav(Sidebar)` contributes for itself drives. `false` when the toolkit has no
    /// pane to toggle there (or no sidebar concept at all). Per host, so a second window's
    /// button collapses its own sidebar (docs/toolbars.md, docs/navigation.md).
    fn toggle_sidebar(&mut self, _host: RNode) -> bool {
        false
    }
    /// Press the platform's back affordance (`Toolkit::native_back`): the native path a
    /// real tap takes, which `nav_back()` (Day's rail) never runs. `false` when nothing is
    /// popped by it.
    fn native_back(&mut self) -> bool {
        false
    }
    fn prepare_snapshot(
        &mut self,
        root: Option<RNode>,
        revision: u32,
    ) -> Result<day_spec::capture::Readiness, String>;
    fn snapshot(&mut self) -> Result<Vec<u8>, String>;
    /// Where the primary window's root sits in [`Self::snapshot`]'s image, in points (see
    /// `Toolkit::snapshot_origin`); `None` when the toolkit does not say.
    fn snapshot_origin(&mut self) -> Option<Point>;
    /// The same capture with the window's own chrome (see `Toolkit::snapshot_window_chrome`).
    fn snapshot_chrome(&mut self) -> Result<Vec<u8>, String>;

    // --- raster images (docs/images.md) -------------------------------------------------
    // Request-shaped, like `present`: the answer arrives as `Event::ImageDecoded` /
    // `Event::ImageEncoded` and resolves the waiter in `crate::image`.

    /// Decode encoded bytes into a native image under `id` (see `Toolkit::decode_image`).
    fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]);
    /// What a decoded image is (see `Toolkit::image_info`).
    fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo>;
    /// An image's metadata beyond its pixels (see `Toolkit::image_properties`).
    fn image_properties(&mut self, id: day_spec::BitmapId) -> Option<day_spec::ImageProperties>;
    /// Encode a decoded image back to bytes (see `Toolkit::encode_image`).
    fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec);
    /// Which formats this toolkit encodes (see `Toolkit::encode_formats`).
    fn image_encode_formats(&mut self) -> Vec<day_spec::ImageFormat>;
    /// Release a decoded image (see `Toolkit::release_image`).
    fn release_image(&mut self, id: day_spec::BitmapId);
    /// Render a canvas drawing into a bitmap under `id` (see `Toolkit::render_bitmap`); the
    /// answer arrives as `Event::BitmapRendered`.
    fn render_bitmap(
        &mut self,
        req: u64,
        id: day_spec::BitmapId,
        ops: &[day_spec::DrawOp],
        size: Size,
        scale: f64,
    );
    /// Render canvas drawings into a PDF (see `Toolkit::render_pdf`); the answer arrives as
    /// `Event::PdfRendered`.
    fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo);
    /// Whether the toolkit can rasterize its own window at all (`Cap::Snapshot`).
    fn window_image_support(&mut self) -> day_spec::Support;
    /// The platform's font families (see `Toolkit::font_families`); cached by day-core.
    fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo>;
    /// Measure one line of canvas text (see `Toolkit::measure_text`).
    fn measure_text(
        &mut self,
        text: &str,
        size: f64,
        font: &day_spec::CanvasFont,
    ) -> Option<day_spec::TextMetrics>;
    /// Whether native transitions have settled (see `Toolkit::ui_idle`).
    fn ui_idle(&mut self) -> bool;
    fn root_node(&self) -> RNode;

    // --- secondary windows (docs/windows.md) -------------------------------------------

    /// Open a native window and adopt its content container as an additional boundary
    /// root. Inserts the root record, asks `Toolkit::open_window`, and answers per the
    /// toolkit's reply: `Open(root)` = live now (handle installed, window entry pushed),
    /// `Pending(root)` = native creation is in flight (the record is parked without a
    /// handle until [`Self::adopt_window_root`]), `Unsupported` = the placeholder was
    /// removed again; present the content as a cover instead.
    fn open_window_root(&mut self, options: &WindowOptions, kind: WindowKind) -> WindowRootReply;
    /// Complete a `Pending` open: adopt `raw` as the window's content container, install
    /// it on the parked root, and start laying out at `size`. `false` = the root is gone
    /// (closed before completion); the caller should drop the native window again.
    fn adopt_window_root(&mut self, root: RNode, raw: day_spec::RawHandle, size: Size) -> bool;
    /// Remove an (already childless) window root: bookkeeping + handle release + window
    /// entry removal. Never the primary. Idempotent; also valid for a parked Pending root.
    fn remove_window_root(&mut self, root: RNode);
    /// A secondary window's content size changed (its `WindowResized` handler).
    fn set_root_size(&mut self, root: RNode, s: Size);

    /// Ask the toolkit to size the window whose content root is `root` to `size`
    /// (`WindowOptions::size_to_fit`). Also updates Day's own layout size for that root, so the
    /// content is re-laid at the size the window actually became.
    fn fit_window(&mut self, root: RNode, size: Size);
    /// Register an extra layout root: a node that stays attached in the tree (native
    /// re-homing needs the parent link) but lays out independently at its own reported
    /// size: the cover-fallback surface (docs/windows.md). The primary root's PassThrough
    /// layout only descends into its first child, so a second top-level surface must drive
    /// its own layout entry. `set_root_size` resizes it; drop it before subtree removal.
    fn add_extra_layout_root(&mut self, node: RNode, size: Size);
    /// Unregister an extra layout root (the entry only; the node itself is removed by the
    /// ordinary `remove_subtree`).
    fn drop_extra_layout_root(&mut self, node: RNode);
    /// Ask the platform to close the window whose root is `root` (async; the platform
    /// confirms with `Event::WindowClosed`).
    fn close_native_window(&mut self, root: RNode);
    /// End the app: the last primary window has closed (docs/windows.md close policy).
    fn quit_app(&mut self);
    /// Bring the window whose root is `root` to front and make it key.
    fn focus_native_window(&mut self, root: RNode);
    /// Retitle the window whose root is `root`.
    fn set_native_window_title(&mut self, root: RNode, title: &str);
    /// Apply a property change to the window whose root is `root` (docs/windows.md "Window
    /// properties"). Ignored for a root with no native handle yet.
    fn apply_window(&mut self, root: RNode, change: &day_spec::WindowChange);
    /// Install the app's Dock menu (docs/menus.md).
    fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]);
    /// Show the app's status items (docs/status-item.md).
    fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]);
    /// Show progress on the app's Dock or taskbar icon.
    fn set_app_progress(&mut self, progress: day_spec::AppProgress);
    /// Show or hide the macOS Dock icon.
    fn set_dock_visible(&mut self, visible: bool);
    /// Keep the process running when its last window closes (day-core decides when to quit).
    fn set_keep_running(&mut self, keep: bool);
    /// The outer frame of the window whose root is `root` (docs/windows.md).
    fn native_window_frame(&self, root: RNode) -> Option<day_spec::Rect>;
    /// The attached displays.
    fn monitors(&self) -> Vec<day_spec::Monitor>;
    /// Replace the app's run-time launcher shortcuts.
    fn set_launcher_shortcuts(&mut self, shortcuts: &[day_spec::LauncherShortcut]);
    /// Snapshot the window whose root is `root` (the primary answers `snapshot`).
    fn snapshot_of(&mut self, root: RNode) -> Result<Vec<u8>, String>;
    /// Toolkit capability probe (pieces pick presentation with it, e.g. `Cap::NavSplit`).
    fn capability(&self, cap: Cap) -> Support;
    /// Attach pull recognition to a mounted scroll view.
    fn attach_refresh(&mut self, node: RNode, host: NodeId);
    fn set_presented(&mut self, node: RNode, visible: bool);
    /// Does the running backend deliver this lifecycle phase (docs/lifecycle.md)?
    fn supports_lifecycle(&self, phase: day_spec::Lifecycle) -> bool;
    /// Present a native modal for request `req` (docs/dialogs.md).
    fn present(&mut self, req: u64, spec: &present::PresentSpec);
    /// Dismiss the modal for `req` (programmatic resolve while it is still up).
    fn dismiss(&mut self, req: u64);
    /// Open `url` in the platform's default handler (what the `link` piece calls).
    fn open_url(&mut self, url: &str);
    fn share_support(&self) -> Support;
    fn share_url(&mut self, url: &str, title: &str) -> bool;
    fn application_handlers(
        &mut self,
        query: &day_spec::applications::HandlerQuery,
    ) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError>;
    fn open_url_with_application(
        &mut self,
        url: &str,
        application: &str,
        completion: day_spec::applications::OpenApplicationCompletion,
    );

    /// Re-send the union of every mounted `defers_system_gestures` request (docs/cover.md).
    fn defer_system_gestures(&mut self, edges: day_spec::Edges);
    /// Re-send whether any mounted `status_bar_hidden` request asks to hide the status bar
    /// (docs/cover.md).
    fn set_status_bar_hidden(&mut self, hidden: bool);

    // Recycling list methods (docs/list.md, §10). Called by day-core's `ListSource` closures
    // (via `with_tree`) when the native list pulls rows; never nested inside another borrow.
    // (`len`/`token_at` read the piece's snapshot directly and don't need the tree.)
    fn install_list(&mut self, node: RNode, driver: crate::list::ListDriver);
    /// Decide whether row `key`'s cell must be built (returns a fresh anchor) or rebound.
    /// `header`: the row about to bind is a section header (docs/list.md "Sections"); a cell
    /// that held the other kind is rebuilt.
    fn list_prepare_cell(
        &mut self,
        node: RNode,
        key: usize,
        cell: RawHandle,
        header: bool,
    ) -> crate::list::CellStep;
    /// Record a freshly built row (or section header) for a cell.
    fn list_store_cell(
        &mut self,
        node: RNode,
        key: usize,
        anchor: RNode,
        built: crate::list::BuiltRow,
        header: bool,
    );
    /// Lay the row out inside its cell bounds (row content width × the RowHeight).
    fn list_layout_cell(&mut self, node: RNode, key: usize);
    /// Re-lay the row at the cell's actual width (the list's width is only the first
    /// approximation: a native row's chrome, GtkListView's themed `row` node, makes the cell
    /// narrower, and a row laid at the list's width holds the whole list wider than its frame).
    fn list_layout_cell_width(&mut self, node: RNode, key: usize, width: f64);
    /// The height the cell's row was last laid at (`ListSource::cell_height`); 0 before its
    /// first layout.
    fn list_cell_height(&self, node: RNode, key: usize) -> f64;
    /// The physical-cell keys of every bound cell of the list at `node` (for a bulk re-layout
    /// after the list's own width changed).
    /// Active cells eligible for width-change layout; excludes cells parked by `recycle`.
    fn list_cell_keys(&self, node: RNode) -> Vec<usize>;
    /// A pooled cell left the visible row set (an emulated backend hides rows past a shrunk
    /// source instead of destroying them): clear the cell subtree's element ids so stale rows
    /// stop answering dayscript lookups. The cell itself stays pooled; the next bind re-ids it.
    fn list_recycle_cell(&mut self, node: RNode, key: usize);
    /// The host discarded cell `key` of list `node` for good: dispose the row built in it.
    fn list_release_cell(&mut self, node: RNode, key: usize);
    /// Cell `key` is the host's pinned header copy (`ListSource::bind_pinned`): park its ids, now
    /// and on every rebind, so lookups find the header row in the list.
    fn list_pin_cell(&mut self, node: RNode, key: usize);
    /// Apply a data change: the native host re-queries the source.
    fn list_reload(&mut self, node: RNode);
    fn list_splice(&mut self, node: RNode, deltas: Vec<day_spec::props::RowDelta>);
    fn set_undo_state(&mut self, state: &day_spec::UndoState);
    fn set_edit_state(&mut self, state: &day_spec::EditState);
    fn modifiers(&mut self) -> day_spec::Modifiers;
    /// Imperatively scroll the native list so its last row is fully visible (no-op if empty).
    fn list_scroll_to_end(&mut self, node: RNode);
    /// Imperatively scroll the native list so row `row` is visible (clamped; no-op if empty).
    fn list_scroll_to_row(&mut self, node: RNode, row: usize);
    /// Programmatically sync the list's selected rows (empty = clear). The toolkit applies
    /// without re-emitting a selection event.
    fn list_set_selected(&mut self, node: RNode, rows: Vec<usize>);
    /// Enter or leave the list's native editing mode (`ListPatch::Editing`); a toolkit
    /// without one ignores it.
    fn list_set_editing(&mut self, node: RNode, on: bool);
    /// The list's driver, for the guard → commit path `list_try_reorder` runs outside the
    /// borrow (`None` when `node` hosts no list).
    fn list_driver(&mut self, node: RNode) -> Option<std::rc::Rc<crate::list::ListDriver>>;

    // Hierarchical tree methods (docs/tree.md): the list methods' shape, token-addressed. Called
    // by day-core's `TreeSource` closures (via `with_tree`) when the native tree pulls
    // rows; never nested inside another borrow.
    fn install_tree(&mut self, node: RNode, driver: crate::tree_driver::TreeDriver);
    /// Decide whether the cell for `key` must be built (fresh anchor) or rebound.
    fn tree_prepare_cell(
        &mut self,
        node: RNode,
        key: usize,
        cell: RawHandle,
    ) -> crate::tree_driver::TreeCellStep;
    /// Record a freshly built row for a cell.
    fn tree_store_cell(
        &mut self,
        node: RNode,
        key: usize,
        anchor: RNode,
        built: crate::tree_driver::TreeBuiltRow,
    );
    /// Lay the row out inside its cell bounds (row content width × the RowHeight).
    fn tree_layout_cell(&mut self, node: RNode, key: usize);
    /// Re-lay the row at the cell's actual width (indentation makes tree cells per-row wide).
    fn tree_layout_cell_width(&mut self, node: RNode, key: usize, width: f64);
    fn tree_layout_cell_size(&mut self, node: RNode, key: usize, size: Size);
    /// The height the cell's row was last laid at (`TreeSource::cell_height`); 0 before its
    /// first layout.
    fn tree_cell_height(&self, node: RNode, key: usize) -> f64;
    /// The cell went back to the host's reuse pool: clear the row subtree's element ids, so
    /// a collapsed-away row stops answering `find_by_id` (dayscript `assert_missing`) and a
    /// stale id can never hijack a lookup. The next bind re-sets the live row's id.
    fn tree_recycle_cell(&mut self, node: RNode, key: usize);
    /// Apply a data change: the native host re-queries the source (expansion and selection
    /// survive by token).
    fn tree_reload(&mut self, node: RNode);
    /// Programmatically disclose/collapse one row (no `TreeExpanded` echo).
    fn tree_set_expanded(&mut self, node: RNode, token: u64, expanded: bool);
    /// Programmatically sync the tree's selected rows (no selection-event echo).
    fn tree_set_selected(&mut self, node: RNode, tokens: Vec<u64>);
    /// Scroll this row into view, realizing it if needed (ancestors already expanded).
    fn tree_reveal(&mut self, node: RNode, token: u64);
    /// The tree's driver, for the guard → commit path `tree_try_move` runs outside the
    /// borrow (`None` when `node` hosts no tree).
    fn tree_driver(&mut self, node: RNode) -> Option<std::rc::Rc<crate::tree_driver::TreeDriver>>;
    /// Install native transfer behavior on a realized host.
    fn set_drag_source(&mut self, node: RNode, source: day_spec::transfer::Source);
    fn set_drop_target(&mut self, node: RNode, target: day_spec::transfer::Target);
    /// Install a summon-time context-menu provider on `node` (docs/menus.md).
    fn set_context_menu_fn(&mut self, node: RNode, f: day_spec::ContextMenuFn);
    /// The context menu the app gave `node` (or its nearest ancestor that has one), as a
    /// provider; what the dayscript `context_menu` step chooses from. Returned rather than
    /// called, because a provider is app code: it may select what it summons over and flush,
    /// which re-enters the tree, so the caller asks it once the tree borrow has ended.
    fn context_menu_of(&mut self, node: RNode) -> Option<day_spec::ContextMenuFn>;
}

impl<B: Toolkit> TreeOps for Tree<B> {
    fn set_presented(&mut self, node: RNode, visible: bool) {
        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
            self.toolkit.set_presented(&handle, visible);
        }
    }

    fn attach_refresh(&mut self, node: RNode, host: NodeId) {
        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
            self.toolkit.attach_refresh(&handle, host);
        }
    }

    fn capability(&self, cap: Cap) -> Support {
        self.toolkit.capability(cap)
    }

    fn supports_lifecycle(&self, phase: day_spec::Lifecycle) -> bool {
        self.toolkit.supports_lifecycle(phase)
    }

    fn present(&mut self, req: u64, spec: &present::PresentSpec) {
        self.toolkit.present(req, spec);
    }

    fn dismiss(&mut self, req: u64) {
        self.toolkit.dismiss(req);
    }

    fn open_url(&mut self, url: &str) {
        self.toolkit.open_url(url);
    }
    fn share_support(&self) -> Support {
        self.toolkit.share_support()
    }
    fn share_url(&mut self, url: &str, title: &str) -> bool {
        self.toolkit.share_url(url, title)
    }

    fn application_handlers(
        &mut self,
        query: &day_spec::applications::HandlerQuery,
    ) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError>
    {
        self.toolkit.application_handlers(query)
    }

    fn open_url_with_application(
        &mut self,
        url: &str,
        application: &str,
        completion: day_spec::applications::OpenApplicationCompletion,
    ) {
        self.toolkit
            .open_url_with_application(url, application, completion);
    }

    fn set_appearance(&mut self, dark: Option<bool>) {
        self.toolkit.set_appearance(dark);
    }

    fn set_app_badge(&mut self, badge: &day_spec::AppBadge) {
        self.toolkit.set_app_badge(badge);
    }

    fn defer_system_gestures(&mut self, edges: day_spec::Edges) {
        self.toolkit.defer_system_gestures(edges);
    }

    fn set_status_bar_hidden(&mut self, hidden: bool) {
        self.toolkit.set_status_bar_hidden(hidden);
    }

    fn create_node(
        &mut self,
        kind: PieceKind,
        props: &dyn Any,
        layout: Rc<dyn Layout>,
        flex: Flex,
        native: bool,
        is_boundary: bool,
        scope: Scope,
    ) -> RNode {
        let mut probe = NodeProbe {
            enabled: true,
            ..Default::default()
        };
        {
            use day_spec::props::*;
            if let Some(p) = props.downcast_ref::<LabelProps>() {
                probe.text = p.text.clone();
            } else if let Some(p) = props.downcast_ref::<NavMenuProps>() {
                probe.selected = p.selected.map(|i| i as i64).unwrap_or(-1);
                probe.value = probe.selected as f64;
            } else if let Some(p) = props.downcast_ref::<ButtonProps>() {
                probe.text = p.title.clone();
                probe.enabled = p.enabled;
                // The selected state reads like a toggle's (`assert_on`).
                probe.flag = p.selected;
            } else if let Some(p) = props.downcast_ref::<ToggleProps>() {
                probe.flag = p.on;
                probe.enabled = p.enabled;
            } else if let Some(p) = props.downcast_ref::<SliderProps>() {
                probe.value = p.value;
                probe.enabled = p.enabled;
            } else if let Some(p) = props.downcast_ref::<TextFieldProps>() {
                probe.text = p.text.clone();
                probe.enabled = p.enabled;
            } else if let Some(p) = props.downcast_ref::<ProgressProps>() {
                // `flag` marks indeterminate; `value` holds the determinate fraction.
                probe.flag = p.value.is_none();
                probe.value = p.value.unwrap_or(0.0);
            } else if let Some(p) = props.downcast_ref::<PickerProps>() {
                probe.selected = p.selected as i64;
                probe.value = p.selected as f64;
                // A picker's text is the option it shows: what `assert_text` should see
                // (the index is `assert_value`'s answer). Kept current by both patches below.
                probe.text = p.options.get(p.selected).cloned().unwrap_or_default();
                probe.options = p.options.clone();
                probe.enabled = p.enabled;
            } else if let Some(p) = props.downcast_ref::<TextAreaProps>() {
                probe.text = p.text.clone();
            }
        }
        let node = self.nodes.insert(NodeData {
            kind,
            handle: None,
            parent: RNode::null(),
            children: Vec::new(),
            layout,
            flex,
            scope,
            id: None,
            parked_id: None,
            a11y: Default::default(),
            cache: Vec::new(),
            baseline_cache: None,
            probe,
            needs_measure: true,
            needs_layout: true,
            last_native_frame: None,
            scroll_content: None,
            implicit_anim: None,
            tweaked: false,
            is_boundary,
        });
        if native {
            let h = self.toolkit.realize(kind, props, rnode_to_id(node));
            self.nodes[node].handle = Some(h);
        }
        node
    }

    fn attach(&mut self, parent: RNode, child: RNode) {
        let index = self
            .nodes
            .get(parent)
            .map(|p| p.children.len())
            .unwrap_or(0);
        self.attach_impl(parent, child, index);
    }

    fn native_window_tabs(&self) -> bool {
        self.toolkit.native_window_tabs()
    }
    fn native_document_tabs(&self) -> bool {
        self.toolkit.native_document_tabs()
    }
    fn group_windows(&mut self, roots: &[RNode]) {
        let hosts = roots
            .iter()
            .filter_map(|r| self.nodes.get(*r)?.handle.clone())
            .collect::<Vec<_>>();
        self.toolkit.group_windows(&hosts);
    }
    fn window_tab_order(&self, root: RNode) -> Vec<day_spec::NodeId> {
        self.nodes
            .get(root)
            .and_then(|n| n.handle.as_ref())
            .map(|h| self.toolkit.window_tab_order(h))
            .unwrap_or_default()
    }
    fn reparent(&mut self, child: RNode, parent: RNode) -> bool {
        if !self.nodes.contains_key(child) || !self.nodes.contains_key(parent) {
            return false;
        }
        let old = self.nodes[child].parent;
        if old == parent {
            return true;
        }
        // Reject cycles and window roots: only content may migrate.
        if self.windows.iter().any(|w| w.root == child) {
            return false;
        }
        let mut up = parent;
        while let Some(n) = self.nodes.get(up) {
            if up == child {
                return false;
            }
            up = n.parent;
        }
        let ancestor = self.native_ancestor(old);
        let handle = self.nodes.get(ancestor).and_then(|n| n.handle.clone());
        let mut roots = Vec::new();
        if self.nodes[child].handle.is_some() {
            roots.push(child);
        } else {
            self.native_descendants(child, &mut roots);
        }
        if let Some(h) = handle {
            for r in roots {
                // roots contains only nodes with handles, collected above without mutation.
                self.toolkit
                    .remove(&h, self.nodes[r].handle.as_ref().unwrap());
            }
        }
        if let Some(p) = self.nodes.get_mut(old) {
            p.children.retain(|n| *n != child);
        }
        self.mark_needs_measure_impl(old);
        self.attach(parent, child);
        self.layout_dirty = true;
        true
    }

    fn attach_at(&mut self, parent: RNode, child: RNode, index: usize) {
        self.attach_impl(parent, child, index);
    }

    fn reorder_children(&mut self, parent: RNode, order: Vec<RNode>) {
        // Nothing moved, and the resync below is not free. `each` re-runs its diff whenever the
        // source closure's tracked reads wake it, which is far more often than the order changes:
        // a projection that reads its store coarsely re-runs for every keystroke in a field that
        // store also feeds. Re-inserting every native descendant on each of those is churn on the
        // backends that can re-parent cheaply, and on the ones whose `move_child` detaches first
        // (android, arkui) it also drops the keyboard focus of a text field inside the subtree
        // (docs/focus.md): the field a user was typing into loses focus per character.
        if self.nodes.get(parent).is_some_and(|p| p.children == order) {
            return;
        }
        if let Some(p) = self.nodes.get_mut(parent) {
            p.children = order;
        }
        // Full native resync of the nearest native ancestor: rebuild in-order positions.
        let ancestor = self.native_ancestor(parent);
        let anc_handle = self.nodes[ancestor]
            .handle
            .clone()
            .expect("native ancestor");
        let mut desired = Vec::new();
        self.native_descendants(ancestor, &mut desired);
        for (i, r) in desired.iter().enumerate() {
            let h = self.nodes[*r].handle.clone().unwrap();
            self.toolkit.move_child(&anc_handle, &h, i);
        }
        self.mark_needs_measure_impl(parent);
    }

    fn remove_subtree(&mut self, node: RNode) {
        // Window roots have no native parent to detach from; they go through
        // `remove_window_root` (docs/windows.md), never here.
        debug_assert!(
            !self.windows.iter().any(|w| w.root == node),
            "remove_subtree called with a window root"
        );
        self.remove_subtree_impl(node);
    }

    fn on_event(&mut self, node: RNode, h: EventHandler) {
        self.handlers.entry(node).or_default().push(h);
    }

    fn handlers_for(&self, node: RNode) -> Vec<EventHandler> {
        self.handlers.get(&node).cloned().unwrap_or_default()
    }
    fn native_view_of(&self, node: RNode) -> Option<RNode> {
        let mut cur = node;
        for _ in 0..16 {
            let n = self.nodes.get(cur)?;
            if n.handle.is_some() {
                return Some(cur);
            }
            match n.children.as_slice() {
                [only] => cur = *only,
                _ => return None,
            }
        }
        None
    }
    fn gesture_target(&self, node: RNode, kind: day_spec::GestureKind) -> Option<RNode> {
        let has = |n: RNode| self.gestures.get(&n).is_some_and(|k| k.contains(&kind));
        if has(node) {
            return Some(node);
        }
        // Climb the element's own wrappers, native ones included. An element nested in another
        // (`.any()` and more modifiers) extends the span to the enclosing element's outer node.
        let mut cur = node;
        let mut bound = self.element_outer.get(&node).copied();
        while let Some(outer) = bound {
            if cur == outer {
                bound = self.element_outer.get(&outer).copied();
                continue;
            }
            let Some(parent) = self.nodes.get(cur).map(|n| n.parent) else {
                break;
            };
            if parent == cur || !self.nodes.contains_key(parent) {
                break;
            }
            cur = parent;
            if has(cur) {
                return Some(cur);
            }
        }
        self.wrappers_above(cur).into_iter().find(|w| has(*w))
    }

    fn set_element_outer(&mut self, inner: RNode, outer: RNode) {
        if inner != outer {
            self.element_outer.insert(inner, outer);
        }
    }

    fn wrappers_above(&self, node: RNode) -> Vec<RNode> {
        let mut out = Vec::new();
        let mut cur = node;
        for _ in 0..16 {
            let Some(parent) = self.nodes.get(cur).map(|n| n.parent) else {
                break;
            };
            match self.nodes.get(parent) {
                Some(p) if p.handle.is_none() && p.children.len() == 1 && parent != cur => {
                    out.push(parent);
                    cur = parent;
                }
                _ => break,
            }
        }
        out
    }
    fn node_exists(&self, node: RNode) -> bool {
        self.nodes.contains_key(node)
    }
    fn dark_mode(&mut self) -> bool {
        self.toolkit.dark_mode()
    }
    fn reduce_motion(&mut self) -> bool {
        self.toolkit.reduce_motion()
    }

    fn mounted_id_families(&self) -> Vec<String> {
        self.mounted_id_families.iter().cloned().collect()
    }
    fn set_id(&mut self, node: RNode, id: String) {
        if self.nodes.contains_key(node) {
            self.mounted_id_families
                .insert(crate::element_id::family_of(&id).to_owned());
        }
        if let Some(n) = self.nodes.get_mut(node) {
            n.id = Some(id.clone());
            n.a11y.merge(&A11yProps {
                identifier: Some(id),
                ..Default::default()
            });
            if let Some(h) = n.handle.clone() {
                self.toolkit.set_a11y(&h, &n.a11y);
            }
        }
    }

    fn forward_whole_row(&mut self, wrapper: RNode, inner: RNode) {
        let whole = self.nodes.get(inner).is_some_and(|n| n.flex.whole_row);
        if let Some(n) = self.nodes.get_mut(wrapper) {
            n.flex.whole_row = whole;
        }
    }

    fn set_grid_facts(&mut self, node: RNode, facts: GridFacts) {
        if let Some(n) = self.nodes.get_mut(node) {
            let g = &mut n.flex.grid;
            if facts.is_row {
                g.is_row = true;
            }
            if facts.row_valign.is_some() {
                g.row_valign = facts.row_valign;
            }
            if facts.col_span != 0 {
                g.col_span = facts.col_span;
            }
            if facts.align.is_some() {
                g.align = facts.align;
            }
        }
    }

    fn announce(&mut self, text: &str, urgent: bool) {
        self.toolkit.announce(text, urgent);
    }

    fn set_a11y(&mut self, node: RNode, a11y: A11yProps) {
        if let Some(n) = self.nodes.get_mut(node) {
            // Merge onto whatever's already recorded (piece default role, an earlier `.a11y`/`.id`)
            // and re-apply the full picture; backends set each present field idempotently (§13).
            n.a11y.merge(&a11y);
            // A canvas has no text of its own: what it tells a screen reader (its value, else
            // its label) is its text, so `assert_text` reads a drawn readout the way it reads
            // a label.
            if n.kind == kinds::CANVAS
                && let Some(text) = n.a11y.value.clone().or_else(|| n.a11y.label.clone())
            {
                n.probe.text = text;
            }
            if let Some(h) = n.handle.clone() {
                self.toolkit.set_a11y(&h, &n.a11y);
            }
        }
    }

    fn enable_gesture(&mut self, node: RNode, kind: day_spec::GestureKind) {
        let kinds = self.gestures.entry(node).or_default();
        if !kinds.contains(&kind) {
            kinds.push(kind);
        }
        // `.on_tap`/`.on_drag` often land on a layout-only wrapper (`.frame()`, `.padding()`,
        // `.grow()` produce one) that has no native view to carry a recognizer. Descend
        // through single-child layout-only nodes to the nearest native descendant and attach
        // there, but deliver events against the original node, where the modifier registered
        // its handler.
        let mut cur = node;
        for _ in 0..16 {
            let Some(n) = self.nodes.get(cur) else { return };
            if let Some(h) = n.handle.clone() {
                if kind == day_spec::GestureKind::Tap && n.kind == kinds::BUTTON {
                    log::warn!(
                        "tap gesture attached to native button {:?} (id: {:?}): \
                         use .action(...) instead of .on_tap(...) or .on_tap_at(...). \
                         A separate gesture recognizer can delay pressed feedback and \
                         bypass native keyboard, accessibility, and disabled behavior",
                        rnode_to_id(cur),
                        n.id,
                    );
                }
                self.toolkit.enable_gesture(&h, rnode_to_id(node), kind);
                return;
            }
            match n.children.as_slice() {
                [only] => cur = *only,
                _ => break,
            }
        }
        log::warn!(
            "enable_gesture({kind:?}) found no native view under the target node — \
             the gesture will not fire natively (attach it to a piece with a native handle)"
        );
    }

    fn focus_node(&mut self, node: RNode, focused: bool) {
        // The wrapper-descent `set_focusable` makes: an id (and so a `focus:` step) often lands
        // on a layout-only wrapper (`.frame`, `.padding`), and focusing it did nothing at all.
        let mut cur = node;
        for _ in 0..16 {
            let Some(n) = self.nodes.get(cur) else { return };
            if let Some(h) = n.handle.clone() {
                self.toolkit.focus(&h, rnode_to_id(node), focused);
                return;
            }
            match n.children.as_slice() {
                [only] => cur = *only,
                _ => return,
            }
        }
    }

    fn set_focusable(&mut self, node: RNode, focusable: bool) {
        // Same wrapper-descent as `enable_gesture`: `.focusable()` often lands on a
        // layout-only wrapper; the duty needs the nearest native view, events keep the
        // original node.
        let mut cur = node;
        for _ in 0..16 {
            let Some(n) = self.nodes.get(cur) else { return };
            if let Some(h) = n.handle.clone() {
                self.toolkit.set_focusable(&h, rnode_to_id(node), focusable);
                return;
            }
            match n.children.as_slice() {
                [only] => cur = *only,
                _ => break,
            }
        }
        log::warn!(
            "set_focusable found no native view under the target node — \
             the piece will not join the focus order"
        );
    }

    fn set_probe_focused(&mut self, node: RNode, focused: bool) {
        if let Some(n) = self.nodes.get_mut(node) {
            n.probe.focused = focused;
        }
        // The layout-only wrappers directly above a native view are the same element: an id
        // (`.frame(..).id(..)`) and a modifier often sit on one, while the toolkit reports
        // focus on the view itself. Mirror the state up through them, the inverse of the
        // descent `set_focusable` and `focus_node` make.
        for w in self.wrappers_above(node) {
            if let Some(p) = self.nodes.get_mut(w) {
                p.probe.focused = focused;
            }
        }
        // And down through the single-child layout-only chain to the native view: the
        // toolkit reports focus against the node that enabled it (a `.focusable()` or
        // `.focused(..)` wrapper), while `.id` names the piece's own node below it
        // (docs/api-style.md "Modifier classes"), which is what a dayscript `assert_focused`
        // resolves. Both are the same element.
        let mut cur = node;
        for _ in 0..16 {
            let Some(n) = self.nodes.get(cur) else { break };
            if n.handle.is_some() && cur != node {
                if let Some(p) = self.nodes.get_mut(cur) {
                    p.probe.focused = focused;
                }
                break;
            }
            let next = match n.children.as_slice() {
                [only] => *only,
                _ => break,
            };
            if let Some(p) = self.nodes.get_mut(next) {
                p.probe.focused = focused;
            }
            cur = next;
        }
        // Remember which node has it, beyond the per-node flag: keys follow focus
        // (docs/menus.md), so dayscript's `key:` step needs the same answer the platform gives.
        // A loss only clears the record if this node is still the one holding it; gains land
        // before losses in the pump, so a hand-off has already named the new owner.
        FOCUSED.with(|f| match focused {
            true => f.set(Some(node)),
            false if f.get() == Some(node) => f.set(None),
            false => {}
        });
    }

    fn set_probe_selected(&mut self, node: RNode, selected: Option<usize>) {
        if let Some(n) = self.nodes.get_mut(node) {
            // Both fields, as a picker does: `assert_value` reads `value` for a number and
            // `assert_selected` reads `selected`, and a nav host answers either.
            n.probe.selected = selected.map(|i| i as i64).unwrap_or(-1);
            n.probe.value = n.probe.selected as f64;
        }
    }

    fn set_probe_value(&mut self, node: RNode, value: f64, text: String) {
        if let Some(n) = self.nodes.get_mut(node) {
            n.probe.value = value;
            n.probe.text = text;
        }
    }

    fn set_app_menu(&mut self, items: Vec<day_spec::MenuItem>) {
        collect_menu_families(&items, &mut self.mounted_id_families);
        self.toolkit.set_app_menu(&items);
    }

    fn edit_window_toolbar(&mut self, root: RNode, ops: Vec<day_spec::ToolbarOp>) -> bool {
        let Some(h) = self.nodes.get(root).and_then(|n| n.handle.clone()) else {
            return false;
        };
        for op in &ops {
            if let day_spec::ToolbarOp::Insert { item, .. } = op {
                self.mounted_id_families
                    .insert(crate::element_id::family_of(&item.id).to_owned());
            }
        }
        self.toolkit.edit_toolbar(&h, &ops)
    }

    fn patch_window_toolbar(&mut self, root: RNode, patch: day_spec::ToolbarPatch) -> bool {
        let Some(h) = self.nodes.get(root).and_then(|n| n.handle.clone()) else {
            return false;
        };
        self.toolkit.update_toolbar(&h, &patch);
        true
    }

    fn set_context_menu(&mut self, node: RNode, items: Vec<day_spec::MenuItem>) {
        // The modifier often sits on a handle-less layout wrapper (`.padding`/`.frame` build
        // those): the native affordance needs a real view, so fall through to the first
        // native root under the node. Silently dropping the menu here is what made
        // `label(..).padding(..).context_menu(..)` dead on every backend.
        let target = if self.nodes.get(node).is_some_and(|n| n.handle.is_some()) {
            Some(node)
        } else {
            let mut roots = Vec::new();
            self.native_descendants(node, &mut roots);
            roots.first().copied()
        };
        let Some(t) = target else {
            log::warn!("context_menu on a subtree with no native view — menu dropped");
            return;
        };
        collect_menu_families(&items, &mut self.mounted_id_families);
        let model = ContextMenuModel::Items(items.clone());
        self.context_menus.insert(node, model.clone());
        self.context_menus.insert(t, model);
        if let Some(h) = self.nodes.get(t).and_then(|n| n.handle.clone()) {
            self.toolkit.set_context_menu(&h, rnode_to_id(t), &items);
        }
    }

    fn scroll_to_target(&mut self, node: RNode, target: &ScrollTarget, animated: bool) -> bool {
        // `Id` routes through reveal: the element names the scroll implicitly.
        if let ScrollTarget::Id(id) = target {
            let Some(el) = self.find_by_id(id) else {
                return false;
            };
            return self.scroll_reveal(el, animated);
        }
        let Some(n) = self.nodes.get(node) else {
            return false;
        };
        if n.kind == kinds::NAV_MENU {
            return match (n.handle.clone(), target) {
                (Some(h), ScrollTarget::Top | ScrollTarget::Bottom) => self
                    .toolkit
                    .nav_scroll_to_edge(&h, matches!(target, ScrollTarget::Bottom)),
                _ => false,
            };
        }
        if n.kind != kinds::SCROLL {
            return false;
        }
        let Some(h) = n.handle.clone() else {
            return false;
        };
        let viewport = n.last_native_frame.map(|f| f.size).unwrap_or(Size::ZERO);
        let content = n.scroll_content.unwrap_or(viewport);
        // Compose a content-space rect whose minimal reveal lands on the target
        // (`Toolkit::scroll_to` is scrollRectToVisible semantics on every backend).
        let rect = match target {
            ScrollTarget::Top | ScrollTarget::Leading => Rect::new(0.0, 0.0, 1.0, 1.0),
            ScrollTarget::Bottom => Rect::new(0.0, (content.height - 1.0).max(0.0), 1.0, 1.0),
            ScrollTarget::Trailing => Rect::new((content.width - 1.0).max(0.0), 0.0, 1.0, 1.0),
            // A viewport-sized rect: minimal reveal pins the viewport origin to the point
            // (exactly, when the point is within the scrollable range).
            ScrollTarget::Offset(p) => Rect::new(p.x, p.y, viewport.width, viewport.height),
            ScrollTarget::Id(_) => unreachable!("routed to scroll_reveal above"),
        };
        self.toolkit
            .scroll_to(&h, rect, animated && !crate::reduce_motion_now());
        true
    }

    fn scroll_reveal(&mut self, node: RNode, animated: bool) -> bool {
        // The element's frame is relative to its nearest REALIZED native ancestor (§7);
        // accumulate native origins up to (not including) the enclosing scroll, which puts
        // the rect in the scroll's content space, which is what Toolkit::scroll_to expects.
        let Some(mut rect) = self.nodes.get(node).and_then(|n| n.last_native_frame) else {
            return false;
        };
        let mut anc = match self.nodes.get(node) {
            Some(n) => n.parent,
            None => return false,
        };
        loop {
            let Some(a) = self.nodes.get(anc) else {
                return false; // walked off the root: no scroll ancestor
            };
            if a.kind == kinds::SCROLL {
                let Some(h) = a.handle.clone() else {
                    return false;
                };
                self.toolkit
                    .scroll_to(&h, rect, animated && !crate::reduce_motion_now());
                return true;
            }
            if a.handle.is_some()
                && let Some(f) = a.last_native_frame
            {
                rect.origin.x += f.origin.x;
                rect.origin.y += f.origin.y;
            }
            anc = a.parent;
        }
    }

    fn patch(&mut self, node: RNode, patch: Box<dyn Any>, affects_size: bool) {
        {
            use day_spec::props::*;
            if let Some(n) = self.nodes.get_mut(node) {
                if let Some(p) = patch.downcast_ref::<LabelPatch>() {
                    // Both text-carrying variants: a `.markdown()` label re-parses through
                    // `Runs`, and a probe that only tracked `Text` would report the string the
                    // label was born with forever (docs/text-runs.md).
                    match p {
                        LabelPatch::Text(t) => n.probe.text = t.clone(),
                        LabelPatch::Runs(t, _) => n.probe.text = t.clone(),
                        LabelPatch::Font(_) | LabelPatch::Color(_) => {}
                    }
                } else if let Some(p) = patch.downcast_ref::<ButtonPatch>() {
                    match p {
                        ButtonPatch::Title(t) => n.probe.text = t.clone(),
                        ButtonPatch::Content(c) => n.probe.text = c.title.clone(),
                        ButtonPatch::Enabled(e) => n.probe.enabled = *e,
                        ButtonPatch::Selected(on) => n.probe.flag = *on,
                        // The style is a look, not something a probe asserts on.
                        ButtonPatch::Style(_) => {}
                    }
                } else if let Some(p) = patch.downcast_ref::<TogglePatch>() {
                    match p {
                        TogglePatch::On(v) => n.probe.flag = *v,
                        TogglePatch::Enabled(e) => n.probe.enabled = *e,
                    }
                } else if let Some(p) = patch.downcast_ref::<SliderPatch>() {
                    match p {
                        SliderPatch::Value(v) => n.probe.value = *v,
                        SliderPatch::Enabled(e) => n.probe.enabled = *e,
                    }
                } else if let Some(p) = patch.downcast_ref::<PickerPatch>() {
                    match p {
                        PickerPatch::Selected(i) => {
                            n.probe.selected = *i as i64;
                            n.probe.value = *i as f64;
                        }
                        PickerPatch::Options(opts) => n.probe.options = opts.clone(),
                        PickerPatch::Enabled(e) => n.probe.enabled = *e,
                    }
                    let i = n.probe.selected.max(0) as usize;
                    n.probe.text = n.probe.options.get(i).cloned().unwrap_or_default();
                } else if let Some(TextAreaPatch::SetText(t)) =
                    patch.downcast_ref::<TextAreaPatch>()
                {
                    n.probe.text = t.clone();
                } else if let Some(ProgressPatch::Value(v)) = patch.downcast_ref::<ProgressPatch>()
                {
                    n.probe.flag = v.is_none();
                    n.probe.value = v.unwrap_or(0.0);
                } else if let Some(p) = patch.downcast_ref::<TextFieldPatch>() {
                    match p {
                        TextFieldPatch::Text { text, .. } => n.probe.text = text.clone(),
                        TextFieldPatch::Enabled(e) => n.probe.enabled = *e,
                        _ => {}
                    }
                } else if let Some(NavMenuPatch::Selected(sel)) =
                    patch.downcast_ref::<NavMenuPatch>()
                {
                    n.probe.selected = sel.map(|i| i as i64).unwrap_or(-1);
                    n.probe.value = n.probe.selected as f64;
                }
            }
        }
        let Some(n) = self.nodes.get(node) else {
            return;
        };
        let kind = n.kind;
        if let Some(h) = n.handle.clone() {
            let anim = self.resolve_anim(node);
            self.toolkit.update(&h, kind, patch.as_ref(), anim.as_ref());
        }
        if affects_size {
            self.mark_needs_measure_impl(node);
        }
    }

    fn set_implicit_anim(&mut self, node: RNode, anim: Option<day_spec::AnimSpec>) {
        let had = self
            .nodes
            .get(node)
            .map(|n| n.implicit_anim.is_some())
            .unwrap_or(false);
        if let Some(n) = self.nodes.get_mut(node) {
            n.implicit_anim = anim;
        } else {
            return;
        }
        match (had, anim.is_some()) {
            (false, true) => self.implicit_anim_count += 1,
            (true, false) => self.implicit_anim_count = self.implicit_anim_count.saturating_sub(1),
            _ => {}
        }
    }

    fn set_node_opacity(&mut self, node: RNode, opacity: f64) {
        let Some(h) = self.nodes.get(node).and_then(|n| n.handle.clone()) else {
            return;
        };
        let anim = self.resolve_anim(node);
        self.toolkit.set_opacity(&h, opacity, anim.as_ref());
    }

    fn set_node_transform(&mut self, node: RNode, t: day_spec::Transform) {
        let Some(n) = self.nodes.get(node) else {
            return;
        };
        let Some(h) = n.handle.clone() else {
            return;
        };
        // The node's laid-out size, passed so backends resolve the transform's anchor to a pixel
        // pivot without querying the (possibly not-yet-allocated) native widget (§8.4).
        let size = n.last_native_frame.map(|f| f.size).unwrap_or(Size::ZERO);
        let anim = self.resolve_anim(node);
        self.toolkit.set_transform(&h, t, size, anim.as_ref());
    }

    fn set_node_selectable(&mut self, node: RNode, selectable: bool) {
        let Some(h) = self.nodes.get(node).and_then(|n| n.handle.clone()) else {
            return;
        };
        // A toolkit may have to rebuild the widget as a selection-capable class (UIKit's
        // label → read-only text view); adopt the replacement so patches and layout follow it.
        if let Some(new) = self.toolkit.set_selectable(&h, selectable)
            && let Some(n) = self.nodes.get_mut(node)
        {
            if n.tweaked {
                log::warn!(
                    "`.selectable()` rebuilt this widget as a different native class, \
                     discarding an earlier tweak's changes — apply `.selectable()` BEFORE the \
                     tweak so it runs against the widget that ships (docs/tweaks.md)."
                );
            }
            n.handle = Some(new);
        }
    }

    fn set_node_input_traits(&mut self, node: RNode, traits: &day_spec::InputTraits) {
        let Some(h) = self.nodes.get(node).and_then(|n| n.handle.clone()) else {
            return;
        };
        // A toolkit whose secure field is its own class rebuilds the widget (AppKit, WinUI);
        // adopt the replacement so patches, layout and focus follow it.
        if let Some(new) = self.toolkit.set_input_traits(&h, traits)
            && let Some(n) = self.nodes.get_mut(node)
        {
            if n.tweaked {
                log::warn!(
                    "a text field's `.secure()` rebuilt this widget as a different native \
                     class, discarding an earlier tweak's changes (docs/tweaks.md)."
                );
            }
            n.handle = Some(new);
            n.last_native_frame = None;
            self.mark_needs_measure_impl(node);
        }
    }

    fn set_node_cursor(&mut self, node: RNode, cursor: day_spec::Cursor) {
        // The wrapper descent `enable_gesture` makes: `.padding(…).cursor(…)` lands on a
        // layout-only wrapper with no view of its own, and the cursor belongs on the view it
        // wraps.
        let Some(h) = self
            .native_view_of(node)
            .and_then(|n| self.nodes.get(n))
            .and_then(|n| n.handle.clone())
        else {
            return;
        };
        self.toolkit.set_cursor(&h, cursor);
    }

    fn set_node_drag_region(&mut self, node: RNode, drag: bool) {
        // Same descent: `row(…).padding(8.0).window_drag_region()` marks the row.
        let Some(h) = self
            .native_view_of(node)
            .and_then(|n| self.nodes.get(n))
            .and_then(|n| n.handle.clone())
        else {
            log::warn!(
                "window_drag_region found no native view under the target node; give the \
                 region a piece with a native view (a background, a row)"
            );
            return;
        };
        self.toolkit.set_drag_region(&h, drag);
    }

    fn note_node_tweaked(&mut self, node: RNode) {
        if let Some(n) = self.nodes.get_mut(node) {
            n.tweaked = true;
        }
    }

    fn request_frame(&mut self, root: RNode, cb: day_spec::FrameCallback) -> day_spec::CancelFrame {
        if let Some(h) = self.nodes.get(root).and_then(|n| n.handle.clone()) {
            self.toolkit.request_frame(&h, cb)
        } else {
            Box::new(|| {})
        }
    }

    fn replay(&mut self, node: RNode, ops: Vec<DrawOp>) {
        let Some(n) = self.nodes.get(node) else {
            return;
        };
        let size = n.last_native_frame.map(|f| f.size).unwrap_or(Size::ZERO);
        if let Some(h) = n.handle.clone() {
            self.toolkit.replay(&h, &ops, size);
        }
    }

    fn mark_needs_measure(&mut self, node: RNode) {
        self.mark_needs_measure_impl(node);
    }

    fn mark_layout_dirty(&mut self) {
        self.layout_dirty = true;
    }

    fn invalidate_all_measurements(&mut self) {
        for (_, n) in self.nodes.iter_mut() {
            n.needs_measure = true;
            n.needs_layout = true;
            n.cache.clear();
        }
        // Cells keep a row's measurements while its width holds; forgetting the width makes the
        // dirty-cell sweep measure each bound row afresh, and a self-sizing row whose height
        // changes reports it (`ListPatch::RowSizeInvalidated`).
        for state in self.lists.values_mut() {
            for cell in state.cells.values_mut() {
                cell.laid_width = None;
            }
        }
        for state in self.trees.values_mut() {
            for cell in state.cells.values_mut() {
                cell.laid_width = None;
            }
        }
        self.layout_dirty = true;
    }

    fn layout_if_needed(&mut self) {
        if !self.layout_dirty {
            return;
        }
        self.layout_dirty = false;
        self.layout_now();
    }

    fn set_route(&mut self, route: &str) {
        self.toolkit.set_route(route);
    }

    fn set_window_size(&mut self, s: Size) {
        // The primary window (`WINDOW_NODE` routing); secondary windows resize through
        // `set_root_size` with their own root.
        if s != self.windows[0].size {
            self.windows[0].size = s;
            let root = self.windows[0].root;
            self.mark_needs_measure_impl(root);
        }
    }

    fn child_count(&self, node: RNode) -> usize {
        self.nodes.get(node).map(|n| n.children.len()).unwrap_or(0)
    }

    fn first_child(&self, node: RNode) -> Option<RNode> {
        self.nodes
            .get(node)
            .and_then(|n| n.children.first().copied())
    }

    fn parent_of(&self, node: RNode) -> Option<RNode> {
        self.nodes
            .get(node)
            .map(|n| n.parent)
            .filter(|p| !p.is_null() && *p != node)
    }

    fn node_kind(&self, node: RNode) -> Option<PieceKind> {
        self.nodes.get(node).map(|n| n.kind)
    }

    fn node_id(&self, node: RNode) -> Option<String> {
        self.nodes.get(node).and_then(|n| n.id.clone())
    }

    fn node_handle_any(&self, node: RNode) -> Option<Box<dyn Any>> {
        self.nodes
            .get(node)
            .and_then(|n| n.handle.clone())
            .map(|h| Box::new(h) as Box<dyn Any>)
    }

    fn node_frame(&self, node: RNode) -> Option<Rect> {
        self.nodes.get(node).and_then(|n| n.last_native_frame)
    }

    fn node_probe(&self, node: RNode) -> Option<NodeProbe> {
        self.nodes.get(node).map(|n| n.probe.clone())
    }

    fn node_a11y(&self, node: RNode) -> Option<A11yProps> {
        self.nodes.get(node).map(|n| n.a11y.clone())
    }

    fn read_native(&self, node: RNode) -> Option<day_spec::NativeSnapshot> {
        let n = self.nodes.get(node)?;
        let h = n.handle.as_ref()?;
        Some(self.toolkit.read_native(h))
    }

    fn a11y_nodes(&self) -> Vec<(String, PieceKind, A11yProps, day_spec::NativeSnapshot)> {
        self.nodes
            .values()
            .filter_map(|n| {
                let id = n.id.clone()?;
                let h = n.handle.as_ref()?;
                Some((id, n.kind, n.a11y.clone(), self.toolkit.read_native(h)))
            })
            .collect()
    }

    fn find_by_id(&self, id: &str) -> Option<RNode> {
        // A settings page can exist both in the app sidebar and in its focused window/cover.
        // Slot order can otherwise mix fields from one form with the Save button of another.
        let focused = crate::windows::focused_window()
            .map(|w| id_to_rnode(crate::windows::window_node_id(&w)))
            .unwrap_or_else(|| self.root());
        let mut fallback = None;
        for (key, node) in &self.nodes {
            if node.id.as_deref() != Some(id) {
                continue;
            }
            fallback.get_or_insert(key);
            let mut ancestor = key;
            while let Some(node) = self.nodes.get(ancestor) {
                // Covers are children of the primary root but own a separate layout root.
                // Stop at the nearest root so a closing cover cannot masquerade as primary.
                if self.windows.iter().any(|w| w.root == ancestor) {
                    if ancestor == focused {
                        return Some(key);
                    }
                    break;
                }
                ancestor = if node.kind == kinds::LIST_CELL && node.parent.is_null() {
                    // Recycling-list/tree cells are independent layout anchors, not children
                    // in the owner's layout. Follow their logical owner for window lookup.
                    self.lists
                        .iter()
                        .find_map(|(&owner, state)| {
                            state
                                .cells
                                .values()
                                .any(|c| c.anchor == ancestor)
                                .then_some(owner)
                        })
                        .or_else(|| {
                            self.trees.iter().find_map(|(&owner, state)| {
                                state
                                    .cells
                                    .values()
                                    .any(|c| c.anchor == ancestor)
                                    .then_some(owner)
                            })
                        })
                        .unwrap_or(node.parent)
                } else {
                    node.parent
                };
            }
        }
        fallback
    }

    fn toggle_sidebar(&mut self, host: RNode) -> bool {
        let Some(h) = self.nodes.get(host).and_then(|n| n.handle.as_ref()) else {
            return false;
        };
        self.toolkit.toggle_sidebar(h)
    }

    fn native_back(&mut self) -> bool {
        self.toolkit.native_back()
    }

    fn prepare_snapshot(
        &mut self,
        root: Option<RNode>,
        revision: u32,
    ) -> Result<day_spec::capture::Readiness, String> {
        let host = match root {
            Some(root) if self.windows[0].root != root => Some(
                self.nodes
                    .get(root)
                    .and_then(|n| n.handle.clone())
                    .ok_or("window is gone")?,
            ),
            _ => None,
        };
        self.toolkit.prepare_snapshot(host.as_ref(), revision)
    }

    fn snapshot(&mut self) -> Result<Vec<u8>, String> {
        self.toolkit.snapshot_window()
    }

    fn snapshot_origin(&mut self) -> Option<Point> {
        let root = self.windows[0].root;
        let h = self.nodes.get(root).and_then(|n| n.handle.clone())?;
        self.toolkit.snapshot_origin(&h)
    }

    fn snapshot_chrome(&mut self) -> Result<Vec<u8>, String> {
        self.toolkit.snapshot_window_chrome()
    }

    fn decode_image(&mut self, req: u64, id: day_spec::BitmapId, bytes: &[u8]) {
        self.toolkit.decode_image(req, id, bytes);
    }

    fn image_info(&mut self, id: day_spec::BitmapId) -> Option<day_spec::BitmapInfo> {
        self.toolkit.image_info(id)
    }

    fn image_properties(&mut self, id: day_spec::BitmapId) -> Option<day_spec::ImageProperties> {
        self.toolkit.image_properties(id)
    }

    fn encode_image(&mut self, req: u64, id: day_spec::BitmapId, spec: &day_spec::EncodeSpec) {
        self.toolkit.encode_image(req, id, spec);
    }

    fn image_encode_formats(&mut self) -> Vec<day_spec::ImageFormat> {
        self.toolkit.encode_formats()
    }

    fn release_image(&mut self, id: day_spec::BitmapId) {
        self.toolkit.release_image(id);
    }

    fn render_bitmap(
        &mut self,
        req: u64,
        id: day_spec::BitmapId,
        ops: &[day_spec::DrawOp],
        size: Size,
        scale: f64,
    ) {
        self.toolkit.render_bitmap(req, id, ops, size, scale);
    }

    fn render_pdf(&mut self, req: u64, pages: &[day_spec::PdfPage], info: &day_spec::PdfInfo) {
        self.toolkit.render_pdf(req, pages, info);
    }

    fn window_image_support(&mut self) -> day_spec::Support {
        self.toolkit.capability(day_spec::Cap::Snapshot)
    }

    fn font_families(&mut self) -> Vec<day_spec::FontFamilyInfo> {
        self.toolkit.font_families()
    }

    fn measure_text(
        &mut self,
        text: &str,
        size: f64,
        font: &day_spec::CanvasFont,
    ) -> Option<day_spec::TextMetrics> {
        self.toolkit.measure_text(text, size, font)
    }

    fn ui_idle(&mut self) -> bool {
        self.toolkit.ui_idle()
    }

    fn root_node(&self) -> RNode {
        self.windows[0].root
    }

    fn open_window_root(&mut self, options: &WindowOptions, kind: WindowKind) -> WindowRootReply {
        // The same "wrap an externally-owned handle" record as the primary root and the
        // list cell anchors; the handle arrives now (desktop) or at adoption (mobile).
        let root = self.nodes.insert(NodeData {
            kind: kinds::CONTAINER,
            handle: None,
            parent: RNode::null(),
            children: Vec::new(),
            layout: Rc::new(PassThrough),
            flex: Flex::default(),
            scope: Scope::root(),
            id: None,
            parked_id: None,
            a11y: Default::default(),
            cache: Vec::new(),
            baseline_cache: None,
            probe: NodeProbe::default(),
            needs_measure: true,
            needs_layout: true,
            last_native_frame: None,
            scroll_content: None,
            implicit_anim: None,
            tweaked: false,
            is_boundary: true,
        });
        match self.toolkit.open_window(rnode_to_id(root), options, kind) {
            day_spec::WindowOpenReply::Open(h) => {
                self.nodes[root].handle = Some(h);
                self.windows.push(WindowEntry {
                    root,
                    size: options.size,
                });
                self.layout_dirty = true;
                WindowRootReply::Open(root)
            }
            day_spec::WindowOpenReply::Pending => WindowRootReply::Pending(root),
            day_spec::WindowOpenReply::Unsupported => {
                self.nodes.remove(root);
                WindowRootReply::Unsupported
            }
        }
    }

    fn adopt_window_root(&mut self, root: RNode, raw: day_spec::RawHandle, size: Size) -> bool {
        let Some(node) = self.nodes.get_mut(root) else {
            return false; // closed before the native side finished; the caller drops the window
        };
        let handle = self.toolkit.adopt(raw);
        node.handle = Some(handle);
        node.needs_measure = true;
        self.windows.push(WindowEntry { root, size });
        self.layout_dirty = true;
        true
    }

    fn remove_window_root(&mut self, root: RNode) {
        // Any window may go, including the first one opened (docs/windows.md close policy);
        // the app's life is the life of its primary windows, not of `windows[0]` specifically.
        //
        // The last entry is kept, because `root()` has to answer for the whole tree and callers
        // are in no position to handle "no windows". Reaching that point means the last window
        // has closed, which is the app exiting: its content is already gone (teardown removes
        // the children first) and the empty shell outlives nothing.
        if self.windows.len() <= 1 {
            self.collect_and_release(root);
            self.layout_dirty = true;
            return;
        }
        self.windows.retain(|w| w.root != root);
        // No native detach: a window root has no native parent; the platform window is
        // already closed (or the backend releases it with the content handle).
        self.collect_and_release(root);
        self.layout_dirty = true;
    }

    fn set_root_size(&mut self, root: RNode, s: Size) {
        if let Some(w) = self.windows.iter_mut().find(|w| w.root == root)
            && w.size != s
        {
            w.size = s;
            self.mark_needs_measure_impl(root);
        }
    }

    fn fit_window(&mut self, root: RNode, size: Size) {
        if let Some(h) = self.nodes.get(root).and_then(|n| n.handle.clone()) {
            self.toolkit.fit_window(&h, size);
        }
        self.set_root_size(root, size);
    }

    fn add_extra_layout_root(&mut self, node: RNode, size: Size) {
        if !self.windows.iter().any(|w| w.root == node) {
            self.windows.push(WindowEntry { root: node, size });
            self.layout_dirty = true;
        }
    }

    fn drop_extra_layout_root(&mut self, node: RNode) {
        debug_assert!(
            self.windows.first().map(|w| w.root) != Some(node),
            "drop_extra_layout_root called with the primary root"
        );
        self.windows.retain(|w| w.root != node);
    }

    fn close_native_window(&mut self, root: RNode) {
        if let Some(h) = self.nodes.get(root).and_then(|n| n.handle.clone()) {
            self.toolkit.close_window(&h);
        }
    }

    fn quit_app(&mut self) {
        self.toolkit.quit_app();
    }

    fn focus_native_window(&mut self, root: RNode) {
        if let Some(h) = self.nodes.get(root).and_then(|n| n.handle.clone()) {
            self.toolkit.focus_window(&h);
        }
    }

    fn set_native_window_title(&mut self, root: RNode, title: &str) {
        if let Some(h) = self.nodes.get(root).and_then(|n| n.handle.clone()) {
            self.toolkit.set_window_title(&h, title);
        }
    }

    fn apply_window(&mut self, root: RNode, change: &day_spec::WindowChange) {
        if let Some(h) = self.nodes.get(root).and_then(|n| n.handle.clone()) {
            self.toolkit.apply_window(&h, change);
        }
    }

    fn set_dock_menu(&mut self, items: &[day_spec::MenuItem]) {
        self.toolkit.set_dock_menu(items);
    }

    fn set_status_items(&mut self, items: &[day_spec::StatusItemSpec]) {
        self.toolkit.set_status_items(items);
    }

    fn set_app_progress(&mut self, progress: day_spec::AppProgress) {
        self.toolkit.set_app_progress(progress);
    }

    fn set_dock_visible(&mut self, visible: bool) {
        self.toolkit.set_dock_visible(visible);
    }

    fn set_keep_running(&mut self, keep: bool) {
        self.toolkit.set_keep_running(keep);
    }

    fn native_window_frame(&self, root: RNode) -> Option<day_spec::Rect> {
        let h = self.nodes.get(root).and_then(|n| n.handle.clone())?;
        self.toolkit.window_frame(&h)
    }

    fn monitors(&self) -> Vec<day_spec::Monitor> {
        self.toolkit.monitors()
    }

    fn set_launcher_shortcuts(&mut self, shortcuts: &[day_spec::LauncherShortcut]) {
        self.toolkit.set_launcher_shortcuts(shortcuts);
    }

    fn snapshot_of(&mut self, root: RNode) -> Result<Vec<u8>, String> {
        if self.windows[0].root == root {
            return self.toolkit.snapshot_window();
        }
        match self.nodes.get(root).and_then(|n| n.handle.clone()) {
            Some(h) => self.toolkit.snapshot_window_of(&h),
            None => Err("window is gone".into()),
        }
    }

    fn install_list(&mut self, node: RNode, driver: crate::list::ListDriver) {
        let driver = Rc::new(driver);
        let sections = driver
            .sections
            .is_some()
            .then(|| crate::list::register_sections(node, driver.clone()));
        self.lists.insert(
            node,
            crate::list::ListState {
                driver: driver.clone(),
                cells: HashMap::new(),
                sections: sections.clone(),
            },
        );
        let source = crate::list::make_source(node, driver, sections);
        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
            self.toolkit.attach_list(&handle, source);
        }
    }

    fn list_prepare_cell(
        &mut self,
        node: RNode,
        key: usize,
        cell: RawHandle,
        header: bool,
    ) -> crate::list::CellStep {
        // A cell that held the other kind (a header's cell reused for an item, or the reverse)
        // cannot be rebound: its subtree is the wrong piece. Dispose it as a release would and
        // build afresh in the same native cell.
        if let Some(state) = self.lists.get_mut(&node)
            && state.cells.get(&key).is_some_and(|b| b.header != header)
            && let Some(old) = state.cells.remove(&key)
        {
            old.scope.dispose();
            self.remove_subtree_impl(old.anchor);
        }
        if let Some(state) = self.lists.get_mut(&node)
            && let Some(bound) = state.cells.get_mut(&key)
        {
            bound.active = true;
            let (rebind, anchor, pinned) = (bound.rebind.clone(), bound.anchor, bound.pinned);
            // A pooled cell coming back: its ids were parked when it was recycled, and a
            // rebind to unchanged content would never re-set them (see `parked_id`). A pinned
            // header copy keeps its ids parked.
            if !pinned {
                self.restore_subtree_ids(anchor);
            }
            return crate::list::CellStep::Rebind { rebind, anchor };
        }
        // First use of this cell: adopt the native cell and anchor a fresh subtree under it,
        // inside the platform's row margins (docs/list.md "Row metrics").
        let mut metrics = match self.nodes.get(node).and_then(|n| n.handle.clone()) {
            Some(list) => self.toolkit.list_row_metrics(&list),
            None => day_spec::RowMetrics::default(),
        };
        // A section header lines up with the rows (the side insets) but is no row: its own
        // padding sets its height, and the platform's least row height is a touch target's,
        // which a header is not.
        if header {
            metrics.insets.top = 0.0;
            metrics.insets.bottom = 0.0;
            metrics.min_height = 0.0;
        }
        let handle = self.toolkit.adopt(cell);
        let anchor = self.create_cell_anchor(
            handle,
            Scope::child(),
            Rc::new(crate::layout::CellMetrics(metrics)),
        );
        crate::list::CellStep::Build { anchor }
    }

    fn list_store_cell(
        &mut self,
        node: RNode,
        key: usize,
        anchor: RNode,
        built: crate::list::BuiltRow,
        header: bool,
    ) {
        if let Some(state) = self.lists.get_mut(&node) {
            state.cells.insert(
                key,
                crate::list::BoundCell {
                    anchor,
                    active: true,
                    scope: built.scope,
                    rebind: built.rebind,
                    native_width: None,
                    laid_width: None,
                    laid_height: None,
                    header,
                    pinned: false,
                },
            );
        }
    }

    fn list_layout_cell(&mut self, node: RNode, key: usize) {
        // The width the backend last granted this cell, once it has said so (GtkListView's themed
        // `row` node pads the cell, so it is narrower than the list); until then the list's own
        // content width, which is right wherever the cell IS the row. Every path that re-lays a
        // row (a rebind, the dirty-cell sweep, a data change) comes through here, so a width
        // the backend corrected once stays corrected.
        let native = self
            .lists
            .get(&node)
            .and_then(|s| s.cells.get(&key))
            .and_then(|c| c.native_width);
        let width = native.unwrap_or_else(|| {
            self.nodes
                .get(node)
                .and_then(|n| n.last_native_frame)
                .map(|f| f.size.width)
                .unwrap_or(self.windows[0].size.width)
        });
        self.layout_list_cell_at(node, key, width);
    }

    fn list_layout_cell_width(&mut self, node: RNode, key: usize, width: f64) {
        // The backend's word on the cell's width (`ListSource::layout_cell`), remembered so the
        // next first-approximation pass does not undo it.
        if let Some(cell) = self
            .lists
            .get_mut(&node)
            .and_then(|s| s.cells.get_mut(&key))
        {
            cell.native_width = Some(width);
        }
        self.layout_list_cell_at(node, key, width);
    }

    fn list_cell_height(&self, node: RNode, key: usize) -> f64 {
        self.lists
            .get(&node)
            .and_then(|s| s.cells.get(&key))
            .filter(|b| b.active)
            .and_then(|b| b.laid_height)
            .unwrap_or(0.0)
    }

    fn list_cell_keys(&self, node: RNode) -> Vec<usize> {
        self.lists
            .get(&node)
            .map(|s| {
                s.cells
                    .iter()
                    .filter_map(|(key, cell)| cell.active.then_some(*key))
                    .collect()
            })
            .unwrap_or_default()
    }

    fn list_reload(&mut self, node: RNode) {
        if let Some(map) = self.lists.get(&node).and_then(|s| s.sections.as_ref()) {
            map.invalidate();
        }
        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
            self.toolkit.update(
                &handle,
                kinds::LIST,
                &day_spec::props::ListPatch::Reload as &dyn Any,
                None,
            );
        }
    }

    fn list_splice(&mut self, node: RNode, deltas: Vec<day_spec::props::RowDelta>) {
        // A sectioned list's deltas name items, and the headers around them move too: the
        // host re-queries instead (docs/list.md "Sections").
        if self.lists.get(&node).is_some_and(|s| s.sections.is_some()) {
            self.list_reload(node);
            return;
        }
        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
            self.toolkit.update(
                &handle,
                kinds::LIST,
                &day_spec::props::ListPatch::Splice(deltas) as &dyn Any,
                None,
            );
        }
    }

    fn set_undo_state(&mut self, state: &day_spec::UndoState) {
        self.toolkit.set_undo_state(state);
    }

    fn set_edit_state(&mut self, state: &day_spec::EditState) {
        self.toolkit.set_edit_state(state);
    }

    fn modifiers(&mut self) -> day_spec::Modifiers {
        self.toolkit.modifiers()
    }

    fn list_scroll_to_end(&mut self, node: RNode) {
        // Empty list: nothing to scroll to (the row count is read straight from the piece's
        // snapshot, with no tree access, so this guard is cheap and backend-independent).
        if self.lists.get(&node).map(|s| (s.driver.len)()).unwrap_or(0) == 0 {
            return;
        }
        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
            self.toolkit.update(
                &handle,
                kinds::LIST,
                &day_spec::props::ListPatch::ScrollToEnd as &dyn Any,
                None,
            );
        }
    }

    fn list_scroll_to_row(&mut self, node: RNode, row: usize) {
        let len = self.lists.get(&node).map(|s| (s.driver.len)()).unwrap_or(0);
        if len == 0 {
            return;
        }
        let mut row = row.min(len - 1);
        if let Some(map) = self.lists.get(&node).and_then(|s| s.sections.as_ref()) {
            row = map.display_of(row).unwrap_or(row);
        }
        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
            self.toolkit.update(
                &handle,
                kinds::LIST,
                &day_spec::props::ListPatch::ScrollToRow(row) as &dyn Any,
                None,
            );
        }
    }

    fn list_set_editing(&mut self, node: RNode, on: bool) {
        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
            self.toolkit.update(
                &handle,
                kinds::LIST,
                &day_spec::props::ListPatch::Editing(on) as &dyn Any,
                None,
            );
        }
    }

    fn list_set_selected(&mut self, node: RNode, rows: Vec<usize>) {
        let rows = match self.lists.get(&node).and_then(|s| s.sections.as_ref()) {
            Some(map) => rows.iter().filter_map(|i| map.display_of(*i)).collect(),
            None => rows,
        };
        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
            self.toolkit.update(
                &handle,
                kinds::LIST,
                &day_spec::props::ListPatch::Selected(rows) as &dyn Any,
                None,
            );
        }
    }

    fn list_driver(&mut self, node: RNode) -> Option<std::rc::Rc<crate::list::ListDriver>> {
        self.lists.get(&node).map(|s| s.driver.clone())
    }

    fn install_tree(&mut self, node: RNode, driver: crate::tree_driver::TreeDriver) {
        let driver = Rc::new(driver);
        self.trees.insert(
            node,
            crate::tree_driver::TreeState {
                driver: driver.clone(),
                cells: HashMap::new(),
            },
        );
        let source = crate::tree_driver::make_tree_source(node, driver);
        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
            self.toolkit.attach_tree(&handle, source);
        }
    }

    fn tree_prepare_cell(
        &mut self,
        node: RNode,
        key: usize,
        cell: RawHandle,
    ) -> crate::tree_driver::TreeCellStep {
        if let Some(state) = self.trees.get(&node)
            && let Some(bound) = state.cells.get(&key)
        {
            let (rebind, anchor) = (bound.rebind.clone(), bound.anchor);
            // Same rule as `list_prepare_cell`: give a pooled cell its parked ids back.
            self.restore_subtree_ids(anchor);
            return crate::tree_driver::TreeCellStep::Rebind { rebind, anchor };
        }
        // First use of this cell: adopt the native cell and anchor a fresh subtree under it.
        // The centering anchor layout, not the list's PassThrough: tree rows have a fixed
        // Uniform height and content that hugs, so the content centers in the cell.
        let handle = self.toolkit.adopt(cell);
        let anchor =
            self.create_cell_anchor(handle, Scope::child(), Rc::new(crate::layout::CellCenter));
        crate::tree_driver::TreeCellStep::Build { anchor }
    }

    fn tree_store_cell(
        &mut self,
        node: RNode,
        key: usize,
        anchor: RNode,
        built: crate::tree_driver::TreeBuiltRow,
    ) {
        if let Some(state) = self.trees.get_mut(&node) {
            state.cells.insert(
                key,
                crate::tree_driver::TreeBoundCell {
                    anchor,
                    scope: built.scope,
                    rebind: built.rebind,
                    native_width: None,
                    native_height: None,
                    laid_width: None,
                    laid_height: None,
                },
            );
        }
    }

    fn tree_layout_cell(&mut self, node: RNode, key: usize) {
        // The width the backend last granted this cell, once it has said so (indentation makes
        // every tree cell's width its own); until then the tree's own content width. Every path
        // that re-lays a row comes through here, so a width the backend corrected stays corrected.
        let native = self
            .trees
            .get(&node)
            .and_then(|s| s.cells.get(&key))
            .and_then(|c| c.native_width);
        let width = native.unwrap_or_else(|| {
            self.nodes
                .get(node)
                .and_then(|n| n.last_native_frame)
                .map(|f| f.size.width)
                .unwrap_or(self.windows[0].size.width)
        });
        self.layout_tree_cell_at(node, key, width);
    }

    fn tree_layout_cell_width(&mut self, node: RNode, key: usize, width: f64) {
        // The backend's word on the cell's width (`TreeSource::layout_cell`), remembered so the
        // next first-approximation pass does not undo it.
        if let Some(cell) = self
            .trees
            .get_mut(&node)
            .and_then(|s| s.cells.get_mut(&key))
        {
            cell.native_width = Some(width);
        }
        self.layout_tree_cell_at(node, key, width);
    }

    fn tree_cell_height(&self, node: RNode, key: usize) -> f64 {
        self.trees
            .get(&node)
            .and_then(|s| s.cells.get(&key))
            .and_then(|b| b.laid_height)
            .unwrap_or(0.0)
    }

    fn tree_layout_cell_size(&mut self, node: RNode, key: usize, size: Size) {
        let changed = self
            .trees
            .get_mut(&node)
            .and_then(|s| s.cells.get_mut(&key))
            .and_then(|cell| {
                let changed = cell.native_height != Some(size.height);
                cell.native_height = Some(size.height);
                changed.then_some(cell.anchor)
            });
        if let Some(anchor) = changed {
            self.invalidate_subtree(anchor);
        }
        self.tree_layout_cell_width(node, key, size.width);
    }

    fn tree_recycle_cell(&mut self, node: RNode, key: usize) {
        let Some(anchor) = self
            .trees
            .get(&node)
            .and_then(|s| s.cells.get(&key))
            .map(|b| b.anchor)
        else {
            return;
        };
        self.clear_subtree_ids(anchor);
    }

    fn list_recycle_cell(&mut self, node: RNode, key: usize) {
        let Some(anchor) = self
            .lists
            .get_mut(&node)
            .and_then(|s| s.cells.get_mut(&key))
            .map(|b| {
                b.active = false;
                // The next row this cell shows is laid afresh by its `bind_row`, and the host
                // reads `cell_height` right after; a height left over from the previous row
                // would make that first layout look like a change and raise a spurious
                // `RowSizeInvalidated`.
                b.laid_height = None;
                b.anchor
            })
        else {
            return;
        };
        self.clear_subtree_ids(anchor);
    }

    fn list_release_cell(&mut self, node: RNode, key: usize) {
        // Unknown cell (never bound, or released twice): nothing to do.
        let Some(cell) = self.lists.get_mut(&node).and_then(|s| s.cells.remove(&key)) else {
            return;
        };
        // The same teardown `collect_and_release` gives every cell when the list goes
        // (docs/list.md): the row's reactive graph, then its nodes. The anchor's own handle
        // is the host's cell and is only dropped, never queued for release (`LIST_CELL`);
        // the handles under it are Day's and go through the release queue as usual.
        cell.scope.dispose();
        self.remove_subtree_impl(cell.anchor);
    }

    fn list_pin_cell(&mut self, node: RNode, key: usize) {
        let Some(anchor) = self
            .lists
            .get_mut(&node)
            .and_then(|s| s.cells.get_mut(&key))
            .map(|b| {
                b.pinned = true;
                b.anchor
            })
        else {
            return;
        };
        self.clear_subtree_ids(anchor);
    }

    fn tree_reload(&mut self, node: RNode) {
        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
            self.toolkit.update(
                &handle,
                kinds::TREE,
                &day_spec::props::TreePatch::Reload as &dyn Any,
                None,
            );
        }
    }

    fn tree_set_expanded(&mut self, node: RNode, token: u64, expanded: bool) {
        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
            self.toolkit.update(
                &handle,
                kinds::TREE,
                &day_spec::props::TreePatch::Expand(token, expanded) as &dyn Any,
                None,
            );
        }
    }

    fn tree_set_selected(&mut self, node: RNode, tokens: Vec<u64>) {
        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
            self.toolkit.update(
                &handle,
                kinds::TREE,
                &day_spec::props::TreePatch::Selected(tokens) as &dyn Any,
                None,
            );
        }
    }

    fn tree_reveal(&mut self, node: RNode, token: u64) {
        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
            self.toolkit.update(
                &handle,
                kinds::TREE,
                &day_spec::props::TreePatch::Reveal(token) as &dyn Any,
                None,
            );
        }
    }

    fn tree_driver(&mut self, node: RNode) -> Option<std::rc::Rc<crate::tree_driver::TreeDriver>> {
        self.trees.get(&node).map(|s| s.driver.clone())
    }

    fn set_drag_source(&mut self, node: RNode, source: day_spec::transfer::Source) {
        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
            self.toolkit.set_drag_source(&handle, source);
        }
    }
    fn set_drop_target(&mut self, node: RNode, target: day_spec::transfer::Target) {
        if let Some(handle) = self.nodes.get(node).and_then(|n| n.handle.clone()) {
            self.toolkit.set_drop_target(&handle, target);
        }
    }
    fn set_context_menu_fn(&mut self, node: RNode, f: day_spec::ContextMenuFn) {
        // Match static menus: padding/frame decorators are layout-only, but the provider
        // must be installed on the native root beneath them, not silently discarded.
        let target = if self.nodes.get(node).is_some_and(|n| n.handle.is_some()) {
            Some(node)
        } else {
            let mut roots = Vec::new();
            self.native_descendants(node, &mut roots);
            roots.first().copied()
        };
        let Some(target) = target else {
            log::warn!("context_menu_fn on a subtree with no native view — menu dropped");
            return;
        };
        let model = ContextMenuModel::Provider(f.clone());
        self.context_menus.insert(node, model.clone());
        self.context_menus.insert(target, model);
        if let Some(handle) = self.nodes.get(target).and_then(|n| n.handle.clone()) {
            self.toolkit
                .set_context_menu_fn(&handle, rnode_to_id(target), f);
        }
    }

    fn context_menu_of(&mut self, node: RNode) -> Option<day_spec::ContextMenuFn> {
        // The element a script names may sit above or below the node the menu landed on (an id
        // on a wrapper, a menu on the label inside it): the node itself, then its ancestors.
        let mut cur = node;
        loop {
            if let Some(model) = self.context_menus.get(&cur) {
                return Some(match model {
                    ContextMenuModel::Items(items) => {
                        let items = items.clone();
                        Rc::new(move |_| items.clone())
                    }
                    ContextMenuModel::Provider(f) => f.clone(),
                });
            }
            // The root (and a list cell's anchor) is its own parent, or has a null one,
            // which the lookup misses.
            let parent = self.nodes.get(cur)?.parent;
            if parent == cur {
                return None;
            }
            cur = parent;
        }
    }
}

// ---------------------------------------------------------------------------
// Thread-local tree + event pump
// ---------------------------------------------------------------------------

day_reactive::tls_slots! {
    tree;
    /// The installed tree. `ManuallyDrop` so the thread-local destructor never drops it: the
    /// tree owns the toolkit's native widgets, and dropping those at thread exit runs the
    /// toolkit's callbacks (a GtkListBox being emptied calls its header func) against
    /// thread-locals that may already be gone — Rust destroys them in an order nobody controls,
    /// and a panic inside a C trampoline cannot unwind, so the process aborted on the way out
    /// of a clean exit. At process exit the OS reclaims the widgets; nothing in their drop
    /// matters. [`uninstall_tree`] (tests, Android's remount) still drops the tree explicitly,
    /// while every thread-local is alive.
    static TREE: std::mem::ManuallyDrop<RefCell<Option<Box<dyn TreeOps>>>> =
        const { std::mem::ManuallyDrop::new(RefCell::new(None)) };
    static EVENTS: RefCell<VecDeque<(NodeId, Event)>> = const { RefCell::new(VecDeque::new()) };
    static PUMP_PENDING: Cell<bool> = const { Cell::new(false) };
    static PUMP_ACTIVE: Cell<bool> = const { Cell::new(false) };
    /// Posted main-thread closures that arrived while the tree was borrowed and so could
    /// not run (see [`run_posted_or_defer`]). Drained at the next safe point, in order.
    static DEFERRED: RefCell<Vec<Box<dyn FnOnce() + Send>>> = const { RefCell::new(Vec::new()) };
    /// The event observer installed by [`set_event_observer`] and consulted by [`enqueue_events`].
    /// `Rc`, not `Box`, so the handle can be cloned out and invoked with no borrow held (the
    /// observer may safely re-enter Day to read the tree or stop recording).
    static EVENT_OBSERVER: RefCell<Option<Rc<EventObserver>>> = const { RefCell::new(None) };
    /// Monotonic pump counter, bumped once per [`pump_events_inner`]. The recorder ages its
    /// coalescing candidate by it: a tap folds into a navigation caused in the same or the next
    /// pump (a signal-bound sidebar remount settles one pump late), but never a later, unrelated
    /// navigation.
    static PUMP_GEN: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };

    /// The node that last reported gaining focus, cleared when it reports losing it.
    static FOCUSED: std::cell::Cell<Option<RNode>> = const { std::cell::Cell::new(None) };
}

pub fn install_tree(tree: Box<dyn TreeOps>) {
    // A fresh mount starts with no route hosts; nav()/tabs() re-register during build.
    crate::nav::clear_controllers();
    TREE.with(|t| *t.borrow_mut() = Some(tree));
    // Read the export answers now, while the tree is free, so a context menu built inside a
    // later borrow finds them (`image::canvas_exports`).
    let _ = crate::image::canvas_exports();
}

/// Tear the current mount down so the app can be built again in the same process
/// (docs/settings.md "Appearance on Android").
///
/// Android is the one platform that needs this: an activity recreation (the mechanism of a
/// light/dark switch, and the side effect of any configuration change the manifest does not
/// claim) destroys the window and calls the app's entry point a second time.
/// Everywhere else launch happens exactly once by construction.
///
/// What this resets is everything an app's `root()` registers, because `root()` is about to run
/// again and register it all a second time: the window registry and its content scopes, the
/// navigation controllers, the per-window ambient signals, the lifecycle handlers, the menu
/// actions. What it leaves alone is state that lives on the root reactive scope
/// (`Signal::global`, `Ambient::app()`), which is exactly the state an app expects to outlive a
/// window, and which is what makes a recreation cheap rather than a cold start (docs/state.md).
///
/// One thing it cannot reset is an app's own `std::sync::Once`: a one-time install guarded that
/// way will not re-run, so a `Once` in `root()` is the pattern to avoid on Android.
pub fn prepare_remount() {
    // Drop in-flight reactive work first. Anything already queued was scheduled by the mount
    // that is about to be disposed, and running it afterwards reads signals that no longer
    // exist ("read of disposed Signal"). This also re-roots the scope stack, which matters more
    // than it looks: left pointing at a disposed scope, every `Signal::new` in the rebuild is
    // born dead and the new tree panics on its own state.
    day_reactive::recover_from_panic();
    uninstall_tree();
    // Tearing the old tree down can schedule cleanup of its own; go back to idle before rebuilding.
    day_reactive::recover_from_panic();
    crate::lifecycle::reset_handlers();
    crate::menu::reset_menus();
}

/// Whether a tree is installed on this thread, i.e. whether the app has already launched.
///
/// The one caller that is not a test is Android's `nativeStart`, which an activity recreation can
/// re-enter after the app is already up (docs/settings.md "Appearance on Android"). Everywhere
/// else launch happens exactly once by construction.
pub fn is_mounted() -> bool {
    TREE.with(|t| t.borrow().is_some())
}

/// Reset the thread-local tree + queues (tests).
pub fn uninstall_tree() {
    // A decode parked on the tree that is going away would wait forever (docs/images.md).
    crate::image::reset();
    crate::nav::clear_controllers();
    crate::windows::reset_windows();
    crate::status::reset_status();
    // Per-window signals are keyed by root node, and roots repeat across trees on this thread;
    // a stale entry would hand the next tree the previous one's size class.
    crate::reset_ambient();
    TREE.with(|t| *t.borrow_mut() = None);
    EVENTS.with(|e| e.borrow_mut().clear());
    PUMP_PENDING.with(|c| c.set(false));
    // The event observer (§14.6) is thread-local state too; a test that installed one must not
    // leak it into the next tree on this thread.
    EVENT_OBSERVER.with(|o| *o.borrow_mut() = None);
}

/// Access the installed tree. Tree methods never run user code, so nesting cannot occur
/// while a borrow is held; if events were queued during the call, they are pumped after
/// the borrow is released (the "safe point" of §3.3).
pub fn with_tree<R>(f: impl FnOnce(&mut dyn TreeOps) -> R) -> R {
    let r = TREE.with(|t| {
        let mut opt = t.borrow_mut();
        let ops = opt.as_mut().expect("day: no tree installed on this thread");
        f(ops.as_mut())
    });
    if PUMP_PENDING.with(|c| c.replace(false)) {
        pump_events();
    }
    run_deferred();
    r
}

/// Run a posted main-thread closure now, or hold it for the next safe point when the tree is
/// borrowed. Tree methods never run user code, but a backend may pump its native message
/// loop from inside one (XAML's `open_window` waits for the new root to load; a modal native
/// loop can nest anywhere), and a closure that loop dispatches would re-enter [`with_tree`]
/// on the borrowed tree and panic ("RefCell already borrowed"). Held closures run at the end
/// of the outermost `with_tree`, in arrival order, each contained like any posted task.
pub(crate) fn run_posted_or_defer(f: Box<dyn FnOnce() + Send>) {
    let borrowed = TREE.with(|t| t.try_borrow_mut().is_err());
    if borrowed {
        DEFERRED.with(|d| d.borrow_mut().push(f));
    } else {
        crate::contain_posted_panic(f);
    }
}

/// The safe-point drain for [`run_posted_or_defer`]: called once the borrow is released. A
/// drained closure may defer more (it can borrow the tree and nest a pump of its own), so
/// this loops until the queue stays empty; each batch is taken out before it runs.
fn run_deferred() {
    loop {
        let batch = DEFERRED.with(|d| std::mem::take(&mut *d.borrow_mut()));
        if batch.is_empty() {
            return;
        }
        for f in batch {
            crate::contain_posted_panic(f);
        }
    }
}

/// Query the active toolkit's support for a capability (docs). Lets app/piece code adapt its
/// content to the backend, e.g. a page can skip a title the native nav already shows in a header
/// (`Cap::NavHeader`), or pick a presentation from `Cap::NavSplit`.
pub fn capability(cap: day_spec::Cap) -> day_spec::Support {
    with_tree(|t| t.capability(cap))
}

/// Open `url` in the platform's default handler (system browser for `http(s)`, mail client for
/// `mailto:`, …). The function behind the [`link`](/api/day_pieces/fn.link.html) piece; call it
/// directly from a tap handler for a custom affordance. Fire and forget: no result, unopenable
/// URLs are ignored by the backend.
pub fn open_url(url: &str) {
    // While `day test` runs the app's cases, a link is recorded for `assert_opened_url` and
    // nothing opens: a test run must not launch the machine's browser (docs/testing.md).
    if crate::conformance::intercept_open_url(url) {
        return;
    }
    with_tree(|t| t.open_url(url));
}

/// Speak `text` through the screen reader without moving its focus (docs/accessibility.md):
/// the outcome of an action the user cannot otherwise learn about ("Saved", "3 results"). The
/// sentence waits for whatever is being read to finish; [`announce_urgent`] interrupts it.
/// Nothing happens when no screen reader is running, and nothing happens on a toolkit that
/// answers [`Cap::Announce`](day_spec::Cap::Announce) with `Unsupported`.
pub fn announce(text: &str) {
    crate::conformance::note_announcement(text);
    with_tree(|t| t.announce(text, false));
}

/// [`announce`], interrupting what the screen reader is saying: an error, or a change that
/// cannot wait.
pub fn announce_urgent(text: &str) {
    crate::conformance::note_announcement(text);
    with_tree(|t| t.announce(text, true));
}

/// Whether the current toolkit can present a native sharing chooser.
pub fn share_support() -> Support {
    with_tree(|t| t.share_support())
}
/// Present a native chooser for a URL. Call directly from user activation (required on web).
/// Returns false if unavailable or presentation failed; cancellation is not an error and no
/// completion is implied. The caller owns any explicitly labeled fallback.
pub fn share_url(url: &str, title: &str) -> bool {
    with_tree(|t| t.share_url(url, title))
}

/// Query current system associations on the UI thread. macOS AppKit implements all query
/// kinds; other backends return `Unsupported`. No application is launched by discovery.
pub fn application_handlers(
    query: &day_spec::applications::HandlerQuery,
) -> Result<day_spec::applications::ApplicationHandlers, day_spec::applications::ApplicationError> {
    with_tree(|t| t.application_handlers(query))
}

/// The OS-chosen browser for HTTPS links, read afresh rather than cached by Day.
pub fn default_browser()
-> Result<Option<day_spec::applications::Application>, day_spec::applications::ApplicationError> {
    application_handlers(&day_spec::applications::HandlerQuery::Scheme(
        "https".into(),
    ))
    .map(|h| h.default)
}

/// Open a URL or file URL in a chosen application. Await on the UI executor. Success means
/// the OS accepted the open request; tab/window presentation belongs to the receiving app.
pub async fn open_url_with_application(
    url: &str,
    application: &str,
) -> Result<(), day_spec::applications::ApplicationError> {
    let (send, receive) = day_async::oneshot();
    with_tree(|t| {
        t.open_url_with_application(url, application, Box::new(move |result| send.send(result)))
    });
    receive
        .await
        .unwrap_or(Err(day_spec::applications::ApplicationError::LaunchFailed))
}

/// Tell layout that a node's intrinsic size may have changed. For tweaks (docs/tweaks.md):
/// after a native call that alters a widget's preferred size (fonts, tick marks, bezel styles),
/// the measure cache along the node's path must be invalidated, since Day can't see native
/// mutations it didn't make. Relayout runs at the next turn boundary as usual. No-op on a
/// disposed node.
pub fn invalidate_size(node: RNode) {
    with_tree(|t| {
        t.mark_needs_measure(node);
        t.mark_layout_dirty();
    });
}

/// Like `with_tree`, but returns `None` instead of panicking when the tree can't be entered:
/// already borrowed, or not installed yet. A snapshot (`TreeOps::snapshot`) holds the borrow
/// while the backend draws the window synchronously, and that draw can re-enter Day through a
/// native callback, e.g. a lazy list's `viewForRow`/`connect_bind`/`cellForRow` firing during
/// `cacheDisplayInRect`. And platform style callbacks can fire before `install_tree`, e.g.
/// GTK's StyleManager emits a `dark` notify while `startup` applies a forced `DAY_THEME`
/// scheme, before `activate` mounts the tree; a panic there unwinds into a C signal trampoline
/// and aborts the process. Such callbacks use this and skip their work; the next real
/// layout (or the signal's first post-mount read) catches up.
pub fn try_with_tree<R>(f: impl FnOnce(&mut dyn TreeOps) -> R) -> Option<R> {
    let r = TREE.with(|t| {
        let mut opt = t.try_borrow_mut().ok()?;
        let ops = opt.as_mut()?;
        Some(f(ops.as_mut()))
    });
    if r.is_some() {
        if PUMP_PENDING.with(|c| c.replace(false)) {
            pump_events();
        }
        run_deferred();
    }
    r
}

/// [`try_with_tree`] without the pump on the way out, for work that is itself part of a pump,
/// or that raises no events (`release_image`), where a nested pump would be wrong or wasted.
pub(crate) fn with_tree_if_free<R>(f: impl FnOnce(&mut dyn TreeOps) -> R) -> Option<R> {
    TREE.with(|t| {
        let mut opt = t.try_borrow_mut().ok()?;
        let ops = opt.as_mut()?;
        Some(f(ops.as_mut()))
    })
}

/// Whether no tree is installed, as distinct from one that is merely borrowed right now, which
/// this answers `false` for. [`is_mounted`] cannot tell the two apart without panicking.
pub(crate) fn tree_absent() -> bool {
    // Bitmap handles can outlive the entire core TLS root at process/thread exit.
    TREE.try_with(|t| t.try_borrow().map(|o| o.is_none()).unwrap_or(false))
        .unwrap_or(true)
}

/// Ask for a pump at the next safe point (the end of the current `with_tree`), for work queued
/// while the tree was borrowed.
pub(crate) fn request_pump() {
    PUMP_PENDING.with(|c| c.set(true));
}

pub fn has_tree() -> bool {
    // Native resize/layout callbacks can ask while a Toolkit call already borrows the tree.
    // A busy tree is installed, not absent; this presence probe must not borrow it again.
    !tree_absent()
}

/// The enqueue-only event sink installed into every backend (§8.3). May be invoked
/// re-entrantly from inside any Toolkit method; dispatch happens at the next safe point.
pub fn enqueue_event(id: NodeId, ev: Event) {
    enqueue_events([(id, ev)]);
}

/// The toolkit's event sink: [`enqueue_event`], after a sectioned list's row events are
/// translated from the host's display rows to the app's items (docs/list.md "Sections").
/// Everything else (dayscript, probes, day-core's own reports) already speaks items and
/// enqueues directly.
pub(crate) fn enqueue_native_event(id: NodeId, ev: Event) {
    if let Some(ev) = crate::list::translate_native_event(id, ev) {
        enqueue_event(id, ev);
    }
}

/// Enqueue several events into one drain before dispatching. Backends that observe a focus
/// move at a single point (Qt's `focusChanged(old, new)`, an AppKit first-responder change)
/// deliver the loss+gain pair through this so the pump can dispatch the gain first and a
/// shared group signal never passes through `None` (docs/focus.md).
pub fn enqueue_events(evs: impl IntoIterator<Item = (NodeId, Event)>) {
    // Recording/telemetry hook (§14.6): when an observer is installed, let it see every event in
    // the exact order and form the app is about to receive, before it is dispatched,
    // so it observes precisely what the app receives. This is the single point every backend
    // funnels native events through, so the observer needs no per-toolkit code. The handle is
    // cloned out first (a cheap `Rc` bump) so no thread-local borrow is held across the call: the
    // observer may re-enter Day (resolve an id via `id_of`, or even remove itself to stop
    // recording) without a borrow conflict. A `None` observer costs one `Option` check and takes
    // the original zero-copy `extend` path.
    let observer = EVENT_OBSERVER.with(|o| o.borrow().clone());
    match observer {
        Some(obs) => {
            let batch: Vec<(NodeId, Event)> = evs.into_iter().collect();
            for (id, ev) in &batch {
                obs(*id, ev);
            }
            EVENTS.with(|e| e.borrow_mut().extend(batch));
        }
        None => EVENTS.with(|e| e.borrow_mut().extend(evs)),
    }
    let tree_free = TREE.with(|t| t.try_borrow_mut().is_ok());
    if tree_free {
        pump_events();
    } else {
        PUMP_PENDING.with(|c| c.set(true));
    }
}

/// The current pump generation (see `PUMP_GEN`). Read by the recorder's nav coalescing.
pub fn pump_generation() -> u64 {
    PUMP_GEN.with(|g| g.get())
}

/// Install (or clear, with `None`) an observer that sees every event day-core dispatches, in queue
/// order, at the one point every backend funnels native events through ([`enqueue_events`],
/// §8.3), before the event reaches the app, so it observes exactly what the app receives. This
/// is the recording/telemetry hook behind [`day::record`](../day_script/record/index.html)
/// (§14.6): a higher layer captures user actions into a replayable dayscript without touching
/// any of the backends. Main-thread only; a `None` observer adds no cost to the event path. The
/// boxed closure is adopted into an `Rc` internally so [`enqueue_events`] can call it with no
/// borrow held.
pub fn set_event_observer(observer: Option<Box<EventObserver>>) {
    EVENT_OBSERVER.with(|o| *o.borrow_mut() = observer.map(Rc::from));
}

/// Resolve a dispatched [`NodeId`] back to the app-authored `.id()` string that named its node
/// (`find_by_id`'s inverse, §5.5), or `None` for an id-less node or one no longer in the tree. The
/// recorder ([`day::record`](../day_script/record/index.html), §14.6) calls this from inside its
/// event observer to label a tap/input with the id an app would target in a dayscript step.
/// Borrow-safe: returns `None` rather than panicking if the tree is momentarily borrowed by a
/// re-entrant backend call.
pub fn id_of(node: NodeId) -> Option<String> {
    try_with_tree(|t| t.node_id(id_to_rnode(node))).flatten()
}

/// A human-readable label for a node, for annotating a recorded script (§14.6): the accessibility
/// label if one is set (`.a11y(label = …)`, the localized string the screen reader speaks),
/// otherwise the control's own visible text. `None` when the node carries neither.
pub fn label_of(node: NodeId) -> Option<String> {
    try_with_tree(|t| {
        let rnode = id_to_rnode(node);
        let a11y = t
            .node_a11y(rnode)
            .and_then(|a| a.label)
            .filter(|s| !s.is_empty());
        a11y.or_else(|| {
            t.node_probe(rnode)
                .map(|p| p.text)
                .filter(|s| !s.is_empty())
        })
    })
    .flatten()
}

/// Dispatch queued native events from the backend queue, containing any panic. Native event
/// callbacks reach Day through `extern "C"` signal trampolines (GTK's `value_changed_trampoline`,
/// Qt's event filters, …) that abort the process on unwind (`panic_cannot_unwind`). A panic in a
/// Day event handler or its reactive drain (e.g. the reactive-cycle assertion firing during a
/// slider drag) would therefore `SIGABRT` the whole app instead of surfacing. Catch it at this
/// single backend-agnostic boundary, log it (the message carries the offending effect's source
/// location), and reset the runtime so the app keeps running (degraded) rather than crashing.
pub fn pump_events() {
    // Native mutations in a handler can enqueue focus, value, or dismissal
    // events. Finish that handler before dispatching them: nested dispatch can
    // dispose the signals still used by its remaining binding writes.
    if PUMP_ACTIVE.with(|active| active.replace(true)) {
        return;
    }
    struct PumpGuard;
    impl Drop for PumpGuard {
        fn drop(&mut self) {
            PUMP_ACTIVE.with(|active| active.set(false));
        }
    }
    let _guard = PumpGuard;
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        loop {
            pump_events_inner();
            // flush_sync and route notifications may themselves enqueue events.
            // Drain these after their current reactions finish, before returning.
            if EVENTS.with(|events| events.borrow().is_empty()) {
                break;
            }
        }
    }));
    if let Err(payload) = result {
        let msg = payload
            .downcast_ref::<&str>()
            .map(|s| (*s).to_string())
            .or_else(|| payload.downcast_ref::<String>().cloned())
            .unwrap_or_else(|| "unknown panic".to_string());
        log::warn!(
            "a native event handler panicked and was contained — the app continues, but \
             reactive/UI state may be inconsistent until the next interaction. Cause: {msg}"
        );
        // Drop the in-flight event batch and reset drain state so the runtime isn't wedged.
        EVENTS.with(|e| e.borrow_mut().clear());
        PUMP_PENDING.with(|c| c.set(false));
        day_reactive::recover_from_panic();
        crate::notify_contained_panic();
    }
}

fn pump_events_inner() {
    // The tree borrow has ended by now: run the image releases that arrived while it was held.
    crate::image::flush_deferred_releases();
    // A new pump: bump the generation, then record any route change that a previous pump left
    // pending (a signal-bound sidebar/stack remount settles into NAV_STACK a tick after the pump
    // that triggered it, so the tail check below reads a stale route; this start check catches it
    // at the next pump boundary, still fresh enough to fold its triggering select/tap). §14.6.
    PUMP_GEN.with(|g| g.set(g.get() + 1));
    crate::nav::maybe_notify_route_change();
    loop {
        let item = EVENTS.with(|e| e.borrow_mut().pop_front());
        let Some((id, ev)) = item else { break };
        // Presentation answers are keyed by request id, not by tree node (docs/dialogs.md).
        if let Event::PresentResult { req, result } = ev {
            crate::present::resolve_presentation(req, result);
            continue;
        }
        // Image decodes/encodes are keyed by request id too (docs/images.md), for the same
        // reason presentation is: the answer belongs to the caller that asked, not to a node.
        if let Event::ImageDecoded { req, result } = ev {
            crate::image::resolve_image_decode(req, result);
            continue;
        }
        if let Event::ImageEncoded { req, result } = ev {
            crate::image::resolve_image_encode(req, result);
            continue;
        }
        // Canvas exports answer the caller too (docs/canvas.md "Exporting").
        if let Event::BitmapRendered { req, result } = ev {
            crate::image::resolve_bitmap_render(req, result);
            continue;
        }
        if let Event::PdfRendered { req, result } = ev {
            crate::image::resolve_pdf_render(req, result);
            continue;
        }
        // Menu actions are keyed by action id, not by tree node (§ menus).
        if let Event::MenuAction(action) = ev {
            crate::menu::dispatch_menu_action(action);
            continue;
        }
        // Toolbar values are keyed by action id too (docs/toolbars.md); borrowed, because the
        // payload owns a String and the arms below still need `ev`.
        if let Event::ToolbarChanged { action, value } = &ev {
            crate::toolbar::dispatch_toolbar_value(*action, value);
            continue;
        }
        // Lifecycle phases are app-global, not keyed by tree node (docs/lifecycle.md).
        if let Event::Lifecycle(phase) = ev {
            crate::lifecycle::dispatch_lifecycle(phase);
            continue;
        }
        // Focus loss/gain pairing (docs/focus.md): when focus moves between two Day controls,
        // the loss and gain arrive as separate events. Dispatching the queued gain first lets a
        // shared group signal transition `Some(A)` → `Some(B)` without an observable `None`
        // (the loss handler only clears the signal if it still names its own control).
        if ev == Event::FocusChanged(false) {
            let paired = EVENTS.with(|e| {
                let mut q = e.borrow_mut();
                let gain = q
                    .iter()
                    .position(|(gid, gev)| *gid != id && *gev == Event::FocusChanged(true));
                gain.map(|i| q.remove(i).expect("indexed event"))
            });
            if let Some((gid, gev)) = paired {
                dispatch_focus_probe(gid, &gev);
                dispatch_to_node(gid, &gev);
            }
        }
        if let Event::FocusChanged(_) = ev {
            dispatch_focus_probe(id, &ev);
        }
        dispatch_to_node(id, &ev);
    }
    day_reactive::flush_sync();
    // The route has settled now that every queued event is dispatched and reactive writes have
    // flushed. A sidebar click, a nav_link, a stack push, and a native back all change the route
    // by calling `navigate`/`pop` from an event handler, none of which pass back through
    // `enqueue_events`, so the event observer never sees them. Notifying here (deduped against
    // the last route) is how the recorder captures navigation regardless of what triggered it
    // (docs/navigation.md, §14.6).
    crate::nav::maybe_notify_route_change();
}

/// The node that currently has the keyboard, as the platform last reported it. Keys follow
/// focus (docs/menus.md), so this is where a synthetic key has to land for a scripted run to
/// exercise the same route a real one does. `None` when nothing focusable holds it.
pub fn focused_node() -> Option<RNode> {
    FOCUSED.with(|f| f.get())
}

/// Mirror a focus event into the node's dayscript probe (`assert_focused` reads it).
fn dispatch_focus_probe(id: NodeId, ev: &Event) {
    if let Event::FocusChanged(f) = ev {
        let node = id_to_rnode(id);
        with_tree(|t| t.set_probe_focused(node, *f));
    }
}

/// Imperatively scroll a `scroll` piece (docs/scroll.md): `node` is the scroll node for edge
/// and offset targets (`ScrollTarget::Id` ignores it and reveals the named element in its own
/// nearest scroll). Animated on-screen; dayscript uses the unanimated variant for determinism.
/// Call with no tree borrow held.
pub fn scroll_to(node: RNode, target: ScrollTarget) {
    with_tree(|t| {
        t.scroll_to_target(node, &target, true);
    });
}

/// Run one already-routed event through its node's handlers (the tail of the pump loop).
fn dispatch_to_node(id: NodeId, ev: &Event) {
    let node = if id == day_spec::WINDOW_NODE {
        with_tree(|t| t.root_node())
    } else {
        id_to_rnode(id)
    };
    // A gesture addressed to a piece's own node (a dayscript step by id, which names that node
    // wherever `.id` sits in the chain; a probe's emit) is delivered to the node that enabled
    // the gesture: the node itself, or the wrapper above it where `.padding(..).on_tap(..)`
    // registered its handler, as a native gesture on the inner view reaches the recognizer on
    // its superview. A natively delivered gesture already names that node, so nothing moves.
    let gesture = match ev {
        Event::Tap(_) => Some(day_spec::GestureKind::Tap),
        Event::LongPress(_) => Some(day_spec::GestureKind::LongPress),
        Event::Drag { .. } => Some(day_spec::GestureKind::Drag),
        Event::Pan { .. } => Some(day_spec::GestureKind::Pan),
        Event::Pinch { .. } => Some(day_spec::GestureKind::Pinch),
        Event::Hover { .. } => Some(day_spec::GestureKind::Hover),
        _ => None,
    };
    let node = match gesture.and_then(|k| with_tree(|t| t.gesture_target(node, k))) {
        Some(target) => target,
        None => node,
    };
    let mut handlers = with_tree(|t| t.handlers_for(node));
    // A key or a focus change the toolkit raised on a native view also reaches the layout-only
    // wrappers directly above it (the same element): `.frame(..).on_key(..)` listens on the
    // wrapper, while the platform delivers the key to the view. Only these two: a tap or a drag
    // already reaches the wrapper through `enable_gesture`'s descent, and would arrive twice.
    if matches!(ev, Event::Key(_) | Event::FocusChanged(_)) {
        with_tree(|t| {
            for w in t.wrappers_above(node) {
                handlers.extend(t.handlers_for(w));
            }
        });
    }
    if handlers.is_empty() {
        // A press routed to a node that no longer exists is a staleness bug somewhere
        // upstream (an element index, a native view outliving its node); surface it in
        // debug builds instead of dropping silently; alive-but-handlerless is normal.
        if cfg!(debug_assertions)
            && matches!(ev, Event::Pressed | Event::Tap(_))
            && !with_tree(|t| t.node_exists(node))
        {
            log::warn!("{ev:?} dropped — node {id:?} no longer exists (stale reference)");
        }
        return;
    }
    day_reactive::batch(|| {
        for h in &handlers {
            h(ev);
        }
    });
}

fn collect_menu_families(
    items: &[day_spec::MenuItem],
    families: &mut std::collections::BTreeSet<String>,
) {
    for item in items {
        match item {
            day_spec::MenuItem::Action { id: Some(id), .. } => {
                families.insert(crate::element_id::family_of(id).to_owned());
            }
            day_spec::MenuItem::Submenu { items, .. } => collect_menu_families(items, families),
            _ => {}
        }
    }
}

#[cfg(test)]
mod thread_exit_tests {
    use super::*;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicBool, Ordering};

    /// A toolkit that records being dropped: the tree owns it, so it goes when the tree does.
    struct Probe(Arc<AtomicBool>);

    impl Drop for Probe {
        fn drop(&mut self) {
            self.0.store(true, Ordering::SeqCst);
        }
    }

    impl Toolkit for Probe {
        type Handle = ();
        fn realize(&mut self, _: PieceKind, _: &dyn Any, _: NodeId) -> Self::Handle {}
        fn release(&mut self, _: Self::Handle) {}
        fn insert(&mut self, _: &Self::Handle, _: &Self::Handle, _: usize) {}
        fn remove(&mut self, _: &Self::Handle, _: &Self::Handle) {
            panic!("test probe has no attached children to remove");
        }
        fn move_child(&mut self, _: &Self::Handle, _: &Self::Handle, _: usize) {}
        fn measure(&mut self, _: &Self::Handle, _: PieceKind, _: Proposal) -> Size {
            Size::new(0.0, 0.0)
        }
        fn set_frame(&mut self, _: &Self::Handle, _: Rect, _: Option<&AnimSpec>) {}
        fn set_input_traits(&mut self, _: &Self::Handle, _: &InputTraits) -> Option<Self::Handle> {
            None
        }
        fn set_event_sink(&mut self, _: EventSink) {}
        fn update(&mut self, _: &Self::Handle, _: &'static str, _: &dyn Any, _: Option<&AnimSpec>) {
        }
    }

    fn install_probe(dropped: &Arc<AtomicBool>) {
        let tree = Tree::new(Probe(dropped.clone()), (), Size::new(0.0, 0.0));
        install_tree(Box::new(tree));
    }

    /// The tree owns the toolkit's native widgets, and dropping those at thread exit runs the
    /// toolkit's callbacks against thread-locals that are already gone (a GtkListBox being
    /// emptied calls its header func; a panic there cannot unwind through C and aborts the
    /// process on the way out of a clean exit). So a thread's end must leak the tree.
    #[test]
    fn the_tree_is_not_dropped_when_its_thread_ends() {
        let dropped = Arc::new(AtomicBool::new(false));
        let d = dropped.clone();
        std::thread::spawn(move || install_probe(&d))
            .join()
            .expect("thread");
        assert!(
            !dropped.load(Ordering::SeqCst),
            "the thread-local destructor dropped the tree, and with it the native widgets"
        );
    }

    /// Explicit teardown is a different matter: tests and Android's remount take the tree down
    /// while every thread-local is alive, and that must still drop it.
    #[test]
    fn uninstall_still_drops_the_tree() {
        let dropped = Arc::new(AtomicBool::new(false));
        let d = dropped.clone();
        std::thread::spawn(move || {
            install_probe(&d);
            uninstall_tree();
            assert!(
                d.load(Ordering::SeqCst),
                "uninstall_tree must drop the tree"
            );
        })
        .join()
        .expect("thread");
    }

    #[test]
    fn removing_an_unattached_node_releases_without_native_detach() {
        let dropped = Arc::new(AtomicBool::new(false));
        let mut tree = Tree::new(Probe(dropped), (), Size::new(0.0, 0.0));
        let scope = Scope::detached();
        let node = tree.create_node(
            "fixture.detached",
            &(),
            Rc::new(crate::LeafLayout),
            Flex::default(),
            true,
            false,
            scope,
        );
        tree.remove_subtree(node);
        assert!(!tree.node_exists(node));
        assert_eq!(
            tree.release_queue.len(),
            1,
            "the unattached native handle must still be released"
        );
        scope.dispose();
    }

    /// A posted closure that arrives while the tree is borrowed (a backend pumping its native
    /// loop from inside a tree method) must wait for the safe point rather than re-enter
    /// `with_tree` on the borrowed tree: the "RefCell already borrowed" the web view demo hit
    /// opening Browser Settings on WinUI while a second tab's poll kept posts in flight.
    #[test]
    fn a_post_during_a_tree_borrow_runs_at_the_safe_point() {
        std::thread::spawn(|| {
            install_probe(&Arc::new(AtomicBool::new(false)));
            let ran = Arc::new(AtomicBool::new(false));
            let r = ran.clone();
            with_tree(|_| {
                run_posted_or_defer(Box::new(move || {
                    // The deferred closure borrows the tree itself, as a reactive flush or an
                    // eval reply does; running it inside the outer borrow would panic here.
                    with_tree(|_| r.store(true, Ordering::SeqCst));
                }));
                assert!(!ran.load(Ordering::SeqCst), "ran inside the borrow");
            });
            assert!(
                ran.load(Ordering::SeqCst),
                "never ran after the borrow was released"
            );
            // With the tree free, the same door runs the closure immediately.
            let now = Arc::new(AtomicBool::new(false));
            let n = now.clone();
            run_posted_or_defer(Box::new(move || n.store(true, Ordering::SeqCst)));
            assert!(
                now.load(Ordering::SeqCst),
                "a post with the tree free must run at once"
            );
            uninstall_tree();
        })
        .join()
        .expect("thread");
    }
}