waft-widgets 0.9.1

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

use std::any::{Any, type_name};
use std::collections::HashSet;
use std::fmt::{self, Debug};
use std::ops::{BitAnd, BitOr, Deref, Not};
use std::rc::Rc;

use waft_embedder::{Canvas, Color, Offset, Paint, Path, Rect};
use waft_foundation::Ref;
use waft_foundation::{App, ChangeNotifier, ChangeNotifierData, Handle, K_IS_WEB};
use waft_painting::{
    AnyBorderSide, AnyColor, AnyTextStyle, BorderSide, BorderSideExtension, ColorExtension,
    EdgeInsetsGeometry, OutlinedBorder, OutlinedBorderRef, RoundedRectangleBorder, ShapeBorder,
    ShapeBorderRef, TextDirection, TextStyle, TextStyleExtension,
};
use waft_services::{MouseCursor, MouseCursorRef, MouseCursorSession, SystemMouseCursors};

/// Dart's `Set<WidgetState>`: the interactive states a widget is in.
pub type WidgetStates = HashSet<WidgetState>;

/// This mixin allows [`WidgetState`] enum values to be combined
/// using the `&`, `|`, and `~` operators.
///
/// A map with [`WidgetStatesConstraint`] objects as keys can be used
/// in the `<dyn WidgetStateProperty<T>>::from_map` constructor
/// to resolve to one of its values, based on the first key that
/// [`is_satisfied_by`](Self::is_satisfied_by) the current set of states.
///
/// A constraint is stored erased as a [`WidgetStatesConstraintRef`], which the operators
/// produce; `constraint.into()` erases a value by hand.
pub trait WidgetStatesConstraint: Debug + 'static {
    /// Whether the provided `states` satisfy this object's criteria.
    ///
    /// If the constraint is a single [`WidgetState`] object,
    /// it's satisfied by the set if the set contains the object.
    ///
    /// The constraint can also be created using one or more operators, for example:
    ///
    /// ```text
    /// let constraint = WidgetState::Focused | WidgetState::Hovered;
    /// ```
    ///
    /// In the above case, `constraint.is_satisfied_by(&states)` is equivalent to:
    ///
    /// ```text
    /// states.contains(&WidgetState::Focused) || states.contains(&WidgetState::Hovered)
    /// ```
    fn is_satisfied_by(&self, states: &WidgetStates) -> bool;

    /// Downcast support for Dart's `is` checks between constraint classes.
    fn as_any(&self) -> &dyn Any;

    /// Dart's `==`. Identity unless a class overrides it, as the combinators do.
    fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
        std::ptr::addr_eq(
            self as *const Self,
            other as *const dyn WidgetStatesConstraint,
        )
    }
}

impl PartialEq for dyn WidgetStatesConstraint {
    fn eq(&self, other: &dyn WidgetStatesConstraint) -> bool {
        self.eq_constraint(other)
    }
}

/// A shared, erased [`WidgetStatesConstraint`] (a Dart object reference).
///
/// The `&`, `|`, and `~` operators of the Dart mixin live here and on [`WidgetState`], and
/// produce this type: `WidgetState::Hovered & WidgetState::Focused`, `~WidgetState::Disabled`.
/// It derefs to the constraint for [`is_satisfied_by`](WidgetStatesConstraint::is_satisfied_by).
#[derive(Clone)]
pub struct WidgetStatesConstraintRef(Rc<dyn WidgetStatesConstraint>);

impl WidgetStatesConstraintRef {
    /// Erases a constraint.
    pub fn new(constraint: impl WidgetStatesConstraint) -> WidgetStatesConstraintRef {
        WidgetStatesConstraintRef(Rc::new(constraint))
    }
}

impl<C: WidgetStatesConstraint> From<C> for WidgetStatesConstraintRef {
    fn from(constraint: C) -> WidgetStatesConstraintRef {
        WidgetStatesConstraintRef::new(constraint)
    }
}

impl Deref for WidgetStatesConstraintRef {
    type Target = dyn WidgetStatesConstraint;

    fn deref(&self) -> &dyn WidgetStatesConstraint {
        &*self.0
    }
}

impl PartialEq for WidgetStatesConstraintRef {
    fn eq(&self, other: &WidgetStatesConstraintRef) -> bool {
        self.0.eq_constraint(&*other.0)
    }
}

impl Debug for WidgetStatesConstraintRef {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// The operators of Dart's `WidgetStatesConstraint` mixin, for a type that implements it.
macro_rules! widget_states_constraint_operators {
    ($constraint:ty) => {
        impl<R: Into<WidgetStatesConstraintRef>> BitAnd<R> for $constraint {
            type Output = WidgetStatesConstraintRef;

            /// Combines two [`WidgetStatesConstraint`] values using logical "and".
            fn bitand(self, other: R) -> WidgetStatesConstraintRef {
                WidgetStatesConstraintRef::new(WidgetStateAnd {
                    first: self.into(),
                    second: other.into(),
                })
            }
        }

        impl<R: Into<WidgetStatesConstraintRef>> BitOr<R> for $constraint {
            type Output = WidgetStatesConstraintRef;

            /// Combines two [`WidgetStatesConstraint`] values using logical "or".
            fn bitor(self, other: R) -> WidgetStatesConstraintRef {
                WidgetStatesConstraintRef::new(WidgetStateOr {
                    first: self.into(),
                    second: other.into(),
                })
            }
        }

        impl Not for $constraint {
            type Output = WidgetStatesConstraintRef;

            /// Takes a [`WidgetStatesConstraint`] and applies the logical "not".
            fn not(self) -> WidgetStatesConstraintRef {
                WidgetStatesConstraintRef::new(WidgetStateNot { value: self.into() })
            }
        }
    };
}

widget_states_constraint_operators!(WidgetStatesConstraintRef);

// Dart's `_WidgetStateCombo` is the `first` / `second` pair the two combinators share.

struct WidgetStateAnd {
    first: WidgetStatesConstraintRef,
    second: WidgetStatesConstraintRef,
}

impl WidgetStatesConstraint for WidgetStateAnd {
    fn is_satisfied_by(&self, states: &WidgetStates) -> bool {
        self.first.is_satisfied_by(states) && self.second.is_satisfied_by(states)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
        other
            .as_any()
            .downcast_ref::<WidgetStateAnd>()
            .is_some_and(|other| other.first == self.first && other.second == self.second)
    }
}

impl Debug for WidgetStateAnd {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({:?} & {:?})", self.first, self.second)
    }
}

struct WidgetStateOr {
    first: WidgetStatesConstraintRef,
    second: WidgetStatesConstraintRef,
}

impl WidgetStatesConstraint for WidgetStateOr {
    fn is_satisfied_by(&self, states: &WidgetStates) -> bool {
        self.first.is_satisfied_by(states) || self.second.is_satisfied_by(states)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
        other
            .as_any()
            .downcast_ref::<WidgetStateOr>()
            .is_some_and(|other| other.first == self.first && other.second == self.second)
    }
}

impl Debug for WidgetStateOr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "({:?} | {:?})", self.first, self.second)
    }
}

struct WidgetStateNot {
    value: WidgetStatesConstraintRef,
}

impl WidgetStatesConstraint for WidgetStateNot {
    fn is_satisfied_by(&self, states: &WidgetStates) -> bool {
        !self.value.is_satisfied_by(states)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
        other
            .as_any()
            .downcast_ref::<WidgetStateNot>()
            .is_some_and(|other| other.value == self.value)
    }
}

impl Debug for WidgetStateNot {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "~{:?}", self.value)
    }
}

/// A private class, used to create [`WidgetState::any`]. Every instance is equal, as Dart's
/// `const` one is canonical.
struct AnyWidgetStates;

impl WidgetStatesConstraint for AnyWidgetStates {
    fn is_satisfied_by(&self, _states: &WidgetStates) -> bool {
        true
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
        other.as_any().is::<AnyWidgetStates>()
    }
}

impl Debug for AnyWidgetStates {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("WidgetState.any")
    }
}

/// Interactive states that some of the widgets can take on when receiving input
/// from the user.
///
/// States are defined by <https://m3.material.io/foundations/interaction/states>,
/// but are not limited to the Material design system or library.
///
/// Some widgets track their current state in a [`WidgetStates`] set.
///
/// See also:
///
///  * `MaterialState`, the Material specific version of `WidgetState`.
///  * [`WidgetStateProperty`], an interface for objects that "resolve" to
///    different values depending on a widget's state.
///  * [`WidgetStateColor`], a `Color` that implements `WidgetStateProperty`
///    which is used in APIs that need to accept either a `Color` or a
///    `WidgetStateProperty<Color>`.
///  * [`WidgetStateMouseCursor`], a `MouseCursor` that implements
///    `WidgetStateProperty` which is used in APIs that need to accept either
///    a `MouseCursor` or a `WidgetStateProperty<MouseCursor>`.
///  * `WidgetStateOutlinedBorder`, an `OutlinedBorder` that implements
///    `WidgetStateProperty` which is used in APIs that need to accept either
///    an `OutlinedBorder` or a `WidgetStateProperty<OutlinedBorder>`.
///  * `WidgetStateBorderSide`, a `BorderSide` that implements
///    `WidgetStateProperty` which is used in APIs that need to accept either
///    a `BorderSide` or a `WidgetStateProperty<BorderSide>`.
///  * `WidgetStateTextStyle`, a `TextStyle` that implements
///    `WidgetStateProperty` which is used in APIs that need to accept either
///    a `TextStyle` or a `WidgetStateProperty<TextStyle>`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WidgetState {
    /// The state when the user drags their mouse cursor over the given widget.
    ///
    /// See: <https://material.io/design/interaction/states.html#hover>.
    Hovered,

    /// The state when the user navigates with the keyboard to a given widget.
    ///
    /// This can also sometimes be triggered when a widget is tapped. For example,
    /// when a `TextField` is tapped, it becomes [`Focused`](Self::Focused).
    ///
    /// See: <https://material.io/design/interaction/states.html#focus>.
    Focused,

    /// The state when the user is actively pressing down on the given widget.
    ///
    /// See: <https://material.io/design/interaction/states.html#pressed>.
    Pressed,

    /// The state when this widget is being dragged from one place to another by
    /// the user.
    ///
    /// <https://material.io/design/interaction/states.html#dragged>.
    Dragged,

    /// The state when this item has been selected.
    ///
    /// This applies to things that can be toggled (such as chips and checkboxes)
    /// and things that are selected from a set of options (such as tabs and radio buttons).
    ///
    /// See: <https://material.io/design/interaction/states.html#selected>.
    Selected,

    /// The state when this widget overlaps the content of a scrollable below.
    ///
    /// Used by `AppBar` to indicate that the primary scrollable's
    /// content has scrolled up and behind the app bar.
    ScrolledUnder,

    /// The state when this widget is disabled and cannot be interacted with.
    ///
    /// Disabled widgets should not respond to hover, focus, press, or drag
    /// interactions.
    ///
    /// See: <https://material.io/design/interaction/states.html#disabled>.
    Disabled,

    /// The state when the widget has entered some form of invalid state.
    ///
    /// See <https://material.io/design/interaction/states.html#usage>.
    Error,
}

impl WidgetState {
    /// To prevent a situation where each [`WidgetStatesConstraint`]
    /// isn't satisfied by the given set of states, consider adding
    /// [`WidgetState::any`] as the final [`WidgetStateMap`] key.
    pub fn any() -> WidgetStatesConstraintRef {
        WidgetStatesConstraintRef::new(AnyWidgetStates)
    }
}

impl WidgetStatesConstraint for WidgetState {
    fn is_satisfied_by(&self, states: &WidgetStates) -> bool {
        states.contains(self)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn eq_constraint(&self, other: &dyn WidgetStatesConstraint) -> bool {
        other.as_any().downcast_ref::<WidgetState>() == Some(self)
    }
}

widget_states_constraint_operators!(WidgetState);

/// Signature for the function that returns a value of type `T` based on a given
/// set of states.
pub type WidgetPropertyResolver<T> = Rc<dyn Fn(&WidgetStates) -> T>;

/// Defines a `Color` that is also a [`WidgetStateProperty`].
///
/// This class exists to enable widgets with `Color` valued properties
/// to also accept `WidgetStateProperty<Color>` values. A widget
/// state color property represents a color which depends on
/// a widget's "interactive state". This state is represented as a
/// set of [`WidgetState`]s, like [`WidgetState::Pressed`],
/// [`WidgetState::Focused`] and [`WidgetState::Hovered`].
///
/// [`WidgetStateColor`] should only be used with widgets that document
/// their support, like `TimePickerThemeData.dayPeriodColor`.
///
/// A [`WidgetStateColor`] can be created in one of the following ways:
///   1. Use [`WidgetStateColor::resolve_with`] and pass in a callback that
///      will be used to resolve the color in the given states.
///   2. Use [`WidgetStateColor::from_map`] to assign a value using a [`WidgetStateMap`].
///
/// It is the `Color` it is in Dart once erased with [`into_any`](Self::into_any) (or
/// `.into()`): an [`AnyColor`] whose value is the color resolved in the default state (the
/// empty set of states), Dart's `super(defaultValue)`, and whose extension is this object,
/// recovered with `color.extension::<WidgetStateColor>()`.
pub struct WidgetStateColor {
    subclass: ColorSubclass,
}

/// Dart's three private subclasses of `WidgetStateColor`.
enum ColorSubclass {
    /// `_WidgetStateColor`.
    ResolveWith(WidgetPropertyResolver<Color>),
    /// `_WidgetStateColorTransparent`.
    Transparent,
    /// `_WidgetStateColorMapper`.
    Mapper(WidgetStateMapper<Color>),
}

impl WidgetStateColor {
    /// Creates a [`WidgetStateColor`] from a [`WidgetPropertyResolver<Color>`]
    /// callback function.
    ///
    /// If used as a regular color, the color resolved in the default state (the
    /// empty set of states) will be used.
    ///
    /// The given callback parameter must return a non-null color in the default
    /// state.
    pub fn resolve_with(callback: impl Fn(&WidgetStates) -> Color + 'static) -> WidgetStateColor {
        WidgetStateColor {
            subclass: ColorSubclass::ResolveWith(Rc::new(callback)),
        }
    }

    /// Creates a [`WidgetStateColor`] from a [`WidgetStateMap<Color>`].
    ///
    /// This constructor's [`resolve`](WidgetStateProperty::resolve) method finds the first
    /// entry whose key is satisfied by the set of states, and returns its associated value.
    /// It should only be used with widgets that document support for
    /// [`WidgetStateColor`] (panics if used as a normal `Color` with no key satisfied by
    /// the empty set of states).
    ///
    /// To prevent a situation where each [`WidgetStatesConstraint`]
    /// isn't satisfied by the given set of states, consider adding
    /// [`WidgetState::any`] as the final [`WidgetStateMap`] key.
    pub fn from_map(map: WidgetStateMap<Color>) -> WidgetStateColor {
        WidgetStateColor {
            subclass: ColorSubclass::Mapper(WidgetStateMapper::new(map)),
        }
    }

    /// A constant whose value is transparent for all states.
    pub fn transparent() -> WidgetStateColor {
        WidgetStateColor {
            subclass: ColorSubclass::Transparent,
        }
    }

    /// The color as the `Color` it is in Dart: the default-state value, carrying this
    /// object as the extension.
    pub fn into_any(self) -> AnyColor {
        let default_value = self.resolve(&WidgetStates::new());
        AnyColor::with_shared(default_value, Rc::new(self))
    }
}

impl WidgetStateProperty<Color> for WidgetStateColor {
    /// Returns a `Color` that's to be used when a component is in the specified
    /// state.
    fn resolve(&self, states: &WidgetStates) -> Color {
        match &self.subclass {
            ColorSubclass::ResolveWith(resolve) => resolve(states),
            ColorSubclass::Transparent => Color::new(0x00000000),
            ColorSubclass::Mapper(mapper) => mapper.resolve(states),
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_mapper(&self) -> Option<&WidgetStateMapper<Color>> {
        match &self.subclass {
            ColorSubclass::Mapper(mapper) => Some(mapper),
            _ => None,
        }
    }

    // Dart's `Color.==`: the same runtime type and value; the mapper subclass has
    // `WidgetStateMapper.==`.
    fn eq_property(&self, other: &dyn WidgetStateProperty<Color>) -> bool {
        if let ColorSubclass::Mapper(mapper) = &self.subclass {
            return mapper.eq_property(other);
        }
        let default_states = WidgetStates::new();
        other
            .as_any()
            .downcast_ref::<WidgetStateColor>()
            .is_some_and(|other| {
                self.eq_extension(other)
                    && self.resolve(&default_states) == other.resolve(&default_states)
            })
    }
}

impl ColorExtension for WidgetStateColor {
    fn as_any(&self) -> &dyn Any {
        self
    }

    // Dart's `Color.==` compares runtime types (values are already equal here); the mapper
    // subclass compares maps instead.
    fn eq_extension(&self, other: &dyn ColorExtension) -> bool {
        other
            .as_any()
            .downcast_ref::<WidgetStateColor>()
            .is_some_and(|other| match (&self.subclass, &other.subclass) {
                (ColorSubclass::ResolveWith(_), ColorSubclass::ResolveWith(_))
                | (ColorSubclass::Transparent, ColorSubclass::Transparent) => true,
                (ColorSubclass::Mapper(mine), ColorSubclass::Mapper(theirs)) => mine == theirs,
                _ => false,
            })
    }
}

impl Debug for WidgetStateColor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.subclass {
            ColorSubclass::ResolveWith(_) => f.write_str("WidgetStateColor.resolveWith"),
            ColorSubclass::Transparent => f.write_str("WidgetStateColor.transparent"),
            ColorSubclass::Mapper(mapper) => mapper.fmt(f),
        }
    }
}

impl From<WidgetStateColor> for AnyColor {
    fn from(color: WidgetStateColor) -> AnyColor {
        color.into_any()
    }
}

impl MaybeWidgetStateProperty<Color> for AnyColor {
    fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<Color>> {
        self.extension::<WidgetStateColor>()
            .map(|color| color as &dyn WidgetStateProperty<Color>)
    }

    fn from_resolved(value: Color) -> AnyColor {
        AnyColor::new(value)
    }
}

/// Defines a `MouseCursor` whose value depends on a set of [`WidgetState`]s which
/// represent the interactive state of a component.
///
/// This kind of `MouseCursor` is useful when the set of interactive
/// actions a widget supports varies with its state. For example, a
/// mouse pointer hovering over a disabled `ListTile` should not
/// display [`SystemMouseCursors::CLICK`], since a disabled list tile
/// doesn't respond to mouse clicks. `ListTile`'s default mouse cursor
/// is a [`WidgetStateMouseCursor::clickable`], which resolves to
/// [`SystemMouseCursors::BASIC`] when the button is disabled.
///
/// This class should only be used for parameters that document their support
/// for [`WidgetStateMouseCursor`].
///
/// A [`WidgetStateMouseCursor`] can be created in one of the following ways:
///   1. Use [`WidgetStateMouseCursor::resolve_with`] and pass in a callback that
///      will be used to resolve the color in the given states.
///   2. Use [`WidgetStateMouseCursor::from_map`] to assign a value using a [`WidgetStateMap`].
///
/// This example defines a mouse cursor that resolves to
/// [`SystemMouseCursors::FORBIDDEN`] when its widget is disabled.
///
/// ```text
/// let cursor = WidgetStateMouseCursor::resolve_with(
///     |states| {
///         if states.contains(&WidgetState::Disabled) {
///             return SystemMouseCursors::FORBIDDEN.into();
///         }
///         SystemMouseCursors::CLICK.into()
///     },
///     None,
/// );
/// ```
///
/// It is the `MouseCursor` it is in Dart once erased with `.into()`: a [`MouseCursorRef`]
/// recovered with `cursor.as_any().downcast_ref::<WidgetStateMouseCursor>()`.
///
/// See also:
///
///  * [`MouseCursor`] for introduction on the mouse cursor system.
///  * [`SystemMouseCursors`], which defines cursors that are supported by
///    native platforms.
pub struct WidgetStateMouseCursor {
    subclass: MouseCursorSubclass,
}

/// Dart's two private subclasses of `WidgetStateMouseCursor`.
enum MouseCursorSubclass {
    /// `_WidgetStateMouseCursor`.
    ResolveWith {
        resolve: WidgetPropertyResolver<MouseCursorRef>,
        debug_description: String,
    },
    /// `_WidgetMouseCursorMapper`.
    Mapper(WidgetStateMapper<MouseCursorRef>),
}

impl WidgetStateMouseCursor {
    /// Creates a [`WidgetStateMouseCursor`] using a [`WidgetPropertyResolver`]
    /// callback.
    ///
    /// A `debug_description` may optionally be provided (Dart's default is
    /// `'WidgetStateMouseCursor()'`).
    ///
    /// If used as a regular `MouseCursor`, the cursor resolved
    /// in the default state (the empty set of states) will be used.
    pub fn resolve_with(
        callback: impl Fn(&WidgetStates) -> MouseCursorRef + 'static,
        debug_description: Option<&str>,
    ) -> WidgetStateMouseCursor {
        WidgetStateMouseCursor {
            subclass: MouseCursorSubclass::ResolveWith {
                resolve: Rc::new(callback),
                debug_description: debug_description
                    .unwrap_or("WidgetStateMouseCursor()")
                    .to_owned(),
            },
        }
    }

    /// Creates a [`WidgetStateMouseCursor`] from a [`WidgetStateMap`].
    ///
    /// This constructor's [`resolve`](WidgetStateProperty::resolve) method finds the first
    /// entry whose key is satisfied by the set of states, and returns its associated value.
    /// It should only be used with classes that document support for
    /// [`WidgetStateMouseCursor`] (panics if used as a regular
    /// `MouseCursor` with no key satisfied by the empty set of states).
    pub fn from_map(map: WidgetStateMap<MouseCursorRef>) -> WidgetStateMouseCursor {
        WidgetStateMouseCursor {
            subclass: MouseCursorSubclass::Mapper(WidgetStateMapper::new(map)),
        }
    }

    /// A mouse cursor for clickable widgets, which resolves differently when the
    /// widget is disabled.
    ///
    /// By default this cursor resolves to [`SystemMouseCursors::CLICK`]. If the widget is
    /// disabled, the cursor resolves to [`SystemMouseCursors::BASIC`].
    pub fn clickable() -> WidgetStateMouseCursor {
        thread_local! {
            static RESOLVE: WidgetPropertyResolver<MouseCursorRef> =
                Rc::new(WidgetStateMouseCursor::resolve_clickable);
        }
        Self::canonical(&RESOLVE, "WidgetStateMouseCursor(clickable)")
    }

    fn resolve_clickable(states: &WidgetStates) -> MouseCursorRef {
        if states.contains(&WidgetState::Disabled) {
            return SystemMouseCursors::BASIC.into();
        }
        SystemMouseCursors::CLICK.into()
    }

    /// A platform-adaptive mouse cursor for clickable widgets, which resolves
    /// differently based on the widget's state and the platform.
    ///
    /// On web platforms, this cursor resolves to [`SystemMouseCursors::CLICK`] by
    /// default. If the widget is disabled, it resolves to
    /// [`SystemMouseCursors::BASIC`].
    ///
    /// On non-web platforms, this cursor always resolves to
    /// [`SystemMouseCursors::BASIC`].
    ///
    /// This cursor is commonly used for interactive widgets like buttons. The
    /// difference in behavior across platforms reflects native conventions (e.g.,
    /// web uses a hand pointer for buttons, while desktop platforms do not).
    pub fn adaptive_clickable() -> WidgetStateMouseCursor {
        thread_local! {
            static RESOLVE: WidgetPropertyResolver<MouseCursorRef> =
                Rc::new(WidgetStateMouseCursor::resolve_adaptive_clickable);
        }
        Self::canonical(&RESOLVE, "WidgetStateMouseCursor(adaptiveClickable)")
    }

    fn resolve_adaptive_clickable(states: &WidgetStates) -> MouseCursorRef {
        if states.contains(&WidgetState::Disabled) {
            return SystemMouseCursors::BASIC.into();
        }
        if K_IS_WEB {
            SystemMouseCursors::CLICK.into()
        } else {
            SystemMouseCursors::BASIC.into()
        }
    }

    /// A mouse cursor for widgets related to text, which resolves differently
    /// when the widget is disabled.
    ///
    /// By default this cursor resolves to [`SystemMouseCursors::TEXT`]. If the widget is
    /// disabled, the cursor resolves to [`SystemMouseCursors::BASIC`].
    ///
    /// This cursor is the default for many widgets.
    pub fn textable() -> WidgetStateMouseCursor {
        thread_local! {
            static RESOLVE: WidgetPropertyResolver<MouseCursorRef> =
                Rc::new(WidgetStateMouseCursor::resolve_textable);
        }
        Self::canonical(&RESOLVE, "WidgetStateMouseCursor(textable)")
    }

    /// One of Dart's `static const` cursors: every call shares the one resolver, so the
    /// cursors compare equal as Dart's one canonical object does.
    fn canonical(
        resolve: &'static std::thread::LocalKey<WidgetPropertyResolver<MouseCursorRef>>,
        debug_description: &str,
    ) -> WidgetStateMouseCursor {
        WidgetStateMouseCursor {
            subclass: MouseCursorSubclass::ResolveWith {
                resolve: resolve.with(Rc::clone),
                debug_description: debug_description.to_owned(),
            },
        }
    }

    /// Dart's identity of a `_WidgetStateMouseCursor`: a cursor is the object its resolver
    /// was made for, so two share a resolver only when they are one of the canonical cursors.
    fn same_resolver(&self, other: &WidgetStateMouseCursor) -> bool {
        match (&self.subclass, &other.subclass) {
            (
                MouseCursorSubclass::ResolveWith { resolve: mine, .. },
                MouseCursorSubclass::ResolveWith {
                    resolve: theirs, ..
                },
            ) => Rc::ptr_eq(mine, theirs),
            _ => false,
        }
    }

    fn resolve_textable(states: &WidgetStates) -> MouseCursorRef {
        if states.contains(&WidgetState::Disabled) {
            return SystemMouseCursors::BASIC.into();
        }
        SystemMouseCursors::TEXT.into()
    }
}

impl MouseCursor for WidgetStateMouseCursor {
    fn create_session(&self, device: i64) -> Box<dyn MouseCursorSession> {
        self.resolve(&WidgetStates::new()).create_session(device)
    }

    fn debug_description(&self) -> String {
        match &self.subclass {
            MouseCursorSubclass::ResolveWith {
                debug_description, ..
            } => debug_description.clone(),
            MouseCursorSubclass::Mapper(mapper) => format!("{mapper:?}"),
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    // Identity, except that the mapper subclass compares maps (Dart's `WidgetStateMapper.==`).
    fn eq_cursor(&self, other: &dyn MouseCursor) -> bool {
        let Some(other) = other.as_any().downcast_ref::<WidgetStateMouseCursor>() else {
            return false;
        };
        match (&self.subclass, &other.subclass) {
            (MouseCursorSubclass::Mapper(mine), MouseCursorSubclass::Mapper(theirs)) => {
                mine == theirs
            }
            _ => self.same_resolver(other),
        }
    }
}

impl WidgetStateProperty<MouseCursorRef> for WidgetStateMouseCursor {
    /// Returns a `MouseCursor` that's to be used when a component is in the
    /// specified state.
    fn resolve(&self, states: &WidgetStates) -> MouseCursorRef {
        match &self.subclass {
            MouseCursorSubclass::ResolveWith { resolve, .. } => resolve(states),
            MouseCursorSubclass::Mapper(mapper) => mapper.resolve(states),
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_mapper(&self) -> Option<&WidgetStateMapper<MouseCursorRef>> {
        match &self.subclass {
            MouseCursorSubclass::Mapper(mapper) => Some(mapper),
            MouseCursorSubclass::ResolveWith { .. } => None,
        }
    }

    // Identity, except that the mapper subclass has `WidgetStateMapper.==`.
    fn eq_property(&self, other: &dyn WidgetStateProperty<MouseCursorRef>) -> bool {
        match &self.subclass {
            MouseCursorSubclass::Mapper(mapper) => mapper.eq_property(other),
            MouseCursorSubclass::ResolveWith { .. } => other
                .as_any()
                .downcast_ref::<WidgetStateMouseCursor>()
                .is_some_and(|other| self.same_resolver(other)),
        }
    }
}

impl Debug for WidgetStateMouseCursor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.debug_description())
    }
}

impl From<WidgetStateMouseCursor> for MouseCursorRef {
    fn from(cursor: WidgetStateMouseCursor) -> MouseCursorRef {
        Rc::new(cursor)
    }
}

impl MaybeWidgetStateProperty<MouseCursorRef> for MouseCursorRef {
    fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<MouseCursorRef>> {
        self.as_any()
            .downcast_ref::<WidgetStateMouseCursor>()
            .map(|cursor| cursor as &dyn WidgetStateProperty<MouseCursorRef>)
    }

    fn from_resolved(value: MouseCursorRef) -> MouseCursorRef {
        value
    }
}

/// Defines a `BorderSide` whose value depends on a set of [`WidgetState`]s which represent
/// the interactive state of a component.
///
/// To use a [`WidgetStateBorderSide`], you can either:
///   1. Create a subclass of [`WidgetStateBorderSide`] and implement the abstract
///      `resolve` method.
///   2. Use [`WidgetStateBorderSide::resolve_with`] and pass in a callback that will be used
///      to resolve the color in the given states.
///   3. Use [`WidgetStateBorderSide::from_map`] to assign a value using a [`WidgetStateMap`].
///
/// If a [`WidgetStateBorderSide`] is used for a property or a parameter that doesn't
/// support resolving [`WidgetStateProperty<Option<BorderSide>>`]s, then its default value
/// will be used for all states.
///
/// It is the `BorderSide` it is in Dart once erased with [`into_any`](Self::into_any) (or
/// `.into()`): an [`AnyBorderSide`] whose value is Dart's `super` value, the default
/// `BorderSide`, and whose extension is this object, recovered with
/// `side.extension::<WidgetStateBorderSide>()`.
pub struct WidgetStateBorderSide {
    subclass: BorderSideSubclass,
}

/// Dart's two private subclasses of `WidgetStateBorderSide`.
enum BorderSideSubclass {
    /// `_WidgetStateBorderSide`.
    ResolveWith(WidgetPropertyResolver<Option<BorderSide>>),
    /// `_WidgetBorderSideMapper`.
    Mapper(WidgetStateMapper<Option<BorderSide>>),
}

impl WidgetStateBorderSide {
    /// Creates a [`WidgetStateBorderSide`] from a [`WidgetPropertyResolver<Option<BorderSide>>`]
    /// callback function.
    ///
    /// If used as a regular `BorderSide`, its behavior matches an empty `BorderSide()`
    /// constructor.
    pub fn resolve_with(
        callback: impl Fn(&WidgetStates) -> Option<BorderSide> + 'static,
    ) -> WidgetStateBorderSide {
        WidgetStateBorderSide {
            subclass: BorderSideSubclass::ResolveWith(Rc::new(callback)),
        }
    }

    /// Creates a [`WidgetStateBorderSide`] from a [`WidgetStateMap`].
    ///
    /// This constructor's [`resolve`](WidgetStateProperty::resolve) method finds the first
    /// entry whose key is satisfied by the set of states, and returns its associated value.
    pub fn from_map(map: WidgetStateMap<Option<BorderSide>>) -> WidgetStateBorderSide {
        WidgetStateBorderSide {
            subclass: BorderSideSubclass::Mapper(WidgetStateMapper::new(map)),
        }
    }

    /// The side as the `BorderSide` it is in Dart: the default `BorderSide`, carrying this
    /// object as the extension.
    pub fn into_any(self) -> AnyBorderSide {
        AnyBorderSide::with_shared(BorderSide::default(), Rc::new(self))
    }

    /// Linearly interpolate between two [`WidgetStateProperty`]s of `BorderSide`.
    pub fn lerp(
        a: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
        b: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
        t: f64,
    ) -> Option<WidgetStatePropertyRef<Option<BorderSide>>> {
        // Avoid creating a _LerpSides object for a common case.
        if a.is_none() && b.is_none() {
            return None;
        }
        if let (Some(a), Some(b)) = (&a, &b)
            && Rc::ptr_eq(a, b)
        {
            return Some(Rc::clone(a));
        }
        Some(Rc::new(LerpSides { a, b, t }))
    }
}

impl WidgetStateProperty<Option<BorderSide>> for WidgetStateBorderSide {
    fn resolve(&self, states: &WidgetStates) -> Option<BorderSide> {
        match &self.subclass {
            BorderSideSubclass::ResolveWith(resolve) => resolve(states),
            BorderSideSubclass::Mapper(mapper) => mapper.resolve(states),
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_mapper(&self) -> Option<&WidgetStateMapper<Option<BorderSide>>> {
        match &self.subclass {
            BorderSideSubclass::Mapper(mapper) => Some(mapper),
            BorderSideSubclass::ResolveWith(_) => None,
        }
    }

    // Dart's `BorderSide.==`; the mapper subclass has `WidgetStateMapper.==`.
    fn eq_property(&self, other: &dyn WidgetStateProperty<Option<BorderSide>>) -> bool {
        if let BorderSideSubclass::Mapper(mapper) = &self.subclass {
            return mapper.eq_property(other);
        }
        other
            .as_any()
            .downcast_ref::<WidgetStateBorderSide>()
            .is_some_and(|other| self.eq_extension(other))
    }
}

impl BorderSideExtension for WidgetStateBorderSide {
    fn as_any(&self) -> &dyn Any {
        self
    }

    // Dart's `BorderSide.==` compares runtime types (values are already equal here); the
    // mapper subclass compares maps instead.
    fn eq_extension(&self, other: &dyn BorderSideExtension) -> bool {
        other
            .as_any()
            .downcast_ref::<WidgetStateBorderSide>()
            .is_some_and(|other| match (&self.subclass, &other.subclass) {
                (BorderSideSubclass::ResolveWith(_), BorderSideSubclass::ResolveWith(_)) => true,
                (BorderSideSubclass::Mapper(mine), BorderSideSubclass::Mapper(theirs)) => {
                    mine == theirs
                }
                _ => false,
            })
    }
}

impl Debug for WidgetStateBorderSide {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.subclass {
            BorderSideSubclass::ResolveWith(_) => f.write_str("WidgetStateBorderSide.resolveWith"),
            BorderSideSubclass::Mapper(mapper) => mapper.fmt(f),
        }
    }
}

impl From<WidgetStateBorderSide> for AnyBorderSide {
    fn from(side: WidgetStateBorderSide) -> AnyBorderSide {
        side.into_any()
    }
}

/// Dart's `T?` is `BorderSide?`: a `WidgetStateBorderSide` resolves to an optional side.
impl MaybeWidgetStateProperty<Option<BorderSide>> for Option<AnyBorderSide> {
    fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<Option<BorderSide>>> {
        self.as_ref()
            .and_then(|side| side.extension::<WidgetStateBorderSide>())
            .map(|side| side as &dyn WidgetStateProperty<Option<BorderSide>>)
    }

    fn from_resolved(value: Option<BorderSide>) -> Option<AnyBorderSide> {
        value.map(AnyBorderSide::new)
    }
}

/// Dart's `_LerpSides`.
struct LerpSides {
    a: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
    b: Option<WidgetStatePropertyRef<Option<BorderSide>>>,
    t: f64,
}

impl WidgetStateProperty<Option<BorderSide>> for LerpSides {
    fn resolve(&self, states: &WidgetStates) -> Option<BorderSide> {
        let resolved_a = self.a.as_ref().and_then(|a| a.resolve(states));
        let resolved_b = self.b.as_ref().and_then(|b| b.resolve(states));
        match (resolved_a, resolved_b) {
            (None, None) => None,
            (None, Some(resolved_b)) => Some(BorderSide::lerp(
                BorderSide {
                    width: 0.0,
                    color: resolved_b.color.with_alpha(0),
                    ..BorderSide::default()
                },
                resolved_b,
                self.t,
            )),
            (Some(resolved_a), None) => Some(BorderSide::lerp(
                resolved_a,
                BorderSide {
                    width: 0.0,
                    color: resolved_a.color.with_alpha(0),
                    ..BorderSide::default()
                },
                self.t,
            )),
            (Some(resolved_a), Some(resolved_b)) => {
                Some(BorderSide::lerp(resolved_a, resolved_b, self.t))
            }
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl Debug for LerpSides {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "_LerpSides({:?}, {:?}, {})", self.a, self.b, self.t)
    }
}

/// Defines an `OutlinedBorder` whose value depends on a set of [`WidgetState`]s which
/// represent the interactive state of a component.
///
/// To use a [`WidgetStateOutlinedBorder`], you should create a subclass of a
/// [`WidgetStateOutlinedBorder`] and override the abstract `resolve` method, or use
/// [`WidgetStateOutlinedBorder::resolve_with`] or [`WidgetStateOutlinedBorder::from_map`].
///
/// If a [`WidgetStateOutlinedBorder`] is used for a property or a parameter that doesn't
/// support resolving [`WidgetStateProperty<Option<OutlinedBorderRef>>`]s, then its
/// default value, Dart's `RoundedRectangleBorder()`, will be used for all states.
///
/// It is itself an `OutlinedBorder`, as `OutlinedBorder` is a trait here: it is recovered
/// from an `OutlinedBorderRef` with
/// `border.as_any().downcast_ref::<WidgetStateOutlinedBorder>()`.
#[derive(Clone)]
pub struct WidgetStateOutlinedBorder {
    subclass: OutlinedBorderSubclass,
    /// Dart's `super`: `_WidgetStateOutlinedBorder extends RoundedRectangleBorder`.
    border: RoundedRectangleBorder,
}

/// Dart's two private subclasses of `WidgetStateOutlinedBorder`.
#[derive(Clone)]
enum OutlinedBorderSubclass {
    /// `_WidgetStateOutlinedBorder`.
    ResolveWith(WidgetPropertyResolver<Option<OutlinedBorderRef>>),
    /// `_WidgetOutlinedBorderMapper`.
    Mapper(Rc<WidgetStateMapper<Option<OutlinedBorderRef>>>),
}

impl WidgetStateOutlinedBorder {
    /// Creates a [`WidgetStateOutlinedBorder`] from a [`WidgetPropertyResolver`] callback
    /// function.
    ///
    /// If used as a regular `OutlinedBorder`, it acts the same as an empty
    /// `RoundedRectangleBorder()` constructor.
    pub fn resolve_with(
        callback: impl Fn(&WidgetStates) -> Option<OutlinedBorderRef> + 'static,
    ) -> WidgetStateOutlinedBorder {
        WidgetStateOutlinedBorder {
            subclass: OutlinedBorderSubclass::ResolveWith(Rc::new(callback)),
            border: RoundedRectangleBorder::default(),
        }
    }

    /// Creates a [`WidgetStateOutlinedBorder`] from a [`WidgetStateMap`].
    ///
    /// This constructor's [`resolve`](WidgetStateProperty::resolve) method finds the first
    /// entry whose key is satisfied by the set of states, and returns its associated value.
    pub fn from_map(map: WidgetStateMap<Option<OutlinedBorderRef>>) -> WidgetStateOutlinedBorder {
        WidgetStateOutlinedBorder {
            subclass: OutlinedBorderSubclass::Mapper(Rc::new(WidgetStateMapper::new(map))),
            border: RoundedRectangleBorder::default(),
        }
    }
}

impl WidgetStateProperty<Option<OutlinedBorderRef>> for WidgetStateOutlinedBorder {
    fn resolve(&self, states: &WidgetStates) -> Option<OutlinedBorderRef> {
        match &self.subclass {
            OutlinedBorderSubclass::ResolveWith(resolve) => resolve(states),
            OutlinedBorderSubclass::Mapper(mapper) => mapper.resolve(states),
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_mapper(&self) -> Option<&WidgetStateMapper<Option<OutlinedBorderRef>>> {
        match &self.subclass {
            OutlinedBorderSubclass::Mapper(mapper) => Some(mapper.as_ref()),
            OutlinedBorderSubclass::ResolveWith(_) => None,
        }
    }

    // Dart's `RoundedRectangleBorder.==`; the mapper subclass has `WidgetStateMapper.==`.
    fn eq_property(&self, other: &dyn WidgetStateProperty<Option<OutlinedBorderRef>>) -> bool {
        if let OutlinedBorderSubclass::Mapper(mapper) = &self.subclass {
            return mapper.eq_property(other);
        }
        other
            .as_any()
            .downcast_ref::<WidgetStateOutlinedBorder>()
            .is_some_and(|other| self.eq_shape(other))
    }
}

impl Debug for WidgetStateOutlinedBorder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.subclass {
            OutlinedBorderSubclass::ResolveWith(_) => {
                f.write_str("WidgetStateOutlinedBorder.resolveWith")
            }
            OutlinedBorderSubclass::Mapper(mapper) => mapper.fmt(f),
        }
    }
}

/// `_WidgetStateOutlinedBorder extends RoundedRectangleBorder`: every `ShapeBorder` member is
/// the default rounded rectangle's.
impl ShapeBorder for WidgetStateOutlinedBorder {
    fn dimensions(&self) -> EdgeInsetsGeometry {
        self.border.dimensions()
    }

    fn scale(&self, t: f64) -> ShapeBorderRef {
        ShapeBorder::scale(&self.border, t)
    }

    fn lerp_from(&self, a: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
        self.border.lerp_from(a, t)
    }

    fn lerp_to(&self, b: Option<&dyn ShapeBorder>, t: f64) -> Option<ShapeBorderRef> {
        self.border.lerp_to(b, t)
    }

    fn get_outer_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
        self.border.get_outer_path(rect, text_direction)
    }

    fn get_inner_path(&self, rect: Rect, text_direction: Option<TextDirection>) -> Path {
        self.border.get_inner_path(rect, text_direction)
    }

    fn hit_test(
        &self,
        rect: Rect,
        position: Offset,
        text_direction: Option<TextDirection>,
    ) -> bool {
        self.border.hit_test(rect, position, text_direction)
    }

    fn paint_interior(
        &self,
        canvas: &mut Canvas,
        rect: Rect,
        paint: &Paint,
        text_direction: Option<TextDirection>,
    ) {
        self.border
            .paint_interior(canvas, rect, paint, text_direction);
    }

    fn prefer_paint_interior(&self) -> bool {
        self.border.prefer_paint_interior()
    }

    fn paint(&self, canvas: &mut Canvas, rect: Rect, text_direction: Option<TextDirection>) {
        self.border.paint(canvas, rect, text_direction);
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_outlined_border(&self) -> Option<&dyn OutlinedBorder> {
        Some(self)
    }

    fn into_outlined_border(self: Rc<Self>) -> Option<Rc<dyn OutlinedBorder>> {
        Some(self)
    }

    // Dart's `RoundedRectangleBorder.==`: the same runtime type and fields; the mapper
    // compares maps.
    fn eq_shape(&self, other: &dyn ShapeBorder) -> bool {
        other
            .as_any()
            .downcast_ref::<WidgetStateOutlinedBorder>()
            .is_some_and(|other| {
                self.border.eq_shape(&other.border)
                    && match (&self.subclass, &other.subclass) {
                        (
                            OutlinedBorderSubclass::ResolveWith(_),
                            OutlinedBorderSubclass::ResolveWith(_),
                        ) => true,
                        (
                            OutlinedBorderSubclass::Mapper(mine),
                            OutlinedBorderSubclass::Mapper(theirs),
                        ) => mine == theirs,
                        _ => false,
                    }
            })
    }
}

impl OutlinedBorder for WidgetStateOutlinedBorder {
    fn side(&self) -> BorderSide {
        self.border.side()
    }

    fn copy_with(&self, side: Option<BorderSide>) -> OutlinedBorderRef {
        OutlinedBorder::copy_with(&self.border, side)
    }
}

/// Dart's `T?` is `OutlinedBorder?`: a `WidgetStateOutlinedBorder` resolves to an optional
/// border.
impl MaybeWidgetStateProperty<Option<OutlinedBorderRef>> for Option<OutlinedBorderRef> {
    fn as_widget_state_property(
        &self,
    ) -> Option<&dyn WidgetStateProperty<Option<OutlinedBorderRef>>> {
        self.as_ref()
            .and_then(|border| border.as_any().downcast_ref::<WidgetStateOutlinedBorder>())
            .map(|border| border as &dyn WidgetStateProperty<Option<OutlinedBorderRef>>)
    }

    fn from_resolved(value: Option<OutlinedBorderRef>) -> Option<OutlinedBorderRef> {
        value
    }
}

/// Defines a `TextStyle` that is also a [`WidgetStateProperty`].
///
/// This class exists to enable widgets with `TextStyle` valued properties to also accept
/// `WidgetStateProperty<TextStyle>` values. A widget state text style property represents a
/// text style which depends on a widget's "interactive state". This state is represented as
/// a set of [`WidgetState`]s, like [`WidgetState::Pressed`], [`WidgetState::Focused`] and
/// [`WidgetState::Hovered`].
///
/// [`WidgetStateTextStyle`] should only be used with widgets that document their support,
/// like `InputDecoration.labelStyle`.
///
/// It is the `TextStyle` it is in Dart once erased with [`into_any`](Self::into_any) (or
/// `.into()`): an [`AnyTextStyle`] whose value is Dart's `super` value, the empty
/// `TextStyle()`, and whose extension is this object, recovered with
/// `style.extension::<WidgetStateTextStyle>()`.
pub struct WidgetStateTextStyle {
    subclass: TextStyleSubclass,
}

/// Dart's two private subclasses of `WidgetStateTextStyle`.
enum TextStyleSubclass {
    /// `_WidgetStateTextStyle`.
    ResolveWith(WidgetPropertyResolver<TextStyle>),
    /// `_WidgetTextStyleMapper`.
    Mapper(WidgetStateMapper<TextStyle>),
}

impl WidgetStateTextStyle {
    /// Creates a [`WidgetStateTextStyle`] from a [`WidgetPropertyResolver<TextStyle>`]
    /// callback function.
    ///
    /// If used as a regular text style, the style resolved in the default state (the empty
    /// set of states) will be used.
    ///
    /// The given callback parameter must return a non-null text style in the default state.
    pub fn resolve_with(
        callback: impl Fn(&WidgetStates) -> TextStyle + 'static,
    ) -> WidgetStateTextStyle {
        WidgetStateTextStyle {
            subclass: TextStyleSubclass::ResolveWith(Rc::new(callback)),
        }
    }

    /// Creates a [`WidgetStateTextStyle`] from a [`WidgetStateMap<TextStyle>`].
    ///
    /// This constructor's [`resolve`](WidgetStateProperty::resolve) method finds the first
    /// entry whose key is satisfied by the set of states, and returns its associated value.
    pub fn from_map(map: WidgetStateMap<TextStyle>) -> WidgetStateTextStyle {
        WidgetStateTextStyle {
            subclass: TextStyleSubclass::Mapper(WidgetStateMapper::new(map)),
        }
    }

    /// The style as the `TextStyle` it is in Dart: the empty style, carrying this object as
    /// the extension.
    pub fn into_any(self) -> AnyTextStyle {
        AnyTextStyle::with_shared(TextStyle::new(), Rc::new(self))
    }
}

impl WidgetStateProperty<TextStyle> for WidgetStateTextStyle {
    fn resolve(&self, states: &WidgetStates) -> TextStyle {
        match &self.subclass {
            TextStyleSubclass::ResolveWith(resolve) => resolve(states),
            TextStyleSubclass::Mapper(mapper) => mapper.resolve(states),
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_mapper(&self) -> Option<&WidgetStateMapper<TextStyle>> {
        match &self.subclass {
            TextStyleSubclass::Mapper(mapper) => Some(mapper),
            TextStyleSubclass::ResolveWith(_) => None,
        }
    }

    // Dart's `TextStyle.==`; the mapper subclass has `WidgetStateMapper.==`.
    fn eq_property(&self, other: &dyn WidgetStateProperty<TextStyle>) -> bool {
        if let TextStyleSubclass::Mapper(mapper) = &self.subclass {
            return mapper.eq_property(other);
        }
        other
            .as_any()
            .downcast_ref::<WidgetStateTextStyle>()
            .is_some_and(|other| self.eq_extension(other))
    }
}

impl TextStyleExtension for WidgetStateTextStyle {
    fn as_any(&self) -> &dyn Any {
        self
    }

    // Dart's `TextStyle.==` compares runtime types (values are already equal here); the
    // mapper subclass compares maps instead.
    fn eq_extension(&self, other: &dyn TextStyleExtension) -> bool {
        other
            .as_any()
            .downcast_ref::<WidgetStateTextStyle>()
            .is_some_and(|other| match (&self.subclass, &other.subclass) {
                (TextStyleSubclass::ResolveWith(_), TextStyleSubclass::ResolveWith(_)) => true,
                (TextStyleSubclass::Mapper(mine), TextStyleSubclass::Mapper(theirs)) => {
                    mine == theirs
                }
                _ => false,
            })
    }
}

impl Debug for WidgetStateTextStyle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.subclass {
            TextStyleSubclass::ResolveWith(_) => f.write_str("WidgetStateTextStyle.resolveWith"),
            TextStyleSubclass::Mapper(mapper) => mapper.fmt(f),
        }
    }
}

impl From<WidgetStateTextStyle> for AnyTextStyle {
    fn from(style: WidgetStateTextStyle) -> AnyTextStyle {
        style.into_any()
    }
}

impl MaybeWidgetStateProperty<TextStyle> for AnyTextStyle {
    fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<TextStyle>> {
        self.extension::<WidgetStateTextStyle>()
            .map(|style| style as &dyn WidgetStateProperty<TextStyle>)
    }

    fn from_resolved(value: TextStyle) -> AnyTextStyle {
        AnyTextStyle::new(value)
    }
}

/// Interface for classes that [`resolve`] to a value of type `T` based
/// on a widget's interactive "state", which is defined as a set
/// of [`WidgetState`]s.
///
/// Widget state properties represent values that depend on a widget's "state".
/// The state is encoded as a set of [`WidgetState`] values, like
/// [`WidgetState::Focused`], [`WidgetState::Hovered`], [`WidgetState::Pressed`]. For
/// example the `InkWell.overlayColor` defines the color that fills the ink well
/// when it's pressed (the "splash color"), focused, or hovered. The `InkWell`
/// uses the overlay color's [`resolve`] method to compute the color for the
/// ink well's current state.
///
/// `ButtonStyle`, which is used to configure the appearance of
/// buttons like `TextButton`, `ElevatedButton`, and `OutlinedButton`,
/// has many material state properties. The button widgets keep track
/// of their current material state and [`resolve`] the button style's
/// material state properties when their value is needed.
///
/// ## Performance Consideration
///
/// In order for constructed [`WidgetStateProperty`] objects to be recognized as
/// equivalent, they need to have overrides for `==`
/// ([`eq_property`](WidgetStateProperty::eq_property)).
///
/// This comes into play when, for instance, two `ThemeData` objects are being
/// compared for equality.
///
/// For a concrete `WidgetStateProperty` object that supports stable
/// equality checks, consider using [`WidgetStateMapper`].
///
/// A property is stored erased as a [`WidgetStatePropertyRef`], whose `==` is Dart's;
/// Dart's static members (`from_map`, `resolve_as`, `resolve_with`, `all`, `lerp`) are on
/// `<dyn WidgetStateProperty<T>>`.
///
/// See also:
///
///  * `MaterialStateProperty`, the Material specific version of
///    `WidgetStateProperty`.
///  * [`WidgetStateColor`] and [`WidgetStateMouseCursor`], the value types that
///    implement it.
///
/// [`resolve`]: WidgetStateProperty::resolve
pub trait WidgetStateProperty<T>: Debug + 'static {
    /// Returns a value of type `T` that depends on `states`.
    ///
    /// Widgets like `TextButton` and `ElevatedButton` apply this method to their
    /// current [`WidgetState`]s to compute colors and other visual parameters
    /// at build time.
    fn resolve(&self, states: &WidgetStates) -> T;

    /// Downcast support for Dart's `is` checks in `==`.
    fn as_any(&self) -> &dyn Any;

    /// Dart's `other is WidgetStateMapper<T>`: the mapper this property is, if it is one,
    /// as the private mapper subclasses of `WidgetStateColor` and the rest are.
    fn as_mapper(&self) -> Option<&WidgetStateMapper<T>> {
        None
    }

    /// Dart's `==`. Identity unless a class overrides it, as [`WidgetStatePropertyAll`] and
    /// [`WidgetStateMapper`] do.
    fn eq_property(&self, other: &dyn WidgetStateProperty<T>) -> bool {
        std::ptr::addr_eq(
            self as *const Self,
            other as *const dyn WidgetStateProperty<T>,
        )
    }
}

impl<T: 'static> PartialEq for dyn WidgetStateProperty<T> {
    fn eq(&self, other: &dyn WidgetStateProperty<T>) -> bool {
        self.eq_property(other)
    }
}

/// A shared, erased [`WidgetStateProperty`] (a Dart object reference).
pub type WidgetStatePropertyRef<T> = Rc<dyn WidgetStateProperty<T>>;

/// A value that may be a [`WidgetStateProperty`] in disguise: Dart's
/// `value is WidgetStateProperty<T>` in `<dyn WidgetStateProperty<T>>::resolve_as`.
///
/// [`AnyColor`] answers through its [`WidgetStateColor`] extension, [`MouseCursorRef`]
/// through `as_any`, and an `Option` of either through its content (Dart's `T?`).
pub trait MaybeWidgetStateProperty<T>: Clone {
    /// The property this value is, if it is one.
    fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<T>>;

    /// A resolved value as this type (Dart's `T` is both).
    fn from_resolved(value: T) -> Self;
}

impl<T, V: MaybeWidgetStateProperty<T>> MaybeWidgetStateProperty<T> for Option<V> {
    fn as_widget_state_property(&self) -> Option<&dyn WidgetStateProperty<T>> {
        self.as_ref().and_then(V::as_widget_state_property)
    }

    fn from_resolved(value: T) -> Option<V> {
        Some(V::from_resolved(value))
    }
}

impl<T: 'static> dyn WidgetStateProperty<T> {
    /// Creates a property that resolves using a [`WidgetStateMap`].
    ///
    /// This constructor's [`resolve`](WidgetStateProperty::resolve) method finds the first
    /// entry whose key is satisfied by the set of states, and returns its associated value.
    ///
    /// Panics if no keys match (see [`WidgetStateMapper`]).
    /// To prevent a situation where each [`WidgetStatesConstraint`]
    /// isn't satisfied by the given set of states, consider adding
    /// [`WidgetState::any`] as the final [`WidgetStateMap`] key.
    pub fn from_map(map: WidgetStateMap<T>) -> WidgetStatePropertyRef<T>
    where
        T: Clone + Debug + PartialEq,
    {
        Rc::new(WidgetStateMapper::new(map))
    }

    /// Resolves the value for the given set of states if `value` is a
    /// [`WidgetStateProperty`], otherwise returns the value itself.
    ///
    /// This is useful for widgets that have parameters which can optionally be a
    /// [`WidgetStateProperty`]. For example, `InkWell.mouseCursor` can be a
    /// `MouseCursor` or a `WidgetStateProperty<MouseCursor>`.
    ///
    /// Dart's `T` is the value's own type here (`AnyColor` for a `Color`,
    /// [`MouseCursorRef`] for a `MouseCursor`, or an `Option` of one):
    /// `<dyn WidgetStateProperty<Color>>::resolve_as(&color, &states)`.
    pub fn resolve_as<V: MaybeWidgetStateProperty<T>>(value: &V, states: &WidgetStates) -> V {
        if let Some(property) = value.as_widget_state_property() {
            return V::from_resolved(property.resolve(states));
        }
        value.clone()
    }

    /// Convenience method for creating a [`WidgetStateProperty`] from a
    /// [`WidgetPropertyResolver`] function alone.
    pub fn resolve_with(
        callback: impl Fn(&WidgetStates) -> T + 'static,
    ) -> WidgetStatePropertyRef<T> {
        Rc::new(WidgetStatePropertyWith {
            resolve: Rc::new(callback),
        })
    }

    /// Convenience method for creating a [`WidgetStateProperty`] that resolves
    /// to a single value for all states.
    ///
    /// Prefer using [`WidgetStatePropertyAll`] directly.
    pub fn all(value: T) -> WidgetStatePropertyRef<T>
    where
        T: Clone + Debug + PartialEq,
    {
        Rc::new(WidgetStatePropertyAll::new(value))
    }

    /// Linearly interpolate between two [`WidgetStateProperty`]s.
    pub fn lerp(
        a: Option<WidgetStatePropertyRef<T>>,
        b: Option<WidgetStatePropertyRef<T>>,
        t: f64,
        lerp_function: impl Fn(Option<T>, Option<T>, f64) -> Option<T> + 'static,
    ) -> Option<WidgetStatePropertyRef<Option<T>>> {
        // Avoid creating a LerpProperties object for a common case.
        if a.is_none() && b.is_none() {
            return None;
        }
        Some(Rc::new(LerpProperties {
            a,
            b,
            t,
            lerp_function: Rc::new(lerp_function),
        }))
    }
}

/// Dart's `T? Function(T?, T?, double)` argument of `WidgetStateProperty.lerp`.
type LerpFunction<T> = Rc<dyn Fn(Option<T>, Option<T>, f64) -> Option<T>>;

struct LerpProperties<T> {
    a: Option<WidgetStatePropertyRef<T>>,
    b: Option<WidgetStatePropertyRef<T>>,
    t: f64,
    lerp_function: LerpFunction<T>,
}

impl<T: 'static> WidgetStateProperty<Option<T>> for LerpProperties<T> {
    fn resolve(&self, states: &WidgetStates) -> Option<T> {
        let resolved_a = self.a.as_ref().map(|a| a.resolve(states));
        let resolved_b = self.b.as_ref().map(|b| b.resolve(states));
        (self.lerp_function)(resolved_a, resolved_b, self.t)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl<T> Debug for LerpProperties<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "LerpProperties({:?}, {:?}, {})", self.a, self.b, self.t)
    }
}

impl<T: 'static> dyn WidgetStateProperty<Option<T>> {
    /// Linearly interpolate between two [`WidgetStateProperty`]s of a nullable value.
    ///
    /// This is Dart's `WidgetStateProperty.lerp<T>` with `T` nullable, such as the
    /// `WidgetStateProperty<Color?>` fields of a `ButtonStyle`: Dart's `T??` is `T?`, so the
    /// lerped property resolves to `Option<T>`, where [`lerp`](Self::lerp) over
    /// `Option<T>` would resolve to `Option<Option<T>>`. A side that resolves to `None` is
    /// handed to `lerp_function` as `None`, as Dart hands it `null`.
    pub fn lerp_optional(
        a: Option<WidgetStatePropertyRef<Option<T>>>,
        b: Option<WidgetStatePropertyRef<Option<T>>>,
        t: f64,
        lerp_function: impl Fn(Option<T>, Option<T>, f64) -> Option<T> + 'static,
    ) -> Option<WidgetStatePropertyRef<Option<T>>> {
        // Avoid creating a LerpProperties object for a common case.
        if a.is_none() && b.is_none() {
            return None;
        }
        Some(Rc::new(LerpOptionalProperties {
            a,
            b,
            t,
            lerp_function: Rc::new(lerp_function),
        }))
    }
}

/// Dart's `_LerpProperties<T>` with `T` nullable, which `lerp_optional` makes.
struct LerpOptionalProperties<T> {
    a: Option<WidgetStatePropertyRef<Option<T>>>,
    b: Option<WidgetStatePropertyRef<Option<T>>>,
    t: f64,
    lerp_function: LerpFunction<T>,
}

impl<T: 'static> WidgetStateProperty<Option<T>> for LerpOptionalProperties<T> {
    fn resolve(&self, states: &WidgetStates) -> Option<T> {
        let resolved_a = self.a.as_ref().and_then(|a| a.resolve(states));
        let resolved_b = self.b.as_ref().and_then(|b| b.resolve(states));
        (self.lerp_function)(resolved_a, resolved_b, self.t)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl<T> Debug for LerpOptionalProperties<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "LerpProperties({:?}, {:?}, {})", self.a, self.b, self.t)
    }
}

struct WidgetStatePropertyWith<T> {
    resolve: WidgetPropertyResolver<T>,
}

impl<T: 'static> WidgetStateProperty<T> for WidgetStatePropertyWith<T> {
    fn resolve(&self, states: &WidgetStates) -> T {
        (self.resolve)(states)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

impl<T> Debug for WidgetStatePropertyWith<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("WidgetStateProperty.resolveWith")
    }
}

/// A map used to resolve to a single value of type `T` based on
/// the current set of Widget states.
///
/// Dart's `Map<WidgetStatesConstraint, T>`, kept as its entries in insertion order.
///
/// Example:
///
/// ```text
/// // This WidgetStateMap<Option<Color>> resolves to None if no keys match.
/// <dyn WidgetStateProperty<Option<Color>>>::from_map(vec![
///     (WidgetState::Error.into(), Some(RED)),
///     (WidgetState::Hovered & WidgetState::Focused, Some(BLUE_ACCENT)),
///     (WidgetState::Focused.into(), Some(BLUE)),
///     (~WidgetState::Disabled, Some(BLACK)),
///     (WidgetState::any(), None),
/// ]);
///
/// // The same can be accomplished with a WidgetPropertyResolver,
/// // but it's more verbose:
/// <dyn WidgetStateProperty<Option<Color>>>::resolve_with(|states| {
///     if states.contains(&WidgetState::Error) {
///         Some(RED)
///     } else if states.contains(&WidgetState::Hovered) && states.contains(&WidgetState::Focused) {
///         Some(BLUE_ACCENT)
///     } else if states.contains(&WidgetState::Focused) {
///         Some(BLUE)
///     } else if !states.contains(&WidgetState::Disabled) {
///         Some(BLACK)
///     } else {
///         None
///     }
/// });
/// ```
///
/// A widget state combination can be stored in a variable,
/// and [`WidgetState::any`] can be used for non-nullable types to ensure
/// that there's a match:
///
/// ```text
/// let selected_error = WidgetState::Selected & WidgetState::Error;
///
/// let color = <dyn WidgetStateProperty<Color>>::from_map(vec![
///     (selected_error.clone() & WidgetState::Hovered, RED_ACCENT),
///     (selected_error, RED),
///     (WidgetState::any(), BLACK),
/// ]);
///
/// // The (more verbose) WidgetPropertyResolver implementation:
/// let color_resolve_with = <dyn WidgetStateProperty<Color>>::resolve_with(|states| {
///     if states.contains(&WidgetState::Selected) && states.contains(&WidgetState::Error) {
///         if states.contains(&WidgetState::Hovered) {
///             return RED_ACCENT;
///         }
///         return RED;
///     }
///     BLACK
/// });
/// ```
pub type WidgetStateMap<T> = Vec<(WidgetStatesConstraintRef, T)>;

/// Uses a [`WidgetStateMap`] to resolve to a single value of type `T` based on
/// the current set of Widget states.
///
/// Classes that hold a [`WidgetStateMapper`] can implement any other interface,
/// but should only be used for fields that document their support for
/// [`WidgetStateProperty`] objects.
///
/// For example, a [`WidgetStateColor::from_map`] object can be passed anywhere that
/// accepts either a `Color` or a [`WidgetStateProperty`] object.
///
/// [`resolve`](WidgetStateProperty::resolve) panics when no key is satisfied, whatever
/// `T`; a map that should resolve to `None` ends with `(WidgetState::any(), None)`.
#[derive(Clone)]
pub struct WidgetStateMapper<T> {
    map: WidgetStateMap<T>,
}

impl<T> WidgetStateMapper<T> {
    /// Creates a [`WidgetStateProperty`] object that can resolve
    /// to a value of type `T` using the provided `map`.
    pub fn new(map: WidgetStateMap<T>) -> WidgetStateMapper<T> {
        WidgetStateMapper { map }
    }
}

impl<T: Clone + Debug + PartialEq + 'static> WidgetStateProperty<T> for WidgetStateMapper<T> {
    fn resolve(&self, states: &WidgetStates) -> T {
        for (key, value) in &self.map {
            if key.is_satisfied_by(states) {
                return value.clone();
            }
        }

        panic!(
            "The current set of widget states is {states:?}.\n\
             None of the provided map keys matched this set, \
             and the type \"{t}\" is non-nullable.\n\
             Consider using \"WidgetStateMapper<Option<{t}>>\" with a final \
             \"WidgetState::any()\" key mapped to None, \
             or adding the \"WidgetState::any()\" key to this map.",
            t = type_name::<T>()
        );
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn as_mapper(&self) -> Option<&WidgetStateMapper<T>> {
        Some(self)
    }

    // Dart's `other is WidgetStateMapper<T> && mapEquals(_map, other._map)`.
    fn eq_property(&self, other: &dyn WidgetStateProperty<T>) -> bool {
        other.as_mapper().is_some_and(|other| self == other)
    }
}

impl<T: PartialEq> PartialEq for WidgetStateMapper<T> {
    // Dart's `mapEquals`: the same entries, looked up by key equality.
    fn eq(&self, other: &WidgetStateMapper<T>) -> bool {
        self.map.len() == other.map.len()
            && self.map.iter().all(|(key, value)| {
                other
                    .map
                    .iter()
                    .any(|(other_key, other_value)| other_key == key && other_value == value)
            })
    }
}

impl<T: Debug> Debug for WidgetStateMapper<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "WidgetStateMapper<{}>({:?})", type_name::<T>(), self.map)
    }
}

/// Convenience class for creating a [`WidgetStateProperty`] that
/// resolves to the given value for all states.
///
/// See also:
///
///  * `MaterialStatePropertyAll`, the Material specific version of
///    `WidgetStatePropertyAll`.
#[derive(Clone, PartialEq)]
pub struct WidgetStatePropertyAll<T> {
    /// The value of the property that will be used for all states.
    pub value: T,
}

impl<T> WidgetStatePropertyAll<T> {
    /// Constructs a [`WidgetStateProperty`] that always resolves to the given
    /// value.
    pub const fn new(value: T) -> WidgetStatePropertyAll<T> {
        WidgetStatePropertyAll { value }
    }
}

impl<T: Clone + Debug + PartialEq + 'static> WidgetStateProperty<T> for WidgetStatePropertyAll<T> {
    fn resolve(&self, _states: &WidgetStates) -> T {
        self.value.clone()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    // Dart's `other is WidgetStatePropertyAll<T> && other.runtimeType == runtimeType &&
    // other.value == value`.
    fn eq_property(&self, other: &dyn WidgetStateProperty<T>) -> bool {
        other
            .as_any()
            .downcast_ref::<WidgetStatePropertyAll<T>>()
            .is_some_and(|other| other.value == self.value)
    }
}

impl<T: Debug> Debug for WidgetStatePropertyAll<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "WidgetStatePropertyAll({:?})", self.value)
    }
}

/// Manages a set of [`WidgetState`]s and notifies listeners of changes.
///
/// Used by widgets that expose their internal state for the sake of
/// extensions that add support for additional states. See
/// `TextButton` for an example.
///
/// The controller's [`value`] is its current set of states. Listeners
/// are notified whenever the [`value`] changes. The [`value`] should only be
/// changed with [`update`]; it should not be modified directly.
///
/// The controller's [`value`] represents the set of states that a
/// widget's visual properties, typically [`WidgetStateProperty`]
/// values, are resolved against. It is _not_ the intrinsic state of
/// the widget. The widget is responsible for ensuring that the
/// controller's [`value`] tracks its intrinsic state. For example one
/// cannot request the keyboard focus for a widget by adding
/// [`WidgetState::Focused`] to its controller. When the widget gains the
/// or loses the focus it will [`update`] its controller's [`value`] and
/// notify listeners of the change.
///
/// When calling `set_state` in a [`WidgetStatesController`] listener, use the
/// `SchedulerBinding::add_post_frame_callback` to delay the call to `set_state` after
/// the frame has been rendered. It's generally prudent to use the
/// `SchedulerBinding::add_post_frame_callback` because some of the widgets that
/// depend on [`WidgetStatesController`] may call [`update`] in their build method.
/// In such cases, listener's that call `set_state` - during the build phase - will cause
/// an error.
///
/// Dart's `ValueNotifier<Set<WidgetState>>` superclass is the `change_notifier` and `value`
/// fields here, with its [`value`] / [`set_value`] / [`dispose`]; the handle is a
/// `Listenable`.
///
/// See also:
///
///  * `MaterialStatesController`, the Material specific version of
///    `WidgetStatesController`.
///
/// [`value`]: WidgetStatesController::value
/// [`set_value`]: WidgetStatesController::set_value
/// [`dispose`]: WidgetStatesController::dispose
/// [`update`]: WidgetStatesController::update
#[derive(Debug)]
pub struct WidgetStatesController {
    change_notifier: ChangeNotifierData,
    value: WidgetStates,
}

impl WidgetStatesController {
    /// Creates a WidgetStatesController.
    pub fn new(app: &mut App, value: Option<WidgetStates>) -> Ref<WidgetStatesController> {
        app.create(WidgetStatesController {
            change_notifier: ChangeNotifierData::new(),
            value: value.unwrap_or_default(),
        })
    }

    /// The current set of states.
    pub fn value(&self) -> &WidgetStates {
        &self.value
    }

    /// Replaces the current set of states, notifying listeners when it differs
    /// (`ValueNotifier`'s setter). Prefer [`update`](Self::update).
    pub fn set_value(self: Handle<Self>, app: &mut App, new_value: WidgetStates) {
        if app.get(self).value == new_value {
            return;
        }
        app.get_mut(self).value = new_value;
        self.notify_listeners(app);
    }

    /// Discards any resources used by the object; see [`ChangeNotifierData::dispose`].
    pub fn dispose(self: Handle<Self>, app: &mut App) {
        ChangeNotifierData::dispose(app, self);
    }

    /// Adds `state` to [`value`](Self::value) if `add` is true, and removes it otherwise,
    /// and notifies listeners if [`value`](Self::value) has changed.
    pub fn update(self: Handle<Self>, app: &mut App, state: WidgetState, add: bool) {
        let value = &mut app.get_mut(self).value;
        let value_changed = if add {
            value.insert(state)
        } else {
            value.remove(&state)
        };
        if value_changed {
            self.notify_listeners(app);
        }
    }
}

impl ChangeNotifier for WidgetStatesController {
    fn change_notifier_data(&self) -> &ChangeNotifierData {
        &self.change_notifier
    }

    fn change_notifier_data_mut(&mut self) -> &mut ChangeNotifierData {
        &mut self.change_notifier
    }
}

#[cfg(test)]
mod tests {
    use std::cell::Cell;
    use waft_foundation::AppCell;

    use waft_foundation::{Listenable, Listener};
    use waft_painting::TextStyle;

    use super::*;

    const WHITE: Color = Color::new(0xFFFFFFFF);
    const BLACK: Color = Color::new(0xFF000000);
    const RED: Color = Color::new(0xFFFF0000);

    fn states(states: impl IntoIterator<Item = WidgetState>) -> WidgetStates {
        states.into_iter().collect()
    }

    fn cursor(cursor: MouseCursorRef) -> MouseCursorRef {
        cursor
    }

    // widget_state_property_test.dart 'WidgetStateProperty.resolveWith()'.
    #[test]
    fn resolve_with_resolves_through_the_callback() {
        let value = <dyn WidgetStateProperty<WidgetState>>::resolve_with(|states| {
            states.iter().next().copied().expect("one state")
        });
        for state in [
            WidgetState::Hovered,
            WidgetState::Focused,
            WidgetState::Pressed,
            WidgetState::Dragged,
            WidgetState::Selected,
            WidgetState::Disabled,
            WidgetState::Error,
        ] {
            assert_eq!(value.resolve(&states([state])), state);
        }
    }

    // widget_state_property_test.dart 'WidgetStateProperty.map()'.
    #[test]
    fn a_map_resolves_to_the_first_satisfied_key_through_the_combinators() {
        let active = WidgetState::Hovered | WidgetState::Focused | WidgetState::Pressed;
        let value = <dyn WidgetStateProperty<Option<&str>>>::from_map(vec![
            (active.clone() & WidgetState::Error, Some("active error")),
            (
                WidgetState::Disabled | WidgetState::Error,
                Some("kinda sus"),
            ),
            (
                !(WidgetState::Dragged | WidgetState::Selected) & !active.clone(),
                Some("this is boring"),
            ),
            (active, Some("active")),
            (WidgetState::any(), None),
        ]);
        assert_eq!(
            value.resolve(&states([WidgetState::Focused, WidgetState::Error])),
            Some("active error")
        );
        assert_eq!(
            value.resolve(&states([WidgetState::ScrolledUnder])),
            Some("this is boring")
        );
        assert_eq!(
            value.resolve(&states([WidgetState::Disabled])),
            Some("kinda sus")
        );
        assert_eq!(
            value.resolve(&states([WidgetState::Hovered])),
            Some("active")
        );
        assert_eq!(value.resolve(&states([WidgetState::Dragged])), None);
    }

    #[test]
    fn any_is_satisfied_by_every_set_and_a_constraint_prints_as_dart_does() {
        assert!(WidgetState::any().is_satisfied_by(&WidgetStates::new()));
        assert!(WidgetState::any().is_satisfied_by(&states([WidgetState::Disabled])));
        assert_eq!(WidgetState::any(), WidgetState::any());
        assert_eq!(format!("{:?}", WidgetState::any()), "WidgetState.any");
        assert_eq!(
            format!("{:?}", !(WidgetState::Hovered & WidgetState::Focused)),
            "~(Hovered & Focused)"
        );
        assert_eq!(
            WidgetState::Hovered | WidgetState::Focused,
            WidgetState::Hovered | WidgetState::Focused
        );
        assert_ne!(
            WidgetState::Hovered | WidgetState::Focused,
            WidgetState::Focused | WidgetState::Hovered
        );
        assert_ne!(
            WidgetState::Hovered | WidgetState::Focused,
            WidgetState::Hovered & WidgetState::Focused
        );
    }

    #[test]
    #[should_panic(expected = "None of the provided map keys matched this set")]
    fn a_map_with_no_satisfied_key_panics_with_darts_message() {
        let value = WidgetStateMapper::new(vec![(WidgetState::Hovered.into(), 1)]);
        value.resolve(&states([WidgetState::Focused]));
    }

    // widget_state_property_test.dart 'WidgetStateProperty.all()' and 'WidgetStatePropertyAll'.
    #[test]
    fn all_resolves_to_its_value_for_every_state() {
        let value = <dyn WidgetStateProperty<i32>>::all(123);
        let constant = WidgetStatePropertyAll::new(123);
        assert_eq!(constant.resolve(&WidgetStates::new()), 123);
        for state in [
            WidgetState::Hovered,
            WidgetState::Focused,
            WidgetState::Pressed,
            WidgetState::Dragged,
            WidgetState::Selected,
            WidgetState::Disabled,
            WidgetState::Error,
        ] {
            assert_eq!(value.resolve(&states([state])), 123);
            assert_eq!(constant.resolve(&states([state])), 123);
        }
        assert_eq!(
            format!("{:?}", WidgetStatePropertyAll::new(Some(WHITE))),
            format!("WidgetStatePropertyAll({:?})", Some(WHITE))
        );
        assert_eq!(
            WidgetStatePropertyAll::new(1),
            WidgetStatePropertyAll::new(1)
        );
        assert_ne!(
            WidgetStatePropertyAll::new(1),
            WidgetStatePropertyAll::new(2)
        );
    }

    // widget_state_property_test.dart "Can interpolate between two WidgetStateProperty's".
    #[test]
    fn lerp_interpolates_the_resolved_values() {
        let enabled = WidgetStates::new();
        let text_style_1: WidgetStatePropertyRef<TextStyle> = Rc::new(WidgetStatePropertyAll::new(
            TextStyle::new().font_size(14.0),
        ));
        let text_style_2: WidgetStatePropertyRef<TextStyle> = Rc::new(WidgetStatePropertyAll::new(
            TextStyle::new().font_size(20.0),
        ));
        let lerp = |t: f64| {
            <dyn WidgetStateProperty<TextStyle>>::lerp(
                Some(Rc::clone(&text_style_1)),
                Some(Rc::clone(&text_style_2)),
                t,
                |a, b, t| TextStyle::lerp(a.as_ref(), b.as_ref(), t),
            )
            .expect("one side")
            .resolve(&enabled)
            .expect("both sides")
            .font_size
        };
        assert_eq!(lerp(0.0), Some(14.0));
        assert_eq!(lerp(0.5), Some(17.0));
        assert_eq!(lerp(1.0), Some(20.0));
        assert!(
            <dyn WidgetStateProperty<TextStyle>>::lerp(None, None, 0.5, |_, _, _| None).is_none()
        );
    }

    #[test]
    fn lerp_optional_interpolates_nullable_values_and_hands_a_none_side_on() {
        let enabled = WidgetStates::new();
        let some: WidgetStatePropertyRef<Option<f64>> =
            Rc::new(WidgetStatePropertyAll::new(Some(10.0)));
        let none: WidgetStatePropertyRef<Option<f64>> = Rc::new(WidgetStatePropertyAll::new(None));
        let lerp = |a: &WidgetStatePropertyRef<Option<f64>>,
                    b: Option<&WidgetStatePropertyRef<Option<f64>>>,
                    t: f64| {
            <dyn WidgetStateProperty<Option<f64>>>::lerp_optional(
                Some(Rc::clone(a)),
                b.cloned(),
                t,
                |a, b, t| match (a, b) {
                    (Some(a), Some(b)) => Some(a + (b - a) * t),
                    (Some(a), None) => Some(a * (1.0 - t)),
                    (None, Some(b)) => Some(b * t),
                    (None, None) => None,
                },
            )
            .expect("one side")
            .resolve(&enabled)
        };
        let twenty: WidgetStatePropertyRef<Option<f64>> =
            Rc::new(WidgetStatePropertyAll::new(Some(20.0)));
        assert_eq!(lerp(&some, Some(&twenty), 0.5), Some(15.0));
        assert_eq!(lerp(&some, Some(&none), 0.5), Some(5.0));
        assert_eq!(lerp(&some, None, 0.5), Some(5.0));
        assert_eq!(lerp(&none, Some(&none), 0.5), None);
        assert!(
            <dyn WidgetStateProperty<Option<f64>>>::lerp_optional(None, None, 0.5, |_, _, _| None)
                .is_none()
        );
    }

    #[test]
    fn a_widget_state_color_resolves_per_state_and_travels_through_a_text_style() {
        let color = WidgetStateColor::resolve_with(|states| {
            if states.contains(&WidgetState::Pressed) {
                return RED;
            }
            BLACK
        });
        assert_eq!(color.resolve(&states([WidgetState::Pressed])), RED);
        assert_eq!(color.resolve(&WidgetStates::new()), BLACK);

        let style = TextStyle::new().color(color);
        let color = style.color.clone().expect("set above");
        assert_eq!(color.color(), BLACK, "the default-state value is the Color");
        let property = color
            .extension::<WidgetStateColor>()
            .expect("the extension survives the style");
        assert_eq!(property.resolve(&states([WidgetState::Pressed])), RED);

        assert_eq!(
            <dyn WidgetStateProperty<Color>>::resolve_as(&color, &states([WidgetState::Pressed])),
            AnyColor::new(RED)
        );
        assert_eq!(
            <dyn WidgetStateProperty<Color>>::resolve_as(
                &Some(color),
                &states([WidgetState::Pressed])
            ),
            Some(AnyColor::new(RED))
        );
    }

    #[test]
    fn resolve_as_returns_a_plain_color_unchanged() {
        let plain = AnyColor::new(RED);
        assert_eq!(
            <dyn WidgetStateProperty<Color>>::resolve_as(&plain, &states([WidgetState::Pressed])),
            plain
        );
        assert_eq!(
            <dyn WidgetStateProperty<Color>>::resolve_as(
                &None::<AnyColor>,
                &states([WidgetState::Pressed])
            ),
            None
        );
    }

    #[test]
    fn transparent_resolves_transparent_and_a_from_map_color_resolves_its_first_key() {
        let transparent = WidgetStateColor::transparent().into_any();
        assert_eq!(transparent.color(), Color::new(0x00000000));
        assert_eq!(
            transparent
                .extension::<WidgetStateColor>()
                .expect("a WidgetStateColor")
                .resolve(&states([WidgetState::Pressed])),
            Color::new(0x00000000)
        );
        assert_eq!(transparent, WidgetStateColor::transparent().into_any());

        let color = WidgetStateColor::from_map(vec![
            (WidgetState::Focused | WidgetState::Hovered, WHITE),
            (WidgetState::any(), BLACK),
        ]);
        assert_eq!(color.resolve(&states([WidgetState::Hovered])), WHITE);
        assert_eq!(color.resolve(&states([WidgetState::Pressed])), BLACK);
        assert_eq!(color.into_any().color(), BLACK);
    }

    // widget_state_property_test.dart '.fromMap() constructors perform accurate equality checks'.
    #[test]
    fn from_map_constructors_perform_accurate_equality_checks() {
        let color_1 = WidgetStateColor::from_map(vec![
            (WidgetState::Focused | WidgetState::Hovered, WHITE),
            (WidgetState::any(), BLACK),
        ])
        .into_any();
        let color_2 = WidgetStateColor::from_map(vec![
            (WidgetState::Focused | WidgetState::Hovered, WHITE),
            (WidgetState::any(), BLACK),
        ])
        .into_any();
        let color_3 = WidgetStateColor::from_map(vec![
            (WidgetState::Focused | WidgetState::Hovered, BLACK),
            (WidgetState::any(), WHITE),
        ])
        .into_any();
        assert!(color_1 == color_2);
        assert!(color_1 != color_3);

        let cursor_1 = cursor(
            WidgetStateMouseCursor::from_map(vec![
                (
                    WidgetState::Focused | WidgetState::Hovered,
                    <dyn MouseCursor>::defer(),
                ),
                (WidgetState::any(), <dyn MouseCursor>::uncontrolled()),
            ])
            .into(),
        );
        let cursor_2 = cursor(
            WidgetStateMouseCursor::from_map(vec![
                (
                    WidgetState::Focused | WidgetState::Hovered,
                    <dyn MouseCursor>::defer(),
                ),
                (WidgetState::any(), <dyn MouseCursor>::uncontrolled()),
            ])
            .into(),
        );
        let cursor_3 = cursor(
            WidgetStateMouseCursor::from_map(vec![
                (
                    WidgetState::Focused | WidgetState::Hovered,
                    <dyn MouseCursor>::uncontrolled(),
                ),
                (WidgetState::any(), <dyn MouseCursor>::defer()),
            ])
            .into(),
        );
        assert!(*cursor_1 == *cursor_2);
        assert!(*cursor_1 != *cursor_3);

        let white_border = BorderSide {
            color: WHITE,
            ..BorderSide::default()
        };
        let black_border = BorderSide::default();
        let side = |first: BorderSide, rest: BorderSide| {
            WidgetStateBorderSide::from_map(vec![
                (WidgetState::Focused | WidgetState::Hovered, Some(first)),
                (WidgetState::any(), Some(rest)),
            ])
            .into_any()
        };
        assert!(side(white_border, black_border) == side(white_border, black_border));
        assert!(side(white_border, black_border) != side(black_border, white_border));

        let rrect = |side: BorderSide| -> OutlinedBorderRef {
            OutlinedBorderRef::new(RoundedRectangleBorder {
                side,
                ..RoundedRectangleBorder::default()
            })
        };
        let border = |first: BorderSide, rest: BorderSide| {
            WidgetStateOutlinedBorder::from_map(vec![
                (
                    WidgetState::Focused | WidgetState::Hovered,
                    Some(rrect(first)),
                ),
                (WidgetState::any(), Some(rrect(rest))),
            ])
        };
        assert!(border(white_border, black_border).eq_shape(&border(white_border, black_border)));
        assert!(!border(white_border, black_border).eq_shape(&border(black_border, white_border)));

        let text = |first: Color, rest: Color| {
            WidgetStateTextStyle::from_map(vec![
                (
                    WidgetState::Focused | WidgetState::Hovered,
                    TextStyle::new().color(first),
                ),
                (WidgetState::any(), TextStyle::new().color(rest)),
            ])
            .into_any()
        };
        assert!(text(WHITE, BLACK) == text(WHITE, BLACK));
        assert!(text(WHITE, BLACK) != text(BLACK, WHITE));
    }

    /// Not a Dart case: the `==` overrides of `widget_state.dart`, read through the erased
    /// property a theme stores.
    #[test]
    fn erased_properties_compare_as_darts_equality_overrides_do() {
        let all = |value: f64| <dyn WidgetStateProperty<f64>>::all(value);
        assert!(*all(1.0) == *all(1.0));
        assert!(*all(1.0) != *all(2.0));

        let map = |first: Color, rest: Color| {
            <dyn WidgetStateProperty<Color>>::from_map(vec![
                (WidgetState::Disabled.into(), first),
                (WidgetState::any(), rest),
            ])
        };
        assert!(*map(WHITE, BLACK) == *map(WHITE, BLACK));
        assert!(*map(WHITE, BLACK) != *map(BLACK, WHITE));
        let mapped_color: WidgetStatePropertyRef<Color> =
            Rc::new(WidgetStateColor::from_map(vec![
                (WidgetState::Disabled.into(), WHITE),
                (WidgetState::any(), BLACK),
            ]));
        assert!(*map(WHITE, BLACK) == *mapped_color);
        assert!(*mapped_color == *map(WHITE, BLACK));
        assert!(*map(WHITE, BLACK) != *<dyn WidgetStateProperty<Color>>::all(WHITE));

        let resolved = <dyn WidgetStateProperty<f64>>::resolve_with(|_| 1.0);
        assert!(*resolved == *Rc::clone(&resolved));
        assert!(*resolved != *<dyn WidgetStateProperty<f64>>::resolve_with(|_| 1.0));

        let color = |value: Color| -> WidgetStatePropertyRef<Color> {
            Rc::new(WidgetStateColor::resolve_with(move |_| value))
        };
        assert!(*color(WHITE) == *color(WHITE));
        assert!(*color(WHITE) != *color(BLACK));

        // Dart's `WidgetStatePropertyAll<Widget?>`: widgets compare by identity.
        use crate::framework::{IntoWidget, WidgetRef};
        let icon: WidgetRef = crate::widgets::basic::SizedBox::new().into_widget();
        let widget = |widget: &WidgetRef| {
            <dyn WidgetStateProperty<Option<WidgetRef>>>::all(Some(Rc::clone(widget)))
        };
        assert!(*widget(&icon) == *widget(&icon));
        let other: WidgetRef = crate::widgets::basic::SizedBox::new().into_widget();
        assert!(*widget(&icon) != *widget(&other));
    }

    // widget_state_property_test.dart 'WidgetStateBorderSide.lerp()'.
    #[test]
    fn border_side_lerp_interpolates_the_resolved_sides() {
        let side_1: WidgetStatePropertyRef<Option<BorderSide>> =
            Rc::new(WidgetStatePropertyAll::new(Some(BorderSide {
                color: Color::new(0xffff0000),
                width: 4.0,
                ..BorderSide::default()
            })));
        let side_2: WidgetStatePropertyRef<Option<BorderSide>> =
            Rc::new(WidgetStatePropertyAll::new(Some(BorderSide {
                color: Color::new(0xff0000ff),
                width: 12.0,
                ..BorderSide::default()
            })));
        let lerp = |t: f64| {
            WidgetStateBorderSide::lerp(Some(Rc::clone(&side_1)), Some(Rc::clone(&side_2)), t)
                .expect("two sides")
                .resolve(&WidgetStates::new())
                .expect("a side")
        };
        assert_eq!(lerp(0.0).color, Color::new(0xffff0000));
        assert_eq!(lerp(0.0).width, 4.0);
        // Dart's `isSameColorAs` allows a rounding step per channel.
        #[allow(deprecated)]
        let (red, blue) = (lerp(0.5).color.red(), lerp(0.5).color.blue());
        assert!(
            (red - 0x7f).abs() <= 1 && (blue - 0x7f).abs() <= 1,
            "{:?}",
            lerp(0.5).color
        );
        assert_eq!(lerp(0.5).width, 8.0);
        assert_eq!(lerp(1.0).color, Color::new(0xff0000ff));
        assert_eq!(lerp(1.0).width, 12.0);
        assert!(WidgetStateBorderSide::lerp(None, None, 0.5).is_none());
    }

    /// A widget-state side, border or style passed where Dart takes the plain value is the
    /// default value there and resolves through `resolve_as`.
    #[test]
    fn the_widget_state_values_are_their_default_and_resolve_through_resolve_as() {
        let pressed = states([WidgetState::Pressed]);
        let red_side = BorderSide {
            color: RED,
            ..BorderSide::default()
        };
        let side: Option<AnyBorderSide> = Some(
            WidgetStateBorderSide::resolve_with(move |states| {
                states.contains(&WidgetState::Pressed).then_some(red_side)
            })
            .into(),
        );
        assert_eq!(
            *side.as_ref().expect("a side").value(),
            BorderSide::default()
        );
        let resolved = <dyn WidgetStateProperty<Option<BorderSide>>>::resolve_as(&side, &pressed);
        assert_eq!(resolved, Some(AnyBorderSide::new(red_side)));
        let resolved =
            <dyn WidgetStateProperty<Option<BorderSide>>>::resolve_as(&side, &WidgetStates::new());
        assert_eq!(resolved, None);

        let style: AnyTextStyle = WidgetStateTextStyle::resolve_with(|states| {
            TextStyle::new().font_size(if states.contains(&WidgetState::Pressed) {
                20.0
            } else {
                10.0
            })
        })
        .into();
        assert_eq!(*style.value(), TextStyle::new());
        let resolved = <dyn WidgetStateProperty<TextStyle>>::resolve_as(&style, &pressed);
        assert_eq!(resolved.font_size, Some(20.0));

        let border: Option<OutlinedBorderRef> = Some(OutlinedBorderRef::new(
            WidgetStateOutlinedBorder::resolve_with(|states| {
                states.contains(&WidgetState::Pressed).then(|| {
                    OutlinedBorderRef::new(RoundedRectangleBorder {
                        side: BorderSide {
                            width: 3.0,
                            ..BorderSide::default()
                        },
                        ..RoundedRectangleBorder::default()
                    })
                })
            }),
        ));
        assert_eq!(
            border.as_ref().expect("a border").side(),
            RoundedRectangleBorder::default().side,
            "as a plain border it is the default rounded rectangle"
        );
        let resolved =
            <dyn WidgetStateProperty<Option<OutlinedBorderRef>>>::resolve_as(&border, &pressed)
                .expect("a border");
        assert_eq!(resolved.side().width, 3.0);
    }

    #[test]
    fn clickable_resolves_to_basic_when_disabled_and_is_a_mouse_cursor() {
        let clickable = WidgetStateMouseCursor::clickable();
        assert!(
            *clickable.resolve(&WidgetStates::new()) == *cursor(SystemMouseCursors::CLICK.into())
        );
        assert!(
            *clickable.resolve(&states([WidgetState::Disabled]))
                == *cursor(SystemMouseCursors::BASIC.into())
        );
        assert_eq!(
            clickable.debug_description(),
            "WidgetStateMouseCursor(clickable)"
        );

        let textable = WidgetStateMouseCursor::textable();
        assert!(
            *textable.resolve(&WidgetStates::new()) == *cursor(SystemMouseCursors::TEXT.into())
        );

        // Dart's `static const` cursors are one object each, so they compare equal; a
        // `resolve_with` cursor is equal only to itself.
        let as_property =
            |cursor: WidgetStateMouseCursor| -> WidgetStatePropertyRef<MouseCursorRef> {
                Rc::new(cursor)
            };
        assert!(
            *as_property(WidgetStateMouseCursor::clickable())
                == *as_property(WidgetStateMouseCursor::clickable())
        );
        assert!(
            *as_property(WidgetStateMouseCursor::clickable())
                != *as_property(WidgetStateMouseCursor::textable())
        );
        let as_cursor = |cursor: WidgetStateMouseCursor| -> MouseCursorRef { Rc::new(cursor) };
        assert!(
            *as_cursor(WidgetStateMouseCursor::adaptive_clickable())
                == *as_cursor(WidgetStateMouseCursor::adaptive_clickable())
        );
        let resolve_click =
            |_: &WidgetStates| -> MouseCursorRef { SystemMouseCursors::CLICK.into() };
        assert!(
            *as_property(WidgetStateMouseCursor::resolve_with(resolve_click, None))
                != *as_property(WidgetStateMouseCursor::resolve_with(resolve_click, None))
        );
        assert!(
            *textable.resolve(&states([WidgetState::Disabled]))
                == *cursor(SystemMouseCursors::BASIC.into())
        );

        // Used as a plain cursor, the session is the default-state cursor's.
        let session = clickable.create_session(1);
        assert!(*session.cursor() == *cursor(SystemMouseCursors::CLICK.into()));
        assert_eq!(session.device(), 1);

        let erased: MouseCursorRef = clickable.into();
        assert!(erased.as_any().is::<WidgetStateMouseCursor>());
        assert!(
            *<dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(
                &erased,
                &states([WidgetState::Disabled])
            ) == *cursor(SystemMouseCursors::BASIC.into())
        );
        assert!(
            *<dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(
                &Some(Rc::clone(&erased)),
                &states([WidgetState::Disabled])
            )
            .expect("some")
                == *cursor(SystemMouseCursors::BASIC.into())
        );
        let plain = cursor(SystemMouseCursors::GRAB.into());
        assert!(Rc::ptr_eq(
            &<dyn WidgetStateProperty<MouseCursorRef>>::resolve_as(&plain, &WidgetStates::new()),
            &plain
        ));
    }

    // widget_state_mouse_cursor.0.dart: a cursor that is forbidden when disabled.
    #[test]
    fn a_resolve_with_cursor_can_forbid_when_disabled() {
        let cursor = WidgetStateMouseCursor::resolve_with(
            |states| {
                if states.contains(&WidgetState::Disabled) {
                    return SystemMouseCursors::FORBIDDEN.into();
                }
                SystemMouseCursors::CLICK.into()
            },
            None,
        );
        assert!(
            *cursor.resolve(&states([WidgetState::Disabled]))
                == *MouseCursorRef::from(SystemMouseCursors::FORBIDDEN)
        );
        assert!(
            *cursor.resolve(&WidgetStates::new())
                == *MouseCursorRef::from(SystemMouseCursors::CLICK)
        );
        assert_eq!(cursor.debug_description(), "WidgetStateMouseCursor()");
    }

    // widget_states_controller_test.dart 'WidgetStatesController constructor'.
    #[test]
    fn controller_starts_with_the_given_states() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let empty = WidgetStatesController::new(&mut app, None);
        assert_eq!(*app.get(&empty).value(), WidgetStates::new());
        let selected = WidgetStatesController::new(&mut app, Some(states([WidgetState::Selected])));
        assert_eq!(*app.get(&selected).value(), states([WidgetState::Selected]));
    }

    // widget_states_controller_test.dart 'WidgetStatesController update, listener'.
    #[test]
    fn controller_update_notifies_only_on_change() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let count = Rc::new(Cell::new(0));
        let value_changed = Listener::new({
            let count = Rc::clone(&count);
            move |_app| count.set(count.get() + 1)
        });

        let controller = WidgetStatesController::new(&mut app, None);
        controller.add_listener(&mut app, value_changed.clone());

        let expect = |app: &App, expected: &[WidgetState], expected_count: i32| {
            assert_eq!(
                *app.get(&controller).value(),
                states(expected.iter().copied())
            );
            assert_eq!(count.get(), expected_count);
        };

        controller.update(&mut app, WidgetState::Selected, true);
        expect(&app, &[WidgetState::Selected], 1);
        controller.update(&mut app, WidgetState::Selected, true);
        expect(&app, &[WidgetState::Selected], 1);

        controller.update(&mut app, WidgetState::Hovered, false);
        expect(&app, &[WidgetState::Selected], 1);
        controller.update(&mut app, WidgetState::Selected, false);
        expect(&app, &[], 2);

        controller.update(&mut app, WidgetState::Hovered, true);
        expect(&app, &[WidgetState::Hovered], 3);
        controller.update(&mut app, WidgetState::Hovered, true);
        expect(&app, &[WidgetState::Hovered], 3);
        controller.update(&mut app, WidgetState::Pressed, true);
        expect(&app, &[WidgetState::Hovered, WidgetState::Pressed], 4);
        controller.update(&mut app, WidgetState::Selected, true);
        expect(
            &app,
            &[
                WidgetState::Hovered,
                WidgetState::Pressed,
                WidgetState::Selected,
            ],
            5,
        );
        controller.update(&mut app, WidgetState::Selected, false);
        expect(&app, &[WidgetState::Hovered, WidgetState::Pressed], 6);
        controller.update(&mut app, WidgetState::Selected, false);
        expect(&app, &[WidgetState::Hovered, WidgetState::Pressed], 6);
        controller.update(&mut app, WidgetState::Pressed, false);
        expect(&app, &[WidgetState::Hovered], 7);
        controller.update(&mut app, WidgetState::Hovered, false);
        expect(&app, &[], 8);

        controller.remove_listener(&mut app, &value_changed);
        controller.update(&mut app, WidgetState::Selected, true);
        expect(&app, &[WidgetState::Selected], 8);
    }

    // widget_states_controller_test.dart 'WidgetStatesController const initial value'.
    #[test]
    fn controller_with_an_initial_value_notifies_only_on_change() {
        let cell = AppCell::new();
        let mut app = cell.borrow_mut();
        let count = Rc::new(Cell::new(0));
        let controller =
            WidgetStatesController::new(&mut app, Some(states([WidgetState::Selected])));
        controller.add_listener(&mut app, {
            let count = Rc::clone(&count);
            Listener::new(move |_app| count.set(count.get() + 1))
        });

        controller.update(&mut app, WidgetState::Selected, true);
        assert_eq!(
            *app.get(&controller).value(),
            states([WidgetState::Selected])
        );
        assert_eq!(count.get(), 0);

        controller.update(&mut app, WidgetState::Selected, false);
        assert_eq!(*app.get(&controller).value(), WidgetStates::new());
        assert_eq!(count.get(), 1);

        controller.set_value(&mut app, states([WidgetState::Hovered]));
        assert_eq!(count.get(), 2);
        controller.set_value(&mut app, states([WidgetState::Hovered]));
        assert_eq!(count.get(), 2);

        controller.dispose(&mut app);
        assert!(!app.get(&controller).change_notifier_data().has_listeners());
    }
}