quadraui 0.6.0

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
//! `FormController` — a composed controller for a single `Form` with
//! built-in scrollbar support.
//!
//! Mirrors [`TreeController`](super::tree_controller::TreeController):
//! owns scroll state, renders the form + scrollbar, and handles scroll
//! wheel / scrollbar click / thumb-drag events. Apps push field data
//! per frame via [`FormController::set_form`], call
//! [`FormController::render`] + [`FormController::handle`], and match
//! on [`FormControllerEvent`] for semantic actions.
//!
//! Two event-handling paths:
//!
//! - [`FormController::handle`] — requires `&mut dyn Backend`. Use when
//!   the event handler has a backend reference (e.g. `AppLogic::handle`).
//! - [`FormController::handle_cached`] — backend-free. Uses metrics
//!   cached by [`FormController::render`] or [`FormController::set_backend_info`].
//!   Use when the event handler runs without a backend (e.g. vimcode's
//!   TUI mouse handler).
//!
//! ## Keyboard editing
//!
//! `KeyPressed` / `CharTyped` / `ClipboardPaste` route to the field named
//! by `Form.focused_field`, and only while [`FormController::has_focus`]
//! is true — a host is expected to forward every event in (see the two
//! event-handling paths above), so without this gate a form that isn't
//! even the active panel would still swallow `Tab` and every other key.
//! Toggle it with [`FormController::set_has_focus`], the same shape
//! `compose::sidebar_system` uses.
//!
//! - `Tab` / `Shift+Tab` (or `BackTab`) move focus to the next/previous
//!   non-`Label`, non-`ReadOnly`, non-disabled field, scroll it into
//!   view, and emit [`FormEvent::FocusChanged`]. The app stores the new
//!   id and feeds it back as `focused_field` on the next
//!   [`FormController::set_form`] — same contract `primitives/form.rs`'s
//!   module doc already describes.
//! - While a `TextInput` / `TextArea` / `PasswordInput` field is
//!   focused, every other key is decoded through
//!   [`crate::EditOp::from_key`] and applied via [`crate::TextEditor::apply`]
//!   against that field's `value`, emitting
//!   [`FormEvent::TextInputChanged`] with the new value.
//!   `Ctrl`/`Cmd`+`<character>` combos are rejected before
//!   `EditOp::from_key` sees them — every backend delivers those as
//!   `Key::Char` with the modifier set, so an unregistered accelerator
//!   (Ctrl+C, Cmd+S, ...) doesn't get typed as a literal character.
//!   `Enter` commits instead of inserting a newline, emitting
//!   [`FormEvent::TextInputCommitted`] — except on a `TextArea`, where
//!   `Enter` inserts a newline, since that is the one field kind meant
//!   to hold them. `ClipboardPaste` inserts its text via
//!   [`crate::EditOp::InsertText`].
//! - The cursor/selection position is **owned by `FormController`**, not
//!   the app — it survives across keystrokes internally (see
//!   `text_edit` below) even though the app only ever has to persist the
//!   `value` string from `TextInputChanged`/`TextInputCommitted`. This is
//!   what makes "no app-side key plumbing" true: the app's model needs a
//!   `String` per text field, nothing else. Each keystroke builds a
//!   throwaway [`crate::TextEditor`] (see `apply_text_edit_op`), so
//!   `EditOp::Undo`/`Redo` never have history to act on for a form
//!   field — out of scope here, since nothing in `Form`'s per-frame data
//!   carries edit history across keystrokes.
//!
//! ## Date picker fields
//!
//! `FieldKind::DatePicker` splits ownership the same way text fields do
//! (see "Keyboard editing" above): the app stays the source of truth for
//! the *confirmed* value (`selected`, pushed back via
//! [`FormEvent::DateChanged`] once `Enter` confirms a day), while
//! `FormController` owns the live scrubbing position between keystrokes
//! (see `DateEditState`) so `Left`/`Right`/`Up`/`Down`/`PageUp`/`PageDown`
//! keep moving the calendar without an app round-trip on every key.
//!
//! - While the row is focused, the renderer shows the cached scrub
//!   position (`focused`), not `selected` — otherwise a scrub past the
//!   first confirmed date would be invisible. Once focus moves on, the
//!   renderer falls back to `selected` (or `focused` before any date has
//!   ever been confirmed).
//! - `Tab`/`Shift+Tab`/`BackTab` are excluded from the picker's own key
//!   set, so focus traversal off a `DatePicker` field still works
//!   normally, and `Ctrl`/`Alt`/`Cmd` + any of the picker's keys fall
//!   through to the generic dispatch (and from there to the host) rather
//!   than being swallowed as navigation.
//! - A disabled focused `DatePicker` does not intercept its navigation
//!   keys at all — they fall through to the generic dispatch below,
//!   which is a no-op for a non-text field, the same as any other
//!   disabled field kind.
//! - Clicking a `DatePicker` field only changes focus (`FieldKind` has no
//!   click-driven navigation yet); the cached scrub position is only
//!   ever overlaid onto the field that is still focused, so a click that
//!   moves focus elsewhere can't leave a stale scrub position visible on
//!   the field it left.

use crate::primitives::date_picker::{CalendarDate, DatePickerEvent};
use crate::primitives::form::{
    FieldKind, Form, FormEvent, FormFieldMeasure, FormHit, FormItemMeasure,
};
use crate::primitives::scrollbar::{scroll_by_clamped, wheel_row_delta, PressZone, ThumbDrag};
use crate::primitives::text_input::{EditOp, TextEditor, TextInput};
use crate::text_util::snap_to_char_boundary;
use crate::{
    Backend, ButtonMask, Key, Modifiers, MouseButton, NamedKey, Point, Rect, Scrollbar, UiEvent,
    WidgetId,
};

/// What happened after [`FormController::handle`] processed an event.
#[derive(Debug, Clone, PartialEq)]
pub enum FormControllerEvent {
    /// A field-level event occurred (toggle changed, text input, etc.).
    FormAction(FormEvent),
    /// Scrollbar interaction changed the scroll offset.
    ScrollChanged,
    /// Event consumed (drag update, hover) — caller should redraw.
    Consumed,
    /// Event not relevant to the form.
    Ignored,
}

/// Live cursor/selection for the field currently being typed into.
/// `value` is **not** cached here — it is always read fresh from
/// `FormController::form` (the app's own canonical string, pushed via
/// `set_form`), so the app staying the single source of truth for field
/// *content* still holds; only cursor placement is controller-owned.
/// See this module's "Keyboard editing" doc section for why.
struct TextEditState {
    field_id: WidgetId,
    cursor: usize,
    selection_anchor: Option<usize>,
}

/// Live focused-day/visible-month for the `DatePicker` field currently
/// being navigated. Mirrors `TextEditState`'s split: the app stays the
/// source of truth for `selected` (pushed back via `FormEvent::DateChanged`
/// once Enter confirms a day), while the controller owns the scrubbing
/// position between keystrokes so Left/Right/Up/Down/PageUp/PageDown keep
/// moving without an app round-trip on every key.
struct DateEditState {
    field_id: WidgetId,
    focused: CalendarDate,
    visible_month: CalendarDate,
}

pub struct FormController {
    id: String,
    form: Option<Form>,
    scroll_offset: usize,
    has_focus: bool,
    scroll_drag: Option<ThumbDrag>,
    cached_lh: Option<f32>,
    text_edit: Option<TextEditState>,
    date_edit: Option<DateEditState>,
}

impl FormController {
    pub fn new(id: String) -> Self {
        Self {
            id,
            form: None,
            scroll_offset: 0,
            has_focus: false,
            scroll_drag: None,
            cached_lh: None,
            text_edit: None,
            date_edit: None,
        }
    }

    // ── Per-frame data ────────────────────────────────────────────────

    pub fn set_form(&mut self, form: Form) {
        self.form = Some(form);
    }

    // ── State accessors ───────────────────────────────────────────────

    pub fn form(&self) -> Option<&Form> {
        self.form.as_ref()
    }

    pub fn id(&self) -> &str {
        &self.id
    }

    pub fn default_form_id(&self) -> WidgetId {
        WidgetId::new(format!("{}-form", self.id))
    }

    pub fn scroll_offset(&self) -> usize {
        self.scroll_offset
    }

    pub fn has_focus(&self) -> bool {
        self.has_focus
    }

    pub fn field_count(&self) -> usize {
        self.form.as_ref().map_or(0, |f| f.fields.len())
    }

    // ── Programmatic state control ────────────────────────────────────

    pub fn set_scroll_offset(&mut self, offset: usize) {
        self.scroll_offset = offset;
    }

    pub fn set_has_focus(&mut self, has_focus: bool) {
        self.has_focus = has_focus;
    }

    /// Cache backend metrics so [`Self::handle_cached`] can process
    /// events without a `Backend` reference. Call once at init, or
    /// again if `line_height` changes (font/DPI change).
    ///
    /// [`Self::render`] caches this automatically, so explicit calls
    /// are only needed when `handle_cached` must work before the first
    /// `render`.
    pub fn set_backend_info(&mut self, line_height: f32) {
        self.cached_lh = Some(line_height);
    }

    // ── Render ────────────────────────────────────────────────────────

    pub fn render(&self, backend: &mut dyn Backend, rect: Rect) {
        let lh = backend.line_height();
        // Cache metrics for handle_cached(). The &self receiver prevents
        // mutation here, so we defer to a post-render cache call pattern:
        // callers that need handle_cached() should call set_backend_info()
        // or render_and_cache().
        let (form_rect, sb_rect) = split_rect_lh(self.field_count(), lh, rect);
        let form = self.build_form(form_rect);
        backend.draw_form(form_rect, &form);
        if let Some(sb_rect) = sb_rect {
            let sb = build_scrollbar_lh(
                &self.id,
                self.field_count(),
                self.scroll_offset,
                self.scroll_drag.is_some(),
                lh,
                sb_rect,
            );
            backend.draw_scrollbar(sb_rect, &sb);
        }
    }

    /// Render and cache backend metrics for [`Self::handle_cached`].
    ///
    /// Equivalent to calling [`Self::set_backend_info`] then
    /// [`Self::render`], but in one step.
    pub fn render_and_cache(&mut self, backend: &mut dyn Backend, rect: Rect) {
        self.cached_lh = Some(backend.line_height());
        self.render(backend, rect);
    }

    // ── Handle (with backend) ────────────────────────────────────────

    pub fn handle(
        &mut self,
        event: &UiEvent,
        backend: &mut dyn Backend,
        rect: Rect,
    ) -> FormControllerEvent {
        let lh = backend.line_height();
        self.handle_inner(event, rect, lh, Some(backend))
    }

    // ── Handle (cached, no backend) ──────────────────────────────────

    /// Backend-free event handler. Requires [`Self::set_backend_info`]
    /// or [`Self::render_and_cache`] called first. Returns
    /// [`FormControllerEvent::Ignored`] if metrics aren't cached yet.
    pub fn handle_cached(&mut self, event: &UiEvent, rect: Rect) -> FormControllerEvent {
        let Some(lh) = self.cached_lh else {
            return FormControllerEvent::Ignored;
        };
        self.handle_inner(event, rect, lh, None)
    }

    // ── Scroll primitives (pub for SidebarSystem reuse) ──────────────

    pub fn scroll_by(&mut self, delta: isize, viewport_rows: usize) {
        let max = self.field_count().saturating_sub(viewport_rows);
        self.scroll_offset = scroll_by_clamped(self.scroll_offset, delta, max);
    }

    pub fn page_scroll(&mut self, delta: isize, viewport_rows: usize) {
        self.scroll_by(delta, viewport_rows);
    }

    pub fn scroll_to_field(&mut self, field_idx: usize, viewport_rows: usize) {
        if viewport_rows == 0 {
            return;
        }
        if field_idx < self.scroll_offset {
            self.scroll_offset = field_idx;
        } else if field_idx >= self.scroll_offset + viewport_rows {
            self.scroll_offset = field_idx.saturating_sub(viewport_rows.saturating_sub(1));
        }
    }

    pub fn viewport_rows(&self, backend: &dyn Backend, rect: Rect) -> usize {
        viewport_rows_lh(backend.line_height(), rect)
    }

    // ── Internal: shared handle dispatch ─────────────────────────────

    fn handle_inner(
        &mut self,
        event: &UiEvent,
        rect: Rect,
        lh: f32,
        backend: Option<&mut dyn Backend>,
    ) -> FormControllerEvent {
        match event {
            UiEvent::MouseDown {
                button: MouseButton::Left,
                position,
                ..
            } => self.click_inner(rect, position.x, position.y, lh, backend),

            UiEvent::MouseMoved {
                position,
                buttons:
                    ButtonMask {
                        left: true,
                        middle: _,
                        right: _,
                    },
            } => self.drag_to(position.y),

            UiEvent::MouseUp {
                button: MouseButton::Left,
                ..
            } => {
                self.scroll_drag = None;
                FormControllerEvent::Ignored
            }

            UiEvent::Scroll { delta, .. } => {
                let vr = viewport_rows_lh(lh, rect);
                let rows = wheel_row_delta(delta.y, 1.0);
                self.scroll_by(rows, vr);
                FormControllerEvent::Consumed
            }

            // Gate on `self.has_focus`: `FormController::handle`'s
            // documented usage is "forward every event in" (see this
            // module's top doc), so without this a host that always
            // routes `KeyPressed` through a form would lose global `Tab`
            // (and every other key) to a form that isn't even the
            // active panel. `set_has_focus`/`form_has_focus` exist for
            // exactly this (mirrors `compose/sidebar_system.rs`).
            UiEvent::KeyPressed { key, modifiers, .. } if self.has_focus => {
                let vr = viewport_rows_lh(lh, rect);
                self.handle_key(key, modifiers, vr)
            }

            UiEvent::CharTyped(ch) if self.has_focus => {
                self.handle_text_op(EditOp::InsertChar(*ch))
            }

            UiEvent::ClipboardPaste(text) if self.has_focus => {
                self.handle_text_op(EditOp::InsertText(text.clone()))
            }

            _ => FormControllerEvent::Ignored,
        }
    }

    // ── Internal helpers ──────────────────────────────────────────────

    fn build_form(&self, _rect: Rect) -> Form {
        match &self.form {
            Some(f) => {
                let mut form = f.clone();
                form.scroll_offset = self.scroll_offset;
                form.has_focus = self.has_focus;
                if let Some(e) = &self.text_edit {
                    if let Some(field) = form.fields.iter_mut().find(|fld| fld.id == e.field_id) {
                        overlay_text_cursor(&mut field.kind, e.cursor, e.selection_anchor);
                    }
                }
                // Gated on the field still being focused (unlike the
                // `text_edit` overlay above): a click that moves focus
                // off a `DatePicker` field goes through `form_click_event`
                // (not `move_focus`), which doesn't reseed/clear
                // `date_edit`, so a stale cached scrub position could
                // otherwise outlive the row it was scrubbed on.
                if let Some(e) = &self.date_edit {
                    if form.focused_field == Some(e.field_id) {
                        if let Some(field) = form.fields.iter_mut().find(|fld| fld.id == e.field_id)
                        {
                            overlay_date_edit(&mut field.kind, e.focused, e.visible_month);
                        }
                    }
                }
                form
            }
            None => Form {
                id: self.default_form_id(),
                fields: Vec::new(),
                focused_field: None,
                scroll_offset: self.scroll_offset,
                has_focus: self.has_focus,
            },
        }
    }

    // ── Keyboard: focus traversal + text editing ──────────────────────

    fn handle_key(
        &mut self,
        key: &Key,
        modifiers: &Modifiers,
        viewport_rows: usize,
    ) -> FormControllerEvent {
        // `DatePicker` claims Left/Right/Up/Down/PageUp/PageDown/Enter
        // ahead of the generic dispatch below — those keys would
        // otherwise fall through to `EditOp::from_key` (a no-op for a
        // non-text field) or, for `Enter`, to `commit_focused_text`
        // (also a no-op). `Tab`/`BackTab` aren't in this set, so focus
        // traversal off a `DatePicker` field still works normally.
        //
        // Guarded the same way the `Tab` arm below is: without the
        // modifier check, a host accelerator like Ctrl+Enter would be
        // swallowed into `navigate` whenever a date field has focus
        // instead of falling through to the app. A disabled focused
        // field is excluded too, so its keys reach the generic dispatch
        // below (which is a no-op for a non-text field) rather than
        // being eaten outright.
        if !modifiers.ctrl && !modifiers.alt && !modifiers.cmd {
            if let Some(key_name) = date_picker_key_name(key) {
                if self.focused_field_is_enabled_date_picker() {
                    return self.handle_date_picker_key(key_name);
                }
            }
        }
        match key {
            Key::Named(NamedKey::Tab) if !modifiers.ctrl && !modifiers.alt && !modifiers.cmd => {
                self.move_focus(if modifiers.shift { -1 } else { 1 }, viewport_rows)
            }
            Key::Named(NamedKey::BackTab) => self.move_focus(-1, viewport_rows),
            // `Enter` commits for `TextInput`/`PasswordInput` (a single
            // commit boundary), but `TextArea` is the one field kind
            // that is meant to hold newlines, so `Enter` inserts one
            // there instead — same split VS Code makes between a
            // single-line input and a multi-line text area.
            Key::Named(NamedKey::Enter) if self.focused_field_is_text_area() => {
                self.handle_text_op(EditOp::InsertChar('\n'))
            }
            Key::Named(NamedKey::Enter) => self.commit_focused_text(),
            // Every backend delivers Ctrl/Cmd+<letter> as `Key::Char`
            // with the modifier set (so an unregistered accelerator can
            // still be recovered), not as a dedicated key variant — see
            // `EditOp::from_key`'s callers in `examples/common/text_input_demo.rs`
            // for the same guard. Without this, Ctrl+C/Ctrl+V/Ctrl+W (or
            // Cmd+<letter> on macOS) would type a stray literal character
            // into the focused field instead of falling through to an
            // app-level accelerator.
            Key::Char(_) if modifiers.ctrl || modifiers.cmd => FormControllerEvent::Ignored,
            _ => match EditOp::from_key(key, *modifiers) {
                Some(op) => self.handle_text_op(op),
                None => FormControllerEvent::Ignored,
            },
        }
    }

    /// Whether the currently-focused field is a `TextArea` — gives
    /// `Enter` its kind-specific meaning (insert a newline there, commit
    /// everywhere else).
    fn focused_field_is_text_area(&self) -> bool {
        let Some(form) = &self.form else {
            return false;
        };
        let Some(focused_id) = &form.focused_field else {
            return false;
        };
        form.fields
            .iter()
            .find(|f| &f.id == focused_id)
            .is_some_and(|f| matches!(f.kind, FieldKind::TextArea { .. }))
    }

    /// Whether the currently-focused field is a non-disabled
    /// `DatePicker` — gates `handle_key`'s date-navigation interception.
    /// Excluding the disabled case here (rather than inside
    /// `handle_date_picker_key`) lets its keys fall through to the
    /// generic dispatch below instead of being swallowed outright.
    fn focused_field_is_enabled_date_picker(&self) -> bool {
        let Some(form) = &self.form else {
            return false;
        };
        let Some(focused_id) = &form.focused_field else {
            return false;
        };
        form.fields
            .iter()
            .find(|f| &f.id == focused_id)
            .is_some_and(|f| !f.disabled && matches!(f.kind, FieldKind::DatePicker(_)))
    }

    /// Route `key_name` into the focused `DatePicker`'s own
    /// [`crate::primitives::date_picker::DatePicker::navigate`] and apply
    /// the result: a `FocusMoved` updates the cached scrubbing position
    /// (see `DateEditState`) without touching the app's `selected` value,
    /// while a `DateSelected` (Enter) clears the cache and hands the app
    /// [`FormEvent::DateChanged`] to persist.
    fn handle_date_picker_key(&mut self, key_name: &str) -> FormControllerEvent {
        let Some(form) = &self.form else {
            return FormControllerEvent::Ignored;
        };
        let Some(focused_id) = form.focused_field else {
            return FormControllerEvent::Ignored;
        };
        let Some(field) = form.fields.iter().find(|f| f.id == focused_id) else {
            return FormControllerEvent::Ignored;
        };
        if field.disabled {
            return FormControllerEvent::Ignored;
        }
        let FieldKind::DatePicker(picker) = &field.kind else {
            return FormControllerEvent::Ignored;
        };

        // Overlay the cached scrubbing position before calling `navigate`
        // so consecutive keystrokes compose on top of each other instead
        // of resetting to the app-provided `focused`/`visible_month`
        // every time (the app only ever sees the field again once a
        // `DateChanged` round-trip persists a new `selected`).
        let mut picker = picker.clone();
        if let Some(e) = &self.date_edit {
            if e.field_id == focused_id {
                picker.focused = e.focused;
                picker.visible_month = e.visible_month;
            }
        }

        match picker.navigate(key_name) {
            Some(DatePickerEvent::FocusMoved(date)) => {
                picker.focused = date;
                if !picker.is_in_visible_month(date) {
                    picker.visible_month = date.first_of_month();
                }
                self.date_edit = Some(DateEditState {
                    field_id: focused_id,
                    focused: picker.focused,
                    visible_month: picker.visible_month,
                });
                FormControllerEvent::Consumed
            }
            Some(DatePickerEvent::DateSelected(date)) => {
                self.date_edit = None;
                FormControllerEvent::FormAction(FormEvent::DateChanged {
                    id: focused_id,
                    value: date,
                })
            }
            None => FormControllerEvent::Ignored,
        }
    }

    /// Move focus to the next/previous non-`Label`, non-`ReadOnly`,
    /// non-disabled field, wrapping around, and scroll it into view.
    /// Emits [`FormEvent::FocusChanged`] — the app persists the new
    /// `focused_field` the same way it already persists a toggle flip
    /// (see this module's "Keyboard editing" doc section).
    fn move_focus(&mut self, delta: isize, viewport_rows: usize) -> FormControllerEvent {
        let Some(form) = &self.form else {
            return FormControllerEvent::Ignored;
        };
        let stops: Vec<&WidgetId> = form
            .fields
            .iter()
            .filter(|f| field_is_focusable(f))
            .map(|f| &f.id)
            .collect();
        if stops.is_empty() {
            return FormControllerEvent::Ignored;
        }
        let n = stops.len() as isize;
        let cur_idx = form
            .focused_field
            .as_ref()
            .and_then(|id| stops.iter().position(|fid| *fid == id));
        let next_idx = match cur_idx {
            Some(i) => (((i as isize + delta) % n + n) % n) as usize,
            None if delta >= 0 => 0,
            None => stops.len() - 1,
        };
        let id = *stops[next_idx];
        // The stop's index among `stops` isn't necessarily its index in
        // `form.fields` (non-focusable fields are filtered out above),
        // so re-find its field index for scrolling and for seeding the
        // new field's starting cursor below. Resolved up front (and
        // `form`'s borrow dropped here) because both steps below need
        // `&mut self`.
        let field_idx = form.fields.iter().position(|f| f.id == id);
        // Seed a starting cursor for the newly-focused field if it's
        // text-editable, so `build_form` overlays a caret immediately
        // instead of the field rendering as read-only (no cursor, per
        // `primitives/form.rs`) until the first keystroke.
        let new_text_edit = field_idx
            .and_then(|i| form.fields.get(i))
            .filter(|f| text_field_value(&f.kind).is_some())
            .map(|f| {
                let (cursor, selection_anchor) = default_text_cursor(&f.kind);
                TextEditState {
                    field_id: id,
                    cursor,
                    selection_anchor,
                }
            });
        // Same seeding as `new_text_edit` above, but for a `DatePicker`:
        // the newly-focused field's own `focused`/`visible_month` become
        // the starting scrubbing position, so `build_form` overlays them
        // immediately rather than waiting for the first keystroke.
        let new_date_edit =
            field_idx
                .and_then(|i| form.fields.get(i))
                .and_then(|f| match &f.kind {
                    FieldKind::DatePicker(picker) => Some(DateEditState {
                        field_id: id,
                        focused: picker.focused,
                        visible_month: picker.visible_month,
                    }),
                    _ => None,
                });

        if let Some(field_idx) = field_idx {
            self.scroll_to_field(field_idx, viewport_rows);
        }
        self.text_edit = new_text_edit;
        self.date_edit = new_date_edit;
        FormControllerEvent::FormAction(FormEvent::FocusChanged { id })
    }

    /// `Enter` on a focused `TextInput`/`PasswordInput` field commits
    /// instead of inserting a newline — see this module's "Keyboard
    /// editing" doc section. (`TextArea` is handled separately in
    /// `handle_key`.)
    fn commit_focused_text(&mut self) -> FormControllerEvent {
        let Some(form) = &self.form else {
            return FormControllerEvent::Ignored;
        };
        let Some(focused_id) = form.focused_field else {
            return FormControllerEvent::Ignored;
        };
        let Some(field) = form.fields.iter().find(|f| f.id == focused_id) else {
            return FormControllerEvent::Ignored;
        };
        if field.disabled {
            return FormControllerEvent::Ignored;
        }
        let Some(value) = text_field_value(&field.kind) else {
            return FormControllerEvent::Ignored;
        };
        let value = value.to_string();
        self.text_edit = None;
        FormControllerEvent::FormAction(FormEvent::TextInputCommitted {
            id: focused_id,
            value,
        })
    }

    /// Apply `op` to the currently-focused text field (if any), emitting
    /// [`FormEvent::TextInputChanged`] with the new value. The cursor
    /// produced by `op` is cached on `self.text_edit` so the next
    /// keystroke continues from it — see `TextEditState`'s doc.
    fn handle_text_op(&mut self, op: EditOp) -> FormControllerEvent {
        let Some(form) = &self.form else {
            return FormControllerEvent::Ignored;
        };
        let Some(focused_id) = form.focused_field else {
            return FormControllerEvent::Ignored;
        };
        let Some(field) = form.fields.iter().find(|f| f.id == focused_id) else {
            return FormControllerEvent::Ignored;
        };
        if field.disabled {
            return FormControllerEvent::Ignored;
        }
        let Some(value) = text_field_value(&field.kind) else {
            return FormControllerEvent::Ignored;
        };

        let (cursor, anchor) = match &self.text_edit {
            Some(e) if e.field_id == focused_id => (e.cursor, e.selection_anchor),
            _ => default_text_cursor(&field.kind),
        };
        let cursor = snap_to_char_boundary(value, cursor.min(value.len()));

        let value_before = value.to_string();
        let (new_value, new_cursor, new_anchor) = apply_text_edit_op(value, cursor, anchor, op);
        let text_changed = new_value != value_before;
        // `TextEditor::move_cursor_to` leaves a degenerate `anchor ==
        // cursor` selection in place for a no-op extend (e.g. Shift+Left
        // at offset 0). Left uncleared, the *next* keystroke would see a
        // phantom one-character-wide selection and silently eat a
        // character. Normalise it away here, where the controller caches
        // the anchor across keystrokes (unlike a one-shot `TextEditor`
        // call, which never notices).
        let new_anchor = new_anchor.filter(|a| *a != new_cursor);
        self.text_edit = Some(TextEditState {
            field_id: focused_id,
            cursor: new_cursor,
            selection_anchor: new_anchor,
        });
        if text_changed {
            FormControllerEvent::FormAction(FormEvent::TextInputChanged {
                id: focused_id,
                value: new_value,
            })
        } else {
            // Cursor-only movement (or selection extend): the field's
            // text content is unchanged, so there is nothing for the app
            // to persist — but the cursor/selection did move, so the
            // caller should still redraw to show it.
            FormControllerEvent::Consumed
        }
    }

    fn click_inner(
        &mut self,
        rect: Rect,
        x: f32,
        y: f32,
        lh: f32,
        backend: Option<&mut dyn Backend>,
    ) -> FormControllerEvent {
        if !rect.contains(Point::new(x, y)) {
            return FormControllerEvent::Ignored;
        }
        let (form_rect, sb_rect) = split_rect_lh(self.field_count(), lh, rect);

        if let Some(sb_rect) = sb_rect {
            if sb_rect.contains(Point::new(x, y)) {
                return self.click_scrollbar_lh(lh, form_rect, sb_rect, y);
            }
        }

        if form_rect.contains(Point::new(x, y)) {
            let form = self.build_form(form_rect);
            let layout = if let Some(be) = backend {
                be.form_layout(form_rect, &form)
            } else {
                let row_h = row_height(lh);
                let char_w = lh * 0.6;
                form.layout(form_rect.width, form_rect.height, |i| {
                    form_field_measure(&form.fields[i], row_h, char_w)
                })
            };
            match layout.hit_test(x - form_rect.x, y - form_rect.y) {
                FormHit::Field(id) => {
                    let event = form_click_event(&form, &id);
                    FormControllerEvent::FormAction(event)
                }
                FormHit::Empty => FormControllerEvent::Consumed,
            }
        } else {
            FormControllerEvent::Ignored
        }
    }

    fn click_scrollbar_lh(
        &mut self,
        lh: f32,
        form_rect: Rect,
        sb_rect: Rect,
        y: f32,
    ) -> FormControllerEvent {
        let vr = viewport_rows_lh(lh, form_rect);
        let max_offset = self.field_count().saturating_sub(vr);
        if max_offset == 0 {
            return FormControllerEvent::Ignored;
        }

        let sb = build_scrollbar_lh(
            &self.id,
            self.field_count(),
            self.scroll_offset,
            self.scroll_drag.is_some(),
            lh,
            sb_rect,
        );

        match sb.press_zone(y) {
            PressZone::Thumb => {
                self.scroll_drag = Some(ThumbDrag::begin(
                    y,
                    self.scroll_offset as f32,
                    sb.travel(),
                    max_offset as f32,
                ));
                FormControllerEvent::ScrollChanged
            }
            PressZone::Before => {
                self.page_scroll(-(vr as isize), vr);
                FormControllerEvent::ScrollChanged
            }
            PressZone::After => {
                self.page_scroll(vr as isize, vr);
                FormControllerEvent::ScrollChanged
            }
        }
    }

    fn drag_to(&mut self, y: f32) -> FormControllerEvent {
        let Some(drag) = &self.scroll_drag else {
            return FormControllerEvent::Ignored;
        };
        let Some(new) = drag.offset_at(y) else {
            return FormControllerEvent::Ignored;
        };
        let new = new.round() as usize;
        if new == self.scroll_offset {
            return FormControllerEvent::Ignored;
        }
        self.scroll_offset = new;
        FormControllerEvent::Consumed
    }
}

// ── Free functions (shared by FormController + SidebarSystem) ────────

/// Determine the `FormEvent` for a click on a form field.
///
/// Used by `FormController::handle` and `SidebarSystem` click dispatch.
pub(crate) fn form_click_event(form: &Form, clicked_id: &WidgetId) -> FormEvent {
    for field in &form.fields {
        if &field.id == clicked_id {
            return match &field.kind {
                FieldKind::Toggle { value } => FormEvent::ToggleChanged {
                    id: *clicked_id,
                    value: !value,
                },
                FieldKind::Button => FormEvent::ButtonClicked { id: *clicked_id },
                _ => FormEvent::FocusChanged { id: *clicked_id },
            };
        }
        if let FieldKind::ToggleGroup { toggles } = &field.kind {
            if let Some(t) = toggles.iter().find(|t| &t.id == clicked_id) {
                return FormEvent::ToggleChanged {
                    id: *clicked_id,
                    value: !t.value,
                };
            }
        }
        if let FieldKind::ButtonRow { buttons } = &field.kind {
            if buttons.iter().any(|b| &b.id == clicked_id) {
                return FormEvent::ButtonClicked { id: *clicked_id };
            }
        }
        if let FieldKind::SegmentedControl { .. } = &field.kind {
            let prefix = format!("{}__seg_", field.id.as_str());
            if clicked_id.as_str().starts_with(&prefix) {
                if let Ok(idx) = clicked_id.as_str()[prefix.len()..].parse::<usize>() {
                    return FormEvent::SegmentedControlChanged {
                        id: field.id,
                        selected_idx: idx,
                    };
                }
            }
        }
        if let FieldKind::Toolbar(toolbar) = &field.kind {
            if toolbar.buttons.iter().any(|btn| {
                matches!(btn,
                    crate::primitives::toolbar::ToolbarButton::Action { id, .. }
                    if id == clicked_id
                )
            }) {
                return FormEvent::ToolbarButtonClicked {
                    field_id: field.id,
                    button_id: *clicked_id,
                };
            }
        }
    }
    FormEvent::FocusChanged { id: *clicked_id }
}

// ── Keyboard editing helpers ──────────────────────────────────────────

/// Whether `field` is a Tab stop: not a `Label`, not a non-interactive
/// `ReadOnly` display field, and not disabled. Mirrors
/// `primitives/form.rs`'s module doc ("Tab / Shift-Tab moves
/// focused_field forward/backward through interactive fields (skip
/// Label)") — VS Code, the stated GUI reference, does not focus a
/// read-only row either.
fn field_is_focusable(field: &crate::primitives::form::FormField) -> bool {
    !matches!(field.kind, FieldKind::Label | FieldKind::ReadOnly { .. }) && !field.disabled
}

/// The editable text of a `TextInput` / `TextArea` / `PasswordInput`
/// field, or `None` for every other `FieldKind` (not text-editable).
fn text_field_value(kind: &FieldKind) -> Option<&str> {
    match kind {
        FieldKind::TextInput { value, .. }
        | FieldKind::TextArea { value, .. }
        | FieldKind::PasswordInput { value, .. } => Some(value.as_str()),
        _ => None,
    }
}

/// Starting cursor/selection for a text field that has no cached
/// [`TextEditState`] yet — the field's own `cursor` (defaulting to
/// end-of-text) and `selection_anchor` where the kind carries one.
fn default_text_cursor(kind: &FieldKind) -> (usize, Option<usize>) {
    match kind {
        FieldKind::TextInput {
            value,
            cursor,
            selection_anchor,
            ..
        } => (cursor.unwrap_or(value.len()), *selection_anchor),
        FieldKind::TextArea { value, cursor, .. } => (cursor.unwrap_or(value.len()), None),
        FieldKind::PasswordInput { value, cursor, .. } => (cursor.unwrap_or(value.len()), None),
        _ => (0, None),
    }
}

/// Write `cursor`/`selection_anchor` back onto `kind` for rendering.
/// No-op for `FieldKind` variants with no cursor (anything but the three
/// text-editable kinds).
fn overlay_text_cursor(kind: &mut FieldKind, cursor: usize, selection_anchor: Option<usize>) {
    match kind {
        FieldKind::TextInput {
            cursor: c,
            selection_anchor: a,
            ..
        } => {
            *c = Some(cursor);
            *a = selection_anchor;
        }
        FieldKind::TextArea { cursor: c, .. } | FieldKind::PasswordInput { cursor: c, .. } => {
            *c = Some(cursor);
        }
        _ => {}
    }
}

/// Write `focused`/`visible_month` back onto `kind` for rendering.
/// No-op for every `FieldKind` other than `DatePicker` — mirrors
/// `overlay_text_cursor`'s shape.
fn overlay_date_edit(kind: &mut FieldKind, focused: CalendarDate, visible_month: CalendarDate) {
    if let FieldKind::DatePicker(picker) = kind {
        picker.focused = focused;
        picker.visible_month = visible_month;
    }
}

/// Maps a key to the string name [`crate::primitives::date_picker::DatePicker::navigate`]
/// recognises, or `None` for a key it doesn't act on (e.g. `Tab`, so focus
/// traversal off a `DatePicker` field keeps working in `handle_key`).
fn date_picker_key_name(key: &Key) -> Option<&'static str> {
    match key {
        Key::Named(NamedKey::Left) => Some("Left"),
        Key::Named(NamedKey::Right) => Some("Right"),
        Key::Named(NamedKey::Up) => Some("Up"),
        Key::Named(NamedKey::Down) => Some("Down"),
        Key::Named(NamedKey::PageUp) => Some("PageUp"),
        Key::Named(NamedKey::PageDown) => Some("PageDown"),
        Key::Named(NamedKey::Enter) => Some("Enter"),
        _ => None,
    }
}

/// Byte offset `byte_offset` into `value` (which may contain `'\n'`,
/// e.g. a `TextArea`) → `(line, char_column)`, the coordinate space
/// [`TextEditor`]/[`EditOp`] operate in.
fn byte_offset_to_line_col(value: &str, byte_offset: usize) -> (usize, usize) {
    let byte_offset = byte_offset.min(value.len());
    let prefix = &value[..byte_offset];
    let line = prefix.matches('\n').count();
    let line_start = prefix.rfind('\n').map(|i| i + 1).unwrap_or(0);
    let col = prefix[line_start..].chars().count();
    (line, col)
}

/// Inverse of [`byte_offset_to_line_col`]: `(line, char_column)` →
/// byte offset into `value`.
fn line_col_to_byte_offset(value: &str, line: usize, col: usize) -> usize {
    let mut offset = 0usize;
    for (i, l) in value.split('\n').enumerate() {
        if i == line {
            let take: usize = l.chars().take(col).map(char::len_utf8).sum();
            return offset + take.min(l.len());
        }
        offset += l.len() + 1; // +1 for the '\n' separator consumed between lines
    }
    value.len()
}

/// Route one [`EditOp`] through [`TextEditor::apply`] against a flat
/// `value` + byte-offset `cursor`/`selection_anchor` — the shape every
/// `FieldKind::TextInput`/`TextArea`/`PasswordInput` field uses — and
/// hand back the resulting `(value, cursor, selection_anchor)`.
///
/// `TextEditor` itself works in `(line, char_column)` coordinates (see
/// `text_input.rs`'s module doc), so this wraps `value` in a throwaway
/// single-use [`TextInput`] for the one `apply` call and converts back
/// via [`byte_offset_to_line_col`]/[`line_col_to_byte_offset`] — the
/// conversion this controller owns so every other call site keeps
/// working in the byte-offset space `Form`'s `FieldKind` already
/// documents.
fn apply_text_edit_op(
    value: &str,
    cursor: usize,
    selection_anchor: Option<usize>,
    op: EditOp,
) -> (String, usize, Option<usize>) {
    let lines: Vec<String> = if value.is_empty() {
        vec![String::new()]
    } else {
        value.split('\n').map(str::to_string).collect()
    };
    let (line, col) = byte_offset_to_line_col(value, cursor);
    let input = TextInput::new(WidgetId::new("form-field-edit"))
        .with_lines(lines)
        .with_cursor_line(line)
        .with_cursor_col(col);
    let mut editor = TextEditor::new(input);
    if let Some(anchor_byte) = selection_anchor {
        // `selection_anchor` is app-owned public data (see
        // `primitives/form.rs`'s doc on `FieldKind::TextInput`) and isn't
        // guaranteed to land on a char boundary — snap and clamp it the
        // same way `cursor` already is above, so a bogus byte offset
        // (e.g. an app computing it in char counts) clamps the
        // selection instead of panicking on a mid-char slice.
        let anchor_byte = snap_to_char_boundary(value, anchor_byte.min(value.len()));
        editor.set_selection_anchor(Some(byte_offset_to_line_col(value, anchor_byte)));
    }
    editor.apply(op);

    let new_value = editor.lines.join("\n");
    let new_cursor = line_col_to_byte_offset(&new_value, editor.cursor_line, editor.cursor_col);
    let new_anchor = editor
        .selection_anchor()
        .map(|(l, c)| line_col_to_byte_offset(&new_value, l, c));
    (new_value, new_cursor, new_anchor)
}

// ── Pure helpers (line_height → derived values) ─────────────────────

fn row_height(lh: f32) -> f32 {
    (lh * 1.4).round()
}

fn track_width(lh: f32) -> f32 {
    (lh * 0.4).max(1.0).round()
}

fn viewport_rows_lh(lh: f32, rect: Rect) -> usize {
    if lh <= 0.0 {
        return 0;
    }
    let rh = row_height(lh);
    if rh <= 0.0 {
        return 0;
    }
    (rect.height / rh).floor() as usize
}

fn split_rect_lh(field_count: usize, lh: f32, rect: Rect) -> (Rect, Option<Rect>) {
    let tw = track_width(lh);
    if rect.width <= tw {
        return (rect, None);
    }
    let form_rect = Rect::new(rect.x, rect.y, rect.width - tw, rect.height);
    let vr = viewport_rows_lh(lh, form_rect);
    if field_count <= vr {
        return (rect, None);
    }
    let sb_rect = Rect::new(rect.x + rect.width - tw, rect.y, tw, rect.height);
    (form_rect, Some(sb_rect))
}

fn build_scrollbar_lh(
    id: &str,
    field_count: usize,
    scroll_offset: usize,
    is_dragging: bool,
    lh: f32,
    sb_rect: Rect,
) -> Scrollbar {
    let total = field_count as f32;
    let rh = row_height(lh);
    let visible = if rh > 0.0 {
        (sb_rect.height / rh).floor()
    } else {
        total
    };
    let min_thumb = lh.max(1.0);
    let mut sb = Scrollbar::vertical(
        format!("{id}-scrollbar"),
        sb_rect,
        scroll_offset as f32,
        total,
        visible,
        min_thumb,
    );
    sb.dragging = is_dragging;
    sb
}

fn form_field_measure(
    field: &crate::primitives::form::FormField,
    row_h: f32,
    char_w: f32,
) -> FormFieldMeasure {
    match &field.kind {
        FieldKind::ToggleGroup { toggles } => {
            let label_w = field.label.visible_width() as f32 * char_w;
            let start_x = if label_w > 0.0 {
                label_w + char_w * 2.0
            } else {
                char_w
            };
            let items = toggles
                .iter()
                .map(|t| FormItemMeasure {
                    id: t.id,
                    width: (t.label.chars().count() as f32 + 2.0) * char_w,
                })
                .collect();
            FormFieldMeasure::with_items(row_h, start_x, char_w, items)
        }
        FieldKind::ButtonRow { buttons } => {
            let label_w = field.label.visible_width() as f32 * char_w;
            let start_x = if label_w > 0.0 {
                label_w + char_w * 2.0
            } else {
                char_w
            };
            let items = buttons
                .iter()
                .map(|b| {
                    let icon_w = b
                        .icon
                        .as_ref()
                        .map(|i| {
                            let gw = i.fallback.chars().count() as f32;
                            if b.label.is_empty() {
                                gw
                            } else {
                                gw + 1.0
                            }
                        })
                        .unwrap_or(0.0);
                    FormItemMeasure {
                        id: b.id,
                        width: (b.label.chars().count() as f32 + icon_w + 2.0) * char_w,
                    }
                })
                .collect();
            FormFieldMeasure::with_items(row_h, start_x, char_w, items)
        }
        FieldKind::SegmentedControl { options, .. } => {
            let label_w = field.label.visible_width() as f32 * char_w;
            let start_x = if label_w > 0.0 {
                label_w + char_w * 2.0
            } else {
                char_w
            };
            let items = options
                .iter()
                .enumerate()
                .map(|(idx, opt)| FormItemMeasure {
                    id: WidgetId::new(format!("{}__seg_{idx}", field.id.as_str())),
                    width: (opt.chars().count() as f32 + 2.0) * char_w,
                })
                .collect();
            FormFieldMeasure::with_items(row_h, start_x, 0.0, items)
        }
        FieldKind::TextArea { visible_rows, .. } => {
            FormFieldMeasure::new(row_h * *visible_rows as f32)
        }
        _ => FormFieldMeasure::new(row_h),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::primitives::form::{FieldKind, FormField};
    use crate::types::StyledText;

    fn make_fields(n: usize) -> Vec<FormField> {
        (0..n)
            .map(|i| FormField {
                id: WidgetId::new(format!("field-{i}")),
                label: StyledText::plain(format!("Field {i}")),
                kind: FieldKind::Toggle { value: false },
                hint: StyledText::default(),
                disabled: false,
                validation: None,
            })
            .collect()
    }

    fn make_form(n: usize) -> Form {
        Form {
            id: WidgetId::new("test-form"),
            fields: make_fields(n),
            focused_field: None,
            scroll_offset: 0,
            has_focus: false,
        }
    }

    fn test_controller(field_count: usize) -> FormController {
        let mut fc = FormController::new("test".into());
        fc.set_form(make_form(field_count));
        fc
    }

    // ── Accessors ────────────────────────────────────────────────────

    #[test]
    fn new_starts_empty() {
        let fc = FormController::new("fc".into());
        assert_eq!(fc.scroll_offset(), 0);
        assert!(!fc.has_focus());
        assert!(fc.form().is_none());
        assert_eq!(fc.field_count(), 0);
    }

    #[test]
    fn set_form_and_read_back() {
        let mut fc = FormController::new("fc".into());
        fc.set_form(make_form(5));
        assert!(fc.form().is_some());
        assert_eq!(fc.field_count(), 5);
    }

    #[test]
    fn set_has_focus() {
        let mut fc = FormController::new("fc".into());
        fc.set_has_focus(true);
        assert!(fc.has_focus());
    }

    #[test]
    fn default_form_id() {
        let fc = FormController::new("settings".into());
        assert_eq!(fc.default_form_id().as_str(), "settings-form");
    }

    // ── Scroll-by ───────────────────────────────────────────────────

    #[test]
    fn scroll_by_advances_offset() {
        let mut fc = test_controller(20);
        fc.scroll_by(3, 5);
        assert_eq!(fc.scroll_offset(), 3);
    }

    #[test]
    fn scroll_by_retreats_offset() {
        let mut fc = test_controller(20);
        fc.set_scroll_offset(5);
        fc.scroll_by(-2, 5);
        assert_eq!(fc.scroll_offset(), 3);
    }

    #[test]
    fn scroll_by_clamps_to_bounds() {
        let mut fc = test_controller(10);
        fc.scroll_by(100, 5);
        assert_eq!(fc.scroll_offset(), 5); // 10 - 5
        fc.scroll_by(-100, 5);
        assert_eq!(fc.scroll_offset(), 0);
    }

    // ── Page scroll ─────────────────────────────────────────────────

    #[test]
    fn page_scroll_clamps() {
        let mut fc = test_controller(20);
        fc.page_scroll(100, 5);
        assert_eq!(fc.scroll_offset(), 15); // 20 - 5
        fc.page_scroll(-100, 5);
        assert_eq!(fc.scroll_offset(), 0);
    }

    // ── Scroll-to-field ─────────────────────────────────────────────

    #[test]
    fn scroll_to_field_scrolls_down() {
        let mut fc = test_controller(20);
        fc.scroll_to_field(8, 5);
        assert!(fc.scroll_offset() + 5 > 8);
        assert!(fc.scroll_offset() <= 8);
    }

    #[test]
    fn scroll_to_field_scrolls_up() {
        let mut fc = test_controller(20);
        fc.set_scroll_offset(10);
        fc.scroll_to_field(3, 5);
        assert_eq!(fc.scroll_offset(), 3);
    }

    #[test]
    fn scroll_to_field_noop_when_visible() {
        let mut fc = test_controller(20);
        fc.set_scroll_offset(5);
        fc.scroll_to_field(7, 5);
        assert_eq!(fc.scroll_offset(), 5);
    }

    #[test]
    fn scroll_to_field_noop_with_zero_viewport() {
        let mut fc = test_controller(20);
        fc.scroll_to_field(10, 0);
        assert_eq!(fc.scroll_offset(), 0);
    }

    // ── build_form injects controller state ──────────────────────────

    #[test]
    fn build_form_injects_scroll_offset() {
        let mut fc = test_controller(10);
        fc.set_scroll_offset(3);
        fc.set_has_focus(true);
        let form = fc.build_form(Rect::new(0.0, 0.0, 40.0, 100.0));
        assert_eq!(form.scroll_offset, 3);
        assert!(form.has_focus);
    }

    #[test]
    fn build_form_with_no_data_returns_empty() {
        let fc = FormController::new("empty".into());
        let form = fc.build_form(Rect::new(0.0, 0.0, 40.0, 100.0));
        assert!(form.fields.is_empty());
        assert_eq!(form.id.as_str(), "empty-form");
    }

    // ── form_click_event ────────────────────────────────────────────

    #[test]
    fn click_toggle_flips_value() {
        let form = make_form(3);
        let ev = form_click_event(&form, &WidgetId::new("field-0"));
        assert_eq!(
            ev,
            FormEvent::ToggleChanged {
                id: WidgetId::new("field-0"),
                value: true
            }
        );
    }

    #[test]
    fn click_button_emits_button_clicked() {
        let mut form = make_form(3);
        form.fields[1].kind = FieldKind::Button;
        let ev = form_click_event(&form, &WidgetId::new("field-1"));
        assert_eq!(
            ev,
            FormEvent::ButtonClicked {
                id: WidgetId::new("field-1")
            }
        );
    }

    #[test]
    fn click_text_input_emits_focus_changed() {
        let mut form = make_form(3);
        form.fields[2].kind = FieldKind::TextInput {
            value: "hello".into(),
            placeholder: String::new(),
            cursor: None,
            selection_anchor: None,
        };
        let ev = form_click_event(&form, &WidgetId::new("field-2"));
        assert_eq!(
            ev,
            FormEvent::FocusChanged {
                id: WidgetId::new("field-2")
            }
        );
    }

    #[test]
    fn click_unknown_id_emits_focus_changed() {
        let form = make_form(3);
        let ev = form_click_event(&form, &WidgetId::new("unknown"));
        assert_eq!(
            ev,
            FormEvent::FocusChanged {
                id: WidgetId::new("unknown")
            }
        );
    }

    #[test]
    fn click_toolbar_button_emits_toolbar_button_clicked() {
        use crate::primitives::toolbar::{Toolbar, ToolbarButton};
        let mut form = make_form(1);
        form.fields[0].kind = FieldKind::Toolbar(Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![
                ToolbarButton::Action {
                    id: WidgetId::new("reset"),
                    label: "Reset".into(),
                    icon: None,
                    key_hint: None,
                    enabled: true,
                    is_active: false,
                    tooltip: String::new(),
                },
                ToolbarButton::Action {
                    id: WidgetId::new("export"),
                    label: "Export".into(),
                    icon: None,
                    key_hint: None,
                    enabled: true,
                    is_active: false,
                    tooltip: String::new(),
                },
            ],
            bg: None,
            focused_index: None,
        });

        // Clicking the first button should emit ToolbarButtonClicked with
        // the owning field_id and the button_id.
        let ev = form_click_event(&form, &WidgetId::new("reset"));
        assert_eq!(
            ev,
            FormEvent::ToolbarButtonClicked {
                field_id: WidgetId::new("field-0"),
                button_id: WidgetId::new("reset"),
            },
            "clicking 'reset' should emit ToolbarButtonClicked"
        );

        // Clicking the second button should emit ToolbarButtonClicked too.
        let ev2 = form_click_event(&form, &WidgetId::new("export"));
        assert_eq!(
            ev2,
            FormEvent::ToolbarButtonClicked {
                field_id: WidgetId::new("field-0"),
                button_id: WidgetId::new("export"),
            },
            "clicking 'export' should emit ToolbarButtonClicked"
        );
    }

    #[test]
    fn click_toolbar_disabled_button_still_emits_toolbar_button_clicked() {
        // A click on a disabled action still routes through form_click_event
        // (the primitive layout marks it non-clickable, so the hit won't
        // fire in practice). But if a caller does pass a disabled action id
        // in, we should still recover the field_id correctly.
        use crate::primitives::toolbar::{Toolbar, ToolbarButton};
        let mut form = make_form(1);
        form.fields[0].kind = FieldKind::Toolbar(Toolbar {
            id: WidgetId::new("tb"),
            buttons: vec![ToolbarButton::Action {
                id: WidgetId::new("noop"),
                label: "Noop".into(),
                icon: None,
                key_hint: None,
                enabled: false,
                is_active: false,
                tooltip: String::new(),
            }],
            bg: None,
            focused_index: None,
        });

        // form_click_event matches by id, not by enabled state.
        let ev = form_click_event(&form, &WidgetId::new("noop"));
        assert_eq!(
            ev,
            FormEvent::ToolbarButtonClicked {
                field_id: WidgetId::new("field-0"),
                button_id: WidgetId::new("noop"),
            }
        );
    }

    // ── Empty-form edge cases ────────────────────────────────────────

    #[test]
    fn scroll_by_on_empty_is_noop() {
        let mut fc = FormController::new("fc".into());
        fc.scroll_by(5, 10);
        assert_eq!(fc.scroll_offset(), 0);
    }

    // ── handle_cached ───────────────────────────────────────────────

    #[test]
    fn handle_cached_returns_ignored_without_backend_info() {
        let mut fc = test_controller(20);
        let ev = fc.handle_cached(
            &UiEvent::Scroll {
                widget: None,
                delta: crate::ScrollDelta { x: 0.0, y: 1.0 },
                position: crate::Point { x: 5.0, y: 5.0 },
            },
            Rect::new(0.0, 0.0, 40.0, 10.0),
        );
        assert_eq!(ev, FormControllerEvent::Ignored);
    }

    #[test]
    fn handle_cached_scroll_works_after_set_backend_info() {
        let mut fc = test_controller(20);
        // TUI: lh=1.0, row_h=1.0, rect height=5 → 5 viewport rows
        fc.set_backend_info(1.0);
        let ev = fc.handle_cached(
            &UiEvent::Scroll {
                widget: None,
                delta: crate::ScrollDelta { x: 0.0, y: -1.0 },
                position: crate::Point { x: 5.0, y: 2.0 },
            },
            Rect::new(0.0, 0.0, 40.0, 5.0),
        );
        assert_eq!(ev, FormControllerEvent::Consumed);
        assert_eq!(fc.scroll_offset(), 1);
    }

    #[test]
    fn handle_cached_scroll_consumes_the_delta_magnitude_not_just_its_sign() {
        let mut fc = test_controller(20);
        fc.set_backend_info(1.0);
        let ev = fc.handle_cached(
            &UiEvent::Scroll {
                widget: None,
                delta: crate::ScrollDelta { x: 0.0, y: -3.0 },
                position: crate::Point { x: 5.0, y: 2.0 },
            },
            Rect::new(0.0, 0.0, 40.0, 5.0),
        );
        assert_eq!(ev, FormControllerEvent::Consumed);
        assert_eq!(fc.scroll_offset(), 3);
    }

    #[test]
    fn handle_cached_click_uses_fallback_layout() {
        let mut fc = test_controller(3);
        fc.set_backend_info(1.0);
        let ev = fc.handle_cached(
            &UiEvent::MouseDown {
                widget: None,
                button: MouseButton::Left,
                position: crate::Point { x: 5.0, y: 0.5 },
                modifiers: Default::default(),
            },
            Rect::new(0.0, 0.0, 40.0, 5.0),
        );
        match ev {
            FormControllerEvent::FormAction(FormEvent::ToggleChanged { id, value }) => {
                assert_eq!(id.as_str(), "field-0");
                assert!(value);
            }
            other => panic!("expected FormAction(ToggleChanged), got {other:?}"),
        }
    }

    // ── Pure helper tests ───────────────────────────────────────────

    #[test]
    fn viewport_rows_lh_tui() {
        // TUI: lh=1.0, row_h=round(1.4)=1.0, height=10 → 10 rows
        assert_eq!(viewport_rows_lh(1.0, Rect::new(0.0, 0.0, 40.0, 10.0)), 10);
    }

    #[test]
    fn viewport_rows_lh_gtk() {
        // GTK: lh=20.0, row_h=round(28.0)=28.0, height=280 → 10 rows
        assert_eq!(
            viewport_rows_lh(20.0, Rect::new(0.0, 0.0, 400.0, 280.0)),
            10
        );
    }

    #[test]
    fn split_rect_lh_no_scrollbar_when_fits() {
        let (form_rect, sb) = split_rect_lh(5, 1.0, Rect::new(0.0, 0.0, 40.0, 10.0));
        assert!(sb.is_none());
        assert_eq!(form_rect.width, 40.0);
    }

    #[test]
    fn split_rect_lh_scrollbar_when_overflows() {
        let (form_rect, sb) = split_rect_lh(20, 1.0, Rect::new(0.0, 0.0, 40.0, 10.0));
        assert!(sb.is_some());
        assert!(form_rect.width < 40.0);
    }

    // ── Keyboard editing ───────────────────────────────────────────

    fn key_event(key: Key, modifiers: Modifiers) -> UiEvent {
        UiEvent::KeyPressed {
            key,
            modifiers,
            repeat: false,
        }
    }

    fn shift() -> Modifiers {
        Modifiers {
            shift: true,
            ..Default::default()
        }
    }

    fn text_field(id: &str, value: &str, cursor: Option<usize>) -> FormField {
        FormField {
            id: WidgetId::new(id),
            label: StyledText::plain("Label"),
            kind: FieldKind::TextInput {
                value: value.to_string(),
                placeholder: String::new(),
                cursor,
                selection_anchor: None,
            },
            hint: StyledText::default(),
            disabled: false,
            validation: None,
        }
    }

    fn label_field(id: &str) -> FormField {
        FormField {
            id: WidgetId::new(id),
            label: StyledText::plain("Header"),
            kind: FieldKind::Label,
            hint: StyledText::default(),
            disabled: false,
            validation: None,
        }
    }

    fn toggle_field(id: &str, disabled: bool) -> FormField {
        FormField {
            id: WidgetId::new(id),
            label: StyledText::plain("On"),
            kind: FieldKind::Toggle { value: false },
            hint: StyledText::default(),
            disabled,
            validation: None,
        }
    }

    fn date_field(id: &str, focused: CalendarDate, disabled: bool) -> FormField {
        FormField {
            id: WidgetId::new(id),
            label: StyledText::plain("Date"),
            kind: FieldKind::DatePicker(crate::primitives::date_picker::DatePicker::new(
                WidgetId::new(id),
                focused,
            )),
            hint: StyledText::default(),
            disabled,
            validation: None,
        }
    }

    fn controller_with(fields: Vec<FormField>, focused: Option<&str>) -> FormController {
        let mut fc = FormController::new("f".into());
        fc.set_form(Form {
            id: WidgetId::new("form"),
            fields,
            focused_field: focused.map(WidgetId::new),
            scroll_offset: 0,
            has_focus: true,
        });
        // The controller's own `has_focus` gates `KeyPressed`/`CharTyped`/
        // `ClipboardPaste` (not `Form.has_focus` above, which only
        // affects rendering) — these keyboard-editing tests need it set.
        fc.set_has_focus(true);
        fc.set_backend_info(1.0);
        fc
    }

    const RECT: Rect = Rect::new(0.0, 0.0, 40.0, 10.0);

    #[test]
    fn tab_moves_focus_to_first_focusable_field_skipping_label() {
        let mut fc = controller_with(
            vec![
                label_field("hdr"),
                text_field("name", "", None),
                toggle_field("tgl", false),
            ],
            None,
        );
        let ev = fc.handle_cached(
            &key_event(Key::Named(NamedKey::Tab), Modifiers::default()),
            RECT,
        );
        assert_eq!(
            ev,
            FormControllerEvent::FormAction(FormEvent::FocusChanged {
                id: WidgetId::new("name")
            })
        );
    }

    #[test]
    fn tab_advances_and_wraps_around() {
        let mut fc = controller_with(
            vec![text_field("a", "", None), toggle_field("b", false)],
            Some("b"),
        );
        let ev = fc.handle_cached(
            &key_event(Key::Named(NamedKey::Tab), Modifiers::default()),
            RECT,
        );
        assert_eq!(
            ev,
            FormControllerEvent::FormAction(FormEvent::FocusChanged {
                id: WidgetId::new("a")
            }),
            "tab from the last field should wrap to the first"
        );
    }

    #[test]
    fn shift_tab_retreats_and_wraps() {
        let mut fc = controller_with(
            vec![text_field("a", "", None), toggle_field("b", false)],
            Some("a"),
        );
        let ev = fc.handle_cached(&key_event(Key::Named(NamedKey::Tab), shift()), RECT);
        assert_eq!(
            ev,
            FormControllerEvent::FormAction(FormEvent::FocusChanged {
                id: WidgetId::new("b")
            }),
            "shift+tab from the first field should wrap to the last"
        );
    }

    #[test]
    fn back_tab_also_retreats() {
        let mut fc = controller_with(
            vec![text_field("a", "", None), toggle_field("b", false)],
            Some("b"),
        );
        let ev = fc.handle_cached(
            &key_event(Key::Named(NamedKey::BackTab), Modifiers::default()),
            RECT,
        );
        assert_eq!(
            ev,
            FormControllerEvent::FormAction(FormEvent::FocusChanged {
                id: WidgetId::new("a")
            })
        );
    }

    #[test]
    fn tab_skips_disabled_field() {
        let mut fc = controller_with(
            vec![
                text_field("a", "", None),
                toggle_field("disabled-tgl", true),
                toggle_field("c", false),
            ],
            Some("a"),
        );
        let ev = fc.handle_cached(
            &key_event(Key::Named(NamedKey::Tab), Modifiers::default()),
            RECT,
        );
        assert_eq!(
            ev,
            FormControllerEvent::FormAction(FormEvent::FocusChanged {
                id: WidgetId::new("c")
            }),
            "tab should skip the disabled field entirely"
        );
    }

    #[test]
    fn typing_char_appends_and_updates_value() {
        let mut fc = controller_with(vec![text_field("name", "ab", Some(2))], Some("name"));
        let ev = fc.handle_cached(&key_event(Key::Char('c'), Modifiers::default()), RECT);
        assert_eq!(
            ev,
            FormControllerEvent::FormAction(FormEvent::TextInputChanged {
                id: WidgetId::new("name"),
                value: "abc".to_string(),
            })
        );
    }

    #[test]
    fn cursor_persists_across_keystrokes_even_if_app_never_echoes_it_back() {
        let mut fc = controller_with(vec![text_field("name", "ab", Some(2))], Some("name"));
        let ev1 = fc.handle_cached(&key_event(Key::Char('c'), Modifiers::default()), RECT);
        assert_eq!(
            ev1,
            FormControllerEvent::FormAction(FormEvent::TextInputChanged {
                id: WidgetId::new("name"),
                value: "abc".to_string(),
            })
        );

        // The app updates `value` per the emitted event but — as the
        // issue requires — never tracks `cursor` itself; it stays `None`.
        fc.set_form(Form {
            id: WidgetId::new("form"),
            fields: vec![text_field("name", "abc", None)],
            focused_field: Some(WidgetId::new("name")),
            scroll_offset: 0,
            has_focus: true,
        });

        let ev2 = fc.handle_cached(&key_event(Key::Char('d'), Modifiers::default()), RECT);
        assert_eq!(
            ev2,
            FormControllerEvent::FormAction(FormEvent::TextInputChanged {
                id: WidgetId::new("name"),
                value: "abcd".to_string(),
            }),
            "the controller's cached cursor (after 'c') should carry over, \
             appending 'd' at the end rather than re-deriving a stale position"
        );
    }

    #[test]
    fn backspace_deletes_char_before_cursor() {
        let mut fc = controller_with(vec![text_field("name", "abc", Some(3))], Some("name"));
        let ev = fc.handle_cached(
            &key_event(Key::Named(NamedKey::Backspace), Modifiers::default()),
            RECT,
        );
        assert_eq!(
            ev,
            FormControllerEvent::FormAction(FormEvent::TextInputChanged {
                id: WidgetId::new("name"),
                value: "ab".to_string(),
            })
        );
    }

    #[test]
    fn enter_commits_text_field_instead_of_inserting_newline() {
        let mut fc = controller_with(vec![text_field("name", "hello", Some(5))], Some("name"));
        let ev = fc.handle_cached(
            &key_event(Key::Named(NamedKey::Enter), Modifiers::default()),
            RECT,
        );
        assert_eq!(
            ev,
            FormControllerEvent::FormAction(FormEvent::TextInputCommitted {
                id: WidgetId::new("name"),
                value: "hello".to_string(),
            })
        );
    }

    #[test]
    fn char_typed_event_also_inserts_into_the_focused_field() {
        let mut fc = controller_with(vec![text_field("name", "", None)], Some("name"));
        let ev = fc.handle_cached(&UiEvent::CharTyped('x'), RECT);
        assert_eq!(
            ev,
            FormControllerEvent::FormAction(FormEvent::TextInputChanged {
                id: WidgetId::new("name"),
                value: "x".to_string(),
            })
        );
    }

    #[test]
    fn disabled_text_field_ignores_keystrokes() {
        let mut fc = controller_with(
            vec![FormField {
                id: WidgetId::new("name"),
                label: StyledText::plain("Name"),
                kind: FieldKind::TextInput {
                    value: "ab".to_string(),
                    placeholder: String::new(),
                    cursor: Some(2),
                    selection_anchor: None,
                },
                hint: StyledText::default(),
                disabled: true,
                validation: None,
            }],
            Some("name"),
        );
        let ev = fc.handle_cached(&key_event(Key::Char('c'), Modifiers::default()), RECT);
        assert_eq!(ev, FormControllerEvent::Ignored);
    }

    #[test]
    fn no_focused_field_ignores_text_keys() {
        let mut fc = controller_with(vec![text_field("name", "ab", Some(2))], None);
        let ev = fc.handle_cached(&key_event(Key::Char('c'), Modifiers::default()), RECT);
        assert_eq!(ev, FormControllerEvent::Ignored);
    }

    #[test]
    fn shift_left_then_char_replaces_the_selection() {
        // "ab|c" (cursor after 'b') — shift+Left selects "b", typing 'X'
        // replaces the selection (EditOp::InsertChar's documented
        // selection-replace behaviour), landing on "aXc".
        let mut fc = controller_with(vec![text_field("name", "abc", Some(2))], Some("name"));
        let ev1 = fc.handle_cached(&key_event(Key::Named(NamedKey::Left), shift()), RECT);
        assert_eq!(
            ev1,
            FormControllerEvent::Consumed,
            "pure cursor/selection movement changes no text, so it's Consumed not a FormEvent"
        );

        let ev2 = fc.handle_cached(&key_event(Key::Char('X'), Modifiers::default()), RECT);
        assert_eq!(
            ev2,
            FormControllerEvent::FormAction(FormEvent::TextInputChanged {
                id: WidgetId::new("name"),
                value: "aXc".to_string(),
            })
        );
    }

    #[test]
    fn build_form_overlays_the_cached_cursor_for_rendering() {
        let mut fc = controller_with(vec![text_field("name", "ab", Some(2))], Some("name"));
        fc.handle_cached(&key_event(Key::Char('c'), Modifiers::default()), RECT);

        // Realistic round-trip: the app persists `value` from the
        // emitted `TextInputChanged` (same as it already does for a
        // toggle flip) but — per this module's "Keyboard editing" doc
        // section — never has to track `cursor` itself, so it stays
        // `None` here.
        fc.set_form(Form {
            id: WidgetId::new("form"),
            fields: vec![text_field("name", "abc", None)],
            focused_field: Some(WidgetId::new("name")),
            scroll_offset: 0,
            has_focus: true,
        });

        let rendered = fc.build_form(RECT);
        match &rendered.fields[0].kind {
            FieldKind::TextInput { value, cursor, .. } => {
                assert_eq!(value, "abc");
                assert_eq!(
                    *cursor,
                    Some(3),
                    "controller-cached cursor should overlay the app's \
                     None, sitting after the just-typed 'c'"
                );
            }
            other => panic!("expected TextInput, got {other:?}"),
        }
    }

    #[test]
    fn text_area_newline_round_trips_through_byte_offset_conversion() {
        // TextArea's `value` embeds '\n' directly — exercise the
        // multi-line byte_offset_to_line_col / line_col_to_byte_offset
        // conversion, not just the single-line TextInput path.
        let field = FormField {
            id: WidgetId::new("notes"),
            label: StyledText::plain("Notes"),
            kind: FieldKind::TextArea {
                value: "line one\nline two".to_string(),
                placeholder: String::new(),
                cursor: Some("line one\n".len()), // start of "line two"
                visible_rows: 3,
            },
            hint: StyledText::default(),
            disabled: false,
            validation: None,
        };
        let mut fc = controller_with(vec![field], Some("notes"));
        let ev = fc.handle_cached(&key_event(Key::Char('X'), Modifiers::default()), RECT);
        assert_eq!(
            ev,
            FormControllerEvent::FormAction(FormEvent::TextInputChanged {
                id: WidgetId::new("notes"),
                value: "line one\nXline two".to_string(),
            })
        );
    }

    fn ctrl() -> Modifiers {
        Modifiers {
            ctrl: true,
            ..Default::default()
        }
    }

    fn cmd() -> Modifiers {
        Modifiers {
            cmd: true,
            ..Default::default()
        }
    }

    #[test]
    fn ctrl_c_on_a_focused_text_field_is_ignored_not_typed() {
        // Every backend delivers Ctrl+C as `Key::Char('c')` with
        // `modifiers.ctrl == true` (see this module's "Keyboard editing"
        // doc section) — without the guard in `handle_key`, this would
        // insert a literal 'c' into the field *and* report
        // `TextInputChanged`, i.e. the keystroke was "consumed" as text
        // instead of falling through to an app-level Copy accelerator.
        let mut fc = controller_with(vec![text_field("name", "ab", Some(2))], Some("name"));
        let ev = fc.handle_cached(&key_event(Key::Char('c'), ctrl()), RECT);
        assert_eq!(ev, FormControllerEvent::Ignored);
        // The value is genuinely untouched, not just the return value.
        match &fc.form().unwrap().fields[0].kind {
            FieldKind::TextInput { value, .. } => assert_eq!(value, "ab"),
            other => panic!("expected TextInput, got {other:?}"),
        }
    }

    #[test]
    fn cmd_s_on_a_focused_text_field_is_ignored_not_typed() {
        // Same guard, macOS's modifier.
        let mut fc = controller_with(vec![text_field("name", "ab", Some(2))], Some("name"));
        let ev = fc.handle_cached(&key_event(Key::Char('s'), cmd()), RECT);
        assert_eq!(ev, FormControllerEvent::Ignored);
    }

    #[test]
    fn selection_anchor_mid_multibyte_char_snaps_instead_of_panicking() {
        // `selection_anchor` is app-owned public data (`primitives/form.rs`
        // documents it as "a byte offset into `value`") and isn't
        // guaranteed to land on a char boundary — e.g. an app that
        // accidentally computes it in char counts instead of bytes.
        // `byte_offset_to_line_col` slices `value[..byte_offset]`, which
        // would panic on a non-boundary offset into "h\u{e9}llo" (byte 2
        // is the second byte of the two-byte 'é').
        let field = FormField {
            id: WidgetId::new("name"),
            label: StyledText::plain("Name"),
            kind: FieldKind::TextInput {
                value: "h\u{e9}llo".to_string(),
                placeholder: String::new(),
                cursor: Some(5),
                selection_anchor: Some(2), // mid-char: not a valid boundary
            },
            hint: StyledText::default(),
            disabled: false,
            validation: None,
        };
        let mut fc = controller_with(vec![field], Some("name"));
        // Must not panic. `EditOp::MoveRight` with `extend: false` drops
        // the selection, so the exact resulting event only needs to be
        // some non-panicking outcome — the regression is the absence of
        // a panic, not this particular value.
        let _ = fc.handle_cached(
            &key_event(Key::Named(NamedKey::Right), Modifiers::default()),
            RECT,
        );
    }

    // ── DatePicker routing ──────────────────────────────────────────

    #[test]
    fn right_arrow_moves_date_picker_focus_and_is_consumed_not_a_form_action() {
        let start = CalendarDate::new(2024, 3, 15);
        let mut fc = controller_with(vec![date_field("d", start, false)], Some("d"));
        let ev = fc.handle_cached(
            &key_event(Key::Named(NamedKey::Right), Modifiers::default()),
            RECT,
        );
        assert_eq!(
            ev,
            FormControllerEvent::Consumed,
            "pure focus-day movement changes no persisted value, so it's \
             Consumed not a FormEvent, mirroring text cursor movement"
        );
        let form = fc.build_form(RECT);
        match &form.fields[0].kind {
            FieldKind::DatePicker(picker) => {
                assert_eq!(picker.focused, start.add_days(1));
            }
            other => panic!("expected DatePicker, got {other:?}"),
        }
    }

    #[test]
    fn cached_focused_date_persists_across_keystrokes_even_if_app_never_echoes_it_back() {
        let start = CalendarDate::new(2024, 3, 15);
        let mut fc = controller_with(vec![date_field("d", start, false)], Some("d"));
        fc.handle_cached(
            &key_event(Key::Named(NamedKey::Right), Modifiers::default()),
            RECT,
        );

        // The app never tracks `focused` itself (per `DateEditState`'s
        // doc) — it stays at `start` here, exactly as the field was
        // first pushed.
        fc.set_form(Form {
            id: WidgetId::new("form"),
            fields: vec![date_field("d", start, false)],
            focused_field: Some(WidgetId::new("d")),
            scroll_offset: 0,
            has_focus: true,
        });

        let ev2 = fc.handle_cached(
            &key_event(Key::Named(NamedKey::Right), Modifiers::default()),
            RECT,
        );
        assert_eq!(ev2, FormControllerEvent::Consumed);
        let form = fc.build_form(RECT);
        match &form.fields[0].kind {
            FieldKind::DatePicker(picker) => assert_eq!(
                picker.focused,
                start.add_days(2),
                "the controller's cached focused day should carry over, \
                 landing two days forward rather than re-deriving a stale position"
            ),
            other => panic!("expected DatePicker, got {other:?}"),
        }
    }

    #[test]
    fn enter_confirms_the_cached_focused_date_and_clears_the_cache() {
        let start = CalendarDate::new(2024, 3, 15);
        let mut fc = controller_with(vec![date_field("d", start, false)], Some("d"));
        fc.handle_cached(
            &key_event(Key::Named(NamedKey::Right), Modifiers::default()),
            RECT,
        );
        let ev = fc.handle_cached(
            &key_event(Key::Named(NamedKey::Enter), Modifiers::default()),
            RECT,
        );
        assert_eq!(
            ev,
            FormControllerEvent::FormAction(FormEvent::DateChanged {
                id: WidgetId::new("d"),
                value: start.add_days(1),
            })
        );

        // The cache clears on confirm, so re-rendering the app's
        // untouched field (still `start`) shows `start` again, not the
        // confirmed day — the app is expected to push the new value
        // back via `set_form` itself.
        let form = fc.build_form(RECT);
        match &form.fields[0].kind {
            FieldKind::DatePicker(picker) => assert_eq!(picker.focused, start),
            other => panic!("expected DatePicker, got {other:?}"),
        }
    }

    #[test]
    fn disabled_date_picker_field_ignores_navigation_keys() {
        let start = CalendarDate::new(2024, 3, 15);
        let mut fc = controller_with(vec![date_field("d", start, true)], Some("d"));
        let ev = fc.handle_cached(
            &key_event(Key::Named(NamedKey::Right), Modifiers::default()),
            RECT,
        );
        assert_eq!(ev, FormControllerEvent::Ignored);
    }

    #[test]
    fn tab_moves_focus_away_from_a_focused_date_picker_field_normally() {
        let start = CalendarDate::new(2024, 3, 15);
        let mut fc = controller_with(
            vec![date_field("d", start, false), toggle_field("t", false)],
            Some("d"),
        );
        let ev = fc.handle_cached(
            &key_event(Key::Named(NamedKey::Tab), Modifiers::default()),
            RECT,
        );
        assert_eq!(
            ev,
            FormControllerEvent::FormAction(FormEvent::FocusChanged {
                id: WidgetId::new("t")
            }),
            "Tab isn't one of DatePicker's claimed keys, so focus traversal \
             off a focused DatePicker field still works"
        );
    }

    #[test]
    fn date_edit_cache_resets_when_focus_moves_to_a_different_date_picker_field() {
        let d1_start = CalendarDate::new(2024, 3, 15);
        let d2_start = CalendarDate::new(2024, 6, 1);
        let mut fc = controller_with(
            vec![
                date_field("d1", d1_start, false),
                date_field("d2", d2_start, false),
            ],
            Some("d1"),
        );
        fc.handle_cached(
            &key_event(Key::Named(NamedKey::Right), Modifiers::default()),
            RECT,
        );
        fc.handle_cached(
            &key_event(Key::Named(NamedKey::Tab), Modifiers::default()),
            RECT,
        );

        // `move_focus` only emits `FocusChanged` — per this module's
        // "Keyboard editing" doc section, the app persists the new
        // `focused_field` itself, same as it would for a toggle flip.
        fc.set_form(Form {
            id: WidgetId::new("form"),
            fields: vec![
                date_field("d1", d1_start, false),
                date_field("d2", d2_start, false),
            ],
            focused_field: Some(WidgetId::new("d2")),
            scroll_offset: 0,
            has_focus: true,
        });

        let ev = fc.handle_cached(
            &key_event(Key::Named(NamedKey::Right), Modifiers::default()),
            RECT,
        );
        assert_eq!(ev, FormControllerEvent::Consumed);
        let form = fc.build_form(RECT);
        match &form.fields[1].kind {
            FieldKind::DatePicker(picker) => assert_eq!(
                picker.focused,
                d2_start.add_days(1),
                "moving focus to d2 should seed its own focused day, not \
                 carry over d1's cached scrubbing position"
            ),
            other => panic!("expected DatePicker, got {other:?}"),
        }
    }

    #[test]
    fn build_form_shows_live_scrub_position_over_a_confirmed_selected_date() {
        let start = CalendarDate::new(2024, 3, 15);
        let field_with_selected = |selected: CalendarDate| {
            let mut f = date_field("d", start, false);
            if let FieldKind::DatePicker(picker) = &mut f.kind {
                picker.selected = Some(selected);
            }
            f
        };
        let mut fc = controller_with(vec![field_with_selected(start)], Some("d"));

        // Scrub past the already-confirmed date. The renderer (see the
        // "Date picker fields" doc section above) picks `focused` over
        // `selected` while the row is focused, so this must advance
        // `focused` without touching `selected`.
        let ev = fc.handle_cached(
            &key_event(Key::Named(NamedKey::Right), Modifiers::default()),
            RECT,
        );
        assert_eq!(ev, FormControllerEvent::Consumed);

        let form = fc.build_form(RECT);
        match &form.fields[0].kind {
            FieldKind::DatePicker(picker) => {
                assert_eq!(
                    picker.selected,
                    Some(start),
                    "scrubbing must not touch the app's confirmed value"
                );
                assert_eq!(
                    picker.focused,
                    start.add_days(1),
                    "the live scrub position must be exposed via `focused` \
                     even once a date has already been confirmed, so the \
                     renderer doesn't show a frozen `selected` instead"
                );
            }
            other => panic!("expected DatePicker, got {other:?}"),
        }
    }

    #[test]
    fn ctrl_modified_date_picker_key_falls_through_instead_of_navigating() {
        let start = CalendarDate::new(2024, 3, 15);
        let mut fc = controller_with(vec![date_field("d", start, false)], Some("d"));
        let ev = fc.handle_cached(
            &key_event(
                Key::Named(NamedKey::Right),
                Modifiers {
                    ctrl: true,
                    ..Modifiers::default()
                },
            ),
            RECT,
        );
        assert_eq!(
            ev,
            FormControllerEvent::Ignored,
            "Ctrl+Right is a host accelerator candidate, not calendar \
             navigation, so it must not be swallowed by the DatePicker"
        );
        let form = fc.build_form(RECT);
        match &form.fields[0].kind {
            FieldKind::DatePicker(picker) => {
                assert_eq!(picker.focused, start, "the calendar must not have moved")
            }
            other => panic!("expected DatePicker, got {other:?}"),
        }
    }

    #[test]
    fn build_form_does_not_overlay_a_stale_cached_scrub_onto_an_unfocused_date_picker() {
        let d1_start = CalendarDate::new(2024, 3, 15);
        let d2_start = CalendarDate::new(2024, 6, 1);
        let mut fc = controller_with(
            vec![
                date_field("d1", d1_start, false),
                date_field("d2", d2_start, false),
            ],
            Some("d1"),
        );
        fc.handle_cached(
            &key_event(Key::Named(NamedKey::Right), Modifiers::default()),
            RECT,
        );

        // Move focus to "d2" by a click rather than Tab — unlike
        // `move_focus`, `click_inner`'s path to `FormEvent::FocusChanged`
        // doesn't reseed/clear the cached scrub on "d1", so this is the
        // scenario where a stale `date_edit` could otherwise leak.
        fc.set_form(Form {
            id: WidgetId::new("form"),
            fields: vec![
                date_field("d1", d1_start, false),
                date_field("d2", d2_start, false),
            ],
            focused_field: Some(WidgetId::new("d2")),
            scroll_offset: 0,
            has_focus: true,
        });

        let form = fc.build_form(RECT);
        match &form.fields[0].kind {
            FieldKind::DatePicker(picker) => assert_eq!(
                picker.focused, d1_start,
                "the stale cached scrub for \"d1\" must not be overlaid \
                 once focus has moved to \"d2\""
            ),
            other => panic!("expected DatePicker, got {other:?}"),
        }
    }
}