day-piece-settings 0.7.9

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

//! day-piece-settings: the settings and About surface every Day app shares (docs/settings.md).
//!
//! Three layers, all toolkit-neutral:
//!
//! - **Values.** [`Pref<T>`]: a typed, persisted, reactive setting declared once as a static.
//!   Reads are signals the app can watch; writes land in the [`Store`] (the platform's own
//!   preferences store through day-part-preferences unless the app installs another).
//! - **Declaration.** [`Preferences`] holds an [`About`] and the [`Group`]s of [`Section`]s of
//!   rows ([`rows::toggle`], [`rows::choice`], [`rows::slider`], [`rows::stepper`], [`rows::text`], [`rows::action`], [`rows::link`],
//!   [`rows::navigate`], [`rows::info`], [`rows::note`], [`rows::custom`]). Groups carry a localized title, an icon and
//!   a route id. Other crates contribute groups through a [`Provider`].
//! - **Presentation.** [`Preferences::install`] registers the Preferences window (desktop) or
//!   the navigation presentation (mobile: an About header, then the groups as a list that
//!   pushes one page per group), the About window, the Settings…/About/Check for Updates… menu
//!   items, and the `settings/<group>` string routes. The pieces are composed from ordinary Day
//!   pieces on every backend; a toolkit feature adds native rows and panels where the platform
//!   has a stronger idiom.
//!
//! ```ignore
//! // root(), after res::locales::install():
//! let prefs = day_piece_settings::Preferences::new()
//!     .about(About::from_manifest().link(res::str::about_website(), "https://daybrite.dev"))
//!     .group(day_piece_settings::general_group(res::locales::ALL))
//!     .install();
//! // … and in the nav, for the platforms with no menu bar:
//! nav(section)
//!     .items(prefs.nav_item(Section::Settings))
//!     .destination(move |_: &Section| prefs.page())
//! ```

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

use day_core::{AnyPiece, Piece};
use day_pieces::prelude::*;
use day_pieces::{Label, TextSource};
use day_reactive::{Signal, watch};
use day_spec::{Cap, Support};

day_pieces::glue_modules!(appkit, gtk, qt, uikit, material, arkui);

#[cfg(all(feature = "xaml", target_os = "windows"))]
#[path = "lib-xaml.rs"]
mod xaml_impl;

/// A `(tag, autonym)` locale table, the shape of a generated `res::locales::ALL`.
pub type LocaleTable = &'static [(&'static str, &'static str)];

/// What an app's `root()` and settings module import: the declaration types, the handle, the
/// row constructors as a module, and the General group.
pub mod prelude {
    pub use crate::{
        APPEARANCE, About, Appearance, Group, LANGUAGE, Pref, PrefValue, Preferences, Prefs,
        Presentation, Providers, Row, Section, appearance_row, general_group, language_row,
        pref_enum, rows,
    };
}

// ===========================================================================
// Values: Pref<T> over a Store
// ===========================================================================

pub use day_part_preferences::{
    MemoryStore, NativeStore, Pref, PrefValue, Store, install_store, persistence_failures,
    pref_enum,
};

day_core::tls_group! {
    /// The installed declaration, what the free functions ([`open`], [`open_at`]) reach.
    static INSTALLED: RefCell<Option<Rc<Installed>>> = const { RefCell::new(None) };
    /// Providers registered at run time ([`register_provider`]): the wasm path, and explicit
    /// registration anywhere.
    static RUNTIME_PROVIDERS: RefCell<Vec<&'static Provider>> = const { RefCell::new(Vec::new()) };
    /// Whether the General group's appearance/language watchers are installed (once per process).
    static GENERAL_WIRED: Cell<bool> = const { Cell::new(false) };
    /// The locale the app started in (system or `--locale`), captured before any stored
    /// override applies: what the language picker's "System" entry restores.
    static SYSTEM_LOCALE: std::cell::OnceCell<String> = const { std::cell::OnceCell::new() };
    /// Sub-page builders by title, what a pushed `page:<title>` route builds.
    static SUBPAGES: RefCell<HashMap<String, Build>> = RefCell::new(HashMap::new());
}

// ===========================================================================
// Declaration: Preferences, Group, Section, rows
// ===========================================================================

/// A group's icon: a bundled vector/image (`res::vectors::prefs_weather`) or a standard glyph.
#[derive(Clone, Debug, PartialEq)]
pub enum GroupIcon {
    Image(day_spec::ImageName),
    Symbol(day_spec::Symbol),
}

impl From<day_spec::Symbol> for GroupIcon {
    fn from(s: day_spec::Symbol) -> Self {
        GroupIcon::Symbol(s)
    }
}
impl From<day_spec::ImageName> for GroupIcon {
    fn from(n: day_spec::ImageName) -> Self {
        GroupIcon::Image(n)
    }
}
impl From<day_spec::VectorName> for GroupIcon {
    fn from(n: day_spec::VectorName) -> Self {
        GroupIcon::Image(n.into())
    }
}

type Build = Rc<dyn Fn() -> AnyPiece>;
type Avail = Rc<dyn Fn() -> bool>;

/// One group of settings (docs/settings.md): a page on desktop (a toolbar tab, a dialog page,
/// a sidebar entry) and a row of the mobile root list that pushes the page.
#[derive(Clone)]
#[must_use]
pub struct Group {
    id: &'static str,
    title: TextSource,
    subtitle: Option<TextSource>,
    icon: Option<GroupIcon>,
    sections: Vec<Section>,
    custom: Option<Build>,
    order: i32,
    available: Option<Avail>,
}

impl Group {
    /// A group with a route id (also its element id, `prefs-group-<id>`) and a localized title.
    pub fn new<M>(id: &'static str, title: impl IntoText<M>) -> Self {
        Group {
            id,
            title: title.into_text(),
            subtitle: None,
            icon: None,
            sections: Vec::new(),
            custom: None,
            order: 0,
            available: None,
        }
    }
    /// The glyph beside the title: a bundled vector (the same name a `nav` item takes) or a
    /// standard [`day_spec::Symbol`].
    pub fn icon(mut self, icon: impl Into<GroupIcon>) -> Self {
        self.icon = Some(icon.into());
        self
    }
    /// One line under the title in the mobile root list ("Units, data source").
    pub fn subtitle<M>(mut self, t: impl IntoText<M>) -> Self {
        self.subtitle = Some(t.into_text());
        self
    }
    /// Append a section.
    pub fn section(mut self, section: Section) -> Self {
        self.sections.push(section);
        self
    }
    /// Append a row to the group's trailing untitled section (created as needed).
    pub fn row(mut self, row: Row) -> Self {
        match self.sections.last_mut() {
            Some(s) if s.title.is_none() && s.footer.is_none() => s.rows.push(row),
            _ => self.sections.push(Section::new().row(row)),
        }
        self
    }
    /// A bespoke piece that is the whole group page (Skies' city editor). Sections, if any,
    /// render above it.
    pub fn custom<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
        self.custom = Some(Rc::new(move || AnyPiece::new(build())));
        self
    }
    /// Sort key: app groups keep declaration order at 0, providers default to 500, About is
    /// always last.
    pub fn order(mut self, order: i32) -> Self {
        self.order = order;
        self
    }
    /// Hide the whole group when false (evaluated at install and at each build).
    pub fn available(mut self, f: impl Fn() -> bool + 'static) -> Self {
        self.available = Some(Rc::new(f));
        self
    }
    /// Hide the group unless the toolkit supports `cap`.
    pub fn requires(self, cap: Cap) -> Self {
        self.available(move || day_core::capability(cap) != Support::Unsupported)
    }
    /// The route id.
    #[must_use]
    pub fn id(&self) -> &'static str {
        self.id
    }
    fn is_available(&self) -> bool {
        self.available.as_ref().is_none_or(|f| f())
    }
}

/// A titled card of rows inside a group.
#[derive(Clone, Default)]
#[must_use]
pub struct Section {
    title: Option<TextSource>,
    footer: Option<TextSource>,
    rows: Vec<Row>,
}

impl Section {
    pub fn new() -> Self {
        Section::default()
    }
    /// The header above the card.
    pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
        self.title = Some(t.into_text());
        self
    }
    /// The footnote under the card.
    pub fn footer<M>(mut self, t: impl IntoText<M>) -> Self {
        self.footer = Some(t.into_text());
        self
    }
    pub fn row(mut self, row: Row) -> Self {
        self.rows.push(row);
        self
    }
    pub fn rows(mut self, rows: impl IntoIterator<Item = Row>) -> Self {
        self.rows.extend(rows);
        self
    }
}

/// How a [`rows::choice`] row presents its options.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum ChoiceStyle {
    /// A menu/combo (the default): any number of options.
    #[default]
    Menu,
    /// A segmented control: for a few short labels (Light / Dark / System).
    Segmented,
}

#[derive(Clone)]
enum RowKind {
    Toggle(Signal<bool>),
    Choice {
        labels: Vec<TextSource>,
        index: Signal<usize>,
        style: ChoiceStyle,
    },
    Slider {
        value: Signal<f64>,
        range: std::ops::RangeInclusive<f64>,
        step: Option<f64>,
        value_text: Option<Rc<dyn Fn(f64) -> String>>,
    },
    Stepper {
        value: Signal<f64>,
        range: std::ops::RangeInclusive<f64>,
        step: f64,
    },
    Text {
        value: Signal<String>,
        placeholder: Option<TextSource>,
        secure: bool,
    },
    Action {
        on: Rc<dyn Fn()>,
        destructive: bool,
        confirm: Option<TextSource>,
        confirm_label: Option<TextSource>,
        busy: Option<Reactive<bool>>,
    },
    Link(String),
    Navigate(Build),
    Info {
        value: TextSource,
        copyable: bool,
    },
    Note,
    Custom(Build),
}

/// One row of a section (docs/settings.md), built by the row constructors.
#[derive(Clone)]
#[must_use]
pub struct Row {
    title: TextSource,
    caption: Option<TextSource>,
    id: Option<day_core::ElementId>,
    enabled: Option<Reactive<bool>>,
    available: Option<Avail>,
    kind: RowKind,
}

impl Row {
    fn new<M>(title: impl IntoText<M>, kind: RowKind) -> Self {
        Row {
            title: title.into_text(),
            caption: None,
            id: None,
            enabled: None,
            available: None,
            kind,
        }
    }
    /// The row's title (every row constructor takes one, this replaces it).
    pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
        self.title = t.into_text();
        self
    }
    /// A secondary line under the title.
    pub fn caption<M>(mut self, t: impl IntoText<M>) -> Self {
        self.caption = Some(t.into_text());
        self
    }
    /// The element id of the row's control (default `pref-<key>` for a pref row).
    pub fn id(mut self, id: day_core::ElementId) -> Self {
        self.id = Some(id);
        self
    }
    /// Gray the control out while this reads false: a `Signal<bool>`, or a derived condition
    /// (`|| !INCOGNITO.get()`), tracked like any reactive read.
    pub fn enabled<M>(mut self, enabled: impl IntoReactive<bool, M>) -> Self {
        self.enabled = Some(enabled.into_reactive());
        self
    }
    /// Omit the row when false.
    pub fn available(mut self, f: impl Fn() -> bool + 'static) -> Self {
        self.available = Some(Rc::new(f));
        self
    }
    /// Omit the row unless the toolkit supports `cap`.
    pub fn requires(self, cap: Cap) -> Self {
        self.available(move || day_core::capability(cap) != Support::Unsupported)
    }
    fn is_available(&self) -> bool {
        self.available.as_ref().is_none_or(|f| f())
    }
}

/// The row constructors (docs/settings.md). Use them qualified (`rows::toggle(..)`): several
/// share a name with a piece in the Day prelude.
pub mod rows {
    use super::*;

    fn pref_id<T: PrefValue>(p: &Pref<T>) -> day_core::ElementId {
        day_core::id!(pref, p.key())
    }

    /// An on/off row bound to a `Pref<bool>`.
    pub fn toggle<M>(pref: &'static Pref<bool>, title: impl IntoText<M>) -> Row {
        Row::new(title, RowKind::Toggle(pref.signal())).id(pref_id(pref))
    }

    /// A one-of-N row: `options` pairs each value with its label. Menu by default;
    /// [`Row::segmented`] for a few short labels.
    pub fn choice<T: PrefValue, M, L, LM>(
        pref: &'static Pref<T>,
        title: impl IntoText<M>,
        options: impl IntoIterator<Item = (T, L)>,
    ) -> Row
    where
        L: IntoText<LM>,
    {
        let (values, labels): (Vec<T>, Vec<TextSource>) =
            options.into_iter().map(|(v, l)| (v, l.into_text())).unzip();
        let sig = pref.signal();
        let current = sig.get_untracked();
        let index = Signal::global(values.iter().position(|v| *v == current).unwrap_or(0));
        // Two-way: the index drives the pref; an outside write to the pref (a menu command, a
        // reset) moves the index. `set_if_changed` on both ends breaks the echo.
        {
            let values = values.clone();
            watch(
                move || index.get(),
                move |ix, _| {
                    if let Some(v) = values.get(*ix) {
                        pref.set(v.clone());
                    }
                },
            );
        }
        watch(
            move || sig.get(),
            move |v, _| {
                if let Some(ix) = values.iter().position(|x| x == v) {
                    index.set_if_changed(ix);
                }
            },
        );
        Row::new(
            title,
            RowKind::Choice {
                labels,
                index,
                style: ChoiceStyle::Menu,
            },
        )
        .id(pref_id(pref))
    }

    impl Row {
        /// Present a [`choice`] as a segmented control.
        pub fn segmented(mut self) -> Self {
            if let RowKind::Choice { style, .. } = &mut self.kind {
                *style = ChoiceStyle::Segmented;
            }
            self
        }
        /// A [`slider`]'s or [`stepper`]'s step.
        pub fn step(mut self, s: f64) -> Self {
            match &mut self.kind {
                RowKind::Slider { step, .. } => *step = Some(s),
                RowKind::Stepper { step, .. } => *step = s,
                _ => {}
            }
            self
        }
        /// A [`slider`]'s value label, shown beside the control.
        pub fn value_text(mut self, f: impl Fn(f64) -> String + 'static) -> Self {
            if let RowKind::Slider { value_text, .. } = &mut self.kind {
                *value_text = Some(Rc::new(f));
            }
            self
        }
        /// A [`text`] row's placeholder.
        pub fn placeholder<M>(mut self, t: impl IntoText<M>) -> Self {
            if let RowKind::Text { placeholder, .. } = &mut self.kind {
                *placeholder = Some(t.into_text());
            }
            self
        }
        /// A [`text`] row that hides its characters.
        pub fn secure(mut self) -> Self {
            if let RowKind::Text { secure, .. } = &mut self.kind {
                *secure = true;
            }
            self
        }
        /// An [`action`] drawn as destructive (red where the platform has a red).
        pub fn destructive(mut self) -> Self {
            if let RowKind::Action { destructive, .. } = &mut self.kind {
                *destructive = true;
            }
            self
        }
        /// An [`action`] that asks first: a confirm dialog with `message`, destructive when the
        /// row is.
        pub fn confirm<M>(mut self, message: impl IntoText<M>) -> Self {
            if let RowKind::Action { confirm, .. } = &mut self.kind {
                *confirm = Some(message.into_text());
            }
            self
        }
        /// The confirm dialog's own button label ("Reset" rather than the generic OK).
        pub fn confirm_label<M>(mut self, label: impl IntoText<M>) -> Self {
            if let RowKind::Action { confirm_label, .. } = &mut self.kind {
                *confirm_label = Some(label.into_text());
            }
            self
        }
        /// An [`action`] that shows a spinner and disables while this reads true: a
        /// `Signal<bool>` or a closure.
        pub fn busy<M>(mut self, busy: impl IntoReactive<bool, M>) -> Self {
            if let RowKind::Action { busy: b, .. } = &mut self.kind {
                *b = Some(busy.into_reactive());
            }
            self
        }
        /// An [`info`] row with a copy affordance.
        pub fn copyable(mut self) -> Self {
            if let RowKind::Info { copyable, .. } = &mut self.kind {
                *copyable = true;
            }
            self
        }
    }

    /// A continuous value over `range`.
    pub fn slider<M>(
        pref: &'static Pref<f64>,
        title: impl IntoText<M>,
        range: std::ops::RangeInclusive<f64>,
    ) -> Row {
        let sig = pref.signal();
        Row::new(
            title,
            RowKind::Slider {
                value: sig,
                range,
                step: None,
                value_text: None,
            },
        )
        .id(pref_id(pref))
    }

    /// A small integer with increment/decrement controls.
    pub fn stepper<M>(
        pref: &'static Pref<i64>,
        title: impl IntoText<M>,
        range: std::ops::RangeInclusive<i64>,
    ) -> Row {
        let sig = pref.signal();
        let value = Signal::global(sig.get_untracked() as f64);
        watch(move || value.get(), move |v, _| pref.set(v.round() as i64));
        watch(
            move || sig.get(),
            move |v, _| value.set_if_changed(*v as f64),
        );
        Row::new(
            title,
            RowKind::Stepper {
                value,
                range: (*range.start() as f64)..=(*range.end() as f64),
                step: 1.0,
            },
        )
        .id(pref_id(pref))
    }

    /// A free-text value; every edit persists.
    pub fn text<M>(pref: &'static Pref<String>, title: impl IntoText<M>) -> Row {
        let sig = pref.signal();
        Row::new(
            title,
            RowKind::Text {
                value: sig,
                placeholder: None,
                secure: false,
            },
        )
        .id(pref_id(pref))
    }

    /// A command row: a button with the title. [`Row::destructive`], [`Row::confirm`],
    /// [`Row::busy`].
    pub fn action<M>(title: impl IntoText<M>, on: impl Fn() + 'static) -> Row {
        Row::new(
            title,
            RowKind::Action {
                on: Rc::new(on),
                destructive: false,
                confirm: None,
                confirm_label: None,
                busy: None,
            },
        )
    }

    /// A row that opens `url` in the platform's handler.
    pub fn link<M>(title: impl IntoText<M>, url: impl Into<String>) -> Row {
        Row::new(title, RowKind::Link(url.into()))
    }

    /// A row that pushes a sub-page built by `build` (a chevron row).
    pub fn navigate<M, P: Piece>(title: impl IntoText<M>, build: impl Fn() -> P + 'static) -> Row {
        Row::new(
            title,
            RowKind::Navigate(Rc::new(move || AnyPiece::new(build()))),
        )
    }

    /// A read-only title/value pair. [`Row::copyable`].
    pub fn info<M, VM>(title: impl IntoText<M>, value: impl IntoText<VM>) -> Row {
        Row::new(
            title,
            RowKind::Info {
                value: value.into_text(),
                copyable: false,
            },
        )
    }

    /// A footnote paragraph inside a section.
    pub fn note<M>(text: impl IntoText<M>) -> Row {
        Row::new(text, RowKind::Note)
    }

    /// Any piece as a row, inside the section's card.
    pub fn custom<P: Piece>(build: impl Fn() -> P + 'static) -> Row {
        Row::new("", RowKind::Custom(Rc::new(move || AnyPiece::new(build()))))
    }
}

// ===========================================================================
// About
// ===========================================================================

/// The app's About content (docs/settings.md): a window on the desktops, the toolkit's About
/// dialog on GTK, a page inside Settings on mobile and Windows.
#[derive(Clone, Default)]
#[must_use]
pub struct About {
    name: Option<TextSource>,
    version: Option<String>,
    build: Option<String>,
    tagline: Option<TextSource>,
    copyright: Option<TextSource>,
    icon: Option<day_spec::ImageName>,
    links: Vec<(TextSource, String)>,
    privacy: Option<String>,
    credits: Option<TextSource>,
    licenses: Option<TextSource>,
    custom: Option<Build>,
}

impl About {
    /// Name, version and build from the app identity `day build` exports (`Day.toml`
    /// `[app]`), falling back to the window's app name and `WindowOptions::version` at run
    /// time.
    pub fn from_manifest() -> Self {
        About {
            version: option_env!("DAY_SETTINGS_APP_VERSION").map(str::to_owned),
            build: option_env!("DAY_SETTINGS_APP_BUILD").map(str::to_owned),
            ..Default::default()
        }
    }
    /// The display name (default: the app title from the manifest, else the window title).
    pub fn name<M>(mut self, t: impl IntoText<M>) -> Self {
        self.name = Some(t.into_text());
        self
    }
    pub fn version(mut self, v: impl Into<String>) -> Self {
        self.version = Some(v.into());
        self
    }
    pub fn build(mut self, b: impl Into<String>) -> Self {
        self.build = Some(b.into());
        self
    }
    /// One line under the name.
    pub fn tagline<M>(mut self, t: impl IntoText<M>) -> Self {
        self.tagline = Some(t.into_text());
        self
    }
    pub fn copyright<M>(mut self, t: impl IntoText<M>) -> Self {
        self.copyright = Some(t.into_text());
        self
    }
    /// The app icon as a bundled image (`res::images::icon`).
    pub fn icon(mut self, icon: impl Into<day_spec::ImageName>) -> Self {
        self.icon = Some(icon.into());
        self
    }
    /// A titled link. The two links most apps carry have their own methods with localized
    /// titles: [`website`](Self::website) and [`source`](Self::source).
    pub fn link<M>(mut self, title: impl IntoText<M>, url: impl Into<String>) -> Self {
        self.links.push((title.into_text(), url.into()));
        self
    }
    /// The app's website, titled from Day's catalog (`day_about_website`).
    pub fn website(self, url: impl Into<String>) -> Self {
        self.link(day_localization_ui::res::str::day_about_website(), url)
    }
    /// The app's source code, titled from Day's catalog (`day_about_source`).
    pub fn source(self, url: impl Into<String>) -> Self {
        self.link(day_localization_ui::res::str::day_about_source(), url)
    }
    /// The privacy policy URL: a known slot (the stores ask for it, GTK has a field).
    pub fn privacy(mut self, url: impl Into<String>) -> Self {
        self.privacy = Some(url.into());
        self
    }
    /// Acknowledgements, as a text block (Markdown where the toolkit renders it).
    pub fn credits<M>(mut self, t: impl IntoText<M>) -> Self {
        self.credits = Some(t.into_text());
        self
    }
    /// Third-party license notices, as one text block.
    pub fn licenses<M>(mut self, t: impl IntoText<M>) -> Self {
        self.licenses = Some(t.into_text());
        self
    }
    /// A bespoke piece that replaces the composed About body.
    pub fn custom<P: Piece>(mut self, build: impl Fn() -> P + 'static) -> Self {
        self.custom = Some(Rc::new(move || AnyPiece::new(build())));
        self
    }

    /// The resolved display name.
    pub fn display_name(&self) -> String {
        match &self.name {
            Some(n) => n.initial(),
            None => option_env!("DAY_SETTINGS_APP_TITLE")
                .map(str::to_owned)
                .or_else(|| day_core::launch_options().map(|o| o.app_name.unwrap_or(o.title)))
                .unwrap_or_default(),
        }
    }
    /// The version line, localized ("Version 2.3.0 (14)").
    #[must_use]
    pub fn version_line(&self) -> Option<String> {
        use std::fmt::Write as _;
        let version = self
            .version
            .clone()
            .or_else(|| day_core::launch_options().and_then(|o| o.version.clone()))?;
        let mut line = day_localization_ui::res::str::day_about_version(version).format();
        if let Some(build) = &self.build
            && !build.is_empty()
        {
            let _ = write!(line, " ({build})");
        }
        Some(line)
    }
    #[must_use]
    pub fn version_value(&self) -> Option<&str> {
        self.version.as_deref()
    }
    #[must_use]
    pub fn build_value(&self) -> Option<&str> {
        self.build.as_deref()
    }
    #[must_use]
    pub fn links(&self) -> &[(TextSource, String)] {
        &self.links
    }
    #[must_use]
    pub fn privacy_url(&self) -> Option<&str> {
        self.privacy.as_deref()
    }
    #[must_use]
    pub fn icon_name(&self) -> Option<&day_spec::ImageName> {
        self.icon.as_ref()
    }
    pub fn tagline_text(&self) -> Option<String> {
        self.tagline.as_ref().map(TextSource::initial)
    }
    pub fn copyright_text(&self) -> Option<String> {
        self.copyright.as_ref().map(TextSource::initial)
    }
    pub fn credits_text(&self) -> Option<String> {
        self.credits.as_ref().map(TextSource::initial)
    }
    pub fn licenses_text(&self) -> Option<String> {
        self.licenses.as_ref().map(TextSource::initial)
    }
    #[must_use]
    pub fn custom_piece(&self) -> Option<AnyPiece> {
        self.custom.as_ref().map(|b| b())
    }
}

// ===========================================================================
// Providers
// ===========================================================================

/// A settings group contributed by another crate (docs/settings.md): the self-updater's
/// Updates group is the first. Declared as a static through [`provider!`], which registers it
/// in the link-time slice on native targets; on wasm (no linkme) and anywhere an explicit
/// order matters, [`register_provider`] / [`Preferences::provider`] name it directly.
pub struct Provider {
    /// The group's route id; also used by [`Preferences::without_provider`].
    pub id: &'static str,
    /// Sort key among the app's groups (apps default to 0, providers to 500).
    pub order: i32,
    /// Whether the group applies to this build/platform at all.
    pub available: fn() -> bool,
    /// The group.
    pub group: fn() -> Group,
    /// Runs once inside [`Preferences::install`], after the store is reachable: register menu
    /// actions, start a scheduler, apply a persisted value.
    pub startup: Option<fn()>,
}

/// Every statically registered [`Provider`] (native targets; empty on wasm).
#[cfg(not(target_arch = "wasm32"))]
#[linkme::distributed_slice]
pub static PROVIDERS: [&'static Provider];

/// Declare a provider static and register it (docs/settings.md):
///
/// ```ignore
/// day_piece_settings::provider! {
///     static UPDATES: Provider = Provider { id: "updates", order: 900, available: || true,
///         group: updates_group, startup: Some(schedule) };
/// }
/// ```
#[macro_export]
macro_rules! provider {
    ($(#[$meta:meta])* $vis:vis static $name:ident : Provider = $init:expr ;) => {
        $(#[$meta])*
        $vis static $name: $crate::Provider = $init;
        // The crate path keeps an out-of-tree provider free of its own `linkme` dependency.
        #[cfg(not(target_arch = "wasm32"))]
        #[$crate::linkme::distributed_slice($crate::PROVIDERS)]
        #[linkme(crate = $crate::linkme)]
        static __DAY_SETTINGS_PROVIDER: &'static $crate::Provider = &$name;
    };
}

#[doc(hidden)]
pub use linkme;

/// Register a provider at run time (before [`Preferences::install`]): the wasm path, and the
/// explicit alternative to the link-time slice anywhere.
pub fn register_provider(p: &'static Provider) {
    RUNTIME_PROVIDERS.with(|r| {
        let mut r = r.borrow_mut();
        if !r.iter().any(|q| std::ptr::eq(*q, p)) {
            r.push(p);
        }
    });
}

fn all_providers() -> Vec<&'static Provider> {
    let mut out: Vec<&'static Provider> = Vec::new();
    #[cfg(not(target_arch = "wasm32"))]
    out.extend(PROVIDERS.iter().copied());
    RUNTIME_PROVIDERS.with(|r| {
        for p in r.borrow().iter() {
            if !out.iter().any(|q| std::ptr::eq(*q, *p)) {
                out.push(p);
            }
        }
    });
    out
}

/// Which providers [`Preferences::install`] collects.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum Providers {
    /// Every registered provider whose `available` says yes (the default).
    #[default]
    Registered,
    /// Only the ones named with [`Preferences::provider`].
    None,
}

// ===========================================================================
// Preferences: the declaration and install()
// ===========================================================================

/// How the surface is presented; chosen per toolkit by default.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Presentation {
    /// A desktop Preferences window with the groups as tabs/pages (the app menu opens it).
    Window,
    /// A navigation presentation: a root list (About header, groups) pushing one page per
    /// group. Mobile, and any app that keeps settings as an in-app route.
    Navigation,
}

/// The settings declaration (docs/settings.md). Build it in `root()` and call
/// [`Self::install`].
#[must_use]
pub struct Preferences {
    about: Option<About>,
    groups: Vec<Group>,
    providers: Providers,
    explicit: Vec<&'static Provider>,
    excluded: Vec<&'static str>,
    presentation: Option<Presentation>,
    window_size: day_spec::Size,
    title: Option<TextSource>,
}

impl Default for Preferences {
    fn default() -> Self {
        Self::new()
    }
}

impl Preferences {
    pub fn new() -> Self {
        Preferences {
            about: None,
            groups: Vec::new(),
            providers: Providers::Registered,
            explicit: Vec::new(),
            excluded: Vec::new(),
            presentation: None,
            window_size: day_spec::Size::new(560.0, 640.0),
            title: None,
        }
    }
    /// The About content; registers the About menu item and window.
    pub fn about(mut self, about: About) -> Self {
        self.about = Some(about);
        self
    }
    /// Append a group.
    pub fn group(mut self, group: Group) -> Self {
        self.groups.push(group);
        self
    }
    /// Which registered providers to collect (default: all available).
    pub fn providers(mut self, policy: Providers) -> Self {
        self.providers = policy;
        self
    }
    /// Name a provider explicitly (also what a wasm build does, where the link-time slice is
    /// empty).
    pub fn provider(mut self, p: &'static Provider) -> Self {
        self.explicit.push(p);
        self
    }
    /// Leave out a registered provider by id.
    pub fn without_provider(mut self, id: &'static str) -> Self {
        self.excluded.push(id);
        self
    }
    /// Pin the presentation instead of letting the toolkit decide.
    pub fn presentation(mut self, p: Presentation) -> Self {
        self.presentation = Some(p);
        self
    }
    /// The desktop window's size (height is a ceiling: the window fits its page).
    pub fn window_size(mut self, width: f64, height: f64) -> Self {
        self.window_size = day_spec::Size::new(width, height);
        self
    }
    /// The surface's title (default: the platform's word, Settings or Preferences).
    pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
        self.title = Some(t.into_text());
        self
    }

    /// Wire everything up (docs/settings.md) and return the handle the app's nav and pages
    /// use. Call once, in `root()`, after the locale catalog installs and before `app_menu`.
    pub fn install(self) -> Prefs {
        let Preferences {
            about,
            mut groups,
            providers,
            explicit,
            excluded,
            presentation,
            window_size,
            title,
        } = self;
        // Collect providers: the registered set (unless opted out), plus explicit ones.
        let mut chosen: Vec<&'static Provider> = Vec::new();
        if providers == Providers::Registered {
            chosen.extend(all_providers());
        }
        for p in explicit {
            if !chosen.iter().any(|q| std::ptr::eq(*q, p)) {
                chosen.push(p);
            }
        }
        chosen.retain(|p| !excluded.contains(&p.id) && (p.available)());
        for p in &chosen {
            if let Some(startup) = p.startup {
                startup();
            }
            groups.push((p.group)().order(p.order));
        }
        groups.sort_by_key(|g| g.order);
        let presentation = presentation.unwrap_or_else(default_presentation);
        let title = title.unwrap_or_else(|| TextSource::Dyn(Rc::new(platform_word)));
        let installed = Rc::new(Installed {
            in_nav: Cell::default(),
            about,
            groups,
            presentation,
            title,
            selected: Signal::global(String::new()),
            path: Signal::global(Vec::new()),
        });
        INSTALLED.with(|i| *i.borrow_mut() = Some(installed.clone()));

        // Desktop: the Preferences window and its menu item, and the About window. A
        // navigation-presentation toolkit with an app menu (the web's emulated menu button)
        // registers the cover as the surface instead, so the injected Settings… item exists
        // and opens it; without a menu nothing is registered and the app's nav item is the
        // entry.
        match presentation {
            Presentation::Window => {
                let inst = installed.clone();
                day_core::register_preferences_with(
                    day_spec::WindowOptions {
                        title: installed.title.initial(),
                        size: window_size,
                        size_to_fit: true,
                        ..day_spec::WindowOptions::default()
                    },
                    move || window_shell(inst.clone()),
                );
            }
            Presentation::Navigation
                if day_core::capability(Cap::AppMenu) != Support::Unsupported =>
            {
                let inst = installed.clone();
                day_core::register_preferences_with(
                    day_spec::WindowOptions {
                        title: installed.title.initial(),
                        ..day_spec::WindowOptions::default()
                    },
                    move || navigation_shell_with_done(inst.clone()),
                );
            }
            Presentation::Navigation => {}
        }
        if installed.about.is_some() {
            install_about(installed.clone());
        }
        register_route_controller(installed.clone());
        Prefs(installed)
    }
}

/// The installed declaration, shared by the handle and the free functions.
struct Installed {
    about: Option<About>,
    groups: Vec<Group>,
    presentation: Presentation,
    title: TextSource,
    /// The selected group id in the desktop window ("" = first).
    selected: Signal<String>,
    /// The pushed path in the navigation presentation.
    path: Signal<Vec<SettingsRoute>>,
    /// The app placed the navigation presentation in its own navigation (a nav item or an
    /// embedded page), which then owns the `settings` route.
    in_nav: std::cell::Cell<bool>,
}

impl Installed {
    fn visible_groups(&self) -> Vec<&Group> {
        self.groups.iter().filter(|g| g.is_available()).collect()
    }
    fn group(&self, id: &str) -> Option<&Group> {
        self.groups.iter().find(|g| g.id == id && g.is_available())
    }
}

/// The word the platform uses for the surface: "Settings" on macOS, Windows and the phones,
/// "Preferences" on GNOME and KDE.
fn platform_word() -> String {
    let gnome_or_kde = matches!(day_core::toolkit_key(), Some("gtk" | "qt"));
    if gnome_or_kde {
        day_localization::t(day_localization::key::day_preferences)
    } else {
        day_localization::t(day_localization::key::day_settings)
    }
}

fn default_presentation() -> Presentation {
    // A toolkit that can open a window and has a menu bar to reach it from gets the window;
    // everything else (the phones, HarmonyOS, the web) gets the navigation presentation.
    let windows = day_core::capability(Cap::MultiWindow) != Support::Unsupported;
    let menu = day_core::capability(Cap::AppMenu) != Support::Unsupported;
    if windows && menu {
        Presentation::Window
    } else {
        Presentation::Navigation
    }
}

/// The handle [`Preferences::install`] returns: `Copy`, so pages and the nav take it by value.
#[derive(Clone)]
pub struct Prefs(Rc<Installed>);

impl Prefs {
    /// Open-or-focus the surface: the window on desktop; on mobile, select the nav item when
    /// one is mounted, else present the navigation presentation as a cover.
    pub fn open(&self) -> bool {
        open()
    }
    /// Open and select a group (`"updates"`), optionally a row (`"updates/check"`).
    pub fn open_at(&self, route: &str) -> bool {
        open_at(route)
    }
    /// Whether the app should place a Settings entry in its own navigation: true where the
    /// platform gives no app menu to reach the surface from (the phones); false on the
    /// desktops and on the web, whose menu button carries Settings… and About.
    #[must_use]
    pub fn in_nav(&self) -> bool {
        self.0.presentation == Presentation::Navigation
            && day_core::capability(Cap::AppMenu) == Support::Unsupported
    }
    /// The Settings entry for the app's navigation, titled with the platform's word and
    /// opening [`page`](Self::page): `Some` where [`Self::in_nav`], `None` where the platform's
    /// application menu already carries Settings. Goes straight into a nav's items:
    /// `nav(sel).items((…, prefs.nav_item(Section::Settings)))`.
    pub fn nav_item<K>(&self, key: impl Into<K>) -> Option<NavItem<K>> {
        self.in_nav().then(|| self.nav_item_everywhere(key))
    }
    /// The Settings entry on every platform, menu or not: for an app that wants Settings in
    /// its sidebar on the desktop too. Most apps want [`nav_item`](Self::nav_item).
    pub fn nav_item_everywhere<K>(&self, key: impl Into<K>) -> NavItem<K> {
        self.0.in_nav.set(true);
        let title = self.0.title.clone();
        let inst = self.0.clone();
        item(key, move || title.initial()).page(move || navigation_shell(inst.clone()))
    }
    /// The navigation presentation as a piece: the destination of the nav item, or any place
    /// the app embeds settings.
    pub fn page(&self) -> AnyPiece {
        self.0.in_nav.set(true);
        navigation_shell(self.0.clone())
    }
    /// One group's page alone (an in-reader sheet, a sidebar pane).
    pub fn group_page(&self, id: &str) -> AnyPiece {
        match self.0.group(id) {
            Some(g) => group_page(self.0.clone(), g, false),
            None => column(()).any(),
        }
    }
    /// One group's sections without a scroll, for a sheet that stacks several groups and
    /// owns the scrolling itself: put the bodies in one `scroll`. The phones keep their native
    /// shape, sized to its rows.
    pub fn group_body(&self, id: &str) -> AnyPiece {
        match self.0.group(id) {
            Some(g) => group_body(self.0.clone(), g),
            None => column(()).any(),
        }
    }
    /// The composed About page.
    pub fn about_page(&self) -> AnyPiece {
        about_page(self.0.clone())
    }
    /// The surface's title.
    #[must_use]
    pub fn title(&self) -> String {
        self.0.title.initial()
    }
}

fn installed() -> Option<Rc<Installed>> {
    INSTALLED.with(|i| i.borrow().clone())
}

/// Open-or-focus the installed settings surface (see [`Prefs::open`]).
pub fn open() -> bool {
    let Some(inst) = installed() else {
        log::warn!("day-piece-settings: open() before Preferences::install()");
        return false;
    };
    match inst.presentation {
        Presentation::Window => day_core::open_preferences(),
        Presentation::Navigation => day_core::navigate(NAV_KEY) || open_cover(inst),
    }
}

/// Present the navigation presentation as a cover (a Done button closes it): the mobile path
/// when no nav item is mounted.
fn open_cover(inst: Rc<Installed>) -> bool {
    // A newly presented Settings cover starts at its group list. Keep the current
    // page when merely focusing a cover that is already open. `open_at` applies its
    // requested group after this call, so deep links still land on that group.
    if day_core::window_by_key(day_core::windows::PREFERENCES_KEY).is_none() {
        inst.path.set(Vec::new());
    }
    day_core::open_window(
        day_spec::WindowOptions::default()
            .title(inst.title.initial())
            .key(day_core::windows::PREFERENCES_KEY)
            .kind(day_spec::WindowKind::Preferences),
        move || navigation_shell_with_done(inst.clone()),
    );
    true
}

/// The nav item key an app conventionally mounts the surface under; `open()` tries it first.
pub const NAV_KEY: &str = "settings";

/// The installed navigation presentation as a piece (see [`Prefs::page`]), for code that has
/// no [`Prefs`] handle at hand. An empty piece before [`Preferences::install`].
pub fn page() -> AnyPiece {
    match installed() {
        Some(inst) => {
            // The app is placing Settings in its own navigation, which then owns the
            // `settings` route (the phone cover controller stands aside).
            inst.in_nav.set(true);
            navigation_shell(inst)
        }
        None => column(()).any(),
    }
}

/// One installed group's page alone (see [`Prefs::group_page`]).
pub fn group_page_of(id: &str) -> AnyPiece {
    match installed() {
        Some(inst) => Prefs(inst).group_page(id),
        None => column(()).any(),
    }
}

/// Open the surface at a group route (`"updates"`, `"updates/check"`).
pub fn open_at(route: &str) -> bool {
    let Some(inst) = installed() else {
        return false;
    };
    let (group, _row) = route.split_once('/').unwrap_or((route, ""));
    if group == "about" {
        return day_core::open_about();
    }
    if inst.group(group).is_none() {
        return false;
    }
    match inst.presentation {
        Presentation::Window => {
            inst.selected.set_if_changed(group.to_string());
            day_core::open_preferences()
        }
        Presentation::Navigation => {
            // Already inside the settings section (a route's second segment arriving while
            // the first is current): just move the stack, without re-entering `navigate`.
            let inside = day_core::current_route()
                .is_some_and(|r| r == NAV_KEY || r.starts_with(&format!("{NAV_KEY}/")));
            let ok = inside || open();
            inst.path.set(vec![SettingsRoute::Group(group.to_string())]);
            ok
        }
    }
}

/// Register the desktop surface as a route root, so `navigate("settings/updates")` and a deep
/// link open the window on the group (the navigation presentation routes through its nav
/// item instead).
///
/// Two controllers: the root answers `settings` (and `about`, and a bare group id) by opening
/// the window; a second, registered right after it, answers the group segment that follows.
/// day-core feeds an absolute path's tail only to the surfaces nested after the one that
/// took its head, never to that surface itself, and the window's own nav is `.local()` (it
/// must not contribute to the app's route), so the tail needs a surface of its own to land on.
///
/// For the window presentation, and for a navigation presentation whose toolkit has an app
/// menu (the web). Where the platform has no menu the app's nav item owns the `settings`
/// route and the stack inside it owns the group segment; a controller there would be
/// consulted before the app's nav (it registers earlier) and would present the cover over a
/// section that never switched. An app with no nav host on such a platform reaches the
/// cover through [`open`] from its own affordance.
fn register_route_controller(inst: Rc<Installed>) {
    // The web is the navigation presentation with an emulated app menu: the cover is the
    // registered preferences surface and no nav item claims `settings`, so the routes land
    // here too (the starter's `navigate: settings` step runs on every target).
    let menu = day_core::capability(Cap::AppMenu) != Support::Unsupported;
    if inst.presentation != Presentation::Window && !menu {
        register_cover_route_controller(inst);
        return;
    }
    let open_surface = day_core::open_preferences;
    let root = inst.clone();
    let open_root = open_surface;
    let _root_token = day_core::register_nav(day_core::NavController {
        push: Box::new(move |route| {
            if route == NAV_KEY {
                open_root()
            } else if route == "about" {
                day_core::open_about()
            } else if root.group(route).is_some() {
                open_at(route)
            } else {
                false
            }
        }),
        pop: Box::new(|_| false),
        current: Box::new(String::new),
        enter: Box::new(move |segment| segment == NAV_KEY && open_surface()),
        segments: Box::new(Vec::new),
        depth: 0,
        layer: Box::new(|| 0),
        active: Box::new(|| true),
    });
    let group = inst;
    let _group_token = day_core::register_nav(day_core::NavController {
        push: Box::new(|_| false),
        pop: Box::new(|_| false),
        current: Box::new(String::new),
        enter: Box::new(move |segment| group.group(segment).is_some() && open_at(segment)),
        segments: Box::new(Vec::new),
        // Depth 0, like the root: day-core offers an absolute path's tail to the surfaces
        // after the anchor in depth order, registration order within a depth. At depth 1
        // this controller came after the app's own nav (depth 0, registered later), which
        // took a tail naming one of its sections (`settings/practice` opened Lexicon's
        // Practice section). At depth 0 it is consulted first, and a segment naming no group
        // still falls through to the app.
        depth: 0,
        layer: Box::new(|| 0),
        active: Box::new(|| true),
    });
}

/// The routes for a phone app with no nav host: `navigate("settings/search")` and a deep link
/// present the Settings cover on that group, as [`open_at`] does. A fallback
/// ([`day_core::register_nav_fallback`]): consulted only when no mounted surface accepts the
/// route, so an app with a `settings` section of its own (built yet or not: a sidebar builds a
/// page on its first visit) selects that section, whose Settings stack then takes the group.
/// It also stands aside once the app has mounted Settings anywhere in its own navigation
/// ([`Prefs::nav_item`], [`Prefs::page`], [`page`]).
fn register_cover_route_controller(inst: Rc<Installed>) {
    let root = inst.clone();
    let active = inst.clone();
    let enter = inst;
    let _token = day_core::register_nav_fallback(day_core::NavController {
        push: Box::new(move |route| {
            if route == NAV_KEY {
                open_cover(root.clone())
            } else if route == "about" {
                day_core::open_about()
            } else if root.group(route).is_some() {
                open_cover(root.clone());
                root.path.set(vec![SettingsRoute::Group(route.to_string())]);
                true
            } else {
                false
            }
        }),
        pop: Box::new(|_| false),
        current: Box::new(String::new),
        // The rest of `settings/<group>` once `push` has opened the cover.
        enter: Box::new(move |segment| {
            if enter.group(segment).is_none() {
                return false;
            }
            enter
                .path
                .set(vec![SettingsRoute::Group(segment.to_string())]);
            true
        }),
        segments: Box::new(Vec::new),
        depth: 0,
        layer: Box::new(|| 0),
        active: Box::new(move || !active.in_nav.get()),
    });
}

fn install_about(inst: Rc<Installed>) {
    #[cfg(feature = "gtk")]
    {
        if gtk_impl::install_about(inst.clone()) {
            return;
        }
    }
    let name = inst.about.as_ref().map_or_default(About::display_name);
    let title = day_localization_ui::res::str::day_about_app(name);
    // Where windows open as covers (the web, a phone), About is a sheet with a title bar and a
    // Done button, as Settings is there: a bare page had no way out.
    let cover = day_core::capability(day_spec::Cap::MultiWindow) == day_spec::Support::Unsupported;
    day_core::register_about_window(
        day_spec::WindowOptions {
            title: title.format(),
            size: day_spec::Size::new(320.0, 480.0),
            size_to_fit: true,
            ..day_spec::WindowOptions::default()
        },
        move || {
            if cover {
                let title = title.clone();
                nav_stack(
                    Signal::new(Vec::<SettingsRoute>::new()),
                    about_page(inst.clone()),
                )
                .title(move || title.format())
                .toolbar(
                    toolbar_button(
                        day_core::id!(about_done),
                        day_localization_ui::res::str::day_settings_done(),
                    )
                    .action(|| {
                        if let Some(w) = day_core::window_by_key(day_core::windows::ABOUT_KEY) {
                            w.close();
                        }
                    }),
                )
                .any()
            } else {
                about_page(inst.clone())
            }
        },
    );
}

// ===========================================================================
// The General group: appearance + language
// ===========================================================================

pref_enum! {
    /// The app's appearance override: the platform's light or dark look, or whatever the system
    /// says (the default).
    pub enum Appearance { Light = "light", Dark = "dark", System = "system" }
}

/// The appearance pref every app shares, key `day.appearance`. `DAY_THEME` wins at launch.
pub static APPEARANCE: Pref<Appearance> =
    Pref::new("day.appearance", || Appearance::System).env("DAY_THEME");

/// The language pref every app shares, key `day.locale`: a locale tag, or empty for the
/// system language. `DAY_LOCALE` wins at launch.
pub static LANGUAGE: Pref<String> = Pref::new("day.locale", String::new).env("DAY_LOCALE");

fn system_locale() -> String {
    SYSTEM_LOCALE
        .with(|c| c.get().cloned())
        .unwrap_or_else(|| day_localization_ui::locale().get_untracked())
}

fn apply_appearance(a: Appearance) {
    if day_core::capability(Cap::Appearance) == Support::Unsupported {
        return;
    }
    day_core::set_appearance(match a {
        Appearance::Light => Some(false),
        Appearance::Dark => Some(true),
        Appearance::System => None,
    });
}

fn apply_language(tag: &str) {
    if tag.is_empty() {
        day_localization_ui::set_locale(&system_locale());
    } else {
        day_localization_ui::set_locale(tag);
    }
}

/// Apply the persisted appearance and language at boot and keep applying every later change
/// (docs/settings.md). Runs once per process; [`general_group`] calls it, and an app that
/// uses the prefs without the group calls it itself. Honors the env-wins rule: under
/// `DAY_THEME`/`DAY_LOCALE` the stored value is not applied at boot (the launch override
/// stays deterministic), while live changes always apply.
pub fn wire_general() {
    if GENERAL_WIRED.with(|w| w.replace(true)) {
        return;
    }
    SYSTEM_LOCALE.with(|c| {
        let _ = c.set(day_localization_ui::locale().get_untracked());
    });
    if !APPEARANCE.env_forced() {
        apply_appearance(APPEARANCE.get_untracked());
    }
    if !LANGUAGE.env_forced() {
        let tag = LANGUAGE.get_untracked();
        if !tag.is_empty() {
            apply_language(&tag);
        }
    }
    let root = day_reactive::Scope::root();
    root.enter(|| {
        APPEARANCE.watch(|a| apply_appearance(*a));
        LANGUAGE.watch(|tag| apply_language(tag));
    });
}

/// The "General" group every app starts with: Appearance (`theme-picker`, present where the
/// toolkit honors a runtime override) and Language (`language-picker`: System plus every
/// bundled locale under its own name). `locales` is the app's generated `res::locales::ALL`.
pub fn general_group(locales: LocaleTable) -> Group {
    wire_general();
    Group::new(
        "general",
        day_localization_ui::res::str::day_settings_general(),
    )
    .icon(day_spec::Symbol::Settings)
    .row(appearance_row())
    .row(language_row(locales))
}

/// The Light / Dark / System row alone (id `theme-picker`), for apps composing their own group.
pub fn appearance_row() -> Row {
    wire_general();
    rows::choice(
        &APPEARANCE,
        day_localization_ui::res::str::day_settings_theme(),
        [
            (
                Appearance::Light,
                day_localization_ui::res::str::day_theme_light(),
            ),
            (
                Appearance::Dark,
                day_localization_ui::res::str::day_theme_dark(),
            ),
            (
                Appearance::System,
                day_localization_ui::res::str::day_theme_system(),
            ),
        ],
    )
    .segmented()
    .id(day_core::id!(theme_picker))
    .requires(Cap::Appearance)
}

/// The language row alone (id `language-picker`).
pub fn language_row(locales: LocaleTable) -> Row {
    wire_general();
    let mut options: Vec<(String, TextSource)> = vec![(
        String::new(),
        day_localization_ui::res::str::day_theme_system().into_text(),
    )];
    options.extend(
        locales
            .iter()
            .map(|(tag, name)| ((*tag).to_string(), TextSource::Static((*name).to_string()))),
    );
    choice_text(
        &LANGUAGE,
        day_localization_ui::res::str::day_settings_language(),
        options,
    )
    .id(day_core::id!(language_picker))
}

/// [`choice`] over already-resolved label sources (what [`language_row`] builds from a
/// locale table).
fn choice_text<T: PrefValue, M>(
    pref: &'static Pref<T>,
    title: impl IntoText<M>,
    options: Vec<(T, TextSource)>,
) -> Row {
    rows::choice(
        pref,
        title,
        options.into_iter().map(|(v, l)| (v, Resolved(l))),
    )
}

/// An `IntoText` adapter over a `TextSource` (the sources module offers no direct impl).
struct Resolved(TextSource);
struct ResolvedMark;
impl IntoText<ResolvedMark> for Resolved {
    fn into_text(self) -> TextSource {
        self.0
    }
}

// ===========================================================================
// Composed presentation
// ===========================================================================

/// The route type of the navigation presentation's stack: pushed pages are groups, About, a
/// row's sub-page or a choice list.
#[derive(Clone, PartialEq, Debug)]
pub enum SettingsRoute {
    About,
    Group(String),
}

impl Route for SettingsRoute {
    fn key(&self) -> String {
        match self {
            SettingsRoute::About => "about".into(),
            SettingsRoute::Group(g) => g.clone(),
        }
    }
    fn from_key(key: &str) -> Option<Self> {
        Some(match key {
            "about" => SettingsRoute::About,
            g => SettingsRoute::Group(g.to_string()),
        })
    }
    /// Tracked, so a shown page's bar follows a language change (`nav_stack` re-reads it).
    fn title(&self) -> String {
        match self {
            SettingsRoute::About => day_localization::t(day_localization::key::day_about),
            // A row's sub-page goes by its title (`push_subpage`); its key carries a prefix.
            SettingsRoute::Group(g) => match g.strip_prefix("page:") {
                Some(title) => title.to_string(),
                None => installed()
                    .and_then(|i| i.group(g).map(|g| resolve_text(&g.title)))
                    .unwrap_or_else(|| g.clone()),
            },
        }
    }
}

fn text_label(t: &TextSource) -> Label {
    match t {
        TextSource::Static(s) => label(s.clone()),
        TextSource::Dyn(f) => {
            let f = f.clone();
            label(move || f())
        }
    }
}

/// A text source as a closure a label or a control re-reads: tracked, so a localized source
/// (`tr(..)`, a generated accessor) relabels when the locale changes, and a signal-backed
/// one when the signal does.
fn text_source_fn(t: &TextSource) -> impl Fn() -> String + 'static {
    let t = t.clone();
    move || resolve_text(&t)
}

/// Resolve a text source, tracked (see [`text_source_fn`]).
pub(crate) fn resolve_text(t: &TextSource) -> String {
    match t {
        TextSource::Static(s) => s.clone(),
        TextSource::Dyn(f) => f(),
    }
}

/// A choice row's picker, the same on every presentation: the option titles are the row's
/// text sources (so they re-resolve on locale change), bound to the row's index, and the
/// row's enabled gate reaches the control. Every arm builds its picker here, so the two
/// behaviors cannot drift between the composed rows and a native row's suffix control.
pub(crate) fn choice_picker(
    labels: &[TextSource],
    index: Signal<usize>,
    segmented: bool,
    enabled: impl Fn() -> bool + 'static,
) -> day_pieces::Picker<usize, day_pieces::Required<Signal<usize>>> {
    let options: Vec<(usize, TextSource)> = labels.iter().cloned().enumerate().collect();
    let mut p = picker(index, options).enabled(enabled);
    if segmented {
        p = p.segmented();
    }
    p
}

/// A stepper row's two buttons, the same on every presentation: each steps the value within
/// the bounds, and each is enabled only while the row's gate holds AND the bound leaves room.
/// A native row's disabled styling never reaches its child buttons, so the gate is applied to
/// the buttons themselves here.
pub(crate) fn stepper_buttons(
    v: Signal<f64>,
    range: &std::ops::RangeInclusive<f64>,
    step: f64,
    enabled: impl Fn() -> bool + Clone + 'static,
) -> (day_pieces::Button, day_pieces::Button) {
    let (lo, hi, st) = (*range.start(), *range.end(), step);
    let enabled_inc = enabled.clone();
    let dec = button("−")
        .action(move || v.set((v.get_untracked() - st).max(lo)))
        .enabled(move || enabled() && v.get() > lo);
    let inc = button("+")
        .action(move || v.set((v.get_untracked() + st).min(hi)))
        .enabled(move || enabled_inc() && v.get() < hi);
    (dec, inc)
}

/// The same script targets on every settings presentation: the id names the value label,
/// and its two buttons have stable suffixes. Keep these on the controls, not their row.
pub(crate) fn stepper_control(
    value: Signal<f64>,
    dec: day_pieces::Button,
    inc: day_pieces::Button,
    id: Option<&day_core::ElementId>,
) -> AnyPiece {
    let value_label = label(move || format!("{}", value.get() as i64)).tabular();
    match id {
        Some(id) => row((
            dec.id(day_core::id!(pref_decrement, id.as_str())),
            value_label.id(id.clone()),
            inc.id(day_core::id!(pref_increment, id.as_str())),
        ))
        .spacing(8.0)
        .align(VAlign::Center)
        .any(),
        None => row((dec, value_label, inc))
            .spacing(8.0)
            .align(VAlign::Center)
            .any(),
    }
}

/// The desktop window: a sidebar of groups beside the selected page (one group: the page
/// alone). A toolkit feature replaces this with its native panel.
fn window_shell(inst: Rc<Installed>) -> AnyPiece {
    #[cfg(all(feature = "appkit", target_os = "macos"))]
    {
        if let Some(p) = appkit_impl::window_shell(inst.clone()) {
            return p;
        }
    }
    #[cfg(feature = "gtk")]
    {
        if let Some(p) = gtk_impl::window_shell(inst.clone()) {
            return p;
        }
    }
    #[cfg(feature = "qt")]
    {
        if let Some(p) = qt_impl::window_shell(inst.clone()) {
            return p;
        }
    }
    composed_window_shell(inst)
}

#[expect(
    clippy::needless_pass_by_value,
    reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
)]
fn composed_window_shell(inst: Rc<Installed>) -> AnyPiece {
    let groups = inst.visible_groups();
    if groups.len() <= 1 {
        return match groups.first() {
            Some(g) => group_page(inst.clone(), g, true),
            None => column(()).any(),
        };
    }
    if inst.selected.get_untracked().is_empty() {
        inst.selected.set(groups[0].id.to_string());
    }
    let mut nav = nav(inst.selected)
        .style(NavStyle::Sidebar)
        .local()
        .id(day_core::id!(prefs_nav));
    for g in groups {
        let id = g.id;
        let title = text_source_fn(&g.title);
        let inst2 = inst.clone();
        let build = move || {
            let inst = inst2.clone();
            match inst.group(id) {
                Some(g) => group_page(inst.clone(), g, true),
                None => column(()).any(),
            }
        };
        nav = match &g.icon {
            Some(GroupIcon::Image(name)) => {
                nav.items(item(id, title).icon(name.clone()).page(build))
            }
            _ => nav.item(id, title, build),
        };
    }
    let nav = nav.any();
    #[cfg(all(feature = "xaml", target_os = "windows"))]
    let nav = xaml_impl::sidebar_symbols(nav, &inst.visible_groups());
    nav
}

/// A group's page: its sections as a form, then its custom piece.
fn group_page(inst: Rc<Installed>, g: &Group, desktop: bool) -> AnyPiece {
    // The phones draw a group as their own grouped table (a `UITableView` in the inset
    // grouped style, a Material preference list) when the arm provides one.
    if !desktop {
        #[cfg(all(feature = "uikit", target_os = "ios"))]
        {
            if let Some(p) = uikit_impl::group_page(inst.clone(), g) {
                return p;
            }
        }
        #[cfg(all(feature = "material", target_os = "android"))]
        {
            if let Some(p) = android_impl::group_page(inst.clone(), g) {
                return p;
            }
        }
        #[cfg(all(feature = "arkui", target_env = "ohos"))]
        {
            if let Some(p) = arkui_impl::group_page(inst.clone(), g) {
                return p;
            }
        }
    }
    composed_group_page(inst, g, desktop)
}

/// One group's sections with no scroll of their own (see [`Prefs::group_body`]). The phones'
/// native pages size themselves to their rows inside a Day `scroll`.
fn group_body(inst: Rc<Installed>, g: &Group) -> AnyPiece {
    #[cfg(all(feature = "uikit", target_os = "ios"))]
    {
        if let Some(p) = uikit_impl::group_body(inst.clone(), g) {
            return p;
        }
    }
    #[cfg(all(feature = "material", target_os = "android"))]
    {
        if let Some(p) = android_impl::group_body(inst.clone(), g) {
            return p;
        }
    }
    #[cfg(all(feature = "arkui", target_env = "ohos"))]
    {
        if let Some(p) = arkui_impl::group_body(inst.clone(), g) {
            return p;
        }
    }
    column((composed_group_form(inst, g, false),))
        .align(HAlign::Leading)
        .padding(16.0)
        .grow(Dimension::Width)
        .any()
}

/// A group's sections as a form, then its custom piece.
#[expect(
    clippy::needless_pass_by_value,
    reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
)]
fn composed_group_form(inst: Rc<Installed>, g: &Group, desktop: bool) -> AnyPiece {
    let mut parts: Vec<AnyPiece> = Vec::new();
    for s in &g.sections {
        if let Some(p) = section_piece(inst.clone(), s, desktop) {
            parts.push(p);
        }
    }
    if let Some(custom) = &g.custom {
        parts.push(custom());
    }
    form(parts).id(day_core::id!(prefs_group, g.id)).any()
}

/// A group's page from ordinary Day pieces: its sections as a form, then its custom piece.
fn composed_group_page(inst: Rc<Installed>, g: &Group, desktop: bool) -> AnyPiece {
    let body = composed_group_form(inst, g, desktop);
    // A desktop panel fits its page (`size_to_fit`), so the page measures its content; past
    // the height the window can give it (a long page, a large text size) it scrolls.
    if desktop {
        hugging_scroll(
            column((body,))
                .align(HAlign::Leading)
                .padding(20.0)
                .grow(Dimension::Width),
        )
        .any()
    } else {
        scroll(
            column((body,))
                .align(HAlign::Leading)
                .padding(16.0)
                .grow(Dimension::Width),
        )
        .any()
    }
}

#[expect(
    clippy::needless_pass_by_value,
    reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
)]
fn section_piece(inst: Rc<Installed>, s: &Section, desktop: bool) -> Option<AnyPiece> {
    let rows: Vec<AnyPiece> = s
        .rows
        .iter()
        .filter(|r| r.is_available())
        .map(|r| row_piece(inst.clone(), r, desktop))
        .collect();
    if rows.is_empty() {
        return None;
    }
    let mut sec = section(rows);
    if let Some(t) = &s.title {
        sec = sec.title(text_source_fn(t));
    }
    if let Some(f) = &s.footer {
        sec = sec.footer(text_source_fn(f));
    }
    Some(sec.any())
}

/// One composed row: title (and caption) leading, the control trailing, the System Settings
/// / iOS Settings shape every platform reads. A toolkit feature replaces it with its native row.
fn row_piece(inst: Rc<Installed>, r: &Row, desktop: bool) -> AnyPiece {
    #[cfg(feature = "gtk")]
    {
        if let Some(p) = gtk_impl::row_piece(inst.clone(), r, desktop) {
            return p;
        }
    }
    #[cfg(all(feature = "uikit", target_os = "ios"))]
    {
        if let Some(p) = uikit_impl::row_piece(inst.clone(), r, desktop) {
            return p;
        }
    }
    #[cfg(all(feature = "material", target_os = "android"))]
    {
        if let Some(p) = android_impl::row_piece(inst.clone(), r, desktop) {
            return p;
        }
    }
    #[cfg(all(feature = "xaml", target_os = "windows"))]
    {
        if let Some(p) = xaml_impl::row_piece(inst.clone(), r, desktop) {
            return p;
        }
    }
    #[cfg(all(feature = "arkui", target_env = "ohos"))]
    {
        if let Some(p) = arkui_impl::row_piece(inst.clone(), r, desktop) {
            return p;
        }
    }
    composed_row(inst, r, desktop)
}

/// The title column of a row: the title, and the caption under it in the footnote style.
fn title_column(r: &Row) -> AnyPiece {
    let title = text_label(&r.title);
    match &r.caption {
        Some(c) => column((
            title,
            text_label(c).font(day_spec::Font::Footnote).secondary(),
        ))
        .spacing(2.0)
        .align(HAlign::Leading)
        .any(),
        None => title.any(),
    }
}

/// Title leading, control trailing, on one line; a stretching control (a text field) takes
/// the row's remaining width.
fn trailing_row(titles: AnyPiece, control: AnyPiece) -> AnyPiece {
    // The title column wraps past a readable width rather than widening into the control:
    // a long caption would otherwise push a popup off the panel's edge.
    row((titles.max_width(TITLE_COLUMN_MAX), spacer(), control))
        .spacing(12.0)
        .align(VAlign::Center)
        .grow(Dimension::Width)
        .any()
}

/// The widest a composed row's title column grows before its caption wraps.
const TITLE_COLUMN_MAX: f64 = 360.0;
/// A composed slider's width, the same on every row so a page of sliders aligns.
const SLIDER_WIDTH: f64 = 200.0;
/// The value column beside a composed slider: room for "1000%", trailing-aligned.
const VALUE_WIDTH: f64 = 52.0;

fn composed_row(inst: Rc<Installed>, r: &Row, _desktop: bool) -> AnyPiece {
    let id = r.id.clone();
    let enabled = r.enabled.clone();
    let with_id = |p: AnyPiece| match &id {
        Some(id) => p.id(id.clone()).any(),
        None => p,
    };
    let enabled_fn = move || enabled.as_ref().is_none_or(day_pieces::Reactive::get);
    match &r.kind {
        RowKind::Toggle(sig) => {
            let ctl = with_id(toggle(*sig).enabled(enabled_fn).any());
            trailing_row(title_column(r), ctl)
        }
        RowKind::Choice {
            labels,
            index,
            style,
        } => {
            let p = choice_picker(labels, *index, *style == ChoiceStyle::Segmented, enabled_fn);
            trailing_row(title_column(r), with_id(p.any()))
        }
        RowKind::Slider {
            value,
            range,
            step,
            value_text,
        } => {
            let mut s = slider(*value).range(range.clone()).enabled(enabled_fn);
            if let Some(st) = step {
                s = s.step(*st);
            }
            // The id goes on the control itself, before the layout modifiers wrap it. The
            // slider takes one fixed width on every row, so a page of sliders lines up at
            // both ends however long each row's title is (System Settings does the same);
            // only a row too narrow for it stacks the control under the title.
            let ctl = match &id {
                Some(i) => s
                    .id(i.clone())
                    .min_width(SLIDER_WIDTH)
                    .max_width(SLIDER_WIDTH)
                    .any(),
                None => s.min_width(SLIDER_WIDTH).max_width(SLIDER_WIDTH).any(),
            };
            let ctl = match value_text {
                Some(f) => {
                    let f = f.clone();
                    let v = *value;
                    // One line, trailing-aligned in a fixed column so the values line up
                    // whatever their length; id `<id>-value` for scripts.
                    let value_label = label(move || f(v.get()))
                        .tabular()
                        .secondary()
                        .single_line()
                        .align(day_spec::props::TextAlign::Trailing);
                    let value_label = match &id {
                        Some(i) => value_label
                            .id(day_core::id!(pref_value, i.as_str()))
                            .min_width(VALUE_WIDTH)
                            .max_width(VALUE_WIDTH)
                            .any(),
                        None => value_label
                            .min_width(VALUE_WIDTH)
                            .max_width(VALUE_WIDTH)
                            .any(),
                    };
                    row((ctl, value_label))
                        .spacing(8.0)
                        .align(VAlign::Center)
                        .any()
                }
                None => ctl,
            };
            trailing_row(title_column(r), ctl)
        }
        RowKind::Stepper { value, range, step } => {
            let v = *value;
            let (dec, inc) = stepper_buttons(v, range, *step, enabled_fn);
            let ctl = stepper_control(v, dec, inc, id.as_ref());
            trailing_row(title_column(r), ctl)
        }
        RowKind::Text {
            value,
            placeholder,
            secure,
        } => {
            let mut f = if *secure {
                secure_field(*value)
            } else {
                text_field(*value)
            };
            if let Some(ph) = placeholder {
                f = f.placeholder(text_source_fn(ph));
            }
            let f = f.enabled(enabled_fn);
            let ctl = match &id {
                Some(i) => f
                    .id(i.clone())
                    .grow(Dimension::Width)
                    .min_width(160.0)
                    .any(),
                None => f.grow(Dimension::Width).min_width(160.0).any(),
            };
            trailing_row(title_column(r), ctl)
        }
        RowKind::Action {
            on,
            destructive: _,
            confirm,
            confirm_label,
            busy,
        } => {
            let on = on.clone();
            let title = text_source_fn(&r.title);
            let confirm = confirm.clone();
            let confirm_label = confirm_label.clone();
            let busy = busy.clone();
            let run = move || {
                let on = on.clone();
                match &confirm {
                    Some(message) => {
                        let message = message.initial();
                        let title = title();
                        let label = confirm_label.as_ref().map(TextSource::initial);
                        day_core::task(async move {
                            if crate::confirm_dialog(&title, &message, label).await {
                                on();
                            }
                        });
                    }
                    None => on(),
                }
            };
            let busy_gate = busy.clone();
            let b = button(text_source_fn(&r.title))
                .action(run)
                .enabled(move || {
                    enabled_fn() && !busy_gate.as_ref().is_some_and(day_pieces::Reactive::get)
                });
            let ctl = with_id(b.any());
            let ctl = match busy {
                Some(b) => row((when(move || b.get(), spinner), ctl))
                    .spacing(8.0)
                    .align(VAlign::Center)
                    .any(),
                None => ctl,
            };
            // The button carries the title; a caption is the row's explanatory line, so it
            // stands alone in the title column rather than repeating the title above it.
            match &r.caption {
                Some(c) => trailing_row(caption_only(c), ctl),
                None => ctl,
            }
        }
        RowKind::Link(url) => {
            let url = url.clone();
            let l = link(text_source_fn(&r.title), url);
            match &r.caption {
                Some(c) => trailing_row(caption_only(c), with_id(l.any())),
                None => with_id(l.any()),
            }
        }
        RowKind::Navigate(build) => {
            let build = build.clone();
            let title = text_source_fn(&r.title);
            let open = move || {
                let build = build.clone();
                let title = title();
                push_subpage(inst.clone(), title, build);
            };
            with_id(
                row((title_column(r), spacer(), label("›").secondary()))
                    .spacing(12.0)
                    .align(VAlign::Center)
                    .grow(Dimension::Width)
                    .on_tap(open)
                    .any(),
            )
        }
        RowKind::Info { value, copyable } => {
            let v = text_label(value).secondary();
            let v = if *copyable {
                // A visible affordance: the value plus a plain copy button.
                let text = value.clone();
                row((
                    v,
                    button("")
                        .icon(day_spec::Symbol::Copy)
                        .icon_only()
                        .plain()
                        .action(move || {
                            let _ = day_part_clipboard::set_text(&text.initial());
                        }),
                ))
                .spacing(4.0)
                .align(VAlign::Center)
                .any()
            } else {
                v.any()
            };
            trailing_row(title_column(r), with_id(v))
        }
        RowKind::Note => with_id(
            text_label(&r.title)
                .font(day_spec::Font::Footnote)
                .secondary()
                .any(),
        ),
        RowKind::Custom(build) => with_id(build()),
    }
}

/// Push a row's sub-page: onto the navigation presentation's stack when inside one, else into
/// a cover.
#[expect(
    clippy::needless_pass_by_value,
    reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
)]
fn push_subpage(inst: Rc<Installed>, title: String, build: Build) {
    SUBPAGES.with(|s| s.borrow_mut().insert(title.clone(), build.clone()));
    #[cfg(feature = "gtk")]
    {
        // Into the open preferences dialog, as one of its own sub-pages.
        if gtk_impl::push_subpage(inst.clone(), title.clone(), build.clone()) {
            return;
        }
    }
    if inst.presentation == Presentation::Navigation {
        inst.path
            .update(|p| p.push(SettingsRoute::Group(format!("page:{title}"))));
    } else {
        day_core::open_window(
            day_spec::WindowOptions::default()
                .key(format!("day.settings.{title}"))
                .title(title)
                .size(480.0, 560.0)
                .size_to_fit()
                .kind(day_spec::WindowKind::Preferences),
            move || build(),
        );
    }
}

async fn confirm_dialog(title: &str, message: &str, label: Option<String>) -> bool {
    let dialog = confirm(title.to_string())
        .message(message.to_string())
        .destructive();
    match label {
        Some(l) => dialog.confirm_label(l).await,
        None => dialog.await,
    }
}

/// A row's caption alone, for rows whose control already shows the title (a button, a link).
fn caption_only(c: &TextSource) -> AnyPiece {
    text_label(c)
        .font(day_spec::Font::Footnote)
        .secondary()
        .any()
}

/// The navigation presentation: a stack whose root lists About and the groups.
fn navigation_shell(inst: Rc<Installed>) -> AnyPiece {
    navigation_stack(inst, false)
}

/// The same inside a cover: a Done button closes it.
fn navigation_shell_with_done(inst: Rc<Installed>) -> AnyPiece {
    navigation_stack(inst, true)
}

#[expect(
    clippy::needless_pass_by_value,
    reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
)]
fn navigation_stack(inst: Rc<Installed>, done: bool) -> AnyPiece {
    let root_inst = inst.clone();
    let dest_inst = inst.clone();
    let mut stack = nav_stack(inst.path, root_page(root_inst))
        .title(text_source_fn(&inst.title))
        .destination(move |r: &SettingsRoute| destination(dest_inst.clone(), r));
    if done {
        stack = stack.toolbar(
            toolbar_button(
                day_core::id!(settings_done),
                day_localization_ui::res::str::day_settings_done(),
            )
            .action(|| {
                if let Some(w) = day_core::window_by_key(day_core::windows::PREFERENCES_KEY) {
                    w.close();
                }
            })
            // The cover's way out, on the bar on every platform: without an icon, an Automatic
            // item folds into Android's overflow menu.
            .placement(day_spec::ToolbarPlacement::Primary),
        );
    }
    stack.id(day_core::id!(settings_stack)).any()
}

fn destination(inst: Rc<Installed>, r: &SettingsRoute) -> AnyPiece {
    match r {
        SettingsRoute::About => about_page(inst),
        SettingsRoute::Group(g) => {
            if let Some(title) = g.strip_prefix("page:") {
                return SUBPAGES
                    .with(|s| s.borrow().get(title).cloned())
                    .map_or_else(|| column(()).any(), |b| b());
            }
            match inst.group(g) {
                Some(group) => group_page(inst.clone(), group, false),
                None => column(()).any(),
            }
        }
    }
}

/// The mobile root page: the About header card, then the groups as chevron rows (one group:
/// its rows inline under the header).
/// One row of the mobile root list, for a toolkit arm that draws the list natively: a group
/// (or the About header) with what the row shows and what tapping it does.
// Consumed by the uikit/android/arkui arms, which only compile for their targets.
#[allow(dead_code)]
pub(crate) struct RootEntry {
    /// The group id (`"about"` for the About header), also the row's element id suffix.
    pub id: String,
    pub title: TextSource,
    pub subtitle: Option<TextSource>,
    pub icon: Option<GroupIcon>,
    /// Push the entry's page onto the settings stack.
    pub open: Rc<dyn Fn()>,
}

/// The root list's entries in order: the About header first (when an About is declared),
/// then every visible group.
#[allow(dead_code)]
pub(crate) fn root_entries(inst: &Rc<Installed>) -> (Option<RootEntry>, Vec<RootEntry>) {
    let path = inst.path;
    let about = inst.about.as_ref().map(|about| RootEntry {
        id: "about".into(),
        title: TextSource::Static(about.display_name()),
        subtitle: about.version_line().map(TextSource::Static),
        icon: about.icon_name().cloned().map(GroupIcon::Image),
        open: Rc::new(move || path.update(|p| p.push(SettingsRoute::About))),
    });
    let groups = inst
        .visible_groups()
        .into_iter()
        .map(|g| {
            let id = g.id;
            RootEntry {
                id: id.to_string(),
                title: g.title.clone(),
                subtitle: g.subtitle.clone(),
                icon: g.icon.clone(),
                open: Rc::new(move || {
                    path.update(|p| p.push(SettingsRoute::Group(id.to_string())));
                }),
            }
        })
        .collect();
    (about, groups)
}

/// The mobile root page: the arm's native grouped list where one exists, else composed.
fn root_page(inst: Rc<Installed>) -> AnyPiece {
    #[cfg(all(feature = "uikit", target_os = "ios"))]
    {
        if let Some(p) = uikit_impl::root_page(inst.clone()) {
            return p;
        }
    }
    #[cfg(all(feature = "material", target_os = "android"))]
    {
        if let Some(p) = android_impl::root_page(inst.clone()) {
            return p;
        }
    }
    #[cfg(all(feature = "arkui", target_env = "ohos"))]
    {
        if let Some(p) = arkui_impl::root_page(inst.clone()) {
            return p;
        }
    }
    composed_root_page(inst)
}

/// The mobile root page from ordinary Day pieces: the About header card, then the groups as
/// chevron rows (one group: its rows inline under the header).
#[expect(
    clippy::needless_pass_by_value,
    reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
)]
fn composed_root_page(inst: Rc<Installed>) -> AnyPiece {
    let mut parts: Vec<AnyPiece> = Vec::new();
    if let Some(about) = &inst.about {
        parts.push(about_header(inst.clone(), about));
    }
    let groups = inst.visible_groups();
    if groups.len() == 1 {
        let g = groups[0];
        for s in &g.sections {
            if let Some(p) = section_piece(inst.clone(), s, false) {
                parts.push(p);
            }
        }
        if let Some(custom) = &g.custom {
            parts.push(custom());
        }
    } else {
        let rows: Vec<AnyPiece> = groups
            .iter()
            .map(|g| {
                let id = g.id;
                let path = inst.path;
                let titles = match &g.subtitle {
                    Some(sub) => column((
                        text_label(&g.title),
                        text_label(sub).font(day_spec::Font::Footnote).secondary(),
                    ))
                    .spacing(2.0)
                    .align(HAlign::Leading)
                    .any(),
                    None => text_label(&g.title).any(),
                };
                // A bundled vector draws as an image; a standard glyph has no image name, so
                // it draws as a plain icon-only button that opens the same page (the only piece
                // that renders a `Symbol` on every toolkit). No icon: an empty slot keeps the
                // titles of iconed and icon-less rows aligned.
                // A standard glyph draws from day-spec's shared outline as a template image
                // (an icon-only button would bring the toolkit's button chrome with it: on
                // the web a pill that squashed the glyph). No icon: an empty slot keeps the
                // titles of iconed and icon-less rows aligned.
                let leading = match &g.icon {
                    Some(GroupIcon::Image(name)) => {
                        image(name.clone()).template().frame(24.0, 24.0).any()
                    }
                    Some(GroupIcon::Symbol(sym)) => match sym.outline_svg() {
                        Some(svg) => image(svg.into_bytes()).template().frame(24.0, 24.0).any(),
                        None => spacer().frame(24.0, 24.0).any(),
                    },
                    None => spacer().frame(24.0, 24.0).any(),
                };
                row((leading, titles, spacer(), label("›").secondary()))
                    .spacing(12.0)
                    .align(VAlign::Center)
                    .grow(Dimension::Width)
                    .on_tap(move || path.update(|p| p.push(SettingsRoute::Group(id.to_string()))))
                    .id(day_core::id!(prefs_group, id))
                    .any()
            })
            .collect();
        parts.push(section(rows).any());
    }
    scroll(
        form(parts)
            .padding(16.0)
            .grow(Dimension::Width)
            .id(day_core::id!(settings_root)),
    )
    .any()
}

/// The About header card on the mobile root: icon, name, version; tapping opens the About page.
#[expect(
    clippy::needless_pass_by_value,
    reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
)]
fn about_header(inst: Rc<Installed>, about: &About) -> AnyPiece {
    let path = inst.path;
    let name = about.display_name();
    let version = about.version_line().unwrap_or_default();
    let icon = match about.icon_name() {
        Some(n) => image(n.clone()).frame(48.0, 48.0).corner_radius(10.0).any(),
        None => column(()).any(),
    };
    section((row((
        icon,
        column((
            label(name).bold(),
            label(version).font(day_spec::Font::Footnote).secondary(),
        ))
        .spacing(2.0)
        .align(HAlign::Leading),
        spacer(),
        label("›").secondary(),
    ))
    .spacing(12.0)
    .align(VAlign::Center)
    .grow(Dimension::Width)
    .on_tap(move || path.update(|p| p.push(SettingsRoute::About)))
    .id(day_core::id!(settings_about)),))
    .any()
}

/// The composed About page: icon, name, version, tagline, links, credits, licenses, copyright.
#[expect(
    clippy::needless_pass_by_value,
    reason = "every settings builder, per-toolkit ones included, takes the shared `Rc` by value"
)]
fn about_page(inst: Rc<Installed>) -> AnyPiece {
    let Some(about) = &inst.about else {
        return column(()).any();
    };
    if let Some(custom) = about.custom_piece() {
        return custom;
    }
    if inst.presentation == Presentation::Navigation {
        #[cfg(all(feature = "uikit", target_os = "ios"))]
        {
            if let Some(p) = uikit_impl::about_page(inst.clone()) {
                return p;
            }
        }
        #[cfg(all(feature = "material", target_os = "android"))]
        {
            if let Some(p) = android_impl::about_page(inst.clone()) {
                return p;
            }
        }
    }
    let mut head: Vec<AnyPiece> = Vec::new();
    if let Some(n) = about.icon_name() {
        head.push(image(n.clone()).frame(96.0, 96.0).corner_radius(20.0).any());
    }
    head.push(
        label(about.display_name())
            .font(day_spec::Font::Title2)
            .bold()
            .id(day_core::id!(about_name))
            .any(),
    );
    if let Some(v) = about.version_line() {
        head.push(label(v).secondary().id(day_core::id!(about_version)).any());
    }
    if let Some(t) = about.tagline_text() {
        head.push(label(t).id(day_core::id!(about_tagline)).any());
    }
    let mut parts: Vec<AnyPiece> = vec![
        column(head)
            .spacing(6.0)
            .align(HAlign::Center)
            .grow(Dimension::Width)
            .any(),
    ];
    // Ids by position (`about-link-0`, …) and `about-privacy`: what a walkthrough asserts.
    let mut links: Vec<AnyPiece> = about
        .links()
        .iter()
        .enumerate()
        .map(|(i, (t, url))| {
            link(text_source_fn(t), url.clone())
                .id(day_core::id!(about_link, i))
                .any()
        })
        .collect();
    if let Some(p) = about.privacy_url() {
        links.push(
            link(
                day_localization_ui::res::str::day_about_privacy(),
                p.to_string(),
            )
            .id(day_core::id!(about_privacy))
            .any(),
        );
    }
    if !links.is_empty() {
        parts.push(section(links).any());
    }
    let mut notes: Vec<AnyPiece> = Vec::new();
    if let Some(c) = about.credits_text() {
        let credits = c.clone();
        notes.push(
            rows::navigate(
                day_localization_ui::res::str::day_about_acknowledgements(),
                move || scroll(label(credits.clone()).padding(16.0)),
            )
            .into_piece(inst.clone()),
        );
    }
    if let Some(l) = about.licenses_text() {
        let licenses = l.clone();
        notes.push(
            rows::navigate(
                day_localization_ui::res::str::day_about_licenses(),
                move || scroll(label(licenses.clone()).monospace().padding(16.0)),
            )
            .into_piece(inst.clone()),
        );
    }
    if !notes.is_empty() {
        parts.push(section(notes).any());
    }
    if let Some(c) = about.copyright_text() {
        parts.push(
            label(c)
                .font(day_spec::Font::Footnote)
                .secondary()
                .id(day_core::id!(about_copyright))
                .any(),
        );
    }
    let body = form(parts)
        .padding(20.0)
        .grow(Dimension::Width)
        .id(day_core::id!(about_page));
    // The About window fits its content like the settings panel and scrolls past the height
    // it can have; a pushed page scrolls.
    if inst.presentation == Presentation::Window {
        hugging_scroll(body).any()
    } else {
        scroll(body).any()
    }
}

/// A vertical scroll that hugs its content: it measures as tall as the content up to the
/// height it is offered, so a window that fits its content (`size_to_fit`) still shrinks to a
/// short page, and a page taller than the window can be scrolls instead of clipping. Day's
/// `scroll` takes the whole proposal, which would pin a fitted window at its ceiling.
fn hugging_scroll<P: Piece>(child: P) -> impl Piece {
    day_core::piece_fn(move |cx: &mut day_core::BuildCx| {
        let node = cx.native(
            day_spec::kinds::SCROLL,
            &day_spec::props::ScrollProps {
                horizontal: false,
                ..Default::default()
            },
            Rc::new(HuggingScrollLayout),
            day_core::Flex {
                grow_w: true,
                ..Default::default()
            },
            day_core::Boundary::Yes,
        );
        cx.under(node, |cx| {
            let _ = child.build(cx);
        });
        node
    })
}

/// The layout behind [`hugging_scroll`]: `day_core::ScrollLayout` with a content-hugging
/// measure.
struct HuggingScrollLayout;

impl day_core::Layout for HuggingScrollLayout {
    fn measure(
        &self,
        cx: &mut dyn day_core::LayoutOps,
        children: &[day_core::RNode],
        p: day_spec::Proposal,
    ) -> day_spec::Size {
        let cs = match children.first() {
            Some(&c) => cx.measure_child(c, day_spec::Proposal::new(p.width, None)),
            None => day_spec::Size::ZERO,
        };
        let height = match p.height {
            Some(h) => cs.height.min(h),
            None => cs.height,
        };
        day_spec::Size::new(p.width.unwrap_or(cs.width), height)
    }
    fn place(
        &self,
        cx: &mut dyn day_core::LayoutOps,
        children: &[day_core::RNode],
        bounds: day_spec::Rect,
    ) {
        let Some(&c) = children.first() else {
            return;
        };
        let mut width = bounds.size.width;
        let mut cs = cx.measure_child(c, day_spec::Proposal::new(Some(width), None));
        if cs.height > bounds.size.height {
            // A classic scroll bar takes room from the viewport; lay the content out beside it.
            let inset = cx.scroll_bar_inset(true);
            if inset > 0.0 {
                width = (width - inset).max(0.0);
                cs = cx.measure_child(c, day_spec::Proposal::new(Some(width), None));
            }
        }
        let content = day_spec::Size::new(width, cs.height.max(bounds.size.height));
        cx.place_child(c, day_spec::Rect::from_size(content));
        cx.set_scroll_content(content);
    }
}

impl Row {
    /// Build this row as a piece for `inst`'s presentation (what sections do internally).
    fn into_piece(self, inst: Rc<Installed>) -> AnyPiece {
        let desktop = inst.presentation == Presentation::Window;
        row_piece(inst, &self, desktop)
    }
}

// ===========================================================================
// Conformance cases (docs/testing.md)
// ===========================================================================

/// The settings surface's conformance cases.
#[cfg(feature = "conformance")]
pub mod conformance {
    // Synthetic shared store: assertions observe exactly the store the fixture installed.
    struct SharedTestStore(std::rc::Rc<super::MemoryStore>);
    impl super::Store for SharedTestStore {
        fn get(&self, key: &str) -> Option<String> {
            self.0.get(key)
        }
        fn set(&self, key: &str, value: &str) -> bool {
            self.0.set(key, value)
        }
        fn remove(&self, key: &str) -> bool {
            self.0.remove(key)
        }
    }

    use day_core::conformance::{Case, Drive};
    use day_spec::Cap;

    use super::*;

    static SOUND: Pref<bool> = Pref::new("conformance.sound", || true);
    static SCALE: Pref<f64> = Pref::new("conformance.scale", || 100.0);

    /// A real Windows card must reflow its control before its header becomes a column of
    /// broken words, while keeping a roomy card horizontal.
    #[cfg(all(feature = "xaml", target_os = "windows"))]
    #[day_macros::test(day_core)]
    fn settings_card_keeps_header_readable() -> Case {
        Case::new()
            .proves("day-piece-settings.row")
            .page(|| {
                let inst = Rc::new(Installed {
                    in_nav: Default::default(),
                    about: None,
                    groups: Vec::new(),
                    presentation: Presentation::Window,
                    title: TextSource::Static("Settings".into()),
                    selected: Signal::new(String::new()),
                    path: Signal::new(Vec::new()),
                });
                let narrow = xaml_impl::row_piece(
                    inst.clone(),
                    &appearance_row().id(day_core::id!(settings::narrow_theme)),
                    true,
                )
                .unwrap();
                let wide = xaml_impl::row_piece(
                    inst,
                    &appearance_row().id(day_core::id!(settings::wide_theme)),
                    true,
                )
                .unwrap();
                column((
                    narrow.id(day_core::id!(settings::narrow_card)).width(250.0),
                    wide.id(day_core::id!(settings::wide_card)).width(520.0),
                ))
            })
            .drive(|d: Drive| async move {
                for (card_id, control_id, stacked) in [
                    ("settings::narrow_card", "settings::narrow_theme", true),
                    ("settings::wide_card", "settings::wide_theme", false),
                ] {
                    d.assert_frame(card_id, day_core::conformance::FrameExpect {
                        width: Some(if stacked { 250.0 } else { 520.0 }),
                        ..Default::default()
                    }).await?;
                    let (card, control) = day_core::with_tree(|t| {
                        let card = t
                            .read_native(t.find_by_id(card_id).unwrap())
                            .unwrap()
                            .frame
                            .unwrap();
                        let control = t
                            .read_native(t.find_by_id(control_id).unwrap())
                            .unwrap()
                            .frame
                            .unwrap();
                        (card, control)
                    });
                    let y = control.origin.y - card.origin.y;
                    d.check(
                        if stacked { y >= 48.0 } else { y < 40.0 },
                        "the theme control must move below its header only in a narrow card",
                    )?;
                    d.check(
                        control.origin.x >= card.origin.x + 15.0
                            && control.origin.x + control.size.width
                                <= card.origin.x + card.size.width - 15.0,
                        &format!("the theme control must remain within the card padding: {card:?}, {control:?}"),
                    )?;
                }
                d.select("settings::narrow_theme", 1).await?;
                d.check(
                    APPEARANCE.get_untracked() == Appearance::Dark,
                    "reflowed theme control must remain interactive",
                )?;
                d.select("settings::narrow_theme", 2).await
            })
    }

    /// Choosing a theme applies it and persists; System clears the stored key again.
    #[day_macros::test(day_core)]
    fn settings_theme_applies_and_persists() -> Case {
        let store = Rc::new(MemoryStore::default());
        let page_store = store.clone();
        Case::new()
            .proves_cap(Cap::Appearance)
            .proves_duty("set_appearance")
            .requires(Cap::Appearance)
            .page(move || {
                install_store(SharedTestStore(page_store.clone()));
                let inst = Rc::new(Installed {
                    in_nav: Cell::default(),
                    about: None,
                    groups: vec![Group::new("general", "General").row(appearance_row())],
                    presentation: Presentation::Window,
                    title: TextSource::Static("Settings".into()),
                    selected: Signal::new(String::new()),
                    path: Signal::new(Vec::new()),
                });
                let g = inst.groups[0].clone();
                column((group_page(inst, &g, true),))
            })
            .drive(move |d: Drive| {
                let store = store.clone();
                async move {
                    d.select(day_core::id!(theme_picker).as_str(), 1).await?;
                    d.wait_idle().await?;
                    d.check(
                        store.get("day.appearance").as_deref() == Some("dark"),
                        "dark not saved",
                    )?;
                    d.select(day_core::id!(theme_picker).as_str(), 2).await?;
                    d.wait_idle().await?;
                    d.check(
                        store.get("day.appearance").is_none(),
                        "System (the default) did not clear the key",
                    )
                }
            })
    }

    /// A toggle row and a slider row round-trip through the store.
    #[day_macros::test(day_core)]
    fn settings_rows_persist() -> Case {
        let store = Rc::new(MemoryStore::default());
        let page_store = store.clone();
        Case::new()
            .page(move || {
                install_store(SharedTestStore(page_store.clone()));
                let inst = Rc::new(Installed {
                    in_nav: Cell::default(),
                    about: None,
                    groups: vec![
                        Group::new("sound", "Sound")
                            .row(rows::toggle(&SOUND, "Sounds"))
                            .row(rows::slider(&SCALE, "Scale", 50.0..=200.0).step(10.0)),
                    ],
                    presentation: Presentation::Window,
                    title: TextSource::Static("Settings".into()),
                    selected: Signal::new(String::new()),
                    path: Signal::new(Vec::new()),
                });
                let g = inst.groups[0].clone();
                column((group_page(inst, &g, true),))
            })
            .drive(move |d: Drive| {
                let store = store.clone();
                async move {
                    d.toggle(day_core::id!(pref, "conformance.sound").as_str(), false)
                        .await?;
                    d.wait_idle().await?;
                    d.check(!SOUND.get_untracked(), "toggle did not write the pref")?;
                    d.check(
                        store.get("conformance.sound").as_deref() == Some("false"),
                        "toggle did not persist",
                    )?;
                    d.set_value(day_core::id!(pref, "conformance.scale").as_str(), 150.0)
                        .await?;
                    d.wait_idle().await?;
                    d.check(
                        (SCALE.get_untracked() - 150.0).abs() < 0.5,
                        "slider did not write the pref",
                    )?;
                    SOUND.reset();
                    d.check(
                        store.get("conformance.sound").is_none(),
                        "reset did not remove the key",
                    )
                }
            })
    }

    static COUNT: Pref<i64> = Pref::new("conformance.count", || 3);

    /// A row's enabled gate reaches every interactive control the row builds: a stepper's two
    /// buttons stay disabled while the gate is off, however the bounds would allow a step.
    #[day_macros::test(day_core)]
    fn settings_row_enabled_gates_stepper() -> Case {
        let gate = Signal::new(false);
        Case::new()
            .page(move || {
                let inst = Rc::new(Installed {
                    in_nav: Cell::default(),
                    about: None,
                    groups: vec![
                        Group::new("counts", "Counts")
                            .row(rows::stepper(&COUNT, "Count", 0..=10).enabled(gate)),
                    ],
                    presentation: Presentation::Window,
                    title: TextSource::Static("Settings".into()),
                    selected: Signal::new(String::new()),
                    path: Signal::new(Vec::new()),
                });
                let g = inst.groups[0].clone();
                column((
                    group_page(inst, &g, true),
                    button("Enable")
                        .action(move || gate.set(true))
                        .id(day_core::id!(settings::enable)),
                ))
            })
            .drive(|d: Drive| async move {
                let count = day_core::id!(pref, "conformance.count");
                let increment = day_core::id!(pref_increment, count.as_str());
                let decrement = day_core::id!(pref_decrement, count.as_str());
                d.assert_enabled(increment.as_str(), false).await?;
                d.assert_enabled(decrement.as_str(), false).await?;
                d.tap("settings::enable").await?;
                d.wait_idle().await?;
                d.assert_enabled(increment.as_str(), true).await?;
                d.assert_enabled(decrement.as_str(), true).await?;
                let initial = COUNT.get_untracked();
                d.assert_text(count.as_str(), &initial.to_string()).await?;
                d.tap(increment.as_str()).await?;
                d.assert_text(count.as_str(), &(initial + 1).to_string())
                    .await?;
                d.tap(decrement.as_str()).await?;
                d.assert_text(count.as_str(), &initial.to_string()).await
            })
    }
}