day-pieces 0.6.1

Declarative app development API using native UI toolkits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! Navigation. Imperative helpers (`navigate`, `nav_back`, `current_route`, `nav_link`); typed
//! routes (the `Route` trait, the `routes!` macro, `RoutePath`); and the host pieces that project
//! an app-owned `Signal` into native navigation: `nav` (tabs/sidebar), `nav_stack` (push/pop),
//! and `cover` (modal), including nested-stack merging.

use std::cell::{Cell, RefCell};
use std::rc::Rc;

use day_core::*;
use day_reactive::{AnyBinding, Scope, Signal, bind, bind_seeded};
use day_spec::{Event, Size, kinds};

use crate::*;

// ---------------------------------------------------------------------------
// Navigation (docs/navigation.md): nav + stack, each a
// projection of an app-owned Signal.
// ---------------------------------------------------------------------------

/// Navigate to a route (docs/navigation.md).
///
/// * A single key (`navigate("inbox")`) is relative: the innermost route surface is tried
///   first, falling through outward; `""` pops the innermost stack to its root.
/// * A `/`-separated path (`navigate("mail/inbox/msg-42")`) is absolute: anchored at the
///   outermost surface that knows the first segment, everything inside reset, the remaining
///   segments consumed inward (surfaces mounting during the cascade take theirs as they appear).
/// * A trailing `?name=value&…` carries [`route_params`] to the destination builders.
///
/// False = no surface recognized the (first) segment.
pub fn navigate(path: &str) -> bool {
    day_core::navigate(path)
}

/// Pop one navigation level. False = nothing to pop.
pub fn nav_back() -> bool {
    day_core::nav_back()
}

/// The full current route: every mounted surface's contribution, outermost to innermost,
/// `/`-joined. Round-trips through [`navigate`]: persist it on exit, `navigate(&saved)` on
/// launch (docs/navigation.md).
pub fn current_route() -> Option<String> {
    day_core::current_route()
}

/// The query params of the most recent [`navigate`] (`?name=value&…`), read inside a
/// destination builder. See docs/navigation.md for when params apply.
pub fn route_params() -> std::rc::Rc<Vec<(String, String)>> {
    day_core::route_params()
}

/// One query param of the most recent [`navigate`] (`None` = not present).
pub fn route_param(name: &str) -> Option<String> {
    day_core::route_param(name)
}

/// A tappable link that navigates to `path` when pressed.
pub fn nav_link<M>(label: impl IntoText<M>, path: &str) -> Button {
    let path = path.to_string();
    button(label).action(move || {
        let _ = day_core::navigate(&path);
    })
}

// ---------------------------------------------------------------------------
// Typed routes (docs/navigation.md): routes as data instead of string encoding.
// ---------------------------------------------------------------------------

/// A typed route key, the compile-checked alternative to raw string keys.
///
/// Implement on an enum (one variant per destination) and use it everywhere a key goes:
/// `nav(Signal<Option<Section>>)` + `.item(Section::Controls, …)`,
/// `nav_stack(Signal<Vec<Drill>>, …)` + `.destination(|d: &Drill| …)`, [`navigate_to`], [`route`].
/// The string layer stays the wire format (deep links, dayscript, and [`current_route`]
/// still speak [`Route::key`] strings), but app code never assembles or splits them.
///
/// Variants can carry data (`Item { id: u32 }` ↔ `"item-42"`): encode it in [`Route::key`],
/// parse it back in [`Route::from_key`], and destination builders receive the typed value.
/// For plain data-free enums the [`routes!`] macro writes both sides.
pub trait Route: Clone + PartialEq + 'static {
    /// The path segment this value occupies in a route string. Must round-trip through
    /// [`Route::from_key`] and must not be empty; `""` means "no selection" (see the
    /// `Option<R>` impl).
    fn key(&self) -> String;
    /// Parse a path segment back into the typed value; `None` = not one of this type's routes.
    fn from_key(key: &str) -> Option<Self>;
    /// The human-readable title shown in the native navigation bar when this route is the top of
    /// a [`nav_stack`]. Defaults to [`key`](Route::key); override it to show a display name (e.g. an
    /// app's name) instead of the wire key.
    fn title(&self) -> String {
        self.key()
    }
}

/// Raw string keys, the untyped baseline. Every segment parses.
impl Route for String {
    fn key(&self) -> String {
        self.clone()
    }
    fn from_key(key: &str) -> Option<Self> {
        Some(key.to_string())
    }
}

/// `None` ↔ `""` (no selection): the key type for a sidebar [`nav`], whose collapsed
/// mobile state is "nothing selected". `.item(Section::X, …)` still takes the bare value
/// (`Section: Into<Option<Section>>`).
impl<R: Route> Route for Option<R> {
    fn key(&self) -> String {
        match self {
            Some(r) => r.key(),
            None => String::new(),
        }
    }
    fn from_key(key: &str) -> Option<Self> {
        if key.is_empty() {
            Some(None)
        } else {
            R::from_key(key).map(Some)
        }
    }
}

/// Define a plain routes enum and its [`Route`] impl in one shot:
///
/// ```ignore
/// day::routes! {
///     pub enum Section { Controls => "controls", Text => "text" }
/// }
/// nav(section).item(Section::Controls, tr("controls"), controls_page)
/// ```
///
/// A variant may add its display title after the key, anything a label takes (a string, or a
/// localized `tr(…)` resolved when the page is pushed). It is what a [`nav_stack`] shows in the
/// navigation bar for that route; a variant without one shows its key:
///
/// ```ignore
/// day::routes! {
///     enum Demo { Basics => "basics" (tr("demo-basics")), Stress => "stress" }
/// }
/// ```
///
/// Variants that carry data (`Item { id: u32 }` ↔ `"item-42"`) implement [`Route`] by hand.
#[macro_export]
macro_rules! routes {
    ($(#[$meta:meta])* $vis:vis enum $name:ident {
        $($(#[$vmeta:meta])* $variant:ident => $key:literal $(($title:expr))?),+ $(,)?
    }) => {
        $(#[$meta])*
        #[derive(Clone, Copy, PartialEq, Eq, Debug)]
        $vis enum $name { $($(#[$vmeta])* $variant),+ }
        impl $crate::Route for $name {
            fn key(&self) -> String {
                match self { $(Self::$variant => ($key).to_string()),+ }
            }
            fn from_key(key: &str) -> Option<Self> {
                match key { $($key => Some(Self::$variant),)+ _ => None }
            }
            fn title(&self) -> String {
                match self { $(Self::$variant => $crate::__route_title!($key $(, $title)?)),+ }
            }
        }
    };
}

/// A [`routes!`] variant's title: its display title when it has one, else its key.
#[doc(hidden)]
#[macro_export]
macro_rules! __route_title {
    ($key:literal) => {
        ($key).to_string()
    };
    ($key:literal, $title:expr) => {
        $crate::route_title_text($title)
    };
}

/// Resolve a [`routes!`] display title to the string the navigation bar shows.
#[doc(hidden)]
pub fn route_title_text<M>(title: impl crate::IntoText<M>) -> String {
    title.into_text().initial()
}

/// A typed absolute route: segments built from [`Route`] values plus query params.
/// `route(&Section::Stack).then(&Drill::Item { id: 42 }).param("hint", "linked")` encodes to
/// `"stack/item-42?hint=linked"`; [`RoutePath::navigate`] it, or hand it to [`nav_link_to`].
#[derive(Clone, Debug, Default)]
pub struct RoutePath {
    segments: Vec<String>,
    params: Vec<(String, String)>,
}

/// Start a typed [`RoutePath`] at the outermost segment.
pub fn route(first: &impl Route) -> RoutePath {
    RoutePath {
        segments: vec![first.key()],
        params: Vec::new(),
    }
}

impl RoutePath {
    /// Append the next-inner segment.
    pub fn then(mut self, next: &impl Route) -> Self {
        self.segments.push(next.key());
        self
    }
    /// Append a query param (the destination reads it via [`route_param`]).
    pub fn param(mut self, name: &str, value: impl std::fmt::Display) -> Self {
        self.params.push((name.to_string(), value.to_string()));
        self
    }
    /// The encoded route string (percent-escaped where needed), the form [`navigate`] accepts.
    pub fn to_route(&self) -> String {
        day_core::encode_route(&self.segments, &self.params)
    }
    /// Navigate to this path. False = no surface recognized the first segment.
    pub fn navigate(&self) -> bool {
        day_core::navigate(&self.to_route())
    }
}

impl std::fmt::Display for RoutePath {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.to_route())
    }
}

/// Navigate to a single typed key, relative (innermost surface first): the typed
/// `navigate(&r.key())`, percent-escaped. For absolute paths chain a [`route`].
pub fn navigate_to(r: &impl Route) -> bool {
    day_core::navigate(&day_core::encode_route(std::slice::from_ref(&r.key()), &[]))
}

/// A tappable link that navigates to a typed [`RoutePath`] when pressed.
pub fn nav_link_to<M>(label: impl IntoText<M>, path: RoutePath) -> Button {
    let path = path.to_route();
    button(label).action(move || {
        let _ = day_core::navigate(&path);
    })
}

// ---------------------------------------------------------------------------
// Nested-nav merge (docs/navigation.md): a `nav_stack()` built inside a page of an enclosing NAV
// host that presents as a push stack (mobile, `split == false`) pushes its pages onto that host
// instead of minting a second native container: one native nav chain, one back button. The
// enclosing host is threaded to nested pieces at build time via a thread-local context stack;
// `owners` is the per-host ordered stack of "what a back on the topmost page does".
// ---------------------------------------------------------------------------

/// Performs the topmost page's back action. Arg = the toolkit already popped natively (iOS/Android
/// system back), so the owner must not re-issue a pop.
type PopOwner = Rc<dyn Fn(bool)>;

#[derive(Clone)]
struct NavHostCx {
    host: RNode,
    sizes: Rc<RefCell<std::collections::HashMap<RNode, Size>>>,
    /// One entry per page pushed above the root, in native order; the host's single `NavBack`
    /// handler invokes the last.
    owners: Rc<RefCell<Vec<PopOwner>>>,
    /// The enclosing host presents as split panes. A nested stack does not merge into a split
    /// host; it keeps its own detail-pane stack. Shared and mutable because the host can
    /// re-present under us: a page built while the window is narrow should merge, and one built
    /// after it widens should not.
    split: Rc<Cell<bool>>,
    /// Votes to route this host's native back through Day (`NavPatch::GuardTop`): a guarded stack
    /// above its root holds one, and so does a detail shown beside its composed list. Counted, so
    /// one voter withdrawing never disarms another.
    guards: Rc<Cell<usize>>,
}

impl NavHostCx {
    /// Add (`true`) or withdraw (`false`) one vote to route the native back through Day. The
    /// patch goes out only when the count crosses zero.
    fn vote_guard(&self, on: bool) {
        let was = self.guards.get();
        let now = if on { was + 1 } else { was.saturating_sub(1) };
        self.guards.set(now);
        if (was == 0) != (now == 0) {
            let host = self.host;
            with_tree(|t| {
                t.patch(
                    host,
                    Box::new(day_spec::props::NavPatch::GuardTop(now > 0)),
                    false,
                )
            });
        }
    }
}

day_reactive::tls_group! {
    /// Increasing presentation order for fullscreen navigation layers.
    static NEXT_COVER_LAYER: Cell<u64> = const { Cell::new(1) };
    /// Build-time stack of enclosing nav hosts. `None` is a barrier (a resident container such as
    /// tabs) that a nested stack must not merge through.
    static NAV_HOST_CX: RefCell<Vec<Option<NavHostCx>>> = const { RefCell::new(Vec::new()) };
    /// Build-time stack of "is the page I am being built into the one its host shows?", one entry
    /// per enclosing resident page. Only a chrome host (a tab bar, a rail) pushes one: everywhere
    /// else the outgoing page is torn down, so a surface that still exists is by definition the
    /// one on screen. A surface captures the whole stack at registration and is on screen only
    /// when every gate above it answers true.
    static NAV_PAGE_ACTIVE: RefCell<Vec<Rc<dyn Fn() -> bool>>> = const { RefCell::new(Vec::new()) };

    /// How many routed one-of-N surfaces (`nav`/tabs) are live at each nesting depth. Two at
    /// the same depth are siblings whose keys both flow into `current_route()`, the case that
    /// wants `.local()` (docs/navigation.md). Used only to warn; never changes behavior.
    static ROUTED_ONE_OF_N: RefCell<std::collections::HashMap<usize, usize>> =
        RefCell::new(std::collections::HashMap::new());
}

/// Build `f` with `gate` deciding whether what it builds counts as on screen (`NAV_PAGE_ACTIVE`).
fn with_page_active<R>(gate: Rc<dyn Fn() -> bool>, f: impl FnOnce() -> R) -> R {
    NAV_PAGE_ACTIVE.with(|s| s.borrow_mut().push(gate));
    let r = f();
    NAV_PAGE_ACTIVE.with(|s| {
        s.borrow_mut().pop();
    });
    r
}

/// A document can leave the resident container for its own native window. Replace
/// its selection gate while retaining enclosing navigation gates and nested-page gates.
pub(crate) fn with_document_active<R>(gate: Rc<dyn Fn() -> bool>, f: impl FnOnce() -> R) -> R {
    struct Restore(Option<Rc<dyn Fn() -> bool>>);
    impl Drop for Restore {
        fn drop(&mut self) {
            NAV_PAGE_ACTIVE.with(|s| {
                let mut s = s.borrow_mut();
                s.pop();
                if let Some(previous) = self.0.take() {
                    s.push(previous);
                }
            });
        }
    }
    let previous = NAV_PAGE_ACTIVE.with(|s| {
        let mut s = s.borrow_mut();
        let previous = s.pop();
        s.push(gate);
        previous
    });
    let _restore = Restore(previous);
    f()
}

/// Run `f` with `cx` as the innermost nav-host context (a barrier when `None`), restoring after.
fn with_nav_host<R>(cx: Option<NavHostCx>, f: impl FnOnce() -> R) -> R {
    NAV_HOST_CX.with(|s| s.borrow_mut().push(cx));
    let r = f();
    NAV_HOST_CX.with(|s| {
        s.borrow_mut().pop();
    });
    r
}

/// The innermost mergeable nav host, if any (a barrier or an empty stack yields `None`).
fn current_nav_host() -> Option<NavHostCx> {
    NAV_HOST_CX.with(|s| s.borrow().last().cloned().flatten())
}

/// Create a NAV_PAGE under `host` and wire its FrameChanged size reports into `sizes`
/// (the native container owns each page's frame; Day lays content out at the reported size).
fn nav_page(
    host: RNode,
    props: &day_spec::props::NavPageProps,
    sizes: &Rc<RefCell<std::collections::HashMap<RNode, Size>>>,
) -> RNode {
    let mut cx = BuildCx::new(host);
    let page = cx.native(
        kinds::NAV_PAGE,
        props,
        Rc::new(PassThrough),
        Flex::default(),
        Boundary::Yes,
    );
    let sizes = sizes.clone();
    cx.on(page, move |ev| {
        if let Event::FrameChanged(sz) = ev {
            let changed = sizes.borrow().get(&page) != Some(sz);
            if changed {
                sizes.borrow_mut().insert(page, *sz);
                with_tree(|t| {
                    t.mark_needs_measure(page);
                    t.mark_layout_dirty();
                    t.layout_if_needed();
                });
            }
        }
    });
    page
}

/// Whether a list layer is the thing the user is looking at (docs/toolbars.md).
///
/// One rule, three sites: the native content-list pane, and the composed gated flow's two shapes.
/// A list's commands (add, filter, sort) act on rows the user can see, so they leave the
/// window's bar the moment something covers them. Two ways that happens: the destination
/// collapses the pane (`content_list_for`), or a detail is pushed over it on a shape that shows
/// one layer at a time. Side by side, both layers are up and both keep their commands.
fn list_layer_gate(
    visible: Option<Signal<bool>>,
    detail_open: Option<AnyBinding<bool>>,
    pres: Option<Signal<day_spec::props::NavPresentation>>,
) -> Rc<dyn Fn() -> bool> {
    // `try_get` throughout: a gate is asked at merge time, which can be a window's
    // teardown, so a disposed signal answers "not showing" rather than panicking.
    Rc::new(move || {
        let shown = visible.is_none_or(|v| v.try_get().unwrap_or(false));
        let side_by_side = pres.is_some_and(|p| p.try_get().is_some_and(|p| p.is_split()));
        shown && (side_by_side || detail_open.is_none_or(|d| !d.try_get().unwrap_or(false)))
    })
}

/// The navigation page being built, captured so a piece built later (a `when` arm a morph
/// re-runs) can build inside it again: its commands then land on that page's chrome, under
/// its gate (docs/toolbars.md).
#[derive(Clone)]
struct PageContext {
    chrome: day_core::Chrome,
    gate: Option<Rc<dyn Fn() -> bool>>,
    column: day_spec::ToolbarColumn,
    window: RNode,
}

impl PageContext {
    fn current() -> PageContext {
        PageContext {
            chrome: day_core::current_chrome(),
            gate: day_core::current_page_gate(),
            column: day_core::current_page_column(),
            window: day_core::current_page_window(),
        }
    }

    /// `piece`, built inside the captured page (as is, before one was captured).
    fn enter(at: &Rc<RefCell<Option<PageContext>>>, piece: impl Piece + 'static) -> AnyPiece {
        let at = at.clone();
        AnyPiece::new(piece_fn(move |cx| {
            let ctx = at.borrow().clone();
            match ctx {
                Some(PageContext {
                    chrome: day_core::Chrome::Page(page),
                    gate,
                    column,
                    window,
                }) => day_core::with_page_in(page, gate, column, window, || piece.build(cx)),
                _ => piece.build(cx),
            }
        }))
    }
}

/// `gate`, and the gate of the page being built (a tab's "selected"), when it has one: a list
/// registered inline in a page shows its commands only while that page does too.
fn within_page_gate(gate: Rc<dyn Fn() -> bool>) -> Rc<dyn Fn() -> bool> {
    match day_core::current_page_gate() {
        Some(outer) => Rc::new(move || outer() && gate()),
        None => gate,
    }
}

/// Whether a destination page is the one showing: the selection is on it (docs/toolbars.md).
fn destination_gate<K: Route, S: Binding<K> + 'static>(
    selection: S,
    key: String,
) -> Rc<dyn Fn() -> bool> {
    Rc::new(move || selection.read().key() == key)
}

// Scope context survives reactive content rebuilds after the build-time nav stack unwinds.
#[derive(Clone, Default)]
struct NavLayer {
    order: Rc<Cell<u64>>,
    depth: usize,
}

/// Register a string-route adapter over a route surface's own signal, so `navigate()` /
/// deep links / dayscript keep working by key. This is a convenience layer: the surface
/// itself is driven by the signal, not by this registry (docs/navigation.md).
///
/// `enter` consumes one segment of an absolute path (`navigate("a/b/c")`); `segments` is the
/// surface's contribution to the full [`current_route`].
fn register_route_surface(
    push: impl Fn(&str) -> bool + 'static,
    pop: impl Fn(bool) -> bool + 'static,
    current: impl Fn() -> String + 'static,
    enter: impl Fn(&str) -> bool + 'static,
    segments: impl Fn() -> Vec<String> + 'static,
) {
    register_route_surface_in_layer(
        Scope::current()
            .use_context::<NavLayer>()
            .unwrap_or_default(),
        push,
        pop,
        current,
        enter,
        segments,
    );
}

fn register_route_surface_in_layer(
    layer: NavLayer,
    push: impl Fn(&str) -> bool + 'static,
    pop: impl Fn(bool) -> bool + 'static,
    current: impl Fn() -> String + 'static,
    enter: impl Fn(&str) -> bool + 'static,
    segments: impl Fn() -> Vec<String> + 'static,
) {
    // The nesting depth day-core descends by. `NAV_HOST_CX` is the stack of hosts this build is
    // inside, so its length is how deep this surface sits, and unlike registration order it does
    // not depend on whether a host registers before or after building its pages.
    let depth = layer.depth + NAV_HOST_CX.with(|s| s.borrow().len());
    // The resident pages this surface is built inside, captured now because the stack unwinds as
    // soon as the build returns. Empty for a surface at the window root, which is then always on
    // screen, since `all` over nothing is true.
    let gates: Vec<Rc<dyn Fn() -> bool>> = NAV_PAGE_ACTIVE.with(|s| s.borrow().clone());
    let token = day_core::register_nav(day_core::NavController {
        depth,
        layer: Box::new(move || layer.order.get()),
        push: Box::new(push),
        pop: Box::new(pop),
        current: Box::new(current),
        enter: Box::new(enter),
        segments: Box::new(segments),
        active: Box::new(move || gates.iter().all(|g| g())),
    });
    Scope::current().on_cleanup(move || day_core::unregister_nav(token));
}

/// Note a routed nav/tabs at the current nav depth and, in debug builds, warn if it is a
/// sibling of another routed one-of-N surface, the case `.local()` exists for
/// (docs/navigation.md). The count is decremented when the surface's scope disposes, so
/// switching sections doesn't leak. A stack is exempt (its whole path is one surface's
/// contribution; sibling stacks are a documented layout), as is a cover (its segment is empty
/// unless presented).
fn note_routed_one_of_n(kind: &str) {
    let depth = NAV_HOST_CX.with(|s| s.borrow().len());
    let count = ROUTED_ONE_OF_N.with(|m| {
        let mut m = m.borrow_mut();
        let c = m.entry(depth).or_insert(0);
        *c += 1;
        *c
    });
    if count > 1 {
        warn_sibling_selectors(kind);
    }
    Scope::current().on_cleanup(move || {
        ROUTED_ONE_OF_N.with(|m| {
            if let Some(c) = m.borrow_mut().get_mut(&depth) {
                *c = c.saturating_sub(1);
            }
        });
    });
}

#[cfg(debug_assertions)]
fn warn_sibling_selectors(kind: &str) {
    log::warn!(
        "two routed one-of-N surfaces ({kind}) are mounted at the same navigation level. \
         Their keys both flow into current_route(), so you'll see `section/childA/childB` and \
         `navigate(\"child\")` is ambiguous. Mark all but the primary one `.local()` \
         (docs/navigation.md)."
    );
}

#[cfg(not(debug_assertions))]
fn warn_sibling_selectors(_kind: &str) {}

// ===========================================================================
// Nav: one-of-N, bound to a Signal<String> of the active key.
// ===========================================================================

/// How a [`nav`] presents its one-of-N choice (docs/navigation.md).
///
/// The default is [`Self::Automatic`]: unless you say otherwise, a nav wears whatever the
/// platform wears at the window's current width, and changes as the window does.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum NavStyle {
    /// **The default.** The platform's own answer at this size: a tab bar on a phone-shaped
    /// window, a rail in the middle, a sidebar beside the detail when there is room, and it
    /// re-presents live as the window crosses a breakpoint (docs/size-classes.md).
    ///
    /// This is `.tabViewStyle(.sidebarAdaptable)`'s job, and the native containers it maps to
    /// are the ones the platforms built for it: `UITabBarController` in `.tabSidebar` mode, a
    /// `NavigationView` driving its own `PaneDisplayMode`, a Material navigation bar / rail /
    /// drawer. A toolkit that cannot draw a tab bar (`Cap::NavTabs`) degrades to [`Self::Sidebar`]
    /// rather than to a hole.
    #[default]
    Automatic,
    /// Pinned: a tab bar at every size, however wide the window gets. Reach for it when the
    /// content is peer sections that should never become a sidebar.
    Tabs,
    /// Pinned: a NavigationSplitView, a sidebar list + a detail. Wide windows show both panes
    /// (on GTK an `AdwNavigationSplitView`); narrow ones collapse to a list that pushes the
    /// detail, which is the one shape [`Self::Automatic`] never produces on its own.
    Sidebar,
}

/// A built detail page of a nav, and what it takes to tear it down. Exactly one of these
/// exists per shown page in a split or stacked presentation; one per visited page in a
/// presentation whose rows are chrome, where pages are resident (docs/navigation.md).
struct ResidentPage {
    /// The item key this page was built for, the identity a re-selection matches on.
    key: String,
    /// The page's own reactive scope; disposing it runs the content's cleanup.
    scope: Scope,
    /// The `NAV_PAGE` node, in the host's detail-child attach order. Its index in the owning
    /// `Vec` is what `NavPatch::Select` addresses.
    node: RNode,
}

/// Builds the page for a data-driven key (`&K` → piece): a nav's `.destination` fallback
/// or a stack's `.destination`.
type DestFn<K> = Rc<dyn Fn(&K) -> AnyPiece>;

/// Which destinations show the content-list pane (`Nav::content_list_for`).
type ListPred<K> = Rc<dyn Fn(&K) -> bool>;

/// Completions for a search field's current text (`Nav::search_suggestions`).
type SuggestFn = Rc<dyn Fn(&str) -> Vec<String>>;

/// The toolbar item id a `.searchable()` surface's field carries when its placement resolves to
/// the window toolbar (docs/search.md). Reserved and stable: dayscript's `toolbar:` step addresses
/// the field by this id, and it is Day's own rather than the app's, since the app never declares
/// the item.
pub const SEARCH_ITEM_ID: &str = day_spec::SEARCH_ITEM_ID;

/// The flattened live rows a nav's dynamic blocks derive to: per-row key strings, typed
/// keys, titles, and icons (index-aligned). Carried through the reconcile `bind`.
/// One tracked derive of a nav's rows: (key strings, typed keys, titles, icons, badges,
/// section headers). Compared by equality to gate the re-patch, so every decoration a backend
/// renders has to ride along; a badge that changed but was not carried here would not repaint.
type DerivedRows<K> = (
    Vec<String>,
    Vec<K>,
    Vec<String>,
    Vec<Option<String>>,
    Vec<Option<String>>,
    Vec<Option<String>>,
    Vec<Option<day_spec::Color>>,
    Vec<Vec<day_spec::MenuItem>>,
    Vec<Option<String>>,
    Vec<Option<day_spec::Color>>,
);

/// The rows the native menu last received, to tell a value change (`rows_changed`) from a new
/// row set.
struct ShownRows {
    keys: Vec<String>,
    titles: Vec<String>,
    icons: Vec<Option<String>>,
    badges: Vec<Option<String>>,
    badge_icons: Vec<Option<String>>,
    badge_tints: Vec<Option<day_spec::Color>>,
    sections: Vec<Option<String>>,
    tints: Vec<Option<day_spec::Color>>,
    menus: Vec<Vec<day_spec::MenuItem>>,
}

impl<K: Route> NavRows<K> {
    fn shown(&self) -> ShownRows {
        ShownRows {
            keys: self.keys.iter().map(|k| k.key()).collect(),
            titles: self.titles.clone(),
            icons: self.icons.clone(),
            badges: self.badges.clone(),
            badge_icons: self.badge_icons.clone(),
            badge_tints: self.badge_tints.clone(),
            sections: self.sections.clone(),
            tints: self.tints.clone(),
            menus: self.menus.clone(),
        }
    }
}

#[derive(Clone)]
#[doc(hidden)]
pub struct SectionHeader {
    id: Option<String>,
    title: TextSource,
}

#[doc(hidden)]
pub struct SelItem<K> {
    key: K,
    title: TextSource,
    /// Optional bundled-image name for the item's native icon (docs/navigation.md).
    icon: Option<String>,
    /// Optional per-row icon tint (docs/vectors.md).
    tint: Option<day_spec::Color>,
    /// Per-row context menu (docs/menus.md), already lowered: items carry registered
    /// action ids. Empty = no menu.
    menu: Vec<day_spec::MenuItem>,
    /// Trailing accessory (an unread count). A `TextSource` so a live count retitles on its
    /// own signal, and so a localized badge follows `set_locale`.
    badge: Option<TextSource>,
    /// Trailing accessory glyph, in the same slot as `badge` (docs/navigation.md).
    badge_icon: Option<String>,
    /// Tint for `badge_icon`; `None` leaves it at the backend's neutral template tint.
    badge_tint: Option<day_spec::Color>,
    /// Header introducing the group this item opens (docs/navigation.md).
    section: Option<SectionHeader>,
    /// Immersive-chrome page (docs/navigation.md): keeps the floating transparent bar on
    /// backends with an immersive nav mode; standard opaque bar otherwise.
    immersive: bool,
    /// The item's own page builder ([`NavItem::page`]); an item without one is built by the
    /// nav's `.destination` fallback.
    build: Option<PageFn>,
}

/// A page builder, shared between an item and the nav's builder map.
type PageFn = Rc<dyn Fn() -> AnyPiece>;

/// One nav item (docs/navigation.md): a key, a title, and its decorations, built by [`item`].
/// The same value describes a static destination (`item("home", title).page(home_page)`) and
/// a row of a data-driven block (`nav_items(move || feeds(), |f| item(f.id, f.name))`).
pub struct NavItem<K = String> {
    key: K,
    title: TextSource,
    icon: Option<String>,
    icon_tint: Option<day_spec::Color>,
    menu: Vec<day_spec::MenuItem>,
    badge: Option<TextSource>,
    badge_icon: Option<String>,
    badge_tint: Option<day_spec::Color>,
    section: Option<SectionHeader>,
    immersive: bool,
    page: Option<PageFn>,
}

/// A nav item: `item("today", res::str::today()).icon(res::images::today).page(today_page)`
/// (docs/navigation.md). Goes into a [`Nav::items`] or [`Nav::section`] block, alone, in a
/// tuple, or from a [`nav_items`] mapper; an item without a [`page`](NavItem::page) is built by
/// the nav's [`Nav::destination`]. For a typed nav over `Option<Section>` pass the bare
/// `Section::X`.
pub fn item<M, K, I: Into<K>>(key: I, title: impl IntoText<M>) -> NavItem<K> {
    NavItem {
        key: key.into(),
        icon_tint: None,
        menu: Vec::new(),
        title: title.into_text(),
        icon: None,
        badge: None,
        badge_icon: None,
        badge_tint: None,
        section: None,
        immersive: false,
        page: None,
    }
}

impl<K> NavItem<K> {
    /// The page this item opens; `build` runs when the item is first shown. An item without
    /// one is built by the nav's [`Nav::destination`], the usual choice for a data-driven block
    /// whose rows share one page shape.
    pub fn page<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
        self.page = Some(Rc::new(move || AnyPiece::new(build())));
        self
    }
    /// A bundled-image name for the item's native icon (typed [`ImageName`](day_spec::ImageName),
    /// resolved like [`image()`], e.g. `res::images::nav_home`), or an absolute local image path
    /// supplied as an owned string. Shown beside the label where the backend's nav supports it
    /// (the Windows NavigationView, the iOS/macOS source list); backends that can't decorate
    /// rows ignore it. AppKit/UIKit preserve the colors of local files; bundled glyphs remain
    /// templates.
    pub fn icon(mut self, icon: impl Into<day_spec::ImageName>) -> Self {
        self.icon = Some(icon.into().as_str().to_owned());
        self
    }
    /// Tint this row's icon (docs/vectors.md): the glyph recolors to `color` instead of the
    /// backend's neutral template tint. Backends without per-row tinting keep the neutral look.
    pub fn icon_tint(mut self, color: day_spec::Color) -> Self {
        self.icon_tint = Some(color);
        self
    }
    /// Attach a context menu to this row (docs/menus.md): shown on secondary-click /
    /// long-press, the same `menu_item`/`sub_menu` builders as everywhere else. A chosen
    /// entry runs its action exactly like a piece context menu. Backends without per-row
    /// menus drop it (see the matrix in docs/menus.md).
    pub fn context_menu(
        mut self,
        entries: impl IntoIterator<Item = crate::menus::MenuEntry>,
    ) -> Self {
        // Scoped: row menus are re-lowered on every derive; the previous build's closures
        // are reclaimed when the registering scope (the nav's surface) is disposed.
        self.menu = crate::menus::lower_menu_scoped(entries.into_iter().collect());
        self
    }
    /// A trailing accessory for this row (an unread count, a status). Rendered right-aligned
    /// and de-emphasized where the toolkit has an affordance for it, and dropped where it does
    /// not (see docs/coverage-matrix.md). Empty text shows no badge, so a count can return `""`
    /// at zero.
    pub fn badge<M>(mut self, badge: impl IntoText<M>) -> Self {
        self.badge = Some(badge.into_text());
        self
    }
    /// A trailing accessory glyph for this row, in the same slot as [`Self::badge`] and drawn
    /// after it. Takes a bundled image name exactly as [`Self::icon`] does, so a symbol
    /// (`Symbol::Star`) or an app image both work.
    ///
    /// This is what a row-level status gets drawn with (a starred page's star) where `badge`
    /// carries a count or a word. Pair it with [`Self::badge_tint`] when the glyph's color is
    /// part of its meaning; left untinted it takes the backend's neutral template tint and reads
    /// as another piece of chrome.
    pub fn badge_icon(mut self, icon: impl Into<day_spec::ImageName>) -> Self {
        self.badge_icon = Some(icon.into().to_string());
        self
    }
    /// The color for [`Self::badge_icon`]. `None` (the default) keeps the neutral template tint.
    pub fn badge_tint(mut self, color: day_spec::Color) -> Self {
        self.badge_tint = Some(color);
        self
    }
    /// Open a new section with this header, immediately before this row.
    pub fn section<M>(mut self, title: impl IntoText<M>) -> Self {
        self.section = Some(SectionHeader {
            id: None,
            title: title.into_text(),
        });
        self
    }
    /// Open a section with an identity independent of its localized title or first row.
    pub fn section_id<M>(mut self, id: impl Into<String>, title: impl IntoText<M>) -> Self {
        self.section = Some(SectionHeader {
            id: Some(id.into()),
            title: title.into_text(),
        });
        self
    }
    /// Mark this item's pushed page immersive-chrome (docs/navigation.md): on backends with an
    /// immersive nav mode (android edge-to-edge today) its pushed page keeps the floating
    /// transparent bar over full-bleed content; unmarked pages get the standard opaque bar. A
    /// no-op on every other backend.
    pub fn immersive(mut self) -> Self {
        self.immersive = true;
        self
    }

    fn into_source(self) -> ItemSource<K> {
        ItemSource::Static(SelItem {
            key: self.key,
            title: self.title,
            icon: self.icon,
            tint: self.icon_tint,
            menu: self.menu,
            badge: self.badge,
            badge_icon: self.badge_icon,
            badge_tint: self.badge_tint,
            section: self.section,
            immersive: self.immersive,
            build: self.page,
        })
    }
}

/// A data-driven block of nav items (docs/navigation.md), built by [`nav_items`]: re-derives
/// whenever the signal changes.
pub struct NavItems<K> {
    derive: Box<dyn Fn() -> Vec<SelItem<K>>>,
}

/// A data-driven item block: `nav_items(move || st.feeds.get(), |f| item(f.id, f.name).icon(…))`
/// (docs/navigation.md). `items` is a tracked reader (a `Signal<Vec<T>>` via its `Fn()` deref,
/// or a closure); the block re-derives whenever it changes: rows are added and removed on the
/// native sidebar/tab widget, and if the selected key disappears the selection resets (to
/// `None` for an `Option` key). Static items and blocks may be mixed; the final list is their
/// declaration order. A row without its own [`page`](NavItem::page) is built by the nav's
/// [`Nav::destination`].
pub fn nav_items<T: Clone + 'static, K: 'static>(
    items: impl Fn() -> Vec<T> + 'static,
    map: impl Fn(&T) -> NavItem<K> + 'static,
) -> NavItems<K> {
    NavItems {
        derive: Box::new(move || {
            items()
                .iter()
                .map(|t| match map(t).into_source() {
                    ItemSource::Static(it) => it,
                    ItemSource::Dynamic(_) => unreachable!("an item maps to one row"),
                })
                .collect()
        }),
    }
}

/// What a [`Nav::items`] or [`Nav::section`] block takes: one [`NavItem`], a tuple of them, an
/// `Option` (an item the platform may not want: `prefs.nav_item(key)`), a `Vec` or array, or a
/// data-driven [`nav_items`] block. Any mix nests: `(item(..), nav_items(..), Some(item(..)))`.
pub trait NavContent<K> {
    /// Append this content's sources, in order.
    fn push_sources(self, out: &mut Vec<ItemSource<K>>);
}

impl<K> NavContent<K> for NavItem<K> {
    fn push_sources(self, out: &mut Vec<ItemSource<K>>) {
        out.push(self.into_source());
    }
}

impl<K: 'static> NavContent<K> for NavItems<K> {
    fn push_sources(self, out: &mut Vec<ItemSource<K>>) {
        out.push(ItemSource::Dynamic(self.derive));
    }
}

impl<K, C: NavContent<K>> NavContent<K> for Option<C> {
    fn push_sources(self, out: &mut Vec<ItemSource<K>>) {
        if let Some(c) = self {
            c.push_sources(out);
        }
    }
}

impl<K, C: NavContent<K>> NavContent<K> for Vec<C> {
    fn push_sources(self, out: &mut Vec<ItemSource<K>>) {
        for c in self {
            c.push_sources(out);
        }
    }
}

impl<K, C: NavContent<K>, const N: usize> NavContent<K> for [C; N] {
    fn push_sources(self, out: &mut Vec<ItemSource<K>>) {
        for c in self {
            c.push_sources(out);
        }
    }
}

impl<K> NavContent<K> for () {
    fn push_sources(self, _out: &mut Vec<ItemSource<K>>) {}
}

macro_rules! impl_nav_content_tuple {
    ($($name:ident),+) => {
        impl<K, $($name: NavContent<K>),+> NavContent<K> for ($($name,)+) {
            #[allow(non_snake_case)]
            fn push_sources(self, out: &mut Vec<ItemSource<K>>) {
                let ($($name,)+) = self;
                $($name.push_sources(out);)+
            }
        }
    };
}
impl_nav_content_tuple!(A);
impl_nav_content_tuple!(A, B);
impl_nav_content_tuple!(A, B, C);
impl_nav_content_tuple!(A, B, C, D);
impl_nav_content_tuple!(A, B, C, D, E);
impl_nav_content_tuple!(A, B, C, D, E, F);
impl_nav_content_tuple!(A, B, C, D, E, F, G);
impl_nav_content_tuple!(A, B, C, D, E, F, G, H);
impl_nav_content_tuple!(A, B, C, D, E, F, G, H, I);
impl_nav_content_tuple!(A, B, C, D, E, F, G, H, I, J);
impl_nav_content_tuple!(A, B, C, D, E, F, G, H, I, J, L);
impl_nav_content_tuple!(A, B, C, D, E, F, G, H, I, J, L, N);

/// A source of nav items: a fixed item, or a signal-driven block that re-derives its items
/// when the signal changes (docs/navigation.md).
// Boxing `Static` would trade an allocation per row for a saving that is nominal here: these
// enums live in one `Vec` built once when a nav is constructed, a few dozen entries at most,
// and the static case is the overwhelmingly common one. The gap is only this wide because a row
// carries its decorations inline (icon, tint, badge text, badge glyph, section, menu).
#[allow(clippy::large_enum_variant)]
#[doc(hidden)]
pub enum ItemSource<K> {
    Static(SelItem<K>),
    /// Reads a signal (tracked) and maps its elements to items. Called to (re)derive the block.
    Dynamic(Box<dyn Fn() -> Vec<SelItem<K>>>),
}

// A nav's item sources reduced to what both `build_sidebar` and `build_tabs` need: a
// per-key page builder for static items, the ordered metadata sources (statics + dynamic
// blocks) that `derive` walks to produce the live row list, and the `.destination` fallback
// for data-driven keys. `derive` is called untracked for the first build and tracked inside a
// reactive effect that re-patches the native rows when a dynamic block's signal changes.
// Boxing `Static` would trade an allocation per row for a saving that is nominal here: these
// enums live in one `Vec` built once when a nav is constructed, a few dozen entries at most,
// and the static case is the overwhelmingly common one. The gap is only this wide because a row
// carries its decorations inline (icon, tint, badge text, badge glyph, section, menu).
#[allow(clippy::large_enum_variant)]
enum MetaSource<K> {
    Static(K, TextSource, RowMeta, bool),
    Dynamic(Box<dyn Fn() -> Vec<SelItem<K>>>),
}

/// The non-title decorations of one nav row.
#[derive(Clone, Default)]
struct RowMeta {
    icon: Option<String>,
    tint: Option<day_spec::Color>,
    menu: Vec<day_spec::MenuItem>,
    badge: Option<TextSource>,
    badge_icon: Option<String>,
    badge_tint: Option<day_spec::Color>,
    section: Option<SectionHeader>,
}

#[derive(Clone)]
struct NavReorder<K> {
    eligible: Rc<dyn Fn(&K) -> bool>,
    moved: Rc<dyn Fn(K, K)>,
}

/// How a sidebar row drags under [`Nav::regroup_items`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NavDrag {
    /// Doesn't drag, and nothing drops into its section.
    Fixed,
    /// Drags to another place in its own section or into another section.
    Reorder,
    /// Drags into another section only: its own section keeps the app's sorted order.
    Regroup,
}

/// Where a dragged sidebar row landed ([`Nav::regroup_items`]).
#[derive(Clone, Debug, PartialEq)]
pub struct NavDrop<K> {
    /// The dragged row.
    pub moved: K,
    /// The destination section's id (`section_id`), `None` for a section declared without one
    /// and for the rows above the first header.
    pub section: Option<String>,
    /// The row it now sits before in that section; `None` at the section's end. Never `moved`.
    pub before: Option<K>,
}

#[derive(Clone)]
struct NavRegroup<K> {
    drag: Rc<dyn Fn(&K) -> NavDrag>,
    dropped: Rc<dyn Fn(NavDrop<K>)>,
}

/// A nav's sidebar dragging: [`Nav::reorder_items`] or [`Nav::regroup_items`], whichever was
/// declared last.
#[derive(Clone)]
enum SidebarDrag<K> {
    Reorder(NavReorder<K>),
    Regroup(NavRegroup<K>),
}

impl<K> SidebarDrag<K> {
    /// How the row with this key drags; a reorder's eligible row reorders.
    fn drag(&self, key: &K) -> NavDrag {
        match self {
            SidebarDrag::Reorder(r) if (r.eligible)(key) => NavDrag::Reorder,
            SidebarDrag::Reorder(_) => NavDrag::Fixed,
            SidebarDrag::Regroup(g) => (g.drag)(key),
        }
    }
}

/// One nav's rows as a regroup sees them, in item order: each key, whether a section header
/// opens before it, and that header's `section_id`. Rows above the first header form one
/// unnamed section.
struct RegroupRows<K> {
    keys: Vec<K>,
    opens: Vec<bool>,
    ids: Vec<Option<String>>,
}

impl<K: Route> RegroupRows<K> {
    fn from_nav(rows: NavRows<K>) -> Self {
        RegroupRows {
            opens: rows.sections.iter().map(Option::is_some).collect(),
            ids: rows.section_ids,
            keys: rows.keys,
        }
    }

    /// From the stand-in list's rows, where each header is a row of its own.
    fn from_sidebar(rows: &[SidebarRow<K>]) -> Self {
        let mut r = RegroupRows {
            keys: Vec::new(),
            opens: Vec::new(),
            ids: Vec::new(),
        };
        let mut header = None;
        for row in rows {
            match &row.key {
                None => header = Some(row.section_id.clone()),
                Some(key) => {
                    r.keys.push(key.clone());
                    r.opens.push(header.is_some());
                    r.ids.push(header.take().flatten());
                }
            }
        }
        r
    }

    /// The rows [`reorder_sidebar`]'s list has: `None` for a header, `Some(i)` for item `i`.
    fn display(&self) -> Vec<Option<usize>> {
        let mut rows = Vec::with_capacity(self.keys.len() * 2);
        for (i, opens) in self.opens.iter().enumerate() {
            if *opens {
                rows.push(None);
            }
            rows.push(Some(i));
        }
        rows
    }

    /// The first item of the section holding item `i`.
    fn section_of(&self, i: usize) -> usize {
        (1..=i).rev().find(|s| self.opens[*s]).unwrap_or(0)
    }

    /// A drop in item indices (`Event::NavRegroup`'s terms) checked against the regroup rules:
    /// `Ok(None)` for a drop back where the row started, which reports nothing.
    fn drop_at(
        &self,
        regroup: &NavRegroup<K>,
        from: usize,
        section: usize,
        before: Option<usize>,
    ) -> Result<Option<NavDrop<K>>, &'static str> {
        let len = self.keys.len();
        let drag = |i: usize| (regroup.drag)(&self.keys[i]);
        if from >= len || drag(from) == NavDrag::Fixed {
            return Err("regroup denied: the row is fixed or out of range");
        }
        if section >= len || (section > 0 && !self.opens[section]) {
            return Err("regroup denied: no section starts at that row");
        }
        let end = (section + 1..len).find(|i| self.opens[*i]).unwrap_or(len);
        if before.is_some_and(|b| b < section || b >= end || b == from) {
            return Err("regroup denied: the row it lands before is not in that section");
        }
        if (section..end).any(|i| drag(i) == NavDrag::Fixed) {
            return Err("regroup denied: a fixed row holds that section");
        }
        if self.section_of(from) == section {
            if drag(from) == NavDrag::Regroup {
                return Err("regroup denied: the row keeps its section's sorted order");
            }
            let next = (from + 1 < end).then_some(from + 1);
            if before == next {
                return Ok(None);
            }
        }
        Ok(Some(NavDrop {
            moved: self.keys[from].clone(),
            section: if self.opens[section] {
                self.ids[section].clone()
            } else {
                None
            },
            before: before.map(|b| self.keys[b].clone()),
        }))
    }

    /// A move of display row `from` to display row `to` (the stand-in list's rotation: the
    /// row ends up at index `to`), as a checked drop. Moving down onto a header lands on that
    /// section's first row; moving up onto one lands at the end of the section above it.
    fn display_drop(
        &self,
        regroup: &NavRegroup<K>,
        from: usize,
        to: usize,
    ) -> Result<Option<NavDrop<K>>, &'static str> {
        let rows = self.display();
        let Some(Some(moved)) = rows.get(from).copied() else {
            return Err("regroup denied: the row is a section header or out of range");
        };
        if to >= rows.len() {
            return Err("regroup denied: the target is out of range");
        }
        // Display rows in their order after the move, named by their index before it.
        let mut order: Vec<usize> = (0..rows.len()).filter(|r| *r != from).collect();
        order.insert(to, from);
        let section = match order[..to].iter().rev().find(|r| rows[**r].is_none()) {
            // A header is always followed by its section's first row.
            Some(header) => rows.get(header + 1).copied().flatten(),
            None => rows[0],
        }
        .ok_or("regroup denied: no section above the first header")?;
        let before = order.get(to + 1).and_then(|r| rows[*r]);
        self.drop_at(regroup, moved, section, before)
    }
}

#[derive(Clone, PartialEq)]
struct SidebarRow<K> {
    id: String,
    parent: Option<String>,
    key: Option<K>,
    /// A header row's `section_id`; `None` on item rows and on headers declared without one.
    section_id: Option<String>,
    title: String,
    icon: Option<String>,
    tint: Option<day_spec::Color>,
    badge: Option<String>,
    badge_icon: Option<String>,
    badge_tint: Option<day_spec::Color>,
    menu: Vec<day_spec::MenuItem>,
}
fn sidebar_rows<K: Route>(rows: NavRows<K>) -> Vec<SidebarRow<K>> {
    let mut result = Vec::new();
    let mut parent = None;
    for (i, key) in rows.keys.into_iter().enumerate() {
        if let Some(title) = &rows.sections[i] {
            let id = rows.section_ids[i].clone().unwrap_or_else(|| key.key());
            let header = format!("header:{id}");
            parent = Some(header.clone());
            result.push(SidebarRow {
                id: header,
                parent: None,
                key: None,
                section_id: rows.section_ids[i].clone(),
                title: title.clone(),
                icon: None,
                tint: None,
                badge: None,
                badge_icon: None,
                badge_tint: None,
                menu: vec![],
            });
        }
        result.push(SidebarRow {
            id: format!("item:{}", key.key()),
            parent: parent.clone(),
            key: Some(key),
            section_id: None,
            title: rows.titles[i].clone(),
            icon: rows.icons[i].clone(),
            tint: rows.tints[i],
            badge: rows.badges[i].clone(),
            badge_icon: rows.badge_icons[i].clone(),
            badge_tint: rows.badge_tints[i],
            menu: rows.menus[i].clone(),
        });
    }
    result
}
fn sidebar_image<K: Route>(slot: ItemSlot<SidebarRow<K>, String>, trailing: bool) -> AnyPiece {
    // Downloaded artwork keeps its colors. Rebuild when a recycled row switches between
    // a bundled placeholder and a local file: template is a realization-time property.
    when(
        move || {
            slot.field(|r| {
                let name = if trailing { &r.badge_icon } else { &r.icon };
                name.as_deref()
                    .is_some_and(|name| std::path::Path::new(name).is_absolute())
            })
        },
        move || sidebar_image_view(slot, trailing, false),
    )
    .otherwise(move || sidebar_image_view(slot, trailing, true))
    .any()
}
fn sidebar_image_view<K: Route>(
    slot: ItemSlot<SidebarRow<K>, String>,
    trailing: bool,
    template: bool,
) -> AnyPiece {
    piece_fn(move |cx| {
        // A template glyph (docs/vectors.md): untinted, it draws in the row's own foreground
        // and follows the theme, as the native nav-menu rows draw theirs. As authored, the
        // bundled art is black on transparent — invisible on a dark sidebar. The row's tint
        // is realized with the view, not only patched in: a patch lands nowhere while the
        // cell holding this row has no native view yet.
        let tint_of = move || slot.field(|r| if trailing { r.badge_tint } else { r.tint });
        let seed = day_reactive::untrack(tint_of);
        let image = image(move || {
            day_spec::ImageSource::Named(slot.field(|r| {
                if trailing {
                    r.badge_icon.clone()
                } else {
                    r.icon.clone()
                }
                .unwrap_or_default()
            }))
        })
        .initial_tint(seed);
        let node = if template { image.template() } else { image }.build(cx);
        bind(tint_of, move |tint| {
            with_tree(|t| {
                t.patch(
                    node,
                    Box::new(day_spec::props::ImagePatch::Tint(*tint)),
                    false,
                )
            });
        });
        node
    })
    .frame(20.0, 20.0)
    .any()
}
fn sidebar_progress<K: Route>(
    slot: ItemSlot<SidebarRow<K>, String>,
    progress: Option<IconProgressSource<K>>,
) -> AnyPiece {
    let activity = Rc::new(move || {
        let key = slot.field(|row| row.key.clone())?;
        progress.as_ref()?()
            .into_iter()
            .find(|(k, _)| k.key() == key.key())
            .map(|(_, fraction)| fraction)
    });
    let (visible, determinate, drawn) = (activity.clone(), activity.clone(), activity);
    when(
        move || visible().is_some(),
        move || {
            let (determinate, drawn) = (determinate.clone(), drawn.clone());
            when(
                move || determinate().flatten().is_some(),
                move || {
                    let drawn = drawn.clone();
                    canvas(move |draw, size| {
                        let fraction = drawn().flatten().unwrap_or(0.0).clamp(0.0, 1.0);
                        let color = slot
                            .field(|r| r.tint)
                            .unwrap_or(day_spec::Color::hex(0x0A84FF));
                        let rect = day_spec::Rect::new(
                            1.0,
                            1.0,
                            (size.width - 2.0).max(0.0),
                            (size.height - 2.0).max(0.0),
                        );
                        draw.stroke(
                            day_spec::Shape::Arc {
                                rect,
                                start_deg: -90.0,
                                sweep_deg: 360.0 * fraction,
                            },
                            color,
                            2.0,
                        );
                    })
                    .frame(20.0, 20.0)
                },
            )
            .otherwise(|| spinner().frame(20.0, 20.0))
        },
    )
    .any()
}
fn section_sidebar<K: Route, S: Binding<K>>(
    rows: Rc<SelItems<K>>,
    selection: S,
    collapsed: AnyBinding<std::collections::HashSet<String>>,
    changed: Option<Rc<dyn Fn(String, bool)>>,
    progress: Option<IconProgressSource<K>>,
) -> AnyPiece {
    use crate::structure::{branches, tree};
    let snapshot = Signal::new(day_reactive::untrack(|| sidebar_rows(rows.derive())));
    bind(
        move || sidebar_rows(rows.derive()),
        move |v| snapshot.set_if_changed(v.clone()),
    );
    let open = Signal::new(std::collections::HashSet::new());
    bind(
        move || {
            let closed = collapsed.get();
            snapshot
                .get()
                .iter()
                .filter(|r| r.key.is_none())
                .filter(|r| !closed.contains(r.id.strip_prefix("header:").unwrap_or(&r.id)))
                .map(|r| r.id.clone())
                .collect::<std::collections::HashSet<_>>()
        },
        move |v| open.set_if_changed(v.clone()),
    );
    let selected = selection.clone();
    tree(
        branches(
            move || snapshot.get(),
            |r: &SidebarRow<K>| r.id.clone(),
            |r| r.parent.clone(),
        ),
        move |slot| {
            let progress = progress.clone();
            piece_fn(move |cx| {
                let node = when(
                    move || slot.field(|r| r.key.is_none()),
                    move || {
                        row((label(move || slot.field(|r| r.title.clone()))
                            .font(day_spec::Font::Caption)
                            .single_line()
                            .grow_w(),))
                        .align(VAlign::Center)
                        .grow()
                        .any()
                    },
                )
                .otherwise(move || {
                    let progress = progress.clone();
                    row((
                        when(
                            move || slot.field(|r| r.icon.is_some()),
                            move || {
                                sidebar_image(slot, false)
                                    .overlay(sidebar_progress(slot, progress.clone()))
                            },
                        ),
                        label(move || slot.field(|r| r.title.clone()))
                            .single_line()
                            .grow_w(),
                        label(move || slot.field(|r| r.badge.clone().unwrap_or_default()))
                            .font(day_spec::Font::Caption),
                        when(
                            move || slot.field(|r| r.badge_icon.is_some()),
                            move || sidebar_image(slot, true),
                        ),
                    ))
                    .spacing(8.0)
                    .align(VAlign::Center)
                    // The surrounding `when` fills the native cell. Its content must
                    // fill the height too, so centering uses the entire selection row.
                    .grow()
                    .any()
                })
                .grow()
                .build(cx);
                with_tree(|t| {
                    t.set_context_menu_fn(node, Rc::new(move |_| slot.field(|r| r.menu.clone())))
                });
                node
            })
        },
    )
    .section_headers()
    .row_height(day_spec::props::RowHeight::Uniform(32.0))
    .expanded(open)
    .on_expansion(move |id, expanded| {
        let Some(id) = id.strip_prefix("header:") else {
            return;
        };
        collapsed.update(|s| {
            if expanded {
                s.remove(id);
            } else {
                s.insert(id.to_owned());
            }
        });
        if let Some(f) = &changed {
            f(id.to_owned(), expanded);
        }
    })
    .selected(move || vec![format!("item:{}", selected.read().key())])
    .on_selection(move |ids| {
        let Some(row) = snapshot
            .get()
            .into_iter()
            .find(|r| ids.contains(&r.id) && r.key.is_some())
        else {
            return;
        };
        if let Some(key) = row.key {
            day_core::note_navigation(&key.key(), Some(&row.title));
            selection.write(key);
        }
    })
    .type_ahead(move |id| {
        snapshot
            .get()
            .iter()
            .find(|r| &r.id == id)
            .map(|r| r.title.clone())
            .unwrap_or_default()
    })
    .row_id(|id| day_core::id!(sidebar, id))
    .id(day_core::id!(nav_sections))
    .grow()
    .any()
}

/// A dayscript `reorder` of a toolkit's own sidebar (`Cap::NavReorder` Native), in the rows
/// [`reorder_sidebar`]'s list would have: a header row before each section, so one script
/// drives both. A row moves within the run of movable rows around it; `to` is where it lands,
/// the row whose place it takes in the order before the move. A regrouping nav's script goes
/// through [`RegroupRows::display_drop`] instead, the stand-in list's rule.
fn script_nav_reorder<K: Route>(
    keys: &[K],
    sections: &[Option<String>],
    reorder: &NavReorder<K>,
    from: usize,
    to: usize,
) -> Result<usize, &'static str> {
    let mut rows: Vec<Option<usize>> = Vec::with_capacity(keys.len() * 2);
    for i in 0..keys.len() {
        if sections.get(i).is_some_and(Option::is_some) {
            rows.push(None);
        }
        rows.push(Some(i));
    }
    let movable = |r: usize| {
        rows.get(r)
            .copied()
            .flatten()
            .is_some_and(|i| (reorder.eligible)(&keys[i]))
    };
    if !movable(from) || to >= rows.len() {
        return Err("reorder denied: the row is fixed or the target is out of range");
    }
    let (lo, hi) = (from.min(to), from.max(to));
    if !(lo..=hi).all(movable) {
        return Err("reorder denied: a fixed row or a section header is in the way");
    }
    if let (Some(Some(a)), Some(Some(b))) = (rows.get(from), rows.get(to))
        && a != b
    {
        (reorder.moved)(keys[*a].clone(), keys[*b].clone());
    }
    Ok(to)
}

fn reorder_sidebar<K: Route, S: Binding<K>>(
    rows: Rc<SelItems<K>>,
    selection: S,
    drag: SidebarDrag<K>,
    progress: Option<IconProgressSource<K>>,
) -> AnyPiece {
    // Pure drag callbacks read the committed snapshot, never re-run application row builders.
    let snapshot = Signal::new(day_reactive::untrack(|| sidebar_rows(rows.derive())));
    bind(
        move || sidebar_rows(rows.derive()),
        move |value| snapshot.set_if_changed(value.clone()),
    );
    let source = Rc::new(move || snapshot.get());
    let selection_revision = Signal::new(0u64);
    let (read, guard, commit, selected) = (
        source.clone(),
        source.clone(),
        source.clone(),
        source.clone(),
    );
    let selected_binding = selection.clone();
    let tapped_selection = selection.clone();
    list(
        items(move || read(), |r: &SidebarRow<K>| r.id.clone()),
        move |slot| {
            let activity = progress.clone();
            let tapped_selection = tapped_selection.clone();
            piece_fn(move |cx| {
                let node = row((when(
                    move || slot.field(|r| r.key.is_none()),
                    move || {
                        label(move || slot.field(|r| r.title.clone()))
                            .font(day_spec::Font::Caption)
                            .padding(day_spec::Insets::symmetric(8.0, 0.0))
                            .grow_w()
                    },
                )
                .otherwise(move || {
                    let activity = activity.clone();
                    row((
                        when(
                            move || slot.field(|r| r.icon.is_some()),
                            move || {
                                sidebar_image(slot, false)
                                    .overlay(sidebar_progress(slot, activity.clone()))
                            },
                        ),
                        label(move || slot.field(|r| r.title.clone()))
                            .single_line()
                            .grow_w(),
                        label(move || slot.field(|r| r.badge.clone().unwrap_or_default()))
                            .font(day_spec::Font::Caption),
                        when(
                            move || slot.field(|r| r.badge_icon.is_some()),
                            move || sidebar_image(slot, true),
                        ),
                    ))
                    .spacing(8.0)
                    .align(VAlign::Center)
                    .padding(day_spec::Insets::symmetric(8.0, 0.0))
                    .grow_w()
                }),))
                .align(VAlign::Center)
                .grow()
                .id_of(move || day_core::id!(sidebar, slot.field(|r| r.id.clone())))
                .on_tap(move || {
                    if let Some(key) = slot.field(|r| r.key.clone()) {
                        let title = slot.field(|r| r.title.clone());
                        day_core::note_navigation(&key.key(), Some(&title));
                        tapped_selection.write(key);
                    }
                })
                .build(cx);
                with_tree(|t| {
                    t.set_context_menu_fn(node, Rc::new(move |_| slot.field(|r| r.menu.clone())))
                });
                node
            })
        },
    )
    .row_height(day_spec::props::RowHeight::Uniform(36.0))
    .on_select(move |id| {
        selection_revision.update(|n| *n = n.wrapping_add(1));
        if let Some(row) = source().into_iter().find(|r| r.id == id)
            && let Some(key) = row.key
        {
            day_core::note_navigation(&key.key(), Some(&row.title));
            selection.write(key);
        }
    })
    .selected_rows(move || {
        selection_revision.get();
        selected()
            .iter()
            .position(|r| {
                r.key
                    .as_ref()
                    .is_some_and(|k| k.key() == selected_binding.read().key())
            })
            .into_iter()
            .collect()
    })
    .reorderable(match drag {
        SidebarDrag::Reorder(reorder) => crate::Reorder::new(move |from, to| {
            let rows = commit();
            if let (Some(a), Some(b)) = (
                rows.get(from).and_then(|r| r.key.clone()),
                rows.get(to).and_then(|r| r.key.clone()),
            ) {
                (reorder.moved)(a, b);
            }
        })
        .guard(move |from, to| {
            let rows = guard();
            if from >= rows.len()
                || to >= rows.len()
                || rows[from.min(to)..=from.max(to)]
                    .iter()
                    .any(|r| r.key.as_ref().is_none_or(|k| !(reorder.eligible)(k)))
            {
                ReorderVerdict::Deny
            } else {
                ReorderVerdict::Allow
            }
        }),
        // Headers are rows here, so the list's move names a destination section by where the
        // row lands among them (`RegroupRows::display_drop`).
        SidebarDrag::Regroup(regroup) => {
            let check = regroup.clone();
            crate::Reorder::new(move |from, to| {
                let rows = RegroupRows::from_sidebar(&commit());
                if let Ok(Some(drop)) = rows.display_drop(&regroup, from, to) {
                    (regroup.dropped)(drop);
                }
            })
            .guard(move |from, to| {
                match RegroupRows::from_sidebar(&guard()).display_drop(&check, from, to) {
                    Ok(_) => ReorderVerdict::Allow,
                    Err(_) => ReorderVerdict::Deny,
                }
            })
        }
    })
    .id(day_core::id!(nav_reorder_list))
    .grow()
    .any()
}

/// One nav's live rows, flattened across its static items and dynamic blocks.
struct NavRows<K> {
    keys: Vec<K>,
    titles: Vec<String>,
    icons: Vec<Option<String>>,
    badges: Vec<Option<String>>,
    badge_icons: Vec<Option<String>>,
    badge_tints: Vec<Option<day_spec::Color>>,
    sections: Vec<Option<String>>,
    section_ids: Vec<Option<String>>,
    tints: Vec<Option<day_spec::Color>>,
    menus: Vec<Vec<day_spec::MenuItem>>,
}

struct SelItems<K> {
    static_builders: std::collections::HashMap<String, PageFn>,
    /// Page builders carried by the rows of data-driven blocks, refreshed on every derive.
    dynamic_builders: RefCell<std::collections::HashMap<String, PageFn>>,
    meta: Rc<Vec<MetaSource<K>>>,
    destination: Option<DestFn<K>>,
}

impl<K: Route> SelItems<K> {
    fn from_sources(sources: Vec<ItemSource<K>>, destination: Option<DestFn<K>>) -> Self {
        let mut static_builders = std::collections::HashMap::new();
        let mut meta = Vec::new();
        for src in sources {
            match src {
                ItemSource::Static(it) => {
                    if let Some(b) = it.build {
                        static_builders.insert(it.key.key(), b);
                    }
                    meta.push(MetaSource::Static(
                        it.key,
                        it.title,
                        RowMeta {
                            icon: it.icon,
                            tint: it.tint,
                            menu: it.menu,
                            badge: it.badge,
                            badge_icon: it.badge_icon,
                            badge_tint: it.badge_tint,
                            section: it.section,
                        },
                        it.immersive,
                    ));
                }
                ItemSource::Dynamic(f) => {
                    meta.push(MetaSource::Dynamic(f));
                }
            }
        }
        SelItems {
            static_builders,
            dynamic_builders: RefCell::new(std::collections::HashMap::new()),
            meta: Rc::new(meta),
            destination,
        }
    }

    /// The flat live rows: (typed keys, resolved titles, icons). Tracked, because reading
    /// a `Dynamic` block's signal subscribes the caller (the derive effect) to row changes,
    /// and resolving each title through [`TextSource::resolve`] subscribes it to the locale,
    /// so `set_locale` re-runs the effect and the native rows retitle (docs/navigation.md).
    fn derive(&self) -> NavRows<K> {
        let mut r = NavRows {
            keys: Vec::new(),
            titles: Vec::new(),
            icons: Vec::new(),
            badges: Vec::new(),
            badge_icons: Vec::new(),
            badge_tints: Vec::new(),
            sections: Vec::new(),
            section_ids: Vec::new(),
            tints: Vec::new(),
            menus: Vec::new(),
        };
        let mut push = |k: K, title: String, m: &RowMeta| {
            r.keys.push(k);
            r.titles.push(title);
            r.icons.push(m.icon.clone());
            // Empty text is no badge: a toolkit given `Some("")` draws a bare dot (UIKit does).
            r.badges.push(
                m.badge
                    .as_ref()
                    .map(|b| b.resolve())
                    .filter(|b| !b.is_empty()),
            );
            r.badge_icons.push(m.badge_icon.clone());
            r.badge_tints.push(m.badge_tint);
            r.sections
                .push(m.section.as_ref().map(|s| s.title.resolve()));
            r.section_ids
                .push(m.section.as_ref().and_then(|s| s.id.clone()));
            r.tints.push(m.tint);
            r.menus.push(m.menu.clone());
        };
        for ms in self.meta.iter() {
            match ms {
                MetaSource::Static(k, t, m, _) => push(k.clone(), t.resolve(), m),
                MetaSource::Dynamic(f) => {
                    for it in f() {
                        if let Some(b) = it.build {
                            self.dynamic_builders.borrow_mut().insert(it.key.key(), b);
                        }
                        let m = RowMeta {
                            icon: it.icon,
                            tint: it.tint,
                            menu: it.menu,
                            badge: it.badge,
                            badge_icon: it.badge_icon,
                            badge_tint: it.badge_tint,
                            section: it.section,
                        };
                        let title = it.title.resolve();
                        push(it.key, title, &m);
                    }
                }
            }
        }
        r
    }

    /// An item's immersive-chrome flag (docs/navigation.md). A data-driven key checks its
    /// block's current rows untracked: chrome is resolved at push time, not a dependency of
    /// the push (a tracked read here would re-run the selection effect on every list change).
    fn immersive_of(&self, key: &str) -> bool {
        self.meta.iter().any(|ms| match ms {
            MetaSource::Static(k, _, _, imm) => *imm && k.key() == key,
            MetaSource::Dynamic(f) => {
                day_reactive::untrack(|| f().iter().any(|it| it.immersive && it.key.key() == key))
            }
        })
    }

    /// A static item's live title source (locale-reactive retitle); `None` for a data-driven
    /// key, whose title is a resolved snapshot from the derived list.
    fn static_title(&self, key: &str) -> Option<TextSource> {
        self.meta.iter().find_map(|ms| match ms {
            MetaSource::Static(k, t, _, _) if k.key() == key => Some(t.clone()),
            _ => None,
        })
    }

    /// Build a key's page: the item's own builder (static, or carried by a data-driven row),
    /// else the `.destination` fallback, else a blank leaf (misconfigured: an item with neither).
    fn build_page(&self, key: &K) -> AnyPiece {
        let k = key.key();
        let dynamic = self.dynamic_builders.borrow().get(&k).cloned();
        if let Some(b) = self.static_builders.get(&k) {
            b()
        } else if let Some(b) = dynamic {
            b()
        } else if let Some(d) = &self.destination {
            d(key)
        } else {
            piece_fn(|cx| cx.layout_only(Rc::new(PassThrough), Flex::default(), Boundary::No)).any()
        }
    }
}

type IconProgressSource<K> = Rc<dyn Fn() -> Vec<(K, Option<f64>)>>;

/// A one-of-N nav whose active key is an app-owned signal (two-way, exactly like
/// `Picker`/`Toggle`). Deep links and dayscript address items by key (docs/navigation.md).
///
/// The key type is any [`Route`]: `String` for raw keys, or a typed enum; use
/// `Signal<Option<Section>>` for a sidebar (`None` = the collapsed mobile list) and
/// `Signal<Tab>` for tabs (always selected).
///
/// ```ignore
/// let section = Signal::new("home".to_string());   // or Signal::new(None::<Section>)
/// nav(section).style(NavStyle::Sidebar)
///     .item("home", tr("home"), home_page)         // or .item(Section::Home, …)
///     .item("settings", tr("settings"), settings_page)
/// ```
type DocumentEvent = Rc<dyn Fn(&Event)>;
type RefreshSource = (Reactive<bool>, Rc<dyn Fn()>);

pub struct Nav<S: Binding<K>, K: Route = String> {
    selection: S,
    documents: Option<day_spec::props::DocumentTabsConfig>,
    document_event: Option<DocumentEvent>,
    icon_progress: Option<IconProgressSource<K>>,
    refresh: Option<RefreshSource>,
    style: NavStyle,
    title: TextSource,
    header: Option<Box<dyn FnOnce() -> AnyPiece>>,
    footer: Option<Box<dyn FnOnce() -> AnyPiece>>,
    sources: Vec<ItemSource<K>>,
    /// Builds the page for a key with no static item (a data-driven item from `.items`).
    destination: Option<DestFn<K>>,
    /// Whether this nav contributes to the app route (deep links / dayscript). `false`
    /// (`.local()`) for a nav used as a self-contained widget, so it does not add a segment
    /// to `current_route` or intercept `navigate` (docs/navigation.md).
    routed: bool,
    /// The persistence key set by [`Nav::restore`]: the selected item's key is saved here on
    /// every change and restored at build (unless a launch deep link is pending). `None` = not
    /// persisted.
    restore: Option<String>,
    /// Keep a filtered-out selection while its underlying record still exists.
    retain_selection: Option<ListPred<K>>,
    /// Sidebar dragging ([`Nav::reorder_items`] or [`Nav::regroup_items`], the later wins).
    reorder_items: Option<SidebarDrag<K>>,
    collapsed_sections: Option<AnyBinding<std::collections::HashSet<String>>>,
    on_section_expansion: Option<Rc<dyn Fn(String, bool)>>,
    /// Items declared on this host's own chrome ([`Nav::toolbar`]).
    toolbar: Vec<crate::ToolbarSource>,
    /// Draw the platform's own sidebar toggle (off with [`Nav::no_sidebar_toggle`]).
    sidebar_toggle: bool,
    /// Search over this surface ([`Nav::searchable`]). `None` unless set.
    search: Option<SearchSpec>,
    /// The presentation pinned by [`Nav::presentation`]; `None` = automatic, resolved from
    /// the window's size class and re-resolved whenever it changes.
    presentation: Option<day_spec::props::NavPresentation>,
    /// The content-list pane builder ([`Nav::content_list`], docs/navigation.md): the
    /// Mail shape's middle column, built once and resident for the host's life. `None` = the
    /// classic two-pane nav.
    content_list: Option<Rc<dyn Fn() -> AnyPiece>>,
    /// Preferred width of the content-list pane in points.
    content_list_width: f64,
    /// Which destinations show the pane ([`Nav::content_list_for`]); `None` = all of them.
    content_list_pred: Option<ListPred<K>>,
    /// Whether the detail is showing, two-way ([`ContentList::detail_visible`]): what gates
    /// the detail push in a stacked presentation with a content list, and what native back
    /// writes `false` into. `None` = the detail behaves classically (pushed on selection).
    detail_visible: Option<AnyBinding<bool>>,
    /// The navigation-bar title of the detail layer a content list opens
    /// ([`ContentList::detail_title`]). `None` = the destination's own title.
    detail_title: Option<TextSource>,
}

/// Search over a navigation surface (docs/search.md), declared with [`Nav::searchable`]:
/// `Search::new(query).prompt(res::str::search()).reveal(SearchReveal::OnPull)`.
///
/// Search is declared on the surface, not on the toolbar, the same move SwiftUI made with
/// `.searchable()`. That is what lets the platform choose where to draw the field: the window
/// toolbar on a wide window, attached to the navigation list on a narrow one, without the app
/// branching on either. The query and the scope are app-owned bindings, which is what lets the
/// field move between placements without the state moving with it. A `Search` holds those
/// bindings, so build it where the nav is built; it is not a value to share across windows.
pub struct Search {
    query: AnyBinding<String>,
    prompt: Option<TextSource>,
    placement: day_spec::props::SearchPlacement,
    reveal: SearchReveal,
    /// Scope titles and the binding holding the chosen index. Empty titles = no scope bar.
    scopes: Vec<TextSource>,
    scope: Option<AnyBinding<usize>>,
    /// Completions for the current text, re-derived whenever its reactive reads change.
    suggestions: Option<SuggestFn>,
    /// Runs with the field's text when the user presses its Return or Search key.
    submit: Option<SubmitFn>,
    /// Whether a page's field is offered right now; `None` = always.
    available: Option<crate::Reactive<bool>>,
}

/// What [`Search::on_submit`] runs.
type SubmitFn = Rc<dyn Fn(&str)>;

/// How a navigation surface's search field comes and goes on a phone (docs/search.md). The
/// desktop toolbar field is always there whatever this says.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SearchReveal {
    /// The field is always shown.
    #[default]
    Always,
    /// The field and the title chrome collapse as the root list scrolls.
    Scrolls,
    /// The field starts hidden and is revealed by pulling down on the list; it collapses on
    /// scroll afterwards (iOS owns the reveal/collapse transitions, with a compact title).
    OnPull,
}

impl Search {
    /// Search bound two-way to `query` (a `Signal<String>` or any other binding).
    pub fn new(query: impl Binding<String>) -> Search {
        Search {
            query: AnyBinding::new(query),
            prompt: None,
            placement: day_spec::props::SearchPlacement::Automatic,
            reveal: SearchReveal::Always,
            scopes: Vec::new(),
            scope: None,
            suggestions: None,
            submit: None,
            available: None,
        }
    }
    /// The field's empty-state prompt.
    pub fn prompt<M>(mut self, prompt: impl IntoText<M>) -> Search {
        self.prompt = Some(prompt.into_text());
        self
    }
    /// Ask for a particular placement. A preference: a backend that cannot honor it falls back
    /// to its platform's own convention, so `Automatic` (the default) is almost always right.
    pub fn placement(mut self, placement: day_spec::props::SearchPlacement) -> Search {
        self.placement = placement;
        self
    }
    /// How the field comes and goes on a phone (default [`SearchReveal::Always`]).
    pub fn reveal(mut self, reveal: SearchReveal) -> Search {
        self.reveal = reveal;
        self
    }
    /// A one-of-N scope bar under the field, bound to `scope` (an index into `titles`).
    ///
    /// Native on UIKit alone; elsewhere it is a native component doing the same job (a
    /// Material `ChipGroup` of single-selection filter chips, an ArkUI `SegmentButtonV2`, an
    /// `NSSegmentedControl`) or, on web and system XAML, one composed from primitives.
    pub fn scopes<M>(
        mut self,
        scope: impl Binding<usize>,
        titles: impl IntoIterator<Item = impl IntoText<M>>,
    ) -> Search {
        self.scopes = titles.into_iter().map(IntoText::into_text).collect();
        self.scope = Some(AnyBinding::new(scope));
        self
    }
    /// Completions for the current text, re-derived whenever a reactive read inside `f` changes.
    ///
    /// On a navigation surface these complete the field rather than replacing the list: the list
    /// is already the filtered result set, so an overlay of results would cover the very thing it
    /// is narrowing. Backends whose search widget does completions natively use it
    /// (`AutoSuggestBox`, `QCompleter`, `<datalist>`, `UISearchResultsUpdating`).
    pub fn suggestions(mut self, f: impl Fn(&str) -> Vec<String> + 'static) -> Search {
        self.suggestions = Some(Rc::new(f));
        self
    }
    /// Run `f` with the field's text when the user presses its Return or Search key: the
    /// trigger for a search that runs on demand (a server query) instead of narrowing as the
    /// text changes. `query` already holds the text when `f` runs.
    pub fn on_submit(mut self, f: impl Fn(&str) + 'static) -> Search {
        self.submit = Some(Rc::new(f));
        self
    }
    /// Offer a page's field only while `v` is true (default: always), for a page that learns
    /// whether it can be searched after it shows: a feed that has to load first. The field
    /// keeps its text while it is withdrawn. A navigation surface's search ignores this.
    pub fn available<M>(mut self, v: impl crate::IntoReactive<bool, M>) -> Search {
        self.available = Some(v.into_reactive());
        self
    }
}

/// Install a navigation page's own search field (docs/search.md, "Page search"): the reserved
/// `day::search` item on the page's chrome, which each toolkit draws where its platform puts a
/// page's search (the window toolbar on a desktop, the page's navigation bar on iOS, its app bar
/// on Android). The field shows while its page does and leaves with it.
///
/// The same one-model rule as a surface's search: the item is a rendering of the app's
/// `query`, inbound edits write the signal, and one outbound binding patches the item.
pub(crate) fn install_page_search(search: Search) {
    let chrome = day_core::current_chrome();
    let active = day_core::current_page_gate();
    let column = day_core::current_page_column();
    let query = search.query;
    let text = query.get_untracked();
    // The prompt follows the locale (a `res::str` text re-resolves): the item is re-registered
    // below when it changes, so the field's placeholder is never left in the old language.
    let prompt_source = search.prompt.clone();
    let prompt: Rc<RefCell<String>> = Rc::new(RefCell::new(
        prompt_source
            .as_ref()
            .map(TextSource::initial)
            .unwrap_or_default(),
    ));
    let suggestions = search
        .suggestions
        .as_ref()
        .map(|f| day_reactive::untrack(|| f(&text)))
        .unwrap_or_default();
    // What the field shows, by value (see `SearchSpec::install`).
    let shown: Rc<RefCell<String>> = Rc::new(RefCell::new(text.clone()));
    let action = {
        let shown = shown.clone();
        let submit = search.submit.clone();
        day_core::register_toolbar_value(Rc::new(move |v: &day_spec::ToolbarValue| match v {
            day_spec::ToolbarValue::Text(t) => {
                *shown.borrow_mut() = t.clone();
                query.set(t.clone());
            }
            day_spec::ToolbarValue::Submit(t) => {
                if let Some(f) = &submit {
                    f(t);
                }
            }
            _ => {}
        }))
    };
    let item_prompt = prompt.clone();
    let item = move |text: String, suggestions: Vec<String>| day_spec::ToolbarItem {
        id: day_core::id!(day::search).as_str().to_owned(),
        kind: day_spec::ToolbarItemKind::Search {
            text,
            placeholder: item_prompt.borrow().clone(),
            suggestions,
        },
        label: item_prompt.borrow().clone(),
        tooltip: None,
        icon: None,
        enabled: true,
        action,
        placement: day_spec::ToolbarPlacement::Secondary,
        label_style: day_spec::LabelStyle::Automatic,
        prominent: false,
        column,
    };
    let available = search.available.clone();
    let offered = available.as_ref().is_none_or(|v| v.get_untracked());
    let offered_now = Rc::new(Cell::new(offered));
    let item = Rc::new(item);
    let token = day_core::register_contribution_gated(
        chrome,
        if offered {
            vec![item(text.clone(), suggestions.clone())]
        } else {
            Vec::new()
        },
        active.clone(),
    );
    // Offered and withdrawn as the page learns whether it can be searched, seeded with what the
    // field showed so a field that comes back holds its text.
    if let Some(crate::Reactive::Dyn(f)) = available {
        let (shown, suggest, query) = (shown.clone(), search.suggestions.clone(), query);
        let (item, offered_now) = (item.clone(), offered_now.clone());
        bind_seeded(
            offered,
            move || f(),
            move |on: &bool| {
                offered_now.set(*on);
                let items = if *on {
                    let text = shown.borrow().clone();
                    let list = suggest
                        .as_ref()
                        .map(|f| day_reactive::untrack(|| f(&query.get_untracked())))
                        .unwrap_or_default();
                    vec![item(text, list)]
                } else {
                    Vec::new()
                };
                day_core::update_contribution(token, items);
            },
        );
    }
    if let Some(TextSource::Dyn(read)) = prompt_source {
        let (shown, suggest, item) = (shown.clone(), search.suggestions.clone(), item.clone());
        let seed = prompt.borrow().clone();
        bind_seeded(
            seed,
            move || read(),
            move |p: &String| {
                *prompt.borrow_mut() = p.clone();
                if offered_now.get() {
                    let text = shown.borrow().clone();
                    let list = suggest
                        .as_ref()
                        .map(|f| day_reactive::untrack(|| f(&query.get_untracked())))
                        .unwrap_or_default();
                    day_core::update_contribution(token, vec![item(text, list)]);
                }
            },
        );
    }
    // Recompose as the page comes and goes, as `.toolbar(…)` does.
    if let Some(gate) = active {
        day_reactive::Effect::new(move || {
            let _ = gate();
            day_core::chrome_changed();
        });
    }
    Scope::current().on_cleanup(move || day_core::unregister_contribution(token));
    bind_seeded(
        text,
        move || query.get(),
        move |t: &String| {
            if *shown.borrow() == *t {
                return;
            }
            *shown.borrow_mut() = t.clone();
            day_core::patch_chrome(
                chrome,
                day_spec::ToolbarPatch::Text {
                    item: SEARCH_ITEM_ID.to_string(),
                    text: t.clone(),
                },
            );
        },
    );
    if let Some(f) = search.suggestions {
        bind_seeded(
            suggestions,
            move || f(&query.get()),
            move |list| {
                day_core::patch_chrome(
                    chrome,
                    day_spec::ToolbarPatch::Suggestions {
                        item: SEARCH_ITEM_ID.to_string(),
                        list: list.clone(),
                    },
                )
            },
        );
    }
}

/// The content-list pane of a Mail-shaped nav (docs/navigation.md), declared with
/// [`Nav::content_list`]: mailboxes, message list, message. `build` makes the middle column,
/// built once and resident for the host's life; its content follows the app's own signals
/// (the selection scoping it, the row chosen from it), never a rebuild.
///
/// Where the toolkit has a native pane (`Cap::NavContentList`) the list gets its own column
/// (an AppKit `contentList` split item, a UIKit supplementary column) and otherwise the nav
/// composes it beside (split) or in place of (stacked) each destination. Pair it with
/// [`detail_visible`](ContentList::detail_visible) so compact widths get the list-then-detail
/// push flow, and [`only_for`](ContentList::only_for) to give full-width destinations (a
/// settings page) the whole detail area.
pub struct ContentList<K = String> {
    build: Rc<dyn Fn() -> AnyPiece>,
    width: f64,
    pred: Option<ListPred<K>>,
    detail_visible: Option<AnyBinding<bool>>,
    detail_title: Option<TextSource>,
}

impl<K> ContentList<K> {
    /// The pane, from its builder.
    pub fn new<P: Piece>(build: impl Fn() -> P + 'static) -> ContentList<K> {
        ContentList {
            build: Rc::new(move || AnyPiece::new(build())),
            width: day_spec::NAV_LIST_WIDTH,
            pred: None,
            detail_visible: None,
            detail_title: None,
        }
    }
    /// Preferred width of the pane in points (default [`day_spec::NAV_LIST_WIDTH`]). Where the
    /// divider is user-draggable this is the initial width, not a limit.
    pub fn width(mut self, width: f64) -> ContentList<K> {
        self.width = width;
        self
    }
    /// Which destinations show the pane (default: all of them). A destination answering
    /// `false` collapses the pane and takes the whole detail area: the settings page beside a
    /// mail-shaped app.
    pub fn only_for(mut self, pred: impl Fn(&K) -> bool + 'static) -> ContentList<K> {
        self.pred = Some(Rc::new(pred));
        self
    }
    /// Whether the detail is showing, two-way (a `Signal<bool>` or any other binding).
    /// Split-family presentations ignore it: the detail pane is always there, showing the
    /// app's empty state until a row is chosen. A stacked presentation (a phone, a collapsed
    /// split) uses it as the push gate: the list is the top of the stack until the app writes
    /// `true` (a row was opened), the detail pushes then, and the platform's back writes
    /// `false` on the way out.
    pub fn detail_visible(mut self, visible: impl Binding<bool>) -> ContentList<K> {
        self.detail_visible = Some(AnyBinding::new(visible));
        self
    }
    /// The detail shows while `selected` holds a value: [`detail_visible`](Self::detail_visible)
    /// for a list whose selection is the detail's subject. Writing `Some` opens the detail on a
    /// stacked presentation; the platform's back writes `None`, which clears the selection.
    ///
    /// ```ignore
    /// ContentList::new(item_list).detail_for(scene.selected)
    /// ```
    pub fn detail_for<T: Clone + 'static>(
        self,
        selected: impl Binding<Option<T>>,
    ) -> ContentList<K> {
        self.detail_visible(Presence(AnyBinding::new(selected)))
    }
    /// The navigation-bar title of the detail layer the list opens: the editor a phone pushes
    /// over the list, the detail column's bar where the toolkit titles one. Reactive like every
    /// title: pass a closure reading your own state to title the page after the item it shows.
    /// Unset, the detail layer keeps its destination's title.
    pub fn detail_title<M>(mut self, t: impl IntoText<M>) -> ContentList<K> {
        self.detail_title = Some(t.into_text());
        self
    }
}

/// [`ContentList::detail_for`]'s gate: `true` while the binding holds a value. Writing `false`
/// clears it; `true` comes only from the app writing a value.
#[derive(Clone)]
struct Presence<T: 'static>(AnyBinding<Option<T>>);

impl<T: Clone + 'static> Binding<bool> for Presence<T> {
    fn read(&self) -> bool {
        self.0.get().is_some()
    }
    fn peek(&self) -> bool {
        self.0.get_untracked().is_some()
    }
    fn write(&self, open: bool) {
        if !open && self.peek() {
            self.0.set(None);
        }
    }
    fn write_teardown(&self, _open: bool) {}
}

/// Collapsible sidebar sections (docs/navigation.md), declared with [`Nav::sections`]. The
/// state is the set of COLLAPSED section ids; missing ids default to expanded, and temporarily
/// filtered-out ids are retained. Pair with [`Nav::section_id`] for stable identities; unkeyed
/// headings use their first route as a fallback identity. Takes precedence over
/// [`Nav::reorder_items`] and [`Nav::regroup_items`]; combined collapse/reordering is not
/// supported.
pub struct Sections {
    collapsed: AnyBinding<std::collections::HashSet<String>>,
    on_change: Option<Rc<dyn Fn(String, bool)>>,
}

impl Sections {
    /// Sections whose collapsed set is app state (a `Signal<HashSet<String>>` or any binding).
    pub fn collapsible(collapsed: impl Binding<std::collections::HashSet<String>>) -> Sections {
        Sections {
            collapsed: AnyBinding::new(collapsed),
            on_change: None,
        }
    }
    /// Sections whose collapsed set is persisted under `key` through the installed `NavStore`,
    /// restored at build and saved on every change.
    pub fn restored(key: impl Into<String>) -> Sections {
        let key = key.into();
        let saved = day_core::nav_store_load(&key).unwrap_or_default();
        let mut rest = saved.as_str();
        let mut ids = std::collections::HashSet::new();
        while let Some((len, tail)) = rest.split_once(':') {
            let Some(len) = len.parse::<usize>().ok() else {
                break;
            };
            let Some(id) = tail.get(..len) else {
                break;
            };
            ids.insert(id.to_owned());
            rest = &tail[len..];
        }
        let state = Signal::new(ids);
        bind(
            move || state.get(),
            move |ids| {
                let mut ids: Vec<_> = ids.iter().collect();
                ids.sort();
                let saved = ids
                    .iter()
                    .map(|id| format!("{}:{id}", id.len()))
                    .collect::<String>();
                day_core::nav_store_save(&key, &saved);
            },
        );
        Sections::collapsible(state)
    }
    /// Reports user/scripting disclosure after the collapsed set changed. Programmatic state
    /// writes and restoration do not call it.
    pub fn on_change(mut self, f: impl Fn(String, bool) + 'static) -> Sections {
        self.on_change = Some(Rc::new(f));
        self
    }
}

/// The lowered form of a [`Search`], kept on the nav until build.
struct SearchSpec {
    query: AnyBinding<String>,
    prompt: Option<TextSource>,
    placement: day_spec::props::SearchPlacement,
    hides_on_scroll: bool,
    initially_hidden: bool,
    scopes: Vec<TextSource>,
    scope: Option<AnyBinding<usize>>,
    suggestions: Option<SuggestFn>,
    submit: Option<SubmitFn>,
}

impl SearchSpec {
    /// Turn a requested placement into the one this toolkit will actually use (docs/search.md).
    ///
    /// `Automatic` asks the platform. Today the answer is the window toolbar wherever that
    /// toolbar can hold a search field, and inline (attached to the navigation surface) where it
    /// cannot, which is the phones: their bar is a row of actions. That needs no size class:
    /// "this toolkit's bar holds no field" is a static fact about the backend, not a question
    /// about the window's width. Resolving a narrow window on a toolkit whose bar does hold one
    /// is what waits on the size-class work.
    ///
    /// An explicit `Toolbar` falls back to `Inline` on those same backends, since a field the
    /// bar cannot draw would otherwise not be drawn at all.
    ///
    /// Never returns `Automatic`: the props carry the decision, so a backend reads a placement it
    /// can act on rather than re-deriving the policy itself.
    fn resolve(requested: day_spec::props::SearchPlacement) -> day_spec::props::SearchPlacement {
        use day_spec::props::SearchPlacement as P;
        use day_spec::{Cap, Support};
        let can = |cap| with_tree(|t| t.capability(cap)) != Support::Unsupported;
        match requested {
            P::Inline => P::Inline,
            P::Toolbar if can(Cap::ToolbarSearch) => P::Toolbar,
            P::Automatic if can(Cap::Toolbar) && can(Cap::ToolbarSearch) => P::Toolbar,
            P::Toolbar | P::Automatic => P::Inline,
        }
    }

    /// The props the host is realized with: current values only. Everything live rides the
    /// bindings in [`SearchSpec::bind`].
    fn lower(&self) -> day_spec::props::SearchProps {
        let text = self.query.get_untracked();
        day_spec::props::SearchProps {
            suggestions: self
                .suggestions
                .as_ref()
                .map(|f| day_reactive::untrack(|| f(&text)))
                .unwrap_or_default(),
            text,
            prompt: self
                .prompt
                .as_ref()
                .map(TextSource::initial)
                .unwrap_or_default(),
            // The resolved placement, so a backend reads a decision rather than a request.
            placement: Self::resolve(self.placement),
            hides_on_scroll: self.hides_on_scroll,
            initially_hidden: self.initially_hidden,
            scopes: self.scopes.iter().map(TextSource::initial).collect(),
            scope: self.scope.map(|s| s.get_untracked()).unwrap_or(0),
        }
    }

    /// Install the field and wire it, both directions (docs/search.md).
    ///
    /// One model, one writer. `SearchProps` on the nav host is the model for every
    /// placement; the toolbar item a desktop backend draws is a rendering of it, not a second
    /// representation with its own state. Both inbound transports (a toolbar value callback and
    /// `Event::SearchChanged` from an inline field) land on the same `apply` closure, and the
    /// single outbound binding patches whichever target the resolved placement renders into.
    ///
    /// That is what makes a future placement change tractable: the state does not live in the
    /// widget, so re-rendering into the other target is a patch rather than a rebuild. The
    /// remaining step for the size-class work is a `SearchPatch::Placement` that swaps the render
    /// target on a live host; see docs/search.md.
    fn install(&self, host: RNode, chrome: day_core::Chrome, seed: &day_spec::props::SearchProps) {
        use day_spec::props::{SearchPatch, SearchPlacement as P};
        let placement = Self::resolve(self.placement);
        let query = self.query;
        // Controlled input (§4.4), tracked by value rather than by origin.
        //
        // This used to be a one-shot origin guard: the inbound handler armed it with the text the
        // field reported, and the outbound binding consumed it to avoid patching that same text
        // back. One-shot is the wrong shape for a two-way sync. Whether it is armed at the moment
        // the binding runs depends on how many changes arrived first and whether the binding ran
        // at all, so it swallowed patches it should have sent (a cleared query that never reached
        // the field) and let through patches it should have skipped (rewriting the field mid-type,
        // which resets the caret and drops focus on AppKit).
        //
        // What the field holds is the fact that matters, and it is knowable: the field reports
        // every value it takes, and Day knows every value it pushes. Comparing against it is
        // idempotent and order-independent, with nothing to arm or consume and no way to get out
        // of step. Equal means the field already shows it, so there is nothing to push and no
        // caret to disturb.
        let shown: Rc<RefCell<String>> = Rc::new(RefCell::new(seed.text.clone()));

        if placement == P::Toolbar {
            let g = shown.clone();
            let submit = self.submit.clone();
            let action = day_core::register_toolbar_value(Rc::new(
                move |v: &day_spec::ToolbarValue| match v {
                    day_spec::ToolbarValue::Text(t) => {
                        *g.borrow_mut() = t.clone();
                        query.set(t.clone());
                    }
                    day_spec::ToolbarValue::Submit(t) => {
                        if let Some(f) = &submit {
                            f(t);
                        }
                    }
                    _ => {}
                },
            ));
            // An ordinary contribution on this host's chrome, placed last (where every
            // desktop puts search) and withdrawn with the surface it filters.
            let suggestions = seed.suggestions.clone();
            let item = move |text: String, prompt: String| day_spec::ToolbarItem {
                id: day_core::id!(day::search).as_str().to_owned(),
                kind: day_spec::ToolbarItemKind::Search {
                    text,
                    placeholder: prompt.clone(),
                    suggestions: suggestions.clone(),
                },
                label: prompt,
                tooltip: None,
                icon: None,
                enabled: true,
                action,
                placement: day_spec::ToolbarPlacement::Secondary,
                label_style: day_spec::LabelStyle::Automatic,
                prominent: false,
                // Desktop search belongs at the trailing edge of the window toolbar.
                column: day_spec::ToolbarColumn::Detail,
            };
            let token = day_core::register_contribution(
                chrome,
                vec![item(seed.text.clone(), seed.prompt.clone())],
            );
            // The prompt follows the locale: a changed text re-registers the field with it.
            if let Some(TextSource::Dyn(read)) = self.prompt.clone() {
                let shown = shown.clone();
                bind_seeded(
                    seed.prompt.clone(),
                    move || read(),
                    move |p: &String| {
                        let text = shown.borrow().clone();
                        day_core::update_contribution(token, vec![item(text, p.clone())]);
                    },
                );
            }
            Scope::current().on_cleanup(move || day_core::unregister_contribution(token));
        } else {
            // Inline: no bar item exists, so the reserved id is answered by the host itself.
            // That is what lets a dayscript `toolbar: { item: day::search, text }` reach the same
            // query on a phone as on a desktop (docs/search.md): day-core resolves the id to
            // this host and delivers `Event::SearchChanged`, the event the native field emits.
            day_core::register_search_host(host);
            Scope::current().on_cleanup(move || day_core::unregister_search_host(host));
        }

        // The one outbound binding: the app writing its query reaches whichever target this
        // placement renders into. Seeded, because `lower` already put the value in the realize
        // props; re-applying it here would be the duplicate op §5.2 forbids.
        bind_seeded(
            seed.text.clone(),
            move || query.get(),
            move |t: &String| {
                if *shown.borrow() == *t {
                    return; // the field already shows this; patching it back fights the caret
                }
                *shown.borrow_mut() = t.clone();
                match placement {
                    // The patch mirrors into the owning contribution as well, so a later
                    // re-lower of this chrome rebuilds the field with the text it is showing
                    // rather than the one it was declared with.
                    P::Toolbar => day_core::patch_chrome(
                        chrome,
                        day_spec::ToolbarPatch::Text {
                            item: SEARCH_ITEM_ID.to_string(),
                            text: t.clone(),
                        },
                    ),
                    _ => {
                        let p = SearchPatch::Text(t.clone());
                        with_tree(|tr| tr.patch(host, Box::new(p), false));
                    }
                }
            },
        );

        if let Some(sig) = self.scope {
            let seed_scope = seed.scope;
            bind_seeded(
                seed_scope,
                move || sig.get(),
                move |i| {
                    let p = SearchPatch::Scope(*i);
                    with_tree(|tr| tr.patch(host, Box::new(p), false));
                },
            );
        }
        // Completions re-derive on every keystroke and on whatever else the closure reads.
        if let Some(f) = self.suggestions.clone() {
            bind_seeded(
                seed.suggestions.clone(),
                move || f(&query.get()),
                move |list| match placement {
                    P::Toolbar => day_core::patch_chrome(
                        chrome,
                        day_spec::ToolbarPatch::Suggestions {
                            item: SEARCH_ITEM_ID.to_string(),
                            list: list.clone(),
                        },
                    ),
                    _ => {
                        let p = SearchPatch::Suggestions(list.clone());
                        with_tree(|t| t.patch(host, Box::new(p), false));
                    }
                },
            );
        }
    }
}

pub fn nav<K: Route, S: Binding<K>>(selection: S) -> Nav<S, K> {
    Nav {
        selection,
        documents: None,
        document_event: None,
        icon_progress: None,
        refresh: None,
        style: NavStyle::default(),
        sidebar_toggle: true,
        title: TextSource::Static(String::new()),
        header: None,
        footer: None,
        sources: Vec::new(),
        destination: None,
        routed: true,
        restore: None,
        retain_selection: None,
        reorder_items: None,
        collapsed_sections: None,
        on_section_expansion: None,
        toolbar: Vec::new(),
        search: None,
        presentation: None,
        content_list: None,
        content_list_width: day_spec::NAV_LIST_WIDTH,
        content_list_pred: None,
        detail_visible: None,
        detail_title: None,
    }
}

#[day_macros::builder(NavBuilder<K>)]
impl<K: Route, S: Binding<K>> Nav<S, K> {
    /// Add the platform's pull-to-refresh control to the sidebar rows (docs/navigation.md).
    /// UIKit uses UIRefreshControl, Android SwipeRefreshLayout. Other toolkits can ignore
    /// this affordance, so retain a Refresh command for keyboard/accessibility users.
    /// `refreshing` is app-owned: set it synchronously when accepting a request and clear it
    /// on completion, failure or cancellation. Repeated pulls while busy are ignored. A
    /// declined request stops the indicator immediately. Programmatic state writes never
    /// call `action`. The handler and state bindings live only as long as this navigation.
    pub fn refreshable<M>(
        mut self,
        refreshing: impl IntoReactive<bool, M>,
        action: impl Fn() + 'static,
    ) -> Self {
        self.refresh = Some((refreshing.into_reactive(), Rc::new(action)));
        self
    }

    pub(crate) fn document_mode(
        mut self,
        config: day_spec::props::DocumentTabsConfig,
        event: impl Fn(&Event) + 'static,
    ) -> Self {
        self.documents = Some(config);
        self.document_event = Some(Rc::new(event));
        self
    }
    /// Collapsible sidebar sections (docs/navigation.md), as a [`Sections`] value:
    /// `nav(sel).sections(Sections::restored("nav.sections").on_change(f))`.
    pub fn sections(mut self, sections: Sections) -> Self {
        self.collapsed_sections = Some(sections.collapsed);
        self.on_section_expansion = sections.on_change;
        self
    }
    /// A section with a persistent identity independent of its localized title or first row,
    /// heading `content` (one item, a tuple, an `Option`, a [`nav_items`] block, or a mix).
    pub fn section_id<M>(
        mut self,
        id: impl Into<String>,
        title: impl IntoText<M>,
        content: impl NavContent<K>,
    ) -> Self {
        self.push_section(
            SectionHeader {
                id: Some(id.into()),
                title: title.into_text(),
            },
            content,
        );
        self
    }
    /// Append `content` under a section header (docs/navigation.md). Backends without grouped
    /// rows ignore the header and show one flat list, so a section is a grouping hint, never a
    /// source of items the user cannot otherwise reach.
    fn push_section(&mut self, header: SectionHeader, content: impl NavContent<K>) {
        let mut sources = Vec::new();
        content.push_sources(&mut sources);
        let mut sources = sources.into_iter();
        // The header rides the first row of the content: a static item carries it directly; a
        // data-driven block heads its first row with it, wherever the data starts.
        match sources.next() {
            Some(ItemSource::Static(mut it)) => {
                if it.section.is_none() {
                    it.section = Some(header);
                }
                self.sources.push(ItemSource::Static(it));
            }
            Some(ItemSource::Dynamic(f)) => {
                self.sources.push(ItemSource::Dynamic(Box::new(move || {
                    let mut rows = f();
                    if let Some(first) = rows.first_mut()
                        && first.section.is_none()
                    {
                        first.section = Some(header.clone());
                    }
                    rows
                })));
            }
            None => {}
        }
        self.sources.extend(sources);
    }

    /// Enable dragging within contiguous runs of eligible sidebar items. Fixed items and
    /// section headers cannot be crossed. The callback receives the moved key and the key
    /// whose position it takes (indices refer to the order before removal).
    /// Uses the shared list reorder driver where `Cap::NavReorder` supports it; otherwise
    /// retains the native navigation widget. UIKit navigation remains fixed even though
    /// content lists support dragging. Tab/rail chrome remains fixed. Persist the order in the callback's backing data.
    pub fn reorder_items(
        mut self,
        eligible: impl Fn(&K) -> bool + 'static,
        moved: impl Fn(K, K) + 'static,
    ) -> Self {
        self.reorder_items = Some(SidebarDrag::Reorder(NavReorder {
            eligible: Rc::new(eligible),
            moved: Rc::new(moved),
        }));
        self
    }

    /// Like [`Self::reorder_items`], but rows may also cross section headers: drag a feed from
    /// one collection's section into another's (docs/navigation.md "Moving rows between
    /// sections"). `drag` says how each row drags, re-asked whenever the rows change:
    /// [`NavDrag::Reorder`] rows move within their section and into others,
    /// [`NavDrag::Regroup`] rows only into others (their own section keeps the app's sorted
    /// order), and a section holding a [`NavDrag::Fixed`] row takes no drop at all. Rows above
    /// the first header form one unnamed section. `dropped` gets the moved key, the
    /// destination section's `section_id` and the row it now sits before; a drop back where
    /// the row started reports nothing. Apply the move to the app's data, which brings the new
    /// rows back. Declaring this and [`Self::reorder_items`] on one nav keeps the later one;
    /// collapsible [`Self::sections`] take precedence over both. Probe `Cap::NavReorder`.
    pub fn regroup_items(
        mut self,
        drag: impl Fn(&K) -> NavDrag + 'static,
        dropped: impl Fn(NavDrop<K>) + 'static,
    ) -> Self {
        self.reorder_items = Some(SidebarDrag::Regroup(NavRegroup {
            drag: Rc::new(drag),
            dropped: Rc::new(dropped),
        }));
        self
    }

    /// Preserve the current destination when its row disappears and `keep` returns true.
    /// Useful for filtered sidebars: reading a feed's last unread article can hide its row
    /// without closing the article. The native sidebar then has no highlighted row.
    /// Return false for deleted records to retain the normal selection-reset behavior.
    /// Evaluated when the item list changes; pair with [`Self::destination`] for dynamic keys.
    pub fn retain_selection_when(mut self, keep: impl Fn(&K) -> bool + 'static) -> Self {
        self.retain_selection = Some(Rc::new(keep));
        self
    }

    /// Progress over leading icons, without rebuilding rows or changing label geometry.
    /// Return active route keys with None while connecting/unknown-length, or Some(0..=1)
    /// for a known fraction. Omit finished keys. AppKit/UIKit animate in the compositor;
    /// other toolkits currently leave icons unchanged. Bind separately from `.items`.
    pub fn icon_progress(mut self, progress: impl Fn() -> Vec<(K, Option<f64>)> + 'static) -> Self {
        self.icon_progress = Some(Rc::new(progress));
        self
    }

    pub fn style(mut self, style: NavStyle) -> Self {
        self.style = style;
        self
    }
    /// The sidebar / window title (Sidebar style).
    pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
        self.title = t.into_text();
        self
    }
    /// A section: `content` (one item, a tuple, an `Option`, a [`nav_items`] block, or a mix)
    /// under a header. Backends without grouped rows ignore the header and show one flat list,
    /// so a section is a grouping hint, never a source of items the user cannot otherwise reach.
    ///
    /// ```ignore
    /// nav(sel)
    ///     .section(res::str::smart_feeds(), (
    ///         item("today", res::str::today()).icon(res::images::today).page(today_page),
    ///         item("unread", res::str::unread()).icon(res::images::unread).page(unread_page),
    ///     ))
    ///     .section(res::str::feeds(), nav_items(move || st.feeds.get(), |f| item(f.id, f.name)))
    /// ```
    pub fn section<M>(mut self, title: impl IntoText<M>, content: impl NavContent<K>) -> Self {
        self.push_section(
            SectionHeader {
                id: None,
                title: title.into_text(),
            },
            content,
        );
        self
    }
    /// An optional piece shown above the sidebar list (a logo, app name…).
    pub fn header<P: Piece>(mut self, build: impl FnOnce() -> P + 'static) -> Self {
        self.header = Some(Box::new(move || AnyPiece::new(build())));
        self
    }
    /// An optional piece pinned below the sidebar list, outside its scroll area.
    /// It belongs to the root page: stacked destinations do not carry it along.
    /// Like [`Self::header`], this slot applies to sidebar navigation, not tab/rail chrome.
    pub fn footer<P: Piece>(mut self, build: impl FnOnce() -> P + 'static) -> Self {
        self.footer = Some(Box::new(move || AnyPiece::new(build())));
        self
    }
    /// Pin the presentation instead of letting the window's size decide (docs/size-classes.md).
    ///
    /// Leave this unset (the default) and the nav shows sidebar+detail on a window wide
    /// enough for both and stacks on one that is not, re-presenting live as the window is resized
    /// or the device rotated. Pin it when the content only works one way: a settings sidebar whose
    /// detail is meaningless alone, a wizard that must stay a stack.
    ///
    /// A pin is still a preference. A toolkit with no split container (the phones today) stacks
    /// whatever is asked for, exactly as it does for the automatic case.
    pub fn presentation(mut self, presentation: day_spec::props::NavPresentation) -> Self {
        self.presentation = Some(presentation);
        self
    }
    /// A content-list pane between the sidebar and the detail, the Mail shape (docs/navigation.md),
    /// as a [`ContentList`] value:
    ///
    /// ```ignore
    /// nav(scene.section).content_list(
    ///     ContentList::new(pages::items::item_list_pane)
    ///         .width(320.0)
    ///         .only_for(|s: &Section| matches!(s, Section::Items))
    ///         .detail_visible(scene.detail_open)
    ///         .detail_title(move || pages::items::detail_title(scene)),
    /// )
    /// ```
    pub fn content_list(mut self, list: ContentList<K>) -> Self {
        self.content_list = Some(list.build);
        self.content_list_width = list.width;
        self.content_list_pred = list.pred;
        self.detail_visible = list.detail_visible;
        self.detail_title = list.detail_title;
        self
    }
    /// Add one destination: `item(key, title).page(build)` in one call. `key` addresses it
    /// (navigate / deep link / dayscript); `title` is its label; `build` runs when the item is
    /// first shown. For a typed nav over `Option<Section>` pass the bare `Section::X`. For an
    /// icon, a badge or a tint, build the [`item`] value and add it with [`items`](Self::items).
    pub fn item<M, P: Piece>(
        self,
        key: impl Into<K>,
        title: impl IntoText<M>,
        build: impl Fn() -> P + 'static,
    ) -> Self {
        self.items(crate::item(key, title).page(build))
    }
    /// Add items (docs/navigation.md): one [`item`], a tuple of them, an `Option`, a `Vec`, a
    /// data-driven [`nav_items`] block, or a mix. Static items and blocks may be mixed in any
    /// order; the final list is their declaration order.
    ///
    /// ```ignore
    /// nav(sel).items((
    ///     item("home", res::str::home()).icon(res::images::home).page(home_page),
    ///     nav_items(move || rooms.get(), |r| item(r.id.clone(), r.name.clone())),
    ///     prefs.nav_item(Section::Settings),
    /// ))
    /// ```
    pub fn items(mut self, content: impl NavContent<K>) -> Self {
        content.push_sources(&mut self.sources);
        self
    }
    /// Build the page for a key whose item has no [`page`](NavItem::page) of its own (the rows
    /// of a data-driven block). Mirrors [`NavStack::destination`]; unused for a nav whose items
    /// all carry a page.
    pub fn destination<P: Piece>(mut self, build: impl Fn(&K) -> P + 'static) -> Self {
        self.destination = Some(Rc::new(move |k| AnyPiece::new(build(k))));
        self
    }
    /// Use this nav as a local widget: its selection is not part of the app route, so it
    /// neither adds a segment to `current_route` nor intercepts `navigate`/deep links.
    ///
    /// Reach for this when a page already routes and you embed a second one-of-N control in
    /// it (a filter tab strip, a secondary sidebar). Two routing selectors at the same level both
    /// feed `current_route()`, so you'd get `section/childA/childB` and `navigate("childB")` would
    /// be ambiguous; mark all but the primary one `.local()`. A nav nested one level deeper
    /// (a `Tabs` inside a `Sidebar` section) is a different case and should stay routed: its
    /// key belongs in the cascade. In debug builds, two routed one-of-N surfaces at the same
    /// level log a warning naming this fix (docs/navigation.md).
    pub fn local(mut self) -> Self {
        self.routed = false;
        self
    }
    /// Remember the selected item across launches (docs/navigation.md). The selected key is saved
    /// under `key` on every change and restored at build (so the app reopens on the tab/section
    /// the user last had) unless a launch deep link is pending, which wins. `day::launch`
    /// installs the preferences as the store (docs/navigation.md); a stale saved
    /// key (its item no longer exists) is ignored. Works whether or not the nav is
    /// [`routed`](Self::local).
    pub fn restore(mut self, key: impl Into<String>) -> Self {
        self.restore = Some(key.into());
        self
    }
    /// Declare toolbar items on this host's chrome (docs/toolbars.md): the sidebar column
    /// where the presentation has one, and the root list when it has collapsed to a stack.
    ///
    /// This is where a command that acts on the list belongs: "add an item", "sort", "filter".
    /// A command that acts on whatever page is open belongs on the page instead, declared with
    /// the same method on the piece that page builds, and then it comes and goes with that page
    /// rather than riding a list it cannot act on.
    ///
    /// Takes one item, a list of them, or a closure that derives the list and re-runs whenever
    /// its reactive reads change.
    ///
    /// ```ignore
    /// nav(section)
    ///     .toolbar(toolbar_button(day_core::id!(add), tr("add")).icon(Symbol::Add).action(add_item))
    /// ```
    pub fn toolbar<M>(mut self, content: impl crate::ToolbarContent<M>) -> Self {
        self.toolbar.push(content.into_source());
        self
    }

    /// Do not draw the platform's own show/hide-sidebar affordance on this host's chrome. It is
    /// on by default for a sidebar presentation, since every desktop expects one and the
    /// toolkit owns both the button and the behavior; this is for a window that should not
    /// offer it.
    pub fn no_sidebar_toggle(mut self) -> Self {
        self.sidebar_toggle = false;
        self
    }

    /// Make this surface searchable (docs/search.md), as a [`Search`] value:
    ///
    /// ```ignore
    /// nav(section)
    ///     .style(NavStyle::Sidebar)
    ///     .searchable(Search::new(query).prompt(res::str::search()).reveal(SearchReveal::OnPull))
    ///     .items(nav_items(move || destinations().filter(|d| matches_query(d, &query.get())), destination_row))
    /// ```
    pub fn searchable(mut self, search: Search) -> Self {
        let (hides_on_scroll, initially_hidden) = match search.reveal {
            SearchReveal::Always => (false, false),
            SearchReveal::Scrolls => (true, false),
            SearchReveal::OnPull => (true, true),
        };
        self.search = Some(SearchSpec {
            query: search.query,
            prompt: search.prompt,
            placement: search.placement,
            hides_on_scroll,
            initially_hidden,
            scopes: search.scopes,
            scope: search.scope,
            suggestions: search.suggestions,
            submit: search.submit,
        });
        self
    }
}

impl<K: Route, S: Binding<K>> Piece for Nav<S, K> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        // One builder for all three styles. The styles differ only in which presentations the
        // resolver may produce, and a presentation differs only in chrome and page residency,
        // so a tab bar is a `kinds::NAV` host wearing a different hat, not a second host kind
        // with its own props, patches, and nine backend implementations (docs/navigation.md).
        build_selector(self, cx)
    }
}

/// Apply a nav's `.restore` at build: seed `selection` from the key saved under `restore`,
/// so the app reopens on the section/tab the user last chose. A pending launch deep link wins
/// (skip). Only a saved key that parses and is a current item is honored (plus the empty
/// "deselected" key, for a sidebar's collapsed state), so a stale key left by an older build is
/// ignored. A no-op when `restore` is unset or no [`NavStore`](day_core::NavStore) is installed.
fn restore_selection<K: Route, S: Binding<K>>(
    restore: &Option<String>,
    selection: &S,
    items: &[K],
) {
    if let Some(key) = restore.as_deref()
        && !day_core::has_launch_deeplink()
        && let Some(saved) = day_core::nav_store_load(key)
        && let Some(k) = K::from_key(&saved)
        && (saved.is_empty() || items.iter().any(|x| x.key() == saved))
    {
        selection.write(k);
    }
}

/// Persist a nav's selection under its `.restore` key on every change (docs/navigation.md).
/// The binding lives in the current scope, so it stops with the surface. Consumes `restore`.
fn persist_selection<K: Route, S: Binding<K>>(restore: Option<String>, selection: &S) {
    if let Some(key) = restore {
        let s = selection.clone();
        bind(
            move || s.read().key(),
            move |k: &String| day_core::nav_store_save(&key, k),
        );
    }
}

// ---------------------------------------------------------------------------
// The composed gated detail (docs/navigation.md): where the toolkit has no content-list pane,
// a list-backed destination with `detail_visible` is a two-layer navigation flow rather than
// an in-place swap. In a chrome presentation (a tab bar, a rail) the destination's page
// is a nested navigation host of its own: the platform's stack controller inside the tab,
// the list at its root, the detail pushed over it. In a stacked presentation the list renders
// inline in the destination's (already pushed) page and the detail pushes onto the enclosing
// host, exactly as a merged `nav_stack()`'s pages do. Both give the compact flow what the native
// idiom always had: a navigation bar, a title, and a back that pops.
// ---------------------------------------------------------------------------

/// What the gated flow needs from its nav, cloneable into the `when` branches that build
/// one shape or the other as the presentation changes.
struct GatedDetail<K: Route> {
    /// Whether the detail layer is up: the nav's `detail_visible` binding, two-way.
    open: AnyBinding<bool>,
    /// Builds the content list, the root layer.
    list: Rc<dyn Fn() -> AnyPiece>,
    /// The nav's items: the detail content builder and the immersive flag.
    items: Rc<SelItems<K>>,
    key: K,
    /// The destination's resolved title (the root layer's bar) and its live source.
    title: String,
    retitle: Option<TextSource>,
    /// The pushed detail's title source (`Nav::detail_title`); `None` = `title`.
    detail_title: Option<TextSource>,
    /// The enclosing nav's host, the merge target while stacked.
    host_cx: NavHostCx,
    /// The nav's toolbar sources, re-homed onto the nested host in a chrome
    /// presentation, whose tabs chrome draws none of its own.
    toolbar: Vec<crate::ToolbarSource>,
}

impl<K: Route> Clone for GatedDetail<K> {
    fn clone(&self) -> Self {
        GatedDetail {
            open: self.open,
            list: self.list.clone(),
            items: self.items.clone(),
            key: self.key.clone(),
            title: self.title.clone(),
            retitle: self.retitle.clone(),
            detail_title: self.detail_title.clone(),
            host_cx: self.host_cx.clone(),
            toolbar: self.toolbar.clone(),
        }
    }
}

/// The gated flow's piece. The shape follows the live presentation, so a morph between a tab
/// bar and a stack rebuilds the right container.
///
/// The condition asks the full question (chrome rows and a compact window) rather than
/// leaning on the enclosing side-by-side `when` to have ruled the wide case out. The two
/// react to the same signals, and their evaluation order in one flush is not promised: a
/// `NavStack → Rail` morph on a desktop flips both at once, and a condition that only asked
/// "chrome?" would build a nested navigation host for the one evaluation before the outer
/// branch replaces it, a whole native host realized and torn down in a single flush, which
/// wedged Qt.
fn gated_detail_piece<K: Route>(
    cfg: GatedDetail<K>,
    pres: Signal<day_spec::props::NavPresentation>,
    window: RNode,
) -> AnyPiece {
    let (c1, c2) = (cfg.clone(), cfg);
    AnyPiece::new(
        when(
            move || {
                pres.get().rows_are_chrome()
                    && !day_core::window_size_class(window).is_some_and(|c| c.prefers_split())
            },
            move || gated_detail_nested(c1.clone()),
        )
        .otherwise(move || gated_detail_merged(c2.clone())),
    )
}

/// A chrome presentation's gated destination: a nested navigation host of its own (a
/// `UINavigationController` inside the tab, a Material toolbar over the fragment back stack),
/// which is what gives the tab a navigation bar, a title, and a native back. Standalone by
/// construction: a resident page is a merge barrier (docs/navigation.md).
fn gated_detail_nested<K: Route>(cfg: GatedDetail<K>) -> impl Piece {
    piece_fn(move |cx| {
        use day_spec::props::{NavPageProps, NavPresentation, NavProps, Pane};
        let sizes: Rc<RefCell<std::collections::HashMap<RNode, Size>>> = Rc::default();
        let host = cx.native(
            kinds::NAV,
            &NavProps {
                documents: None,
                title: cfg.title.clone(),
                // A permanent stack, like the `nav_stack()` piece: the chrome above already
                // adapts, so this host must never try to.
                presentation: NavPresentation::Stack,
                adaptive: false,
                sidebar_toggle: false,
                search: None,
                list_width: None,
                list_visible: true,
            },
            Rc::new(NavLayout::stack(sizes.clone())),
            Flex {
                grow_w: true,
                grow_h: true,
                ..Default::default()
            },
            Boundary::Yes,
        );
        let owners: Rc<RefCell<Vec<PopOwner>>> = Rc::default();
        let target = NavHostCx {
            host,
            sizes: sizes.clone(),
            owners: owners.clone(),
            split: Rc::new(Cell::new(false)),
            guards: Rc::default(),
        };
        let root_page = nav_page(
            host,
            &NavPageProps {
                title: cfg.title.clone(),
                pane: Pane::Detail,
            },
            &sizes,
        );
        // The list is this host's root page, so a `nav_stack()` inside it merges here: a drill-down
        // from the list (a category, then its items) pushes onto the tab's own navigation
        // controller, and the gated detail lands on top of whatever it pushed
        // (docs/navigation.md). Only the native resident pane is a barrier.
        // This shape shows one layer at a time, so the list's commands leave once the detail is
        // pushed over it, the same rule the native pane follows. The enclosing page's own gate
        // still applies: a tab that is not selected takes the list's commands with it.
        let covered = within_page_gate(list_layer_gate(None, Some(cfg.open), None));
        with_nav_host(Some(target.clone()), || {
            day_core::with_page_gated(
                root_page,
                Some(covered),
                day_spec::ToolbarColumn::List,
                || {
                    let mut pcx = BuildCx::new(root_page);
                    let _ = (cfg.list)().grow().build(&mut pcx);
                },
            );
        });
        // The nav's items, re-homed: a chrome presentation draws no bar of its own, so this
        // nested host's root page is where the list's commands belong (docs/toolbars.md).
        for source in cfg.toolbar.clone() {
            crate::contribute(day_core::Chrome::Page(root_page), source);
        }
        // This host's one back dispatcher: the topmost owner, the detail layer's or a
        // stack's that merged inside the detail.
        {
            let owners = owners.clone();
            cx.on(host, move |ev| match ev {
                Event::NavBack { already_popped } => {
                    let top = owners.borrow().last().cloned();
                    if let Some(f) = top {
                        f(*already_popped);
                    }
                }
                Event::RouteRequested(route) => {
                    let _ = day_core::navigate(route);
                }
                _ => {}
            });
        }
        wire_gated_detail(&cfg, target);
        host
    })
}

/// A stacked presentation's gated destination: the list renders inline in the destination's
/// own page and the detail pushes onto the enclosing host, the same merge a nested `nav_stack()`
/// performs, so the whole chain stays one native stack with one back button
/// (docs/navigation.md).
fn gated_detail_merged<K: Route>(cfg: GatedDetail<K>) -> impl Piece {
    piece_fn(move |cx| {
        let target = cfg.host_cx.clone();
        // The list is inline in a page of the enclosing stack, so a `nav_stack()` inside it merges
        // there, as one inside any pushed page does (docs/navigation.md).
        // Same rule as the nested shape: the detail pushes over this list, so the list's own
        // commands leave the bar while it is covered (docs/toolbars.md), and while the page it is
        // inline in is not showing.
        let covered = within_page_gate(list_layer_gate(None, Some(cfg.open), None));
        // The page this list is inline in, whichever it is: the gate is what matters, and the
        // frame keeps the chrome it was already going to land on.
        let page = match day_core::current_chrome() {
            day_core::Chrome::Page(p) => p,
            day_core::Chrome::Window(w) => w,
        };
        let node = with_nav_host(Some(target.clone()), || {
            day_core::with_page_gated(page, Some(covered), day_spec::ToolbarColumn::List, || {
                (cfg.list)().grow().build(cx)
            })
        });
        wire_gated_detail(&cfg, target);
        node
    })
}

/// Drive the detail layer from `detail_visible`, whichever host carries it: `true` pushes the
/// destination's page onto `target`, `false` (and the native back, which writes it) pops.
/// Registered in the current scope, so a section switch or a presentation morph tears the
/// layer down with the shape that built it.
fn wire_gated_detail<K: Route>(cfg: &GatedDetail<K>, target: NavHostCx) {
    use day_spec::props::{NavPageProps, NavPatch, Pane};
    /// The pushed layer: its page, and the scope its content lives in.
    struct Layer {
        scope: Scope,
        page: RNode,
    }
    let layer: Rc<RefCell<Option<Layer>>> = Rc::default();
    // Pops the toolkit already performed (an iOS swipe, the Android system back): the
    // answering `Popped` is absorbed rather than re-issued, same as a stack's.
    let native_popped: Rc<Cell<usize>> = Rc::default();
    let open = cfg.open;
    let owner_scope = Scope::current();

    // The native back, while the detail is up: report it into the signal; the pop itself is
    // performed by the binding below, so a back and a programmatic `false` are one path.
    let owner: PopOwner = {
        let native_popped = native_popped.clone();
        Rc::new(move |already_popped: bool| {
            if already_popped {
                native_popped.set(native_popped.get() + 1);
            }
            open.set(false);
        })
    };

    let detail_src = cfg.detail_title.clone();
    let root_title = cfg.title.clone();
    let push = {
        let (layer, target, owner) = (layer.clone(), target.clone(), owner.clone());
        let (items, key) = (cfg.items.clone(), cfg.key.clone());
        let (detail_src, root_title) = (detail_src.clone(), root_title.clone());
        move || {
            if layer.borrow().is_some() {
                return;
            }
            let title = detail_src
                .as_ref()
                .map(TextSource::initial)
                .unwrap_or_else(|| root_title.clone());
            let page = nav_page(
                target.host,
                &NavPageProps {
                    title: title.clone(),
                    pane: Pane::Detail,
                },
                &target.sizes,
            );
            // Before the content builds, so a stack that merges inside the detail lands its
            // owners on top of this one.
            target.owners.borrow_mut().push(owner.clone());
            let scope = owner_scope.enter(Scope::child);
            let tc = target.clone();
            scope.enter(|| {
                // The app's builder runs inside this page's scope, like the presentation site
                // further down: a page body runs app code (an ambient state read, a `Signal`,
                // a registration), and all of it belongs to the page's lifetime rather than to
                // whichever scope happened to be current when the push landed.
                let content = items.build_page(&key);
                with_nav_host(Some(tc), || {
                    day_core::with_page(page, || {
                        let mut c = BuildCx::new(page);
                        let _ = content.grow().build(&mut c);
                    });
                });
            });
            // Out here for the usual reason: `immersive_of` can run app code, which must not
            // happen inside `with_tree`.
            let immersive = items.immersive_of(&key.key());
            with_tree(|t| {
                t.patch(
                    target.host,
                    Box::new(NavPatch::Pushed { title, immersive }),
                    false,
                );
                t.mark_layout_dirty();
                t.layout_if_needed();
            });
            *layer.borrow_mut() = Some(Layer { scope, page });
        }
    };
    let pop = {
        let (layer, target, native_popped) = (layer.clone(), target.clone(), native_popped.clone());
        move || {
            let taken = layer.borrow_mut().take();
            let Some(l) = taken else {
                return;
            };
            // Scope first: a merged inner stack's cleanup pops its pages (which sit on top
            // natively) before this pops the detail itself: top-down, the order native
            // stacks demand.
            l.scope.dispose();
            if native_popped.get() > 0 {
                native_popped.set(native_popped.get() - 1);
            } else {
                with_tree(|t| t.patch(target.host, Box::new(NavPatch::Popped), false));
            }
            target.owners.borrow_mut().pop();
            target.sizes.borrow_mut().remove(&l.page);
            with_tree(|t| {
                t.remove_subtree(l.page);
                t.mark_layout_dirty();
                t.layout_if_needed();
            });
        }
    };
    {
        let (push, pop) = (push, pop.clone());
        bind(
            move || open.get(),
            move |v: &bool| if *v { push() } else { pop() },
        );
    }

    // The top layer's bar, live: the detail title while up (re-resolving as the state it
    // reads changes), the destination's while down. Seeded with what the build just drew, and
    // sent unconditionally: while the layer is down the enclosing top carries the same
    // destination title, so the patch is a no-op there rather than a wrong name.
    {
        let (retitle, host) = (cfg.retitle.clone(), target.host);
        let top_title = move || {
            let root = || {
                retitle
                    .as_ref()
                    .map_or_else(|| root_title.clone(), TextSource::resolve)
            };
            if open.get() {
                detail_src.as_ref().map_or_else(root, TextSource::resolve)
            } else {
                root()
            }
        };
        let seed = day_reactive::untrack(&top_title);
        bind_seeded(seed, top_title, move |t: &String| {
            with_tree(|tr| tr.patch(host, Box::new(NavPatch::Title(t.clone())), false));
        });
    }

    // `nav_back()` and a dayscript back reach the layer first: a pop-only route surface that
    // claims the back while the detail is up and falls through outward otherwise. It adds no
    // segments, so `current_route()` reads the same across every presentation.
    {
        let (o_push, o_pop) = (open, open);
        register_route_surface(
            move |k| {
                if k.is_empty() && o_push.peek() {
                    o_push.set(false);
                    true
                } else {
                    false
                }
            },
            move |_| {
                if o_pop.peek() {
                    o_pop.set(false);
                    true
                } else {
                    false
                }
            },
            String::new,
            |_| false,
            Vec::new,
        );
    }

    // The layer's page can ride a host this scope does not own (the merged shape), so that
    // host's teardown will not reach it; pop it, top-down, when this shape is left: a
    // section switch, a presentation morph. Guarded for app teardown, like a merged stack.
    owner_scope.on_cleanup(move || {
        let alive = with_tree(|t| t.node_kind(target.host).is_some());
        if alive {
            pop();
        } else if let Some(l) = layer.borrow_mut().take() {
            l.scope.dispose();
        }
    });
}

fn build_selector<K: Route, S: Binding<K>>(sel: Nav<S, K>, cx: &mut BuildCx) -> RNode {
    use day_spec::props::{
        NavMenuPatch, NavMenuProps, NavPageProps, NavPatch, NavPresentation, NavProps, Pane,
    };
    // Presentation (docs/size-classes.md). Resolved from the window's size class on every change,
    // not fixed at build time; `NavPatch::Presentation` re-presents the live host. The window
    // root is captured here: the effect below re-runs long after this build, when the ambient
    // window would answer the primary one instead of ours.
    let icon_progress = sel.icon_progress;
    let progress_revision = Signal::new(0u64);
    let window = day_core::window_being_built();
    let can_split =
        with_tree(|t| t.capability(day_spec::Cap::NavSplit)) == day_spec::Support::Native;
    // Who decides the presentation (docs/size-classes.md), which is what `Cap::NavRepresent`'s
    // three answers distinguish:
    //   Native: we do, and we patch the host when the class changes.
    //   Emulated: the toolkit's adaptive container does, and reports back.
    //   Unsupported: nobody; it is fixed at build time from `Cap::NavSplit` alone, because a
    //     toolkit that cannot change presentation must not have it decided by something that
    //     can: a window launched narrow would be stuck stacked.
    // Can the toolkit draw the rows as its own chrome (a tab bar, and a rail where it has one)?
    // `Emulated` counts: Qt and web-dom compose theirs, and a composed tab bar is still a tab bar
    // to the app. Only `Unsupported` sends `Automatic` down the sidebar path.
    let can_tabs =
        with_tree(|t| t.capability(day_spec::Cap::NavTabs)) != day_spec::Support::Unsupported;
    // A separate question from `can_tabs`: every desktop can draw a tab bar (an app may pin one)
    // but none of them should grow one as its window narrows. That is a statement about the
    // platform's idiom rather than its widget set, so it is the backend's to make.
    let adaptive_tabs = with_tree(|t| t.capability(day_spec::Cap::NavTabsAdaptive))
        != day_spec::Support::Unsupported;
    let represent = with_tree(|t| t.capability(day_spec::Cap::NavRepresent));
    let we_drive = represent == day_spec::Support::Native;
    let toolkit_drives = represent == day_spec::Support::Emulated;
    // The content-list pane (docs/navigation.md). `Native`/`Emulated` = the toolkit places the
    // `Pane::List` page itself; `Unsupported` = the wrapper below composes it around each
    // destination and the backend never hears of it.
    let list_cap = with_tree(|t| t.capability(day_spec::Cap::NavContentList));
    // Either way the window's size decides the initial value: a backend that morphs itself still
    // starts wherever its container will land, so seeding from the class avoids a first frame in
    // the wrong presentation followed by a correcting report.
    let size_decides = we_drive || toolkit_drives;
    let requested = sel.presentation;
    // `Automatic` on a toolkit with no tab bar becomes `Sidebar`, the behavior every backend had
    // before adaptive navigation existed. Degrading to the old shape rather than to a hole is what
    // lets this land one backend at a time (docs/navigation.md).
    let style = match sel.style {
        NavStyle::Automatic if !can_tabs => NavStyle::Sidebar,
        s => s,
    };
    // The resolver owns every "can this toolkit do it" question, so `NavProps` always carries a
    // presentation the backend can draw.
    let resolve = move |class: Option<day_spec::SizeClass>| -> NavPresentation {
        // A pin is still a preference (docs/size-classes.md): a toolkit with no split container
        // stacks whatever it is asked for, and one with no tab bar cannot wear a pinned `Tabs`.
        if let Some(p) = requested {
            return match p {
                NavPresentation::Split if !can_split => NavPresentation::Stack,
                NavPresentation::Tabs | NavPresentation::Rail if !can_tabs => {
                    if can_split {
                        NavPresentation::Split
                    } else {
                        NavPresentation::Stack
                    }
                }
                p => p,
            };
        }
        match style {
            // Pinned tabs: the same bar at every size, so the window never enters into it.
            NavStyle::Tabs => NavPresentation::Tabs,
            // Today's resolution, unchanged: split where there is room, stacked where there isn't.
            NavStyle::Sidebar => match class {
                _ if !can_split => NavPresentation::Stack,
                Some(c) if size_decides && !c.prefers_split() => NavPresentation::Stack,
                _ => NavPresentation::Split,
            },
            // The adaptive ladder: a tab bar at the narrow end, a rail in the middle, a sidebar
            // beside the detail when there is room.
            //
            // Only the bottom rung is platform-specific. Where a tab bar is the idiomatic compact
            // answer (the phones, the web) that is what a narrow window gets; on a desktop it
            // collapses to a stack instead, which is what `Sidebar` has always done and what a
            // Mac or GNOME app does when you drag it narrow. The rail and the split are the same
            // everywhere.
            NavStyle::Automatic => {
                let compact = if adaptive_tabs {
                    NavPresentation::Tabs
                } else {
                    NavPresentation::Stack
                };
                if !size_decides {
                    // Nobody re-presents, so this is decided once and must not be decided by
                    // something that changes underneath (docs/size-classes.md). Prefer the
                    // roomier container the toolkit has.
                    return if can_split {
                        NavPresentation::Split
                    } else {
                        compact
                    };
                }
                if !can_split {
                    return compact;
                }
                match class.map(|c| c.width) {
                    Some(day_spec::WidthClass::Compact) => compact,
                    Some(day_spec::WidthClass::Medium) => NavPresentation::Rail,
                    _ => NavPresentation::Split,
                }
            }
        }
    };
    let presentation = resolve(day_core::window_size_class_untracked(window));
    // What the host props carry is a different question from what this build currently shows.
    // An Emulated toolkit's adaptive container collapses and expands itself, so its host is
    // lowered as `Split` ("build the adaptive container") even when the window is compact
    // right now. `NavStack` in props is thereby reserved for hosts that are stacks at every size
    // (a pinned request, a toolkit that cannot split, the `nav_stack()` piece), which a backend
    // may take literally and realize as a plain navigation container: nesting an adaptive
    // split container inside a pane is exactly what breaks (docs/size-classes.md).
    // An Emulated toolkit's adaptive container collapses and expands itself, so it is lowered the
    // roomiest presentation the app's style admits ("build the adaptive container") even when
    // the window is compact right now. `NavStack` in props is thereby reserved for hosts that are
    // stacks at every size (a pinned request, a toolkit that cannot split, the `nav_stack()` piece),
    // which a backend may take literally: nesting an adaptive container inside a pane is exactly
    // what breaks (docs/size-classes.md). `adaptive` carries whether it may morph at all.
    let adaptive = requested.is_none();
    let lowered =
        if toolkit_drives && adaptive && can_tabs && adaptive_tabs && style != NavStyle::Sidebar {
            // The toolkit has an adaptive container that wears both chromes itself; iOS 18's
            // `UITabBarController` in `.tabSidebar` mode is the archetype: one controller that draws
            // a tab bar when compact and a sidebar when not, with its own animation and its own
            // user-facing toggle. Lowering `Tabs` says "build that", and the toolkit reports what it
            // settled on. Its pages are resident at every size, which is why such a host stays in the
            // chrome-rows model rather than flipping to push/pop as it widens.
            //
            // Only for a style that admits a tab bar. `Sidebar` is an app's explicit "this is a
            // list beside a detail", and its compact answer has always been the stack: one
            // navigation controller the list pushes onto, which is what a phone app with more
            // sections than fit a tab bar looks like. Handing that app a tab container instead
            // puts a bar under every page and (below iOS 18, where there is no sidebar mode to
            // switch to) leaves it there.
            NavPresentation::Tabs
        } else if toolkit_drives && adaptive && can_split && style != NavStyle::Tabs {
            NavPresentation::Split
        } else {
            presentation
        };
    // A `.tabSidebar`-style host is a tabs host at every width (its pages are resident whether
    // it is drawing a bar or a sidebar), so the resolved presentation has to agree with what the
    // backend was told to build. Left disagreeing, day-core would model push/pop while the
    // toolkit modeled resident tabs: the first page built would merge into a host that has no
    // stack to merge into, and land zero-sized.
    let presentation = if lowered == NavPresentation::Tabs && toolkit_drives && adaptive {
        NavPresentation::Tabs
    } else {
        presentation
    };
    // Whether the backend gets a `Pane::List` page of its own, decided only now that the host's
    // shape is known. A chrome-rows host has no column to put one in: UIKit's `.tabSidebar`
    // builds a `UITabBarController` and never the split, so a list page handed to it becomes an
    // extra tab beside the app's own sections. Where there is no pane, the wrapper below composes
    // the list into its destination instead, exactly as it does on a backend that has no pane at
    // all (docs/navigation.md).
    let native_list = sel.content_list.is_some()
        && list_cap != day_spec::Support::Unsupported
        && lowered != NavPresentation::Tabs;
    // A merged-pane backend (uikit) folds the list into the stack when it collapses; that is
    // the only shape where the detail push is gated on `detail_visible`.
    let merged_list = native_list && list_cap == day_spec::Support::Emulated;
    let split = presentation.is_split();
    let presentation_cell = Rc::new(Cell::new(presentation));
    // The same fact as a signal, for content the composed list wrapper builds inside the
    // pages: a re-present re-runs its `when` where a Cell could only be re-read on rebuild.
    let presentation_sig = Signal::new(presentation);
    let split_cell = Rc::new(Cell::new(split));
    let sidebar_cell: Rc<Cell<Option<RNode>>> = Rc::new(Cell::new(None));
    let list_cell: Rc<Cell<Option<RNode>>> = Rc::new(Cell::new(None));
    // ListVisible / ListInStack bookkeeping (both start where the backend starts: the pane
    // visible, the stack without the list). `list_shown` is shared with NavLayout so a
    // collapsed pane stops narrowing the detail's fallback at once.
    let list_shown = Rc::new(Cell::new(true));
    let list_in_stack = Rc::new(Cell::new(false));
    let selection = sel.selection;
    let routed = sel.routed;
    let restore = sel.restore;
    let title_s = sel.title.initial();
    // This host's toolbar items (docs/toolbars.md). They land on the sidebar page's chrome
    // below, which is the sidebar column while split and the root list while collapsed, the two
    // shapes of "the chrome over the list".
    let host_toolbar = sel.toolbar;
    // Cloned for the composed gated flow below: its nested host re-homes them in a chrome
    // presentation, where the tabs chrome draws none of its own (docs/navigation.md).
    let gated_toolbar = host_toolbar.clone();
    // Automatic resolves to a sidebar wherever the window is wide enough, so the affordance
    // follows what the toolkit can present rather than what the app spelled out: an app that
    // never wrote `.style(Sidebar)` still gets the platform's own toggle on a desktop.
    let sidebar_toggle =
        sel.sidebar_toggle && matches!(sel.style, NavStyle::Sidebar | NavStyle::Automatic);
    let detail_title = sel.detail_title;
    // Search over this surface (docs/search.md). Lowered to the host's props with its current
    // values; the live bindings below keep the field in step through targeted patches, so the
    // app writing the query never rebuilds (and refocuses) the field mid-word.
    let search_spec = sel.search;
    // Lowered once: the bindings below need these same values as their seeds, and `lower` runs
    // the app's suggestion closure, which should not run twice per build.
    let search_seed = search_spec.as_ref().map(SearchSpec::lower);
    let search = search_seed.clone();
    let items = Rc::new(SelItems::from_sources(sel.sources, sel.destination));
    // The live row set is reactive: `typed` (index → key) and `titles` are shared mutable state
    // the derive effect updates; the initial derive is untracked (the effect below owns the
    // subscription).
    let rows0 = day_reactive::untrack(|| items.derive());
    let shown0 = rows0.shown();
    let (typed0, titles0, icons0) = (rows0.keys, rows0.titles, rows0.icons);
    // Restore the last-selected section (before the detail's initial `show` runs).
    restore_selection(&restore, &selection, &typed0);
    let typed: Rc<RefCell<Vec<K>>> = Rc::new(RefCell::new(typed0));
    let titles: Rc<RefCell<Vec<String>>> = Rc::new(RefCell::new(titles0));

    // The pane's state for the destination that opens first: the restored selection if there is
    // one, else the first row, which is what the auto-select below will choose. The backend needs
    // it at realize; see `NavProps::list_visible`.
    let initial_list_visible = match sel.content_list_pred.as_ref() {
        Some(pred) if native_list => {
            let restored = selection.peek();
            let first = if restored.key().is_empty() {
                typed.borrow().first().cloned()
            } else {
                Some(restored)
            };
            first.as_ref().is_none_or(|k| pred(k))
        }
        _ => true,
    };
    list_shown.set(initial_list_visible);

    let sizes: Rc<RefCell<std::collections::HashMap<RNode, Size>>> = Rc::default();
    let host = cx.native(
        kinds::NAV,
        &NavProps {
            documents: sel.documents.clone(),
            title: title_s.clone(),
            presentation: lowered,
            adaptive,
            sidebar_toggle,
            search,
            list_width: native_list.then_some(sel.content_list_width),
            list_visible: initial_list_visible,
        },
        Rc::new(NavLayout {
            sizes: sizes.clone(),
            presentation: presentation_cell.clone(),
            sidebar: sidebar_cell.clone(),
            list: list_cell.clone(),
            list_width: sel.content_list_width,
            list_visible: list_shown.clone(),
        }),
        Flex {
            grow_w: true,
            grow_h: true,
            ..Default::default()
        },
        Boundary::Yes,
    );

    if let Some(event) = sel.document_event.clone() {
        cx.on(host, move |ev| event(ev));
    }

    // The per-host back-owner stack (docs/navigation.md): the detail page pushes its "deselect"
    // owner, and a nested stack that merges into this host pushes its page owners on top. The
    // context is threaded to nested pieces built under our pages.
    let owners: Rc<RefCell<Vec<PopOwner>>> = Rc::default();
    let host_cx = NavHostCx {
        host,
        sizes: sizes.clone(),
        owners: owners.clone(),
        split: split_cell.clone(),
        guards: Rc::default(),
    };

    // Sidebar / root page. `Pane::Sidebar` is unconditional: it says what this page is in the
    // model, not how the host happens to draw it today, which is what lets a re-present re-home
    // it between the sidebar pane and the root of the stack (docs/size-classes.md).
    let root_page = nav_page(
        host,
        &NavPageProps {
            title: title_s.clone(),
            pane: Pane::Sidebar,
        },
        &sizes,
    );
    sidebar_cell.set(Some(root_page));

    // Search, both directions (docs/search.md). The app's writes patch the live field; the user's
    // edits arrive as events against this host and write the app's own signals. Nothing here
    // touches the widget directly, which is what lets a later placement change relocate the field
    // without disturbing the query.
    if let Some((spec, seed)) = search_spec.as_ref().zip(search_seed.as_ref()) {
        spec.install(host, day_core::Chrome::Page(root_page), seed);
        let query = spec.query;
        let scope_sig = spec.scope;
        let submit = spec.submit.clone();
        cx.on(host, move |ev| match ev {
            Event::SearchChanged(text) => query.set(text.clone()),
            Event::SearchSubmitted(text) => {
                if let Some(f) = &submit {
                    f(text);
                }
            }
            Event::SearchScopeChanged(i) => {
                if let Some(s) = scope_sig {
                    s.set(*i);
                }
            }
            _ => {}
        });
    }

    // This host's items (docs/toolbars.md): the sidebar column's chrome while split, the
    // root list's while collapsed. Registered under the build's scope, so they are withdrawn if
    // the whole surface goes.
    // The sidebar affordance the host supplies for itself, ahead of the app's own items. Every
    // desktop expects one and the toolkit owns the behavior, so an app that used to declare the
    // button by hand now declares nothing (docs/toolbars.md).
    // The host's chrome is the sidebar column (docs/toolbars.md): a three-pane desktop draws
    // these over the sidebar, against the divider they act on.
    day_core::with_page_in(
        root_page,
        None,
        day_spec::ToolbarColumn::Sidebar,
        window,
        || {
            if sidebar_toggle
                && with_tree(|t| t.capability(day_spec::Cap::Toolbar))
                    != day_spec::Support::Unsupported
            {
                crate::contribute(
                    day_core::Chrome::Page(root_page),
                    crate::ToolbarSource::Fixed(vec![crate::sidebar_toggle_item(host)]),
                );
            }
            for source in host_toolbar {
                crate::contribute(day_core::Chrome::Page(root_page), source);
            }
        },
    );
    let menu_holder: Rc<Cell<Option<RNode>>> = Rc::new(Cell::new(None));
    // Reordering (docs/navigation.md): a toolkit whose own sidebar drags rows
    // (`Cap::NavReorder` Native) keeps it and marks the movable rows; one that cannot stands a
    // reorderable list in for it (`reorder_sidebar`). Collapsible sections win over both.
    let nav_reorder = day_core::capability(day_spec::Cap::NavReorder);
    let native_reorder = sel
        .reorder_items
        .clone()
        .filter(|_| nav_reorder == day_spec::Support::Native && sel.collapsed_sections.is_none());
    // Which rows drag, re-asked whenever the rows change.
    let movable_of = native_reorder.clone();
    {
        let (mh, ks, s, ts) = (
            menu_holder.clone(),
            typed.clone(),
            selection.clone(),
            titles.clone(),
        );
        let (titles_init, icons_init) = (titles.borrow().clone(), icons0.clone());
        // The selection the host is already on, not `None`. `sync_menu` pushes it a moment later
        // as `NavMenuPatch::Selected`, and every backend that draws a resting highlight used to
        // depend on that patch landing after its view existed, which held on UIKit and did not
        // on Android, where the sidebar came up marking nothing at all. Seeding the props means
        // the first realization is already right and the patch is only ever a change.
        let selected_init = {
            let key = selection.peek().key().to_string();
            typed
                .borrow()
                .iter()
                .position(|k| k.key() == key)
                .filter(|_| !key.is_empty())
        };
        let (badges_init, sections_init) = (rows0.badges.clone(), rows0.sections.clone());
        let (badge_icons_init, badge_tints_init) =
            (rows0.badge_icons.clone(), rows0.badge_tints.clone());
        let tints_init = rows0.tints.clone();
        let menus_init = rows0.menus.clone();
        let reorders_natively = native_reorder.is_some();
        let rows_script = items.clone();
        let movable_init: Vec<bool> = movable_of
            .as_ref()
            .map(|r| {
                typed
                    .borrow()
                    .iter()
                    .map(|k| r.drag(k) != NavDrag::Fixed)
                    .collect()
            })
            .unwrap_or_default();
        let regroup_init = matches!(movable_of, Some(SidebarDrag::Regroup(_)));
        let sorted_init: Vec<bool> = match &movable_of {
            Some(r @ SidebarDrag::Regroup(_)) => typed
                .borrow()
                .iter()
                .map(|k| r.drag(k) == NavDrag::Regroup)
                .collect(),
            _ => Vec::new(),
        };
        let document_keys = if sel.documents.is_some() {
            typed.borrow().iter().map(Route::key).collect()
        } else {
            Vec::new()
        };
        let document_event = sel.document_event.clone();
        let refresh = sel.refresh;
        let list_pred_click = sel.content_list_pred.clone();
        let pres_click = presentation_cell.clone();
        let detail_visible_click = sel.detail_visible;
        let menu_piece = if let Some(collapsed) = sel.collapsed_sections {
            section_sidebar(
                items.clone(),
                selection.clone(),
                collapsed,
                sel.on_section_expansion,
                icon_progress.clone(),
            )
        } else if let Some(reorder) = sel
            .reorder_items
            .filter(|_| nav_reorder == day_spec::Support::Emulated)
        {
            reorder_sidebar(
                items.clone(),
                selection.clone(),
                reorder,
                icon_progress.clone(),
            )
        } else {
            piece_fn(move |mcx| {
                let node = mcx.native(
                    kinds::NAV_MENU,
                    &NavMenuProps {
                        document_keys,
                        items: titles_init,
                        icons: icons_init,
                        badges: badges_init,
                        badge_icons: badge_icons_init,
                        badge_tints: badge_tints_init,
                        sections: sections_init,
                        tints: tints_init,
                        menus: menus_init,
                        movable: movable_init,
                        regroup: regroup_init,
                        sorted: sorted_init,
                        selected: selected_init,
                    },
                    Rc::new(LeafLayout),
                    Flex {
                        grow_w: true,
                        grow_h: true,
                        ..Default::default()
                    },
                    Boundary::No,
                );
                mh.set(Some(node));
                // The dayscript `reorder` step drives this sidebar in the rows the stand-in list
                // has, section headers counted, so one script reorders both.
                match native_reorder.clone() {
                    Some(SidebarDrag::Reorder(reorder)) => {
                        let rows = rows_script.clone();
                        day_core::set_scripted_reorder(node, move |from, to| {
                            let NavRows { keys, sections, .. } =
                                day_reactive::untrack(|| rows.derive());
                            script_nav_reorder(&keys, &sections, &reorder, from, to)
                        });
                    }
                    Some(SidebarDrag::Regroup(regroup)) => {
                        let rows = rows_script.clone();
                        day_core::set_scripted_reorder(node, move |from, to| {
                            let rows =
                                RegroupRows::from_nav(day_reactive::untrack(|| rows.derive()));
                            if let Some(drop) = rows.display_drop(&regroup, from, to)? {
                                (regroup.dropped)(drop);
                            }
                            Ok(to)
                        });
                    }
                    None => {}
                }
                if let Some((refreshing, action)) = refresh {
                    let refreshing = Rc::new(refreshing);
                    let state = refreshing.clone();
                    bind(
                        move || state.get(),
                        move |busy| {
                            with_tree(|t| {
                                t.patch(
                                    node,
                                    Box::new(day_spec::props::RefreshPatch { refreshing: *busy }),
                                    false,
                                )
                            });
                        },
                    );
                    mcx.on(node, move |event| {
                        if matches!(event, Event::RefreshRequested) {
                            if !day_reactive::untrack(|| refreshing.get()) {
                                action();
                            }
                            // Re-apply even when the state did not change: the user may have
                            // pulled an empty/offline library and the app declined the work.
                            let busy = day_reactive::untrack(|| refreshing.get());
                            with_tree(|t| {
                                t.patch(
                                    node,
                                    Box::new(day_spec::props::RefreshPatch { refreshing: busy }),
                                    false,
                                )
                            });
                        }
                    });
                }
                if let Some(event) = document_event {
                    mcx.on(node, move |ev| event(ev));
                }
                // A row the sidebar itself dragged: `from` moved to where `to` stood, both
                // item indices into the keys as they were before the move.
                // A drop a regrouping sidebar committed, checked against the app's rules here,
                // whatever the toolkit offered.
                if let Some(SidebarDrag::Regroup(regroup)) = native_reorder.clone() {
                    let rows = rows_script.clone();
                    mcx.on(node, move |ev| {
                        if let Event::NavRegroup {
                            from,
                            section,
                            before,
                        } = *ev
                        {
                            let rows =
                                RegroupRows::from_nav(day_reactive::untrack(|| rows.derive()));
                            if let Ok(Some(drop)) = rows.drop_at(&regroup, from, section, before) {
                                (regroup.dropped)(drop);
                            }
                        }
                    });
                }
                if let Some(SidebarDrag::Reorder(reorder)) = native_reorder {
                    let keys = ks.clone();
                    mcx.on(node, move |ev| {
                        if let Event::ListReorder { from, to } = *ev {
                            let pair = {
                                let keys = keys.borrow();
                                keys.get(from).cloned().zip(keys.get(to).cloned())
                            };
                            if let Some((moved, target)) = pair
                                && (reorder.eligible)(&moved)
                                && (reorder.eligible)(&target)
                            {
                                (reorder.moved)(moved, target);
                            }
                        }
                    });
                }
                mcx.on(node, move |ev| {
                    if let Event::SelectionChanged(i) = ev
                        && let Some(k) = ks.borrow().get(*i as usize)
                    {
                        // Announce the navigation from its source (§14.6) with the row's own title:
                        // the sidebar changes the route only after a remount, so a route observer would
                        // otherwise miss the move and have no label for it. Index the live titles.
                        let label = ts.borrow().get(*i as usize).cloned();
                        day_core::note_navigation(&k.key(), label.as_deref());
                        s.write(k.clone());
                        // Activation is not just selection. UIKit can leave the supplementary
                        // column offstage after its initial collapse, or after native back,
                        // even though this route is already selected. Re-present the list on
                        // EVERY tap, including a tap on the highlighted row. Do not rebuild it.
                        if merged_list
                            && pres_click.get() == NavPresentation::Stack
                            && detail_visible_click.is_some_and(|visible| !visible.peek())
                            && list_pred_click.as_ref().is_none_or(|p| p(k))
                        {
                            with_tree(|t| {
                                t.patch(host, Box::new(NavPatch::ListInStack(true)), false)
                            });
                        }
                    }
                });
                node
            })
            // A reorderable sidebar answers to the stand-in list's name, so a script's
            // `reorder` steps address the sidebar whichever one the toolkit shows.
            .id(if reorders_natively {
                day_core::id!(nav_reorder_list)
            } else {
                day_core::id!(nav_menu)
            })
            .any()
        };
        let content: AnyPiece = match sel.header {
            Some(h) => column((h(), menu_piece))
                .spacing(4.0)
                .align(HAlign::Leading)
                .any(),
            None => column((menu_piece,))
                .spacing(4.0)
                .align(HAlign::Leading)
                .any(),
        };
        let content = match sel.footer {
            Some(footer) => column((content.grow(), footer())).grow().any(),
            None => content,
        };
        with_nav_host(Some(host_cx.clone()), || {
            let mut pcx = BuildCx::new(root_page);
            let _ = content.build(&mut pcx);
        });
    }

    // The content-list page (docs/navigation.md): built once, resident for the host's life.
    // Its content follows the app's signals, so a selection change re-scopes it without a
    // rebuild. `with_nav_host(None)`: the pane is not a merge target, so a stack inside the
    // list keeps its own container rather than pushing onto this host.
    let list_build = sel.content_list.clone();
    let list_pred = sel.content_list_pred.clone();
    let detail_visible = sel.detail_visible;
    // Whether the content-list pane belongs to this destination (`content_list_for`), applied
    // wherever the shown destination can change. It lives here, shared, because three paths
    // reach it: a fresh `show`, a `show` that finds its page already resident (a chrome
    // presentation has built them all), and a presentation change that rebuilds the shape
    // around an unchanged selection. Missing any one of them strands the pane: collapsed
    // because some other destination was the last to speak, with nothing left to reopen it.
    // Set when the content-list page is built below; `apply_list_visible` writes through it so
    // the pane's chrome follows its visibility (docs/toolbars.md).
    let list_visible_sig: Rc<Cell<Option<Signal<bool>>>> = Rc::new(Cell::new(None));
    let apply_list_visible: Rc<dyn Fn(&K)> = {
        let (shown, pred) = (list_shown.clone(), list_pred.clone());
        let mirror = list_visible_sig.clone();
        Rc::new(move |key: &K| {
            if !native_list {
                return;
            }
            let want = pred.as_ref().is_none_or(|p| p(key));
            if want != shown.get() {
                shown.set(want);
                // The chrome mirror, so the pane's own commands leave the bar with the pane.
                if let Some(sig) = mirror.get() {
                    sig.set(want);
                }
                with_tree(|t| t.patch(host, Box::new(NavPatch::ListVisible(want)), false));
            }
        })
    };
    if native_list && let Some(build_list) = list_build.clone() {
        let page = nav_page(
            host,
            &NavPageProps {
                title: title_s.clone(),
                pane: Pane::List,
            },
            &sizes,
        );
        list_cell.set(Some(page));
        // The pane collapses for a destination that spans the whole detail area
        // (`content_list_for`), and a collapsed pane's commands must leave the bar with it
        // (docs/toolbars.md); otherwise a full-page section shows the list's Add and Filter.
        // Reactive, so a collapse re-composes the bar: the Cell above is what `NavLayout` reads
        // during layout, and this mirrors it for the chrome.
        let visible = Signal::new(initial_list_visible);
        list_visible_sig.set(Some(visible));
        // Two ways this pane stops being what the user is looking at: the destination collapses
        // it (`content_list_for`), or, on a shape that shows one pane at a time, a detail is
        // pushed over it. Its Add and Filter act on a list that is then behind the editor, so
        // they leave the bar with it (docs/toolbars.md). Side by side, both panes are up and
        // both keep their commands.
        let (dv, pres_sig) = (detail_visible, presentation_sig);
        // `try_get`: a gate is asked at merge time, which can be a window's teardown; a
        // disposed signal answers "not showing" rather than panicking (docs/toolbars.md).
        let gate: Rc<dyn Fn() -> bool> = Rc::new(move || {
            visible.try_get().unwrap_or(false)
                && (pres_sig.try_get().is_some_and(|p| p.is_split())
                    || dv.is_none_or(|d| !d.try_get().unwrap_or(false)))
        });
        with_nav_host(None, || {
            day_core::with_page_gated(page, Some(gate), day_spec::ToolbarColumn::List, || {
                let mut pcx = BuildCx::new(page);
                let _ = build_list().build(&mut pcx);
            });
        });
    }
    // The composed content list (`Cap::NavContentList` Unsupported): every list-backed
    // destination page carries the pane itself, beside the content while split and as the
    // root of a two-layer push flow while compact (the gated detail above). The
    // presentation is read through the signal, so a live morph re-arranges the page without
    // the host's involvement.
    let compose: Option<DestFn<K>> = if let (Some(list), true) = (list_build.clone(), !native_list)
    {
        let pred = list_pred.clone();
        let width = sel.content_list_width;
        let dv = detail_visible;
        let items_c = items.clone();
        // The live rows, for a data-driven key's title: only a static item carries a
        // `TextSource` of its own, and without these a row from `.items` titled its pushed page
        // with its raw key ("feed:5756…") instead of the name the row shows.
        let (typed_c, titles_c) = (typed.clone(), titles.clone());
        let pres = presentation_sig;
        let win = window;
        let host_cx_g = host_cx.clone();
        let detail_title_g = detail_title.clone();
        Some(Rc::new(move |key: &K| {
            if pred.as_ref().is_some_and(|p| !p(key)) {
                return items_c.build_page(key);
            }
            let (l1, l2) = (list.clone(), list.clone());
            let (i1, i2) = (items_c.clone(), items_c.clone());
            let (k1, k2) = (key.clone(), key.clone());
            let (hc, dt) = (host_cx_g.clone(), detail_title_g.clone());
            let (tk, tt) = (typed_c.clone(), titles_c.clone());
            let ba = gated_toolbar.clone();
            // Each arm rebuilds in this destination's page: a morph re-runs the `when` long after
            // the page was built, and an arm built outside it registers the list's commands
            // without the page's gate (a narrowed tablet then showed Items' Add on Settings).
            // Captured when the page builds: the destination is constructed before its page frame
            // is entered.
            let page: Rc<RefCell<Option<PageContext>>> = Rc::default();
            let at_build = page.clone();
            let arms = when(
                move || {
                    let p = pres.get();
                    // Side by side only where there is room for two columns.
                    // `rows_are_chrome()` alone is not that question: under the adaptive
                    // ladder a tab bar is the compact rung, and pairing a 320pt list with an
                    // editor across a phone leaves neither usable, which is what a scaffold
                    // that wanted tabs on a phone got. A pinned tab bar on a wide window
                    // still earns the pair, so the width is asked rather than the style.
                    p.is_split()
                        || (p.rows_are_chrome()
                            && day_core::window_size_class(win).is_some_and(|c| c.prefers_split()))
                },
                {
                    let page = page.clone();
                    move || {
                        let (l, i, k) = (l1.clone(), i1.clone(), k1.clone());
                        PageContext::enter(
                            &page,
                            row((l().width(width).grow_h(), i.build_page(&k).grow())).grow(),
                        )
                    }
                },
            )
            .otherwise(move || {
                let (l, i, k) = (l2.clone(), i2.clone(), k2.clone());
                PageContext::enter(
                    &page,
                    match dv {
                        // The gated two-layer flow (docs/navigation.md): a nested navigation
                        // host in a chrome presentation, a push onto the enclosing host in a
                        // stacked one; either way a navigation bar, a title, and a native
                        // back, where an in-place swap had none.
                        Some(d) => {
                            let retitle = i.static_title(&k.key());
                            let title = retitle
                                .as_ref()
                                .map(TextSource::initial)
                                .or_else(|| {
                                    let at = tk.borrow().iter().position(|x| x.key() == k.key())?;
                                    tt.borrow().get(at).cloned()
                                })
                                .unwrap_or_else(|| k.title());
                            gated_detail_piece(
                                GatedDetail {
                                    open: d,
                                    list: l,
                                    items: i,
                                    key: k,
                                    title,
                                    retitle,
                                    detail_title: dt.clone(),
                                    host_cx: hc.clone(),
                                    toolbar: ba.clone(),
                                },
                                pres,
                                win,
                            )
                        }
                        None => i.build_page(&k),
                    },
                )
            });
            AnyPiece::new(piece_fn(move |cx| {
                at_build.replace(Some(PageContext::current()));
                arms.build(cx)
            }))
        }))
    } else {
        None
    };

    let sync_menu = {
        let mh = menu_holder.clone();
        move |idx: Option<usize>| {
            if let Some(m) = mh.get() {
                with_tree(|t| t.patch(m, Box::new(NavMenuPatch::Selected(idx)), false));
            }
            // And onto the host, which is the node `.id()` names: a script asserting on a
            // nav addresses the nav, not the row list nested inside it. Every path that
            // changes the selection lands here, so this is the one place that has to record it.
            with_tree(|t| t.set_probe_selected(host, idx));
        }
    };

    // Detail pages, and how long they live.
    //
    // A presentation whose rows are the chrome (a tab bar, a rail) keeps every visited page
    // resident: switching tabs is `NavPatch::Select`, nothing is torn down, and each tab keeps
    // its scroll offset, its focused field, and its animations, which is what every native tab
    // container does. A split or stacked presentation keeps only the shown page and switches by
    // pop-then-push, which is what it did before adaptive navigation existed.
    //
    // Residency follows the presentation rather than the host. Making every nav page resident
    // would keep effects running for pages nobody is looking at and change the disposal
    // contract the docs make ("leaving the piece's branch disposes"); making none resident
    // would rebuild a tab's content on every tap. Splitting it this way means a morph only
    // ever disposes pages that are not on screen, or lazily builds ones that were not built
    // yet; the visible page is never rebuilt, which is the invariant a morph has to keep.
    let resident: Rc<RefCell<Vec<ResidentPage>>> = Rc::default();
    let current: Rc<RefCell<Option<String>>> = Rc::default();
    let nav_scope = Scope::current();
    // Shared: Both the selection bind and the row-derive effect drive the detail (see the
    // derive effect for why the selection bind alone is not enough).
    let show = std::rc::Rc::new({
        let (items, resident, current, sizes, typed_s, titles_s) = (
            items.clone(),
            resident.clone(),
            current.clone(),
            sizes.clone(),
            typed.clone(),
            titles.clone(),
        );
        let (sync_menu, owners, host_cx, selection, pres) = (
            sync_menu.clone(),
            owners.clone(),
            host_cx.clone(),
            selection.clone(),
            presentation_cell.clone(),
        );
        let (list_pred_s, list_in_stack_s) = (list_pred.clone(), list_in_stack.clone());
        let apply_list_visible_s = apply_list_visible.clone();
        let compose_s = compose.clone();
        let detail_title_s = detail_title.clone();
        move |key: &str| {
            if current.borrow().as_deref() == Some(key) {
                return;
            }
            let chrome = pres.get().rows_are_chrome();
            // The list interposes between the sidebar root and the detail exactly while a
            // merged-pane backend is stacked and the app gates the detail
            // (docs/navigation.md). Split-family presentations show the detail beside the
            // list, empty state and all.
            let gated =
                merged_list && pres.get() == NavPresentation::Stack && detail_visible.is_some();
            if !chrome {
                // Stacked or split: the outgoing page goes away. Dispose its scope first: a
                // merged inner stack's cleanup pops its pages (which sit on top natively) before
                // we pop the detail itself, so the native pop order stays top-down (iOS pops the
                // topmost VC; Android's inclusive pop unwinds everything above an entry).
                if let Some(p) = resident.borrow_mut().pop() {
                    p.scope.dispose();
                    with_tree(|t| t.patch(host, Box::new(NavPatch::Popped), false));
                    owners.borrow_mut().pop();
                    sizes.borrow_mut().remove(&p.node);
                    with_tree(|t| {
                        t.remove_subtree(p.node);
                        t.mark_layout_dirty();
                        t.layout_if_needed();
                    });
                }
            }
            *current.borrow_mut() = None;
            if key.is_empty() {
                // Deselected: the list layer (if interposed) leaves the stack with the detail.
                if list_in_stack_s.get() {
                    list_in_stack_s.set(false);
                    with_tree(|t| t.patch(host, Box::new(NavPatch::ListInStack(false)), false));
                    owners.borrow_mut().pop();
                }
                sync_menu(None);
                return;
            }
            let idx = typed_s.borrow().iter().position(|k| k.key() == key);
            let Some(idx) = idx else {
                sync_menu(None);
                return;
            };
            let typed_key_now = typed_s.borrow()[idx].clone();
            // The pane's visibility is settled for every destination change, including the
            // resident case below: a chrome presentation builds every destination, so the
            // last one built would otherwise be the one that had the final word.
            apply_list_visible_s(&typed_key_now);
            // Already built and still alive: the resident case. Nothing to build, nothing to
            // push: tell the host which of its pages to show and we are done.
            if let Some(i) = resident.borrow().iter().position(|p| p.key == key) {
                with_tree(|t| {
                    t.patch(host, Box::new(NavPatch::Select(i)), false);
                    t.mark_layout_dirty();
                    t.layout_if_needed();
                });
                *current.borrow_mut() = Some(key.to_string());
                sync_menu(Some(idx));
                return;
            }
            let typed_key = typed_key_now;
            let title_now = titles_s.borrow()[idx].clone();
            // Per-destination pane visibility (`content_list_for`): a full-width destination
            // collapses the pane, a list-backed one brings it back. `interposed` = this
            // destination puts the list between the sidebar root and its detail (a stacked
            // merged-pane backend, docs/navigation.md).
            let want = native_list && list_pred_s.as_ref().is_none_or(|p| p(&typed_key));
            let interposed = gated && want;
            if native_list {
                if interposed && !list_in_stack_s.get() {
                    // Interpose the list above the sidebar root, with its own back owner
                    // (back from the list = deselect).
                    list_in_stack_s.set(true);
                    with_tree(|t| t.patch(host, Box::new(NavPatch::ListInStack(true)), false));
                    let s = selection.clone();
                    owners.borrow_mut().push(Rc::new(move |_already_popped| {
                        if let Some(root) = K::from_key("") {
                            s.write(root);
                        }
                    }) as PopOwner);
                } else if gated && !want && list_in_stack_s.get() {
                    // A full-width destination while stacked: the list leaves the stack so its
                    // page sits directly on the sidebar root and back deselects.
                    list_in_stack_s.set(false);
                    with_tree(|t| t.patch(host, Box::new(NavPatch::ListInStack(false)), false));
                    owners.borrow_mut().pop();
                }
                // The detail waits for `detail_visible`: the list is the top of the stack
                // until the app opens a row. The selection is recorded as current; the
                // `detail_visible` bind re-enters here to perform the deferred push.
                if interposed && !detail_visible.expect("gated implies Some").peek() {
                    // A selected list can still be offstage after UIKit's initial collapse.
                    // Route changes must present it too, without adding another back owner.
                    with_tree(|t| t.patch(host, Box::new(NavPatch::ListInStack(true)), false));
                    *current.borrow_mut() = Some(key.to_string());
                    sync_menu(Some(idx));
                    return;
                }
            }
            // A static item retitles on locale change (its TextSource); a data-driven key uses
            // the resolved snapshot (its title tracks the items signal, not the locale). A
            // list-backed destination on a host that places the pane natively is the detail
            // layer, so the app's `detail_title` names it where one is set: the layer shows
            // an item, not the section (docs/navigation.md).
            let (page_title, retitle) = match &detail_title_s {
                Some(dt) if want => (dt.initial(), Some(dt.clone())),
                _ => (title_now.clone(), items.static_title(key)),
            };
            let page = nav_page(
                host,
                &NavPageProps {
                    title: page_title.clone(),
                    pane: Pane::Detail,
                },
                &sizes,
            );
            if !chrome {
                // The detail page's back action: with the list interposed, back from the
                // detail returns to the list (`detail_visible` := false); classically it
                // deselects (returns to the sidebar rows). Pushed before the content builds,
                // so a merged inner stack's page owners stack on top of it. A chrome
                // presentation has no back stack to own; a tab bar never pops.
                let owner: PopOwner = if interposed && let Some(dv) = detail_visible {
                    Rc::new(move |_already_popped| {
                        dv.set(false);
                    })
                } else {
                    let s = selection.clone();
                    Rc::new(move |_already_popped| {
                        if let Some(root) = K::from_key("") {
                            s.write(root);
                        }
                    })
                };
                owners.borrow_mut().push(owner);
                // Present the page before its content builds. Anything the content pushes
                // onto this same host while building (a composed gated detail whose signal
                // is already true, a merged stack's restored path) must land above this
                // page, and a backend that presents pages in patch order (Android presents
                // the most recently added) would otherwise show them inverted. `immersive_of`
                // runs out here for the usual reason: it can run app code, which must not
                // happen inside `with_tree`.
                let immersive = items.immersive_of(&typed_key.key());
                with_tree(|t| {
                    t.patch(
                        host,
                        Box::new(NavPatch::Pushed {
                            title: page_title.clone(),
                            immersive,
                        }),
                        false,
                    );
                });
            }
            let scope = nav_scope.enter(Scope::child);
            scope.enter(|| {
                // Inside the page's scope; see the pushed-detail site above.
                let content = match &compose_s {
                    Some(c) => c(&typed_key),
                    None => items.build_page(&typed_key),
                };
                // A resident page is a merge barrier: a `nav_stack` inside a tab keeps its own
                // native container rather than pushing onto the enclosing host, because the
                // enclosing host is not a stack (docs/navigation.md).
                let inner = if chrome { None } else { Some(host_cx.clone()) };
                // The page's own commands ride the window's bar only while it is the page
                // showing (docs/toolbars.md): a resident tab that is not in front, and a
                // destination the selection has moved off, both leave the bar.
                let sel_gate = Some(destination_gate(selection.clone(), key.to_string()));
                let build = || {
                    with_nav_host(inner, || {
                        day_core::with_page_in(
                            page,
                            sel_gate.clone(),
                            day_spec::ToolbarColumn::Detail,
                            window,
                            || {
                                let mut c = BuildCx::new(page);
                                let _ = content.build(&mut c);
                            },
                        );
                    });
                };
                if chrome {
                    // Resident, so anything this page builds outlives the switch away from it and
                    // has to say whether it is selected. Read the selection itself: a route link
                    // can switch tabs and enter a nested route in one batched event, before the
                    // presentation effect updates `current`.
                    with_page_active(destination_gate(selection.clone(), key.to_string()), build);
                } else {
                    build();
                }
            });
            resident.borrow_mut().push(ResidentPage {
                key: key.to_string(),
                scope,
                node: page,
            });
            let at = resident.borrow().len() - 1;
            // A stacked page was presented above, before its content; the resident case
            // selects after the build, because the page must exist to be shown.
            if chrome {
                with_tree(|t| t.patch(host, Box::new(NavPatch::Select(at)), false));
            }
            with_tree(|t| {
                t.mark_layout_dirty();
                t.layout_if_needed();
            });
            // Live retitle for a static item: its title source re-resolves on locale change and
            // the host's native bar follows via `NavPatch::Title`. Scope-owned, dies with the page.
            if let Some(rt) = retitle {
                scope.enter(|| {
                    rt.bind_to(host, |t| Box::new(NavPatch::Title(t)), false);
                });
            }
            *current.borrow_mut() = Some(key.to_string());
            sync_menu(Some(idx));
        }
    });

    // Neither a split nor a tab bar can draw "nothing selected": a split has no way to fill the
    // detail pane, and a tab bar always has one tab active. Both default to the first item. Only
    // a stack has an empty state, and there it is wanted: the collapsed list the user has not
    // chosen from yet. A host with a native content list joins the default-selection rule at
    // every presentation: the pane needs a selection to scope itself to, and a collapsed
    // merged-pane host opens on the list rather than on bare rows.
    if (split || presentation.rows_are_chrome() || native_list)
        && selection.peek().key().is_empty()
        && let Some(k) = typed.borrow().first().cloned()
    {
        selection.write(k);
    }
    // Build every destination, then re-select the current one.
    //
    // A tab bar needs an item per destination up front: `UITabBarController` and Material's
    // navigation bar both build their chrome from the full set, so a page nobody has visited yet
    // is a tab that is not there. Lazy building is right for a split or a stack, where only
    // the shown page is drawn; where the rows are the chrome, the rows have to be complete.
    //
    // This runs before the selection bind below, and that order is the contract with the
    // chrome backends: `NavPatch::Select` names a page by attach order, while the chrome draws
    // the rows, so a suite can only pair the two when page i is row i. Letting the bind build the
    // selected destination first breaks that: restoring a saved section (`.restore`, which
    // android-material installs for every app as its instance-state contract) rebuilds with a
    // non-first selection, whose page then attaches at 0 and highlights row 0.
    let build_all = {
        let (show, typed_a, sel_a) = (show.clone(), typed.clone(), selection.clone());
        Rc::new(move || {
            let keys: Vec<String> = typed_a.borrow().iter().map(|k| k.key()).collect();
            for k in keys {
                show(&k);
            }
            show(&sel_a.peek().key());
        })
    };
    if presentation.rows_are_chrome() {
        build_all();
    }
    {
        let (s, show) = (selection.clone(), show.clone());
        bind(move || s.read().key(), move |key: &String| show(key));
    }

    // `detail_visible`, both directions (docs/navigation.md). Only the stacked merged-pane
    // shape reacts here: `true` performs the deferred detail push for the current selection,
    // `false` pops back to the interposed list. Split-family presentations ignore the signal:
    // their detail pane is always on screen (native back never runs a detail owner there).
    if let Some(dv) = detail_visible {
        let (show_dv, current_dv, resident_dv, sizes_dv, owners_dv) = (
            show.clone(),
            current.clone(),
            resident.clone(),
            sizes.clone(),
            owners.clone(),
        );
        let (pres_dv, list_in_stack_dv) = (presentation_cell.clone(), list_in_stack.clone());
        bind(
            move || dv.get(),
            move |v: &bool| {
                let gated_now = merged_list
                    && pres_dv.get() == NavPresentation::Stack
                    && list_in_stack_dv.get();
                if !gated_now {
                    return;
                }
                if *v {
                    let key = current_dv.borrow().clone();
                    if resident_dv.borrow().is_empty()
                        && let Some(k) = key
                    {
                        // Deferred push: `show` re-runs for the recorded selection, sees the
                        // signal true, and performs the build it withheld.
                        *current_dv.borrow_mut() = None;
                        show_dv(&k);
                    }
                } else if let Some(p) = resident_dv.borrow_mut().pop() {
                    p.scope.dispose();
                    with_tree(|t| t.patch(host, Box::new(NavPatch::Popped), false));
                    owners_dv.borrow_mut().pop();
                    sizes_dv.borrow_mut().remove(&p.node);
                    with_tree(|t| {
                        t.remove_subtree(p.node);
                        t.mark_layout_dirty();
                        t.layout_if_needed();
                    });
                }
            },
        );
    }

    // A detail open beside its list closes before the section is left (docs/navigation.md). Where
    // the list is composed into the destination's page, the platform's back would pop that whole
    // page, list and detail together, so while a detail is open side by side this host routes the
    // native back through Day (`NavHostCx::vote_guard`) and the back handler below closes the
    // detail instead. A native pane is a column of its own, which no native back pops.
    let beside: Rc<Cell<bool>> = Rc::default();
    if let Some(dv) = detail_visible
        && list_build.is_some()
        && !native_list
    {
        let (hc, s, pred, beside) = (
            host_cx.clone(),
            selection.clone(),
            list_pred.clone(),
            beside.clone(),
        );
        bind(
            move || {
                let k = s.read();
                dv.get()
                    && presentation_sig.get().is_split()
                    && !k.key().is_empty()
                    && pred.as_ref().is_none_or(|p| p(&k))
            },
            move |want: &bool| {
                if *want != beside.get() {
                    beside.set(*want);
                    hc.vote_guard(*want);
                }
            },
        );
    }

    // What a presentation change means for the model, whoever caused it. Widening with nothing
    // selected would leave the detail pane empty, the one state a split presentation has no way
    // to draw, so adopt the same first-item rule the build uses. Narrowing keeps the selection
    // instead: the detail becomes the top of the stack, which is where the user already was.
    let reconcile = {
        let (pc, sel_r, typed_r, split_r) = (
            presentation_cell.clone(),
            selection.clone(),
            typed.clone(),
            split_cell.clone(),
        );
        let build_all_r = build_all.clone();
        let (resident_r, current_r, sizes_r, owners_r) = (
            resident.clone(),
            current.clone(),
            sizes.clone(),
            owners.clone(),
        );
        let (list_pred_r, list_in_stack_r, show_r) =
            (list_pred.clone(), list_in_stack.clone(), show.clone());
        let apply_list_visible_r = apply_list_visible.clone();
        Rc::new(move |next: NavPresentation| {
            let was_chrome = pc.get().rows_are_chrome();
            pc.set(next);
            split_r.set(next.is_split());
            presentation_sig.set(next);
            // Leaving a chrome presentation: the resident pages nobody can see any more go away,
            // because a split or stacked host draws exactly one detail page. The shown page is
            // kept (rebuilding what the user is looking at is the one thing a morph must never
            // do) and is left as the sole entry, so it reads as the top of the new stack.
            //
            // Entering a chrome presentation needs no counterpart: the shown page is already
            // resident, and the others build lazily when they are first selected.
            if was_chrome && !next.rows_are_chrome() {
                let shown = current_r.borrow().clone();
                let gone: Vec<ResidentPage> = {
                    let mut r = resident_r.borrow_mut();
                    let (keep, drop): (Vec<_>, Vec<_>) =
                        r.drain(..).partition(|p| Some(&p.key) == shown.as_ref());
                    *r = keep;
                    drop
                };
                for p in gone {
                    p.scope.dispose();
                    sizes_r.borrow_mut().remove(&p.node);
                    with_tree(|t| t.remove_subtree(p.node));
                }
                // The kept page now owns the one back affordance the stack presentation offers.
                owners_r.borrow_mut().clear();
                if let Some(k) = shown {
                    let s = sel_r.clone();
                    let owner: PopOwner = Rc::new(move |_already_popped| {
                        if let Some(root) = K::from_key("") {
                            s.write(root);
                        }
                    });
                    owners_r.borrow_mut().push(owner);
                    let _ = k;
                }
                with_tree(|t| {
                    t.mark_layout_dirty();
                    t.layout_if_needed();
                });
            }
            if !was_chrome && next.rows_are_chrome() {
                // Entering a chrome presentation: the rows become the chrome, so every
                // destination needs its page for the bar to be complete.
                build_all_r();
            }
            if (next.is_split() || next.rows_are_chrome() || native_list)
                && sel_r.peek().key().is_empty()
                && let Some(k) = typed_r.borrow().first().cloned()
            {
                sel_r.write(k);
            }
            // Content-list settlement (docs/navigation.md). The pane's own visibility comes
            // first and applies to every backend that places the pane itself: entering a chrome
            // presentation builds every destination, and a destination without a list collapses
            // the pane on its way past, so the shape that comes next has to state the selected
            // destination's answer again.
            if native_list
                && let Some(k) = typed_r
                    .borrow()
                    .iter()
                    .find(|x| Some(&x.key()) == current_r.borrow().as_ref())
                    .cloned()
            {
                apply_list_visible_r(&k);
            }
            // Narrowing into the gated stack interposes the list for the current selection and
            // retracts a detail the app is not showing; widening back restores the always-on
            // detail beside the pane. The owner stack is rebuilt for the new shape, because the
            // old owners named the old one.
            if merged_list && let Some(dv) = detail_visible {
                if next == NavPresentation::Stack {
                    let key = current_r.borrow().clone();
                    let want = key.as_ref().is_some_and(|k| {
                        typed_r
                            .borrow()
                            .iter()
                            .find(|x| &x.key() == k)
                            .is_some_and(|tk| list_pred_r.as_ref().is_none_or(|p| p(tk)))
                    });
                    if want {
                        if !list_in_stack_r.get() {
                            list_in_stack_r.set(true);
                            with_tree(|t| {
                                t.patch(host, Box::new(NavPatch::ListInStack(true)), false)
                            });
                        }
                        owners_r.borrow_mut().clear();
                        let s = sel_r.clone();
                        owners_r.borrow_mut().push(Rc::new(move |_already_popped| {
                            if let Some(root) = K::from_key("") {
                                s.write(root);
                            }
                        }) as PopOwner);
                        if dv.peek() {
                            // The detail stays on top of the interposed list; its back now
                            // returns to the list, not to the rows.
                            owners_r.borrow_mut().push(Rc::new(move |_already_popped| {
                                dv.set(false);
                            }) as PopOwner);
                        } else if let Some(p) = resident_r.borrow_mut().pop() {
                            // The app is not showing a detail: the list is the top.
                            p.scope.dispose();
                            with_tree(|t| t.patch(host, Box::new(NavPatch::Popped), false));
                            sizes_r.borrow_mut().remove(&p.node);
                            with_tree(|t| {
                                t.remove_subtree(p.node);
                                t.mark_layout_dirty();
                                t.layout_if_needed();
                            });
                        }
                    }
                } else if next.is_split() {
                    // The backend's expand lifted the list back into its own pane.
                    list_in_stack_r.set(false);
                    let key = current_r.borrow().clone();
                    if resident_r.borrow().is_empty()
                        && let Some(k) = key
                    {
                        // The detail was withheld while gated; a split shows it always.
                        *current_r.borrow_mut() = None;
                        show_r(&k);
                    } else if !resident_r.borrow().is_empty() {
                        owners_r.borrow_mut().clear();
                        let s = sel_r.clone();
                        owners_r.borrow_mut().push(Rc::new(move |_already_popped| {
                            if let Some(root) = K::from_key("") {
                                s.write(root);
                            }
                        }) as PopOwner);
                    }
                }
            }
        })
    };

    if requested.is_none() && can_split && we_drive {
        // We drive (docs/size-classes.md). Seeded with what we just built, so the first run is a
        // no-op; after that a class change patches the live host and the backend re-homes the
        // pages it already has. Nothing here rebuilds a page, which is what keeps scroll offsets,
        // field focus, and the search query across the morph.
        let rec = reconcile.clone();
        bind_seeded(
            presentation,
            move || resolve(day_core::window_size_class(window)),
            move |next: &NavPresentation| {
                with_tree(|t| {
                    t.patch(host, Box::new(NavPatch::Presentation(*next)), false);
                    t.mark_layout_dirty();
                    t.layout_if_needed();
                });
                rec(*next);
            },
        );
    } else if toolkit_drives {
        // The toolkit drives: its own adaptive container already morphed and is telling us after
        // the fact, so there is nothing to patch, only the model to reconcile. Pushing a
        // presentation at it instead would be a second owner of the presentation racing the
        // platform's collapse animation.
        let rec = reconcile.clone();
        cx.on(host, move |ev| {
            if let Event::NavPresentationChanged(next) = ev {
                rec(*next);
                with_tree(|t| {
                    t.mark_layout_dirty();
                    t.layout_if_needed();
                });
            }
        });
    }

    let icon_progress_enabled = icon_progress.is_some();
    let documents = sel.documents.is_some();
    let retain_selection = sel.retain_selection;
    // Re-derive the row set when a dynamic block's signal changes (re-patch the native menu,
    // reset the selection if its item vanished) and when the locale changes (tracked title
    // resolution: same keys, new titles). Installed unconditionally: a fully static
    // nav's derive subscribes to nothing and this effect never re-fires.
    {
        let (items_e, typed_e, titles_e, mh_e, sel_e) = (
            items.clone(),
            typed.clone(),
            titles.clone(),
            menu_holder.clone(),
            selection.clone(),
        );
        // The live presentation, not the build-time one: this effect outlives a morph, and what
        // "must never show an empty detail" means changes with it.
        let (show_e, pres_e) = (show.clone(), presentation_cell.clone());
        // Seeded with the rows the menu was realized with.
        let last_rows: RefCell<Option<ShownRows>> = RefCell::new(Some(shown0));
        let (resident_e, current_e, sizes_e) = (resident.clone(), current.clone(), sizes.clone());
        let movable_e = movable_of.clone();
        bind(
            move || {
                // Tracked derive: subscribes to every dynamic block's signal.
                let NavRows {
                    keys: k,
                    titles: t,
                    icons: i,
                    badges: b,
                    badge_icons: bi,
                    badge_tints: bt,
                    section_ids: _,
                    sections: sc,
                    tints: tn,
                    menus: mn,
                } = items_e.derive();
                (
                    k.iter().map(|x| x.key()).collect::<Vec<_>>(),
                    k,
                    t,
                    i,
                    b,
                    sc,
                    tn,
                    mn,
                    bi,
                    bt,
                )
            },
            move |(key_strs, keys, ts, ics, bs, scs, tns, mns, bis, bts): &DerivedRows<K>| {
                // Same rows as the last patch, with only their words or decorations moved?
                let rows_changed = {
                    let mut last = last_rows.borrow_mut();
                    let changed = last.as_ref().and_then(|l: &ShownRows| {
                        (l.keys == *key_strs && l.sections == *scs && l.menus == *mns).then(|| {
                            (0..key_strs.len())
                                .filter(|&i| {
                                    l.titles[i] != ts[i]
                                        || l.icons[i] != ics[i]
                                        || l.tints[i] != tns[i]
                                        || l.badges[i] != bs[i]
                                        || l.badge_icons[i] != bis[i]
                                        || l.badge_tints[i] != bts[i]
                                })
                                .collect::<Box<[usize]>>()
                        })
                    });
                    *last = Some(ShownRows {
                        keys: key_strs.clone(),
                        titles: ts.clone(),
                        icons: ics.clone(),
                        badges: bs.clone(),
                        badge_icons: bis.clone(),
                        badge_tints: bts.clone(),
                        sections: scs.clone(),
                        tints: tns.clone(),
                        menus: mns.clone(),
                    });
                    changed
                };
                *typed_e.borrow_mut() = keys.clone();
                *titles_e.borrow_mut() = ts.clone();
                let selected_key = sel_e.peek();
                let cur = selected_key.key();
                let retain = !cur.is_empty()
                    && !key_strs.contains(&cur)
                    && retain_selection
                        .as_ref()
                        .is_some_and(|keep| keep(&selected_key));
                // A resident page whose row is gone has nothing left to select it, so it would
                // sit alive and invisible for the life of the surface, and shift every
                // `NavPatch::Select` index past it. Drop it here, where the new row set is known.
                // Only reachable in a chrome presentation; elsewhere at most one page is resident
                // and the selection reset below takes care of it.
                {
                    let stale: Vec<ResidentPage> = {
                        let mut r = resident_e.borrow_mut();
                        let (keep, drop): (Vec<_>, Vec<_>) = r
                            .drain(..)
                            .partition(|p| key_strs.contains(&p.key) || (retain && p.key == cur));
                        *r = keep;
                        drop
                    };
                    if !stale.is_empty() {
                        if current_e
                            .borrow()
                            .as_ref()
                            .is_some_and(|c| stale.iter().any(|p| &p.key == c))
                        {
                            *current_e.borrow_mut() = None;
                        }
                        for p in stale {
                            p.scope.dispose();
                            sizes_e.borrow_mut().remove(&p.node);
                            with_tree(|t| t.remove_subtree(p.node));
                        }
                        with_tree(|t| {
                            t.mark_layout_dirty();
                            t.layout_if_needed();
                        });
                    }
                }
                // If the selected key is gone, reset (Option key → None); else keep it selected.
                let still = retain || cur.is_empty() || key_strs.iter().any(|k| k == &cur);
                if !still && let Some(root) = K::from_key("") {
                    sel_e.write(root);
                }
                // A split view must never show an empty detail. The build-time fallback ran
                // once, before any filtering, so re-apply it here: when the selected row is
                // gone, move to the first row that survived rather than blanking the pane.
                let mut cur2 = sel_e.peek().key();
                let pres_now = pres_e.get();
                // A collapsed native content list may have returned to its sidebar root.
                // Background count changes and filtering are not navigation requests: keep
                // that empty selection until a row tap or an explicit route activates it.
                if (pres_now.is_split()
                    || pres_now.rows_are_chrome()
                    || (native_list && pres_now != NavPresentation::Stack))
                    && cur2.is_empty()
                    && let Some(k) = keys.first().cloned()
                {
                    sel_e.write(k.clone());
                    cur2 = k.key();
                }
                let selected = key_strs.iter().position(|k| k == &cur2);
                if let Some(m) = mh_e.get() {
                    with_tree(|t| {
                        t.patch(
                            m,
                            Box::new(day_spec::props::NavMenuPatch::Items {
                                rows_changed: rows_changed.clone(),
                                document_keys: if documents {
                                    key_strs.clone()
                                } else {
                                    Vec::new()
                                }
                                .into_boxed_slice(),
                                items: ts.clone(),
                                icons: ics.clone(),
                                badges: bs.clone(),
                                badge_icons: bis.clone(),
                                badge_tints: bts.clone(),
                                sections: scs.clone(),
                                tints: tns.clone(),
                                menus: mns.clone(),
                                movable: movable_e
                                    .as_ref()
                                    .map(|r| {
                                        keys.iter().map(|k| r.drag(k) != NavDrag::Fixed).collect()
                                    })
                                    .unwrap_or_default(),
                                sorted: match &movable_e {
                                    Some(r @ SidebarDrag::Regroup(_)) => {
                                        keys.iter().map(|k| r.drag(k) == NavDrag::Regroup).collect()
                                    }
                                    _ => Vec::new(),
                                },
                                selected,
                            }),
                            false,
                        );
                    });
                }
                // Re-map active route keys after insertions/filtering, after the row patch.
                if icon_progress_enabled {
                    progress_revision.update(|n| *n = n.wrapping_add(1));
                }
                // Document collections can add in the background and reorder existing keys.
                // Realize missing pages first, then move the same native objects into key order.
                if pres_now.rows_are_chrome() {
                    for key in key_strs {
                        let missing = !resident_e.borrow().iter().any(|p| &p.key == key);
                        if missing {
                            show_e(key);
                        }
                    }
                    let order: Vec<usize> = key_strs
                        .iter()
                        .filter_map(|key| resident_e.borrow().iter().position(|p| &p.key == key))
                        .collect();
                    if order.len() == resident_e.borrow().len()
                        && order.iter().enumerate().any(|(i, old)| i != *old)
                    {
                        let mut old: Vec<Option<ResidentPage>> =
                            resident_e.borrow_mut().drain(..).map(Some).collect();
                        // Unique route keys produce a permutation of all resident pages;
                        // each in-bounds slot is taken exactly once.
                        *resident_e.borrow_mut() =
                            order.iter().map(|i| old[*i].take().unwrap()).collect();
                        with_tree(|t| t.patch(host, Box::new(NavPatch::Reorder(order)), false));
                        *current_e.borrow_mut() = None;
                    }
                }
                // Drive the detail from here as well as from the selection bind. That bind is
                // created first, so when a query signal and the selection are written in one
                // batch it runs while `typed` still holds the pre-filter rows, finds no index
                // for the key, and gives up, leaving a highlighted row over an empty pane with
                // nothing left to re-trigger it. The fallback just above has the same problem in
                // reverse: it changes the selection after that bind has already run. `show` is
                // idempotent (it returns at once when the detail already shows this key), so
                // calling it on every derive costs nothing and closes both holes.
                show_e(&cur2);
            },
        );
    }
    if let Some(progress) = icon_progress {
        let mh = menu_holder.clone();
        let keys = typed.clone();
        bind(
            move || {
                let revision = progress_revision.get();
                let active = progress();
                let keys = keys.borrow();
                let values = active
                    .into_iter()
                    .filter_map(|(key, fraction)| {
                        keys.iter().position(|k| k.key() == key.key()).map(|row| {
                            (
                                row,
                                fraction
                                    .filter(|f| f.is_finite())
                                    .map(|f| f.clamp(0.0, 1.0)),
                            )
                        })
                    })
                    .collect::<Vec<_>>();
                (revision, values)
            },
            move |(_, values)| {
                if let Some(menu) = mh.get() {
                    with_tree(|t| {
                        t.patch(
                            menu,
                            Box::new(NavMenuPatch::IconProgress(values.clone())),
                            false,
                        )
                    });
                }
            },
        );
    }

    // Native back (mobile up-arrow / system back) → the topmost page's owner. With only this
    // sidebar on the host, that's always the detail's deselect owner (returns to the list); when
    // a nested stack has merged its pages on top, its owners run first (docs/navigation.md). A
    // typed key deselects via its "" decoding (`Option<Section>` → `None`); a bare enum has no
    // list-only state so its owner's deselect is a no-op, so back is effectively ignored.
    //
    // A detail open beside its composed list comes first: `beside` holds this host's guard vote,
    // so the platform has not popped, and the back closes the detail rather than the section,
    // unless a stack merged above the section page owns it.
    {
        let owners = owners.clone();
        let (beside, dv_back) = (beside.clone(), detail_visible);
        cx.on(host, move |ev| match ev {
            Event::NavBack { already_popped } => {
                if !*already_popped
                    && beside.get()
                    && owners.borrow().len() <= 1
                    && let Some(dv) = dv_back
                {
                    dv.set(false);
                } else {
                    let top = owners.borrow().last().cloned();
                    if let Some(f) = top {
                        f(*already_popped);
                    }
                }
            }
            Event::RouteRequested(route) => {
                let _ = day_core::navigate(route);
            }
            _ => {}
        });
    }

    // Registered after the pages are built: `register_nav` drains any pending route as it
    // registers, and a route arriving before this host has children attaches a page to a
    // parent that is not in the tree yet (an intermittent startup panic on AppKit). Ordering
    // here does not decide routing; `NavController::depth` does.
    let (tp_push, s_push) = (typed.clone(), selection.clone());
    let s_pop = selection.clone();
    let (dv_pop, lis_pop, pres_pop) = (
        detail_visible,
        list_in_stack.clone(),
        presentation_cell.clone(),
    );
    let (has_list_pop, pred_pop) = (list_build.is_some(), list_pred.clone());
    let s_cur = selection.clone();
    let (tp_enter, s_enter) = (typed.clone(), selection.clone());
    let s_seg = selection.clone();
    let pick =
        |tp: &Rc<RefCell<Vec<K>>>, k: &str| tp.borrow().iter().find(|x| x.key() == k).cloned();
    let pick_push = pick;
    let pick_enter = pick;
    if routed {
        note_routed_one_of_n("sidebar");
        register_route_surface(
            move |k| {
                if k.is_empty() {
                    if let Some(root) = K::from_key("") {
                        s_push.write(root);
                        true
                    } else {
                        false // no empty state (bare-enum key); let the parent handle ""
                    }
                } else if let Some(key) = pick_push(&tp_push, k) {
                    s_push.write(key);
                    true
                } else {
                    false
                }
            },
            move |_| {
                let current = s_pop.peek();
                let pres = pres_pop.get();
                if current.key().is_empty() {
                    false
                } else if let Some(dv) = dv_pop
                    && dv.peek()
                    && has_list_pop
                    && pred_pop.as_ref().is_none_or(|p| p(&current))
                    && (pres.is_split()
                        || (merged_list && pres == NavPresentation::Stack && lis_pop.get()))
                {
                    // The detail is the innermost layer wherever it shows with its list
                    // (docs/navigation.md): over it while the list is interposed in a collapsed
                    // stack, where the native back closes it through the page's owner, and
                    // beside it in a split, where the back closes it before the section is left.
                    // An imperative `nav_back` lands in the same place rather than leaving the
                    // section, which is what it did on a phone, popping the list and the section
                    // under a script's back.
                    dv.set(false);
                    true
                } else if let Some(root) = K::from_key("") {
                    s_pop.write(root);
                    true
                } else {
                    false
                }
            },
            move || s_cur.peek().key(),
            // Absolute-path segment: a declared item key selects it (no "", since segments are
            // non-empty).
            move |k| {
                if let Some(key) = pick_enter(&tp_enter, k) {
                    s_enter.write(key);
                    true
                } else {
                    false
                }
            },
            move || {
                let k = s_seg.peek().key();
                if k.is_empty() { Vec::new() } else { vec![k] }
            },
        );
    }

    persist_selection(restore, &selection);
    host
}

// ===========================================================================
// NavStack: a push/pop navigation stack bound to a Signal<Vec<String>>.
// The native UINavigationController / AdwNavigationView / back-stack is reconciled
// to the path; the back button writes the pop back into the path.
// ===========================================================================

struct StackEntry<K> {
    key: K,
    scope: Scope,
    page: RNode,
}

/// What a [`NavStack::on_back`] guard returns for one back-like event (a native back gesture/button,
/// or [`nav_back`]). Programmatic path writes are not guarded; the guard is a policy on the
/// user's back affordance, matching Jetpack Compose's `BackHandler` (docs/navigation.md).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum BackResponse {
    /// Let the pop happen now.
    Proceed,
    /// Consume the back; the pop does not happen. Stash the [`BackRequest`] and call
    /// [`BackRequest::proceed`] later (e.g. after a confirmation dialog) to perform the pop.
    Handled,
}

/// The deferred pop handed to a [`NavStack::on_back`] guard. Hold it, then call [`proceed`] to
/// perform the back the guard consumed (the unsaved-changes → confirm → leave flow).
///
/// [`proceed`]: BackRequest::proceed
#[derive(Clone)]
pub struct BackRequest {
    pop: Rc<dyn Fn()>,
}

impl BackRequest {
    /// Perform the pop this back requested. Runs the same path pop a `Proceed` would have; safe
    /// to call once (a second call after the page is gone is a no-op).
    pub fn proceed(&self) {
        (self.pop)();
    }
}

/// A push/pop navigation stack whose contents are an app-owned `Signal<Vec<K>>` (the path
/// above the root). Day reconciles the native stack to the path; the native back button
/// writes the pop back into it (docs/navigation.md).
///
/// The key type is any [`Route`]: `String` for raw keys, or a typed enum whose variants can
/// carry data; the destination builder then receives the typed value, and an absolute
/// `navigate("…/item-42")` parses each segment via [`Route::from_key`] (rejecting segments
/// that don't parse; `String` accepts everything).
///
/// ```ignore
/// let path = Signal::new(Vec::<Drill>::new());
/// nav_stack(path.clone(), home_view).destination(|d: &Drill| detail_view(d))
/// // push:  path.update(|p| p.push(Drill::Item { id: 42 }));
/// ```
pub struct NavStack<S: Binding<Vec<K>>, K: Route = String> {
    path: S,
    title: TextSource,
    root: AnyPiece,
    destination: Rc<dyn Fn(&K) -> AnyPiece>,
    on_back: Option<Rc<dyn Fn(BackRequest) -> BackResponse>>,
    /// The persistence key set by [`NavStack::restore`]: the path is saved here (its keys `/`-joined)
    /// on every change and restored at build. `None` = not persisted.
    restore: Option<String>,
    /// Items declared on the stack's root page chrome ([`NavStack::toolbar`]).
    toolbar: Vec<crate::ToolbarSource>,
}

pub fn nav_stack<K: Route, S: Binding<Vec<K>>>(path: S, root: impl Piece) -> NavStack<S, K> {
    NavStack {
        path,
        title: TextSource::Static(String::new()),
        root: AnyPiece::new(root),
        destination: Rc::new(|_| {
            piece_fn(|cx| cx.layout_only(Rc::new(PassThrough), Flex::default(), Boundary::No)).any()
        }),
        on_back: None,
        restore: None,
        toolbar: Vec::new(),
    }
}

#[day_macros::builder(NavStackBuilder<K>)]
impl<K: Route, S: Binding<Vec<K>>> NavStack<S, K> {
    pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
        self.title = t.into_text();
        self
    }
    /// Declare toolbar items on this stack's root page chrome (docs/toolbars.md): the commands
    /// that act on what the root shows, and that have nothing to act on once a pushed page covers
    /// it. A pushed page declares its own with the same method on the piece it builds.
    ///
    /// Takes one item, a list of them, or a closure that derives the list.
    pub fn toolbar<M>(mut self, content: impl crate::ToolbarContent<M>) -> Self {
        self.toolbar.push(content.into_source());
        self
    }

    /// Build the view for a pushed key (`&String` for raw keys, the typed value otherwise).
    pub fn destination<P: Piece>(mut self, build: impl Fn(&K) -> P + 'static) -> Self {
        self.destination = Rc::new(move |k| AnyPiece::new(build(k)));
        self
    }
    /// Intercept the back affordance (docs/navigation.md). The guard runs for every native back
    /// gesture/button and [`nav_back`] while the stack is above its root; it returns
    /// [`BackResponse::Proceed`] to pop now or [`BackResponse::Handled`] to consume the back
    /// (stash the [`BackRequest`] and call [`BackRequest::proceed`] later). Programmatic path
    /// writes are never guarded. While a guard is armed the toolkit stops auto-popping on a
    /// native gesture and routes the back through Day instead (`NavPatch::GuardTop`).
    pub fn on_back(mut self, guard: impl Fn(BackRequest) -> BackResponse + 'static) -> Self {
        self.on_back = Some(Rc::new(guard));
        self
    }
    /// Remember the pushed path across launches (docs/navigation.md). On every change the path's
    /// keys are `/`-joined and saved under `key`; at build the saved path is parsed back (each
    /// segment via [`Route::from_key`]) and restored, so the app reopens exactly where the user
    /// left off, including after an Android process death, unless a launch deep link is pending,
    /// which wins. `day::launch` installs the preferences as the store (docs/navigation.md); a
    /// saved path with a segment that no longer parses is ignored whole.
    pub fn restore(mut self, key: impl Into<String>) -> Self {
        self.restore = Some(key.into());
        self
    }
}

impl<K: Route, S: Binding<Vec<K>>> Piece for NavStack<S, K> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        use day_spec::props::{NavPageProps, NavPatch, NavPresentation, NavProps, Pane};
        let NavStack {
            path,
            title,
            root,
            destination: dest,
            on_back,
            restore,
            toolbar,
        } = self;
        let title_s = title.initial();
        // Only the top page shows (docs/toolbars.md): a desktop's one bar carries its items and
        // its search field, not those of the pages under it. The enclosing page's own gate still
        // applies, so a stack in a tab that is not selected shows nothing.
        let outer_gate = day_core::current_page_gate();
        let shown_depth = Signal::new(0usize);
        let gate = move |at: usize| -> Option<Rc<dyn Fn() -> bool>> {
            let outer = outer_gate.clone();
            Some(Rc::new(move || {
                outer.as_ref().is_none_or(|g| g()) && shown_depth.get() == at
            }))
        };

        // Restore the saved path before the reconcile binding runs, so its pages build on first
        // pass. A launch deep link wins (skip). The path is decoded from the same percent-encoded
        // wire format the rest of nav uses (`parse_route`), so a key that itself contains `/` (or
        // `?`, `%`) round-trips instead of splitting into two. The whole path is parsed via
        // `Route::from_key`; any segment that no longer parses discards the restore rather than
        // building a partial stack (docs/navigation.md).
        if let Some(key) = restore.as_deref()
            && !day_core::has_launch_deeplink()
            && let Some(saved) = day_core::nav_store_load(key)
        {
            let (segments, _) = day_core::parse_route(&saved);
            let parsed: Option<Vec<K>> = segments.iter().map(|s| K::from_key(s)).collect();
            if let Some(v) = parsed {
                path.write(v);
            }
        }

        // If we're built inside a page of an enclosing nav host that presents as a push stack
        // (mobile, `split == false`), merge: push our pages onto that host instead of minting a
        // second native container (one native nav chain, one back button; docs/navigation.md).
        // A split host (desktop) is not merged into; a stack keeps its own detail-pane stack.
        let merge = current_nav_host().filter(|c| !c.split.get());

        let entries: Rc<RefCell<Vec<StackEntry<K>>>> = Rc::default();
        let native_popped: Rc<Cell<usize>> = Rc::new(Cell::new(0));

        let host: RNode;
        let sizes: Rc<RefCell<std::collections::HashMap<RNode, Size>>>;
        let owners: Rc<RefCell<Vec<PopOwner>>>;
        let host_cx: NavHostCx;
        let ret_node: RNode;
        let merged: bool;
        if let Some(ctx) = merge {
            // Merged: reuse the enclosing host; our root renders inline in the current page (which
            // is already a NAV_PAGE), and only our pushed destinations become new pages.
            host = ctx.host;
            sizes = ctx.sizes.clone();
            owners = ctx.owners.clone();
            host_cx = ctx;
            let hc = host_cx.clone();
            ret_node = with_nav_host(Some(hc), || root.build(cx));
            // A merged stack has no chrome of its own: its root renders inside the enclosing
            // host's page, and that page's bar is the one the user sees. Its items go there,
            // where they used to be dropped with a debug warning.
            for source in toolbar {
                crate::contribute(day_core::current_chrome(), source);
            }
            merged = true;
        } else {
            // Standalone: create the native host + root page (an app-root stack, or a nested stack
            // under a split/desktop host).
            sizes = Rc::default();
            host = cx.native(
                kinds::NAV,
                &NavProps {
                    documents: None,
                    // A stack is a stack at every size: it has no sidebar pane to re-home, so
                    // there is nothing for a size-class change to re-present.
                    title: title_s.clone(),
                    presentation: NavPresentation::Stack,
                    // Never adaptive: the `nav_stack()` piece is a push/pop surface at every size, so
                    // an Emulated toolkit must build a plain navigation container for it rather
                    // than its adaptive one (docs/size-classes.md).
                    adaptive: false,
                    // A stack has no sidebar pane, so nothing to toggle.
                    sidebar_toggle: false,
                    // Stacks are not searchable yet: `.searchable()` is on `Nav` only
                    // (docs/search.md); a stack gains the same surface when the placement
                    // resolver lands, since it is the same lowering.
                    search: None,
                    // A content list is a nav shape; a stack has no sidebar to sit beside.
                    list_width: None,
                    // A stack never has a content-list pane, so this says nothing.
                    list_visible: true,
                },
                Rc::new(NavLayout::stack(sizes.clone())),
                Flex {
                    grow_w: true,
                    grow_h: true,
                    ..Default::default()
                },
                Boundary::Yes,
            );
            owners = Rc::default();
            host_cx = NavHostCx {
                host,
                sizes: sizes.clone(),
                owners: owners.clone(),
                split: Rc::new(Cell::new(false)),
                guards: Rc::default(),
            };
            let root_page = nav_page(
                host,
                &NavPageProps {
                    title: title_s,
                    pane: Pane::Detail,
                },
                &sizes,
            );
            let hc = host_cx.clone();
            with_nav_host(Some(hc), || {
                day_core::with_page_gated(
                    root_page,
                    gate(0),
                    day_spec::ToolbarColumn::Detail,
                    || {
                        let mut pcx = BuildCx::new(root_page);
                        let _ = root.build(&mut pcx);
                    },
                );
            });
            // A standalone stack's items ride its root page's chrome: the commands that act
            // on what the root shows, and that a pushed page covers along with it.
            for source in toolbar {
                crate::contribute(day_core::Chrome::Page(root_page), source);
            }
            ret_node = host;
            merged = false;
        }

        let nav_scope = Scope::current();

        // The raw pop: drop the top path segment (reconcile then pops the native page). The
        // guard's `BackRequest::proceed` runs exactly this.
        let raw_pop: Rc<dyn Fn()> = {
            let p = path.clone();
            Rc::new(move || {
                let mut v = p.peek();
                if v.pop().is_some() {
                    p.write(v);
                }
            })
        };
        let depth = {
            let p = path.clone();
            move || p.peek().len()
        };
        // One back-like event (native gesture that Day owns, or `nav_back()`): consult the guard
        // if one is armed and we're above the root, else pop. `Proceed` pops now; `Handled`
        // consumes it (the app holds the `BackRequest`). Programmatic `path.set` never lands here.
        let run_back: Rc<dyn Fn()> = {
            let (raw_pop, depth, guard) = (raw_pop.clone(), depth.clone(), on_back.clone());
            Rc::new(move || {
                if depth() == 0 {
                    return; // at root: nothing of ours to pop
                }
                match &guard {
                    Some(g) => {
                        let req = BackRequest {
                            pop: raw_pop.clone(),
                        };
                        if g(req) == BackResponse::Proceed {
                            raw_pop();
                        }
                    }
                    None => raw_pop(),
                }
            })
        };

        // This stack's back owner (one Rc shared by all its pages): a native pop the toolkit
        // Already performed (an unguarded iOS swipe) is absorbed + synced without the guard; a
        // back Day owns runs `run_back` so the guard decides.
        let stack_owner: PopOwner = {
            let (native_popped, raw_pop, run_back) =
                (native_popped.clone(), raw_pop.clone(), run_back.clone());
            Rc::new(move |already_popped: bool| {
                if already_popped {
                    native_popped.set(native_popped.get() + 1);
                    raw_pop();
                } else {
                    run_back();
                }
            })
        };

        // Reconcile the native stack to `want`: keep the common prefix, pop the rest, push
        // the new suffix. A pop the native already performed (iOS back) is not re-issued. Pages
        // and owners land on `host` (our own, or the enclosing one when merged).
        // `true` while this stack holds a guard vote on its host (`NavHostCx::vote_guard`), so the
        // vote moves only on a real transition (arming/disarming native gesture handling is not
        // free on every pop), and a merged stack shares the count with the host's other voters.
        let guard_armed_sent = Rc::new(Cell::new(false));
        let has_guard = on_back.is_some();
        let reconcile = {
            let (entries, sizes, dest, native_popped, owners, host_cx, stack_owner) = (
                entries.clone(),
                sizes.clone(),
                dest.clone(),
                native_popped.clone(),
                owners.clone(),
                host_cx.clone(),
                stack_owner.clone(),
            );
            let guard_armed_sent = guard_armed_sent.clone();
            move |want: &Vec<K>| {
                let common = {
                    let ents = entries.borrow();
                    let mut i = 0;
                    while i < ents.len() && i < want.len() && ents[i].key == want[i] {
                        i += 1;
                    }
                    i
                };
                while entries.borrow().len() > common {
                    let e = entries.borrow_mut().pop().unwrap();
                    if native_popped.get() > 0 {
                        native_popped.set(native_popped.get() - 1);
                    } else {
                        with_tree(|t| t.patch(host, Box::new(NavPatch::Popped), false));
                    }
                    e.scope.dispose();
                    sizes.borrow_mut().remove(&e.page);
                    with_tree(|t| t.remove_subtree(e.page));
                    owners.borrow_mut().pop();
                }
                for (at, key) in want.iter().enumerate().skip(common) {
                    let title = key.title();
                    let page = nav_page(
                        host,
                        &NavPageProps {
                            title: title.clone(),
                            pane: Pane::Detail,
                        },
                        &sizes,
                    );
                    let scope = nav_scope.enter(Scope::child);
                    let hc = host_cx.clone();
                    scope.enter(|| {
                        // Inside the page's scope; see the pushed-detail site above.
                        let content = (dest)(key);
                        with_nav_host(Some(hc), || {
                            day_core::with_page_gated(
                                page,
                                gate(at + 1),
                                day_spec::ToolbarColumn::Detail,
                                || {
                                    let mut c = BuildCx::new(page);
                                    let _ = content.build(&mut c);
                                },
                            );
                        });
                    });
                    with_tree(|t| {
                        // NavStack destinations are standard chrome in v1; the immersive flag is a
                        // nav-item concept today (docs/navigation.md).
                        t.patch(
                            host,
                            Box::new(NavPatch::Pushed {
                                title,
                                immersive: false,
                            }),
                            false,
                        )
                    });
                    owners.borrow_mut().push(stack_owner.clone());
                    entries.borrow_mut().push(StackEntry {
                        key: key.clone(),
                        scope,
                        page,
                    });
                }
                shown_depth.set(want.len());
                // Arm/disarm native gesture handling when the guarded-above-root state changes
                // (docs/navigation.md). The host is our own container, or the enclosing one when
                // merged; either way the native nav that owns the back gesture.
                if has_guard {
                    let armed = !entries.borrow().is_empty();
                    if armed != guard_armed_sent.get() {
                        guard_armed_sent.set(armed);
                        host_cx.vote_guard(armed);
                    }
                }
                with_tree(|t| {
                    t.mark_layout_dirty();
                    t.layout_if_needed();
                });
            }
        };
        {
            let p = path.clone();
            bind(move || p.read(), move |want: &Vec<K>| reconcile(want));
        }

        // Route identity may stay the same while asynchronously loaded metadata changes
        // its title. Track that title independently of path equality; do not rebuild the
        // page or let an enclosing merged stack rename a deeper stack's current page.
        {
            let p = path.clone();
            let owners = owners.clone();
            let stack_owner = stack_owner.clone();
            bind(
                move || p.read().last().map(Route::title),
                move |title: &Option<String>| {
                    if let Some(title) = title
                        && owners
                            .borrow()
                            .last()
                            .is_some_and(|owner| Rc::ptr_eq(owner, &stack_owner))
                    {
                        with_tree(|t| {
                            t.patch(host, Box::new(NavPatch::Title(title.clone())), false)
                        });
                    }
                },
            );
        }

        // A live root title (a localized string re-resolving on locale change, docs/
        // localization.md): the host's bar follows while the stack shows its root, and again
        // when a pop returns there, since a pushed page's bar is its own (the binding above).
        // A merged stack's root sits inside the enclosing host's page, whose bar is that page's.
        if !merged && let TextSource::Dyn(_) = &title {
            let (p, src) = (path.clone(), title.clone());
            bind_seeded(
                (src.initial(), true),
                move || (src.resolve(), p.read().is_empty()),
                move |(t, at_root): &(String, bool)| {
                    if *at_root {
                        with_tree(|tr| tr.patch(host, Box::new(NavPatch::Title(t.clone())), false));
                    }
                },
            );
        }

        // Persist the path across launches when `.restore` is set: save the keys in the same
        // percent-encoded wire format `parse_route` reads back (`encode_route`), so a key
        // containing `/` survives the round-trip (docs/navigation.md). Scope-owned, so it stops
        // with the stack.
        if let Some(key) = restore {
            let p = path.clone();
            bind(
                move || {
                    let keys: Vec<String> = p.read().iter().map(|k| k.key()).collect();
                    day_core::encode_route(&keys, &[])
                },
                move |s: &String| day_core::nav_store_save(&key, s),
            );
        }

        // Standalone: own the host's single NavBack dispatcher (→ topmost page's owner) and the
        // deeplink handler. Merged: the enclosing host's creator already owns both.
        if !merged {
            let owners_h = owners.clone();
            cx.on(host, move |ev| match ev {
                Event::NavBack { already_popped } => {
                    let top = owners_h.borrow().last().cloned();
                    if let Some(f) = top {
                        f(*already_popped);
                    }
                }
                Event::RouteRequested(route) => {
                    let _ = day_core::navigate(route);
                }
                _ => {}
            });
        }

        // Merged: our pages live on the enclosing host, so the enclosing detail's
        // `remove_subtree` won't reach them; pop every remaining page (top-down) off that host
        // when our scope disposes (e.g. the section switches). Guarded for app teardown.
        if merged {
            let (entries_c, sizes_c, owners_c, native_popped_c) = (
                entries.clone(),
                sizes.clone(),
                owners.clone(),
                native_popped.clone(),
            );
            let (guard_c, host_cx_c) = (guard_armed_sent.clone(), host_cx.clone());
            nav_scope.on_cleanup(move || {
                let alive = with_tree(|t| t.node_kind(host).is_some());
                // A vote this stack still holds would keep the enclosing host routing every back
                // through Day after the stack is gone.
                if alive && guard_c.replace(false) {
                    host_cx_c.vote_guard(false);
                }
                loop {
                    let e = entries_c.borrow_mut().pop();
                    let Some(e) = e else { break };
                    if alive {
                        if native_popped_c.get() > 0 {
                            native_popped_c.set(native_popped_c.get() - 1);
                        } else {
                            with_tree(|t| t.patch(host, Box::new(NavPatch::Popped), false));
                        }
                        sizes_c.borrow_mut().remove(&e.page);
                        with_tree(|t| t.remove_subtree(e.page));
                        owners_c.borrow_mut().pop();
                    }
                }
                if alive {
                    with_tree(|t| {
                        t.mark_layout_dirty();
                        t.layout_if_needed();
                    });
                }
            });
        }

        // string-route adapter. A stack is driven by its `path` (app state / buttons), not by
        // magic navigate-strings: a relative `navigate("<key>")` claims only "" (pop to root),
        // so sibling keys fall through to the enclosing surface, but an absolute path's
        // segments (`enter`) push any segment the key type parses: a `String` stack is
        // open-ended, a typed stack validates via `Route::from_key`, and an explicit `a/b/c`
        // path is the stack's state. `pop` falls through once empty.
        let p_push = path.clone();
        let p_cur = path.clone();
        let p_enter = path.clone();
        let p_seg = path.clone();
        register_route_surface(
            move |k| {
                if k.is_empty() {
                    let mut v = p_push.peek();
                    if v.is_empty() {
                        return false; // already at root; let the parent handle ""
                    }
                    v.clear();
                    p_push.write(v);
                    true
                } else {
                    false
                }
            },
            {
                // `nav_back()` is a back-like event, so it is guarded too (docs/navigation.md):
                // run_back consults the guard. We "own" the back (return true, no fall-through)
                // whenever we're above the root, whether the guard pops or consumes.
                let (run_back, depth) = (run_back.clone(), depth.clone());
                move |_| {
                    if depth() == 0 {
                        return false; // at root; let the parent handle back
                    }
                    run_back();
                    true
                }
            },
            move || p_cur.peek().last().map(|k| k.key()).unwrap_or_default(),
            move |k| {
                let Some(parsed) = K::from_key(k) else {
                    return false; // not one of this stack's routes; leave it queued
                };
                let mut v = p_enter.peek();
                v.push(parsed);
                p_enter.write(v);
                true
            },
            move || p_seg.peek().iter().map(|k| k.key()).collect(),
        );
        ret_node
    }
}

// ===========================================================================
// Cover: a fullscreen modal surface bound to a Signal<Option<Route>> (docs/cover.md).
// ===========================================================================

/// A fullscreen cover: the modal counterpart of [`nav_stack`], bound to a `Signal<Option<R>>`.
/// `Some(r)` presents the built content over the whole window (edge-to-edge, slide-up where
/// the platform animates modals); `None` dismisses it. The SwiftUI analogue is
/// `fullScreenCover(item:)`. Build one with [`cover`].
///
/// The open value is app state, exactly like a stack's path: set it and the cover presents;
/// a native dismissal (Android system back) writes `None` back, unless an
/// [`interactive_dismiss_disabled`](Decorate::interactive_dismiss_disabled) subtree is
/// mounted inside the content, in which case only programmatic writes close it.
/// A cover's per-route surface color (see [`Cover::background`]).
type CoverBackground<R> = Rc<dyn Fn(&R) -> day_spec::Color>;

pub struct Cover<S, R: Route> {
    sheet: bool,
    half: bool,
    open: S,
    build: Rc<dyn Fn(&R) -> AnyPiece>,
    background: Option<CoverBackground<R>>,
    routed: bool,
    _marker: std::marker::PhantomData<R>,
}

/// A fullscreen cover over `open`: `Some(r)` presents `build(&r)`, `None` dismisses
/// (docs/cover.md). Registers a string-route adapter, so `navigate("<key>")` opens it and
/// `nav_back()` closes it, and `current_route()` reports the presented key.
pub fn cover<R: Route, S: Binding<Option<R>>, P: Piece>(
    open: S,
    build: impl Fn(&R) -> P + 'static,
) -> Cover<S, R> {
    Cover {
        sheet: false,
        half: false,
        open,
        // The stored builder is erased because a `Cover` holds one closure for every route it
        // presents; the parameter stays generic so callers never write `.any()` for us.
        build: Rc::new(move |r| AnyPiece::new(build(r))),
        background: None,
        routed: true,
        _marker: std::marker::PhantomData,
    }
}

#[day_macros::builder(CoverBuilder<R>)]
impl<S: Binding<Option<R>>, R: Route> Cover<S, R> {
    /// Prefer a native modal sheet. Backends without sheets retain their modal cover.
    pub fn sheet(mut self) -> Self {
        self.sheet = true;
        self
    }

    /// Present as a half-height sheet rising from the bottom edge, the window content above
    /// it staying on show: an inspector over the canvas it describes, a transport over the
    /// media it controls (docs/cover.md "Half sheet"). iOS presents a medium-detent sheet that
    /// leaves the content interactive, Android a Material bottom sheet, the web, HarmonyOS and
    /// the emulated desktop tiers a bottom-anchored half panel, and macOS its window sheet at
    /// half the window's height. Implies [`Cover::sheet`].
    pub fn half_sheet(mut self) -> Self {
        self.sheet = true;
        self.half = true;
        self
    }

    /// The surface color painted edge-to-edge behind the content (under the status bar and
    /// home indicator) while `r` is presented. Without it the platform's default surface
    /// color shows in the unsafe areas.
    pub fn background(mut self, f: impl Fn(&R) -> day_spec::Color + 'static) -> Self {
        self.background = Some(Rc::new(f));
        self
    }

    /// Keep this cover out of the app's route space: `navigate("<key>")` never presents it, it
    /// contributes nothing to `current_route()`, and `nav_back()` walks past it.
    ///
    /// For a cover that is a **control's own panel** rather than an app destination (a color
    /// picker's chooser, a media scrubber's fullscreen mode), presented and dismissed by the
    /// control, never linked to. Two reasons that matters:
    ///
    /// - **A routed cover claims route segments**, and over the untyped `Route` (`String`,
    ///   whose `from_key` accepts anything) it claims *every* segment: mount one and the next
    ///   `navigate("settings")` presents the cover with the key `"settings"` instead of going to
    ///   settings. A piece that mounts a cover would be silently rewriting its host app's
    ///   navigation.
    /// - **It is not a place.** `current_route()` naming a transient chooser makes a restored
    ///   session reopen it, and a "share this screen" link point at a modal.
    ///
    /// Interactive dismissal is unaffected: the cover still answers Android's system back through
    /// [`Event::NavBack`](day_spec::Event::NavBack) on its own node, which never went through the
    /// route adapter.
    pub fn unrouted(mut self) -> Self {
        self.routed = false;
        self
    }
}

impl<S: Binding<Option<R>>, R: Route> Piece for Cover<S, R> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        use day_spec::props::{CoverPatch, CoverProps};
        let Cover {
            sheet,
            half,
            open,
            build,
            background,
            routed,
            ..
        } = self;
        // A `.sheet()` on a toolkit with no native sheet is composed here: a card over the
        // dimmed page, on the transparent cover (docs/cover.md "Modal sheet"). The window is
        // the one being built, whose size class decides at each presentation.
        let composed_sheet = sheet
            && !half
            && day_core::capability(day_spec::Cap::CoverSheet) == day_spec::Support::Unsupported;
        let window = day_core::window_being_built();

        let size: Rc<RefCell<Option<Size>>> = Rc::default();
        let node = cx.native(
            kinds::COVER,
            &CoverProps { sheet, half },
            Rc::new(day_core::CoverLayout { size: size.clone() }),
            Flex::default(),
            Boundary::Yes,
        );

        // The presented content's scope, and whether a dismiss transition is in flight
        // (content stays mounted until the backend reports `CoverHidden`, so the surface
        // isn't blank while it slides out).
        struct Presented<R> {
            key: R,
            scope: Scope,
        }
        let current: Rc<RefCell<Option<Presented<R>>>> = Rc::default();
        let closing: Rc<Cell<bool>> = Rc::default();
        let owner_scope = Scope::current();
        let layer = NavLayer {
            order: Rc::new(Cell::new(0)),
            depth: owner_scope.use_context::<NavLayer>().map_or(0, |l| l.depth),
        };

        let dispose_content = {
            let current = current.clone();
            move || {
                let presented = current.borrow_mut().take();
                // Detaching focused native inputs can enqueue their final value
                // or blur events. Remove their handlers before disposing signals
                // captured by those handlers, then release the content scope.
                while with_tree(|t| t.child_count(node)) > 0 {
                    match with_tree(|t| t.first_child(node)) {
                        Some(c) => with_tree(|t| t.remove_subtree(c)),
                        None => break,
                    }
                }
                if let Some(p) = presented {
                    p.scope.dispose();
                }
            }
        };

        // Reconcile the presented surface to the signal.
        let reconcile = {
            let (current, closing, dispose_content) =
                (current.clone(), closing.clone(), dispose_content.clone());
            let layer = layer.clone();
            move |want: &Option<R>| match want {
                Some(r) => {
                    let already =
                        !closing.get() && current.borrow().as_ref().is_some_and(|p| p.key == *r);
                    if already {
                        return;
                    }
                    dispose_content();
                    closing.set(false);
                    layer.order.set(NEXT_COVER_LAYER.with(|next| {
                        let order = next.get();
                        next.set(order + 1);
                        order
                    }));
                    let scope = owner_scope.enter(Scope::child);
                    scope.provide(NavLayer {
                        order: layer.order.clone(),
                        depth: layer.depth + 1,
                    });
                    // Run the app's builder inside the presentation scope: side effects it
                    // performs eagerly (state restore, autosave/cleanup registration, signals)
                    // must belong to the presented content's lifetime, not the cover's.
                    // A compact window keeps the full-window cover: a card there would leave a
                    // sliver of dimmed page around it.
                    let card = composed_sheet
                        && !day_core::window_size_class_untracked(window)
                            .is_some_and(|c| c.width == day_spec::WidthClass::Compact);
                    scope.enter(|| {
                        let content = (build)(r);
                        let mut c = BuildCx::new(node);
                        if card {
                            let _ = day_core::ComposedSheet { content }.build(&mut c);
                        } else {
                            let _ = content.build(&mut c);
                        }
                    });
                    *current.borrow_mut() = Some(Presented {
                        key: r.clone(),
                        scope,
                    });
                    // Content is mounted, so any `interactive_dismiss_disabled` inside it has
                    // registered, so the present patch carries the resolved flag.
                    // The composed sheet paints its own card and dimmed page; the cover under
                    // them is clear, so the page shows through.
                    let bg = if card {
                        Some(day_spec::Color::CLEAR)
                    } else {
                        background.as_ref().map(|f| f(r))
                    };
                    with_tree(|t| {
                        t.patch(
                            node,
                            Box::new(CoverPatch::Present {
                                background: bg,
                                dismiss_disabled: day_core::shield::dismiss_disabled(),
                            }),
                            false,
                        );
                        t.mark_needs_measure(node);
                        t.mark_layout_dirty();
                        t.layout_if_needed();
                    });
                }
                None => {
                    layer.order.set(0);
                    if current.borrow().is_some() && !closing.get() {
                        closing.set(true);
                        with_tree(|t| t.patch(node, Box::new(CoverPatch::Dismiss), false));
                    }
                }
            }
        };
        {
            let o = open.clone();
            bind(move || o.read(), move |want: &Option<R>| reconcile(want));
        }

        // While presented, keep the backend's dismiss-disabled flag in sync with the
        // mounted `interactive_dismiss_disabled` modifiers (the shield's change counter
        // makes this binding re-run as they mount/unmount).
        {
            let current = current.clone();
            bind(
                day_core::shield::dismiss_disabled,
                move |disabled: &bool| {
                    if current.borrow().is_some() {
                        with_tree(|t| {
                            t.patch(
                                node,
                                Box::new(CoverPatch::DismissDisabled(*disabled)),
                                false,
                            )
                        });
                    }
                },
            );
        }

        {
            let (o, size, closing, dispose_content) = (
                open.clone(),
                size.clone(),
                closing.clone(),
                dispose_content.clone(),
            );
            cx.on(node, move |ev| match ev {
                // The backend sized the presented content container (safe-area bounds).
                Event::FrameChanged(sz) => {
                    if *size.borrow() != Some(*sz) {
                        *size.borrow_mut() = Some(*sz);
                        with_tree(|t| {
                            t.mark_needs_measure(node);
                            t.mark_layout_dirty();
                            t.layout_if_needed();
                        });
                    }
                }
                // Native dismissal request (Android system back). Honored unless an
                // `interactive_dismiss_disabled` subtree is mounted.
                Event::NavBack { .. } => {
                    if !day_core::shield::dismiss_disabled() && o.peek().is_some() {
                        o.write(None);
                    }
                }
                // The hide transition finished; now the content can go.
                // Idempotent + orderable (docs/cover.md): duplicates and belated reports
                // from a previous dismissal are no-ops via the closing gate.
                Event::CoverHidden if closing.get() => {
                    closing.set(false);
                    dispose_content();
                }
                _ => {}
            });
        }

        // String-route adapter (docs/navigation.md): `navigate("<key>")` presents, `nav_back()`
        // dismisses, and the presented key is this surface's `current_route()` contribution.
        // Skipped for an `unrouted()` cover, which is a control's own panel rather than a place
        // the app navigates to; see `Cover::unrouted` for why that distinction matters.
        if !routed {
            return node;
        }
        let o_push = open.clone();
        let o_pop = open.clone();
        let o_cur = open.clone();
        let o_enter = open.clone();
        let o_seg = open;
        let push = move |k: &str, sig: &S| match R::from_key(k) {
            Some(r) => {
                sig.write(Some(r));
                true
            }
            None => false,
        };
        let push2 = push;
        register_route_surface_in_layer(
            layer,
            move |k| push(k, &o_push),
            move |_| {
                if o_pop.peek().is_some() {
                    o_pop.write(None);
                    true
                } else {
                    false
                }
            },
            move || o_cur.peek().map(|r| r.key()).unwrap_or_default(),
            move |k| push2(k, &o_enter),
            move || o_seg.peek().map(|r| vec![r.key()]).unwrap_or_default(),
        );

        node
    }
}

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

#[cfg(feature = "conformance")]
pub(crate) mod conformance {
    use day_core::Piece;
    use std::rc::Rc;

    use day_core::conformance::{Case, Drive};
    use day_core::{Boundary, Flex, RNode, piece_fn};
    use day_reactive::Signal;
    use day_spec::props::NavPresentation;
    use day_spec::{Cap, Size, kinds};

    use crate::*;

    /// A stack whose root pushes `detail` and whose pages show their key.
    fn stack(path: Signal<Vec<String>>) -> impl Piece {
        nav_stack(
            path,
            column((
                label(move || format!("depth {}", path.get().len())).id(day_core::id!(depth)),
                button("Open")
                    .action(move || path.update(|p| p.push("detail".into())))
                    .id(day_core::id!(open)),
            )),
        )
        .title("Root")
        .destination(|key: &String| {
            label(format!("Page {key}")).id(day_core::id!(page, key.to_owned()))
        })
    }

    /// Pushing a page shows it; going back pops it and writes the pop into the path.
    #[day_macros::test(day_core)]
    fn nav_stack_push_pop() -> Case {
        Case::new()
            .proves(kinds::NAV)
            .proves(kinds::NAV_PAGE)
            .page(|| stack(Signal::new(Vec::new())))
            .drive(|d: Drive| async move {
                d.assert_text("depth", "depth 0").await?;
                d.tap("open").await?;
                d.assert_text("page:detail", "Page detail").await?;
                d.wait_idle().await?;
                d.nav_back().await?;
                d.assert_missing("page:detail").await?;
                d.assert_text("depth", "depth 0").await
            })
    }

    /// The stack follows its path: two keys push two pages, and back returns through them.
    #[day_macros::test(day_core)]
    fn nav_stack_follows_path() -> Case {
        Case::new()
            .proves(kinds::NAV)
            .page(|| stack(Signal::new(vec!["first".into(), "second".into()])))
            .drive(|d: Drive| async move {
                d.assert_text("page:second", "Page second").await?;
                d.wait_idle().await?;
                d.nav_back().await?;
                d.assert_missing("page:second").await?;
                d.assert_text("page:first", "Page first").await?;
                d.wait_idle().await?;
                d.nav_back().await?;
                d.assert_missing("page:first").await?;
                d.assert_text("depth", "depth 0").await
            })
    }

    /// A sidebar's items each show their page when selected, as a route.
    #[day_macros::test(day_core)]
    fn nav_sidebar_selects() -> Case {
        Case::new()
            .proves(kinds::NAV)
            .proves(kinds::NAV_MENU)
            .page(|| {
                nav(Signal::new("alpha".to_string()))
                    .item("alpha", "Alpha", || {
                        label("Page Alpha").id(day_core::id!(page_alpha))
                    })
                    .item("beta", "Beta", || {
                        label("Page Beta").id(day_core::id!(page_beta))
                    })
            })
            .drive(|d: Drive| async move {
                d.navigate("beta").await?;
                d.assert_text("page_beta", "Page Beta").await?;
                d.assert_route("beta").await?;
                d.wait_idle().await?;
                d.navigate("alpha").await?;
                d.assert_text("page_alpha", "Page Alpha").await
            })
    }

    /// Tabs show the selected tab's page and switch on a route.
    #[day_macros::test(day_core)]
    fn nav_tabs_switch() -> Case {
        Case::new()
            .proves(kinds::NAV)
            .page(|| {
                nav(Signal::new("alpha".to_string()))
                    .presentation(NavPresentation::Tabs)
                    .item("alpha", "Alpha", || {
                        label("Tab Alpha").id(day_core::id!(tab_alpha))
                    })
                    .item("beta", "Beta", || {
                        label("Tab Beta").id(day_core::id!(tab_beta))
                    })
            })
            .drive(|d: Drive| async move {
                d.assert_text("tab_alpha", "Tab Alpha").await?;
                d.navigate("beta").await?;
                d.assert_text("tab_beta", "Tab Beta").await?;
                d.assert_route("beta").await
            })
    }

    /// The page under a cover: a button that opens it and the open value as text.
    fn covered(open: Signal<Option<String>>, sheet: bool) -> impl Piece {
        let c = cover(open, move |key: &String| {
            column((
                label(format!("Cover {key}")).id(day_core::id!(cover_text)),
                button("Close")
                    .action(move || open.set(None))
                    .id(day_core::id!(close)),
            ))
        });
        column((
            label(move || format!("open {}", open.get().unwrap_or_default()))
                .id(day_core::id!(state)),
            button("Show")
                .action(move || open.set(Some("panel".into())))
                .id(day_core::id!(show)),
            if sheet { c.sheet().any() } else { c.any() },
        ))
    }

    /// Setting the open value presents the cover; clearing it dismisses it.
    #[day_macros::test(day_core)]
    fn cover_presents_and_dismisses() -> Case {
        Case::new()
            .proves_cap(Cap::Cover)
            .proves(kinds::COVER)
            .page(|| covered(Signal::new(None), false))
            .drive(|d: Drive| async move {
                d.assert_missing("cover_text").await?;
                d.tap("show").await?;
                d.assert_text("cover_text", "Cover panel").await?;
                d.wait_idle().await?;
                d.tap("close").await?;
                d.assert_missing("cover_text").await?;
                d.assert_text("state", "open ").await
            })
    }

    /// A sheet presents the same way, and going back dismisses it and writes `None` back.
    #[day_macros::test(day_core)]
    fn cover_sheet_back_dismisses() -> Case {
        Case::new()
            .proves(kinds::COVER)
            .page(|| covered(Signal::new(None), true))
            .drive(|d: Drive| async move {
                d.tap("show").await?;
                d.assert_text("cover_text", "Cover panel").await?;
                d.assert_text("state", "open panel").await?;
                d.wait_idle().await?;
                d.nav_back().await?;
                d.assert_missing("cover_text").await?;
                d.assert_text("state", "open ").await
            })
    }

    /// A layout that answers the proposal and remembers the height it was placed at: how a
    /// case measures a surface on every toolkit, the mock included, without a number that
    /// would only hold for one window size.
    pub(crate) struct HeightProbe(pub(crate) Rc<std::cell::Cell<f64>>);

    impl day_core::Layout for HeightProbe {
        fn measure(
            &self,
            _cx: &mut dyn day_core::LayoutOps,
            _children: &[RNode],
            p: day_geometry::Proposal,
        ) -> Size {
            Size::new(p.width.unwrap_or(0.0), p.height.unwrap_or(0.0))
        }
        fn place(
            &self,
            _cx: &mut dyn day_core::LayoutOps,
            _children: &[RNode],
            bounds: day_geometry::Rect,
        ) {
            self.0.set(bounds.size.height);
        }
    }

    /// A growable piece that records the height it is laid out at into `into`.
    pub(crate) fn height_probe(into: Rc<std::cell::Cell<f64>>) -> impl Piece {
        piece_fn(move |cx| {
            cx.layout_only(
                Rc::new(HeightProbe(into)),
                Flex {
                    grow_w: true,
                    grow_h: true,
                    ..Default::default()
                },
                Boundary::No,
            )
        })
    }

    // The heights the half-sheet cases compare: the page's, and the cover content's.
    thread_local! {
        static HALF_HEIGHTS: (Rc<std::cell::Cell<f64>>, Rc<std::cell::Cell<f64>>) =
            (Rc::default(), Rc::default());
    }

    /// The page under a half sheet: a probe filling the page, the open value as text, a
    /// button that opens the sheet, and the sheet with a probe filling its content.
    fn half_covered(open: Signal<Option<String>>) -> impl Piece {
        let (page_h, cover_h) = HALF_HEIGHTS.with(|h| (h.0.clone(), h.1.clone()));
        page_h.set(0.0);
        cover_h.set(0.0);
        let sheet = cover(open, move |key: &String| {
            column((
                label(format!("Cover {key}")).id(day_core::id!(cover_text)),
                height_probe(cover_h.clone()),
                button("Close")
                    .action(move || open.set(None))
                    .id(day_core::id!(close)),
            ))
        })
        .half_sheet();
        zstack((
            height_probe(page_h),
            column((
                label(move || format!("open {}", open.get().unwrap_or_default()))
                    .id(day_core::id!(state)),
                button("Show")
                    .action(move || open.set(Some("panel".into())))
                    .id(day_core::id!(show)),
                sheet,
            )),
        ))
    }

    /// Whether `probe_h` is a half sheet's content height against the page's `page_h`: at
    /// most a little over half (a grabber or handle rides inside the half), and well clear of
    /// zero.
    pub(crate) fn is_half(page_h: f64, probe_h: f64) -> bool {
        page_h > 0.0 && probe_h > page_h * 0.15 && probe_h <= page_h * 0.6
    }

    /// Wait for a presented sheet's content to be laid out, then judge it with [`is_half`].
    /// The frame a native sheet reports lands a turn after the presentation (and on the mock
    /// a flush later), so the probe is polled rather than read once.
    pub(crate) async fn check_half(
        d: &Drive,
        what: &str,
        heights: &(Rc<std::cell::Cell<f64>>, Rc<std::cell::Cell<f64>>),
    ) -> day_core::conformance::TestResult {
        let mut got = (0.0, 0.0);
        for _ in 0..40 {
            got = (heights.0.get(), heights.1.get());
            if is_half(got.0, got.1) {
                break;
            }
            d.pause(0.05).await?;
            d.wait_idle().await?;
        }
        d.check(
            is_half(got.0, got.1),
            &format!("{what} {} of page {}: between 15% and 60%", got.1, got.0),
        )
    }

    /// A half sheet presents over the page at (about) half its height, and the content
    /// underneath stays mounted; clearing the value dismisses it.
    #[day_macros::test(day_core)]
    fn cover_half_sheet_presents_over_content() -> Case {
        Case::new()
            .proves(kinds::COVER)
            .page(|| half_covered(Signal::new(None)))
            .drive(|d: Drive| async move {
                d.assert_missing("cover_text").await?;
                d.tap("show").await?;
                d.assert_text("cover_text", "Cover panel").await?;
                d.wait_idle().await?;
                let heights = HALF_HEIGHTS.with(|h| h.clone());
                check_half(&d, "half sheet content", &heights).await?;
                d.assert_text("state", "open panel").await?;
                d.tap("close").await?;
                d.assert_missing("cover_text").await?;
                d.assert_text("state", "open ").await
            })
    }

    /// Going back dismisses a half sheet and writes `None` back, as it does a sheet.
    #[day_macros::test(day_core)]
    fn cover_half_sheet_back_dismisses() -> Case {
        Case::new()
            .proves(kinds::COVER)
            .page(|| half_covered(Signal::new(None)))
            .drive(|d: Drive| async move {
                d.tap("show").await?;
                d.assert_text("cover_text", "Cover panel").await?;
                d.wait_idle().await?;
                d.nav_back().await?;
                d.assert_missing("cover_text").await?;
                d.assert_text("state", "open ").await
            })
    }

    // The heights the composed-sheet case compares: the page's, and the sheet content's.
    thread_local! {
        static SHEET_HEIGHTS: (Rc<std::cell::Cell<f64>>, Rc<std::cell::Cell<f64>>) =
            (Rc::default(), Rc::default());
    }

    /// On a toolkit with no native sheet, a `.sheet()` over a wide window is a card centered
    /// on the dimmed page: its content lays out shorter than the page, the page stays mounted,
    /// and the card's own controls dismiss it.
    #[day_macros::test(day_core)]
    fn cover_sheet_composes_a_card_on_wide() -> Case {
        Case::new()
            .proves(kinds::COVER)
            .requires_support("composed sheet", || {
                if day_core::capability(Cap::CoverSheet) == day_spec::Support::Unsupported {
                    day_spec::Support::Native
                } else {
                    day_spec::Support::Unsupported
                }
            })
            .page(|| {
                let (page_h, sheet_h) = SHEET_HEIGHTS.with(|h| (h.0.clone(), h.1.clone()));
                page_h.set(0.0);
                sheet_h.set(0.0);
                let open = Signal::new(None::<String>);
                let sheet = cover(open, move |key: &String| {
                    column((
                        label(format!("Cover {key}")).id(day_core::id!(cover_text)),
                        height_probe(sheet_h.clone()),
                        button("Close")
                            .action(move || open.set(None))
                            .id(day_core::id!(close)),
                    ))
                })
                .sheet()
                .unrouted();
                zstack((
                    height_probe(page_h),
                    column((
                        label(move || format!("open {}", open.get().unwrap_or_default()))
                            .id(day_core::id!(state)),
                        button("Show")
                            .action(move || open.set(Some("panel".into())))
                            .id(day_core::id!(show)),
                        sheet,
                    )),
                ))
            })
            .drive(|d: Drive| async move {
                let _restore = crate::inspector::conformance::RestoreSizeClass;
                day_core::override_size_class(day_spec::SizeClass {
                    width: day_spec::WidthClass::Expanded,
                    height: day_spec::HeightClass::Expanded,
                });
                d.wait_idle().await?;
                d.tap("show").await?;
                d.assert_text("cover_text", "Cover panel").await?;
                let heights = SHEET_HEIGHTS.with(|h| h.clone());
                let mut got = (0.0, 0.0);
                for _ in 0..40 {
                    got = (heights.0.get(), heights.1.get());
                    if got.0 > 0.0 && got.1 > 0.0 {
                        break;
                    }
                    d.pause(0.05).await?;
                    d.wait_idle().await?;
                }
                d.check(
                    got.0 > 0.0 && got.1 > 0.0 && got.1 < got.0,
                    &format!("sheet content {} under a page {} tall", got.1, got.0),
                )?;
                d.assert_text("state", "open panel").await?;
                d.tap("close").await?;
                d.assert_missing("cover_text").await?;
                d.assert_text("state", "open ").await
            })
    }
}