rust_widgets 2.9.2

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Date editor widget.
//!
//! [`DateEdit`] stores a calendar date as a [`Date`] value and lets the user
//! step through it or set it programmatically.
//!
//! # Conventions
//!
//! * The month is **1-based** (`1` = January, `12` = December) and the day is
//!   **1-based** (`1` = the first of the month), matching both the text format
//!   and the widget's setters.
//! * The widget's range is **inclusive at both ends**: a date equal to
//!   [`DateEdit::minimum_date`] or [`DateEdit::maximum_date`] is accepted.
//! * A `Date` stores whatever it is constructed with; validity is checked
//!   separately. [`Date::is_valid`] is the predicate, and
//!   [`DateEdit::set_date`] rejects invalid or out-of-range dates silently
//!   rather than clamping them, leaving the previous value in place.
//! * The month and day setters on [`Date`] clamp to the field's numeric range
//!   (`1..=12` and `1..=31`); they do not consult the month length, so they can
//!   leave the value invalid. Use [`DateEdit::set_date`] to keep it valid.
//! * Dates are compared and ordered by year, then month, then day.
use super::calendar::Calendar;
use crate::core::{Color, HorizontalAlignment, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::shortcut::Key;
use crate::signal::{GenericSignal, Signal1};
use crate::undo::{UndoStack, ValueCommand};
use crate::widget::capability::access::{date_to_string, weekday_to_str};
use crate::widget::capability::coercion::{
    expect_bool, expect_date, expect_horizontal_alignment, expect_string, expect_weekday,
    horizontal_alignment_to_str,
};
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::input_widgets::shortcut_editor::primary_shortcut_pressed;
use crate::widget::metrics::{dimensions, effective_font};
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
use chrono::{Datelike, NaiveDate, Weekday};
use std::cell::RefCell;
use std::fmt::Write as _;
use std::rc::Rc;

/// Date value (year, month, day).
///
/// This is a plain value type, not a validated one: [`Date::new`] stores the
/// components as given, including values outside the calendar, and the month
/// and day setters clamp only to their field's numeric range. Call
/// [`Date::is_valid`] to check that the combination exists, or use the widget's
/// [`DateEdit::set_date`], which performs that check for you.
///
/// `Ord` follows chronological order: year, then month, then day.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Date {
    year: i32,
    month: u8, // 1-12
    day: u8,   // 1-31
}
impl Date {
    /// Creates a date from raw components without validation.
    ///
    /// `month` is 1-based (`1..=12`) and `day` is 1-based (`1..=31`); the year
    /// may be negative. Out-of-range components are stored as-is and reported
    /// later by [`Date::is_valid`].
    pub fn new(year: i32, month: u8, day: u8) -> Self {
        Self { year, month, day }
    }
    /// Returns the current date.
    ///
    /// # Caveat
    ///
    /// This does **not** consult the system clock: it currently returns the
    /// fixed date `2024-01-01`. Treat it as "a default date", not "today".
    /// Callers that need the real date should obtain it from the platform and
    /// construct a [`Date`] explicitly.
    pub fn today() -> Self {
        Self { year: 2024, month: 1, day: 1 }
    }
    /// Returns the year component. The year is not range-checked.
    pub fn year(&self) -> i32 {
        self.year
    }
    /// Returns the 1-based month (`1` = January).
    pub fn month(&self) -> u8 {
        self.month
    }
    /// Returns the 1-based day of the month (`1` = first).
    pub fn day(&self) -> u8 {
        self.day
    }
    /// Sets the year, accepting any `i32` including negative values.
    ///
    /// No range check is applied; whether the result is a valid date is left to
    /// [`Date::is_valid`].
    pub fn set_year(&mut self, year: i32) {
        self.year = year;
    }
    /// Sets the 1-based month, clamped into `1..=12`.
    ///
    /// Only the numeric range is enforced, so setting a month to `2` on a
    /// 31-day date leaves an invalid combination for [`Date::is_valid`] to
    /// report; the day is not adjusted.
    pub fn set_month(&mut self, month: u8) {
        self.month = month.clamp(1, 12);
    }
    /// Sets the 1-based day, clamped into `1..=31`.
    ///
    /// The month length is not considered, so the result may be invalid for the
    /// month; see [`Date::is_valid`].
    pub fn set_day(&mut self, day: u8) {
        self.day = day.clamp(1, 31);
    }
    /// Returns the number of days in this date's month.
    ///
    /// February accounts for leap years via [`Date::is_leap_year`], giving 28
    /// or 29 days. If `month` is outside `1..=12` (possible after [`Date::new`]
    /// or a direct field assignment) this returns `30`.
    pub fn days_in_month(&self) -> u8 {
        match self.month {
            1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
            4 | 6 | 9 | 11 => 30,
            2 => {
                if self.is_leap_year() {
                    29
                } else {
                    28
                }
            }
            _ => 30,
        }
    }
    /// Returns `true` for Gregorian leap years.
    ///
    /// The rule is the proleptic Gregorian one: divisible by 4, except centuries,
    /// except millennia. It is applied to negative and zero years too, where the
    /// "divisible by" test follows Rust's remainder semantics.
    pub fn is_leap_year(&self) -> bool {
        (self.year % 4 == 0 && self.year % 100 != 0) || (self.year % 400 == 0)
    }
    /// Returns `true` when the stored combination is a real calendar date.
    ///
    /// Requires a month in `1..=12` and a day in `1..=`[`Date::days_in_month`].
    /// The year is never a reason for invalidity.
    pub fn is_valid(&self) -> bool {
        self.month >= 1 && self.month <= 12 && self.day >= 1 && self.day <= self.days_in_month()
    }

    /// The day of the week, `0` = Sunday through `6` = Saturday.
    ///
    /// # Why this exists
    ///
    /// A month grid cannot be laid out without it: the first week of a month starts at the column
    /// of its first day, and that column is a weekday. Without it a calendar popup could only print
    /// the days in a run, which is not a calendar.
    ///
    /// # The algorithm
    ///
    /// Sakamoto's, which needs no tables and no era arithmetic: it is exact for every Gregorian
    /// date, including the `1752-09-14` floor this widget accepts and leap years. It is applied to an
    /// invalid combination (a day of `32`) without checking, the same way every other accessor here
    /// does — validation is [`Date::is_valid`]'s job.
    ///
    /// A month outside `1..=12` (possible after [`Date::new`] or a direct field assignment) yields a
    /// clamped month rather than indexing out of bounds: this is an accessor on a value that is
    /// allowed to be invalid, so it must not be the thing that panics.
    pub fn weekday(&self) -> u8 {
        // Offsets `t` for each month, in **calendar order** (January first). Sakamoto's form: the
        // table folds January and February into the previous year's tail, which is why their offsets
        // are non-monotonic — that is the table, not a mistake.
        //
        //     t = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4]
        //
        // The year term adds a day for each leap year, so it must be taken on the *shifted* year:
        // January and February belong to the year before theirs for that purpose, which is the `-1`
        // below. Using the unshifted year here is the classic way this formula goes wrong once per
        // leap year.
        let month = self.month.clamp(1, 12) as usize;
        const T: [i32; 12] = [0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4];
        let t = T[month - 1];
        let year = if self.month < 3 { self.year - 1 } else { self.year };
        // `rem_euclid` rather than `%`: a pre-epoch year gives a negative sum, and `%` would return a
        // negative weekday instead of one in `0..=6`.
        ((year + year / 4 - year / 100 + year / 400 + t + self.day as i32).rem_euclid(7)) as u8
    }
}
/// Formats the date as `YYYY-MM-DD`.
///
/// The year is zero-padded to four digits; the month and day are always two
/// digits. This is the spelling [`crate::widget::capability::coercion::expect_date`]
/// parses back, so the round-trip is lossless. The fields are emitted verbatim
/// even when the date is not a valid calendar date.
impl std::fmt::Display for Date {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
    }
}

/// Substitutes a `display_format` pattern with the given component values, appending the
/// rendering to `out` and returning whether any token substituted.
///
/// # Why one formatter and not three
///
/// `date_edit`, `date_time_edit` and `time_edit` each hold a pattern that they used to store and
/// round-trip without ever applying — their own documentation said so. Three implementations of
/// "replace `yyyy` with the year" would be three chances for the same pattern to render differently
/// in the three controls, which is how the eight dialogs acquired four title-bar heights (rule #101).
/// The pattern is the same idea in all three, so the substitution is one function.
///
/// # The tokens
///
/// Longest-first, because `MM` and `mm` and `M` all start with `M` and a left-to-right scan that
/// tried `M` first would turn `MM` into two months and `yyyy` into four years. The set is the subset
/// of the usual pattern letters that these three controls can supply:
///
/// | token | meaning |
/// |---|---|
/// | `yyyy` | four-digit year (zero-padded, and sign-preserving) |
/// | `yy` | two-digit year |
/// | `MM` | two-digit month, `01`–`12` |
/// | `M` | month without padding |
/// | `dd` | two-digit day, `01`–`31` |
/// | `d` | day without padding |
/// | `HH` | two-digit 24-hour, `00`–`23` |
/// | `H` | hour without padding |
/// | `hh` | two-digit 12-hour, `01`–`12` |
/// | `h` | 12-hour without padding |
/// | `AP` | `AM` / `PM` |
/// | `ap` | `am` / `pm` |
/// | `mm` | two-digit minute |
/// | `ss` | two-digit second |
/// | `SSS` | milliseconds, three digits |
/// | `zzz` | milliseconds, three digits (the usual pattern spelling) |
///
/// Longest-first is **not enough on its own**. A single-letter token still matches inside a word, and a
/// scan with no lookaround turned the literal `"Today: yyyy"` into `"To8ay: 2026"` — the `d` of
/// `Today` became the day of the month. So a token is only recognised where it can be a **token**:
/// at the start of the pattern, or after a character that is not a letter. That rule is what the
/// usual pattern languages mean by a literal, and it is why `"Today: yyyy"` now passes "Today"
/// through untouched while `"dd/MM/yyyy"` still substitutes every field.
///
/// Anything else — a separator, a literal word — is copied through unchanged, so a pattern that is
/// not understood degrades to more literal text rather than to an empty field.
///
/// The unused components are passed as `None` by the caller: a date-only control has no hour, so
/// `HH` in its pattern expands to nothing rather than to a plausible `00`.
///
/// Returns `false` when the pattern contains **no recognised token at all**, which is the signal a
/// caller uses to fall back to its own fixed spelling: a pattern of `"today"` should not replace the
/// value's display with the word "today".
///
/// # Why into-style
///
/// Every token renders straight into the caller's buffer, so a draw-pass caller spends one
/// allocation per frame instead of one per token on top of the result string.
/// [`format_with_pattern`] is the allocating wrapper kept for `size_hint` and the tests.
pub(crate) fn format_with_pattern_into(
    pattern: &str,
    components: DateTimeComponents,
    out: &mut String,
) -> bool {
    /// One pattern token and the way it renders itself from the components.
    ///
    /// Named so the table below is an array of pairs rather than an array of a type whose shape has to
    /// be read off the literal. Renders into the caller's buffer and reports whether the component
    /// existed — a token with no value behind it writes nothing and is dropped rather than passed
    /// through: the caller chose the pattern and knows which components it has, so `HH` in a date-only
    /// pattern is a mistake to swallow, not a literal to display.
    type Token = (&'static str, fn(&DateTimeComponents, &mut String) -> bool);
    // Longest first, so a two-character token is never eaten by its one-character prefix.
    const TOKENS: [Token; 16] = [
        // 12-hour clock: `0` and `12` both read as 12, the way a wall clock does.
        ("hh", |c, out| match c.hour {
            Some(h) => {
                let hour12 = if h % 12 == 0 { 12 } else { h % 12 };
                let _ = write!(out, "{hour12:02}");
                true
            }
            None => false,
        }),
        ("h", |c, out| match c.hour {
            Some(h) => {
                let hour12 = if h % 12 == 0 { 12 } else { h % 12 };
                let _ = write!(out, "{hour12}");
                true
            }
            None => false,
        }),
        ("zzz", |c, out| match c.millisecond {
            Some(ms) => {
                let _ = write!(out, "{ms:03}");
                true
            }
            None => false,
        }),
        ("AP", |c, out| match c.hour {
            Some(h) => {
                out.push_str(if h < 12 { "AM" } else { "PM" });
                true
            }
            None => false,
        }),
        ("ap", |c, out| match c.hour {
            Some(h) => {
                out.push_str(if h < 12 { "am" } else { "pm" });
                true
            }
            None => false,
        }),
        ("yyyy", |c, out| match c.year {
            Some(y) => {
                let _ = write!(out, "{y:04}");
                true
            }
            None => false,
        }),
        ("SSS", |c, out| match c.millisecond {
            Some(ms) => {
                let _ = write!(out, "{ms:03}");
                true
            }
            None => false,
        }),
        ("yy", |c, out| match c.year {
            Some(y) => {
                let _ = write!(out, "{:02}", y.rem_euclid(100));
                true
            }
            None => false,
        }),
        ("MM", |c, out| match c.month {
            Some(m) => {
                let _ = write!(out, "{m:02}");
                true
            }
            None => false,
        }),
        ("dd", |c, out| match c.day {
            Some(d) => {
                let _ = write!(out, "{d:02}");
                true
            }
            None => false,
        }),
        ("HH", |c, out| match c.hour {
            Some(h) => {
                let _ = write!(out, "{h:02}");
                true
            }
            None => false,
        }),
        ("mm", |c, out| match c.minute {
            Some(m) => {
                let _ = write!(out, "{m:02}");
                true
            }
            None => false,
        }),
        ("ss", |c, out| match c.second {
            Some(s) => {
                let _ = write!(out, "{s:02}");
                true
            }
            None => false,
        }),
        ("M", |c, out| match c.month {
            Some(m) => {
                let _ = write!(out, "{m}");
                true
            }
            None => false,
        }),
        ("d", |c, out| match c.day {
            Some(d) => {
                let _ = write!(out, "{d}");
                true
            }
            None => false,
        }),
        ("H", |c, out| match c.hour {
            Some(h) => {
                let _ = write!(out, "{h}");
                true
            }
            None => false,
        }),
    ];

    let mut substituted = false;
    let mut rest = pattern;
    // Whether a token may start here: only at the beginning or after a non-letter. See the doc
    // comment above for the `"Today"` case this exists to fix.
    let mut at_token_start = true;
    'scan: while !rest.is_empty() {
        if at_token_start {
            for (token, render) in TOKENS {
                if let Some(after) = rest.strip_prefix(token) {
                    if render(&components, out) {
                        substituted = true;
                    }
                    rest = after;
                    // A token's own last character is a letter, so the run continues: `yyyyMM` must
                    // be two tokens, not a year followed by a literal `MM`.
                    at_token_start = true;
                    continue 'scan;
                }
            }
        }
        // No token matched, so this character is literal text (a separator, a word, a stray letter).
        // Advancing by one **char**, not one byte: a multi-byte character in a label would otherwise
        // be split and produce invalid text.
        let Some(ch) = rest.chars().next() else {
            break;
        };
        out.push(ch);
        rest = &rest[ch.len_utf8()..];
        at_token_start = !ch.is_alphabetic();
    }

    substituted
}

/// The allocating wrapper around [`format_with_pattern_into`], kept for `size_hint` and the
/// tests: a draw-pass caller uses the into-style core directly so it can reuse a buffer.
pub(crate) fn format_with_pattern(pattern: &str, components: DateTimeComponents) -> Option<String> {
    let mut out = crate::compat::String::new();
    if format_with_pattern_into(pattern, components, &mut out) {
        Some(out)
    } else {
        None
    }
}

/// The values [`format_with_pattern`] substitutes, each optional.
///
/// `None` means "this control has no such component": a date-only pattern sees no hour, a time-only
/// one sees no day. Stated as a struct rather than eleven arguments because the call sites differ
/// only in which three or four of them they fill in.
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct DateTimeComponents {
    /// Four-digit year.
    pub year: Option<i32>,
    /// Month, `1`–`12`.
    pub month: Option<u8>,
    /// Day of month, `1`–`31`.
    pub day: Option<u8>,
    /// Hour, `0`–`23`.
    pub hour: Option<u8>,
    /// Minute, `0`–`59`.
    pub minute: Option<u8>,
    /// Second, `0`–`59`.
    pub second: Option<u8>,
    /// Millisecond, `0`–`999`.
    pub millisecond: Option<u16>,
}
/// One editable component of a date field.
///
/// A date editor with a section model lets a user type into the year, the month or the
/// day without re-entering the whole value: Left/Right choose the section, Up/Down step
/// it, and digits accumulate into it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DateSection {
    /// The year component.
    Year,
    /// The month component.
    Month,
    /// The day component.
    Day,
}

impl DateSection {
    /// The section after this one, wrapping from day back to year.
    pub const fn next(self) -> Self {
        match self {
            Self::Year => Self::Month,
            Self::Month => Self::Day,
            Self::Day => Self::Year,
        }
    }

    /// The section before this one, wrapping from year back to day.
    pub const fn previous(self) -> Self {
        match self {
            Self::Year => Self::Day,
            Self::Month => Self::Year,
            Self::Day => Self::Month,
        }
    }

    /// How many digits the section accepts before the buffer is trimmed.
    const fn digit_capacity(self) -> usize {
        match self {
            Self::Year => 4,
            _ => 2,
        }
    }
}

/// Date editor widget.
///
/// Shows a date and allows it to be changed a day at a time (see
/// [`DateEdit::step_up`] / [`DateEdit::step_down`]), programmatically via
/// [`DateEdit::set_date`], or through the keyboard (Up/Down step, Ctrl+Z/Ctrl+Y
/// undo and redo).
///
/// The accepted range defaults to `1752-09-14 ..= 9999-12-31` and is inclusive
/// at both ends; see [`DateEdit::minimum_date`] and
/// [`DateEdit::maximum_date`].
///
/// # Display format
///
/// [`DateEdit::display_format`] holds a format pattern string that is exposed
/// as a property, and it is what the field paints when the pattern is one this
/// control can render; the fixed `YYYY-MM-DD` spelling is the fallback.
pub struct DateEdit {
    base: BaseWidget,
    date: Date,
    minimum: Date,
    maximum: Date,
    display_format: String,
    /// Whether the field shows the calendar affordance.
    ///
    /// This is the *affordance* flag, not the open state: with it set, the field paints a
    /// 16 px arrow zone at its trailing edge and a press there toggles [`DateEdit::calendar_open`].
    /// The month grid itself is painted only while the calendar is open. The flag was stored,
    /// published and round-tripped from the day it was added, and the draw never read it -- so
    /// `calendar_popup: true` changed nothing on screen.
    calendar_popup: bool,
    /// Whether the month grid is currently showing.
    ///
    /// A popup has two states (closed and open) and one affordance (whether it can be opened at
    /// all); collapsing both into `calendar_popup` is what made the flag a paint switch with no
    /// open state to toggle. See [`DateEdit::set_calendar_open`].
    calendar_open: bool,
    /// Emitted with the new open state when the calendar grid is shown or hidden, so a host can
    /// dismiss its other popups without polling.
    pub popup_visibility_changed: Signal1<bool>,
    /// How the field's value is aligned within its own box.
    ///
    /// Horizontal only: the value is centred vertically in the field, so a `top`/`bottom` value
    /// would be one this control could never honour —
    /// [`crate::widget::capability::coercion::expect_horizontal_alignment`] refuses those rather
    /// than accepting a write that does nothing. Defaults to left.
    alignment: crate::core::Alignment,
    /// Emitted with the new date after every accepted change, including changes
    /// produced by [`DateEdit::undo`] and [`DateEdit::redo`]. Not emitted when a
    /// change is rejected or when the date is already the requested value.
    pub date_changed: Signal1<Date>,
    undo_stack: UndoStack,
    history_target: Rc<RefCell<Date>>,
    restoring_history: bool,
    /// The section the user is editing, or `None` when the whole value is the unit.
    ///
    /// `None` is the historical mode: Up/Down step a whole day. A section becomes active
    /// when the pointer picks one of the field's three zones or the host sets it.
    current_section: Option<DateSection>,
    /// Digits typed into the active section, cleared when it changes.
    digit_buffer: String,
    /// Whether the field paints a spin-button pair at its trailing edge.
    spin_buttons: bool,
    /// The calendar grid's reveal, so opening it animates like every other popup.
    calendar_reveal: crate::widget::menu_toolbar::popup_reveal::PopupReveal,
    /// Text shown instead of the date when the value equals the minimum.
    special_value_text: Option<String>,
    /// The embedded [`Calendar`] that owns the popup's month facts.
    ///
    /// The popup used to paint its own month grid, which duplicated the calendar's week-start,
    /// day-count and cell arithmetic. The grid now has one implementation: this instance.
    calendar: Calendar,
    /// The first column of the month grid (the embedded calendar's `first_day_of_week`).
    ///
    /// Sunday is the default because it is what the previous self-drawn grid used; a caller can
    /// change it through the `calendar_first_day` property or [`DateEdit::set_calendar_first_day`].
    calendar_first_day: Weekday,
    /// Emitted after the embedded calendar becomes visible.
    pub calendar_opened: GenericSignal,
    /// Emitted after the embedded calendar is dismissed.
    pub calendar_closed: GenericSignal,
    /// Emitted when an edit is committed: Enter on the focused field, or focus leaving it.
    ///
    /// The counterpart of [`crate::widget::advanced_widgets::DateTimeEdit::editing_finished`],
    /// which already existed: without it a host could see `date_changed` (which also fires while
    /// the user is browsing the popup) but had no way to tell "the user finished editing" from
    /// "the value moved".
    pub editing_finished: GenericSignal,
    /// Whether the embedded calendar's geometry and accepted range must be pushed again (K-P02).
    ///
    /// Every pointer move and every key press inside the open popup used to call
    /// `sync_calendar_page`, which re-set the calendar's geometry and bounds (each a repaint
    /// request) for facts that had not changed. Only opening the popup, a range change, a
    /// first-day change or a field move can change those facts, so they mark this flag and the
    /// event paths just read it.
    calendar_sync_dirty: bool,
    /// The popup rectangle last pushed into the embedded calendar, so a field move is detected
    /// without a dirty flag at every geometry write.
    calendar_sync_rect: Rect,
}
impl DateEdit {
    /// Creates a date editor occupying `geometry`.
    ///
    /// The initial date is [`Date::today`], the accepted range is
    /// `1752-09-14 ..= 9999-12-31` (inclusive), the display format is
    /// `"yyyy-MM-dd"`, and the calendar popup is disabled.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::DatePicker, geometry, "DateEdit"),
            date: Date::today(),
            minimum: Date::new(1752, 9, 14),
            maximum: Date::new(9999, 12, 31),
            display_format: "yyyy-MM-dd".to_string(),
            calendar_popup: false,
            calendar_open: false,
            alignment: crate::core::Alignment::Left,
            date_changed: Signal1::new(),
            popup_visibility_changed: Signal1::new(),
            undo_stack: UndoStack::new(),
            history_target: Rc::new(RefCell::new(Date::today())),
            restoring_history: false,
            current_section: None,
            digit_buffer: String::new(),
            spin_buttons: false,
            calendar_reveal: crate::widget::menu_toolbar::popup_reveal::PopupReveal::new(false),
            special_value_text: None,
            calendar: {
                let mut calendar = Calendar::new(calendar_popup_rect(geometry));
                calendar.set_first_day_of_week(Weekday::Sun);
                calendar
            },
            calendar_first_day: Weekday::Sun,
            calendar_opened: GenericSignal::new(),
            calendar_closed: GenericSignal::new(),
            editing_finished: GenericSignal::new(),
            calendar_sync_dirty: true,
            calendar_sync_rect: Rect::new(0, 0, 0, 0),
        }
    }
    /// Returns the current date.
    pub fn date(&self) -> Date {
        self.date
    }
    /// How the field's value is aligned within its own box.
    pub fn alignment(&self) -> crate::core::Alignment {
        self.alignment
    }

    /// Sets how the field's value is aligned within its own box.
    ///
    /// Horizontal only. A `top`/`bottom` alignment is **ignored**, because the value is centred
    /// vertically in the field by the field's own layout — the property route refuses it through
    /// [`crate::widget::capability::coercion::expect_horizontal_alignment`], and this setter
    /// matching that keeps the two entry points from disagreeing.
    pub fn set_alignment(&mut self, alignment: crate::core::Alignment) {
        if alignment.to_horizontal().is_none() || self.alignment == alignment {
            return;
        }
        self.alignment = alignment;
        self.base.request_redraw();
    }
    /// Returns the inclusive lower bound accepted by [`DateEdit::set_date`].
    ///
    /// Defaults to `1752-09-14`, the first date of the Gregorian calendar in
    /// this implementation's convention.
    pub fn minimum_date(&self) -> Date {
        self.minimum
    }
    /// Returns the inclusive upper bound accepted by [`DateEdit::set_date`].
    ///
    /// Defaults to `9999-12-31`.
    pub fn maximum_date(&self) -> Date {
        self.maximum
    }
    /// Returns the stored display-format pattern.
    ///
    /// The pattern is interpreted when the widget paints, through the shared
    /// `format_with_pattern_into` substituter. A pattern with no recognised token still paints
    /// the field's fixed `YYYY-MM-DD` spelling.
    pub fn display_format(&self) -> &str {
        &self.display_format
    }
    /// Returns whether the calendar affordance is enabled.
    ///
    /// Defaults to `false`. With it set, the field paints a 16 px arrow zone at its trailing
    /// edge; the month grid is painted only after the user opens it. See
    /// [`DateEdit::set_calendar_popup`] and [`DateEdit::calendar_open`].
    pub fn calendar_popup(&self) -> bool {
        self.calendar_popup
    }
    /// Returns whether the month grid is currently showing.
    pub fn calendar_open(&self) -> bool {
        self.calendar_open
    }
    /// Sets the current date, subject to validation and the accepted range.
    ///
    /// The assignment happens only when `date` satisfies [`Date::is_valid`],
    /// falls within `minimum ..= maximum` (both inclusive), and differs from the
    /// current date; otherwise the call is a no-op and the previous date is
    /// kept. Out-of-range input is therefore **rejected, not clamped**.
    ///
    /// # Side effects
    ///
    /// On a successful change, an undo entry is pushed (unless this call comes
    /// from [`DateEdit::undo`] / [`DateEdit::redo`]), `date_changed` is emitted
    /// with the new date, and a redraw is requested.
    pub fn set_date(&mut self, date: Date) {
        if date.is_valid() && date >= self.minimum && date <= self.maximum && self.date != date {
            let before = self.date;
            self.date = date;
            if !self.restoring_history {
                *self.history_target.borrow_mut() = self.date;
                self.undo_stack.push(Box::new(ValueCommand::new(
                    self.history_target.clone(),
                    before,
                    self.date,
                    "Edit date",
                    "date_edit",
                )));
            }
            self.date_changed.emit(date);
            self.base.request_redraw();
        }
    }
    /// Sets the inclusive lower bound for accepted dates.
    ///
    /// The current date is re-clamped into the new range, so raising the minimum
    /// moves a now-out-of-range value up to the boundary rather than leaving the
    /// widget holding a date below its own minimum.
    pub fn set_minimum_date(&mut self, date: Date) {
        if self.minimum == date {
            return;
        }
        self.minimum = date;
        // The embedded calendar mirrors the range, so it has to be pushed again (K-P02).
        self.calendar_sync_dirty = true;
        // Re-clamp the current value into the new range. Without this the widget could
        // hold a date below its own minimum, after which every `set_date` call silently
        // failed the range check — the value was stuck and the failure was invisible.
        self.clamp_to_range();
        self.base.request_redraw();
    }
    /// Sets the inclusive upper bound for accepted dates.
    ///
    /// The current date is clamped into the new range, so lowering the maximum moves
    /// a now-out-of-range value down to the boundary rather than leaving the widget
    /// holding a date it would itself reject.
    pub fn set_maximum_date(&mut self, date: Date) {
        if self.maximum == date {
            return;
        }
        self.maximum = date;
        self.calendar_sync_dirty = true;
        self.clamp_to_range();
        self.base.request_redraw();
    }
    /// Sets both ends of the accepted range in one call.
    ///
    /// The current date is clamped into the new range. `min` is not required to be
    /// less than or equal to `max`; if the two are inverted the minimum wins, so a
    /// caller that swaps its arguments gets a working widget pinned at `min` rather
    /// than one where every subsequent [`DateEdit::set_date`] silently fails.
    pub fn set_date_range(&mut self, min: Date, max: Date) {
        if self.minimum == min && self.maximum == max {
            return;
        }
        self.minimum = min;
        self.maximum = max;
        self.calendar_sync_dirty = true;
        self.clamp_to_range();
        self.base.request_redraw();
    }
    /// Moves the current date inside `minimum..=maximum` if it fell outside.
    ///
    /// Called by every bound setter so the invariant "the value is within the range"
    /// holds after any sequence of calls. The inverted-range rule lives in
    /// [`clamp_ordered_range`], shared with the sibling time widgets.
    fn clamp_to_range(&mut self) {
        self.date = super::clamp_ordered_range(self.date, self.minimum, self.maximum);
    }
    /// Stores the display-format pattern.
    ///
    /// The pattern is applied by the next paint; see [`DateEdit::display_format`] for the
    /// supported tokens.
    pub fn set_display_format(&mut self, fmt: String) {
        if self.display_format == fmt {
            return;
        }
        self.display_format = fmt;
        self.base.request_redraw();
    }
    /// Enables or disables the calendar affordance.
    ///
    /// With it set, [`Draw`] paints a 16 px arrow zone at the field's trailing edge. Pressing
    /// that zone opens the month grid — the **month grid for the current date's month** directly
    /// below the field: a row of day-of-week initials and six weeks of day cells, with the
    /// selected day marked. Cells outside the accepted range are drawn muted rather than hidden,
    /// so the reader can see *why* a day is not selectable.
    ///
    /// This used to be "purely stored state; changing it only triggers a redraw", which is
    /// exactly what it did -- a redraw of the same field. It is now the *affordance* flag rather
    /// than the open state: disabling it closes an open grid through
    /// [`DateEdit::set_calendar_open`].
    pub fn set_calendar_popup(&mut self, popup: bool) {
        if self.calendar_popup == popup {
            return;
        }
        self.calendar_popup = popup;
        if !popup {
            self.set_calendar_open(false);
        }
        self.base.request_redraw();
    }

    /// Shows or hides the month grid.
    ///
    /// Opening requires the affordance ([`DateEdit::calendar_popup`]) to be enabled: a grid that
    /// cannot be dismissed by the arrow it was opened with would be a popup with no control.
    /// The new state is announced through `popup_visibility_changed` so a host can close its
    /// other popups, and a redraw is requested.
    pub fn set_calendar_open(&mut self, open: bool) {
        let open = open && self.calendar_popup;
        if self.calendar_open == open {
            return;
        }
        if open {
            self.sync_calendar_open_state();
        }
        self.calendar_open = open;
        self.calendar_reveal.set_open(open);
        self.popup_visibility_changed.emit(open);
        if open {
            self.calendar_opened.emit();
        } else {
            self.calendar_closed.emit();
        }
        self.base.request_redraw();
    }

    /// Opens the calendar if it is closed, closes it if it is open.
    ///
    /// Does nothing while the affordance is disabled.
    pub fn toggle_calendar_popup(&mut self) {
        if self.calendar_popup {
            self.set_calendar_open(!self.calendar_open);
        }
    }

    /// The embedded calendar instance that draws the popup's month grid.
    pub fn calendar(&self) -> &Calendar {
        &self.calendar
    }

    /// Mutably borrows the embedded calendar.
    ///
    /// A caller that needs a calendar configured differently (a different date format, hidden
    /// week numbers, disabled dates) configures it here instead of the field re-deriving those
    /// facts. The field still owns the selected date: the next [`Self::open_calendar`] syncs the
    /// calendar's selection, range and display page from this field.
    pub fn calendar_mut(&mut self) -> &mut Calendar {
        &mut self.calendar
    }

    /// Replaces the embedded calendar instance.
    ///
    /// The instance is positioned and synchronised on the next open or draw, so a replacement
    /// does not have to know the field's geometry. Exposing the instance as a *method* rather
    /// than a property is deliberate: the property contract's `CapabilityValue` has no variant
    /// that can carry a widget, and pretending otherwise would publish a value no setter could
    /// accept.
    pub fn set_calendar(&mut self, mut calendar: Calendar) {
        calendar.set_first_day_of_week(self.calendar_first_day);
        self.calendar = calendar;
        self.calendar_sync_dirty = true;
        if self.calendar_open {
            self.sync_calendar_open_state();
        }
        self.base.request_redraw();
    }

    /// The first column of the popup's month grid.
    pub fn calendar_first_day(&self) -> Weekday {
        self.calendar_first_day
    }

    /// Sets the first column of the popup's month grid.
    pub fn set_calendar_first_day(&mut self, weekday: Weekday) {
        if self.calendar_first_day == weekday {
            return;
        }
        self.calendar_first_day = weekday;
        self.calendar.set_first_day_of_week(weekday);
        self.calendar_sync_dirty = true;
        self.base.request_redraw();
    }

    /// Opens the calendar popup.
    ///
    /// The embedded calendar is synchronised with this field first: its selected date, its
    /// accepted range, its first weekday and the displayed page all come from the field, so the
    /// grid a user sees is the field's own month rather than whatever the instance last showed.
    pub fn open_calendar(&mut self) {
        if !self.calendar_popup || self.calendar_open {
            return;
        }
        self.set_calendar_open(true);
    }

    /// Dismisses the calendar popup without changing the value.
    pub fn close_calendar(&mut self) {
        if self.calendar_open {
            self.set_calendar_open(false);
        }
    }

    /// Copies the field's date facts into the embedded calendar.
    ///
    /// Called when the popup opens (so the page, selection and range agree) and on every draw
    /// (so a range or first-weekday change made while the popup is open is reflected). The
    /// calendar's own display page is only overwritten on open: doing it on every draw would
    /// undo the user's month navigation.
    fn sync_calendar_open_state(&mut self) {
        let popup = calendar_popup_rect(self.geometry());
        self.calendar.set_geometry(popup);
        self.calendar.set_first_day_of_week(self.calendar_first_day);
        if let Some(minimum) = date_to_naive(self.minimum) {
            self.calendar.set_minimum_date(minimum);
        }
        if let Some(maximum) = date_to_naive(self.maximum) {
            self.calendar.set_maximum_date(maximum);
        }
        if let Some(date) = date_to_naive(self.date) {
            self.calendar.set_display_month(date);
            self.calendar.set_selected_date(date);
        }
        // The push above covered everything the flag tracks.
        self.calendar_sync_rect = popup;
        self.calendar_sync_dirty = false;
    }

    /// Keeps the embedded calendar's geometry and range in step without moving its page.
    fn sync_calendar_page(&mut self) {
        let popup = calendar_popup_rect(self.geometry());
        // Nothing that sync writes can have changed since the last push, so the event paths can
        // call this on every pointer move and key press for free (K-P02).
        if !self.calendar_sync_dirty && self.calendar_sync_rect == popup {
            return;
        }
        self.calendar.set_geometry(popup);
        if let Some(minimum) = date_to_naive(self.minimum) {
            self.calendar.set_minimum_date(minimum);
        }
        if let Some(maximum) = date_to_naive(self.maximum) {
            self.calendar.set_maximum_date(maximum);
        }
        self.calendar_sync_rect = popup;
        self.calendar_sync_dirty = false;
    }

    /// Takes the calendar's selected date as this field's value and dismisses the popup.
    fn commit_calendar_selection(&mut self) {
        let selected = naive_to_date(self.calendar.selected_date());
        if selected != self.date {
            self.set_date(selected);
        }
        self.close_calendar();
    }

    /// The section the user is editing, or `None` for whole-day editing.
    pub fn current_section(&self) -> Option<DateSection> {
        self.current_section
    }

    /// Selects the section Up/Down and typed digits apply to.
    ///
    /// `None` restores the historical whole-day behaviour. Changing the section clears
    /// the digit buffer, so digits typed for the year cannot leak into the day.
    pub fn set_current_section(&mut self, section: Option<DateSection>) {
        if self.current_section == section {
            return;
        }
        self.current_section = section;
        self.digit_buffer.clear();
        self.base.request_redraw();
    }

    /// The box one section occupies inside the value text.
    ///
    /// The three zones are equal thirds of the text run. A custom `display_format` can
    /// place the components in any order, and the control does not parse the pattern to
    /// recover their positions, so the zones are the documented approximation: the
    /// underline and the pointer target agree with each other, which is what a user
    /// needs, rather than disagreeing about a parsed layout.
    pub fn section_zone(&self, section: DateSection) -> Rect {
        let rect = self.geometry();
        let trailing = if self.calendar_popup { CALENDAR_ARROW_W } else { 0 }
            + if self.spin_buttons { 24 } else { 0 };
        let width = rect.width.saturating_sub(12 + trailing);
        let third = width / 3;
        let index = match section {
            DateSection::Year => 0,
            DateSection::Month => 1,
            DateSection::Day => 2,
        };
        Rect::new(rect.x + 6 + index * third as i32, rect.y, third, rect.height)
    }

    /// The section containing `pos`, when the point is on the value text.
    fn section_at(&self, pos: Point) -> Option<DateSection> {
        let rect = self.geometry();
        if !rect.contains_point(pos) {
            return None;
        }
        [DateSection::Year, DateSection::Month, DateSection::Day]
            .into_iter()
            .find(|&section| self.section_zone(section).contains_point(pos))
    }

    /// Steps the active section, or the whole day when no section is active.
    pub fn step_current_section(&mut self, delta: i32) {
        let Some(section) = self.current_section else {
            if delta >= 0 {
                self.step_up();
            } else {
                self.step_down();
            }
            return;
        };
        if delta == 0 {
            return;
        }
        let mut next = self.date;
        match section {
            DateSection::Year => {
                next.set_year(self.date.year() + delta);
            }
            DateSection::Month => {
                // Month stepping wraps across the year, which a plain clamp cannot
                // express: December + 1 is January of the next year, not December.
                let total = self.date.year() * 12 + self.date.month() as i32 - 1 + delta;
                next.set_year(total.div_euclid(12));
                next.set_month((total.rem_euclid(12) + 1) as u8);
            }
            DateSection::Day => {
                if delta >= 0 {
                    self.step_up();
                } else {
                    self.step_down();
                }
                return;
            }
        }
        self.set_date(next);
    }

    /// Types one digit into the active section.
    ///
    /// Returns `false` for a non-digit or when no section is active. The buffer keeps at
    /// most the section's digit capacity, so typing `2026` into the year and then `5`
    /// yields `0265` rather than a five-digit year.
    pub fn type_digit(&mut self, digit: char) -> bool {
        if !digit.is_ascii_digit() {
            return false;
        }
        let Some(section) = self.current_section else {
            return false;
        };
        self.digit_buffer.push(digit);
        while self.digit_buffer.len() > section.digit_capacity() {
            self.digit_buffer.remove(0);
        }
        let Ok(value) = self.digit_buffer.parse::<i32>() else {
            return false;
        };
        let mut next = self.date;
        match section {
            DateSection::Year => {
                if value < 1000 {
                    // A partial year is not a year yet: wait for four digits rather than
                    // jumping to year 2 as soon as the user presses `2`.
                    return true;
                }
                next.set_year(value);
            }
            DateSection::Month => next.set_month(value as u8),
            DateSection::Day => next.set_day(value as u8),
        }
        self.set_date(next);
        true
    }

    /// Whether the spin-button pair is painted at the trailing edge.
    pub fn spin_buttons(&self) -> bool {
        self.spin_buttons
    }

    /// Shows or hides the spin-button pair. Off by default, so the field keeps its
    /// historical pixels.
    pub fn set_spin_buttons(&mut self, visible: bool) {
        if self.spin_buttons == visible {
            return;
        }
        self.spin_buttons = visible;
        self.base.request_redraw();
    }

    /// The up and down spin buttons, when they are shown.
    pub fn spin_button_rects(&self) -> Option<(Rect, Rect)> {
        if !self.spin_buttons {
            return None;
        }
        let rect = self.geometry();
        let width = 24u32.min(rect.width);
        let x = rect.x + rect.width as i32
            - width as i32
            - if self.calendar_popup { CALENDAR_ARROW_W as i32 } else { 0 };
        let half = rect.height / 2;
        Some((
            Rect::new(x, rect.y, width, half),
            Rect::new(x, rect.y + half as i32, width, rect.height - half),
        ))
    }

    /// Text painted instead of the value when the date equals the minimum.
    pub fn special_value_text(&self) -> Option<&str> {
        self.special_value_text.as_deref()
    }

    /// Sets the special value text, or clears it with `None`.
    ///
    /// The text replaces the date only when the value is exactly `minimum_date`, which is
    /// the convention a spin box uses for its "unset" value. Off by default.
    pub fn set_special_value_text(&mut self, text: Option<String>) {
        if self.special_value_text == text {
            return;
        }
        self.special_value_text = text;
        self.base.request_redraw();
    }
    /// Advances the date by one day, rolling over month and year ends.
    ///
    /// The resulting date goes through [`DateEdit::set_date`], so stepping
    /// beyond [`DateEdit::maximum_date`] is rejected and leaves the date
    /// unchanged rather than wrapping around. A successful step is undoable.
    pub fn step_up(&mut self) {
        let mut d = self.date;
        let next_day = d.day() as i32 + 1;
        if next_day > d.days_in_month() as i32 {
            d.day = 1;
            let next_month = d.month() as i32 + 1;
            if next_month > 12 {
                d.month = 1;
                d.year += 1;
            } else {
                d.month = next_month as u8;
            }
        } else {
            d.day = next_day as u8;
        }
        self.set_date(d);
    }
    /// Moves the date back by one day, rolling over month and year starts.
    ///
    /// The month length used when wrapping is derived from the target month, so
    /// `2024-03-01` steps back to `2024-02-29`. The change is applied through
    /// [`DateEdit::set_date`], so going below [`DateEdit::minimum_date`] is
    /// rejected and leaves the date unchanged rather than wrapping around. A
    /// successful step is undoable.
    pub fn step_down(&mut self) {
        let mut d = self.date;
        if d.day() > 1 {
            d.set_day(d.day() - 1);
        } else {
            if d.month() > 1 {
                d.set_month(d.month() - 1);
            } else {
                d.set_month(12);
                d.set_year(d.year() - 1);
            }
            d.set_day(d.days_in_month());
        }
        self.set_date(d);
    }
    /// Reverts the most recent date change.
    ///
    /// Returns `true` if a change was undone, `false` when the undo stack is
    /// empty. Undoing emits `date_changed` with the restored date and requests a
    /// redraw, but does not push a new undo entry.
    pub fn undo(&mut self) -> bool {
        if self.undo_stack.undo().is_err() {
            return false;
        }
        self.restore_history_date();
        true
    }
    /// Re-applies the most recently undone date change.
    ///
    /// Returns `true` if a change was redone, `false` when there is nothing to
    /// redo. Like [`DateEdit::undo`], it emits `date_changed` and requests a
    /// redraw without recording a new undo entry.
    pub fn redo(&mut self) -> bool {
        if self.undo_stack.redo().is_err() {
            return false;
        }
        self.restore_history_date();
        true
    }
    /// Returns `true` when there is at least one date change to undo.
    pub fn can_undo(&self) -> bool {
        self.undo_stack.can_undo()
    }
    /// Returns `true` when there is at least one undone date change to redo.
    pub fn can_redo(&self) -> bool {
        self.undo_stack.can_redo()
    }
    fn restore_history_date(&mut self) {
        self.restoring_history = true;
        self.date = *self.history_target.borrow();
        self.restoring_history = false;
        self.date_changed.emit(self.date);
        self.base.request_redraw();
    }
}
impl Widget for DateEdit {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }

    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        crate::core::Size::new(
            dimensions::DATE_EDIT_DEFAULT_WIDTH,
            dimensions::DATE_EDIT_DEFAULT_HEIGHT,
        )
    }

    /// Advances the calendar popup's reveal; `true` while it owes frames.
    fn tick(&mut self, delta_ms: u32) -> bool {
        self.calendar_reveal.tick(delta_ms)
    }

    /// Whether the calendar popup is mid-reveal.
    fn is_animating(&self) -> bool {
        self.calendar_reveal.is_animating()
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
    /// Resolves a published event name to the control's own signal.
    ///
    /// # Why this is explicit
    ///
    /// `connect_event` validates a name against the capability table and registers a hub slot; only
    /// `event_signal_dyn` joins that name to the signal the control actually **emits**. Without an
    /// arm a published name is valid and inert, which is the silent failure
    /// `tools/check_event_signal_dyn.sh` exists to make impossible: the arm set is compared against
    /// the capability's published names, so the two cannot drift.
    ///
    /// # Payload mapping
    ///
    /// A hub name carries no value, so a `Signal1<T>` needs a conversion. The one used here is the
    /// same spelling the property side uses, so a designer reads one representation per kind: a
    /// number as `Int`, a float as `Float`, a flag as `Bool`, text as `String`, and a structured
    /// payload as its debug spelling. A `None` maps to `Null`, which is the same value an absent
    /// optional property uses — so "no selection" is distinguishable from "selection 0".
    fn event_signal_dyn(&self, name: &str) -> Option<crate::signal::EventSignalRef> {
        use crate::signal::EventSignalRef;
        match name {
            "date_changed" => {
                Some(EventSignalRef::mapped("date_changed", &self.date_changed, |v| {
                    CapabilityValue::String(format!("{v:?}"))
                }))
            }
            "popup_visibility_changed" => Some(EventSignalRef::mapped(
                "popup_visibility_changed",
                &self.popup_visibility_changed,
                |v| CapabilityValue::Bool(*v),
            )),
            "calendar_opened" => {
                Some(EventSignalRef::unit("calendar_opened", &self.calendar_opened))
            }
            "calendar_closed" => {
                Some(EventSignalRef::unit("calendar_closed", &self.calendar_closed))
            }
            "editing_finished" => {
                Some(EventSignalRef::unit("editing_finished", &self.editing_finished))
            }
            _ => None,
        }
    }
}

/// `DatePicker`'s property contract (the control is `DateEdit`; `DatePicker` is
/// a type alias for it, so this single impl covers both names).
///
/// Dates round-trip as strings: `date_to_string` on the way out and
/// `expect_date` on the way in, which validates the parsed calendar date so an
/// impossible date is rejected instead of silently stored.
impl WidgetProperties for DateEdit {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "date" => Ok(CapabilityValue::String(date_to_string(self.date()))),
            "minimum_date" => Ok(CapabilityValue::String(date_to_string(self.minimum_date()))),
            "maximum_date" => Ok(CapabilityValue::String(date_to_string(self.maximum_date()))),
            "display_format" => Ok(CapabilityValue::String(self.display_format().to_string())),
            "calendar_popup" => Ok(CapabilityValue::Bool(self.calendar_popup())),
            "calendar_first_day" => {
                Ok(CapabilityValue::String(weekday_to_str(self.calendar_first_day()).to_string()))
            }
            "alignment" => Ok(CapabilityValue::String(
                horizontal_alignment_to_str(self.alignment()).to_string(),
            )),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "date" => {
                self.set_date(expect_date(value)?);
                Ok(())
            }
            "minimum_date" => {
                self.set_minimum_date(expect_date(value)?);
                Ok(())
            }
            "maximum_date" => {
                self.set_maximum_date(expect_date(value)?);
                Ok(())
            }
            "display_format" => {
                self.set_display_format(expect_string(value)?);
                Ok(())
            }
            "calendar_popup" => {
                self.set_calendar_popup(expect_bool(value)?);
                Ok(())
            }
            "calendar_first_day" => {
                self.set_calendar_first_day(expect_weekday(value)?);
                Ok(())
            }
            "alignment" => {
                self.set_alignment(expect_horizontal_alignment(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of![
            "date",
            "minimum_date",
            "maximum_date",
            "display_format",
            "calendar_popup",
            "calendar_first_day",
            "alignment",
            BASE_PROPERTY_NAMES
        ]
    }
}

impl EventHandler for DateEdit {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
        if !self.base.is_enabled() {
            return;
        }
        // Pointer tracking inside the open popup belongs to the embedded calendar: it owns the
        // hovered-day state and the page after a navigation click.
        if self.calendar_open && matches!(event, Event::MouseMove { .. } | Event::MouseLeave { .. })
        {
            self.sync_calendar_page();
            self.calendar.handle_event(event);
        }
        match event {
            Event::MousePress { pos, button, .. } if *button == 1 => {
                let field = self.geometry();
                // Spin buttons sit inside the field's trailing edge and take precedence
                // over the value zones underneath them.
                if let Some((up, down)) = self.spin_button_rects() {
                    if up.contains_point(*pos) {
                        self.step_current_section(1);
                        return;
                    }
                    if down.contains_point(*pos) {
                        self.step_current_section(-1);
                        return;
                    }
                }
                // The arrow comes first: it is drawn inside the field's own box, so a press
                // there would otherwise be indistinguishable from a press on the value.
                if self.calendar_popup && calendar_arrow_rect(field).contains_point(*pos) {
                    self.toggle_calendar_popup();
                } else if self.calendar_open {
                    // The popup is the embedded calendar's own rectangle; a press inside it is
                    // forwarded there, so the day that is hit-tested is the day that was painted.
                    let popup = calendar_popup_rect(field);
                    if popup.contains_point(*pos) {
                        self.sync_calendar_page();
                        let before = self.calendar.selected_date();
                        self.calendar.handle_event(event);
                        let after = self.calendar.selected_date();
                        if after != before {
                            // A day click commits the value and finishes the interaction, which
                            // is what the previous self-drawn grid did.
                            self.set_date(naive_to_date(after));
                            self.close_calendar();
                        }
                    } else {
                        // A press anywhere else dismisses the popup rather than editing a
                        // section hidden underneath it.
                        self.close_calendar();
                    }
                } else if let Some(section) = self.section_at(*pos) {
                    self.set_current_section(Some(section));
                }
            }
            Event::MouseDoubleClick { pos, .. } if self.calendar_open => {
                if calendar_popup_rect(self.geometry()).contains_point(*pos) {
                    self.sync_calendar_page();
                    self.calendar.handle_event(event);
                    self.commit_calendar_selection();
                }
            }
            Event::Wheel { delta, .. } => {
                // A notched wheel steps the value; the direction follows the sign.
                if delta.y > 0 {
                    self.step_current_section(1);
                } else if delta.y < 0 {
                    self.step_current_section(-1);
                }
            }
            Event::KeyPress { key, .. } if self.calendar_open => {
                // Escape closes the popup before any value navigation runs. Every other key
                // belongs to the embedded calendar while it is open: arrows move its selection,
                // Page Up/Down move its page, and Enter/Space commit.
                if *key == 27 {
                    self.close_calendar();
                } else {
                    self.sync_calendar_page();
                    self.calendar.handle_event(event);
                    if *key == 13 || *key == 32 {
                        self.commit_calendar_selection();
                    }
                }
            }
            Event::KeyPress { key, modifiers } => match *key {
                // Escape closes an open grid first, before any value navigation runs.
                27 if self.calendar_open => self.set_calendar_open(false),
                // Enter commits the edit. The open-popup path above commits a day selection and
                // returns before reaching here, so this is the field-focused case.
                13 => self.editing_finished.emit(),
                // Undo and redo are the platform primary chord: Control+Z/Y on
                // Windows and Linux, Command+Z/Y on macOS. A shifted chord is a
                // different binding and stays unbound here.
                _ if primary_shortcut_pressed(*key, *modifiers, Key::Z) => {
                    let _ = self.undo();
                }
                _ if primary_shortcut_pressed(*key, *modifiers, Key::Y) => {
                    let _ = self.redo();
                }
                37 => {
                    // Left moves to the previous section once one is active; with no
                    // section the historical no-op is kept.
                    if let Some(section) = self.current_section {
                        let previous = section.previous();
                        self.set_current_section(Some(previous));
                    }
                }
                39 => {
                    if let Some(section) = self.current_section {
                        let next = section.next();
                        self.set_current_section(Some(next));
                    }
                }
                38 => self.step_current_section(1),  // Up arrow
                40 => self.step_current_section(-1), // Down arrow
                48..=57 if self.current_section.is_some() => {
                    if let Some(digit) = char::from_u32(*key) {
                        self.type_digit(digit);
                    }
                }
                _ => { /* Other keys are not relevant */ }
            },
            // Focus leaving the field ends the edit, the same rule `DateTimeEdit` uses. The
            // base has already recorded the focus loss; this only announces the semantic fact.
            Event::FocusLost => self.editing_finished.emit(),
            _ => { /* Other events are not relevant */ }
        }
    }
}
impl Draw for DateEdit {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.geometry();

        // Chrome colours resolve explicit style first, then the theme's resolved style
        // for this control, and only then fall back to a literal. Without the theme step
        // a light/dark switch changed nothing on screen: the field, its border and its
        // text were all hardcoded, which the rendering census reported as theme-blind.
        //
        // The style lookups are the cached, revision-validated forms: `resolved_theme_style_shared`
        // is a refcount bump on a hit and `palette_shared` answers both colours this draw needs in
        // one read, so neither takes the manager lock (K-P03/K-P17). `date_edit` classifies as
        // `Input`, whose resolved style supplies `text_color` and `border_color` but no
        // `background_color` (ThemeRole::Input resolves that to `None`), so the interior is derived
        // below from the theme's own background rather than left unset.
        let style = self.base.style();
        let theme = crate::style::resolved_theme_style_shared("date_edit");
        let (window_fill, foreground) = match crate::style::palette_shared() {
            Some(colors) => (colors.background, colors.foreground),
            None => (Color::rgb(240, 240, 240), Color::BLACK),
        };

        let ink = style
            .text_color
            .or_else(|| theme.as_ref().and_then(|t| t.text_color))
            .unwrap_or(foreground);
        // An editable field's interior: one step from the window fill toward the text
        // colour, so it reads as a field on a light theme and on a dark one, and is never
        // byte-identical to the window behind it. That identity is the defect the census
        // reports as "painted in the background's own colour".
        let field = window_fill.blend(&ink, 0.08);
        // The filter is on the **resolved** value, not only on the theme's: the active
        // theme is applied to every control before it is drawn, so `style.background_color`
        // already holds the resolved fill and letting it through unfiltered is exactly the
        // invisible-field defect this guards against. A caller's own colour still wins.
        let surface = match style.background_color {
            Some(resolved) if resolved != window_fill => resolved,
            _ => field,
        };
        let border = style
            .border_color
            .or_else(|| theme.as_ref().and_then(|t| t.border_color))
            .filter(|resolved| *resolved != surface)
            .unwrap_or_else(|| surface.blend(&ink, 0.35));

        context.face_with_gradient(
            rect,
            surface,
            self.style().background_gradient.as_ref(),
            self.style().surface.unwrap_or_default(),
            self.style().border_radius.unwrap_or(0),
            Color::BLACK,
        );
        // Rounded to the face's radius: a square outline left the four corners unpainted.
        crate::widget::draw::stroke_surface_border(
            context,
            rect,
            self.style().border_radius.unwrap_or(0),
            border,
            1,
        );
        // The value is spelled by the caller's `display_format` when that pattern is one this control
        // can render, and by `Date`'s own `YYYY-MM-DD` otherwise. The fallback is what keeps an
        // unrecognised pattern showing the value rather than the pattern's literal words. Into the
        // buffer directly: the allocating wrapper built the result plus one string per token.
        let mut text = String::new();
        let special = self.special_value_text.as_deref().filter(|_| self.date == self.minimum);
        if let Some(special) = special {
            text.push_str(special);
        } else if !super::date_edit::format_with_pattern_into(
            &self.display_format,
            super::date_edit::DateTimeComponents {
                year: Some(self.date.year()),
                month: Some(self.date.month()),
                day: Some(self.date.day()),
                ..Default::default()
            },
            &mut text,
        ) {
            text.clear();
            let _ = write!(text, "{}", self.date);
        }
        // Vertically centred through the shared primitive: `rect.y + height / 2` puts the
        // glyph box's top edge on the field's middle line, so the value sat half a line low.
        // The line box is also what a caller reading this field's text position would need,
        // so deriving it here keeps the two from drifting.
        // The **effective font** — the resolved theme/caller font — so the value honours the theme
        // body font and the user's text scale (D09-STYLE-01).
        let font = effective_font(style);
        let line = context.text_line(rect, font);
        // The arrow zone is part of the field's chrome, so the value must not run under it:
        // the text box's trailing edge stops where the affordance begins.
        let text_width = rect
            .width
            .saturating_sub(12)
            .saturating_sub(if self.calendar_popup { CALENDAR_ARROW_W } else { 0 })
            .saturating_sub(if self.spin_buttons { 24 } else { 0 });
        context.draw_text_fitted_cow(
            Rect { x: rect.x + 6, y: line.y, width: text_width, height: line.height },
            text.as_str(),
            font,
            ink,
            self.alignment.to_horizontal().unwrap_or(HorizontalAlignment::Left),
        );

        // The active section is marked with a rule under its zone, so the user can see
        // which digits the arrow keys will step. Only an active section paints it.
        if let Some(section) = self.current_section {
            let zone = self.section_zone(section);
            let y = line.y + line.height as i32;
            context.draw_line(
                Point::new(zone.x + 2, y),
                Point::new(zone.x + zone.width as i32 - 2, y),
                ink,
            );
        }

        if self.calendar_popup {
            draw_calendar_arrow(context, rect, ink);
        }
        if let Some((up, down)) = self.spin_button_rects() {
            let fill = surface.blend(&ink, 0.08);
            context.fill_rect(up, fill);
            context.fill_rect(down, fill);
            context.draw_rect(up, border);
            context.draw_rect(down, border);
            let side = up.width.min(up.height).min(10);
            crate::widget::draw_icon_centered(
                context,
                up,
                side,
                ink,
                crate::widget::IconName::ChevronUp,
            );
            crate::widget::draw_icon_centered(
                context,
                down,
                side,
                ink,
                crate::widget::IconName::ChevronDown,
            );
        }
        if self.calendar_open || !self.calendar_reveal.is_closed() {
            let popup = calendar_popup_rect(rect);
            let revealed = self.calendar_reveal.revealed(
                popup,
                crate::widget::menu_toolbar::popup_reveal::RevealDirection::Down,
                crate::widget::menu_toolbar::popup_reveal::PopupReveal::travel_cap_for(Size::new(
                    popup.width,
                    popup.height,
                )),
            );
            let clipped = !self.calendar_reveal.is_closed();
            if clipped {
                context.push_clip(revealed.x, revealed.y, revealed.width, revealed.height);
            }
            // One month-grid implementation: the embedded calendar paints the popup. Its
            // geometry and accepted range are reasserted here only when one of them actually
            // changed (K-P02) — the calendar's own page and selection are left alone so its
            // navigation survives across frames.
            self.sync_calendar_page();
            self.calendar.draw(context);
            if clipped {
                context.pop_clip();
            }
        }
    }
}

/// The popup's width, in pixels, for the embedded calendar.
const CALENDAR_POPUP_W: u32 = 224;
/// The popup's height: navigation bar, weekday header and a six-week grid.
const CALENDAR_POPUP_H: u32 = 210;
/// The space between the field and the popup it opens.
const POPUP_GAP: i32 = 4;

/// Width of the arrow affordance zone at the field's trailing edge.
pub(crate) const CALENDAR_ARROW_W: u32 = 16;

/// The arrow zone at the field's trailing edge.
///
/// One derivation, read by both the draw pass and the press path, so the chevron a user sees
/// is the chevron a user can click.
pub(crate) fn calendar_arrow_rect(field: Rect) -> Rect {
    Rect::new(field.right() - CALENDAR_ARROW_W as i32, field.y, CALENDAR_ARROW_W, field.height)
}

/// Paints the chevron that tells the user the field opens a calendar.
pub(crate) fn draw_calendar_arrow(context: &mut RenderContext, field: Rect, color: Color) {
    let zone = calendar_arrow_rect(field);
    // Below this size a chevron is two strokes in a smear; the zone stays clickable, but
    // painting it would add noise rather than an affordance.
    if zone.width < 8 || zone.height < 8 {
        return;
    }
    let cx = zone.x + zone.width as i32 / 2;
    let cy = zone.y + zone.height as i32 / 2;
    let half_w = 4;
    let rise = 2;
    context.draw_line(Point::new(cx - half_w, cy - rise), Point::new(cx, cy + rise), color);
    context.draw_line(Point::new(cx, cy + rise), Point::new(cx + half_w, cy - rise), color);
}

/// The plate the embedded calendar occupies, below `field`.
///
/// The draw pass and the press path both read this rectangle, so the popup a user clicks is the
/// popup that was painted. The size is the calendar's own natural size rather than a grid of
/// fixed cells: the calendar lays its navigation bar, weekday header and six-week grid out inside
/// whatever rectangle it is given.
pub(crate) fn calendar_popup_rect(field: Rect) -> Rect {
    Rect::new(
        field.x,
        field.y + field.height as i32 + POPUP_GAP,
        CALENDAR_POPUP_W.max(field.width),
        CALENDAR_POPUP_H,
    )
}

/// Converts the field's [`Date`] into a calendar date.
///
/// `None` for a combination the Gregorian calendar does not have; [`DateEdit::set_date`] refuses
/// those values, so the conversion only fails for a value that was never accepted.
pub(crate) fn date_to_naive(date: Date) -> Option<NaiveDate> {
    NaiveDate::from_ymd_opt(date.year(), date.month() as u32, date.day() as u32)
}

/// Converts a calendar date into the field's [`Date`].
pub(crate) fn naive_to_date(date: NaiveDate) -> Date {
    Date::new(date.year(), date.month() as u8, date.day() as u8)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::Point;
    use crate::widget::input_widgets::shortcut_editor::{
        non_primary_modifier_event_bits, primary_modifier_event_bits,
    };
    use std::sync::{Arc, Mutex};

    // ─── Date helper tests ───────────────────────────────────────

    #[test]
    fn date_creation_and_accessors() {
        let d = Date::new(2026, 6, 8);
        assert_eq!(d.year(), 2026);
        assert_eq!(d.month(), 6);
        assert_eq!(d.day(), 8);
    }

    #[test]
    fn date_clamps_to_valid_ranges() {
        // Date::new no longer clamps; is_valid() checks bounds
        let d = Date::new(2024, 13, 32);
        assert_eq!(d.month(), 13);
        assert_eq!(d.day(), 32);
        assert!(!d.is_valid());
    }

    #[test]
    fn date_is_leap_year() {
        assert!(Date::new(2024, 1, 1).is_leap_year());
        assert!(Date::new(2000, 1, 1).is_leap_year());
        assert!(!Date::new(2023, 1, 1).is_leap_year());
        assert!(!Date::new(1900, 1, 1).is_leap_year());
    }

    #[test]
    fn date_days_in_month() {
        let jan = Date::new(2026, 1, 1);
        assert_eq!(jan.days_in_month(), 31);

        let feb_normal = Date::new(2023, 2, 1); // not leap
        assert_eq!(feb_normal.days_in_month(), 28);

        let feb_leap = Date::new(2024, 2, 1); // leap
        assert_eq!(feb_leap.days_in_month(), 29);

        let apr = Date::new(2026, 4, 1);
        assert_eq!(apr.days_in_month(), 30);
    }

    #[test]
    fn date_is_valid() {
        assert!(Date::new(2026, 6, 8).is_valid());
        assert!(Date::new(2024, 2, 29).is_valid()); // leap
        assert!(!Date::new(2023, 2, 29).is_valid()); // not leap
        assert!(!Date::new(2026, 0, 1).is_valid()); // month 0
        assert!(!Date::new(2026, 13, 1).is_valid()); // month 13
        assert!(!Date::new(2026, 1, 0).is_valid()); // day 0
        assert!(!Date::new(2026, 4, 31).is_valid()); // April has 30 days
    }

    #[test]
    fn date_setters_modify_correctly() {
        let mut d = Date::new(2026, 6, 8);
        d.set_year(2027);
        assert_eq!(d.year(), 2027);

        d.set_month(12);
        assert_eq!(d.month(), 12);

        d.set_day(25);
        assert_eq!(d.day(), 25);
    }

    #[test]
    fn date_setters_clamp_values() {
        let mut d = Date::new(2026, 6, 8);
        d.set_month(0);
        assert_eq!(d.month(), 1);
        d.set_month(13);
        assert_eq!(d.month(), 12);
        d.set_day(0);
        assert_eq!(d.day(), 1);
        d.set_day(32);
        assert_eq!(d.day(), 31);
    }

    #[test]
    fn date_display_format() {
        let d = Date::new(2026, 6, 8);
        assert_eq!(d.to_string(), "2026-06-08");

        let d2 = Date::new(2024, 12, 25);
        assert_eq!(d2.to_string(), "2024-12-25");
    }

    #[test]
    fn date_ordering() {
        let earlier = Date::new(2024, 1, 1);
        let later = Date::new(2026, 6, 8);
        assert!(earlier < later);
        assert!(later > earlier);
        assert_eq!(earlier, Date::new(2024, 1, 1));
    }

    #[test]
    fn date_today() {
        let today = Date::today();
        assert_eq!(today.year(), 2024);
        assert_eq!(today.month(), 1);
        assert_eq!(today.day(), 1);
    }

    // ─── DateEdit widget tests ───────────────────────────────────

    #[test]
    fn date_edit_creation_defaults() {
        let editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        assert_eq!(editor.date(), Date::today());
        assert_eq!(editor.display_format(), "yyyy-MM-dd");
        assert!(!editor.calendar_popup());
        assert!(editor.is_visible());
        assert!(editor.is_enabled());
    }

    #[test]
    fn date_edit_set_date() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        let d = Date::new(2026, 12, 25);
        editor.set_date(d);
        assert_eq!(editor.date(), d);
    }

    #[test]
    fn date_edit_set_date_clamps_to_range() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        // DateEdit default minimum is 1752-09-14, so 1700 is out of range
        let before_min = Date::new(1700, 1, 1);
        editor.set_date(before_min);
        assert_eq!(editor.date(), Date::today()); // Should stay as today
    }

    #[test]
    fn date_edit_set_date_clamps_to_maximum() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        // DateEdit default maximum is 9999-12-31, so 10000 is out of range
        let after_max = Date::new(10000, 1, 1);
        editor.set_date(after_max);
        assert_eq!(editor.date(), Date::today()); // Should stay as today
    }

    #[test]
    fn date_edit_set_date_range() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        let min = Date::new(2020, 1, 1);
        let max = Date::new(2030, 12, 31);
        editor.set_date_range(min, max);
        assert_eq!(editor.minimum_date(), min);
        assert_eq!(editor.maximum_date(), max);
    }

    #[test]
    fn date_edit_set_display_format() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        editor.set_display_format("dd/MM/yyyy".to_string());
        assert_eq!(editor.display_format(), "dd/MM/yyyy");
    }

    /// The `display_format` pattern is **applied**, not merely stored.
    ///
    /// # The defect this pins
    ///
    /// `display_format` was stored, round-tripped through the property contract and documented as
    /// "stored and round-tripped, not yet applied when painting" -- which was honest, and was still a
    /// gap: a host that set `dd/MM/yyyy` got `2026-06-08`. The assertion reads the **document**, since
    /// a model-only check (set then get) passes on the old code.
    ///
    /// Two halves: the requested pattern must lay its own ink, and the default must be unchanged.
    /// The second is what makes this "the pattern works" rather than "the field got longer".
    #[test]
    fn the_display_format_pattern_is_applied_to_the_painted_value() {
        use crate::widget::svg::{render_to_svg, text_subpath_count};
        let _theme_guard = crate::style::theme_test_guard();

        let make = |format: &str| {
            let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
            editor.set_date(Date::new(2026, 6, 8));
            editor.set_display_format(format.to_string());
            editor
        };

        // The default pattern spells the same seventeen characters as `Date`'s own Display, so it must
        // produce exactly the ink it always did -- which is why the snapshots are unchanged.
        let mut plain = make("yyyy-MM-dd");
        let plain_svg = render_to_svg(&mut plain);
        let mut explicit = make("yyyy-MM-dd");
        assert_eq!(
            render_to_svg(&mut explicit),
            plain_svg,
            "the default pattern must reproduce the pre-pattern spelling"
        );

        // A reordered pattern must **move** the ink: a pattern that did nothing would produce a
        // byte-identical file. And the only difference between the two spellings is the order, so the
        // *number of glyph runs* (one per set bitmap bit) is close but not equal -- `08-06-2026` and
        // `2026-06-08` contain the same characters in a different order, and `font8x8`'s glyphs have
        // different bit counts. An earlier version of this test compared the counts for equality and
        // failed by 14 pixels, which measurement says is the glyph-set difference and not a lost field.
        // The field-preservation claim is therefore made where it can be made exactly: on the
        // substituter's own output, one test above.
        let mut reordered = make("dd/MM/yyyy");
        let reordered_svg = render_to_svg(&mut reordered);
        assert_ne!(
            reordered_svg, plain_svg,
            "a reordered pattern must move the ink, or the pattern was ignored"
        );
        // Same magnitude, so no field was duplicated or dropped. The band is a fifth of the total,
        // which is far tighter than a wrong pattern could pass and far looser than the glyph-set
        // difference measured here (14 of 246).
        let (a, b) = (text_subpath_count(&reordered_svg), text_subpath_count(&plain_svg));
        assert!(
            a.abs_diff(b) < b / 5,
            "both spell the same date, so neither may gain or lose a field: reordered={a} plain={b}"
        );

        // A pattern with no usable token falls back to the fixed spelling rather than printing its
        // own literal words -- a field reading \"today\" would be worse than one ignoring the pattern.
        let mut nonsense = make("today");
        assert_eq!(
            render_to_svg(&mut nonsense),
            plain_svg,
            "an unrecognised pattern must fall back to the value, not print the pattern"
        );
    }

    /// The substituter's token table, longest-first, and its literal pass-through.
    ///
    /// The ordering is the whole of the correctness here: a scan that tried `M` before `MM` would turn
    /// `MM` into two months and `yyyy` into four years, and both would still look like a date.
    #[test]
    fn the_pattern_substituter_prefers_the_longest_token() {
        let c = DateTimeComponents {
            year: Some(2026),
            month: Some(6),
            day: Some(8),
            hour: Some(9),
            minute: Some(5),
            second: Some(7),
            millisecond: Some(42),
        };
        let render = |pattern: &str| format_with_pattern(pattern, c);

        assert_eq!(render("yyyy-MM-dd"), Some("2026-06-08".to_string()));
        assert_eq!(render("dd/MM/yyyy"), Some("08/06/2026".to_string()));
        // A single letter is unpadded, which is what makes `M` different from `MM`.
        assert_eq!(render("d/M/yyyy"), Some("8/6/2026".to_string()));
        assert_eq!(render("HH:mm:ss"), Some("09:05:07".to_string()));
        assert_eq!(render("H:mm"), Some("9:05".to_string()));
        assert_eq!(render("SSS"), Some("042".to_string()));
        assert_eq!(render("yy"), Some("26".to_string()));
        // Literal text survives around the tokens.
        assert_eq!(render("Today: yyyy"), Some("Today: 2026".to_string()));
        // A component the caller did not supply is dropped, not invented.
        let date_only = DateTimeComponents { year: Some(2026), ..Default::default() };
        assert_eq!(format_with_pattern("yyyy HH", date_only), Some("2026 ".to_string()));
        // And a pattern with nothing usable reports that, so the caller can fall back.
        assert_eq!(render("nope"), None);
        assert_eq!(render(""), None);
    }

    #[test]
    fn date_edit_set_calendar_popup() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        assert!(!editor.calendar_popup());
        editor.set_calendar_popup(true);
        assert!(editor.calendar_popup());
    }

    /// `weekday()` agrees with known dates and is always in `0..=6`.
    ///
    /// # The defect this pins
    ///
    /// `Date` had no weekday at all, so a month grid could not be laid out: the first week of a
    /// month starts at the column of its first day, and that column *is* a weekday. The anchors are
    /// real calendar dates with externally-known weekdays, and the leap/century cases are included
    /// because a formula that drops either returns a plausible wrong answer rather than failing.
    #[test]
    fn weekday_agrees_with_known_dates() {
        // 0 = Sunday.
        assert_eq!(Date::new(2026, 6, 8).weekday(), 1, "2026-06-08 is a Monday");
        assert_eq!(Date::new(2000, 1, 1).weekday(), 6, "2000-01-01 is a Saturday");
        assert_eq!(Date::new(2024, 2, 29).weekday(), 4, "2024-02-29 is a Thursday");
        assert_eq!(Date::new(1900, 1, 1).weekday(), 1, "1900-01-01 is a Monday");
        assert_eq!(Date::new(2024, 3, 1).weekday(), 5, "2024-03-01 is a Friday");
        assert_eq!(Date::new(1752, 9, 14).weekday(), 4, "the accepted floor is a Thursday");
        // Every date in a run of consecutive days lands in `0..=6`, and consecutive days advance by
        // exactly one -- which a formula with a wrong constant would break without failing the
        // anchors above. The run crosses a month end and a leap day on purpose.
        let mut date = Date::new(2024, 2, 26);
        let mut expected = 1; // 2024-02-26 is a Monday
        for _ in 0..8 {
            assert_eq!(date.weekday(), expected, "{date}");
            expected = (expected + 1) % 7;
            date = next_day(date);
        }
    }

    /// The next calendar day, by the real month lengths rather than by arithmetic on the day field.
    fn next_day(mut date: Date) -> Date {
        if date.day < date.days_in_month() {
            date.day += 1;
            return date;
        }
        date.day = 1;
        if date.month < 12 {
            date.month += 1;
        } else {
            date.month = 1;
            date.year += 1;
        }
        date
    }

    /// The calendar popup is **painted**, not merely stored.
    ///
    /// # The defect this pins
    ///
    /// `calendar_popup` was a stored boolean that `draw` never read: the getter, the setter, the
    /// schema row and the round-trip test all existed, and setting it changed nothing on screen. A
    /// model-only assertion (`assert!(editor.calendar_popup())`) passes on that code, which is why
    /// this one reads the **document**: the popup must add ink, and it must add the *days of the
    /// month* -- not just any ink, which is what "the documents differ" alone would accept.
    #[test]
    fn the_calendar_popup_is_actually_painted() {
        use crate::widget::svg::{render_to_svg, text_subpath_count};
        let _theme_guard = crate::style::theme_test_guard();

        let make = |popup: bool| {
            let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
            editor.set_date(Date::new(2026, 6, 8));
            editor.set_calendar_popup(popup);
            if popup {
                editor.set_calendar_open(true);
            }
            editor
        };

        let mut closed = make(false);
        let closed_svg = render_to_svg(&mut closed);
        let mut open = make(true);
        let open_svg = render_to_svg(&mut open);

        assert_ne!(closed_svg, open_svg, "opening the popup must change the picture");
        // The grid is seven weekday initials plus the days of the month. Six weeks of 31-day
        // coverage needs at least the 31 day numbers, so the ink goes up by far more than one glyph
        // run -- and the date field alone contributes exactly one run (`2026-06-08`).
        let closed_ink = text_subpath_count(&closed_svg);
        let open_ink = text_subpath_count(&open_svg);
        assert!(
            open_ink > closed_ink * 4,
            "the popup must paint the grid and the month's days: closed={closed_ink} open={open_ink}"
        );
        // And the popup's plate is a rectangle below the field, which is what makes it a popup
        // rather than extra glyphs floating on the page.
        assert!(
            open_svg.matches("<rect").count() > closed_svg.matches("<rect").count(),
            "the popup paints its own plate: {open_svg}"
        );
    }

    /// The affordance flag alone must not paint the grid.
    ///
    /// `calendar_popup` is what makes the picker reachable, not what makes it visible: the grid is
    /// the *open* state. This pins the distinction by counting the document's glyph runs, which is
    /// the property-only-a-grid-adds signal — the arrow is drawn with line commands, not text.
    #[test]
    fn calendar_popup_alone_does_not_paint_the_grid() {
        use crate::widget::svg::{render_to_svg, text_subpath_count};
        let _theme_guard = crate::style::theme_test_guard();

        let mut plain = DateEdit::new(Rect::new(0, 0, 200, 30));
        plain.set_date(Date::new(2026, 6, 8));
        let mut affordance = DateEdit::new(Rect::new(0, 0, 200, 30));
        affordance.set_date(Date::new(2026, 6, 8));
        affordance.set_calendar_popup(true);

        assert!(!affordance.calendar_open(), "the flag alone must not open the grid");
        let plain_svg = render_to_svg(&mut plain);
        let affordance_svg = render_to_svg(&mut affordance);
        assert_ne!(plain_svg, affordance_svg, "the arrow affordance itself must be painted");
        assert_eq!(
            text_subpath_count(&affordance_svg),
            text_subpath_count(&plain_svg),
            "no weekday/day runs may appear until the grid is open"
        );
    }

    /// Clicking the arrow opens the grid and announces the new state.
    #[test]
    fn arrow_click_emits_popup_visibility_changed_and_paints_the_grid() {
        use crate::widget::svg::{render_to_svg, text_subpath_count};
        let _theme_guard = crate::style::theme_test_guard();

        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        editor.set_date(Date::new(2026, 6, 8));
        editor.set_calendar_popup(true);

        let seen = Arc::new(Mutex::new(Vec::<bool>::new()));
        let sink = Arc::clone(&seen);
        editor.popup_visibility_changed.connect(move |open| {
            if let Ok(mut v) = sink.lock() {
                v.push(*open);
            }
        });

        let closed_svg = render_to_svg(&mut editor);
        let arrow = calendar_arrow_rect(editor.geometry()).center();
        editor.handle_event(&Event::mouse_press(arrow.x, arrow.y, 1));

        assert!(editor.calendar_open(), "the arrow press must open the grid");
        assert_eq!(*seen.lock().expect("visibility lock"), vec![true]);
        let open_svg = render_to_svg(&mut editor);
        assert!(
            text_subpath_count(&open_svg) > text_subpath_count(&closed_svg) * 4,
            "the open grid must add the month's day runs"
        );
    }

    /// The centre of a day cell in the embedded calendar, derived from the calendar's documented
    /// layout (30 px navigation bar, 24 px weekday header, six rows) and the popup rectangle both
    /// the draw pass and the hit test use. Test-only: it exists so a click can name a day without
    /// reaching into `Calendar`'s private hit test.
    fn calendar_day_center(editor: &DateEdit, day: u32) -> Point {
        let popup = calendar_popup_rect(editor.geometry());
        let nav_h = 30_i32;
        let header_h = 24_i32;
        let grid_y = popup.y + nav_h + header_h;
        let grid_h = popup.height as i32 - nav_h - header_h;
        let cell_w = (popup.width / 7).max(1) as i32;
        let cell_h = (grid_h / 6).max(1);
        let date = editor.date();
        let first = NaiveDate::from_ymd_opt(date.year(), date.month() as u32, 1)
            .expect("the field's month always has a first day");
        let slot = first.weekday().num_days_from_sunday() + day - 1;
        Point::new(
            popup.x + (slot % 7) as i32 * cell_w + cell_w / 2,
            grid_y + (slot / 7) as i32 * cell_h + cell_h / 2,
        )
    }

    /// Choosing a day writes it through `set_date` and dismisses the grid.
    #[test]
    fn selecting_a_day_updates_the_date_and_closes_the_popup() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        editor.set_date(Date::new(2026, 6, 8));
        editor.set_calendar_popup(true);
        editor.set_calendar_open(true);

        let cell = calendar_day_center(&editor, 15);
        editor.handle_event(&Event::mouse_press(cell.x, cell.y, 1));

        assert_eq!(editor.date(), Date::new(2026, 6, 15));
        assert!(!editor.calendar_open(), "picking a day finishes the interaction");
    }

    /// The popup is the embedded `Calendar`: opening syncs its value/range/page, and the two new
    /// signals bracket the open state alongside the historical visibility signal.
    #[test]
    fn calendar_open_and_close_signals_bracket_the_embedded_calendar() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        editor.set_date(Date::new(2026, 6, 8));
        editor.set_calendar_popup(true);

        let opened = Arc::new(Mutex::new(0_usize));
        let closed = Arc::new(Mutex::new(0_usize));
        let opened_sink = Arc::clone(&opened);
        let closed_sink = Arc::clone(&closed);
        editor.calendar_opened.connect(move || {
            if let Ok(mut count) = opened_sink.lock() {
                *count += 1;
            }
        });
        editor.calendar_closed.connect(move || {
            if let Ok(mut count) = closed_sink.lock() {
                *count += 1;
            }
        });

        editor.open_calendar();
        assert!(editor.calendar_open());
        assert_eq!(editor.calendar().selected_date(), NaiveDate::from_ymd_opt(2026, 6, 8).unwrap());
        assert_eq!(
            editor.calendar().first_day_of_week(),
            Weekday::Sun,
            "the popup keeps the grid's historical Sunday-first columns"
        );

        editor.close_calendar();
        assert!(!editor.calendar_open());
        assert_eq!(*opened.lock().expect("opened lock"), 1);
        assert_eq!(*closed.lock().expect("closed lock"), 1);
    }

    /// `calendar_first_day` is a real property: the write reaches the embedded calendar.
    #[test]
    fn calendar_first_day_property_round_trips_and_reaches_the_calendar() {
        use crate::widget::capability::types::CapabilityValue;
        use crate::widget::capability::WidgetProperties;

        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        editor
            .set("calendar_first_day", CapabilityValue::String("mon".to_string()))
            .expect("writable");
        assert_eq!(editor.calendar_first_day(), Weekday::Mon);
        assert_eq!(editor.calendar().first_day_of_week(), Weekday::Mon);
        assert_eq!(
            editor.get("calendar_first_day").expect("readable"),
            CapabilityValue::String("mon".to_string())
        );
    }

    /// Escape closes an open grid before any value navigation runs.
    #[test]
    fn escape_closes_the_calendar_first() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        editor.set_date(Date::new(2026, 6, 8));
        editor.set_calendar_popup(true);
        editor.set_calendar_open(true);

        editor.handle_event(&Event::KeyPress { key: 27, modifiers: 0 });

        assert!(!editor.calendar_open());
        assert_eq!(editor.date(), Date::new(2026, 6, 8), "closing must not change the value");
    }

    #[test]
    fn date_edit_step_up() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        editor.set_date(Date::new(2026, 6, 8));
        editor.step_up();
        assert_eq!(editor.date(), Date::new(2026, 6, 9));
    }

    #[test]
    fn date_edit_step_up_rolls_month() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        editor.set_date(Date::new(2026, 6, 30));
        editor.step_up();
        assert_eq!(editor.date(), Date::new(2026, 7, 1));
    }

    #[test]
    fn date_edit_step_up_rolls_year() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        editor.set_date(Date::new(2026, 12, 31));
        editor.step_up();
        assert_eq!(editor.date(), Date::new(2027, 1, 1));
    }

    #[test]
    fn date_edit_step_down() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        editor.set_date(Date::new(2026, 6, 8));
        editor.step_down();
        assert_eq!(editor.date(), Date::new(2026, 6, 7));
    }

    #[test]
    fn date_edit_step_down_rolls_month() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        editor.set_date(Date::new(2026, 6, 1));
        editor.step_down();
        assert_eq!(editor.date(), Date::new(2026, 5, 31));
    }

    #[test]
    fn date_edit_step_down_rolls_year() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        editor.set_date(Date::new(2026, 1, 1));
        editor.step_down();
        assert_eq!(editor.date(), Date::new(2025, 12, 31));
    }

    #[test]
    fn date_edit_undo_redo_restores_date() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        editor.set_date(Date::new(2026, 6, 8));
        editor.step_up();

        assert!(editor.can_undo());
        assert!(editor.undo());
        assert_eq!(editor.date(), Date::new(2026, 6, 8));
        assert!(editor.can_redo());
        assert!(editor.redo());
        assert_eq!(editor.date(), Date::new(2026, 6, 9));
    }

    #[test]
    fn date_edit_keyboard_shortcuts_drive_history() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        editor.set_date(Date::new(2026, 6, 8));
        editor.set_date(Date::new(2026, 6, 9));

        editor.handle_event(&Event::KeyPress { key: 90, modifiers: primary_modifier_event_bits() });
        assert_eq!(editor.date(), Date::new(2026, 6, 8));
        editor.handle_event(&Event::KeyPress { key: 89, modifiers: primary_modifier_event_bits() });
        assert_eq!(editor.date(), Date::new(2026, 6, 9));
    }

    #[test]
    fn date_edit_primary_shortcut_and_shifted_chord() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        editor.set_date(Date::new(2026, 6, 8));
        editor.set_date(Date::new(2026, 6, 9));

        let primary = primary_modifier_event_bits();
        // Shift+Primary+Z is a different chord, so it is not plain undo.
        editor.handle_event(&Event::key_press(90, primary | 0b0001));
        assert_eq!(editor.date(), Date::new(2026, 6, 9));

        // Primary+Z / Primary+Y are undo / redo on this host.
        editor.handle_event(&Event::key_press(90, primary));
        assert_eq!(editor.date(), Date::new(2026, 6, 8));
        editor.handle_event(&Event::key_press(89, primary));
        assert_eq!(editor.date(), Date::new(2026, 6, 9));

        // The accelerator that is not primary on this host does not undo.
        editor.handle_event(&Event::key_press(90, non_primary_modifier_event_bits()));
        assert_eq!(editor.date(), Date::new(2026, 6, 9));
    }

    #[test]
    fn date_edit_date_changed_signal_emits() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        let captured = Arc::new(Mutex::new(Date::new(0, 1, 1)));
        let sink = captured.clone();
        editor.date_changed.connect(move |d| {
            if let Ok(mut c) = sink.lock() {
                *c = *d;
            }
        });

        let expected = Date::new(2027, 4, 15);
        editor.set_date(expected);
        let got = *captured.lock().unwrap();
        assert_eq!(got, expected);
    }

    #[test]
    fn date_edit_keyboard_navigation() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        editor.set_date(Date::new(2026, 6, 8));

        // Up arrow (key 38) = step_up
        editor.handle_event(&Event::KeyPress { key: 38, modifiers: 0 });
        assert_eq!(editor.date(), Date::new(2026, 6, 9));

        // Down arrow (key 40) = step_down
        editor.handle_event(&Event::KeyPress { key: 40, modifiers: 0 });
        assert_eq!(editor.date(), Date::new(2026, 6, 8));
    }

    #[test]
    fn date_edit_geometry_delegation() {
        let rect = Rect::new(10, 20, 200, 30);
        let editor = DateEdit::new(rect);
        assert_eq!(editor.geometry(), rect);
        assert_eq!(editor.position(), Point::new(10, 20));
        assert_eq!(editor.size(), crate::core::Size::new(200, 30));
    }

    #[test]
    fn date_edit_visibility() {
        let mut editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        assert!(editor.is_visible());
        editor.set_visible(false);
        assert!(!editor.is_visible());
        editor.set_visible(true);
        assert!(editor.is_visible());
    }

    #[test]
    fn date_edit_kind() {
        let editor = DateEdit::new(Rect::new(0, 0, 200, 30));
        assert_eq!(editor.kind(), WidgetKind::DatePicker);
    }

    #[test]
    fn date_edit_ids_are_unique() {
        let a = DateEdit::new(Rect::new(0, 0, 200, 30));
        let b = DateEdit::new(Rect::new(0, 0, 200, 30));
        assert_ne!(a.id(), b.id());
    }

    /// Lowering the maximum must pull the current date down into the new range.
    ///
    /// The bug this pins: the bound setters stored the new bounds without re-checking
    /// the value, so the widget could hold a date outside its own range — after which
    /// every `set_date` call failed the range check silently and the widget was stuck
    /// at a value it reported as invalid.
    #[test]
    fn lowering_the_maximum_clamps_the_current_date() {
        let mut edit = DateEdit::new(Rect::new(0, 0, 200, 30));
        edit.set_date_range(Date::new(2024, 1, 1), Date::new(2024, 12, 31));
        edit.set_date(Date::new(2024, 6, 15));

        edit.set_maximum_date(Date::new(2024, 3, 31));

        assert_eq!(
            edit.date(),
            Date::new(2024, 3, 31),
            "the value must be clamped to the new maximum rather than left out of range"
        );
        edit.set_date(Date::new(2024, 2, 1));
    }

    /// Raising the minimum must pull the current date up into the new range.
    #[test]
    fn raising_the_minimum_clamps_the_current_date() {
        let mut edit = DateEdit::new(Rect::new(0, 0, 200, 30));
        edit.set_date_range(Date::new(2024, 1, 1), Date::new(2024, 12, 31));
        edit.set_date(Date::new(2024, 6, 15));

        edit.set_minimum_date(Date::new(2024, 9, 1));

        assert_eq!(edit.date(), Date::new(2024, 9, 1), "clamped up to the new minimum");
        edit.set_date(Date::new(2024, 10, 1));
    }

    /// An inverted range must not wedge the editor.
    ///
    /// `min > max` is caller error, but it must not leave a value that no write can
    /// replace; the minimum wins so the widget stays usable and pinned at a bound it
    /// would itself accept.
    #[test]
    fn an_inverted_range_pins_to_the_minimum_and_stays_usable() {
        let mut edit = DateEdit::new(Rect::new(0, 0, 200, 30));
        edit.set_date_range(Date::new(2024, 1, 1), Date::new(2024, 12, 31));
        edit.set_date(Date::new(2024, 6, 15));

        edit.set_date_range(Date::new(2024, 10, 1), Date::new(2024, 3, 1));

        assert_eq!(edit.date(), Date::new(2024, 10, 1), "the minimum is authoritative");
        edit.set_date(Date::new(2024, 10, 1));
    }

    /// Bounds that already contain the value must leave it alone.
    #[test]
    fn setting_a_range_that_contains_the_value_does_not_move_it() {
        let mut edit = DateEdit::new(Rect::new(0, 0, 200, 30));
        edit.set_date_range(Date::new(2024, 1, 1), Date::new(2024, 12, 31));
        edit.set_date(Date::new(2024, 6, 15));

        edit.set_minimum_date(Date::new(2024, 2, 1));
        edit.set_maximum_date(Date::new(2024, 11, 1));

        assert_eq!(edit.date(), Date::new(2024, 6, 15), "an in-range value must not be nudged");
    }

    /// Typing into a section edits that component without re-entering the value.
    #[test]
    fn typing_edits_the_active_section() {
        let mut edit = DateEdit::new(Rect::new(0, 0, 200, 30));
        edit.set_date(Date::new(2024, 6, 15));
        assert!(!edit.type_digit('2'), "no section, no typing");

        edit.set_current_section(Some(DateSection::Year));
        for digit in ['2', '0', '2', '6'] {
            assert!(edit.type_digit(digit));
        }
        assert_eq!(edit.date(), Date::new(2026, 6, 15));

        edit.set_current_section(Some(DateSection::Month));
        assert!(edit.type_digit('1'));
        assert!(edit.type_digit('2'));
        assert_eq!(edit.date(), Date::new(2026, 12, 15));

        edit.set_current_section(Some(DateSection::Day));
        assert!(edit.type_digit('3'));
        assert_eq!(edit.date(), Date::new(2026, 12, 3));
        assert!(!edit.type_digit('x'), "a non-digit is refused");
    }

    /// Section stepping wraps the month across a year boundary.
    #[test]
    fn stepping_a_section_wraps_the_month() {
        let mut edit = DateEdit::new(Rect::new(0, 0, 200, 30));
        edit.set_date(Date::new(2026, 12, 15));
        edit.set_current_section(Some(DateSection::Month));
        edit.step_current_section(1);
        assert_eq!(edit.date(), Date::new(2027, 1, 15));
        edit.step_current_section(-1);
        assert_eq!(edit.date(), Date::new(2026, 12, 15));

        edit.set_current_section(Some(DateSection::Year));
        edit.step_current_section(-1);
        assert_eq!(edit.date(), Date::new(2025, 12, 15));
    }

    /// Spin buttons are opt-in, and the up button steps the active section.
    #[test]
    fn spin_buttons_are_opt_in_and_step_the_value() {
        let mut edit = DateEdit::new(Rect::new(0, 0, 200, 30));
        edit.set_date(Date::new(2026, 6, 15));
        assert!(edit.spin_button_rects().is_none(), "off by default");
        edit.set_spin_buttons(true);
        let (up, _down) = edit.spin_button_rects().expect("the pair exists once enabled");

        edit.handle_event(&Event::mouse_press(up.x + 2, up.y + 2, 1));
        assert_eq!(edit.date(), Date::new(2026, 6, 16), "the button steps a whole day");
        edit.set_current_section(Some(DateSection::Month));
        edit.handle_event(&Event::mouse_press(up.x + 2, up.y + 2, 1));
        assert_eq!(edit.date(), Date::new(2026, 7, 16), "and the section once one is active");
    }

    /// The wheel steps the value.
    #[test]
    fn the_wheel_steps_the_value() {
        let mut edit = DateEdit::new(Rect::new(0, 0, 200, 30));
        edit.set_date(Date::new(2026, 6, 15));
        edit.handle_event(&Event::wheel(0, 1, 0));
        assert_eq!(edit.date(), Date::new(2026, 6, 16), "wheel up increases");
        edit.handle_event(&Event::wheel(0, -1, 0));
        assert_eq!(edit.date(), Date::new(2026, 6, 15), "wheel down decreases");
    }

    /// Special value text replaces the date only at the minimum, where it is painted.
    #[test]
    fn special_value_text_is_shown_at_the_minimum() {
        let mut edit = DateEdit::new(Rect::new(0, 0, 200, 30));
        edit.set_date_range(Date::new(2026, 1, 1), Date::new(2026, 12, 31));
        edit.set_date(Date::new(2026, 1, 1));
        let plain = crate::widget::svg::render_to_svg(&mut edit);
        edit.set_special_value_text(Some("Not set".to_string()));
        let special = crate::widget::svg::render_to_svg(&mut edit);
        assert_ne!(plain, special, "the special text must reach the painter");
        assert_eq!(edit.special_value_text(), Some("Not set"));

        edit.set_date(Date::new(2026, 2, 1));
        assert_eq!(edit.date(), Date::new(2026, 2, 1));
    }

    /// The calendar reveal animates when opened and settles when ticked.
    #[test]
    fn the_calendar_popup_reveals() {
        use crate::widget::Widget;

        let mut edit = DateEdit::new(Rect::new(0, 0, 200, 30));
        edit.set_calendar_popup(true);
        edit.set_calendar_open(true);
        assert!(edit.is_animating(), "opening the grid starts a reveal");
        for _ in 0..120 {
            edit.tick(16);
        }
        assert!(!edit.is_animating());
        assert!(edit.calendar_open());
    }

    /// Clicking one of the value's three zones selects that section.
    #[test]
    fn clicking_a_value_zone_selects_its_section() {
        let mut edit = DateEdit::new(Rect::new(0, 0, 240, 30));
        assert_eq!(edit.current_section(), None);
        let month = edit.section_zone(DateSection::Month);
        edit.handle_event(&Event::mouse_press(month.x + 2, month.y + 2, 1));
        assert_eq!(edit.current_section(), Some(DateSection::Month));
        let day = edit.section_zone(DateSection::Day);
        edit.handle_event(&Event::mouse_press(day.x + 2, day.y + 2, 1));
        assert_eq!(edit.current_section(), Some(DateSection::Day));
    }

    /// Enter and focus loss both announce the end of an edit (ADV-02).
    #[test]
    fn the_edit_finishes_on_enter_and_on_focus_loss() {
        use std::sync::{Arc, Mutex};
        let mut edit = DateEdit::new(Rect::new(0, 0, 160, 28));
        let finished = Arc::new(Mutex::new(0u32));
        let sink = Arc::clone(&finished);
        edit.editing_finished.connect(move || *sink.lock().unwrap() += 1);

        edit.handle_event(&Event::key_press(crate::event::key_codes::ENTER, 0));
        assert_eq!(*finished.lock().unwrap(), 1);
        edit.handle_event(&Event::FocusLost);
        assert_eq!(*finished.lock().unwrap(), 2);
    }
}