guido 0.12.0

A reactive Rust GUI library using wgpu for Wayland layer shell widgets
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
//! Container widget and related functionality.

mod anim_bridge;
mod animated_properties;
pub(in crate::widgets::container) use animated_properties::{AnimKind, AnimSlot, ContainerAnims};
mod animations;
mod box_model;
mod interaction;
mod ripple;
mod scrollable;
mod style;

#[cfg(test)]
mod characterization;

use animations::instant_transition;
pub use animations::{AdvanceResult, AnimationState, get_animated_value};
use interaction::{HitContext, untransform_point};
pub use ripple::{MAX_LIVE_RIPPLES, Ripple, RippleState};
use style::Decoration;

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

use crate::animation::{Animatable, IntoAnimated, Motion};
use crate::backdrop::BackdropBlur;
use crate::jobs::{JobRequest, JobType, RequiredJob, request_job};
use crate::layout::{Axis, Constraints, Flex, Layout, Length, Size};
use crate::pivot::Pivot;
use crate::reactive::invalidation::is_detached;
use crate::reactive::{
    CursorIcon, IntoSignal, Prop, RwSignal, create_derived, create_signal, with_signal_tracking,
};
use crate::renderer::{GradientDir, PaintContext, Shadow};
use crate::transform::{Scale, Transform, Translate};
use crate::tree::{LayoutCtx, Tree, WidgetId};
use crate::widget_ref::{WidgetRef, register_widget_ref};

use super::children::ChildrenSource;
use super::control::Control;
use super::into_child::{IntoChild, IntoChildren};
use super::paint_children::{ChildPaintOptions, paint_children};
use super::scroll::{Scroll, ScrollAxis, ScrollState, ScrollbarMetrics, ScrollbarVisibility};
use super::state_layer::{
    Moves, RippleConfig, StateStyle, StateWhen, Stateful, resolve_background,
};
use super::widget::{
    Color, Event, EventResponse, Key, LayoutHints, Modifiers, MouseButton, Padding, Placement,
    Point, Rect, ScrollSource, Widget,
};

/// Callback for click events
pub type ClickCallback = Rc<dyn Fn()>;

#[doc(hidden)]
pub struct FnHandler;
#[doc(hidden)]
pub struct CallbackHandler;
#[doc(hidden)]
pub struct OptionHandler;

/// What a click handler can be written as.
///
/// A closure is the ordinary case. A [`Callback`](crate::reactive::Callback)
/// and an `Option<Callback>` are the shapes a `#[component]` callback prop
/// arrives in, so a component can forward its own prop straight through
/// without a second method name for it.
///
/// The marker parameter is the same trick [`IntoSignal`] uses: it keeps the
/// three impls from overlapping.
pub trait IntoClickHandler<Marker = FnHandler> {
    fn into_click_handler(self) -> Option<ClickCallback>;
}

impl<F: Fn() + 'static> IntoClickHandler<FnHandler> for F {
    fn into_click_handler(self) -> Option<ClickCallback> {
        Some(Rc::new(self))
    }
}

impl IntoClickHandler<CallbackHandler> for crate::reactive::Callback {
    fn into_click_handler(self) -> Option<ClickCallback> {
        Some(Rc::new(move || self.run()))
    }
}

impl IntoClickHandler<OptionHandler> for Option<crate::reactive::Callback> {
    fn into_click_handler(self) -> Option<ClickCallback> {
        self.map(|cb| Rc::new(move || cb.run()) as ClickCallback)
    }
}

/// Callback for a key-down: the key, the modifiers held with it, and whether
/// a held key produced it rather than a press. Answers whether it took the key.
pub type KeyCallback = Rc<dyn Fn(Key, Modifiers, bool) -> EventResponse>;
/// Callback for a key-up: the key, and the modifiers held as it was released.
/// Answers whether it took the key.
pub type KeyUpCallback = Rc<dyn Fn(Key, Modifiers) -> EventResponse>;
/// Callback for hover events (bool = is_hovered)
pub type HoverCallback = Rc<dyn Fn(bool)>;
/// Callback for scroll events (delta_x, delta_y, source)
pub type ScrollCallback = Rc<dyn Fn(f32, f32, ScrollSource)>;
/// Callback for pointer move events (x, y in container-local coords)
pub type PointerMoveCallback = Rc<dyn Fn(f32, f32)>;
/// Callback for mouse down events (x, y in container-local coords)
pub type MouseDownCallback = Rc<dyn Fn(f32, f32)>;
/// Callback for mouse up events (x, y in container-local coords)
pub type MouseUpCallback = Rc<dyn Fn(f32, f32)>;

/// Gradient direction for linear gradients
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GradientDirection {
    /// Left to right
    Horizontal,
    /// Top to bottom
    Vertical,
    /// Top-left to bottom-right
    Diagonal,
    /// Top-right to bottom-left
    DiagonalReverse,
}

impl From<GradientDirection> for GradientDir {
    fn from(direction: GradientDirection) -> Self {
        match direction {
            GradientDirection::Horizontal => GradientDir::Horizontal,
            GradientDirection::Vertical => GradientDir::Vertical,
            GradientDirection::Diagonal => GradientDir::Diagonal,
            GradientDirection::DiagonalReverse => GradientDir::DiagonalReverse,
        }
    }
}

/// Linear gradient definition
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct LinearGradient {
    pub start_color: Color,
    pub end_color: Color,
    pub direction: GradientDirection,
}

impl LinearGradient {
    pub fn new(start: Color, end: Color, direction: GradientDirection) -> Self {
        Self {
            start_color: start,
            end_color: end,
            direction,
        }
    }

    pub fn horizontal(start: Color, end: Color) -> Self {
        Self::new(start, end, GradientDirection::Horizontal)
    }

    pub fn vertical(start: Color, end: Color) -> Self {
        Self::new(start, end, GradientDirection::Vertical)
    }

    /// Top-left to bottom-right.
    pub fn diagonal(start: Color, end: Color) -> Self {
        Self::new(start, end, GradientDirection::Diagonal)
    }
}

/// Border definition
#[derive(Debug, Clone, Copy)]
pub struct Border {
    pub width: f32,
    pub color: Color,
}

impl Border {
    pub fn new(width: impl crate::layout::IntoF32, color: Color) -> Self {
        Self {
            width: width.into_f32(),
            color,
        }
    }
}

/// Overflow behavior for container content
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Overflow {
    /// Content is not clipped and may overflow the container bounds
    #[default]
    Visible,
    /// Content is clipped to the container bounds
    Hidden,
}

/// What the renderer applies to a container's subtree as a whole: the three
/// transform components, the point they act about, and the opacity. Boxed and
/// absent by default, like `anims` and `interaction`.
///
/// Five property fields on every container in every tree, and the
/// overwhelming majority declare none — so they live behind a pointer, and a
/// container that declares none of them does not follow it. The grouping is
/// the one Compose's `graphicsLayer` and Core Animation's `CALayer` make: each
/// is a property of the layer a subtree is drawn as, not of anything drawn in
/// it.
#[derive(Default)]
pub(super) struct LayerProps {
    pub(super) translate: Prop<Translate>,
    pub(super) rotate: Prop<f32>,
    pub(super) scale: Prop<Scale>,
    pub(super) pivot: Prop<Pivot>,
    pub(super) opacity: Prop<f32>,
}

/// The two decorations a container rarely has. Boxed and absent by default,
/// for the reason [`LayerProps`] above is.
///
/// What earns a place here is being **both large and rarely declared**. A
/// `LinearGradient` is two colours and a direction and a `Shadow` is an offset,
/// a blur, a spread and a colour — 36 bytes each, and since #450 a property
/// field holds its value inline, so `Prop::Unset` occupies all 36 whether
/// anything was declared or not. `backdrop_blur` is as rare and fails the other
/// half at 12 bytes, so it stays where it is.
#[derive(Default)]
pub(super) struct DecorationProps {
    pub(super) gradient: Prop<Option<LinearGradient>>,
    pub(super) shadow: Prop<Shadow>,
}

bitflags::bitflags! {
    /// What the pointer is doing to this container.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
    pub(crate) struct InteractionFlags: u8 {
        const HOVERED = 1;
        const PRESSED = 2;
    }
}

/// Interaction state (callbacks, hover/press tracking, state styles, ripple).
/// Only allocated when `.on_click()`, `.when_hovered()`, `.when_pressed()`, etc. are called.
pub(super) struct InteractionState {
    pub(super) on_click: Option<ClickCallback>,
    pub(super) on_right_click: Option<ClickCallback>,
    pub(super) on_middle_click: Option<ClickCallback>,
    pub(super) on_key_down: Option<KeyCallback>,
    pub(super) on_key_up: Option<KeyUpCallback>,
    pub(super) on_hover: Option<HoverCallback>,
    pub(super) on_scroll: Option<ScrollCallback>,
    pub(super) on_pointer_move: Option<PointerMoveCallback>,
    pub(super) on_mouse_down: Option<MouseDownCallback>,
    pub(super) on_mouse_up: Option<MouseUpCallback>,
    /// Whether Tab stops here, and a press inside takes the focus.
    pub(super) focusable: bool,
    /// Hover and press, behind a signal so that *resolving a state layer
    /// subscribes to them*.
    ///
    /// This is the whole point. The container's own paint subscribes, as
    /// before — but so does any descendant text whose colour resolves through
    /// this container, and that is what a plain `bool` plus a hand-written
    /// `request_job(id, Paint)` could never do: it marked one widget, and the
    /// text's cached paint node was reused with the old colour still in it.
    ///
    /// Read with `get_untracked` from event handling, where the value drives
    /// *behaviour* (drag capture, ripple) and a subscription would be noise;
    /// with `get` from style resolution, where the subscription is the point.
    pub(super) flags: RwSignal<InteractionFlags>,
    /// State layers in declaration order. Resolution walks it backwards, so
    /// the last one declared wins wherever two of them speak about the same
    /// property — CSS's rule at equal specificity, and the only one that lets
    /// a caller decide that an error outranks the focus.
    pub(super) states: Vec<(StateWhen, StateStyle)>,
    /// Which of `translate`, `rotate` and `scale` the declared layers override
    /// between them.
    ///
    /// Decided when the layer is pushed, because that is when it is knowable —
    /// a layer either names the property or it does not, and no signal is
    /// involved. Kept rather than rescanned because it gates the identity fast
    /// path in `animated_transform`, which runs on every paint and every
    /// coalesced pointer move: a button with hover, focus and pressed layers
    /// would otherwise walk three `StateStyle`s to be told nothing turns.
    ///
    /// Three answers rather than one, because that fast path is per component:
    /// `when_pressed(|s| s.scale(0.98))` is the commonest state layer there is,
    /// and a single bit would have made it pay for a translate and a rotate
    /// nothing declares.
    pub(super) declares_transform: Moves,
    /// What this container was declared with, and — once the tree has been in
    /// hand — what that means with the enclosing control's answer folded in.
    ///
    /// Two fields because they answer two questions. `declared_enabled` is
    /// what gates events: dispatch is one recursive walk, so a container that
    /// returns before asking its children *is* the propagation, and reading
    /// the folded answer there would be asking the same ancestors twice.
    /// `enabled` is what a style resolves against, and that question has to be
    /// answerable with no tree — from inside a `create_derived` closure — so
    /// the ancestry is folded once, at registration, into a signal.
    pub(super) declared_enabled: Prop<bool>,
    pub(super) enabled: Prop<bool>,
    /// The pointer's shape over this container — see
    /// [`cursor`](Container::cursor).
    pub(super) cursor: Prop<CursorIcon>,
    pub(super) ripple: RippleState,
}

impl Default for InteractionState {
    fn default() -> Self {
        Self {
            on_click: None,
            on_right_click: None,
            on_middle_click: None,
            on_key_down: None,
            on_key_up: None,
            on_hover: None,
            on_scroll: None,
            on_pointer_move: None,
            on_mouse_down: None,
            on_mouse_up: None,
            focusable: false,
            flags: create_signal(InteractionFlags::empty()),
            states: Vec::new(),
            declares_transform: Moves::default(),
            declared_enabled: Prop::Unset,
            enabled: Prop::Unset,
            cursor: Prop::Unset,
            ripple: RippleState::new(),
        }
    }
}

impl InteractionState {
    /// The raw flag, untracked and **ungated by `enabled`** — unlike
    /// [`Control::is_hovered`], which is what a style asks. Event handling can
    /// use it because it never reaches a disabled container: the gate at the
    /// top of `Container::event` returned long before.
    pub(super) fn is_hovered(&self) -> bool {
        self.flags
            .get_untracked()
            .contains(InteractionFlags::HOVERED)
    }

    pub(super) fn is_pressed(&self) -> bool {
        self.flags
            .get_untracked()
            .contains(InteractionFlags::PRESSED)
    }

    /// Set a flag, writing only on a real change so an unchanged pointer move
    /// does not wake every subscriber.
    pub(super) fn set_flag(&self, flag: InteractionFlags, on: bool) {
        let current = self.flags.get_untracked();
        let next = if on { current | flag } else { current - flag };
        if next != current {
            self.flags.set(next);
        }
    }

    /// Whether any state layer is declared at all.
    ///
    /// Gates the subscription in style resolution: a container with only an
    /// `on_click` has nothing to resolve, and must not start repainting on
    /// every hover just because the flags became reactive.
    pub(super) fn has_any_state(&self) -> bool {
        !self.states.is_empty()
    }

    /// Whether a layer with this trigger is declared, without reading any
    /// signal — the gate event handling uses before asking for a repaint.
    pub(super) fn declares(&self, when: impl Fn(&StateWhen) -> bool) -> bool {
        self.states.iter().any(|(w, _)| when(w))
    }

    /// The ripple a pressed layer declares, if one does.
    ///
    /// By value: the caller advances `self.ripple` while holding it, and a
    /// borrow of the whole `InteractionState` would stand in the way of a
    /// borrow of one of its fields.
    pub(super) fn ripple_config(&self) -> Option<RippleConfig> {
        self.states
            .iter()
            .rev()
            .find(|(when, s)| matches!(when, StateWhen::Pressed) && s.ripple.is_some())
            .and_then(|(_, s)| s.ripple)
    }

    /// This container as the interaction unit it is, which is what resolves its
    /// own state layers.
    ///
    /// A container asks [`Control::is_active`] exactly as a `Text` below it
    /// does, so the two cannot come to disagree about the unit they share.
    pub(super) fn as_control(&self, id: WidgetId) -> Control {
        Control::new(id, self.flags, self.enabled)
    }
}

/// Scroll state and configuration, boxed to avoid bloating Container.
/// Only allocated when `.scroll()` is called.
pub(super) struct ScrollData {
    /// What the application declared. Holds the signals and the two styling
    /// closures; nothing reads it per frame except to resolve the metrics.
    pub(super) scroll: Scroll,
    /// The declared measurements, resolved under this pass's layout tracking.
    /// The track and handle rects are arithmetic and read this, not signals.
    pub(super) metrics: ScrollbarMetrics,
    /// What `visibility` said when layout last read it.
    pub(super) scrollbar_visibility: ScrollbarVisibility,
    /// What `fill_viewport` said when layout last read it.
    pub(super) fill_viewport: bool,
    pub(super) scroll_state: ScrollState,
    pub(super) v_scrollbar_track_id: Option<WidgetId>,
    pub(super) v_scrollbar_handle_id: Option<WidgetId>,
    pub(super) v_scrollbar_scale_anim: Option<AnimationState<f32>>,
    pub(super) h_scrollbar_track_id: Option<WidgetId>,
    pub(super) h_scrollbar_handle_id: Option<WidgetId>,
    pub(super) h_scrollbar_scale_anim: Option<AnimationState<f32>>,
}

impl ScrollData {
    /// Built from the declaration and nothing else — there is no default axis
    /// to invent, because a `Scroll` always names one.
    ///
    /// The resolved fields start at their own defaults and are overwritten by
    /// `resolve_scroll` at the top of the first layout, before anything reads
    /// them.
    fn new(scroll: Scroll) -> Self {
        Self {
            scroll,
            metrics: ScrollbarMetrics::default(),
            scrollbar_visibility: ScrollbarVisibility::Always,
            fill_viewport: false,
            scroll_state: ScrollState::default(),
            v_scrollbar_track_id: None,
            v_scrollbar_handle_id: None,
            v_scrollbar_scale_anim: None,
            h_scrollbar_track_id: None,
            h_scrollbar_handle_id: None,
            h_scrollbar_scale_anim: None,
        }
    }
}

pub struct Container {
    // Layout and children
    pub(super) layout: Box<dyn Layout>,
    pub(super) children_source: ChildrenSource,

    // Styling properties
    pub(super) padding: Prop<Padding>,
    pub(super) background: Prop<Color>,
    pub(super) corners: Prop<crate::widgets::Corners>,
    pub(super) border_width: Prop<f32>,
    pub(super) border_color: Prop<Color>,
    pub(super) width: Prop<Length>,
    pub(super) height: Prop<Length>,
    pub(super) overflow: Prop<Overflow>,
    /// What `overflow` resolved to in the last layout or paint.
    ///
    /// Event dispatch needs the value the *drawn* frame used, not the current
    /// one: it tests against `hit.bounds`, which come from the last layout, and
    /// a clip that disagreed with the box it is clipping would answer for a
    /// point the geometry says nothing about. The tracked reads that do
    /// subscribe write here on their way past.
    ///
    /// It is also cheaper than re-reading a closure-backed signal for every
    /// container under the pointer on every coalesced `MouseMove` — but only
    /// one such read of several on that path, so that is a bonus rather than
    /// the reason.
    pub(super) overflow_resolved: Cell<Overflow>,
    /// How far past its own bounds the last layout sized this container's
    /// damage rect to reach — the extent of the deepest shadow it can cast.
    ///
    /// Written by `layout` and read by `animated_shadow`, so the shadow that is
    /// drawn and the rect that is repainted are the *same number* rather than
    /// two computations of it. They were two, and they disagreed: paint asked
    /// [`max_shadow_extent`](style) again, which reads the shadow signal at its
    /// current value, so a card animating from a deep shadow to none was clamped
    /// to the nothing it had not reached yet and the shadow vanished in one
    /// frame while the animation went on running.
    pub(super) shadow_reach: Cell<f32>,
    pub(super) visible: Prop<bool>,
    pub(super) layer: Option<Box<LayerProps>>,
    pub(super) decoration: Option<Box<DecorationProps>>,

    // Interaction state (callbacks, hover/press, state styles, ripple)
    // Only allocated when interaction features are used
    pub(super) interaction: Option<Box<InteractionState>>,

    // Widget ref for reactive bounds tracking
    pub(super) widget_ref: Option<WidgetRef>,

    // Backdrop blur: this surface's own content, the compositor's, or both.
    pub(super) backdrop_blur: Prop<BackdropBlur>,
    /// Whether pointer and touch input reaches this container's area, said to
    /// the compositor rather than to the hit test — see
    /// [`takes_input`](Container::takes_input).
    pub(super) takes_input: Prop<bool>,

    /// Declared with `control()`. A container is an interaction unit for other
    /// reasons too — see `is_control` — so this is only the explicit half.
    pub(super) declared_control: bool,

    // Animation state, boxed: ~2.4KB that a container declaring no motion
    // never allocates.
    pub(super) anims: Option<Box<ContainerAnims>>,

    // Scroll configuration
    pub(super) scroll_axis: ScrollAxis,
    pub(super) scroll_data: Option<Box<ScrollData>>,

    /// The axis the last layout left the children ordered along, if any.
    ///
    /// `paint` narrows the children to a cull rect with a binary search, and a
    /// binary search needs a partitioned slice. Which axis partitions them —
    /// and whether any does — is a property of what the layout *did*, not of
    /// what the container was declared with: a `Flex::row()` under a vertical
    /// scroller orders its children along x, and a layout free to put them
    /// anywhere orders them along neither.
    ///
    /// So it is measured once per layout, where the walk over the children is
    /// already happening and is off the frame path, rather than asked of
    /// `Layout` at every paint.
    pub(super) children_sorted_along: Option<Axis>,
}

/// What [`Container::placed`] answers.
struct Placed {
    transform: Transform,
    pivot: Pivot,
    scroll: (f32, f32),
}

impl Container {
    pub fn new() -> Self {
        let children_source = ChildrenSource::default();
        Self {
            layout: Box::new(Flex::column()),
            children_source,
            padding: Prop::Unset,
            background: Prop::Unset,
            corners: Prop::Unset,
            border_width: Prop::Unset,
            border_color: Prop::Unset,
            width: Prop::Unset,
            height: Prop::Unset,
            overflow: Prop::Unset,
            overflow_resolved: Cell::new(Overflow::Visible),
            shadow_reach: Cell::new(0.0),
            visible: Prop::Unset,
            layer: None,
            decoration: None,
            interaction: None,
            widget_ref: None,
            backdrop_blur: Prop::Unset,
            takes_input: Prop::Unset,
            declared_control: false,
            anims: None,
            scroll_axis: ScrollAxis::None,
            scroll_data: None,
            children_sorted_along: None,
        }
    }

    /// Where a transform can carry what this container draws, published for
    /// whoever is about to decide whether to paint it.
    ///
    /// Read inside this widget's own *Paint* scope, which both callers of
    /// `refresh_paint_bounds` open around it. The transform components belong
    /// to paint, and subscribing *layout* to them would make
    /// `.translate(move || ..)` reflow on every write — which is why the scope
    /// is the Paint one and not whichever happens to be open.
    ///
    /// The schedule still carries the ordinary case: the same write queues a
    /// Paint job, and `refresh_paint_bounds` runs from it before this frame
    /// paints. The subscription is for the case the schedule cannot reach — a
    /// widget culled before it ever painted, whose paint never ran to read
    /// anything (#319).
    fn publish_paint_reach(&self, tree: &mut Tree, id: WidgetId, bounds: Rect) {
        let shadow_extent = self.shadow_reach.get();
        // Only this container's own half. What its children add is
        // `children_outset`, which the tree keeps for it — gathered upward as
        // they publish, and re-measured whenever this container lays out. That
        // split is what lets this run from a Paint job without walking
        // anything.
        tree.set_own_paint_reach(id, self.max_transform_reach(bounds, shadow_extent));
    }

    /// Resolve the declared scroll measurements for this pass.
    ///
    /// At the top of `layout`, inside the Layout scope the call opened, because
    /// the gutter these describe comes out of the content box before anything is
    /// measured
    /// — so a width written to a signal has to re-run this container's layout,
    /// not merely repaint it. The geometry below reads the resolved numbers:
    /// a track rect is arithmetic, and arithmetic should not be reading signals
    /// halfway through.
    fn resolve_scroll(&mut self) {
        let Some(data) = self.scroll_data.as_mut() else {
            return;
        };
        let scroll = &data.scroll;
        let defaults = ScrollbarMetrics::default();
        let width = scroll.width.get_or(defaults.width);
        data.metrics = ScrollbarMetrics {
            width,
            hover_width: scroll
                .hover_width
                .get_or(width * defaults.hover_width / defaults.width),
            margin: scroll.margin.get_or(defaults.margin),
            min_handle_size: scroll.min_handle_size.get_or(defaults.min_handle_size),
            reserve_gutter: scroll.reserve_gutter.get_or(defaults.reserve_gutter),
        };
        data.scrollbar_visibility = scroll.visibility.get_or(ScrollbarVisibility::Always);
        data.fill_viewport = scroll.fill_viewport.get_or(false);
    }

    /// Where this container draws itself and its children against where it
    /// was laid out: its own transform, the pivot that turns about, and the
    /// scroll offset it moves its children by.
    ///
    /// Paint, the hit test and [`Widget::placement`] all read the three through
    /// here, so what a widget ref reports, where a click lands and what is
    /// drawn cannot disagree about where this container is. `bounds` is the
    /// laid-out box a relative translate is a fraction of.
    fn placed(&self, id: WidgetId, bounds: Rect) -> Placed {
        let scroll = if self.scroll_axis != ScrollAxis::None {
            let sd = self.scroll_data();
            (sd.scroll_state.offset_x, sd.scroll_state.offset_y)
        } else {
            (0.0, 0.0)
        };
        Placed {
            transform: self.animated_transform(id, bounds),
            pivot: self.resolved_pivot(id),
            scroll,
        }
    }

    /// Get scroll data (panics if not scrollable — only call when scroll_axis != None)
    fn scroll_data(&self) -> &ScrollData {
        self.scroll_data.as_deref().expect("scroll_data not set")
    }

    /// Get mutable scroll data (panics if not scrollable)
    fn scroll_mut(&mut self) -> &mut ScrollData {
        self.scroll_data
            .as_deref_mut()
            .expect("scroll_data not set")
    }

    /// Get or create the layer properties.
    fn layer_mut(&mut self) -> &mut LayerProps {
        self.layer.get_or_insert_with(Box::default)
    }

    /// Get or create the decoration group.
    fn decoration_mut(&mut self) -> &mut DecorationProps {
        self.decoration.get_or_insert_with(Box::default)
    }

    pub(super) fn gradient_prop(&self) -> Prop<Option<LinearGradient>> {
        self.decoration
            .as_deref()
            .map_or(Prop::Unset, |d| d.gradient)
    }

    pub(super) fn shadow_prop(&self) -> Prop<Shadow> {
        self.decoration.as_deref().map_or(Prop::Unset, |d| d.shadow)
    }

    pub(super) fn translate_prop(&self) -> Prop<Translate> {
        self.layer.as_deref().map_or(Prop::Unset, |t| t.translate)
    }

    pub(super) fn rotate_prop(&self) -> Prop<f32> {
        self.layer.as_deref().map_or(Prop::Unset, |t| t.rotate)
    }

    pub(super) fn scale_prop(&self) -> Prop<Scale> {
        self.layer.as_deref().map_or(Prop::Unset, |t| t.scale)
    }

    pub(super) fn pivot_prop(&self) -> Prop<Pivot> {
        self.layer.as_deref().map_or(Prop::Unset, |t| t.pivot)
    }

    pub(super) fn opacity_prop(&self) -> Prop<f32> {
        self.layer.as_deref().map_or(Prop::Unset, |t| t.opacity)
    }

    /// Get or create interaction state
    fn interact_mut(&mut self) -> &mut InteractionState {
        self.interaction.get_or_insert_with(Box::default)
    }

    /// Set the layout strategy for this container
    pub fn layout(mut self, layout: impl Layout + 'static) -> Self {
        self.layout = Box::new(layout);
        self
    }

    /// Add a single child: a widget value, an `Option` of one, or a closure
    /// returning either for reactive content.
    ///
    /// ```
    /// # use guido::prelude::*;
    /// # let admin = true;
    /// # let count = create_signal(0i32);
    /// container().child(text("always"));
    /// container().child(admin.then(|| text("sometimes")));  // absent when None
    /// container().child(move || (count.get() > 0).then(|| text("badge")));
    /// ```
    pub fn child<M>(mut self, child: impl IntoChild<M>) -> Self {
        child.add_to_container(&mut self.children_source);
        self
    }

    /// Add multiple children (static or dynamic)
    pub fn children<M>(mut self, children: impl IntoChildren<M>) -> Self {
        children.add_to_container(&mut self.children_source);
        self
    }

    /// Set padding in logical pixels.
    ///
    /// Accepts multiple formats via `From` conversions:
    /// - `padding(8.0)` or `padding(8)` — uniform on all sides
    /// - `padding([8.0, 16.0])` — `[vertical, horizontal]` (CSS 2-value shorthand)
    /// - `padding([1.0, 2.0, 3.0, 4.0])` — `[top, right, bottom, left]` (CSS 4-value)
    /// - `padding(Padding::all(8.0).with_top(20.0))` — builder pattern
    /// - `padding(signal)` or `padding(move || ...)` — reactive
    /// - `padding(8.0.transition(200.0))` — eased instead of jumped to
    pub fn padding<M>(mut self, value: impl IntoAnimated<Padding, M>) -> Self {
        self.padding = animated_properties::declare::padding(&mut self.anims, value);
        self
    }

    /// Set the background fill color.
    ///
    /// Supports RGBA transparency. Use [`Color::TRANSPARENT`] for no background.
    /// Accepts static values or reactive signals/closures.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// # struct Theme { surface: Color }
    /// # let theme = Theme { surface: Color::rgb(0.12, 0.12, 0.16) };
    /// # let flash = || Keyframes::new(200.0).at(0.0, Color::BLACK).at(0.5, Color::WHITE).at(1.0, Color::BLACK);
    /// # let errors = create_signal(0u32);
    /// container().background(Color::rgb(0.2, 0.2, 0.3));
    /// container().background(Color::rgba(0.0, 0.0, 0.0, 0.5));  // 50% transparent black
    /// container().background(theme.surface.transition(200.0));  // eased
    /// container().background(theme.surface.timeline(flash().played_by(errors)));
    /// ```
    pub fn background<M>(mut self, color: impl IntoAnimated<Color, M>) -> Self {
        self.background = animated_properties::declare::background(&mut self.anims, color);
        self
    }

    // -----------------------------------------------------------------------
    // Shape
    // -----------------------------------------------------------------------

    /// The shape of the corners: how far they are rounded, and how.
    ///
    /// A bare size means rounded corners: one value for all four,
    /// `[top, bottom]` for the two pairs, or `[top-left, top-right,
    /// bottom-right, bottom-left]` clockwise as CSS writes it. A constructor
    /// names another shape:
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// container().corners(8.0);
    /// container().corners([16.0, 0.0]);
    /// container().corners(Corners::squircle(12.0));
    /// container().corners(Corners::bevel([16.0, 0.0]));
    /// ```
    ///
    /// The shape reaches everything: the box, its border and shadow, the blur
    /// behind it, the clip its children are cut to, and the region that
    /// answers a click.
    ///
    /// A shape that eases carries its own timing —
    /// `corners(8.0.transition(250.0))`. A transition that crosses zero
    /// curvature changes family in one frame: below zero a corner is concave,
    /// and the formula that draws it (and the one that answers a click) is a
    /// different one. Within a family it is continuous.
    pub fn corners<M>(mut self, corners: impl IntoAnimated<crate::widgets::Corners, M>) -> Self {
        self.corners = animated_properties::declare::corners(&mut self.anims, corners);
        self
    }

    /// Blur what is already behind this container.
    ///
    /// Both backdrops are filtered: what this surface has already drawn, and
    /// what the compositor composites below it where the surface is
    /// translucent. Pair it with a translucent
    /// [`background()`](Self::background) so the result shows through.
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// container()
    ///     .corners(16.0)
    ///     .backdrop_blur(32.0)
    ///     .background(Color::rgba(0.1, 0.1, 0.15, 0.6));
    /// ```
    ///
    /// Restrict it with [`BackdropSources`](crate::backdrop::BackdropSources) when
    /// only one side should soften.
    /// The compositor side needs `ext-background-effect-v1` — check
    /// [`compositor_effects()`](crate::compositor::compositor_effects) — and
    /// carries no radius of its own; the compositor picks one.
    ///
    /// See [`crate::backdrop`] for why both are filtered rather than one
    /// being chosen.
    /// A radius of `0.0` is "no blur", so a blur can be switched off by the
    /// same signal that switches it on — the shape
    /// [`Text::backdrop_blur`](crate::widgets::Text::backdrop_blur) already has.
    /// That is the radius saying so, so it holds wherever the surface is a
    /// source. A blur restricted to the compositor has no radius of its own to
    /// say it with, and asks for its region on its sources alone; switch that
    /// one off with [`BackdropSources::empty`](crate::backdrop::BackdropSources::empty).
    pub fn backdrop_blur<M>(mut self, blur: impl IntoSignal<BackdropBlur, M>) -> Self {
        self.backdrop_blur = blur.into_prop();
        self
    }

    /// Whether pointer and touch input reaches this container's area at all.
    ///
    /// This is not the hit test. It is what the *compositor* is told, so
    /// `takes_input(false)` does not merely stop this container answering: the
    /// click goes to whatever is behind the surface, a terminal or the desktop.
    /// A container that should refuse input without giving it away is
    /// [`enabled(false)`](Self::enabled), which is a state and keeps blocking
    /// what is underneath.
    ///
    /// The surface says the baseline and a container says the exception. A
    /// surface takes input everywhere unless it declares
    /// [`click_through`](crate::surface::SurfaceConfig::click_through), so:
    ///
    /// ```
    /// # use guido::prelude::*;
    /// // an island in a surface that lets everything else past
    /// container().takes_input(true).corners(20.0);
    ///
    /// // a hole in a bar, where the desktop gets the click
    /// container().takes_input(false).width(200.0);
    /// ```
    ///
    /// **What is declared is this container's own shape, and nothing else.**
    /// Children are covered because they are drawn inside it, not because the
    /// declaration reaches them — so a child that draws *outside* it, which
    /// `overflow(Visible)` allows, is outside the region too:
    ///
    /// ```
    /// # use guido::prelude::*;
    /// # let do_thing = || {};
    /// container()
    ///     .takes_input(true)
    ///     .width(100.0)
    ///     .height(30.0)
    ///     // Drawn 40px below the parent, so outside what it declared: on a
    ///     // click-through surface this handler never runs, because the
    ///     // compositor sends that click to whatever is behind.
    ///     .child(container().translate((0.0, 40.0)).on_click(do_thing));
    /// ```
    ///
    /// It is the container's shape rather than its subtree because a region is
    /// sent to the compositor as rectangles: one declaration is one shape, and
    /// a declaration every descendant inherited would be a shape per painting
    /// widget, every frame the region moves.
    ///
    /// A descendant declaring the opposite is a smaller area declared later, so
    /// an island inside a hole needs no rule of its own.
    ///
    /// The region follows the shape on screen — its corners, its transform, its
    /// clip — because it is read off the frame that was drawn, and it is gone
    /// the moment the container stops painting.
    pub fn takes_input<M>(mut self, takes: impl IntoSignal<bool, M>) -> Self {
        self.takes_input = takes.into_prop();
        self
    }

    /// The shape the pointer takes over this container.
    ///
    /// Resolved from the point after every pointer event: the innermost
    /// widget under it that declares a cursor wins, and with none the pointer
    /// is the arrow. So a clickable row says `Pointer` once, and a field
    /// inside it still shows its I-beam over itself — or whatever its own
    /// [`cursor`](crate::widgets::TextInput::cursor) says — and hands the
    /// row's shape back the moment the pointer leaves it:
    ///
    /// ```
    /// # use guido::prelude::*;
    /// # let open = || {};
    /// # let query = create_signal(String::new());
    /// container()
    ///     .cursor(CursorIcon::Pointer)
    ///     .on_click(open)
    ///     .child(text_input(query));
    /// ```
    ///
    /// A shape that is about the whole surface rather than one place on it —
    /// busy while something loads — is this, on the root:
    ///
    /// ```
    /// # use guido::prelude::*;
    /// # let loading = create_signal(false);
    /// container().cursor(move || {
    ///     if loading.get() { CursorIcon::Wait } else { CursorIcon::Default }
    /// });
    /// ```
    ///
    /// A container that does not [take input](Self::takes_input) claims
    /// nothing, and whatever is beneath it answers instead.
    pub fn cursor<M>(mut self, cursor: impl IntoSignal<CursorIcon, M>) -> Self {
        self.interact_mut().cursor = cursor.into_prop();
        self
    }

    /// Set a border: a width and a colour, together.
    ///
    /// Both halves, always — a width with no colour and a colour with no width
    /// are the same thing, which is no border, so there is nothing for a
    /// half-declaration to mean. Each half takes a signal of its own, so
    /// anything that has to change over time already can:
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// # struct Theme { line: Color, danger: Color }
    /// # let theme = Theme { line: Color::rgb(0.3, 0.3, 0.35), danger: Color::rgb(0.9, 0.3, 0.2) };
    /// # let failed = create_signal(false);
    /// container().border(1.5, move || if failed.get() { theme.danger } else { theme.line });
    /// ```
    ///
    /// A state layer says it the same way, and replaces the whole border:
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// # struct Theme { line: Color, accent: Color }
    /// # let theme = Theme { line: Color::rgb(0.3, 0.3, 0.35), accent: Color::rgb(0.4, 0.6, 1.0) };
    /// container()
    ///     .border(1.5, theme.line)
    ///     .when_focused(|s| s.border(1.5, theme.accent));
    /// ```
    ///
    /// A width repeated across layers is a constant in your own code — there is
    /// deliberately no way to leave half a border unsaid.
    ///
    /// Each half carries its own timing, which is what the pair wanted: the
    /// two channels are different types and a border can spring open while its
    /// colour eases.
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// # let thick = create_signal(false);
    /// container().border(
    ///     (move || if thick.get() { 14.0 } else { 2.0 }).transition(SpringConfig::BOUNCY),
    ///     Color::rgb(0.40, 0.50, 0.70).transition(300.0),
    /// );
    /// ```
    pub fn border<M1, M2>(
        mut self,
        width: impl IntoAnimated<f32, M1>,
        color: impl IntoAnimated<Color, M2>,
    ) -> Self {
        self.border_width = animated_properties::declare::border_width(&mut self.anims, width);
        self.border_color = animated_properties::declare::border_color(&mut self.anims, color);
        self
    }

    /// Set a linear gradient background. Replaces the solid fill while it is
    /// there.
    ///
    /// `None` is "no gradient", so the background shows through again — the same
    /// contract a radius of `0.0` gives
    /// [`backdrop_blur`](Self::backdrop_blur), and for the same reason: without
    /// a value meaning *off*, a gradient that only applies sometimes forces the
    /// caller back to branching in Rust and rebuilding the widget.
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// # struct Theme { surface: Color }
    /// # let theme = Theme { surface: Color::rgb(0.12, 0.12, 0.16) };
    /// # let expanded = create_signal(false);
    /// # let palette = create_signal(LinearGradient::horizontal(Color::WHITE, Color::BLACK));
    /// container()
    ///     .background(theme.surface)
    ///     .gradient(move || expanded.get().then(|| palette.get()));
    /// ```
    pub fn gradient<M>(mut self, gradient: impl IntoSignal<Option<LinearGradient>, M>) -> Self {
        self.decoration_mut().gradient = gradient.into_prop();
        self
    }

    /// Set the width of the container.
    ///
    /// `width(w.transition(200.0))` grows and shrinks over time instead of
    /// jumping. A size follows the content it holds as well as the length
    /// declared here, so the animation is over the resolved extent.
    pub fn width<M>(mut self, width: impl IntoAnimated<Length, M>) -> Self {
        self.width = animated_properties::declare::width(&mut self.anims, width);
        self
    }

    /// Set the height of the container. Eases the same way
    /// [`width`](Self::width) does.
    pub fn height<M>(mut self, height: impl IntoAnimated<Length, M>) -> Self {
        self.height = animated_properties::declare::height(&mut self.anims, height);
        self
    }

    /// Set the overflow behaviour for content that exceeds the container bounds.
    pub fn overflow<M>(mut self, overflow: impl IntoSignal<Overflow, M>) -> Self {
        let declared = overflow.into_prop();
        // Seed the cache the event path reads, so a container declared clipped
        // is clipped for the first event too, without depending on a layout
        // having run first.
        self.overflow_resolved
            .set(declared.get_or_untracked(Overflow::Visible));
        self.overflow = declared;
        self
    }

    /// Set visibility of this container.
    ///
    /// When `visible` is false, the container takes up no space in layout,
    /// does not paint, and ignores all events. Nothing inside it advances an
    /// animation while it is hidden, except an exit, which plays out so that
    /// its widget can leave.
    pub fn visible<M>(mut self, visible: impl IntoSignal<bool, M>) -> Self {
        self.visible = visible.into_prop();
        self
    }

    /// Whether this container and everything below it accepts input.
    ///
    /// A disabled subtree takes no clicks, no keys and no scrolls: the event
    /// stops here, so nothing below it has to know why. It is still laid out
    /// and still painted exactly as declared — greying it out is
    /// [`when_disabled`](crate::widgets::Stateful::when_disabled), which reads
    /// the same declaration, so the look and the behaviour cannot come apart:
    ///
    /// ```
    /// use guido::prelude::*;
    ///
    /// let busy = create_signal(false);
    /// let _ = container()
    ///     .enabled(move || !busy.get())
    ///     .child(container().on_click(|| println!("send")))
    ///     .child(text("Send").when_disabled(|s| s.color(Color::GRAY)));
    /// ```
    ///
    /// **Disabling propagates and a descendant cannot undo it.** A container
    /// declaring `enabled(true)` inside one declaring `enabled(false)` is
    /// disabled — the rule Qt, GTK and SwiftUI all settled on, and the only one
    /// under which a form can be switched off in a single place.
    ///
    /// A disabled subtree is not where the keyboard is aimed: it resolves no
    /// `when_focused` layer, so the ring goes with the rest of it. That is what
    /// Qt, GTK, SwiftUI and a `<fieldset disabled>` all do. A field that must go
    /// on saying the keys are *its* while refusing them is not disabled — it is
    /// [read-only](crate::widgets::TextInput::readonly), which is the other
    /// half of this and keeps its focus.
    ///
    /// Declaring it makes the container an interaction unit, as every other
    /// behaviour does, because that is what a descendant asks.
    ///
    /// Enabling is a *declaration*, not a state override: there is no way to
    /// say a container is enabled only while hovered, the same way there is no
    /// way to declare a timing on an override.
    ///
    /// ```compile_fail
    /// use guido::prelude::*;
    ///
    /// let _ = container().when_hovered(|s| s.enabled(false));
    /// ```
    pub fn enabled<M>(mut self, enabled: impl IntoSignal<bool, M>) -> Self {
        self.interact_mut().declared_enabled = enabled.into_prop();
        self
    }

    /// Scroll this container, and say what its scrollbar looks like.
    ///
    /// One value rather than three setters. `scrollbar_visibility` and
    /// `scrollbar` used to be separate and were silent no-ops on a container
    /// that never became scrollable — half a configuration that compiled and
    /// did nothing. There is no way to write that now:
    ///
    /// ```compile_fail,E0599
    /// # use guido::prelude::*;
    /// // The parts cannot be declared apart from the thing they configure.
    /// // E0599 pinned on purpose: a bare `compile_fail` passes on any error at
    /// // all, including a typo in the test itself, so it would go on passing
    /// // long after it stopped meaning anything.
    /// container().scrollbar_visibility(ScrollbarVisibility::Hidden);
    /// ```
    ///
    /// ```compile_fail,E0599
    /// # use guido::prelude::*;
    /// // ... and neither can the styling.
    /// container().scrollbar(|sb| sb.width(6.0));
    /// ```
    ///
    /// ```
    /// # use guido::prelude::*;
    /// container().scroll(Scroll::vertical());
    /// container().scroll(
    ///     Scroll::both()
    ///         .overlay()
    ///         .handle(|h| h.background(Color::RED)),
    /// );
    /// ```
    pub fn scroll(mut self, scroll: Scroll) -> Self {
        self.scroll_axis = scroll.axis;
        self.scroll_data = Some(Box::new(ScrollData::new(scroll)));
        self
    }

    /// Called on a left-button press inside the bounds.
    ///
    /// Takes a closure, a [`Callback`](crate::reactive::Callback), or an
    /// `Option<Callback>` — the last being what a `#[component]` callback prop
    /// holds, so a component forwards its own prop with no ceremony:
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// #[component]
    /// fn button(#[prop(callback)] on_click: ()) -> impl Widget {
    ///     container().on_click(on_click)
    /// }
    /// ```
    ///
    /// A `None` prop leaves the container without a click handler, but still a
    /// pointer target if anything else made it one.
    pub fn on_click<M>(mut self, callback: impl IntoClickHandler<M>) -> Self {
        let handler = callback.into_click_handler();
        if handler.is_some() || self.interaction.is_some() {
            self.interact_mut().on_click = handler;
        }
        self
    }

    /// Called on a right-button press inside the bounds.
    pub fn on_right_click<F: Fn() + 'static>(mut self, callback: F) -> Self {
        self.interact_mut().on_right_click = Some(Rc::new(callback));
        self
    }

    /// Called on a middle-button press inside the bounds.
    pub fn on_middle_click<F: Fn() + 'static>(mut self, callback: F) -> Self {
        self.interact_mut().on_middle_click = Some(Rc::new(callback));
        self
    }

    /// Called for a key press nothing with the focus took: one typed while a
    /// focused widget inside lets it through, or with nothing focused at all.
    /// Where two containers both declare it, the inner one hears the key.
    ///
    /// It answers whether it took the key, in the words of
    /// [`Widget::event`]: `Handled` stops it there, and `Ignored` lets it go
    /// on to the next container listening and then to what the key does by
    /// default — Tab moving the focus.
    ///
    /// The third argument says whether a held key produced it rather than a
    /// press. A held key is delivered once per repeat, so a listener that acts
    /// once per press returns early when it is `true`.
    ///
    /// Delivered while the surface has keyboard focus — a layer surface with
    /// [`KeyboardInteractivity`](crate::platform::KeyboardInteractivity) set,
    /// or a popup holding a grab.
    pub fn on_key_down<F: Fn(Key, Modifiers, bool) -> EventResponse + 'static>(
        mut self,
        callback: F,
    ) -> Self {
        self.interact_mut().on_key_down = Some(Rc::new(callback));
        self
    }

    /// Called for a key release nothing with the focus took, along the same
    /// route as [`on_key_down`](Self::on_key_down): where the press went, the
    /// release goes after it. It answers whether it took the key, as
    /// `on_key_down` does.
    ///
    /// A release is not paired with its press. A focused field that takes a
    /// key's press lets its release through, so a control that must not act on
    /// a release it never saw pressed keeps that record itself.
    pub fn on_key_up<F: Fn(Key, Modifiers) -> EventResponse + 'static>(
        mut self,
        callback: F,
    ) -> Self {
        self.interact_mut().on_key_up = Some(Rc::new(callback));
        self
    }

    /// Make this container a place the keyboard focus can be: Tab stops here,
    /// in reading order among the text inputs and the other focusable
    /// containers, and a press inside takes the focus — what `tabindex="0"`
    /// does in HTML. That is how its own
    /// [`when_focused`](crate::widgets::Stateful::when_focused) and the keys
    /// its [`on_key_down`](Self::on_key_down) hears on the focus path become
    /// reachable without a text input inside.
    ///
    /// Structural, like the event handlers: it says what the container is,
    /// and does not reach paint. A container that is not focusable can still
    /// be given the focus by [`WidgetRef::focus`](crate::widget_ref::WidgetRef::focus);
    /// it is only not a stop.
    pub fn focusable(mut self, focusable: bool) -> Self {
        self.interact_mut().focusable = focusable;
        self
    }

    pub fn on_hover<F: Fn(bool) + 'static>(mut self, callback: F) -> Self {
        self.interact_mut().on_hover = Some(Rc::new(callback));
        self
    }

    pub fn on_scroll<F: Fn(f32, f32, ScrollSource) + 'static>(mut self, callback: F) -> Self {
        self.interact_mut().on_scroll = Some(Rc::new(callback));
        self
    }

    pub fn on_pointer_move<F: Fn(f32, f32) + 'static>(mut self, callback: F) -> Self {
        self.interact_mut().on_pointer_move = Some(Rc::new(callback));
        self
    }

    pub fn on_mouse_down<F: Fn(f32, f32) + 'static>(mut self, callback: F) -> Self {
        self.interact_mut().on_mouse_down = Some(Rc::new(callback));
        self
    }

    pub fn on_mouse_up<F: Fn(f32, f32) + 'static>(mut self, callback: F) -> Self {
        self.interact_mut().on_mouse_up = Some(Rc::new(callback));
        self
    }

    /// Attach a [`WidgetRef`] to track this container's surface-relative bounds.
    pub fn widget_ref(mut self, r: WidgetRef) -> Self {
        self.widget_ref = Some(r);
        self
    }

    /// The shadow this container casts — offset, blur, spread and colour, all
    /// four of them.
    ///
    /// There is no elevation level and no table behind one. A design system's
    /// ladder is a set of `Shadow` values the application writes down, the way
    /// it writes down its colours.
    ///
    /// ```
    /// use guido::prelude::*;
    ///
    /// const LIFTED: Shadow = Shadow::new((0.0, 8.0), 16.0, 0.0, Color::BLACK);
    /// let _ = container().shadow(LIFTED);
    /// let _ = container().shadow(LIFTED.transition(120.0));
    /// let _ = container()
    ///     .shadow(Shadow::none().transition(120.0))
    ///     .when_hovered(|s| s.shadow(LIFTED));
    /// ```
    pub fn shadow<M>(mut self, shadow: impl IntoAnimated<Shadow, M>) -> Self {
        let declared = animated_properties::declare::shadow(&mut self.anims, shadow);
        self.decoration_mut().shadow = declared;
        self
    }

    /// Displace this container from where it was laid out.
    ///
    /// In logical pixels, or in fractions of the container's own size with
    /// [`Translate::relative`], which is what a slide by its own width wants
    /// rather than a width read back through a
    /// [`WidgetRef`]; `Translate::relative` says why.
    ///
    /// Paint-only, like the other two: the space the layout gave it does not
    /// move, so nothing around it shifts.
    ///
    /// The three components move independently: each carries its own timing,
    /// so a card can spring into place while its rotation eases. Declaring one
    /// says nothing about the other two.
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// # let offset = create_signal(0.0f32);
    /// # let target = create_signal(Translate::NONE);
    /// # let refusals = create_signal(0u32);
    /// # let nod = || Keyframes::new(200.0).at(0.0, Translate::NONE).at(0.5, Translate::new(0.0, 4.0)).at(1.0, Translate::NONE);
    /// container().translate((20.0, 10.0));
    /// container().translate(Translate::relative(-1.0, 0.0));
    /// container().translate(move || Translate::new(offset.get(), 0.0));
    /// container().translate(target.transition(SpringConfig::SNAPPY));
    /// container().translate(Translate::NONE.timeline(nod().played_by(refusals)));
    /// ```
    pub fn translate<M>(mut self, t: impl IntoAnimated<Translate, M>) -> Self {
        let declared = animated_properties::declare::translate(&mut self.anims, t);
        self.layer_mut().translate = declared;
        self
    }

    /// Turn this container, in degrees, clockwise, about its [`pivot`](Self::pivot).
    ///
    /// The angle is a number and is kept as one — 360 is a full turn, not
    /// zero, and 720 is two. Nothing normalises it, so what
    /// [`rotate`](Self::rotate) is given is what an animation interpolates and
    /// what a read gives back.
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// # let heading = create_signal(0.0f32);
    /// # let rejections = create_signal(0u32);
    /// # let shake = || Keyframes::new(320.0).at(0.0, 0.0).at(0.5, 8.0).at(1.0, 0.0);
    /// container().rotate(45.0);
    /// container().rotate(move || heading.get());
    /// container().rotate(0.0.timeline(shake().played_by(rejections)));
    /// ```
    ///
    /// An eased angle is interpolated as the number it is, so a turn to 360°
    /// is a full revolution. Nothing takes a shorter way round on the
    /// container's behalf: an angle that arrives already wrapped — from
    /// `atan2`, say — wraps the animation with it, and unwrapping it is the
    /// caller's to do because only the caller knows which way was meant.
    ///
    /// A declared `.reverse()` follows the *number*, not the turn, because the
    /// angle is an `f32` and `f32::is_reverse` means decreasing. So a tilt from
    /// `0.0` to `-8.0` takes the reverse curve going out and the forward one
    /// coming home. Where that matters, declare the rest angle as the larger
    /// number — `8.0` out and `0.0` home — or leave the reverse undeclared and
    /// use one curve both ways.
    pub fn rotate<M>(mut self, degrees: impl IntoAnimated<f32, M>) -> Self {
        let declared = animated_properties::declare::rotate(&mut self.anims, degrees);
        self.layer_mut().rotate = declared;
        self
    }

    /// Resize this container about its [`pivot`](Self::pivot), without
    /// re-running layout.
    ///
    /// A bare factor scales both axes; a pair scales them apart.
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// # let open_size = create_signal(Scale::NONE);
    /// # let beats = create_signal(0u32);
    /// # let pulse = || Keyframes::new(200.0).at(0.0, Scale::NONE).at(0.5, Scale::uniform(1.1)).at(1.0, Scale::NONE);
    /// container().scale(1.5);
    /// container().scale((2.0, 0.5));
    /// container().scale(open_size.transition(SpringConfig::SNAPPY));
    /// container().scale(Scale::NONE.timeline(pulse().played_by(beats)));
    /// ```
    pub fn scale<M>(mut self, factor: impl IntoAnimated<Scale, M>) -> Self {
        let declared = animated_properties::declare::scale(&mut self.anims, factor);
        self.layer_mut().scale = declared;
        self
    }

    /// How opaque this container and everything in it is drawn, from `0.0`
    /// (invisible) to `1.0` (as declared, the default).
    ///
    /// Paint-only, like the transforms beside it: the space the layout gave
    /// the container does not change, and it still takes input — a container
    /// faded to nothing is still there to be clicked.
    ///
    /// Nested opacities multiply, so a half inside a half is drawn at a
    /// quarter. The opacity is multiplied into every colour the subtree draws
    /// — backgrounds, borders, shadows, text, images and frost alike — each on
    /// its own, so where two children overlap, the overlap shows through
    /// darker rather than fading as one flat layer.
    ///
    /// ```no_run
    /// # use guido::prelude::*;
    /// # let shown = create_signal(true);
    /// container().opacity(0.5);
    /// container().opacity(move || if shown.get() { 1.0 } else { 0.0 });
    /// container().opacity(1.0.transition(200.0).entering_from(0.0));
    /// ```
    pub fn opacity<M>(mut self, opacity: impl IntoAnimated<f32, M>) -> Self {
        let declared = animated_properties::declare::opacity(&mut self.anims, opacity);
        self.layer_mut().opacity = declared;
        self
    }

    /// The point [`rotate`](Self::rotate) turns about and [`scale`](Self::scale)
    /// grows from. The centre of the container by default.
    pub fn pivot<M>(mut self, origin: impl IntoSignal<Pivot, M>) -> Self {
        self.layer_mut().pivot = origin.into_prop();
        self
    }

    /// Declare this container an interaction unit.
    ///
    /// Everything inside resolves hover, press and focus from here, until a
    /// nested `control` takes over. That is what lets a button's label light
    /// up while the pointer is on the button's padding, and what lets a label
    /// react to the focus of the input beside it.
    ///
    /// Rarely written by hand: anything the pointer can act on is a unit by
    /// necessity, so `on_click`, `on_hover`, `on_scroll`, `scrollable` and a
    /// declared state layer all imply it. Write it where the boundary is real
    /// but nothing else announces it — a form field's label and input, a row
    /// whose highlight belongs to the row.
    ///
    /// # Example
    /// ```no_run
    /// # use guido::prelude::*;
    /// # struct Theme { accent: Color }
    /// # let theme = Theme { accent: Color::rgb(0.4, 0.6, 1.0) };
    /// # let password = create_password();
    /// container().control()
    ///     .child(text("Password").when_focused(|s| s.color(theme.accent)))
    ///     .child(password_input(password));
    /// ```
    pub fn control(mut self) -> Self {
        self.declared_control = true;
        // The flags a descendant subscribes to live here, so they have to
        // exist even for a unit that declares no state of its own.
        self.interact_mut();
        self
    }

    /// Fold the enclosing unit's answer into this one's, once, where the tree
    /// is in hand.
    ///
    /// This is the whole mechanism the propagation rests on. Ancestry cannot be
    /// walked from where the question is asked — a descendant resolves its
    /// colour inside a `create_derived` closure, which has no tree — so the walk
    /// happens here, at registration, and leaves behind a signal. The parent's
    /// own fold has already happened, because registration is top-down and
    /// `set_control` runs before the children are registered, so one `&&` per
    /// nested declaration is the whole chain.
    ///
    /// A container that declares nothing keeps `None` and allocates no signal,
    /// which is nearly all of them, and nesting is the only case that allocates
    /// at all — one declaration inside another's reach.
    ///
    /// That one signal belongs to this widget, and dies with it:
    /// `OwnedWidget` re-enters its own scope for `register_children`, so a
    /// keyed list whose rows declare `enabled` beneath a control that also does
    /// no longer leaves a slot per row behind. It did until #330 — the leak was
    /// found here, because this was the only thing in the widget layer creating
    /// a signal during registration.
    fn fold_enabled(&mut self, tree: &Tree, id: WidgetId) {
        let Some(ix) = self.interaction.as_deref_mut() else {
            return;
        };
        let inherited = tree
            .get_parent(id)
            .and_then(|parent| tree.nearest_control(parent))
            .map_or(Prop::Unset, |control| control.enabled_prop());
        ix.enabled = match (ix.declared_enabled, inherited) {
            (Prop::Unset, above) => above,
            (own, Prop::Unset) => own,
            // Two constants fold to a constant. A literal `.enabled(false)`
            // inside another is the whole of this case, and answering it with
            // a derived signal would be a subscription to two values that
            // cannot change.
            (Prop::Const(own), Prop::Const(above)) => Prop::Const(own && above),
            // At least one side is reactive, so the `&&` has to be asked each
            // time. Neither is `Unset` — the two arms above took those — but
            // `get_or` is how a `Prop` is read and the default it names is the
            // one an undeclared control would have had.
            (own, above) => Prop::Reactive(create_derived(move || {
                above.get_or(true) && own.get_or(true)
            })),
        };
    }

    pub(super) fn is_focusable(&self) -> bool {
        self.interaction.as_ref().is_some_and(|ix| ix.focusable)
    }

    /// Whether this container is an interaction unit.
    ///
    /// A pointer target *is* one — it has to know whether it is being pointed
    /// at — so every behaviour implies it rather than merely allowing it. So
    /// does declaring a state layer, which is what keeps every container
    /// resolving its own states exactly as it did before controls existed.
    pub(super) fn is_control(&self) -> bool {
        if self.declared_control || self.scroll_axis != ScrollAxis::None {
            return true;
        }
        self.interaction.as_ref().is_some_and(|ix| {
            ix.declared_enabled.is_set()
                || ix.has_any_state()
                || ix.on_click.is_some()
                || ix.on_right_click.is_some()
                || ix.on_middle_click.is_some()
                || ix.on_hover.is_some()
                || ix.on_scroll.is_some()
                || ix.on_pointer_move.is_some()
                || ix.on_mouse_down.is_some()
                || ix.on_mouse_up.is_some()
        })
    }
}

/// The same four declarations a leaf has, in the box's own vocabulary.
///
/// One trait for both means `when_hovered` reads the same on a button and on
/// its label — which is the point of the name: it promises nothing about
/// *whose* hover, because the unit that can be hovered is the control you
/// belong to.
impl Stateful for Container {
    type Style = StateStyle;

    fn push_state_style(&mut self, when: StateWhen, style: StateStyle) {
        let moves = style.moves_anything();
        let ix = self.interact_mut();
        ix.declares_transform.merge(moves);
        ix.states.push((when, style));
    }
}

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

impl Widget for Container {
    fn advance_animations(&mut self, tree: &mut Tree, id: WidgetId) -> bool {
        // Use advance_animations_self for this widget's animations
        let mut any_animating = false;
        // Nothing anyone can see, so nothing to advance and no frame to ask
        // for. Read under tracking, exactly as `layout` reads it: that is the
        // subscription that brings the animation back, because a flip to
        // visible queues the Animation job this pass would otherwise have had
        // to keep asking for.
        //
        // A container hidden before its animation ever started never gets here
        // — layout returns at its own gate, so the sequence is never seeded.
        // This is for one hidden while it runs, which before now went on
        // asking for a frame every vsync and repainting a surface showing
        // nothing (#351).
        //
        // A leaving container skips the question: its exit is what disposes
        // it, so it plays whether or not anything can see it.
        let leaving = self.is_leaving();
        if !leaving && is_detached(id) {
            // Inside a child that is leaving: only the exit moves.
            return false;
        }
        // The containers it sits in are asked by `process_jobs`, before this
        // runs (#666).
        let is_visible =
            leaving || with_signal_tracking(id, JobType::Animation, || self.visible.get_or(true));
        if !is_visible {
            return false;
        }

        // One frame, one instant. Every animation below is asked about the
        // same moment — the ripple included, which used to read a clock of its
        // own a few microseconds later than the rest.
        let now = tree.frame_instant();

        any_animating |= self.advance_declared_animations(id, now);

        // Advance ripple animation
        if let Some(ref mut ix) = self.interaction
            && ix.ripple.is_active()
            && let Some(config) = ix.ripple_config()
        {
            let ripple_animating = ix.ripple.advance(&config, now);
            if ripple_animating {
                // Ripple is paint-only, request animation continuation with paint
                request_job(id, JobRequest::Animation(RequiredJob::Paint));
            }
            any_animating = any_animating || ripple_animating;
        }

        // Advance kinetic scroll animation
        if let Some(ref mut sd) = self.scroll_data {
            let has_scroll_velocity =
                sd.scroll_state.velocity_x.abs() > 0.5 || sd.scroll_state.velocity_y.abs() > 0.5;
            if has_scroll_velocity {
                let scroll_animating = sd.scroll_state.advance_momentum(now);
                if scroll_animating {
                    // Kinetic scroll is paint-only, request animation continuation with paint
                    request_job(id, JobRequest::Animation(RequiredJob::Paint));
                }
                any_animating = any_animating || scroll_animating;
            }
        }

        // Advance scrollbar scale animations (for hover expansion effect)
        // Must be done here since scroll/hover is paint-only and layout may not run
        if self.advance_scrollbar_scale_animations_internal(id, now) {
            any_animating = true;
        }

        // Note: No final Animation push needed here - each animation source
        // (the declared animations, the ripple, the kinetic scroll) handles its
        // own continuation

        // The last exit has settled: the container that holds this one
        // disposes it, and is asked to in this frame.
        if leaving
            && !self.is_exiting()
            && let Some(parent) = tree.get_parent(id)
        {
            request_job(parent, JobRequest::Reconcile);
        }

        any_animating
    }

    fn begin_exit(&mut self, tree: &mut Tree, id: WidgetId) -> bool {
        let Some(declared) = self.anims.as_deref_mut() else {
            return false;
        };
        if !declared.slots().any(AnimSlot::declares_exit) {
            return false;
        }
        let now = tree.frame_instant();
        let mut moves_the_box = false;
        for slot in declared.slots_mut() {
            if slot.begin_exit(now) {
                moves_the_box |= slot.moves_the_box();
            }
        }
        let follow_up = if moves_the_box {
            RequiredJob::Layout
        } else {
            RequiredJob::Paint
        };
        request_job(id, JobRequest::Animation(follow_up));
        true
    }

    fn is_exiting(&self) -> bool {
        self.anims.as_deref().is_some_and(|declared| {
            declared
                .slots()
                .any(|slot| slot.is_leaving() && slot.is_animating())
        })
    }

    fn cancel_exit(&mut self, tree: &mut Tree, id: WidgetId) {
        let Some(declared) = self.anims.as_deref_mut() else {
            return;
        };
        for slot in declared.slots_mut() {
            slot.cancel_exit();
        }
        // Sent home now, from where each property is, rather than by the
        // Animation job of the next frame: the frame the key came back is the
        // frame the return begins. A size is sent home by the layout its
        // reattach asks for, in this frame too.
        self.advance_declared_animations(id, tree.frame_instant());
    }

    fn reconcile_children(&mut self, tree: &mut Tree, id: WidgetId) -> bool {
        // Ensure container_id is set before reconciliation
        self.children_source.set_container_id(id);
        self.children_source.reconcile_with_tracking(tree)
    }

    fn register_children(&mut self, tree: &mut Tree, id: WidgetId) {
        // Set container_id for children source
        self.children_source.set_container_id(id);

        self.fold_enabled(tree, id);
        tree.set_control(
            id,
            self.is_control()
                .then(|| {
                    self.interaction
                        .as_ref()
                        .map(|ix| Control::new(id, ix.flags, ix.enabled))
                })
                .flatten(),
        );

        if self
            .interaction
            .as_ref()
            .is_some_and(|ix| ix.on_key_down.is_some() || ix.on_key_up.is_some())
        {
            tree.listen_for_keys(id);
        }
        if self.visible.is_set() {
            tree.declare_visible(id, self.visible);
        }
        if self.is_focusable() {
            tree.make_tab_stop(id);
        }

        // Register pending children
        self.children_source.register_pending(tree, id);
    }

    fn layout_hints(&self) -> LayoutHints {
        // The parent asks this while laying out; snapshots are right here,
        // because the child's own layout subscribes to the same signals and a
        // change re-runs it and its parent anyway — even when the child is a
        // relayout boundary, which absorbs only what changes below it.
        if !self.visible.get_or_untracked(true) {
            return LayoutHints {
                hidden: true,
                ..LayoutHints::default()
            };
        }
        LayoutHints {
            fill_width: self.width.get_or_untracked(Length::default()).is_fill(),
            fill_height: self.height.get_or_untracked(Length::default()).is_fill(),
            hidden: false,
        }
    }

    fn layout(&mut self, ctx: &mut LayoutCtx, constraints: Constraints) -> Size {
        let id = ctx.id();
        let is_visible = self.visible.get_or(true);
        if !is_visible {
            ctx.tree().set_relayout_boundary(id, true);
            return Size::zero();
        }

        // Before `ensure_scrollbar_containers`, which reads the resolved
        // visibility to decide whether to build the parts at all — and before
        // the gutter `child_layout` takes out of the content box, which is
        // measured from the resolved width and margin.
        self.resolve_scroll();

        let boundary = self.is_relayout_boundary_for(constraints);
        ctx.tree().set_relayout_boundary(id, boundary);
        self.ensure_scrollbar_containers(ctx.tree(), id);

        // Before the measurement, because the measurement consumes what this
        // places: `read_box_lengths` reads the animated padding, and a value
        // seeded after it is a value this layout never saw. Asking for another
        // layout afterwards would not do — `measure_natural_size` runs a layout
        // whose size is a *return value*, so on the popup path there is no later
        // pass for a repair to land in.
        //
        // Above it rather than at the top of the function: a layout that skips
        // must not seed, and the gate is what decides that. Below the gate the
        // first layout never skips, because it has no cached constraints.
        self.seed_animations(ctx, id);

        let lengths = self.read_box_lengths(ctx, id, constraints);
        let child = self.child_layout(ctx, &lengths, constraints);
        let padding = lengths.padding;

        let children = self.children_source.reconcile_and_get(ctx.tree());

        // A layout reads its own reactive properties — Flex's spacing and
        // alignment, whatever a user-written `Layout` declares — and those
        // reads belong to this container, which is whose scope the call is
        // already inside.
        let content_size = if !children.is_empty() {
            self.layout
                .layout(ctx, children, child.constraints, child.origin)
        } else {
            Size::zero()
        };

        // A box sits on the baseline of its content, as CSS has it: without
        // this a styled label reports nothing, and a parent aligning on the
        // baseline falls back to its bottom edge — which is how the idiomatic
        // `container().child(text(..))` would silently miss the alignment it
        // asked for.
        // Child origins are stored relative to their parent, so the child's
        // own offset is all that has to be added.
        if let Some((child_id, child_baseline)) = children
            .iter()
            .find_map(|&cid| ctx.tree_ref().baseline(cid).map(|b| (cid, b)))
            && let Some((_, child_y)) = ctx.tree_ref().get_origin(child_id)
        {
            ctx.tree().set_baseline(id, child_y + child_baseline);
        }

        self.children_sorted_along = sorted_axis(ctx.tree_ref(), children);

        if self.scroll_axis != ScrollAxis::None {
            let sd = self.scroll_mut();
            sd.scroll_state.content_width = content_size.width + padding.horizontal_total();
            sd.scroll_state.content_height = content_size.height + padding.vertical_total();
            sd.scroll_state.viewport_width = child.seen_through.width;
            sd.scroll_state.viewport_height = child.seen_through.height;
            sd.scroll_state.clamp_offsets();
        }

        self.update_size_targets(ctx, id, &lengths, content_size);

        let size = self.resolve_size(ctx, &lengths, constraints, content_size);
        // What the layout recorded its children can be arranged in, or — a
        // layout that says nothing — the size they were.
        let content_least = ctx.minimum().unwrap_or(content_size);
        ctx.set_minimum(self.least_size(&lengths, content_least, size));

        self.layout_scrollbar_containers(ctx, id, size);

        // A shadow falls outside the box that casts it, so the damage this
        // container reports has to reach past its own bounds.
        //
        // The *deepest* shadow it can cast, not the one showing: a shadow
        // animates paint-only, so a hover that lifts a card never re-runs this
        // layout, and a reach sized to the resting value would leave the shadow
        // ring outside every damage rect — invisible on the way up, and left
        // behind on the way down. Read under layout tracking, so a declared
        // shadow changing does re-run it.
        //
        // Kept as well as published, because paint clamps to it: the shadow that
        // is drawn and the rect that is repainted have to be one number, not two
        // computations of it made a frame apart.
        let reach = self.max_shadow_extent(id);
        self.shadow_reach.set(reach);
        // The shadow's reach is layout's to publish — it follows the shadow,
        // which layout already tracks. What a transform adds is not: a
        // transform is a paint property and reading it here would make moving a
        // widget reflow it. `refresh_paint_bounds` answers that part, in the
        // pass before paint.
        // The children first, so what the publish below carries upward is what
        // was just measured rather than what stood here before this layout.
        // Layout only: `refresh_paint_bounds` runs from a Paint job, and a walk
        // over the children there would put an O(n) back on the frame path that
        // the window exists to keep off it.
        // What a scroller or an `Overflow::Hidden` box paints is bounded by its
        // own edges, however far the content inside it runs. Counting the
        // overhang would damage, and narrow against, a rect the size of the
        // whole scrolled column.
        //
        // `lengths.overflow` rather than a fresh read: `read_box_lengths`
        // already resolved it under this layout's tracking, so the value is in
        // hand and the dependence is the one that makes a Hidden-to-Visible
        // toggle re-run this.
        ctx.clips_children(
            self.scroll_axis != ScrollAxis::None || lengths.overflow == Overflow::Hidden,
        );
        // Register widget ref so update_widget_refs() can refresh bounds
        if let Some(ref wr) = self.widget_ref {
            register_widget_ref(id, *wr);
        }

        size
    }

    fn event(&mut self, tree: &mut Tree, id: WidgetId, event: &Event) -> EventResponse {
        // Hidden takes nothing, but it gives up what it and its children held,
        // as the disabled gate below does.
        if !self.visible.get_or(true) {
            self.switched_off(tree, id);
            return EventResponse::Ignored;
        }
        let bounds = tree.get_bounds(id).unwrap_or_default();
        let placed = self.placed(id, bounds);
        let hit = HitContext {
            bounds,
            corners: self.animated_corners(id),
            transform: placed.transform,
            pivot: placed.pivot,
        };

        // Undo our own transform before hit testing against the laid-out
        // bounds. A transform collapsed to a line has no inverse, and the
        // event goes on without a position rather than with the wrong one —
        // it still has to arrive, because a press given up and a hover
        // cleared are things only a delivered event can do.
        let local_event: Cow<'_, Event> = match event.coords() {
            Some(at) if !hit.transform.is_identity() => Cow::Owned(
                event.with_coords(untransform_point(&hit.transform, hit.pivot, hit.bounds, at)),
            ),
            _ => Cow::Borrowed(event),
        };

        // The subtree gate. Only this container's own declaration, because
        // returning before the children are asked *is* the propagation: an
        // ancestor that is disabled has already stopped the event above us.
        // What it draws still covers the siblings beneath it, as a disabled
        // control does in the DOM, Flutter and Qt; one that only lays out has
        // nothing to cover them with.
        if let Some(ref ix) = self.interaction
            && !ix.declared_enabled.get_or(true)
        {
            self.switched_off(tree, id);
            if hit.contains(local_event.coords()) && self.draws_its_own_surface(id) {
                return EventResponse::Hit;
            }
            return EventResponse::Ignored;
        }

        // Before anything below can return: a point over this container's
        // scrollbar is still a point over this container.
        self.claim_the_cursor(tree, &hit, &local_event);

        let at = tree.event_instant();

        // Whether the point is inside what this container clips to: its drawn
        // shape, corners included (#704). Neither its children nor its
        // scrollbar answer outside it, and nested clips intersect because each
        // asks in its own frame. Asked only where there is a clip.
        let clips_children = self.overflow_resolved.get() == Overflow::Hidden
            || self.scroll_axis != ScrollAxis::None;
        let in_clip = clips_children && hit.contains(local_event.coords());

        // Asked once for the three that run before the children, because the
        // answer is the same one and a container that does not scroll must not
        // pay for it three times on every pointer event. The fourth, after
        // them, asks `watched_content_drag` instead, which answers the same
        // question and the next one in one read.
        if self.scroll_axis != ScrollAxis::None {
            if let Some(response) =
                self.handle_scrollbar_event(tree, id, &hit, &local_event, in_clip)
            {
                return response;
            }
            // Before the children, because a press has to be watched before
            // one of them takes it; after the scrollbar, because a press the
            // scrollbar took is not a press on the content.
            if let Some(response) = self.watch_for_a_content_drag(id, &hit, &local_event, at) {
                return response;
            }
            // And a gesture this scroller has already won is answered here
            // rather than below: nothing under it can take it back, so there
            // is nothing to ask. The move that has *not* been won yet goes the
            // long way round, after the children — see below.
            if self
                .watched_content_drag()
                .is_some_and(|drag| drag.scrolling)
                && let Some(response) =
                    self.claim_the_content_drag(tree, id, &hit, &local_event, at)
            {
                return response;
            }
        }

        self.track_pointer(tree, id, &hit, &local_event, at);

        // Children are positioned relative to our origin (and to the scroll
        // offset, when we scroll), so their events have to be too.
        let child_event: Cow<'_, Event> = match local_event.coords() {
            Some(at) => {
                let child_at = hit.rebase(at).offset(placed.scroll.0, placed.scroll.1);
                Cow::Owned(local_event.with_coords(Some(child_at)))
            }
            None => local_event.clone(),
        };

        // Children clipped away by hidden overflow or scrolling are invisible,
        // and an invisible child must not steal a click from a sibling drawn
        // below it (a collapsed submenu used to do exactly that).
        // An event with no position falls outside nothing; it reaches the
        // children owed one, and they answer no, because their own bounds
        // test is given the same absence.
        let outside_clip = clips_children && local_event.coords().is_some() && !in_clip;

        let children = self.children_source.get();
        // A pointer event goes to the children that can be under its point —
        // the window paint narrows to — and to those the pointer record still
        // owes one; an event with no position, or a point this container clips
        // away, to the owed alone (#584, #587). A key goes down the key route
        // (#241).
        // Below a point this container clipped away nothing is under it: the
        // children it is owed to are told without it, and only a press keeps
        // it for its drag and its release.
        let withheld = outside_clip.then(|| tree.begin_withholding());
        let targets = tree.event_targets(
            id,
            children,
            &child_event,
            child_event.coords().filter(|_| !outside_clip),
            self.children_sorted_along,
        );
        let mut blind: Option<Event> = None;
        let mut offer = |tree: &mut Tree, index: usize, positioned: bool| {
            let child_id = children[index];
            // A child playing its exit is drawn and takes nothing: the event
            // goes on to whatever is under it.
            if is_detached(child_id) {
                return EventResponse::Ignored;
            }
            let event = if positioned {
                &*child_event
            } else {
                &*blind.get_or_insert_with(|| child_event.with_coords(None))
            };
            tree.with_widget_mut(child_id, |child, child_id, tree| {
                child.event(tree, child_id, event)
            })
            .unwrap_or(EventResponse::Ignored)
        };
        // The one drawn on top first, and the first the point is on stops the
        // walk, whether or not it took the event: what it covers is not under
        // the point (#636).
        let stopped_at = targets.into_iter().find_map(|(index, positioned)| {
            let response = offer(tree, index, positioned);
            (response != EventResponse::Ignored).then_some((index, response))
        });
        let answered = stopped_at.map_or(EventResponse::Ignored, |(_, response)| response);
        // What it covers may still be owed this event: hovered by the last
        // one, or held by the press. It is told what a point clipped away
        // tells — that the pointer is nowhere it can see — so its hover falls,
        // and only the press keeps the position its drag and release need.
        if let Some((top, _)) = stopped_at
            && child_event.coords().is_some()
            && tree.owes_a_child_below(id, top)
        {
            let was = tree.begin_withholding();
            let owed =
                tree.event_targets(id, children, &child_event, None, self.children_sorted_along);
            for (index, positioned) in owed.filter(|&(index, _)| index < top) {
                offer(tree, index, positioned);
            }
            tree.end_withholding(was);
        }
        if let Some(was) = withheld {
            tree.end_withholding(was);
        }

        // After the children, so that a scroller inside this one claims the
        // finger first — and whether or not one of them took the move, because
        // a child taking it is not a *scroller* taking it. Only the second is
        // a reason to leave the gesture alone, and `Tree` is what says which
        // happened.
        if self.watched_content_drag().is_some()
            && let Some(response) = self.claim_the_content_drag(tree, id, &hit, &local_event, at)
        {
            return response;
        }
        if answered == EventResponse::Handled {
            return EventResponse::Handled;
        }

        match self.handle_own_event(tree, id, &hit, event, &local_event, at) {
            EventResponse::Ignored
                if answered == EventResponse::Hit || self.is_hit(id, &hit, &local_event) =>
            {
                EventResponse::Hit
            }
            own => own,
        }
    }

    fn refresh_paint_bounds(&self, tree: &mut Tree, id: WidgetId) {
        let size = tree.cached_size(id).unwrap_or_default();
        self.publish_paint_reach(tree, id, Rect::from_size(size));
    }

    fn placement(&self, tree: &Tree, id: WidgetId) -> Placement {
        let Some(bounds) = tree.get_bounds(id) else {
            return Placement::NONE;
        };
        let placed = self.placed(id, bounds);
        Placement {
            // About the pivot in the container's own box, as flatten turns it.
            own: placed.transform.about(
                placed.pivot,
                Rect::from_size(Size::new(bounds.width, bounds.height)),
            ),
            scroll: placed.scroll,
        }
    }

    fn paint(&self, ctx: &mut PaintContext) {
        let (tree, id) = (ctx.tree(), ctx.id());
        let is_visible = self.visible.get_or(true);
        if !is_visible {
            return;
        }

        // Get bounds from Tree (single source of truth)
        let bounds = tree.get_bounds(id).unwrap_or_default();
        let placed = self.placed(id, bounds);

        // Read inside the scope the framework opened around this call, so a
        // change to any of them repaints this container and nothing else.
        let (
            background,
            corners,
            shadow,
            user_transform,
            pivot,
            border_width,
            border_color,
            gradient,
            backdrop_blur,
            takes_input,
            overflow,
            opacity,
        ) = (
            self.animated_background(id),
            self.animated_corners(id),
            self.animated_shadow(id),
            placed.transform,
            placed.pivot,
            self.animated_border_width(id),
            self.animated_border_color(id),
            self.effective_gradient(id),
            self.backdrop_blur.get(),
            self.takes_input.get(),
            self.overflow.get_or(Overflow::Visible),
            self.animated_opacity(id),
        );
        self.overflow_resolved.set(overflow);

        self.resync_animation_targets(id);

        let (corner_radii, corner_curvature) = (corners.radii, corners.curvature);

        // LOCAL bounds: the origin is this container, the parent already
        // positioned the node.
        let local_bounds = Rect::new(0.0, 0.0, bounds.width, bounds.height);
        ctx.set_bounds(local_bounds);

        // Compose our own transform on top of the position the parent set.
        if !user_transform.is_identity() {
            ctx.apply_transform_with_pivot(user_transform, pivot);
        }
        ctx.set_opacity(opacity);

        // Before the decoration: the container paints over its own blurred
        // backdrop, and the effect must read a target that does not yet include
        // this container.
        //
        // One command carries both halves. The renderer filters the surface's
        // own; the compositor's region is read off this same command after
        // flattening, so the two can never disagree about whether the container
        // still wants it — and a blur cached, culled or hidden is carried or
        // dropped by the render tree itself rather than by a registry that has
        // to be told.
        if let Some(blur) = backdrop_blur
            && blur.asks_for_anything()
        {
            ctx.draw_backdrop_blur(
                local_bounds,
                blur.sources,
                blur.radius,
                corner_radii,
                corner_curvature,
            );
        }

        // Beside the blur command and for the same reason: a region the
        // compositor is told about is read off the frame, so a container that
        // stopped painting cannot leave one behind.
        if let Some(takes) = takes_input {
            ctx.declare_input_region(local_bounds, corner_radii, corner_curvature, takes);
        }

        self.paint_decoration(
            ctx,
            local_bounds,
            &Decoration {
                background,
                gradient,
                corner_radii,
                corner_curvature,
                shadow,
                border_width,
                border_color,
            },
        );

        // Determine if we need to clip children
        let is_scrollable = self.scroll_axis != ScrollAxis::None;

        // Set clip region for scrollable or overflow:hidden containers
        // This clips all children to the container bounds
        if is_scrollable || overflow == Overflow::Hidden {
            ctx.set_clip(local_bounds, corner_radii, corner_curvature);
        }

        // Determine the effective cull rect for children.
        // For scrollable containers: viewport mapped to layout space (before scroll transform).
        // For non-scrollable containers: inherited from parent via PaintContext.
        let effective_cull_rect = if is_scrollable {
            Some(Rect::new(
                placed.scroll.0,
                placed.scroll.1,
                local_bounds.width,
                local_bounds.height,
            ))
        } else {
            ctx.cull_rect()
        };

        // Skip painting children when the container has zero area — nothing
        // can be visible and attempting to render (especially text) wastes
        // atlas space and GPU work.
        if bounds.width < 0.5 || bounds.height < 0.5 {
            return;
        }

        let all_children = self.children_source.get();

        paint_children(
            ctx,
            all_children,
            &ChildPaintOptions {
                scroll_offset: placed.scroll,
                cull_rect: effective_cull_rect,
                children_sorted_along: self.children_sorted_along,
                children_reach: tree.children_reach(id),
                // A scroller's cull rect moves under its content, so a
                // partially visible child has to repaint for its own children
                // to be culled against the current rect.
                cache_requires_full_visibility: is_scrollable,
            },
        );

        // Draw scrollbar containers
        if is_scrollable {
            self.paint_scrollbar_containers(ctx);
        }

        // Ripples, oldest first. The state holds how far along each one is;
        // the geometry it resolves against is the container's.
        if let Some(ref ix) = self.interaction
            && let Some(ripple_config) = ix.ripple_config()
            && ix.ripple.iter().any(|r| r.opacity() > 0.0)
        {
            // Clips the ripples without affecting children.
            ctx.set_overlay_clip(local_bounds, corner_radii, corner_curvature);

            // Once for the frame rather than once per disc, and inside the
            // scope the framework opened around this paint: a ripple held past
            // its growth stops animating on purpose so the loop can go quiet —
            // see `Ripple::advance` — so a colour written while the finger is
            // still down would reach nothing at all without the subscription.
            let declared = ripple_config.color.get();

            for ripple in ix.ripple.iter() {
                let opacity = ripple.opacity();
                if opacity <= 0.0 {
                    continue;
                }
                let (center_x, center_y) = ripple.center(bounds.width, bounds.height);
                let radius = ripple.radius(bounds.width, bounds.height);

                let ripple_color =
                    Color::rgba(declared.r, declared.g, declared.b, declared.a * opacity);

                ctx.draw_overlay_circle(center_x, center_y, radius, ripple_color);
            }
        }
    }
}

/// The axis `children` came out ordered along, if any.
///
/// **Ordered** means what the binary search in `paint_children` needs:
/// consecutive children that do not overlap on that axis, so both of the
/// predicates it searches with partition the slice. Anything less and
/// `partition_point` answers about whichever child it happened to probe rather
/// than about the viewport, and a child sitting in plain view is dropped.
///
/// Non-overlap also settles which axis to answer when a layout orders its
/// children along both: a column's children overlap horizontally and a row's
/// overlap vertically, so each rules the other axis out and the answer is the
/// one that narrows.
///
/// Bails on the first pair that overlaps on both, so a layout that stacks its
/// children costs two of them rather than all of them.
fn sorted_axis(tree: &Tree, children: &[WidgetId]) -> Option<Axis> {
    // No children are ordered along nothing in particular, and answering an
    // axis for them would be a claim about nothing.
    if children.is_empty() {
        return None;
    }
    let (mut vertical, mut horizontal) = (true, true);
    let (mut bottom, mut right) = (f32::NEG_INFINITY, f32::NEG_INFINITY);

    for &child in children {
        // A child the tree cannot answer for is a child the search cannot
        // place, and one unplaceable child unpartitions the whole slice.
        let bounds = tree.get_bounds(child)?;
        let (top, next_bottom) = bounds.span(Axis::Vertical);
        let (left, next_right) = bounds.span(Axis::Horizontal);
        vertical &= top >= bottom;
        horizontal &= left >= right;
        if !(vertical || horizontal) {
            return None;
        }
        (bottom, right) = (next_bottom, next_right);
    }

    Some(if vertical {
        Axis::Vertical
    } else {
        Axis::Horizontal
    })
}

/// Declare an animatable property: keep the value's signal, and install
/// whatever motion arrived with it.
///
/// A declaration is the whole property, so the last one wins outright — value
/// *and* motion. Restating a property with a plain value takes its animation
/// away, which is what makes `adopt_declarations_of` unnecessary: there are
/// never two declarations for one property to reconcile, only the one written
/// last.
///
/// The animation is seeded from the signal's value at builder time — see
/// [`install`], which is where that seed and its replacement are argued.
pub(crate) fn declare<A: Default, T: Animatable, M>(
    anims: &mut Option<Box<A>>,
    value: impl IntoAnimated<T, M>,
    slot: impl FnOnce(&mut A) -> &mut Option<AnimationState<T>>,
) -> Prop<T> {
    let (prop, installed) = declared_motion(value);
    match anims.as_deref_mut() {
        Some(anims) => *slot(anims) = installed,
        None if installed.is_some() => *slot(anims.get_or_insert_with(Box::default)) = installed,
        None => {}
    }
    prop
}

/// The same for a `Container`, which keeps a slot per *declaration* rather
/// than a field per property — so a property nobody gave a motion to costs
/// nothing, and one whose motion is taken away leaves nothing behind.
///
/// Reached through `animated_properties::declare`, which is one function per
/// row: the kind and the variant are paired there rather than at the setter.
pub(crate) fn declare_anim<T: Animatable, M>(
    anims: &mut Option<Box<ContainerAnims>>,
    value: impl IntoAnimated<T, M>,
    kind: AnimKind,
    into_slot: fn(AnimationState<T>) -> AnimSlot,
) -> Prop<T> {
    let (prop, installed) = declared_motion(value);
    put(anims, kind, into_slot, installed);
    prop
}

/// The declaration a property keeps, and the animation its motion asks for.
fn declared_motion<T: Animatable, M>(
    value: impl IntoAnimated<T, M>,
) -> (Prop<T>, Option<AnimationState<T>>) {
    let (prop, motion) = value.into_animated().into_parts();
    // Inside the `map`, as it was when the value was a signal: a declaration
    // with no motion — which is almost every one — never reads it at all, and
    // for a reactive property that read is a whole closure evaluation. Writing
    // it as `motion.zip(prop.get_untracked())`, which the optional value
    // invites, would read on every declaration instead.
    let installed = motion.map(|motion| install(declared_seed(&prop), *motion));
    (prop, installed)
}

/// The value an animation is seeded from, which a declaration always has.
///
/// Loud rather than a silently dropped animation, for the reason
/// [`Animated::into_eased`] gives about the mirror case: `into_animated` puts a
/// value into every `Animated` it makes, so an absent one here would mean that
/// stopped being true, and the day it does this has to say so.
fn declared_seed<T: Clone + 'static>(prop: &Prop<T>) -> T {
    prop.get_untracked().expect(
        "an `Animated` always carries a value — it is built by `into_animated`, \
         inside the setter that immediately consumes it",
    )
}

/// The animation a motion asks for, seeded with the value declared beside it.
///
/// That seed is replaced at the first layout by `seed_animations`, which reads
/// the signal rather than this snapshot. Padding and border width used to be
/// the exception, read there only for their subscription — which left them the
/// two properties `is_initial()` was never false for, and so the two the drift
/// check in `resync_animation_targets` could never speak for.
fn install<T: Animatable>(seed: T, motion: Motion<T>) -> AnimationState<T> {
    match motion {
        Motion::Ease {
            config,
            enter_from,
            exit_to,
        } => AnimationState::new(seed, config)
            .with_enter_from(enter_from)
            .with_exit_to(exit_to),
        Motion::Play { keyframes } => {
            AnimationState::new(seed, instant_transition()).with_timeline(keyframes)
        }
    }
}

/// Put an animation, or the absence of one, where the property keeps it.
///
/// Nothing into a container that has no animation box is the overwhelmingly
/// common case — every plain `background(RED)` — so it must not be the thing
/// that allocates one.
fn put<T: Animatable>(
    anims: &mut Option<Box<ContainerAnims>>,
    kind: AnimKind,
    into_slot: fn(AnimationState<T>) -> AnimSlot,
    installed: Option<AnimationState<T>>,
) {
    match (anims.as_deref_mut(), installed) {
        (Some(anims), Some(anim)) => anims.set(into_slot(anim)),
        (Some(anims), None) => anims.clear(kind),
        (None, Some(anim)) => anims.get_or_insert_with(Box::default).set(into_slot(anim)),
        (None, None) => {}
    }
}

/// The same for a width or a height, the one pair whose declared type is not
/// the type it animates — see [`Animated::into_eased`], which is where that
/// narrowing is argued.
///
/// The seed is where the *first frame* starts, so it reads the declared length
/// alone. `update_size_targets` recomputes the target from the measured
/// content at every layout after that, which is why the two formulas differ.
fn declare_size<M>(
    anims: &mut Option<Box<ContainerAnims>>,
    value: impl IntoAnimated<Length, M>,
    kind: AnimKind,
    into_slot: fn(AnimationState<f32>) -> AnimSlot,
) -> Prop<Length> {
    let (prop, ease) = value.into_animated().into_eased();
    // A size declares a `Length` and animates the `f32` inside it, so the enter
    // is narrowed by the same formula as the seed.
    let resolved = |length: Length| length.exact_size().or(length.min()).unwrap_or(0.0);
    let installed = ease.map(|(config, enter_from, exit_to)| {
        install(
            resolved(declared_seed(&prop)),
            Motion::Ease {
                config,
                enter_from: enter_from.map(resolved),
                exit_to: exit_to.map(|exit_to| {
                    Box::new(move || resolved(exit_to())) as crate::animation::ExitTo<f32>
                }),
            },
        )
    });
    put(anims, kind, into_slot, installed);
    prop
}

impl Container {
    /// Whether an exit has begun here: removed, and still in the tree.
    pub(super) fn is_leaving(&self) -> bool {
        self.anims
            .as_deref()
            .is_some_and(|declared| declared.slots().any(AnimSlot::is_leaving))
    }
}

pub fn container() -> Container {
    Container::new()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::animation::{Animate, TimingFunction, Transition};
    use crate::jobs::{self, Job};
    use crate::layout::Constraints;
    use crate::reactive::create_signal;

    /// Regression test for the missed-write race that left popup menus
    /// permanently collapsed: the Animation subscription for an animated
    /// prop is only registered during paint, but the animation target is
    /// placed (set_immediate) during the first layout, long before a heavy
    /// tree finishes its first paint — and a popup is measured before that
    /// again, which places the target without counting as the first layout.
    /// A signal write landing in that window notified nobody and
    /// the animation sat on the stale target forever. The first paint must
    /// detect the drift and request an Animation job so
    /// advance_animations adopts the missed target.
    #[test]
    fn write_between_first_layout_and_first_paint_starts_animation() {
        let open = create_signal(false);
        let widget = container().scale(
            (move || {
                if open.get() {
                    Scale::NONE
                } else {
                    Scale::new(1.0, 0.0)
                }
            })
            .transition(Transition::new(200, TimingFunction::EaseOut)),
        );

        let mut tree = Tree::new();
        let id = tree.register(Box::new(widget));

        // First layout: initializes the animation to the collapsed state
        // via set_immediate. No Animation subscription exists yet.
        tree.layout_widget(id, Constraints::new(0.0, 0.0, 100.0, 100.0));

        // The missed write: no subscriber is registered, so this notifies
        // nobody and pushes no job for the widget.
        open.set(true);

        // Discard anything queued so far so the assertion below only sees
        // jobs produced by the paint.
        let roots: rustc_hash::FxHashSet<WidgetId> = [id].into_iter().collect();
        jobs::distribute_jobs(&tree, &roots);
        jobs::recycle_job_buffer(jobs::drain_surface_jobs(id));
        jobs::recycle_job_buffer(jobs::drain_orphan_jobs());

        // First paint: registers the subscription AND must notice the
        // animation target no longer matches the signal value.
        let mut root_node = crate::renderer::RenderNode::new(id.as_u64());
        tree.paint_widget(id, &mut root_node, 1.0);

        jobs::distribute_jobs(&tree, &roots);
        let drained = jobs::drain_surface_jobs(id);
        assert!(
            drained.contains(&Job {
                widget_id: id,
                job_type: JobType::Animation,
            }),
            "paint must request an Animation job for the missed target change, got {drained:?}"
        );
    }

    /// A content-sized surface is configured from a measure, and a measure
    /// reports animation TARGETS rather than in-flight values — so a growth
    /// animation resizes the surface once instead of once per frame.
    #[test]
    fn a_measure_reads_animation_targets() {
        let height_sig = create_signal(100.0_f32);
        let widget = container().width(50.0).height(
            (move || height_sig.get()).transition(Transition::new(200, TimingFunction::EaseOut)),
        );

        let mut tree = Tree::new();
        let id = tree.register(Box::new(widget));
        // The real flow measures under DIFFERENT constraints than the
        // render layout (loose caps vs the exact surface size), which is
        // what defeats the layout cache for this root. Not for its children,
        // whose constraints come from its box and can coincide.
        let render = Constraints::new(0.0, 0.0, 400.0, 400.0);
        let measure = Constraints::new(0.0, 0.0, 500.0, 500.0);

        // First layout initializes the animation at 100
        tree.layout_widget(id, render);

        // Retarget to 180: the animation starts from ~100
        height_sig.set(180.0);
        let mid = tree.layout_widget(id, render).unwrap();
        assert!(
            mid.height < 180.0,
            "mid-animation layout should not have reached the target yet (got {})",
            mid.height
        );

        let fin = tree.measure_widget(id, measure).unwrap();
        assert_eq!(
            fin.height, 180.0,
            "a measure has to report the animation target"
        );
    }

    /// The Animation subscription must exist from the FIRST LAYOUT, not the
    /// first paint: creation and first layout run in one synchronous block,
    /// so registering there leaves no window for a write to go unnoticed.
    /// A write right after layout — before any paint — must already
    /// schedule an Animation job. Padding is the prop that was never
    /// covered by the paint-time pass alone.
    #[test]
    fn padding_write_after_first_layout_schedules_animation() {
        let pad = create_signal(4.0_f32);
        let widget = container()
            .padding((move || pad.get()).transition(Transition::new(200, TimingFunction::EaseOut)));

        let mut tree = Tree::new();
        let id = tree.register(Box::new(widget));

        tree.layout_widget(id, Constraints::new(0.0, 0.0, 100.0, 100.0));

        // Discard jobs produced so far; only the write below matters.
        let roots: rustc_hash::FxHashSet<WidgetId> = [id].into_iter().collect();
        jobs::distribute_jobs(&tree, &roots);
        jobs::recycle_job_buffer(jobs::drain_surface_jobs(id));
        jobs::recycle_job_buffer(jobs::drain_orphan_jobs());

        pad.set(12.0);

        jobs::distribute_jobs(&tree, &roots);
        let drained = jobs::drain_surface_jobs(id);
        assert!(
            drained.contains(&Job {
                widget_id: id,
                job_type: JobType::Animation,
            }),
            "a write after first layout must schedule an Animation job \
             without waiting for a paint, got {drained:?}"
        );
    }

    /// A layout's own reactive properties must invalidate the container that
    /// runs it. They are read inside `Layout::layout`, which the container
    /// used to call outside any tracking scope: the read registered no
    /// subscriber, so `Flex::spacing(signal)` — and every property of every
    /// user-written `Layout` — silently stopped being reactive.
    #[test]
    fn a_layout_property_invalidates_its_container() {
        let spacing = create_signal(4.0f32);
        let widget = container()
            .layout(crate::layout::Flex::row().spacing(move || spacing.get()))
            .child(container().width(10.0).height(10.0))
            .child(container().width(10.0).height(10.0));

        let mut tree = Tree::new();
        let id = tree.register(Box::new(widget));
        tree.with_widget_mut(id, |w, id, tree| w.register_children(tree, id));
        let size = tree
            .layout_widget(id, Constraints::new(0.0, 0.0, 500.0, 500.0))
            .unwrap();
        assert_eq!(size.width, 24.0, "10 + spacing 4 + 10");

        let roots: rustc_hash::FxHashSet<WidgetId> = [id].into_iter().collect();
        jobs::distribute_jobs(&tree, &roots);
        jobs::recycle_job_buffer(jobs::drain_surface_jobs(id));
        jobs::recycle_job_buffer(jobs::drain_orphan_jobs());

        spacing.set(20.0);

        jobs::distribute_jobs(&tree, &roots);
        let drained = jobs::drain_surface_jobs(id);
        assert!(
            drained.contains(&Job {
                widget_id: id,
                job_type: JobType::Layout,
            }),
            "writing a layout's reactive property must queue a Layout job, got {drained:?}"
        );
    }
}