day-pieces 0.6.1

Declarative app development API using native UI toolkits
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
// Copyright © The Daybrite Project
// SPDX-License-Identifier: MPL-2.0

//! `Decorate`, the chainable modifiers every piece inherits: padding and sizing, background and
//! corner radius, gestures (`on_tap`, drag), accessibility (`A11yBuilder`), and native-handle
//! capture (`NativeRef`), plus the `Modifier` / `IntoInsets` supporting traits.
//!
//! Modifiers return [`Decorated<P>`], which keeps the decorated piece's type, so a chain
//! never stops reaching that piece's builder methods (§5.2).

use std::cell::Cell;
use std::rc::Rc;

use day_core::*;
use day_reactive::{Scope, bind};
use day_spec::props::*;
use day_spec::{A11yProps, AnimSpec, Color, Cursor, Event, Insets, Role, Transform, kinds};

use crate::menus::lower_menu_scoped;
use crate::*;

// ---------------------------------------------------------------------------
// Decorators (§5.2 Decorate)
// ---------------------------------------------------------------------------

pub trait IntoInsets {
    fn into_insets(self) -> Insets;
}
impl IntoInsets for f64 {
    fn into_insets(self) -> Insets {
        Insets::all(self)
    }
}
impl IntoInsets for Insets {
    fn into_insets(self) -> Insets {
        self
    }
}

/// A one-shot, by-value view transform (the SwiftUI `ViewModifier` analog): wrap a piece into a
/// new one. Pure composition, with no per-backend work. A plain `FnOnce(AnyPiece) -> AnyPiece`
/// closure is a `Modifier` too (the blanket impl below), so the common case needs no new type.
/// Apply one with [`Decorate::modifier`].
///
/// **`AnyPiece` here is a trade, not a requirement.** It is not object safety: a `Modifier` is
/// never stored as `dyn Modifier`, and [`Decorate::modifier`] takes `impl Modifier` and applies
/// it on the spot. It is the closure impl below. A closure has one fixed parameter type, and
/// Rust has no `for<P> FnOnce(P) -> _` bound (higher-ranked bounds range over lifetimes, not
/// types), so making `apply` generic over the content (`fn apply<P: Piece>(self, c: P) ->
/// Self::Out<P>`, which a named modifier can satisfy with a GAT) would leave no closure able to
/// implement the trait at all. Pinning the input to the one piece type that accepts anything is
/// what keeps `|p| …` a modifier, and the erasure is what that costs, which is why this is the
/// single `Decorate` method that erases.
///
/// If a modifier ever needs to preserve its content's type, parameterize the trait rather than
/// the method: `trait Modifier<P: Piece> { type Out: Piece; fn apply(self, c: P) -> Self::Out; }`.
/// Closures survive that (`impl<P: Piece, O: Piece, F: FnOnce(P) -> O> Modifier<P> for F`, and
/// their parameter still infers unannotated), while a named modifier such as day-piece-rating's
/// `Card` becomes `impl<P: Piece> Modifier<P> for Card` with `type Out = Decorated<P>`. The bill
/// is a `Decorate::modifier` whose return type varies per modifier, a generic impl for every
/// named one, and a breaking change: not worth paying while the tree has two implementors.
pub trait Modifier {
    fn apply(self, content: AnyPiece) -> AnyPiece;
}

impl<F> Modifier for F
where
    F: FnOnce(AnyPiece) -> AnyPiece,
{
    fn apply(self, content: AnyPiece) -> AnyPiece {
        self(content)
    }
}

/// A liveness-checked reference to a mounted piece's realized node: the retained half of the
/// tweaks API (docs/tweaks.md). Capture one with [`Decorate::native_ref`], then reach the native
/// widget later (from event handlers, timers) through a toolkit ext accessor. `node`/`with` yield
/// `None` before mount and after the node's subtree is disposed, so async races are safe no-ops.
///
/// Reads are reactive: inside a binding or memo, `node()` subscribes to the ref's mount/clear
/// transitions (a `Trigger` underneath), so a label like
/// `label(move || if r.node().is_some() { "live" } else { "cleared" })` updates when the
/// referenced piece unmounts, as in the toggle demo on the showcase Tweaks page. (The
/// `when`-arm's disposal lands at the turn boundary, after ordinary bindings re-ran;
/// piggybacking on some other signal would read a stale mount state, while the trigger fires
/// at the actual transition.) Main-thread only, like every realized-tree type.
#[derive(Clone)]
pub struct NativeRef {
    cell: Rc<std::cell::Cell<Option<day_core::RNode>>>,
    changed: day_reactive::Trigger,
}

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

impl NativeRef {
    pub fn new() -> Self {
        NativeRef {
            cell: Rc::new(std::cell::Cell::new(None)),
            changed: day_reactive::Trigger::new(),
        }
    }

    /// The mounted node, if it is currently live. A tracked read (see the type docs).
    pub fn node(&self) -> Option<day_core::RNode> {
        self.changed.track();
        let node = self.cell.get()?;
        // Generational slotmap keys make a disposed node a clean miss, never a stale hit.
        let live = day_core::try_with_tree(|t| t.node_kind(node).is_some()).unwrap_or(false);
        live.then_some(node)
    }

    /// Run `f` with the live node (e.g. inside `day_toolkit_appkit::with_native`); `None` if disposed.
    pub fn with<R>(&self, f: impl FnOnce(day_core::RNode) -> R) -> Option<R> {
        self.node().map(f)
    }

    fn transition(&self, node: Option<day_core::RNode>) {
        self.cell.set(node);
        self.changed.notify();
    }
}

/// A transparent native layer node (`CONTAINER`, no fill/clip/corner) used by the animatable
/// modifiers (`.opacity`/`.transform`) to carry a per-node opacity or transform. Layout-transparent (`FillThrough`), so it never affects sizing and a
/// granted stretch flows through to what it paints.
fn layer_node(cx: &mut BuildCx) -> RNode {
    cx.native(
        kinds::CONTAINER,
        &ContainerProps {
            background: None,
            corner_radius: 0.0,
            clips: false,
            role: None,
        },
        Rc::new(FillThrough),
        Flex::default(),
        Boundary::No,
    )
}

// ---------------------------------------------------------------------------
// Decorated: a piece plus its modifiers, with the piece's type kept (§5.2)
// ---------------------------------------------------------------------------

/// The build of a piece plus every modifier applied to it so far.
type Build = Box<dyn FnOnce(&mut BuildCx) -> RNode>;

/// A piece with modifiers chained onto it, keeping the decorated piece's type (§5.2).
///
/// Every [`Decorate`] modifier returns one of these rather than erasing to [`AnyPiece`], which is
/// what lets a chain keep reaching the piece's builder methods: `label(…).padding(8.0)` is
/// still a decorated `Label`, so `.font(…)` after it resolves. Modifiers applied to a `Decorated`
/// append in place (the inherent methods below shadow the trait's), so a chain stays flat instead
/// of nesting `Decorated<Decorated<…>>`.
///
/// Modifiers fall into three classes (docs/api-style.md "Modifier classes"), and only one of
/// them is ordered:
///
/// - **Identity** (`id`, `id_of`) names the piece's own node, the one its build
///   returns, wherever it sits in the chain: `label(t).padding(8.0).id(day_core::id!(x))` and
///   `label(t).id(day_core::id!(x)).padding(8.0)` are the same tree.
/// - **Wrapping** modifiers (`padding`, `frame`, `background`, `grow`, …) each add a node around
///   what came before, so they compose outward in call order, as they read.
/// - **Outer-layout facts** (`grid_span`, `grid_align`) describe the piece to the container it
///   sits in, so they land on the outermost node whatever wrappers follow them.
///
/// `wrapper_id` is the one way to name a wrapper deliberately: it tags whatever node is
/// outermost at the point it is called, for a frame assertion on a padded box.
///
/// Erase explicitly with `.any()` when a single [`AnyPiece`] is what's needed (a `Vec<AnyPiece>`, a
/// `-> AnyPiece` signature).
pub struct Decorated<P> {
    inner: P,
    /// Wrapping modifiers, applied outward in call order.
    ops: Vec<Box<dyn FnOnce(Build) -> Build>>,
    /// Identity modifiers, applied to the node the piece's own build returns.
    node_ops: Vec<Box<dyn FnOnce(RNode)>>,
    /// Outer-layout facts, applied to the outermost node once every wrapper is in place.
    outer_ops: Vec<Box<dyn FnOnce(RNode)>>,
}

impl<P: Piece> Decorated<P> {
    /// An undecorated piece, ready to have modifiers applied CONDITIONALLY. Starting here gives
    /// every branch the same type, so an optional modifier needs no erasure:
    ///
    /// ```ignore
    /// let leaf = Decorated::new(draw);
    /// let leaf = match id { Some(id) => leaf.id(id), None => leaf };
    /// let leaf = if editable { leaf.on_tap(f) } else { leaf };
    /// ```
    ///
    /// [`apply_if`](Self::apply_if) and [`apply_some`](Self::apply_some) are the same move as a
    /// chain step.
    pub fn new(inner: P) -> Self {
        Decorated {
            inner,
            ops: Vec::new(),
            node_ops: Vec::new(),
            outer_ops: Vec::new(),
        }
    }

    fn push(mut self, op: impl FnOnce(Build) -> Build + 'static) -> Self {
        self.ops.push(Box::new(op));
        self
    }

    fn push_node(mut self, op: impl FnOnce(RNode) + 'static) -> Self {
        self.node_ops.push(Box::new(op));
        self
    }

    fn push_outer(mut self, op: impl FnOnce(RNode) + 'static) -> Self {
        self.outer_ops.push(Box::new(op));
        self
    }

    /// Replace the undecorated piece, keeping the modifier chain: how a typed builder trait
    /// reaches through a decoration (docs/api-style.md "Typed builders"). `f` sees the piece as
    /// it was before any modifier, which is why modifier order stops mattering.
    pub fn map_inner<Q: Piece>(self, f: impl FnOnce(P) -> Q) -> Decorated<Q> {
        Decorated {
            inner: f(self.inner),
            ops: self.ops,
            node_ops: self.node_ops,
            outer_ops: self.outer_ops,
        }
    }

    /// Apply `f` to the chain when `cond` holds, else continue unchanged: the conditional
    /// modifier, with no `let x = if c { x.m() } else { x }` rebinding and no erasure.
    ///
    /// ```ignore
    /// nav(sel).apply_if(!primary, |n| n.local())
    /// ```
    ///
    /// `cond` is a plain `bool` resolved at build, like the arms of a `match`; the modifiers
    /// `f` applies may themselves be reactive.
    pub fn apply_if(self, cond: bool, f: impl FnOnce(Self) -> Self) -> Self {
        if cond { f(self) } else { self }
    }

    /// Apply `f` with the value when there is one, else continue unchanged:
    /// `canvas(draw).apply_some(id, |c, id| c.id(id))`.
    pub fn apply_some<T>(self, value: Option<T>, f: impl FnOnce(Self, T) -> Self) -> Self {
        match value {
            Some(v) => f(self, v),
            None => self,
        }
    }
}

impl<P: Piece> Piece for Decorated<P> {
    fn build(self, cx: &mut BuildCx) -> RNode {
        let Decorated {
            inner,
            ops,
            node_ops,
            outer_ops,
        } = self;
        // The piece's own node first, with its identity; then the wrappers, composed outward
        // in call order (the first modifier is innermost); then the facts for the parent, on
        // whatever ended up outermost.
        let wraps = !ops.is_empty();
        let own = Rc::new(Cell::new(None::<RNode>));
        let own_out = own.clone();
        let mut build: Build = Box::new(move |cx| {
            let n = inner.build(cx);
            for op in node_ops {
                op(n);
            }
            own_out.set(Some(n));
            n
        });
        for op in ops {
            build = op(build);
        }
        let outer = build(cx);
        // The span a gesture addressed to the piece's own node (where `.id` sits) climbs to
        // reach a wrapper's `.on_tap` (day-core's `gesture_target`).
        if wraps && let Some(n) = own.get() {
            with_tree(|t| t.set_element_outer(n, outer));
        }
        for op in outer_ops {
            op(outer);
        }
        outer
    }
}

// --- The modifier bodies, written once and shared by the trait and the inherent impl ---

fn op_id(id: day_core::ElementId) -> impl FnOnce(RNode) {
    move |n| with_tree(|t| t.set_id(n, id.as_str().to_owned()))
}

fn op_id_of(id: impl Fn() -> day_core::ElementId + 'static) -> impl FnOnce(RNode) {
    move |n| {
        day_reactive::bind(id, move |s: &day_core::ElementId| {
            let s = s.as_str().to_owned();
            with_tree(|t| t.set_id(n, s));
        });
    }
}

/// Name whatever node is outermost at this point in the chain (see [`Decorated::wrapper_id`]).
fn op_wrapper_id(id: day_core::ElementId) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let n = inner(cx);
            with_tree(|t| t.set_id(n, id.as_str().to_owned()));
            n
        })
    }
}

fn op_tweak(f: impl FnOnce(day_core::RNode) + 'static) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let n = inner(cx);
            f(n);
            // Mark the node so a later backing swap (`.selectable()` on a toolkit that
            // rebuilds the widget) warns about the discarded tweak instead of losing it
            // silently (docs/tweaks.md).
            with_tree(|t| t.note_node_tweaked(n));
            n
        })
    }
}

fn op_selectable() -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let n = inner(cx);
            with_tree(|t| t.set_node_selectable(n, true));
            n
        })
    }
}

fn op_cursor(cursor: Reactive<Cursor>) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let n = inner(cx);
            with_tree(|t| t.set_node_cursor(n, cursor.get_untracked()));
            // Only a reactive source needs a binding; a constant shape is applied once at
            // mount. The setter is idempotent, so a re-run costs one native call.
            if let Reactive::Dyn(_) = &cursor {
                bind(
                    move || cursor.get(),
                    move |c: &Cursor| {
                        with_tree(|t| t.set_node_cursor(n, c.clone()));
                    },
                );
            }
            n
        })
    }
}

fn op_window_drag_region() -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let n = inner(cx);
            with_tree(|t| t.set_node_drag_region(n, true));
            n
        })
    }
}

fn op_native_ref(r: NativeRef) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let n = inner(cx);
            r.transition(Some(n));
            let cleared = r.clone();
            Scope::current().on_cleanup(move || cleared.transition(None));
            n
        })
    }
}

fn op_padding(insets: Insets) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let w = cx.layout_only(
                Rc::new(PaddingLayout { insets }),
                Flex::default(),
                Boundary::No,
            );
            cx.under(w, |cx| {
                let _ = inner(cx);
            });
            w
        })
    }
}

fn op_max_width(max: f64) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let w = cx.layout_only(
                Rc::new(MaxWidthLayout { max }),
                Flex::default(),
                Boundary::No,
            );
            cx.under(w, |cx| {
                let _ = inner(cx);
            });
            w
        })
    }
}

fn op_max_height(max: f64) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            // Yielding, so a column sizes its other children first and gives this one what is
            // left, up to `max`: a capped scroll gives way to the button under it on a short
            // screen instead of pushing it out of the column, and the column still hugs.
            let h = cx.layout_only(
                Rc::new(day_core::MaxHeightLayout { max }),
                Flex {
                    yields_h: true,
                    ..Flex::default()
                },
                Boundary::No,
            );
            cx.under(h, |cx| {
                let _ = inner(cx);
            });
            h
        })
    }
}

fn op_min_width(min: f64) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let w = cx.layout_only(
                Rc::new(day_core::MinWidthLayout { min }),
                Flex::default(),
                Boundary::No,
            );
            cx.under(w, |cx| {
                let _ = inner(cx);
            });
            w
        })
    }
}

fn op_reserving(sample: String) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let w = cx.layout_only(
                Rc::new(day_core::ReserveLayout),
                Flex::default(),
                Boundary::No,
            );
            cx.under(w, |cx| {
                // children[0]: the measured-but-invisible sample.
                let _ = crate::label(sample.clone()).opacity(0.0).build(cx);
                // children[1]: the real content.
                let _ = inner(cx);
            });
            w
        })
    }
}

/// `frame`/`width`/`height`: a fixed size on one or both axes. Two fixed axes make a layout
/// boundary (§7.4); one does not.
fn op_frame(
    width: Option<f64>,
    height: Option<f64>,
    boundary: Boundary,
) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let w = cx.layout_only(
                Rc::new(FrameLayout { width, height }),
                Flex::default(),
                boundary,
            );
            cx.under(w, |cx| {
                let _ = inner(cx);
            });
            w
        })
    }
}

fn op_a11y(f: impl FnOnce(A11yBuilder) -> A11yBuilder + 'static) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let n = inner(cx);
            let (props, live, selected) = f(A11yBuilder::default()).split();
            let seed = props.selected;
            with_tree(|t| t.set_a11y(n, props));
            // The selected state follows its signal the same way: re-sent alone, merged by
            // day-core onto the node's set.
            if let Some(selected) = selected {
                day_reactive::bind_seeded(
                    seed.unwrap_or(false),
                    move || selected.get(),
                    move |on: &bool| {
                        with_tree(|t| {
                            t.set_a11y(
                                n,
                                A11yProps {
                                    selected: Some(*on),
                                    ..Default::default()
                                },
                            )
                        })
                    },
                );
            }
            // A string that reads a signal or the locale re-sends itself alone; day-core
            // merges it onto the node's set and re-applies the whole picture (§13).
            for (src, patch) in live {
                if let TextSource::Dyn(read) = src {
                    let seed = day_reactive::untrack(|| read());
                    day_reactive::bind_seeded(
                        seed,
                        move || read(),
                        move |s: &String| with_tree(|t| t.set_a11y(n, patch(s.clone()))),
                    );
                }
            }
            n
        })
    }
}

fn op_on_tap(f: impl Fn() + 'static) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let n = inner(cx);
            with_tree(|t| t.enable_gesture(n, GestureKind::Tap));
            cx.on(n, move |ev| {
                if matches!(ev, Event::Tap(_)) {
                    f();
                }
            });
            n
        })
    }
}

fn op_on_tap_at(f: impl Fn(day_spec::Point) + 'static) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let n = inner(cx);
            with_tree(|t| t.enable_gesture(n, GestureKind::Tap));
            cx.on(n, move |ev| {
                if let Event::Tap(p) = ev {
                    f(*p);
                }
            });
            n
        })
    }
}

fn op_on_key(f: impl Fn(&day_spec::KeyEvent) + 'static) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let n = inner(cx);
            // Declare the intent as well as listening: a backend whose focused view would have
            // to claim the key from the platform's dispatch checks this first. That check runs
            // on the view, which sits below `n` when `n` is a layout wrapper (`.frame(..)`), so
            // the view is marked too; the key it claims reaches this handler through the
            // wrapper (day-core's dispatch).
            day_spec::keys::mark(day_core::rnode_to_id(n));
            if let Some(view) = with_tree(|t| t.native_view_of(n))
                && view != n
            {
                day_spec::keys::mark(day_core::rnode_to_id(view));
            }
            cx.on(n, move |ev| {
                if let Event::Key(k) = ev {
                    f(k);
                }
            });
            n
        })
    }
}

/// Declare toolbar items for the chrome this piece sits under (docs/toolbars.md).
///
/// The chrome is resolved where the piece is built, not where the modifier was written: the
/// innermost navigation page being built, or the window when there is none. The design exists so
/// that a command sits beside the content it acts on, and the app never says twice which bar it
/// belongs to.
fn op_toolbar(source: crate::ToolbarSource) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let n = inner(cx);
            crate::contribute(day_core::current_chrome(), source);
            n
        })
    }
}

fn op_focusable() -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let n = inner(cx);
            with_tree(|t| t.set_focusable(n, true));
            n
        })
    }
}

fn op_focused(
    want: Box<dyn Fn() -> bool>,
    on_native: Box<dyn Fn(bool)>,
) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let n = inner(cx);
            // Echo cell: the control's focus state as last reported by the native side. An
            // apply whose desired state matches it is the echo of a native change (or already
            // satisfied) and must not re-drive the toolkit: the nav host echo-cell rule.
            let native = Rc::new(Cell::new(false));
            {
                let native = native.clone();
                cx.on(n, move |ev| {
                    if let Event::FocusChanged(f) = ev {
                        native.set(*f);
                        on_native(*f);
                    }
                });
            }
            // Signal → native, deferred one turn (`on_main`): focus is async by contract, and
            // the deferral also lets a mount-time `Some(K::V)` land after the widget is in the
            // window (dialog default focus). The initial `false` is not applied, because resigning
            // focus the control never had would steal it from whoever has it.
            let first = Cell::new(true);
            bind(want, move |want: &bool| {
                let want = *want;
                if first.replace(false) && !want {
                    return;
                }
                if native.get() == want {
                    return;
                }
                day_reactive::on_main(move || with_tree(|t| t.focus_node(n, want)));
            });
            n
        })
    }
}

fn op_context_menu(items: Vec<MenuEntry>) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            // The overlay host places the decorated subtree at its own bounds and the
            // composed-menu mount beside it (see `OverlayHost`; a plain sibling would sit
            // under a single-child layout, never placed).
            let w = cx.layout_only(Rc::new(OverlayHost), Flex::default(), Boundary::No);
            let mut n = w;
            cx.under(w, |cx| {
                n = inner(cx);
                // Scoped: the action closures die with the build scope, not the process;
                // an unscoped registration here leaks one closure per remount.
                let model = lower_menu_scoped(items);
                with_tree(|t| t.set_context_menu(n, model.clone()));
                // A backend with no native menu reports the summon instead; the composed
                // presenter replays the same lowered model (docs/menus.md).
                let model = std::rc::Rc::new(model);
                crate::menus::mount_composed_menu(cx, n, Rc::new(move |_p| (*model).clone()));
            });
            // Sized by its content, so a platform row stays one through the menu's wrapper.
            with_tree(|t| t.forward_whole_row(w, n));
            // Later ops decorate the content node: ids, gestures and menus belong to it,
            // while the wrapper only exists to keep the mount in the layout pass.
            n
        })
    }
}

/// The `.context_menu*` wrapper's layout: the decorated subtree fills the wrapper; every
/// other child (the composed menu's lazy mount) is layout-inert but must still be visited,
/// because a cover lays its content out from the size the backend reports, but only if the
/// place pass reaches it at all.
struct OverlayHost;

impl Layout for OverlayHost {
    fn measure(
        &self,
        cx: &mut dyn LayoutOps,
        children: &[day_core::RNode],
        p: day_spec::Proposal,
    ) -> day_spec::Size {
        match children.first() {
            Some(&c) => cx.measure_child(c, p),
            None => day_spec::Size::ZERO,
        }
    }
    fn place(&self, cx: &mut dyn LayoutOps, children: &[day_core::RNode], bounds: day_spec::Rect) {
        let mut it = children.iter();
        if let Some(&c) = it.next() {
            cx.place_child(c, day_spec::Rect::from_size(bounds.size));
        }
        for &c in it {
            cx.place_child(c, day_spec::Rect::ZERO);
        }
    }
    fn baseline(
        &self,
        cx: &mut dyn LayoutOps,
        children: &[day_core::RNode],
        size: day_spec::Size,
    ) -> Option<f64> {
        children.first().and_then(|&c| cx.baseline_of(c, size))
    }
}

fn op_context_menu_fn(
    f: Rc<dyn Fn(day_spec::Point) -> Vec<MenuEntry>>,
) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let w = cx.layout_only(Rc::new(OverlayHost), Flex::default(), Boundary::No);
            let mut out = w;
            cx.under(w, |cx| {
                out = op_context_menu_fn_body(inner, f, cx);
            });
            // Sized by its content, so a platform row stays one through the menu's wrapper.
            with_tree(|t| t.forward_whole_row(w, out));
            out
        })
    }
}

fn op_context_menu_fn_body(
    inner: Build,
    f: Rc<dyn Fn(day_spec::Point) -> Vec<MenuEntry>>,
    cx: &mut day_core::BuildCx,
) -> day_core::RNode {
    {
        {
            let n = inner(cx);
            // Each summon lowers a fresh menu whose action closures live in their own scope,
            // disposed when the next summon replaces them (and with the build scope at
            // teardown), so per-click menus never accumulate registrations.
            let last: Rc<std::cell::RefCell<Option<day_reactive::Scope>>> = Rc::default();
            {
                let last = last.clone();
                day_reactive::Scope::current().on_cleanup(move || {
                    if let Some(s) = last.borrow_mut().take() {
                        s.dispose();
                    }
                });
            }
            let provider: day_spec::ContextMenuFn = Rc::new(move |p| {
                if let Some(s) = last.borrow_mut().take() {
                    s.dispose();
                }
                let scope = day_reactive::Scope::child();
                let items = scope.enter(|| crate::menus::lower_menu_scoped(f(p)));
                *last.borrow_mut() = Some(scope);
                items
            });
            with_tree(|t| t.set_context_menu_fn(n, provider.clone()));
            // A backend with no native menu reports the summon instead; the composed
            // presenter calls the same provider there (docs/menus.md).
            crate::menus::mount_composed_menu(cx, n, provider);
            n
        }
    }
}

fn op_on_drag(f: impl Fn(Drag) + 'static) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let n = inner(cx);
            with_tree(|t| t.enable_gesture(n, GestureKind::Drag));
            cx.on(n, move |ev| {
                if let Event::Drag {
                    phase,
                    location,
                    translation,
                } = ev
                {
                    f(Drag {
                        phase: *phase,
                        location: *location,
                        translation: *translation,
                    });
                }
            });
            n
        })
    }
}

fn op_on_pinch(f: impl Fn(Pinch) + 'static) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let n = inner(cx);
            with_tree(|t| t.enable_gesture(n, GestureKind::Pinch));
            cx.on(n, move |ev| {
                if let Event::Pinch {
                    phase,
                    scale,
                    location,
                } = ev
                {
                    f(Pinch {
                        phase: *phase,
                        scale: *scale,
                        location: *location,
                    });
                }
            });
            n
        })
    }
}

fn op_on_hover(f: impl Fn(Option<day_spec::Point>) + 'static) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let n = inner(cx);
            with_tree(|t| t.enable_gesture(n, GestureKind::Hover));
            cx.on(n, move |ev| {
                if let Event::Hover { phase, location } = ev {
                    // `None` on exit rather than a phase the caller has to match on: what a
                    // hover handler wants to know is where the pointer IS, and "nowhere" is a
                    // state, not an event kind. It is also what makes a handler that writes a
                    // `Signal<Option<Point>>` a one-liner.
                    f(match phase {
                        day_spec::DragPhase::Ended => None,
                        _ => Some(*location),
                    });
                }
            });
            n
        })
    }
}

fn op_on_pan(f: impl Fn(Pan) + 'static) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let n = inner(cx);
            with_tree(|t| t.enable_gesture(n, GestureKind::Pan));
            cx.on(n, move |ev| {
                if let Event::Pan {
                    phase,
                    delta,
                    location,
                } = ev
                {
                    f(Pan {
                        phase: *phase,
                        delta: *delta,
                        location: *location,
                    });
                }
            });
            n
        })
    }
}

fn op_background(color: Reactive<Color>) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let node = cx.native(
                kinds::CONTAINER,
                &ContainerProps {
                    background: Some(color.get_untracked()),
                    corner_radius: 0.0,
                    clips: false,
                    role: None,
                },
                Rc::new(FillThrough),
                Flex::default(),
                Boundary::No,
            );
            cx.under(node, |cx| {
                let _ = inner(cx);
            });
            // Only a reactive source needs a binding; a constant fill is applied once at realize.
            if let Reactive::Dyn(_) = &color {
                bind(
                    move || color.get(),
                    move |c: &Color| {
                        with_tree(|t| {
                            t.patch(node, Box::new(ContainerPatch::Background(Some(*c))), false)
                        });
                    },
                );
            }
            node
        })
    }
}

/// A semantic surface around the content: the toolkit's material for `role`, clipped to
/// `radius` corners.
fn op_surface(role: day_spec::SurfaceRole, radius: f64) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let w = cx.native(
                kinds::CONTAINER,
                &ContainerProps {
                    background: None,
                    corner_radius: radius,
                    clips: true,
                    role: Some(role),
                },
                Rc::new(FillThrough),
                Flex::default(),
                Boundary::No,
            );
            cx.under(w, |cx| {
                let _ = inner(cx);
            });
            w
        })
    }
}

fn op_corner_radius(radius: f64) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let node = cx.native(
                kinds::CONTAINER,
                &ContainerProps {
                    background: None,
                    corner_radius: radius,
                    clips: true,
                    role: None,
                },
                Rc::new(FillThrough),
                Flex::default(),
                Boundary::No,
            );
            cx.under(node, |cx| {
                let _ = inner(cx);
            });
            node
        })
    }
}

fn op_opacity(op: Reactive<f64>) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let node = layer_node(cx);
            cx.under(node, |cx| {
                let _ = inner(cx);
            });
            bind(
                move || op.get(),
                move |v: &f64| with_tree(|t| t.set_node_opacity(node, *v)),
            );
            node
        })
    }
}

fn op_transform(t: Reactive<Transform>) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let node = layer_node(cx);
            cx.under(node, |cx| {
                let _ = inner(cx);
            });
            bind(
                move || t.get(),
                move |v: &Transform| with_tree(|tr| tr.set_node_transform(node, *v)),
            );
            node
        })
    }
}

fn op_animation(anim: AnimSpec) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            // Layout-only: the implicit animation is Day's own state, which the patches beneath
            // look up through their ancestors, and needs no native view. A native layer here
            // also clipped what it held on the toolkits whose containers clip their children
            // (Qt always, Android by default), so a translated or scaled view under
            // `.animation(..)` vanished past the layer's frame.
            let node = cx.layout_only(Rc::new(FillThrough), Flex::default(), Boundary::No);
            with_tree(|t| t.set_implicit_anim(node, Some(anim)));
            cx.under(node, |cx| {
                let _ = inner(cx);
            });
            node
        })
    }
}

fn op_overlay_aligned(align: Alignment, over: impl Piece) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let node = cx.native(
                kinds::CONTAINER,
                &ContainerProps::default(),
                Rc::new(OverlayLayout {
                    align,
                    size_to_first: true,
                }),
                Flex::default(),
                Boundary::No,
            );
            cx.under(node, |cx| {
                let _ = inner(cx); // sizing content (bottom)
                let _ = over.build(cx); // annotation on top
            });
            node
        })
    }
}

fn op_aspect_ratio(ratio: f64) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            if !(ratio.is_finite() && ratio > 0.0) {
                return inner(cx);
            }
            let node = cx.layout_only(
                Rc::new(AspectRatioLayout { ratio }),
                Flex::default(),
                // Not a boundary: the child still measures itself, and the ratio only decides
                // the box it is offered.
                Boundary::No,
            );
            cx.under(node, |cx| {
                let _ = inner(cx);
            });
            node
        })
    }
}

fn op_grow_axes(w: bool, h: bool) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let node = cx.layout_only(
                Rc::new(GrowLayout { w, h }),
                Flex {
                    grow_w: w,
                    grow_h: h,
                    ..Default::default()
                },
                Boundary::No,
            );
            cx.under(node, |cx| {
                let _ = inner(cx);
            });
            node
        })
    }
}

fn op_grid_facts(facts: GridFacts) -> impl FnOnce(RNode) {
    move |node| with_tree(|t| t.set_grid_facts(node, facts))
}

fn op_defers_system_gestures(edges: day_spec::Edges) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let token = day_core::shield::push_gesture_deferral(edges);
            Scope::current().on_cleanup(move || day_core::shield::pop_gesture_deferral(token));
            inner(cx)
        })
    }
}

fn op_status_bar_hidden(hidden: Reactive<bool>) -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let token = day_core::shield::push_status_bar_request(hidden.get_untracked());
            Scope::current().on_cleanup(move || day_core::shield::pop_status_bar_request(token));
            // A constant answer is registered once; a reactive one follows its source while
            // the subtree stays mounted (a reader's "hide status bar" setting).
            if let Reactive::Dyn(_) = &hidden {
                bind(
                    move || hidden.get(),
                    move |h: &bool| day_core::shield::set_status_bar_request(token, *h),
                );
            }
            inner(cx)
        })
    }
}

fn op_interactive_dismiss_disabled() -> impl FnOnce(Build) -> Build {
    move |inner| {
        Box::new(move |cx| {
            let token = day_core::shield::push_dismiss_disabled();
            Scope::current().on_cleanup(move || day_core::shield::pop_dismiss_disabled(token));
            inner(cx)
        })
    }
}

// --- The chained modifier surface, on an already-decorated piece ---
//
// These inherent methods shadow the `Decorate` trait's (inherent wins method resolution), so a
// modifier applied to a `Decorated` appends to its op list instead of wrapping it in another
// `Decorated`. Each is the same one-liner the trait method is; the bodies live in the `op_*`
// functions above. Documentation stays on the trait, which is the surface every piece has.
impl<P: Piece> Decorated<P> {
    pub fn id(self, id: day_core::ElementId) -> Self {
        self.push_node(op_id(id))
    }
    pub fn id_of(self, id: impl Fn() -> day_core::ElementId + 'static) -> Self {
        self.push_node(op_id_of(id))
    }
    pub fn wrapper_id(self, id: day_core::ElementId) -> Self {
        self.push(op_wrapper_id(id))
    }
    pub fn tweak(self, f: impl FnOnce(day_core::RNode) + 'static) -> Self {
        self.push(op_tweak(f))
    }
    pub fn selectable(self) -> Self {
        self.push(op_selectable())
    }
    pub fn cursor<M>(self, cursor: impl IntoReactive<Cursor, M>) -> Self {
        self.push(op_cursor(cursor.into_reactive()))
    }
    pub fn native_ref(self, r: &NativeRef) -> Self {
        self.push(op_native_ref(r.clone()))
    }
    pub fn window_drag_region(self) -> Self {
        self.push(op_window_drag_region())
    }
    pub fn padding(self, insets: impl IntoInsets) -> Self {
        self.push(op_padding(insets.into_insets()))
    }
    pub fn max_width(self, max: f64) -> Self {
        self.push(op_max_width(max))
    }
    /// Never taller than `max`: the child is never proposed more height, so a scroll stops
    /// growing at `max` and still shrinks where the screen is shorter. In a column it is sized
    /// after its siblings and takes what they leave, up to `max`, so the controls around a
    /// capped scroll stay on screen.
    pub fn max_height(self, max: f64) -> Self {
        self.push(op_max_height(max))
    }
    /// Never narrower than `min`: a stretching control keeps a usable width, and a row that
    /// cannot give it that overflows, so a `labeled` row stacks the control under its label
    /// rather than squeezing it (docs/forms.md).
    pub fn min_width(self, min: f64) -> Self {
        self.push(op_min_width(min))
    }
    pub fn reserving(self, sample: impl Into<String>) -> Self {
        self.push(op_reserving(sample.into()))
    }
    pub fn frame(self, width: f64, height: f64) -> Self {
        self.push(op_frame(Some(width), Some(height), Boundary::Yes))
    }
    pub fn width(self, width: f64) -> Self {
        self.push(op_frame(Some(width), None, Boundary::No))
    }
    pub fn height(self, height: f64) -> Self {
        self.push(op_frame(None, Some(height), Boundary::No))
    }
    pub fn a11y(self, f: impl FnOnce(A11yBuilder) -> A11yBuilder + 'static) -> Self {
        self.push(op_a11y(f))
    }
    /// Handle a tap gesture on this piece.
    ///
    /// Do not use this to activate a native button; use [`crate::ButtonBuilder::action`].
    /// A separate gesture recognizer can delay pressed feedback and bypass native keyboard,
    /// accessibility, and disabled behavior. Day warns when it attaches a tap to a button.
    pub fn on_tap(self, f: impl Fn() + 'static) -> Self {
        self.push(op_on_tap(f))
    }
    /// Handle a tap with its local position. Like [`Self::on_tap`], this is a gesture,
    /// not native button activation; use [`crate::ButtonBuilder::action`] for buttons.
    pub fn on_tap_at(self, f: impl Fn(day_spec::Point) + 'static) -> Self {
        self.push(op_on_tap_at(f))
    }
    pub fn focused<M>(self, binding: impl IntoFocusBinding<M>) -> Self {
        let (want, on_native) = binding.into_focus_binding();
        self.push(op_focused(want, on_native))
    }
    pub fn on_key(self, f: impl Fn(&day_spec::KeyEvent) + 'static) -> Self {
        self.push(op_on_key(f))
    }
    pub fn focusable(self) -> Self {
        self.push(op_focusable())
    }
    pub fn toolbar<M>(self, content: impl crate::ToolbarContent<M>) -> Self {
        self.push(op_toolbar(content.into_source()))
    }
    /// See [`Decorate::searchable`].
    pub fn searchable(self, search: crate::Search) -> Self {
        self.push(move |inner| {
            Box::new(move |cx| {
                let n = inner(cx);
                crate::nav::install_page_search(search);
                n
            })
        })
    }
    /// Offer data through the platform's native drag session.
    pub fn drag_source(
        self,
        source: impl Fn(day_spec::Point) -> Option<day_spec::transfer::Offer> + 'static,
    ) -> Self {
        self.push(move |inner| {
            Box::new(move |cx| {
                let n = layer_node(cx);
                cx.under(n, |cx| {
                    inner(cx);
                });
                let source = scoped_drag_source(Rc::new(source));
                with_tree(|t| t.set_drag_source(n, source));
                n
            })
        })
    }
    /// Attach native drop acceptance policy and an owned-data receiver.
    pub fn drop_target(self, target: day_spec::transfer::Target) -> Self {
        self.push(move |inner| {
            Box::new(move |cx| {
                let n = layer_node(cx);
                cx.under(n, |cx| {
                    inner(cx);
                });
                let target = scoped_drop_target(target);
                with_tree(|t| t.set_drop_target(n, target));
                n
            })
        })
    }
    pub fn context_menu<M>(self, menu: impl ContextMenuContent<M>) -> Self {
        match menu.into_context_menu() {
            ContextMenuSource::Fixed(items) => self.push(op_context_menu(items)),
            ContextMenuSource::OnSummon(f) => self.push(op_context_menu_fn(f)),
        }
    }
    pub fn on_drag(self, f: impl Fn(Drag) + 'static) -> Self {
        self.push(op_on_drag(f))
    }
    pub fn on_pinch(self, f: impl Fn(Pinch) + 'static) -> Self {
        self.push(op_on_pinch(f))
    }
    pub fn on_pan(self, f: impl Fn(Pan) + 'static) -> Self {
        self.push(op_on_pan(f))
    }
    /// The pointer moving over this piece: `Some(point)` in its own coordinates while inside,
    /// `None` when it leaves (docs/canvas.md "Interaction").
    ///
    /// Pointer-only, which is not a gap: every desktop delivers it, an
    /// iPad does with a trackpad or pencil, an Android device with a mouse or stylus, and a
    /// touch-only phone delivers nothing at all. **Anything reachable by hover must also be
    /// reachable by a tap**: wire `on_tap_at` alongside it, exactly as a chart's selection does.
    pub fn on_hover(self, f: impl Fn(Option<day_spec::Point>) + 'static) -> Self {
        self.push(op_on_hover(f))
    }
    /// The platform's card: the grouped-content surface (`SurfaceRole::SectionCard`) with
    /// rounded corners and a `Space::M` inset. Drawn by the toolkit, so it follows the
    /// appearance and never steals hit testing from the content.
    pub fn card(self) -> Self {
        self.padding(crate::Space::M)
            .push(op_surface(day_spec::SurfaceRole::SectionCard, 10.0))
    }
    pub fn background<M>(self, color: impl IntoReactive<Color, M>) -> Self {
        self.push(op_background(color.into_reactive()))
    }
    pub fn corner_radius(self, radius: f64) -> Self {
        self.push(op_corner_radius(radius))
    }
    pub fn opacity<M>(self, opacity: impl IntoReactive<f64, M>) -> Self {
        self.push(op_opacity(opacity.into_reactive()))
    }
    pub fn transform<M>(self, t: impl IntoReactive<Transform, M>) -> Self {
        self.push(op_transform(t.into_reactive()))
    }
    pub fn scale<M>(self, factor: impl IntoReactive<f64, M>) -> Self {
        let f = factor.into_reactive();
        self.transform(move || Transform::scale(f.get(), f.get()))
    }
    pub fn rotation<M>(self, degrees: impl IntoReactive<f64, M>) -> Self {
        let d = degrees.into_reactive();
        self.transform(move || Transform::rotate(d.get()))
    }
    pub fn translation<Mx, My>(
        self,
        x: impl IntoReactive<f64, Mx>,
        y: impl IntoReactive<f64, My>,
    ) -> Self {
        let (x, y) = (x.into_reactive(), y.into_reactive());
        self.transform(move || Transform::translate(x.get(), y.get()))
    }
    pub fn animation(self, anim: AnimSpec) -> Self {
        self.push(op_animation(anim))
    }
    /// Erases, like [`Decorate::modifier`]: `Modifier` is defined over [`AnyPiece`].
    pub fn modifier(self, m: impl Modifier) -> AnyPiece {
        m.apply(self.any())
    }
    pub fn overlay(self, over: impl Piece) -> Self {
        self.overlay_aligned(Alignment::Center, over)
    }
    pub fn overlay_aligned(self, align: Alignment, over: impl Piece) -> Self {
        self.push(op_overlay_aligned(align, over))
    }
    pub fn aspect_ratio(self, ratio: f64) -> Self {
        self.push(op_aspect_ratio(ratio))
    }
    pub fn grow(self) -> Self {
        self.grow_axes(true, true)
    }
    pub fn grow_w(self) -> Self {
        self.grow_axes(true, false)
    }
    pub fn grow_h(self) -> Self {
        self.grow_axes(false, true)
    }
    #[doc(hidden)]
    fn grow_axes(self, w: bool, h: bool) -> Self {
        self.push(op_grow_axes(w, h))
    }
    pub fn grid_span(self, n: usize) -> Self {
        self.push_outer(op_grid_facts(GridFacts {
            col_span: n.clamp(1, u16::MAX as usize) as u16,
            ..Default::default()
        }))
    }
    pub fn grid_align(self, a: Alignment) -> Self {
        self.push_outer(op_grid_facts(GridFacts {
            align: Some(a),
            ..Default::default()
        }))
    }
    pub fn defers_system_gestures(self, edges: day_spec::Edges) -> Self {
        self.push(op_defers_system_gestures(edges))
    }
    pub fn interactive_dismiss_disabled(self) -> Self {
        self.push(op_interactive_dismiss_disabled())
    }
    pub fn status_bar_hidden<M>(self, hidden: impl IntoReactive<bool, M>) -> Self {
        self.push(op_status_bar_hidden(hidden.into_reactive()))
    }
    /// Erase to a single [`AnyPiece`].
    pub fn any(self) -> AnyPiece {
        AnyPiece::new(self)
    }
}

/// Where a context menu's entries come from (see [`Decorate::context_menu`]).
pub enum ContextMenuSource {
    Fixed(Vec<MenuEntry>),
    OnSummon(Rc<dyn Fn(day_spec::Point) -> Vec<MenuEntry>>),
}

/// Anything [`Decorate::context_menu`] accepts: a `Vec` or array of entries, a closure building
/// them on summon, or a closure given the summon point. The marker parameter is the same E0119
/// dodge as [`IntoText`].
pub trait ContextMenuContent<M> {
    fn into_context_menu(self) -> ContextMenuSource;
}

/// Marker for a summon-time closure that takes the summon point.
pub struct AtPointMark;

impl ContextMenuContent<crate::ManyMark> for Vec<MenuEntry> {
    fn into_context_menu(self) -> ContextMenuSource {
        ContextMenuSource::Fixed(self)
    }
}

impl<const N: usize> ContextMenuContent<crate::ManyMark> for [MenuEntry; N] {
    fn into_context_menu(self) -> ContextMenuSource {
        ContextMenuSource::Fixed(Vec::from(self))
    }
}

impl<C, F> ContextMenuContent<crate::DerivedMark> for F
where
    C: IntoIterator<Item = MenuEntry>,
    F: Fn() -> C + 'static,
{
    fn into_context_menu(self) -> ContextMenuSource {
        ContextMenuSource::OnSummon(Rc::new(move |_| self().into_iter().collect()))
    }
}

impl<C, F> ContextMenuContent<AtPointMark> for F
where
    C: IntoIterator<Item = MenuEntry>,
    F: Fn(day_spec::Point) -> C + 'static,
{
    fn into_context_menu(self) -> ContextMenuSource {
        ContextMenuSource::OnSummon(Rc::new(move |p| self(p).into_iter().collect()))
    }
}

pub trait Decorate: Piece + Sized {
    /// Stable element identifier: a11y identifier + dayscript locator + lint uniqueness (§5.5).
    ///
    /// Names the piece's own node wherever it sits in the chain (docs/api-style.md "Modifier
    /// classes"): `.padding(8.0).id(day_core::id!(x))` and `.id(day_core::id!(x)).padding(8.0)` tag the same node. To name
    /// a wrapper instead, use [`wrapper_id`](Self::wrapper_id).
    fn id(self, id: day_core::ElementId) -> Decorated<Self> {
        Decorated::new(self).id(id)
    }

    /// Name the node that is outermost at this point in the chain: the padding box, the frame,
    /// the background, whichever wrapper the modifiers before it built. For a dayscript frame
    /// assertion on the wrapper rather than on the piece. Ordered, unlike [`id`](Self::id).
    fn wrapper_id(self, id: day_core::ElementId) -> Decorated<Self> {
        Decorated::new(self).wrapper_id(id)
    }

    /// Apply `f` to the chain when `cond` holds, else continue unchanged
    /// (see [`Decorated::apply_if`]): `nav(sel).apply_if(!primary, |n| n.local())`. The
    /// closure receives the decorated piece, so forwarded builder methods and modifiers both
    /// chain inside it.
    fn apply_if(
        self,
        cond: bool,
        f: impl FnOnce(Decorated<Self>) -> Decorated<Self>,
    ) -> Decorated<Self> {
        Decorated::new(self).apply_if(cond, f)
    }

    /// Apply `f` with the value when there is one, else continue unchanged
    /// (see [`Decorated::apply_some`]): `canvas(draw).apply_some(id, |c, id| c.id(id))`.
    fn apply_some<T>(
        self,
        value: Option<T>,
        f: impl FnOnce(Decorated<Self>, T) -> Decorated<Self>,
    ) -> Decorated<Self> {
        Decorated::new(self).apply_some(value, f)
    }

    /// Reactive element id: the id for rows inside a recycling [`list`](crate::list). A plain
    /// [`id`](Self::id) is assigned once at build, but a recycled cell rebinds to different
    /// items over its life (and drag-to-reorder rebinds eagerly), so a static item-derived id
    /// keeps naming the first-bound item. This variant re-registers whenever the closure's
    /// value changes; read your `ItemSlot` inside it:
    /// `.id_of(move || day_core::id!(row_remove, slot.key()))`.
    fn id_of(self, id: impl Fn() -> day_core::ElementId + 'static) -> Decorated<Self> {
        Decorated::new(self).id_of(id)
    }

    /// Apply a **tweak**: `f` runs once at mount, after the native widget exists, with the
    /// realized node (docs/tweaks.md). Reach the typed native handle through the compiled
    /// backend's ext accessor (`day_toolkit_appkit::with_native`, `day_toolkit_gtk::with_native`, …), or apply
    /// a packaged `day-tweak-*` crate's modifier instead of calling this directly. If the native
    /// change affects the widget's intrinsic size, follow it with
    /// [`day_core::invalidate_size`]. Day may overwrite *managed* properties (title, value,
    /// enabled, frame, a11y) on its next patch; unmanaged properties are stable.
    ///
    /// Order it after any modifier that can rebuild the backing widget; today that is
    /// [`selectable`](Decorate::selectable), which on UIKit realizes the label as a different
    /// native class. Chained before it, the tweak runs against the widget the rebuild discards
    /// (Day warns at runtime); chained after, it sees the widget that ships.
    fn tweak(self, f: impl FnOnce(day_core::RNode) + 'static) -> Decorated<Self> {
        Decorated::new(self).tweak(f)
    }

    /// Make this piece's text **user-selectable**, so the reader can select and copy it
    /// (docs/text.md). Most useful on a [`label`](crate::label): text is not selectable by default
    /// on any backend, matching each platform's native behavior.
    ///
    /// Every backend honors it on a label: most flip the native widget's selection affordance
    /// (AppKit, GTK, Qt, XAML, HarmonyOS, Android, web); UIKit, whose `UILabel` has none,
    /// rebuilds the label as a read-only `UITextView` behind the same handle. On other widgets
    /// it is best-effort: a backing with no selection affordance leaves the text unselectable
    /// rather than erroring, and a container cascades only where the platform's affordance does
    /// (the web), so prefer the label itself. Selection visuals and the copy shortcut are the
    /// platform's own. Unmanaged: set once at mount, and it survives Day's text updates.
    fn selectable(self) -> Decorated<Self> {
        Decorated::new(self).selectable()
    }

    /// Shape the pointer while it is over this piece and its descendants (docs/cursor.md): a
    /// [`Cursor`] constant, a `Signal<Cursor>`, or a closure, so a canvas tool or a busy state
    /// moves the shape without rebuilding the piece. The nearest ancestor's cursor wins, and
    /// `Cursor::Default` releases the piece back to the platform. `capability(Cap::Cursor)`
    /// says whether this toolkit draws the requested shapes, a nearest neighbor, or nothing;
    /// a touch-only host never shows one, which is correct rather than a failure.
    fn cursor<M>(self, cursor: impl IntoReactive<Cursor, M>) -> Decorated<Self> {
        Decorated::new(self).cursor(cursor)
    }

    /// Let the user move the window by dragging this piece, as a title bar does
    /// (docs/window-chrome.md): what a custom title bar in a [`WindowChrome::Overlay`] or
    /// [`WindowChrome::Frameless`] window needs. The piece's own background starts the drag,
    /// with the platform's snapping and tiling; buttons and fields inside it keep their clicks;
    /// a double click does what the user's title-bar setting says (zoom, minimize, nothing).
    /// `capability(Cap::DragRegion)`; on a phone the piece is an ordinary view.
    ///
    /// [`WindowChrome::Overlay`]: day_spec::WindowChrome::Overlay
    /// [`WindowChrome::Frameless`]: day_spec::WindowChrome::Frameless
    fn window_drag_region(self) -> Decorated<Self> {
        Decorated::new(self).window_drag_region()
    }

    /// Capture a [`NativeRef`] to this piece's realized node for later imperative access
    /// (docs/tweaks.md). The ref clears automatically when the piece's scope is disposed.
    fn native_ref(self, r: &NativeRef) -> Decorated<Self> {
        Decorated::new(self).native_ref(r)
    }

    fn padding(self, insets: impl IntoInsets) -> Decorated<Self> {
        Decorated::new(self).padding(insets)
    }

    /// Cap this piece's width at `max` points: the child is never PROPOSED more, so text
    /// wraps inside the cap (chat bubbles, readable columns) while narrower content hugs.
    fn max_width(self, max: f64) -> Decorated<Self> {
        Decorated::new(self).max_width(max)
    }
    /// Cap this piece's height at `max` points, the vertical twin of [`Decorate::max_width`]: a
    /// scroll or another piece that takes the height it is offered stops at `max`, and still
    /// gets less where its parent has less to give.
    fn max_height(self, max: f64) -> Decorated<Self> {
        Decorated::new(self).max_height(max)
    }
    /// See [`Decorated::min_width`].
    fn min_width(self, min: f64) -> Decorated<Self> {
        Decorated::new(self).min_width(min)
    }

    /// Reserve at least the space `sample` needs, so this piece's size stops changing with its
    /// content.
    ///
    /// For a numeric readout beside a slider: `label(move || value()).reserving("100")` keeps the
    /// row still while the number changes, because the reservation is a real measurement of
    /// `"100"` in this piece's own font: it scales with the platform's accessibility text size
    /// instead of being a point value that clips when someone turns text up.
    ///
    /// Pass the widest value the field can show (`"100"`, `"-99.9"`, `"88:88"`). Pair it with
    /// tabular numbers so the digits themselves stop shifting inside the reservation.
    /// The sample never paints and never takes hit-testing area.
    fn reserving(self, sample: impl Into<String>) -> Decorated<Self> {
        Decorated::new(self).reserving(sample)
    }

    fn frame(self, width: f64, height: f64) -> Decorated<Self> {
        Decorated::new(self).frame(width, height)
    }

    /// Fix this piece's width to `width` points while its height stays flexible (hugging its
    /// content or filling on the cross axis). The single-axis complement to [`Self::frame`], e.g.
    /// a fixed-width sidebar pane in a `row` whose height fills the window.
    fn width(self, width: f64) -> Decorated<Self> {
        Decorated::new(self).width(width)
    }

    /// Fix this piece's height to `height` points while its width stays flexible. The single-axis
    /// complement to [`Self::frame`], e.g. a fixed-height header/toolbar bar that fills its width.
    fn height(self, height: f64) -> Decorated<Self> {
        Decorated::new(self).height(height)
    }

    fn a11y(self, f: impl FnOnce(A11yBuilder) -> A11yBuilder + 'static) -> Decorated<Self> {
        Decorated::new(self).a11y(f)
    }

    /// Fire when this piece is tapped (bounding-box; shapes override with path-precise testing).
    ///
    /// Do not use this to activate a native button; use [`crate::Button::action`] instead.
    /// A separate gesture recognizer can delay pressed feedback and bypass native keyboard,
    /// accessibility, and disabled behavior. Day warns when it attaches a tap to a button.
    fn on_tap(self, f: impl Fn() + 'static) -> Decorated<Self> {
        Decorated::new(self).on_tap(f)
    }

    /// [`on_tap`](Self::on_tap), told where: the point in the piece's own coordinate space,
    /// origin at its top-leading corner.
    ///
    /// What a drawn control needs and a native one does not: a canvas showing a color wheel, a
    /// map, or a waveform has to turn "the user pressed here" into a value, and only the piece
    /// knows how. Pair it with [`on_drag`](Self::on_drag), which already reports a location, to
    /// track a press that turns into a drag; the two are idempotent together, so a backend that
    /// reports a tap as a zero-length drag costs nothing.
    ///
    /// `Event::Tap` has always carried the point; this is the decorator that stops throwing it
    /// away.
    ///
    /// For native buttons use [`crate::Button::action`], not this gesture decorator.
    fn on_tap_at(self, f: impl Fn(day_spec::Point) + 'static) -> Decorated<Self> {
        Decorated::new(self).on_tap_at(f)
    }

    /// Bind this control's keyboard focus to a signal (docs/focus.md), two-way like every other
    /// binding: native focus changes write the signal; writing the signal moves focus. Takes a
    /// `Signal<bool>` for one control, or `(Signal<Option<K>>, K::Variant)` binding one control
    /// of a group; writing `false`/`None` resigns focus (dismissing the soft keyboard on
    /// mobile). Focus applies asynchronously: a write is a request, resolved on the next turn,
    /// and the signal always ends up reflecting what the platform actually did.
    fn focused<M>(self, binding: impl IntoFocusBinding<M>) -> Decorated<Self> {
        Decorated::new(self).focused(binding)
    }

    /// Handle the non-text keys (the arrows) that reach this piece while it has focus
    /// (docs/menus.md). Keys follow focus, so pair it with [`Decorate::focused`] or with a
    /// piece the user can click into: a canvas takes focus on a press, and only the focused
    /// piece hears the keys, so a nudge handler can never fire while a text field, a list or a
    /// sidebar is the one being typed into.
    ///
    /// Which pieces can hold focus is the platform's to answer (docs/focus.md): a `canvas`
    /// is focusable on the backends that draw one from a real view (appkit, web-dom today).
    fn on_key(self, f: impl Fn(&day_spec::KeyEvent) + 'static) -> Decorated<Self> {
        Decorated::new(self).on_key(f)
    }

    /// Declare toolbar items on the chrome this piece sits under (docs/toolbars.md).
    ///
    /// Takes one item, a list of them, or a closure that derives the list and re-runs whenever
    /// its reactive reads change:
    ///
    /// ```ignore
    /// page.toolbar(toolbar_button(day_core::id!(share), tr("share")).icon(Symbol::Share).action(share))
    /// page.toolbar([reply, forward, archive])
    /// page.toolbar(move || vec![toolbar_button(day_core::id!(undo), tr("undo")).enabled(can_undo)])
    /// ```
    ///
    /// Which chrome carries them follows from where this piece is built (a destination page's
    /// own bar, a content-list pane's, or the window's if it is under no page at all), and the
    /// items are withdrawn when this piece is disposed. Where on that chrome they sit is
    /// [`ToolbarEntry::placement`](crate::ToolbarEntry::placement).
    fn toolbar<M>(self, content: impl crate::ToolbarContent<M>) -> Decorated<Self> {
        Decorated::new(self).toolbar(content)
    }

    /// A search field for this navigation page (docs/search.md, "Page search"), drawn where the
    /// platform puts a page's search: the window toolbar on a desktop, the page's navigation bar
    /// on iOS (a `UISearchController`), its app bar on Android. It shows while this page does, and
    /// its text is the app's `query` both ways. For a search the server runs, act on
    /// [`crate::Search::on_submit`]; for a local filter, read the query. Declare it on a
    /// `nav_stack` destination, as `.toolbar(…)` is declared; a whole navigation surface takes
    /// [`crate::Nav::searchable`] instead.
    fn searchable(self, search: crate::Search) -> Decorated<Self> {
        Decorated::new(self).searchable(search)
    }

    /// Opt this piece into the platform's focus system (docs/focus.md): the canvas contract
    /// for anything composed: it joins the key loop, takes focus on a press, reports through
    /// `.focused(…)`, and hears the arrows through `.on_key(…)` while focused. A composed
    /// list column is the motivating case (docs/navigation.md). On a backend without the
    /// `set_focusable` duty the piece renders normally and never takes focus.
    fn focusable(self) -> Decorated<Self> {
        Decorated::new(self).focusable()
    }

    /// Attach a context menu, shown with the platform's native affordance on secondary-click (desktop)
    /// or long-press (mobile). Items are built with [`menu_item`]/[`sub_menu`]/[`menu_role`]/
    /// [`menu_separator`]. Passing an empty `Vec` removes any menu.
    fn drag_source(
        self,
        source: impl Fn(day_spec::Point) -> Option<day_spec::transfer::Offer> + 'static,
    ) -> Decorated<Self> {
        Decorated::new(self).drag_source(source)
    }
    fn drop_target(self, target: day_spec::transfer::Target) -> Decorated<Self> {
        Decorated::new(self).drop_target(target)
    }
    /// A context menu (docs/menus.md): shown on secondary-click / long-press, built from the
    /// same `menu_item`/`sub_menu` entries as everywhere else. Takes a fixed list, or a closure
    /// built when the menu is summoned ("Dynamic context menus"): with no argument, or with the
    /// summon point in this piece's own coordinates, so a canvas can select what is under the
    /// pointer and offer commands for that selection. An empty result shows nothing.
    ///
    /// ```ignore
    /// label(t).context_menu([menu_item(res::str::copy()).action(copy)])
    /// canvas(draw).context_menu(move |at: Point| commands_for(hit_test(at)))
    /// ```
    fn context_menu<M>(self, menu: impl ContextMenuContent<M>) -> Decorated<Self> {
        Decorated::new(self).context_menu(menu)
    }

    fn on_drag(self, f: impl Fn(Drag) + 'static) -> Decorated<Self> {
        Decorated::new(self).on_drag(f)
    }

    /// Fire on each phase of a pinch/magnify over this piece (docs/canvas.md "Zoom and
    /// pan"). Only backends with a native recognizer wired emit it; pair a zoom with
    /// visible controls.
    fn on_pinch(self, f: impl Fn(Pinch) + 'static) -> Decorated<Self> {
        Decorated::new(self).on_pinch(f)
    }

    /// Fire on each viewport-pan event over this piece (docs/canvas.md "Zoom and pan"):
    /// trackpad two-finger scroll, two-finger touch pan. `delta` is incremental; apply it
    /// as it arrives.
    fn on_pan(self, f: impl Fn(Pan) + 'static) -> Decorated<Self> {
        Decorated::new(self).on_pan(f)
    }

    /// The pointer moving over this piece: `Some(point)` in its own coordinates while inside,
    /// `None` when it leaves (docs/canvas.md "Interaction"). Pointer-only; wire `on_tap_at`
    /// alongside it so a touch-only device can reach the same thing.
    fn on_hover(self, f: impl Fn(Option<day_spec::Point>) + 'static) -> Decorated<Self> {
        Decorated::new(self).on_hover(f)
    }

    /// Fill the piece's bounds with a solid color painted behind it: a message-bubble / card /
    /// badge surface. Accepts a constant [`Color`], a `Signal<Color>`, or a `Fn() -> Color`; a
    /// reactive color repaints the surface when its source changes. Wraps the piece in a native
    /// container that carries the fill, so it composes with [`Self::corner_radius`] for a rounded
    /// colored surface and with [`Self::padding`] for interior inset.
    /// The platform's card around this piece: the grouped-content surface with rounded
    /// corners and a `Space::M` inset (see [`Decorated::card`]).
    fn card(self) -> Decorated<Self> {
        Decorated::new(self).card()
    }

    fn background<M>(self, color: impl IntoReactive<Color, M>) -> Decorated<Self> {
        Decorated::new(self).background(color)
    }

    /// Round the piece's corners to `radius` points, clipping its background and content to the
    /// rounded rectangle. Compose after [`Self::background`] for a rounded colored surface, or use
    /// alone to round a clipped child (e.g. an avatar image).
    fn corner_radius(self, radius: f64) -> Decorated<Self> {
        Decorated::new(self).corner_radius(radius)
    }

    /// Animate/set the piece's opacity (`0.0` transparent … `1.0` opaque). Wrapped in a native
    /// layer so it composes with `.background`; the change animates when made inside
    /// [`with_animation`] or under a `.animation` ancestor (§8.4).
    fn opacity<M>(self, opacity: impl IntoReactive<f64, M>) -> Decorated<Self> {
        Decorated::new(self).opacity(opacity)
    }

    /// Apply an animatable [`Transform`] (translate/scale/rotate about the center): the cheap
    /// movement/scaling channel that never triggers relayout (§8.4). Prefer this over `.offset`
    /// for animated motion.
    fn transform<M>(self, t: impl IntoReactive<Transform, M>) -> Decorated<Self> {
        Decorated::new(self).transform(t)
    }

    /// Uniformly scale the piece by `factor` about its center (animatable). Convenience over
    /// [`Self::transform`].
    fn scale<M>(self, factor: impl IntoReactive<f64, M>) -> Decorated<Self> {
        Decorated::new(self).scale(factor)
    }

    /// Rotate the piece by `degrees` clockwise about its center (animatable).
    fn rotation<M>(self, degrees: impl IntoReactive<f64, M>) -> Decorated<Self> {
        Decorated::new(self).rotation(degrees)
    }

    /// Translate the piece by (`x`, `y`) points without relayout (animatable): the
    /// animation-friendly sibling of `.offset`.
    fn translation<Mx, My>(
        self,
        x: impl IntoReactive<f64, Mx>,
        y: impl IntoReactive<f64, My>,
    ) -> Decorated<Self> {
        Decorated::new(self).translation(x, y)
    }

    /// Attach an implicit animation (§8.4): changes to this piece's (and its descendants')
    /// animatable properties animate with `anim` even outside a [`with_animation`]. SwiftUI's
    /// `.animation`. The ambient `with_animation` takes precedence when both apply.
    fn animation(self, anim: AnimSpec) -> Decorated<Self> {
        Decorated::new(self).animation(anim)
    }

    /// Apply a [`Modifier`] (or, via the blanket impl, a plain `FnOnce(AnyPiece) -> AnyPiece`
    /// closure) to this piece. Pure composition: `content.modifier(m) == m.apply(content.any())`.
    ///
    /// The one modifier that erases: `Modifier` is defined over [`AnyPiece`], so the piece's own
    /// type cannot survive it.
    fn modifier(self, m: impl Modifier) -> AnyPiece {
        m.apply(self.any())
    }

    /// Draw `over` on top of this piece, centered, without affecting layout size: a badge /
    /// annotation overlay. `self` is the sizing content (bottom of the z-order); `over` is proposed
    /// `self`'s size and drawn on top. For an explicit alignment use [`Self::overlay_aligned`]; for
    /// a stack that sizes to the union of its children use [`zstack`].
    fn overlay(self, over: impl Piece) -> Decorated<Self> {
        Decorated::new(self).overlay(over)
    }

    /// [`Self::overlay`] with an explicit [`Alignment`] for the annotation (e.g. a corner badge with
    /// [`Alignment::TopTrailing`]).
    fn overlay_aligned(self, align: Alignment, over: impl Piece) -> Decorated<Self> {
        Decorated::new(self).overlay_aligned(align, over)
    }

    /// Constrain this piece to a `width / height` ratio: the largest box of that shape which
    /// fits whatever the parent offers (SwiftUI's `.aspectRatio(_:contentMode: .fit)`).
    ///
    /// Pair it with [`Self::grow_w`] for a piece that takes the width available and derives its
    /// height from it: a `canvas` whose drawing has to keep its proportions as the window
    /// resizes, say. `image` has carried this since it shipped; this is the same layout, for any
    /// piece.
    ///
    /// A ratio that is not finite and positive describes no box, so it is ignored.
    fn aspect_ratio(self, ratio: f64) -> Decorated<Self> {
        Decorated::new(self).aspect_ratio(ratio)
    }

    /// Expand to fill the available space on both axes (a filling pane / card that stretches to
    /// its container). Wraps the piece in a layout-only node carrying grow [`Flex`]: the stack
    /// offers it the space and it fills; no native backing, so this is a pure layout change.
    fn grow(self) -> Decorated<Self> {
        Decorated::new(self).grow()
    }

    /// Expand to fill the available horizontal space.
    fn grow_w(self) -> Decorated<Self> {
        Decorated::new(self).grow_w()
    }

    /// Expand to fill the available vertical space.
    fn grow_h(self) -> Decorated<Self> {
        Decorated::new(self).grow_h()
    }

    #[doc(hidden)]
    /// Span `n` columns (n ≥ 1) of the enclosing [`grid`] (docs/grid.md). Grid modifiers set
    /// facts on the node the grid sees: apply them last (outermost), like `.grow_w()`; an
    /// outer wrapper would hide the facts from the grid.
    fn grid_span(self, n: usize) -> Decorated<Self> {
        Decorated::new(self).grid_span(n)
    }

    /// Override this cell's alignment within its cell rect of the enclosing [`grid`]
    /// (docs/grid.md). Apply last (outermost), like [`Decorated::grid_span`].
    fn grid_align(self, a: Alignment) -> Decorated<Self> {
        Decorated::new(self).grid_align(a)
    }

    /// While this subtree is mounted, ask the OS to require a second swipe for its edge
    /// gestures on `edges` (docs/cover.md), the SwiftUI `defersSystemGestures(on:)`
    /// analogue. Put it on a game or drawing surface whose touches run to the screen edge,
    /// so a swipe up from the bottom doesn't leave the app. iOS defers the chosen edges'
    /// system gestures; Android enters swipe-to-reveal immersive mode while any subtree
    /// requests deferral; desktop backends no-op.
    fn defers_system_gestures(self, edges: day_spec::Edges) -> Decorated<Self> {
        Decorated::new(self).defers_system_gestures(edges)
    }

    /// While this subtree is mounted and `hidden` is true, hide the system status bar, the
    /// SwiftUI `statusBarHidden(_:)` analogue (docs/cover.md). `hidden` is a constant, a
    /// `Signal`, or a closure, so a setting can turn it on and off in place. Put it on a page
    /// that wants the whole screen (a reader, a game, a photo viewer); the bar returns when
    /// the page unmounts. Any mounted request that answers true hides the bar. iOS, Android and
    /// HarmonyOS hide it (`Cap::StatusBarHidden`); desktop and web have none and ignore it.
    fn status_bar_hidden<M>(self, hidden: impl IntoReactive<bool, M>) -> Decorated<Self> {
        Decorated::new(self).status_bar_hidden(hidden)
    }

    /// While this subtree is mounted, the enclosing [`cover`] (or other modal surface) must
    /// not be dismissed interactively, the SwiftUI `interactiveDismissDisabled()` analogue
    /// (docs/cover.md). System back / sheet gestures are ignored; only programmatic writes
    /// (an explicit close control) dismiss it.
    fn interactive_dismiss_disabled(self) -> Decorated<Self> {
        Decorated::new(self).interactive_dismiss_disabled()
    }

    /// Erase to a single [`AnyPiece`]: for a `Vec<AnyPiece>`, a `-> AnyPiece` signature, or any other
    /// place one concrete type is required. [`AnyPiece::any`] is inherent and returns `self`, so
    /// erasing an already-erased piece costs nothing.
    fn any(self) -> AnyPiece {
        AnyPiece::new(self)
    }
}

impl<P: Piece> Decorate for P {}

/// One a11y string that reads a signal or the locale, with the patch that re-sends it alone.
type LiveA11yString = (TextSource, fn(String) -> A11yProps);

/// The annotations `.a11y(|a| …)` collects (docs/accessibility.md). The three strings are
/// [`TextSource`]s, so each takes a literal, a `String`, a `Signal<String>` or a closure: a
/// gauge's value follows the gauge, and a localized label follows the locale.
#[derive(Default)]
pub struct A11yBuilder {
    label: Option<TextSource>,
    hint: Option<TextSource>,
    value: Option<TextSource>,
    /// The selected state, reactive so a tab or row follows the selection.
    selected: Option<Reactive<bool>>,
    props: A11yProps,
}

impl A11yBuilder {
    /// What the screen reader calls the element.
    pub fn label<M>(mut self, s: impl IntoText<M>) -> Self {
        self.label = Some(s.into_text());
        self
    }
    /// A longer description of what the element does.
    pub fn hint<M>(mut self, s: impl IntoText<M>) -> Self {
        self.hint = Some(s.into_text());
        self
    }
    /// The control's current value read aloud by the screen reader (e.g. a `Meter`'s "72%").
    /// Reactive like the others: `.value(move || format!("{:.0}%", level.get()))` re-sends the
    /// value whenever `level` changes.
    pub fn value<M>(mut self, s: impl IntoText<M>) -> Self {
        self.value = Some(s.into_text());
        self
    }
    pub fn role(mut self, r: Role) -> Self {
        self.props.role = r;
        self
    }
    /// Whether this element is the selected one among its peers (a `Role::Tab`, a row): the
    /// platform's selected state, which a screen reader reads as "selected". Reactive like the
    /// strings: `.selected(move || current.get() == key)` re-sends it when the selection moves.
    pub fn selected<M>(mut self, on: impl IntoReactive<bool, M>) -> Self {
        self.selected = Some(on.into_reactive());
        self
    }
    /// Hide this element from assistive tech (still visible on screen), e.g. a redundant chrome
    /// element already announced by its labeled sibling.
    pub fn hidden(mut self) -> Self {
        self.props.hidden = true;
        self
    }
    /// Purely decorative (a background flourish): hidden from assistive tech and, for images,
    /// exempt from the "needs a label" lint (§13).
    pub fn decorative(mut self) -> Self {
        self.props.decorative = true;
        self.props.hidden = true;
        self
    }

    /// The annotations as first applied, with every string resolved once, the sources that
    /// can change, each paired with the patch that re-sends it, and the selected state when it
    /// reads a signal.
    fn split(self) -> (A11yProps, Vec<LiveA11yString>, Option<Reactive<bool>>) {
        let mut props = self.props;
        let mut live = Vec::new();
        let selected = match self.selected {
            Some(Reactive::Const(on)) => {
                props.selected = Some(on);
                None
            }
            Some(dynamic @ Reactive::Dyn(_)) => {
                props.selected = Some(day_reactive::untrack(|| dynamic.get()));
                Some(dynamic)
            }
            None => None,
        };
        let mut take =
            |src: Option<TextSource>, slot: &mut Option<String>, patch: fn(String) -> A11yProps| {
                if let Some(src) = src {
                    *slot = Some(src.initial());
                    if matches!(src, TextSource::Dyn(_)) {
                        live.push((src, patch));
                    }
                }
            };
        take(self.label, &mut props.label, |label| A11yProps {
            label: Some(label),
            ..Default::default()
        });
        take(self.hint, &mut props.hint, |hint| A11yProps {
            hint: Some(hint),
            ..Default::default()
        });
        take(self.value, &mut props.value, |value| A11yProps {
            value: Some(value),
            ..Default::default()
        });
        (props, live, selected)
    }
}

// Native callbacks arrive outside the event dispatcher. Enter their owning scope so
// window ambient state resolves correctly, and reject callbacks retained after disposal.
fn scoped_drag_source(source: day_spec::transfer::Source) -> day_spec::transfer::Source {
    let scope = Scope::current();
    let alive = Rc::new(Cell::new(true));
    let cleanup = alive.clone();
    scope.on_cleanup(move || cleanup.set(false));
    Rc::new(move |point| alive.get().then(|| scope.enter(|| source(point))).flatten())
}
fn scoped_drop_target(target: day_spec::transfer::Target) -> day_spec::transfer::Target {
    let scope = Scope::current();
    let alive = Rc::new(Cell::new(true));
    let cleanup = alive.clone();
    scope.on_cleanup(move || cleanup.set(false));
    let accept_alive = alive.clone();
    day_spec::transfer::Target {
        types: target.types,
        accept: Rc::new(move |location| {
            if accept_alive.get() {
                scope.enter(|| (target.accept)(location))
            } else {
                day_spec::transfer::Operation::None
            }
        }),
        receive: Rc::new(move |drop| alive.get() && scope.enter(|| (target.receive)(drop))),
    }
}

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

/// The modifiers' `#[day::test]` cases, next to the `Decorate` methods they prove.
#[cfg(feature = "conformance")]
pub(crate) mod conformance {
    use day_core::AnyPiece;
    use day_core::conformance::{Case, Drive, FrameExpect};
    use day_reactive::Signal;
    use day_spec::{Cap, Color, DragPhase, Transform};

    use crate::*;

    fn size(width: f64, height: f64) -> FrameExpect {
        FrameExpect {
            width: Some(width),
            height: Some(height),
            ..Default::default()
        }
    }

    /// Padding grows the frame by its insets and moves the content in by them.
    #[day_macros::test(day_core)]
    fn padding_insets() -> Case {
        Case::new()
            .proves_modifier("padding")
            .proves_modifier("wrapper_id")
            .page(|| {
                // `id` names the rectangle wherever it sits; the padding box is a wrapper, so
                // it is named with `wrapper_id`, the one ordered identity modifier.
                rectangle()
                    .fill(Color::rgb(1.0, 0.0, 0.0))
                    .id(day_core::id!(inner))
                    .frame(40.0, 20.0)
                    .padding(10.0)
                    .wrapper_id(day_core::id!(outer))
            })
            .drive(|d: Drive| async move {
                d.assert_frame("outer", size(60.0, 40.0)).await?;
                d.assert_frame(
                    "inner",
                    FrameExpect {
                        x: Some(10.0),
                        y: Some(10.0),
                        relative_to: Some("outer".into()),
                        ..Default::default()
                    },
                )
                .await
            })
    }

    /// A minimum width widens a narrow piece; a maximum narrows a wide one.
    #[day_macros::test(day_core)]
    fn min_max_width() -> Case {
        Case::new()
            .proves_modifier("min_width")
            .proves_modifier("max_width")
            .page(|| {
                column((
                    // The widened box, not the label's own node.
                    label("Hi").min_width(120.0).wrapper_id(day_core::id!(min)),
                    label("A label long enough that it would run past eighty points")
                        .max_width(80.0)
                        .wrapper_id(day_core::id!(max)),
                ))
                .align(HAlign::Leading)
            })
            .drive(|d: Drive| async move {
                d.assert_frame(
                    "min",
                    FrameExpect {
                        width: Some(120.0),
                        ..Default::default()
                    },
                )
                .await?;
                d.assert_frame(
                    "max",
                    FrameExpect {
                        width: Some(80.0),
                        ..Default::default()
                    },
                )
                .await
            })
    }

    /// A maximum height stops a scroll, which takes all the height it is offered, at the cap.
    #[day_macros::test(day_core)]
    fn max_height_caps_a_scroll() -> Case {
        Case::new()
            .proves_modifier("max_height")
            .page(|| {
                column((
                    scroll(column((
                        label("One"),
                        label("Two"),
                        label("Three"),
                        label("Four"),
                        label("Five"),
                        label("Six"),
                    )))
                    .max_height(60.0)
                    .wrapper_id(day_core::id!(capped)),
                    spacer(),
                ))
                .align(HAlign::Leading)
            })
            .drive(|d: Drive| async move {
                d.assert_frame(
                    "capped",
                    FrameExpect {
                        height: Some(60.0),
                        ..Default::default()
                    },
                )
                .await
            })
    }

    /// An aspect ratio sets the height from the width.
    #[day_macros::test(day_core)]
    fn aspect_ratio_height() -> Case {
        Case::new()
            .proves_modifier("aspect_ratio")
            .page(|| {
                rectangle()
                    .fill(Color::rgb(0.0, 0.0, 1.0))
                    .aspect_ratio(2.0)
                    .id(day_core::id!(shape))
                    .width(100.0)
            })
            .drive(|d: Drive| async move { d.assert_frame("shape", size(100.0, 50.0)).await })
    }

    /// A growing child takes the row's remaining width.
    #[day_macros::test(day_core)]
    fn grow_width() -> Case {
        Case::new()
            .proves_modifier("grow_w")
            .page(|| {
                row((
                    rectangle()
                        .fill(Color::rgb(1.0, 0.0, 0.0))
                        .frame(40.0, 20.0),
                    rectangle()
                        .fill(Color::rgb(0.0, 0.0, 1.0))
                        .height(20.0)
                        .grow_w()
                        .id(day_core::id!(grower)),
                ))
                .spacing(0.0)
                .width(200.0)
            })
            .drive(|d: Drive| async move {
                d.assert_frame(
                    "grower",
                    FrameExpect {
                        width: Some(160.0),
                        ..Default::default()
                    },
                )
                .await
            })
    }

    /// An aligned overlay draws over its base, in the corner it names.
    #[day_macros::test(day_core)]
    fn overlay_aligned_corner() -> Case {
        Case::new()
            .proves_modifier("overlay_aligned")
            .requires(Cap::Snapshot)
            .page(|| {
                rectangle()
                    .fill(Color::rgb(1.0, 0.0, 0.0))
                    .frame(100.0, 60.0)
                    .overlay_aligned(
                        day_core::Alignment::BottomTrailing,
                        rectangle()
                            .fill(Color::rgb(0.0, 0.0, 1.0))
                            .frame(20.0, 20.0),
                    )
                    .id(day_core::id!(base))
            })
            .drive(|d: Drive| async move {
                d.sample_pixel("base", 0.95, 0.9, "#0000ff").await?;
                d.sample_pixel("base", 0.1, 0.1, "#ff0000").await
            })
    }

    /// A background fills the piece's frame.
    #[day_macros::test(day_core)]
    fn background_fill() -> Case {
        Case::new()
            .proves_modifier("background")
            .requires(Cap::Snapshot)
            .page(|| {
                label("")
                    .frame(80.0, 40.0)
                    .background(Color::rgb(1.0, 0.0, 0.0))
                    .id(day_core::id!(filled))
            })
            .drive(|d: Drive| async move { d.sample_pixel("filled", 0.5, 0.5, "#ff0000").await })
    }

    /// A corner radius cuts a background's corners and keeps its middle.
    #[day_macros::test(day_core)]
    fn corner_radius_cuts() -> Case {
        Case::new()
            .proves_modifier("corner_radius")
            .requires(Cap::Snapshot)
            .page(|| {
                zstack((
                    rectangle().fill(Color::WHITE),
                    label("")
                        .frame(80.0, 80.0)
                        .background(Color::rgb(0.0, 0.0, 1.0))
                        .corner_radius(30.0),
                ))
                .id(day_core::id!(ground))
                .frame(80.0, 80.0)
            })
            .drive(|d: Drive| async move {
                d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
                d.sample_pixel("ground", 0.03, 0.03, "#ffffff").await
            })
    }

    /// Opacity zero leaves what is below showing.
    #[day_macros::test(day_core)]
    fn opacity_hides() -> Case {
        Case::new()
            .proves_duty("set_opacity")
            .proves_modifier("opacity")
            .requires(Cap::Snapshot)
            .page(|| {
                zstack((
                    rectangle().fill(Color::WHITE),
                    rectangle().fill(Color::rgb(1.0, 0.0, 0.0)).opacity(0.0),
                ))
                .id(day_core::id!(ground))
                .frame(80.0, 40.0)
            })
            .drive(|d: Drive| async move { d.sample_pixel("ground", 0.5, 0.5, "#ffffff").await })
    }

    /// A translation moves what is drawn without moving the layout.
    #[day_macros::test(day_core)]
    fn translation_moves_drawing() -> Case {
        Case::new()
            .proves_modifier("translation")
            .requires(Cap::Snapshot)
            .page(|| {
                zstack((
                    rectangle().fill(Color::WHITE),
                    rectangle()
                        .fill(Color::rgb(0.0, 0.0, 1.0))
                        .frame(40.0, 40.0)
                        .translation(40.0, 0.0),
                ))
                .align(day_core::Alignment::Leading)
                .id(day_core::id!(ground))
                .frame(120.0, 40.0)
            })
            .drive(|d: Drive| async move {
                d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
                d.sample_pixel("ground", 0.1, 0.5, "#ffffff").await
            })
    }

    /// A translation moves a plain view's drawing too, not only a canvas's.
    #[day_macros::test(day_core)]
    fn translation_moves_view() -> Case {
        Case::new()
            .proves_modifier("translation")
            .requires(Cap::Snapshot)
            .page(|| {
                zstack((
                    rectangle().fill(Color::WHITE),
                    label("")
                        .frame(40.0, 40.0)
                        .background(Color::rgb(0.0, 0.0, 1.0))
                        .translation(40.0, 0.0),
                ))
                .align(day_core::Alignment::Leading)
                .id(day_core::id!(ground))
                .frame(120.0, 40.0)
            })
            .drive(|d: Drive| async move {
                d.sample_pixel("ground", 0.5, 0.5, "#0000ff").await?;
                d.sample_pixel("ground", 0.1, 0.5, "#ffffff").await
            })
    }

    /// A scale grows the drawing about its center without moving the layout.
    #[day_macros::test(day_core)]
    fn scale_grows_drawing() -> Case {
        Case::new()
            .proves_modifier("scale")
            .requires(Cap::Snapshot)
            .page(|| {
                zstack((
                    rectangle().fill(Color::WHITE),
                    label("")
                        .frame(40.0, 40.0)
                        .background(Color::rgb(0.0, 0.0, 1.0))
                        .scale(2.0),
                ))
                .id(day_core::id!(ground))
                .frame(120.0, 80.0)
            })
            .drive(|d: Drive| async move {
                // Unscaled, the square spans x 40..80 of 120; scaled twice it spans 20..100.
                d.sample_pixel("ground", 0.25, 0.5, "#0000ff").await?;
                d.sample_pixel("ground", 0.08, 0.5, "#ffffff").await
            })
    }

    /// A rotation turns the drawing clockwise (y points down): a bar red on the left and blue
    /// on the right, turned 90°, is red on top and blue below.
    #[day_macros::test(day_core)]
    fn rotation_turns_clockwise() -> Case {
        Case::new()
            .proves_modifier("rotation")
            .requires(Cap::Snapshot)
            .page(|| {
                zstack((
                    rectangle().fill(Color::WHITE),
                    shape_group([
                        rectangle()
                            .fill(Color::rgb(1.0, 0.0, 0.0))
                            .at(0.0, 0.0, 0.5, 1.0),
                        rectangle()
                            .fill(Color::rgb(0.0, 0.0, 1.0))
                            .at(0.5, 0.0, 0.5, 1.0),
                    ])
                    .frame(80.0, 40.0)
                    .rotation(90.0),
                ))
                .id(day_core::id!(ground))
                .frame(120.0, 120.0)
            })
            .shot("default")
            .drive(|d: Drive| async move {
                d.sample_pixel("ground", 0.5, 0.4, "#ff0000").await?;
                d.sample_pixel("ground", 0.5, 0.6, "#0000ff").await
            })
    }

    // ---- input: every op injects Day's own event, the stream a native recognizer delivers,
    // so these prove the routing and the handler, not that the platform's recognizer fires
    // (docs/testing.md "Known gaps").

    /// A plain target for gestures: a filled rectangle of a known size.
    fn pad(id: day_core::ElementId) -> Decorated<ShapePiece> {
        rectangle()
            .fill(Color::rgb(0.2, 0.4, 0.9))
            .frame(120.0, 80.0)
            .id(id)
    }

    /// A tap runs `.on_tap`'s work, once per tap.
    #[day_macros::test(day_core)]
    fn on_tap_runs() -> Case {
        Case::new()
            .proves_modifier("on_tap")
            .page(|| {
                let taps = Signal::new(0i64);
                column((
                    label(move || format!("taps {}", taps.get())).id(day_core::id!(taps)),
                    label("Tap me")
                        .padding(12.0)
                        .on_tap(move || taps.update(|n| *n += 1))
                        .id(day_core::id!(target)),
                ))
            })
            .drive(|d: Drive| async move {
                d.tap("target").await?;
                d.tap("target").await?;
                d.assert_text("taps", "taps 2").await
            })
    }

    /// `.on_tap_at` hears where in the element the tap landed.
    #[day_macros::test(day_core)]
    fn on_tap_at_reports_point() -> Case {
        Case::new()
            .proves_modifier("on_tap_at")
            .page(|| {
                let at = Signal::new(String::from("none"));
                column((
                    label(move || format!("at {}", at.get())).id(day_core::id!(at)),
                    rectangle()
                        .fill(Color::rgb(0.2, 0.4, 0.9))
                        .frame(120.0, 80.0)
                        .on_tap_at(move |p| at.set(format!("{:.0},{:.0}", p.x, p.y)))
                        .id(day_core::id!(target)),
                ))
            })
            .drive(|d: Drive| async move {
                d.tap_at("target", 30.0, 20.0).await?;
                d.assert_text("at", "at 30,20").await
            })
    }

    /// A drag reports its phases, and its translation from where it began.
    #[day_macros::test(day_core)]
    fn on_drag_reports_translation() -> Case {
        Case::new()
            .proves_duty("enable_gesture")
            .proves_modifier("on_drag")
            .page(|| {
                let state = Signal::new(String::from("idle"));
                column((
                    label(move || state.get()).id(day_core::id!(state)),
                    pad(day_core::id!(target)).on_drag(move |d: Drag| {
                        state.set(match d.phase {
                            DragPhase::Began => "began".into(),
                            DragPhase::Changed => "moving".into(),
                            DragPhase::Ended => {
                                format!("moved {:.0},{:.0}", d.translation.x, d.translation.y)
                            }
                        })
                    }),
                ))
            })
            .drive(|d: Drive| async move {
                d.drag("target", (10.0, 10.0), (50.0, 30.0)).await?;
                d.assert_text("state", "moved 40,20").await
            })
    }

    /// Hover reports the pointer's place while it is over the element, and `None` on leaving.
    #[day_macros::test(day_core)]
    fn on_hover_enters_and_leaves() -> Case {
        Case::new()
            .proves_modifier("on_hover")
            .page(|| {
                let state = Signal::new(String::from("out"));
                column((
                    label(move || state.get()).id(day_core::id!(state)),
                    pad(day_core::id!(target)).on_hover(move |p| {
                        state.set(match p {
                            Some(p) => format!("over {:.0},{:.0}", p.x, p.y),
                            None => "out".into(),
                        })
                    }),
                ))
            })
            .drive(|d: Drive| async move {
                d.hover("target", Some((5.0, 6.0))).await?;
                d.assert_text("state", "over 5,6").await?;
                d.hover_leave("target").await?;
                d.assert_text("state", "out").await
            })
    }

    /// A pan delivers incremental deltas that add up to the whole movement.
    #[day_macros::test(day_core)]
    fn on_pan_adds_deltas() -> Case {
        Case::new()
            .proves_modifier("on_pan")
            .page(|| {
                let total = Signal::new((0.0f64, 0.0f64));
                column((
                    label(move || {
                        let (x, y) = total.get();
                        format!("pan {x:.0},{y:.0}")
                    })
                    .id(day_core::id!(total)),
                    pad(day_core::id!(target)).on_pan(move |p: Pan| {
                        total.update(|(x, y)| {
                            *x += p.delta.x;
                            *y += p.delta.y;
                        })
                    }),
                ))
            })
            .drive(|d: Drive| async move {
                d.pan("target", 40.0, -20.0).await?;
                d.assert_text("total", "pan 40,-20").await
            })
    }

    /// A pinch's scale is cumulative from where it began; its end carries the final scale.
    #[day_macros::test(day_core)]
    fn on_pinch_reports_scale() -> Case {
        Case::new()
            .proves_modifier("on_pinch")
            .page(|| {
                let scale = Signal::new(String::from("none"));
                column((
                    label(move || format!("scale {}", scale.get())).id(day_core::id!(scale)),
                    pad(day_core::id!(target)).on_pinch(move |p: Pinch| {
                        if p.phase == DragPhase::Ended {
                            scale.set(format!("{:.1}", p.scale));
                        }
                    }),
                ))
            })
            .drive(|d: Drive| async move {
                d.pinch("target", 2.5).await?;
                d.assert_text("scale", "scale 2.5").await
            })
    }

    /// A focusable element takes focus, and the keys pressed while it holds it reach `.on_key`.
    #[day_macros::test(day_core)]
    fn on_key_reaches_focused() -> Case {
        Case::new()
            .proves_duty("focus")
            .proves_duty("set_focusable")
            .proves_modifier("on_key")
            .proves_modifier("focusable")
            .page(|| {
                let last = Signal::new(String::from("none"));
                column((
                    label(move || format!("key {}", last.get())).id(day_core::id!(last)),
                    pad(day_core::id!(target))
                        .focusable()
                        .on_key(move |k| last.set(k.key.clone())),
                ))
            })
            .drive(|d: Drive| async move {
                // Focus, then a key to whatever holds focus: the route a real press takes.
                d.focus("target").await?;
                d.assert_focused("target", true).await?;
                d.key(None, "ArrowRight").await?;
                d.assert_text("last", "key ArrowRight").await
            })
    }

    /// A focus binding moves focus when the app sets it, and follows the field when it is
    /// focused natively.
    #[day_macros::test(day_core)]
    fn focused_binding_moves_focus() -> Case {
        Case::new()
            .proves_modifier("focused")
            .page(|| {
                let want = Signal::new(false);
                column((
                    label(move || format!("focused {}", want.get())).id(day_core::id!(state)),
                    button("Focus")
                        .action(move || want.set(true))
                        .id(day_core::id!(go)),
                    text_field(Signal::new(String::new()))
                        .focused(want)
                        .id(day_core::id!(field)),
                ))
            })
            .drive(|d: Drive| async move {
                d.assert_focused("field", false).await?;
                d.tap("go").await?;
                d.assert_focused("field", true).await?;
                d.assert_text("state", "focused true").await
            })
    }

    /// Destroy a focused input and its containing page without first moving focus to a
    /// button. Win32 GTK must detach the IME filter before the input loses its native root.
    #[day_macros::test(day_core)]
    fn focused_inputs_survive_page_removal() -> Case {
        Case::new()
            .proves_duty("focus")
            .page(|| {
                let shown = Signal::new(true);
                column((
                    button("Toggle page")
                        .action(move || shown.set(!shown.get()))
                        .id(day_core::id!(toggle)),
                    text_field(Signal::new(String::new())).id(day_core::id!(survivor)),
                    when(
                        move || shown.get(),
                        || {
                            column((
                                text_field(Signal::new(String::new())).id(day_core::id!(entry)),
                            ))
                            .background(Color::rgb(0.5, 0.5, 0.5))
                        },
                    ),
                ))
            })
            .drive(|d: Drive| async move {
                for _ in 0..4 {
                    d.focus("entry").await?;
                    d.assert_focused("entry", true).await?;
                    // Scripted activation doesn't move native focus to the button first.
                    d.tap("toggle").await?;
                    d.assert_missing("entry").await?;
                    d.wait_idle().await?;
                    d.tap("toggle").await?;
                }
                d.focus("survivor").await?;
                d.tap("toggle").await?;
                d.assert_focused("survivor", true).await?;
                d.input("survivor", "still editable").await?;
                d.assert_text("survivor", "still editable").await
            })
    }

    // ---- layout and the remaining modifiers -------------------------------------------------

    /// `.height` fixes the height and leaves the width to the layout.
    #[day_macros::test(day_core)]
    fn height_fixes_height() -> Case {
        Case::new()
            .proves_modifier("height")
            .page(|| {
                column((rectangle()
                    .fill(Color::rgb(1.0, 0.0, 0.0))
                    .id(day_core::id!(bar))
                    .height(37.0),))
                .width(100.0)
            })
            .drive(|d: Drive| async move {
                d.assert_frame(
                    "bar",
                    FrameExpect {
                        height: Some(37.0),
                        ..Default::default()
                    },
                )
                .await
            })
    }

    /// `.grow_h` takes the height its column has left, in a column and in a row alike.
    #[day_macros::test(day_core)]
    fn grow_vertical_fills_column() -> Case {
        Case::new()
            .proves_modifier("grow_h")
            .page(|| {
                row((
                    column((
                        rectangle()
                            .fill(Color::rgb(1.0, 0.0, 0.0))
                            .id(day_core::id!(top))
                            .frame(40.0, 20.0),
                        rectangle()
                            .fill(Color::rgb(0.0, 0.0, 1.0))
                            .id(day_core::id!(rest))
                            .width(40.0)
                            .grow_h(),
                    ))
                    .spacing(0.0)
                    .height(120.0),
                    rectangle()
                        .fill(Color::rgb(0.0, 1.0, 0.0))
                        .id(day_core::id!(both))
                        .width(30.0)
                        .grow_h(),
                ))
                .spacing(0.0)
                .align(VAlign::Top)
                .height(120.0)
            })
            .drive(|d: Drive| async move {
                d.assert_frame(
                    "rest",
                    FrameExpect {
                        height: Some(100.0),
                        ..Default::default()
                    },
                )
                .await?;
                d.assert_frame(
                    "both",
                    FrameExpect {
                        height: Some(120.0),
                        ..Default::default()
                    },
                )
                .await
            })
    }

    /// A grid cell spans the columns it asks for, and aligns within its cell as asked.
    #[day_macros::test(day_core)]
    fn grid_span_and_align() -> Case {
        Case::new()
            .proves_modifier("grid_span")
            .proves_modifier("grid_align")
            .page(|| {
                let cell = |id: day_core::ElementId, w: f64| {
                    rectangle()
                        .fill(Color::rgb(0.2, 0.4, 0.9))
                        .id(id)
                        .frame(w, 20.0)
                };
                grid((
                    grid_row((cell(day_core::id!(a), 40.0), cell(day_core::id!(b), 60.0))),
                    grid_row((cell(day_core::id!(wide), 30.0)
                        .grid_align(day_core::Alignment::TopTrailing)
                        .grid_span(2),)),
                ))
                .spacing(0.0)
                .align(day_core::Alignment::TopLeading)
            })
            .drive(|d: Drive| async move {
                // The spanning cell's rect is both columns, 100 wide; trailing puts its
                // 30-wide content at x 70 from the first column's start.
                d.assert_frame(
                    "wide",
                    FrameExpect {
                        x: Some(70.0),
                        relative_to: Some("a".into()),
                        ..Default::default()
                    },
                )
                .await
            })
    }

    /// `.overlay` draws its piece centered over the content.
    #[day_macros::test(day_core)]
    fn overlay_centers() -> Case {
        Case::new()
            .proves_modifier("overlay")
            .requires(Cap::Snapshot)
            .page(|| {
                rectangle()
                    .fill(Color::rgb(1.0, 0.0, 0.0))
                    .frame(90.0, 90.0)
                    .overlay(
                        rectangle()
                            .fill(Color::rgb(0.0, 0.0, 1.0))
                            .frame(30.0, 30.0),
                    )
                    .id(day_core::id!(base))
            })
            .drive(|d: Drive| async move {
                d.sample_pixel("base", 0.5, 0.5, "#0000ff").await?;
                d.sample_pixel("base", 0.1, 0.1, "#ff0000").await
            })
    }

    /// `.transform` takes a whole transform: here a translation and a scale together.
    #[day_macros::test(day_core)]
    fn transform_applies_whole() -> Case {
        Case::new()
            .proves_duty("set_transform")
            .proves_modifier("transform")
            .requires(Cap::Snapshot)
            .page(|| {
                zstack((
                    rectangle().fill(Color::WHITE),
                    label("")
                        .frame(20.0, 20.0)
                        .background(Color::rgb(0.0, 0.0, 1.0))
                        .transform(Transform {
                            tx: 30.0,
                            sx: 2.0,
                            sy: 2.0,
                            ..Transform::default()
                        }),
                ))
                .id(day_core::id!(ground))
                .frame(120.0, 60.0)
            })
            .drive(|d: Drive| async move {
                // Centered at x 60, moved to 90, scaled to 40 wide: 70..110 of 120.
                d.sample_pixel("ground", 0.75, 0.5, "#0000ff").await?;
                d.sample_pixel("ground", 0.5, 0.5, "#ffffff").await
            })
    }

    /// An implicit animation still lands on the final value: a square slid across by an
    /// animated translation ends where the translation says.
    #[day_macros::test(day_core)]
    fn animation_lands_on_final() -> Case {
        Case::new()
            .proves_modifier("animation")
            .requires(Cap::Snapshot)
            .page(|| {
                let moved = Signal::new(false);
                column((
                    button("Move")
                        .action(move || moved.set(true))
                        .id(day_core::id!(move_button)),
                    zstack((
                        rectangle().fill(Color::WHITE),
                        label("")
                            .frame(40.0, 40.0)
                            .background(Color::rgb(0.0, 0.0, 1.0))
                            .translation(move || if moved.get() { 80.0 } else { 0.0 }, 0.0)
                            .animation(day_spec::AnimSpec::linear(150)),
                    ))
                    .align(day_core::Alignment::Leading)
                    .id(day_core::id!(ground))
                    .frame(120.0, 40.0),
                ))
            })
            .drive(|d: Drive| async move {
                d.sample_pixel("ground", 0.1, 0.5, "#0000ff").await?;
                d.tap("move_button").await?;
                d.wait_idle().await?;
                d.pause(0.4).await?;
                d.sample_pixel("ground", 0.85, 0.5, "#0000ff").await?;
                d.sample_pixel("ground", 0.1, 0.5, "#ffffff").await
            })
    }

    /// Each way of naming an element finds it: a fixed id, a derived one, a keyed one.
    #[day_macros::test(day_core)]
    fn ids_name_elements() -> Case {
        Case::new()
            .proves_modifier("id")
            .proves_modifier("id_of")
            .page(|| {
                let n = Signal::new(1i64);
                column((
                    label("Fixed").id(day_core::id!(fixed)),
                    label("Derived").id_of(move || day_core::id!(derived, n.get())),
                    label("Keyed").id(day_core::id!(keyed, 7)),
                    button("Next")
                        .action(move || n.set(2))
                        .id(day_core::id!(next)),
                ))
            })
            .drive(|d: Drive| async move {
                d.assert_text("fixed", "Fixed").await?;
                d.assert_text("keyed:7", "Keyed").await?;
                d.assert_text("derived:1", "Derived").await?;
                d.tap("next").await?;
                d.assert_missing("derived:1").await?;
                d.assert_text("derived:2", "Derived").await
            })
    }

    /// `.tweak` runs with the realized node, and `.native_ref` holds it while the piece lives.
    #[day_macros::test(day_core)]
    fn tweak_and_native_ref_see_node() -> Case {
        Case::new()
            .proves_modifier("tweak")
            .proves_modifier("native_ref")
            .page(|| {
                let tweaked = Signal::new(false);
                let r = NativeRef::new();
                let held = r.clone();
                column((
                    label(move || format!("tweaked {}", tweaked.get())).id(day_core::id!(tweaked)),
                    label(move || format!("held {}", held.node().is_some()))
                        .id(day_core::id!(held)),
                    label("Target")
                        .tweak(move |_node| tweaked.set(true))
                        .native_ref(&r),
                ))
            })
            .drive(|d: Drive| async move {
                d.assert_text("tweaked", "tweaked true").await?;
                d.assert_text("held", "held true").await
            })
    }

    /// `.modifier` applies a reusable modifier: here, a closure that pads.
    #[day_macros::test(day_core)]
    fn modifier_applies() -> Case {
        Case::new()
            .proves_modifier("modifier")
            .page(|| {
                let padded = |content: AnyPiece| content.padding(10.0).any();
                column((label("Inner")
                    .id(day_core::id!(inner))
                    .modifier(padded)
                    .id(day_core::id!(outer)),))
                .align(HAlign::Leading)
            })
            .drive(|d: Drive| async move {
                d.assert_frame(
                    "inner",
                    FrameExpect {
                        x: Some(10.0),
                        y: Some(10.0),
                        relative_to: Some("outer".into()),
                        ..Default::default()
                    },
                )
                .await
            })
    }

    /// An announcement reaches the screen reader (the toolkit's `announce`) and the run.
    #[day_macros::test(day_core)]
    fn announce_reaches_reader() -> Case {
        Case::new()
            .proves_duty("announce")
            .proves_cap(Cap::Announce)
            .page(|| {
                button("Save")
                    .action(|| day_core::announce("Saved"))
                    .id(day_core::id!(save))
            })
            .drive(|d: Drive| async move {
                d.tap("save").await?;
                d.assert_announced("Saved").await
            })
    }
}

#[cfg(test)]
mod transfer_tests {
    use super::*;
    use day_spec::transfer::*;

    #[test]
    fn transfer_callbacks_restore_owner_scope_and_reject_after_disposal() {
        let owner = Scope::child();
        let foreign = Scope::child();
        foreign.provide(22u32);
        let (source, target) = owner.enter(|| {
            owner.provide(11u32);
            let check = || assert_eq!(day_core::environment::<u32>(), Some(11));
            (
                scoped_drag_source(Rc::new(move |_| {
                    check();
                    Some(Offer::default())
                })),
                scoped_drop_target(Target {
                    types: vec![],
                    accept: Rc::new(move |_| {
                        check();
                        Operation::Copy
                    }),
                    receive: Rc::new(move |_| {
                        check();
                        true
                    }),
                }),
            )
        });
        let location = || Location {
            position: day_spec::Point::new(40., 20.),
            types: vec![],
            allowed: vec![Operation::Copy],
            local: true,
        };
        foreign.enter(|| {
            assert!(source(day_spec::Point::new(0., 0.)).is_some());
            assert!(target.deliver(location(), Offer::default()));
            assert_eq!(day_core::environment::<u32>(), Some(22));
            owner.dispose();
            assert!(source(day_spec::Point::new(0., 0.)).is_none());
            assert_eq!(target.proposal(&location()), Operation::None);
            assert!(!(target.receive)(Drop {
                local: true,
                position: day_spec::Point::new(0., 0.),
                operation: Operation::Copy,
                items: vec![]
            }));
        });
        foreign.dispose();
    }
}