quadraui 0.6.1

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
//! `Form` primitive: a vertical stack of labeled field rows for settings
//! pages, dialogs, connection-config screens, and any other
//! "fill-in-the-fields" UI.
//!
//! A `Form` describes a sequence of `FormField`s. Each field has a
//! stable `WidgetId` (so events carry the field identity back to the
//! app), an optional `label` (rendered to the left of the input), and
//! a `FieldKind` that determines how it's drawn and what events it emits.
//!
//! Field state (toggle values, text content, focus) is owned by the
//! description — the app rebuilds the `Form` each frame from its own
//! canonical state. The primitive does not retain field values between
//! frames. (Scroll offset, if added later, follows the same
//! primitive-owned-via-WidgetId pattern as `TreeView`.)
//!
//! This module is paint/layout/hit-test only — it has no `UiEvent`
//! handling of its own (there is no `Form::handle`). Keyboard editing
//! and Tab/Shift-Tab focus traversal are implemented one layer up, in
//! [`crate::compose::form_controller::FormController`]:
//! route every event through `FormController::handle`/`handle_cached`
//! and both "just work" with no app-side key decoding. The *shape* of
//! what gets emitted — described below — is still owned by this module,
//! since `FormEvent` lives here.
//!
//! # Backend contract
//!
//! **Mostly declarative.** Render fields top-to-bottom from
//! `fields[scroll_offset..]`. Per-field rendering depends on `FieldKind`:
//!
//! - `Toggle` — checkbox / switch UI; click flips value, emit
//!   `FormEvent::ToggleChanged`.
//! - `TextInput` — render text + cursor + selection; a consumer going
//!   through `FormController` gets keystroke routing for free (see this
//!   module's doc above); emits `FormEvent::TextInputChanged` per
//!   keystroke and `TextInputCommitted` on Enter.
//! - `Button` — render label, click emits `FormEvent::ButtonClicked`.
//! - `Label` — non-interactive header / divider.
//! - `DatePicker` — render the focused/selected date as a compact
//!   single-line summary (the row stays one `row_h` tall like every
//!   other field); a consumer going through `FormController` gets
//!   arrow/page-key day/month navigation and Enter-to-confirm for free,
//!   emitting `FormEvent::DateChanged` on confirm.
//!
//! Tab / Shift-Tab move `focused_field` forward/backward through
//! interactive fields (skip `Label`, skip disabled fields); emit
//! `FormEvent::FocusChanged { id }`. The *app* updates `focused_field`
//! on the next frame — `FormController` computes `id`, it does not
//! mutate `Form.focused_field` itself (the description stays app-owned,
//! per this module's first paragraph).
//!
//! No measurement-dependent state — fields are uniform-height per
//! backend.

use crate::event::Rect;
use crate::types::{Modifiers, StyledText, WidgetId};
use serde::{Deserialize, Serialize};

/// Declarative description of a `Form` widget.
///
/// Note: `Eq` is not derivable because `FieldKind::Slider` carries
/// `f32` values. Apps should not put `Form` into hash maps or use
/// struct equality for state diffing — compare field IDs and
/// individual values instead.
///
/// # Examples
///
/// ```
/// use quadraui::{FieldKind, Form, FormField, FormFieldMeasure, FormHit, StyledText, WidgetId};
///
/// let form = Form {
///     id: WidgetId::new("form:settings"),
///     fields: vec![FormField {
///         id: WidgetId::new("form:word_wrap"),
///         label: StyledText::plain("Word wrap"),
///         kind: FieldKind::Toggle { value: true },
///         hint: StyledText::plain(""),
///         disabled: false,
///         validation: None,
///     }],
///     focused_field: None,
///     scroll_offset: 0,
///     has_focus: true,
/// };
///
/// let layout = form.layout(40.0, 10.0, |_| FormFieldMeasure::new(1.0));
/// assert_eq!(
///     layout.hit_test(0.0, 0.0),
///     FormHit::Field(WidgetId::new("form:word_wrap"))
/// );
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Form {
    pub id: WidgetId,
    pub fields: Vec<FormField>,
    /// `WidgetId` of the field that currently has keyboard focus, or
    /// `None` if the form as a whole has focus but no field is active.
    pub focused_field: Option<WidgetId>,
    /// How many rows have been scrolled past. App-owned for now; a
    /// later primitive stage may lift this into `ScrollState` keyed by
    /// `WidgetId` the same way `TreeView`'s scroll will.
    #[serde(default)]
    pub scroll_offset: usize,
    #[serde(default)]
    pub has_focus: bool,
}

/// Validation state rendered as a colored indicator + message.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum ValidationState {
    Error(String),
    Warning(String),
}

/// One row in a `Form`: a label + an input.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FormField {
    pub id: WidgetId,
    /// Rendered to the left of the field. Omit (empty spans) for rows
    /// that are just buttons or labels standing alone.
    pub label: StyledText,
    pub kind: FieldKind,
    /// Tooltip / hint text rendered below the field (or to the right,
    /// depending on backend). Empty = no hint.
    #[serde(default)]
    pub hint: StyledText,
    /// When true, the field is rendered dimmed and will not emit events.
    #[serde(default)]
    pub disabled: bool,
    /// When set, backends render a red/yellow indicator + message.
    /// Overrides `hint` visually when present.
    #[serde(default)]
    pub validation: Option<ValidationState>,
}

/// The input variant carried by a `FormField`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum FieldKind {
    /// A bold/sectioned header row. Not interactive; used to group
    /// related fields. The field's `label` carries the header text;
    /// `FormEvent`s are never emitted from this kind.
    Label,
    /// Boolean toggle. `value` is the current state. Space / Enter
    /// toggles; emits `FormEvent::ToggleChanged`.
    Toggle { value: bool },
    /// Single-line text input. `value` is the current text. Typing
    /// modifies it; emits `FormEvent::TextInputChanged` on every keystroke
    /// and `FormEvent::TextInputCommitted` on Enter.
    ///
    /// `cursor` is a byte offset into `value`. When `Some(n)`, backends
    /// render a cursor at that position; when `None`, the field is
    /// displayed read-only (no cursor). This primitive itself does no
    /// input handling — it just paints whatever `cursor` says — but a
    /// consumer going through
    /// [`crate::compose::form_controller::FormController`] does not need
    /// to compute `cursor` by hand: the controller tracks it internally
    /// across keystrokes and overlays it when rendering.
    /// A consumer driving `Form` directly (bypassing `FormController`)
    /// is still responsible for updating `cursor` itself.
    ///
    /// `selection_anchor` is a byte offset into `value`. When `Some(n)`
    /// and `n != cursor`, backends render the range between `anchor` and
    /// `cursor` with a selection highlight. `None` means no selection.
    ///
    /// Scroll offset for long text is a later primitive extension.
    TextInput {
        value: String,
        #[serde(default)]
        placeholder: String,
        #[serde(default)]
        cursor: Option<usize>,
        #[serde(default)]
        selection_anchor: Option<usize>,
    },
    /// A clickable button. `label` on the containing field is also used
    /// as the button caption. Emits `FormEvent::ButtonClicked`.
    Button,
    /// Read-only display of a value computed elsewhere. Text-only; no
    /// events. Used for "current version: 0.10.0" style rows.
    ReadOnly { value: StyledText },
    /// Numeric slider bounded by `min`..=`max` with increment `step`.
    /// `value` is the current setting. Click-and-drag on the track
    /// updates value; arrow keys step by `step`; Home/End jump to
    /// bounds. Emits `FormEvent::SliderChanged` per adjustment.
    ///
    /// Use for tab width, font size multiplier, cursor-blink rate,
    /// anything with a natural numeric domain and a reasonable range.
    Slider {
        value: f32,
        min: f32,
        max: f32,
        #[serde(default = "slider_default_step")]
        step: f32,
    },
    /// Colour picker. `value` is the current selection. Click opens an
    /// app-provided palette / hex-input popup (the Form primitive
    /// doesn't render the popup itself — apps handle that). Emits
    /// `FormEvent::ColorChanged` when the user picks a new value.
    ///
    /// Use for theme customisation, highlight-group overrides, chart
    /// colour assignments.
    ColorPicker { value: crate::Color },
    /// Single-choice selection from a fixed list. `options` is the
    /// display list; `selected_idx` is the current choice.
    /// Click / Enter opens the dropdown; arrows select; Enter confirms.
    /// Emits `FormEvent::DropdownChanged` on commit.
    ///
    /// Use for enum-style settings (theme selection, cursor style,
    /// line-ending preference, language server choice).
    Dropdown {
        options: Vec<StyledText>,
        selected_idx: usize,
    },
    /// Multi-line text editing area. `visible_rows` controls the height
    /// hint (number of rows rendered). Emits `FormEvent::TextInputChanged`
    /// and `TextInputCommitted` like `TextInput`.
    TextArea {
        value: String,
        #[serde(default)]
        placeholder: String,
        #[serde(default)]
        cursor: Option<usize>,
        #[serde(default = "textarea_default_rows")]
        visible_rows: usize,
    },
    /// Masked single-line text input. Characters display as `mask_char`
    /// (default `'•'`). Value is stored in plaintext; only rendering is
    /// masked. Emits the same events as `TextInput`.
    PasswordInput {
        value: String,
        #[serde(default)]
        placeholder: String,
        #[serde(default)]
        cursor: Option<usize>,
        #[serde(default = "password_default_mask")]
        mask_char: char,
    },
    /// Horizontal row of N options where exactly one is selected.
    /// All options are visible (unlike Dropdown). Click selects; emits
    /// `FormEvent::SegmentedControlChanged`.
    SegmentedControl {
        options: Vec<String>,
        selected_idx: usize,
    },
    /// Horizontal row of named boolean toggles. Each toggle has its own
    /// `WidgetId`, label, and value. Click toggles the value; emits
    /// `FormEvent::ToggleChanged { id, value }` with the individual
    /// toggle's ID.
    ///
    /// Use for filter bars, toolbar toggle options, search-panel flags
    /// (case-sensitive / whole-word / regex).
    ToggleGroup { toggles: Vec<ToggleGroupItem> },
    /// Horizontal row of action buttons. Each button has its own
    /// `WidgetId` and label. Click emits `FormEvent::ButtonClicked { id }`
    /// with the individual button's ID.
    ///
    /// Use for dialog footers, form submit rows, search-panel actions
    /// (Find Next / Replace / Replace All).
    ButtonRow { buttons: Vec<ButtonRowItem> },
    /// A full [`crate::Toolbar`] strip embedded inside the form as a
    /// single field row. Renders all toolbar features (icons, key hints,
    /// separators, active/disabled states, tooltips) inside the field's
    /// value column. Click emits
    /// `FormEvent::ToolbarButtonClicked { field_id, button_id }`.
    ///
    /// Use for Settings → Reset / Import / Export rows, or any place
    /// where the toolbar idiom (hover states, separators, key hints) is
    /// more appropriate than `ButtonRow`'s simple bracketed labels.
    Toolbar(crate::primitives::toolbar::Toolbar),
    /// A full [`crate::primitives::date_picker::DatePicker`] embedded as a
    /// single field row. The field's row stays the same height as every
    /// other field — see [`crate::primitives::layout_metrics::form_field_measure`]'s
    /// doc for why no `FieldKind` grows the row — so only a compact
    /// single-line summary (the focused or selected date, formatted per
    /// the picker's locale) renders in the value column, not the full
    /// month grid.
    ///
    /// A consumer going through
    /// [`crate::compose::form_controller::FormController`] gets arrow-key
    /// day/week navigation, Page Up/Down month navigation, and Enter-to-
    /// confirm for free: the controller calls the embedded picker's own
    /// [`crate::primitives::date_picker::DatePicker::navigate`] and emits
    /// `FormEvent::DateChanged` on confirmation. Clicking the field's row
    /// only moves focus to it (`FormEvent::FocusChanged`) — day-cell
    /// hit-testing is the keyboard path's job here, not the pointer's.
    DatePicker(crate::primitives::date_picker::DatePicker),
}

/// One toggle in a [`FieldKind::ToggleGroup`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToggleGroupItem {
    pub id: WidgetId,
    pub label: String,
    pub value: bool,
}

/// One button in a [`FieldKind::ButtonRow`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ButtonRowItem {
    pub id: WidgetId,
    pub label: String,
    #[serde(default)]
    pub disabled: bool,
    /// Optional icon rendered before the label. Enables icon-button
    /// rows (commit, push, pull, fetch) in source-control panels.
    #[serde(default)]
    pub icon: Option<crate::types::Icon>,
}

fn slider_default_step() -> f32 {
    1.0
}

fn textarea_default_rows() -> usize {
    3
}

fn password_default_mask() -> char {
    '•'
}

// ── D6 Layout API ───────────────────────────────────────────────────────────
//
// Per Decision D6: primitives return fully-resolved `Layout` structs.
// Seventh primitive on the new shape. Form is structurally a vertical
// stack of fields — same geometry as TreeView. The FieldKind distinction
// (Toggle / TextInput / Button / Label / ReadOnly) is about rendering,
// not layout, so it stays backend-owned: the layout just places rows.

/// Per-field measurement supplied by the backend.
#[derive(Debug, Clone, PartialEq)]
pub struct FormFieldMeasure {
    pub height: f32,
    /// Per-item widths for `ToggleGroup` / `ButtonRow` fields. The
    /// layout uses these to compute per-item hit regions. Empty for
    /// other field kinds.
    pub item_measures: Vec<FormItemMeasure>,
    /// X offset where items start (after label + padding). Only used
    /// when `item_measures` is non-empty.
    pub items_start_x: f32,
    /// Gap between items (cells for TUI, pixels for GTK). Only used
    /// when `item_measures` is non-empty.
    pub item_gap: f32,
}

impl FormFieldMeasure {
    pub fn new(height: f32) -> Self {
        Self {
            height,
            item_measures: Vec::new(),
            items_start_x: 0.0,
            item_gap: 0.0,
        }
    }

    pub fn with_items(
        height: f32,
        items_start_x: f32,
        item_gap: f32,
        items: Vec<FormItemMeasure>,
    ) -> Self {
        Self {
            height,
            item_measures: items,
            items_start_x,
            item_gap,
        }
    }
}

/// Width of one item inside a `ToggleGroup` or `ButtonRow`.
#[derive(Debug, Clone, PartialEq)]
pub struct FormItemMeasure {
    pub id: WidgetId,
    pub width: f32,
}

/// Resolved position of one visible form field after layout.
#[derive(Debug, Clone, PartialEq)]
pub struct VisibleFormField {
    /// Index into `Form.fields`.
    pub field_idx: usize,
    /// Clone of the field's `WidgetId` for click routing without a
    /// re-index into the primitive.
    pub id: WidgetId,
    pub bounds: Rect,
    /// Resolved per-item rects for `ToggleGroup` / `ButtonRow` fields.
    /// Empty for other field kinds. Rasterisers consume these to paint
    /// items at the layout-determined positions.
    pub item_bounds: Vec<(WidgetId, Rect)>,
}

/// Classification of a hit-test result. Carries the field's `WidgetId`
/// so apps can dispatch via the same ID plumbing their event handlers
/// use — no secondary indirection through `fields[i].id`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FormHit {
    /// Click landed on a field row.
    Field(WidgetId),
    /// Click landed outside any field.
    Empty,
}

/// Fully-resolved form layout.
#[derive(Debug, Clone, PartialEq)]
pub struct FormLayout {
    pub viewport_width: f32,
    pub viewport_height: f32,
    pub visible_fields: Vec<VisibleFormField>,
    pub hit_regions: Vec<(Rect, FormHit)>,
    /// Scroll offset actually used, clamped to `[0, fields.len())`.
    pub resolved_scroll_offset: usize,
}

impl FormLayout {
    pub fn hit_test(&self, x: f32, y: f32) -> FormHit {
        for (rect, hit) in &self.hit_regions {
            if x >= rect.x && x < rect.x + rect.width && y >= rect.y && y < rect.y + rect.height {
                return hit.clone();
            }
        }
        FormHit::Empty
    }
}

impl Form {
    /// Compute the full rendering + hit-test layout for this form.
    ///
    /// # Arguments
    ///
    /// - `viewport_width`, `viewport_height` — form area dimensions.
    /// - `measure_field(i)` — height for field `i`. Backends vary
    ///   height by `FieldKind` (e.g. `Label` may be shorter than
    ///   `TextInput`; fields with non-empty `hint` may be taller).
    ///
    /// # Row clipping
    ///
    /// The last visible field's `bounds.height` is clipped to what fits
    /// in the viewport (same semantics as `TreeView::layout`).
    pub fn layout<F>(
        &self,
        viewport_width: f32,
        viewport_height: f32,
        measure_field: F,
    ) -> FormLayout
    where
        F: Fn(usize) -> FormFieldMeasure,
    {
        let mut visible_fields: Vec<VisibleFormField> = Vec::new();
        let mut hit_regions: Vec<(Rect, FormHit)> = Vec::new();

        let resolved_scroll_offset = crate::primitives::scrollbar::clamp_scroll_offset(
            self.scroll_offset,
            self.fields.len(),
        );

        // First pass: walk fields in order deciding which ones are
        // visible and how tall each renders, using the original
        // sequential "stop once the viewport is exhausted" rule. This
        // is a selection decision (how many fields fit), not layout
        // math, so it stays hand-rolled regardless of the `layout`
        // feature — a flex container has no notion of "stop adding
        // children partway through".
        struct Row {
            idx: usize,
            full_height: f32,
            clipped_height: f32,
            item_measures: Vec<FormItemMeasure>,
            items_start_x: f32,
            item_gap: f32,
        }
        let mut rows: Vec<Row> = Vec::new();
        let mut y = 0.0_f32;
        for i in resolved_scroll_offset..self.fields.len() {
            if y >= viewport_height {
                break;
            }
            let m = measure_field(i);
            let remaining = viewport_height - y;
            let clipped_height = m.height.min(remaining).max(0.0);
            if clipped_height <= 0.0 {
                break;
            }
            y += m.height;
            rows.push(Row {
                idx: i,
                full_height: m.height,
                clipped_height,
                item_measures: m.item_measures,
                items_start_x: m.items_start_x,
                item_gap: m.item_gap,
            });
        }

        // Second pass: now that membership is settled, compute each
        // row's `y` from the cumulative full heights (unclipped, same
        // invariant as the selection pass above — a row's position
        // never shrinks to make room for its own clipped height).
        let full_heights: Vec<f32> = rows.iter().map(|r| r.full_height).collect();
        let ys = row_y_positions(viewport_width, &full_heights);

        for (row, y) in rows.into_iter().zip(ys) {
            let bounds = Rect::new(0.0, y, viewport_width, row.clipped_height);
            let id = self.fields[row.idx].id;

            let mut item_bounds = Vec::new();
            if !row.item_measures.is_empty() {
                let widths: Vec<f32> = row.item_measures.iter().map(|item| item.width).collect();
                let item_xs =
                    item_x_positions(row.items_start_x, row.clipped_height, row.item_gap, &widths);
                for (item, item_x) in row.item_measures.iter().zip(item_xs) {
                    let item_rect = Rect::new(item_x, y, item.width, row.clipped_height);
                    hit_regions.push((item_rect, FormHit::Field(item.id)));
                    item_bounds.push((item.id, item_rect));
                }
            }
            hit_regions.push((bounds, FormHit::Field(id)));

            visible_fields.push(VisibleFormField {
                field_idx: row.idx,
                id,
                bounds,
                item_bounds,
            });
        }

        FormLayout {
            viewport_width,
            viewport_height,
            visible_fields,
            hit_regions,
            resolved_scroll_offset,
        }
    }
}

/// Compute each visible field row's top edge given its full
/// (unclipped) height, top-to-bottom, never shrinking — the vertical
/// counterpart of `Toolbar`'s item packing. `viewport_width` is every
/// row's fixed cross-axis size.
///
/// With the `layout` feature this runs through [`crate::flex`]'s shared
/// flexbox engine, so `Form` composes with the same engine
/// [`crate::primitives::Toolbar`] and [`crate::compose::AppShell`] use.
/// Without it, the same arithmetic is done by hand. Both arms are
/// covered by this module's exact-value tests to guarantee they agree
/// bit-for-bit.
#[cfg(feature = "layout")]
fn row_y_positions(viewport_width: f32, heights: &[f32]) -> Vec<f32> {
    crate::flex::pack_1d(
        crate::flex::FlexDirection::Column,
        0.0,
        heights,
        0.0,
        viewport_width,
    )
}

/// Same contract as the `layout`-feature arm above, computed by hand.
#[cfg(not(feature = "layout"))]
fn row_y_positions(_viewport_width: f32, heights: &[f32]) -> Vec<f32> {
    let mut y = 0.0_f32;
    let mut ys = Vec::with_capacity(heights.len());
    for &h in heights {
        ys.push(y);
        y += h;
    }
    ys
}

/// Compute each `ToggleGroup`/`ButtonRow` item's left edge, left-to-right
/// starting at `origin_x` with `gap` between consecutive items, never
/// shrinking. `row_height` is every item's fixed cross-axis size.
///
/// With the `layout` feature this runs through [`crate::flex`]'s shared
/// flexbox engine. Without it, the same arithmetic is done by hand.
#[cfg(feature = "layout")]
fn item_x_positions(origin_x: f32, row_height: f32, gap: f32, widths: &[f32]) -> Vec<f32> {
    crate::flex::pack_1d(
        crate::flex::FlexDirection::Row,
        origin_x,
        widths,
        gap,
        row_height,
    )
}

/// Same contract as the `layout`-feature arm above, computed by hand.
#[cfg(not(feature = "layout"))]
fn item_x_positions(origin_x: f32, _row_height: f32, gap: f32, widths: &[f32]) -> Vec<f32> {
    let mut x = origin_x;
    let mut xs = Vec::with_capacity(widths.len());
    for &w in widths {
        xs.push(x);
        x += w + gap;
    }
    xs
}

// `paint` below is the one shared implementation, written against
// [`crate::paint_surface::PaintSurface`] instead of any one backend's
// drawing API. It handles all 14 variants; before unification, the macOS
// copy matched only 10 of 14 variants and silently fell through on
// `Slider`, `ColorPicker`, `Dropdown` and `TextArea`.
//
// `#[allow(dead_code)]`: `paint` and its private helpers are only called
// when a real pixel backend is compiled in — `GtkBackend::draw_form`,
// `MacBackend::draw_form`/`draw_form_body` and `WinBackend::draw_form`/
// `draw_form_body` are the call sites, and the Win ones live behind a
// further `target_os = "windows"` gate (see `win::form`'s module doc).
// `--features win` alone, on a non-Windows host compiles this module but
// reaches none of those call sites, so nothing here is "dead" in the lint
// sense; it's the same shape `paint_surface.rs`'s own `#[allow(dead_code)]`
// documents, one level up the call chain.
#[cfg(any(
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
#[allow(dead_code)]
mod native_surface_paint {
    use super::{FieldKind, Form, FormLayout, ValidationState};
    use crate::event::Rect;
    use crate::paint_surface::PaintSurface;
    // The selected-item background pill's rect and the widget-state decision
    // of whether to paint it are extracted to `paint_geometry` so both are
    // unit-tested outside this module's own feature-gated `mod tests` too —
    // see `paint_geometry::selected_item_fill`'s doc for details on unifying
    // the three backends' shapes (macOS painted it, GTK painted nothing,
    // Windows painted `hover_bg` at full row height).
    use crate::paint_geometry::selected_item_fill;
    use crate::text_util::snap_to_char_boundary;
    use crate::theme::Theme;
    use crate::types::{Color, StyledText};

    /// Translate a form-local `Rect` (`FormLayout`'s `bounds`/
    /// `item_bounds` are always local to the form, origin at `(0, 0)` —
    /// see `FormLayout`'s doc) into `surface`-absolute coordinates.
    ///
    /// The single place every field-kind arm below crosses into absolute
    /// space, rather than re-deriving the translation per call site the
    /// way the three deleted per-backend copies did — one of which,
    /// `win::form::shift`, added the row's *already-translated* `y` to
    /// the item's still-form-local `y` a second time, over-shifting every
    /// `ToggleGroup` / `ButtonRow` / `SegmentedControl` item on every row
    /// but the first. Not reproduced here: an item's rect and its row's
    /// rect are translated by the same `origin`, once each.
    fn translate(r: &Rect, origin: crate::Point) -> Rect {
        Rect::new(origin.x + r.x, origin.y + r.y, r.width, r.height)
    }

    fn plain_text(t: &StyledText) -> String {
        t.spans.iter().map(|s| s.text.as_str()).collect()
    }

    /// Paint a laid-out [`Form`] using `surface`'s [`PaintSurface`] verbs.
    ///
    /// `flayout` must be the *same* [`FormLayout`] the caller uses for
    /// hit-testing (typically `Backend::form_layout`'s return value for this
    /// `form`) — `paint` reads geometry only from `flayout`, never recomputes
    /// it, so paint and hit-test never disagree.
    ///
    /// `origin` places the form's local `(0, 0)` at `origin` in `surface`'s
    /// coordinate space — mirrors every other `*_layout` primitive's
    /// "local layout + host-supplied origin" contract (see `mac_form_layout`'s
    /// doc for the same convention stated from the hit-test side).
    ///
    /// # `FieldKind::Toolbar` is not painted here
    ///
    /// `PaintSurface`'s drawing verbs have no rounded-rect or
    /// hover/pressed/focus-state support, so a `Toolbar` field's full chrome
    /// can't be reproduced through this trait without growing it well past
    /// this primitive's scope. `paint` still paints a `Toolbar` field's row
    /// background / label / validation indicator like any other field, but
    /// leaves the value column blank — callers must paint the embedded
    /// `Toolbar` themselves *after* `paint` returns (so the two never fight
    /// over `surface`'s exclusive borrow), using their existing per-backend
    /// toolbar rasteriser at the field's `VisibleFormField::bounds` /
    /// `item_bounds`. See `GtkBackend::draw_form` for the reference pattern.
    pub(crate) fn paint(
        form: &Form,
        flayout: &FormLayout,
        surface: &mut dyn PaintSurface,
        theme: &Theme,
        origin: crate::Point,
    ) {
        let form_rect = Rect::new(
            origin.x,
            origin.y,
            flayout.viewport_width,
            flayout.viewport_height,
        );
        surface.surface_fill_rect(form_rect, theme.tab_bar_bg);

        for vf in &flayout.visible_fields {
            let Some(field) = form.fields.get(vf.field_idx) else {
                continue;
            };
            let row_rect = translate(&vf.bounds, origin);
            let row_h_full = row_rect.height;

            // When the field carries a non-empty validation message,
            // split the row into a content strip (label + input,
            // centred the same way every other field is) and a message
            // strip below it, instead of painting the message on top of
            // the label at the same vertical centre.
            let validation_info = field.validation.as_ref().and_then(|vs| {
                let (color, msg) = match vs {
                    ValidationState::Error(m) => (theme.error_fg, m.as_str()),
                    ValidationState::Warning(m) => (theme.warning_fg, m.as_str()),
                };
                if msg.is_empty() {
                    None
                } else {
                    Some((color, msg))
                }
            });
            let message_h = validation_info
                .map(|(_, msg)| surface.surface_measure_text(msg).1)
                .unwrap_or(0.0);
            let row_h = (row_h_full - message_h).max(row_h_full * 0.5);

            let is_focused = form.has_focus
                && form
                    .focused_field
                    .as_ref()
                    .is_some_and(|id| id == &field.id);
            let is_header = matches!(field.kind, FieldKind::Label);

            let (default_fg, row_bg) = if is_focused {
                // `theme.foreground` (the editor-body text
                // colour) has no guaranteed contrast against
                // `selected_bg` — on `vscode-light` both are near-black
                // on mid-blue and the focused row goes unreadable.
                // `header_fg` is `Theme`'s documented on-selection
                // foreground (see its doc comment); `Tree` already pairs
                // it with `selected_bg` the same way for its focused row.
                (theme.header_fg, theme.selected_bg)
            } else if is_header {
                (theme.header_fg, theme.header_bg)
            } else {
                (theme.foreground, theme.tab_bar_bg)
            };
            surface.surface_fill_rect(row_rect, row_bg);

            let field_fg = if field.disabled {
                theme.muted_fg
            } else {
                default_fg
            };

            let label_text = plain_text(&field.label);
            let (label_w, label_h) = surface.surface_measure_text(&label_text);
            let label_x = row_rect.x + 6.0;
            let label_y = row_rect.y + (row_h - label_h) / 2.0;
            surface.surface_draw_text_run(
                Rect::new(label_x, label_y, label_w, label_h),
                &label_text,
                field_fg,
            );
            let label_right = label_x + label_w;
            let no_label = label_text.is_empty();
            let input_right = row_rect.x + row_rect.width - 8.0;

            match &field.kind {
                FieldKind::Label => {}
                FieldKind::Toggle { value } => {
                    // Drawn checkbox rather than a `[x]` / `[ ]` text
                    // glyph — the TUI painter keeps the glyph.
                    let fg = if *value && !field.disabled {
                        theme.accent_fg
                    } else {
                        field_fg
                    };
                    let box_size = (row_h - 8.0).clamp(10.0, 16.0);
                    let ix = if no_label {
                        label_x
                    } else {
                        input_right - box_size
                    };
                    if no_label || ix > label_right + 8.0 {
                        let iy = row_rect.y + (row_h - box_size) / 2.0;
                        let box_rect = Rect::new(ix, iy, box_size, box_size);
                        if *value {
                            surface.surface_fill_rounded_rect(box_rect, 2.0, fg);
                            let check_fg = theme.background;
                            surface.surface_draw_line(
                                crate::Point::new(
                                    box_rect.x + box_size * 0.22,
                                    box_rect.y + box_size * 0.52,
                                ),
                                crate::Point::new(
                                    box_rect.x + box_size * 0.42,
                                    box_rect.y + box_size * 0.75,
                                ),
                                check_fg,
                                1.5,
                            );
                            surface.surface_draw_line(
                                crate::Point::new(
                                    box_rect.x + box_size * 0.42,
                                    box_rect.y + box_size * 0.75,
                                ),
                                crate::Point::new(
                                    box_rect.x + box_size * 0.8,
                                    box_rect.y + box_size * 0.25,
                                ),
                                check_fg,
                                1.5,
                            );
                        } else {
                            surface.surface_stroke_rect(box_rect, fg, 1.0);
                        }
                    }
                }
                FieldKind::TextInput {
                    value,
                    placeholder,
                    cursor,
                    selection_anchor,
                } => {
                    paint_text_input_box(
                        surface,
                        row_rect,
                        label_right,
                        no_label,
                        input_right,
                        value,
                        placeholder,
                        *cursor,
                        *selection_anchor,
                        field_fg,
                        theme.muted_fg,
                        theme.selection_bg,
                        theme.accent_fg,
                        false,
                        '\0',
                    );
                }
                FieldKind::PasswordInput {
                    value,
                    placeholder,
                    cursor,
                    mask_char,
                } => {
                    paint_text_input_box(
                        surface,
                        row_rect,
                        label_right,
                        no_label,
                        input_right,
                        value,
                        placeholder,
                        *cursor,
                        None,
                        field_fg,
                        theme.muted_fg,
                        theme.selection_bg,
                        theme.accent_fg,
                        true,
                        *mask_char,
                    );
                }
                FieldKind::TextArea {
                    value,
                    placeholder,
                    cursor,
                    ..
                } => {
                    let first_line = value.lines().next().unwrap_or("");
                    paint_text_input_box(
                        surface,
                        row_rect,
                        label_right,
                        no_label,
                        input_right,
                        first_line,
                        placeholder,
                        *cursor,
                        None,
                        field_fg,
                        theme.muted_fg,
                        theme.selection_bg,
                        theme.accent_fg,
                        false,
                        '\0',
                    );
                }
                FieldKind::Button => {
                    let cap = label_text.clone();
                    let total_w = label_w + 24.0;
                    let ix = if no_label {
                        label_x
                    } else {
                        input_right - total_w
                    };
                    if no_label || ix > row_rect.x + 8.0 {
                        let brk = if is_focused {
                            theme.accent_fg
                        } else {
                            theme.muted_fg
                        };
                        let (_, h) = surface.surface_measure_text("<");
                        let y = row_rect.y + (row_h - h) / 2.0;
                        surface.surface_draw_text_run(Rect::new(ix, y, 12.0, h), "<", brk);
                        let text_fg = if field.disabled {
                            theme.muted_fg
                        } else {
                            field_fg
                        };
                        surface.surface_draw_text_run(
                            Rect::new(ix + 12.0, y, label_w, h),
                            &cap,
                            text_fg,
                        );
                        surface.surface_draw_text_run(
                            Rect::new(ix + 12.0 + label_w + 4.0, y, 12.0, h),
                            ">",
                            brk,
                        );
                    }
                }
                FieldKind::ReadOnly { value } => {
                    let text = plain_text(value);
                    let (w, h) = surface.surface_measure_text(&text);
                    let ix = if no_label { label_x } else { input_right - w };
                    if no_label || ix > label_right + 8.0 {
                        let iy = row_rect.y + (row_h - h) / 2.0;
                        // Was unconditionally `theme.muted_fg`,
                        // so a focused (`selected_bg`) `ReadOnly` row painted
                        // its value in the same dim colour as an unfocused
                        // one — unreadable on `selected_bg`, unlike every
                        // other field kind here, which derives its value
                        // colour from `field_fg` (focus/disabled-aware).
                        surface.surface_draw_text_run(Rect::new(ix, iy, w, h), &text, field_fg);
                    }
                }
                FieldKind::Slider {
                    value, min, max, ..
                } => {
                    let track_w = 80.0_f32;
                    let range = (max - min).max(f32::EPSILON);
                    let frac = ((value - min) / range).clamp(0.0, 1.0);
                    let value_str = format!("{value:.2}");
                    let (value_w, value_h) = surface.surface_measure_text(&value_str);
                    let total = track_w + 8.0 + value_w;
                    let ix = input_right - total;
                    if ix > label_right + 8.0 {
                        let track_y = row_rect.y + row_h / 2.0 - 2.0;
                        surface.surface_fill_rect(
                            Rect::new(ix, track_y, track_w, 4.0),
                            theme.muted_fg,
                        );
                        surface.surface_fill_rect(
                            Rect::new(ix, track_y, track_w * frac, 4.0),
                            theme.accent_fg,
                        );
                        let vy = row_rect.y + (row_h - value_h) / 2.0;
                        surface.surface_draw_text_run(
                            Rect::new(ix + track_w + 8.0, vy, value_w, value_h),
                            &value_str,
                            field_fg,
                        );
                    }
                }
                FieldKind::ColorPicker { value } => {
                    let hex = format!("#{:02x}{:02x}{:02x}", value.r, value.g, value.b);
                    let (hw, hh) = surface.surface_measure_text(&hex);
                    let swatch = 12.0_f32;
                    let total = swatch + 6.0 + hw;
                    let ix = input_right - total;
                    if ix > label_right + 8.0 {
                        let sy = row_rect.y + (row_h - swatch) / 2.0;
                        surface.surface_fill_rect(Rect::new(ix, sy, swatch, swatch), *value);
                        let ty = row_rect.y + (row_h - hh) / 2.0;
                        surface.surface_draw_text_run(
                            Rect::new(ix + swatch + 6.0, ty, hw, hh),
                            &hex,
                            field_fg,
                        );
                    }
                }
                FieldKind::Dropdown {
                    options,
                    selected_idx,
                } => {
                    let chosen = options
                        .get(*selected_idx)
                        .map(plain_text)
                        .unwrap_or_default();
                    let (cw, ch) = surface.surface_measure_text(&chosen);
                    let (chev_w, _) = surface.surface_measure_text("\u{25BE}");
                    let total = cw + 4.0 + chev_w;
                    let ix = input_right - total;
                    if ix > label_right + 8.0 {
                        let ty = row_rect.y + (row_h - ch) / 2.0;
                        surface.surface_draw_text_run(Rect::new(ix, ty, cw, ch), &chosen, field_fg);
                        surface.surface_draw_text_run(
                            Rect::new(ix + cw + 4.0, ty, chev_w, ch),
                            "\u{25BE}",
                            theme.muted_fg,
                        );
                    }
                }
                FieldKind::ToggleGroup { toggles } => {
                    for (item_id, item_rect) in &vf.item_bounds {
                        if let Some(t) = toggles.iter().find(|t| &t.id == item_id) {
                            let on = t.value && !field.disabled;
                            let fg = if on { theme.accent_fg } else { theme.muted_fg };
                            let r = translate(item_rect, origin);
                            if let Some((pill, bg)) = selected_item_fill(r, on, theme.selected_bg) {
                                surface.surface_fill_rect(pill, bg);
                            }
                            surface.surface_draw_text_run(r, &t.label, fg);
                        }
                    }
                }
                FieldKind::ButtonRow { buttons } => {
                    for (item_id, item_rect) in &vf.item_bounds {
                        if let Some(b) = buttons.iter().find(|b| &b.id == item_id) {
                            let r = translate(item_rect, origin);
                            let disabled = b.disabled || field.disabled;
                            let bg = if disabled { row_bg } else { theme.hover_bg };
                            surface.surface_fill_rect(r, bg);
                            let fg = if disabled { theme.muted_fg } else { field_fg };
                            let mut tx = r.x + 4.0;
                            if let Some(ref icon) = b.icon {
                                let (iw, ih) = surface.surface_measure_text(&icon.fallback);
                                let iy = r.y + (r.height - ih) / 2.0;
                                surface.surface_draw_text_run(
                                    Rect::new(tx, iy, iw, ih),
                                    &icon.fallback,
                                    fg,
                                );
                                tx += iw + 4.0;
                            }
                            let (lw, lh) = surface.surface_measure_text(&b.label);
                            let ly = r.y + (r.height - lh) / 2.0;
                            surface.surface_draw_text_run(Rect::new(tx, ly, lw, lh), &b.label, fg);
                        }
                    }
                }
                FieldKind::SegmentedControl {
                    options,
                    selected_idx,
                } => {
                    for (i, (_item_id, item_rect)) in vf.item_bounds.iter().enumerate() {
                        let opt = options.get(i).map(|s| s.as_str()).unwrap_or("");
                        let fg = if i == *selected_idx {
                            theme.accent_fg
                        } else {
                            theme.muted_fg
                        };
                        let r = translate(item_rect, origin);
                        if let Some((pill, bg)) =
                            selected_item_fill(r, i == *selected_idx, theme.selected_bg)
                        {
                            surface.surface_fill_rect(pill, bg);
                        }
                        let (tw, th) = surface.surface_measure_text(opt);
                        let ty = r.y + (r.height - th) / 2.0;
                        surface.surface_draw_text_run(Rect::new(r.x, ty, tw, th), opt, fg);
                    }
                }
                FieldKind::Toolbar(_) => {
                    // See this fn's doc: painted by the caller after
                    // `paint` returns, using the backend's own toolbar
                    // rasteriser.
                }
                FieldKind::DatePicker(picker) => {
                    // While this row is focused, `focused` is the live
                    // scrub position `FormController` overlays per
                    // keystroke (see `compose::form_controller`'s "Date
                    // picker fields" doc section) — showing `selected`
                    // instead would make every scrub past the first
                    // confirmation invisible. Once focus moves on,
                    // `selected` (falling back to `focused` pre-first-
                    // confirmation) is the field's settled value.
                    let date = if is_focused {
                        picker.focused
                    } else {
                        picker.selected.unwrap_or(picker.focused)
                    };
                    let text = date.format(picker.locale.format);
                    let (tw, th) = surface.surface_measure_text(&text);
                    let ix = if no_label { label_x } else { input_right - tw };
                    if no_label || ix > label_right + 8.0 {
                        let ty = row_rect.y + (row_h - th) / 2.0;
                        surface.surface_draw_text_run(Rect::new(ix, ty, tw, th), &text, field_fg);
                    }
                }
            }

            if let Some((color, msg)) = validation_info {
                // Message strip: below the content strip computed
                // above, not overlapping the label.
                let strip_y = row_rect.y + row_h;
                let strip_h = (row_h_full - row_h).max(0.0);
                surface.surface_fill_rect(
                    Rect::new(
                        row_rect.x + 2.0,
                        strip_y + (strip_h - 3.0).max(0.0) / 2.0,
                        3.0,
                        3.0,
                    ),
                    color,
                );
                let (mw, mh) = surface.surface_measure_text(msg);
                let my = strip_y + (strip_h - mh).max(0.0) / 2.0;
                surface.surface_draw_text_run(Rect::new(row_rect.x + 8.0, my, mw, mh), msg, color);
            }
        }
    }

    /// Shared text-input box painter for `TextInput` / `PasswordInput` /
    /// the single-line `TextArea` preview: a stroked box with px padding
    /// around the value, rather than literal `[value]` bracket glyphs —
    /// the TUI painter keeps the brackets, which read as a terminal
    /// affordance on a pixel canvas. `mask` replaces every character
    /// with `mask_char` when `masked` is true. Descends from
    /// `win::form::draw_bracketed_text` (the most complete of the three
    /// deleted copies — it already carried the selection highlight GTK's
    /// copy had and macOS's never gained).
    #[allow(clippy::too_many_arguments)]
    fn paint_text_input_box(
        surface: &mut dyn PaintSurface,
        row_rect: Rect,
        label_right: f32,
        no_label: bool,
        input_right: f32,
        value: &str,
        placeholder: &str,
        cursor: Option<usize>,
        selection_anchor: Option<usize>,
        field_fg: Color,
        dim_fg: Color,
        sel_bg: Color,
        accent_fg: Color,
        masked: bool,
        mask_char: char,
    ) {
        let masked_value: String;
        let shown: &str = if value.is_empty() {
            placeholder
        } else if masked {
            masked_value = value.chars().map(|_| mask_char).collect();
            &masked_value
        } else {
            value
        };
        let input_fg = if value.is_empty() { dim_fg } else { field_fg };
        let row_h = row_rect.height;
        let (shown_w, shown_h) = surface.surface_measure_text(shown);

        let (ix, _dw, box_right) = if no_label {
            let ix = row_rect.x + 6.0;
            let box_r = input_right - 4.0;
            let avail = (box_r - ix - 8.0).max(0.0);
            (ix, shown_w.min(avail), box_r)
        } else {
            let max_width = (row_rect.width * 0.6).max(80.0);
            let dw = shown_w.min(max_width);
            let ix = input_right - dw - 14.0;
            (ix, dw, ix + 8.0 + dw + 2.0)
        };
        if !(no_label || ix > label_right + 8.0) {
            return;
        }

        surface.surface_stroke_rect(
            Rect::new(ix, row_rect.y + 2.0, (box_right - ix).max(1.0), row_h - 4.0),
            dim_fg,
            1.0,
        );

        let y = row_rect.y + (row_h - shown_h) / 2.0;

        let has_sel = !masked
            && matches!((cursor, selection_anchor), (Some(c), Some(a)) if c != a && !value.is_empty());
        if has_sel {
            let (c, a) = (cursor.unwrap(), selection_anchor.unwrap());
            let (lo, hi) = (c.min(a), c.max(a));
            let lo = snap_to_char_boundary(shown, lo);
            let hi = snap_to_char_boundary(shown, hi);
            let prefix = &shown[..lo];
            let sel_text = &shown[lo..hi];
            let suffix = &shown[hi..];
            let (pw, _) = surface.surface_measure_text(prefix);
            let (sw, _) = surface.surface_measure_text(sel_text);
            surface.surface_fill_rect(
                Rect::new(ix + 8.0 + pw, row_rect.y + 2.0, sw, row_h - 4.0),
                sel_bg,
            );
            surface.surface_draw_text_run(Rect::new(ix + 8.0, y, pw, shown_h), prefix, input_fg);
            surface.surface_draw_text_run(
                Rect::new(ix + 8.0 + pw, y, sw, shown_h),
                sel_text,
                field_fg,
            );
            surface.surface_draw_text_run(
                Rect::new(ix + 8.0 + pw + sw, y, shown_w - pw - sw, shown_h),
                suffix,
                input_fg,
            );
        } else {
            surface.surface_draw_text_run(
                Rect::new(ix + 8.0, y, shown_w, shown_h),
                shown,
                input_fg,
            );
        }

        if !masked {
            if let Some(cur) = cursor {
                if !value.is_empty() {
                    let prefix = &shown[..snap_to_char_boundary(shown, cur)];
                    let (pw, _) = surface.surface_measure_text(prefix);
                    let cx = ix + 8.0 + pw;
                    surface.surface_fill_rect(
                        Rect::new(cx, row_rect.y + 3.0, 1.5, row_h - 6.0),
                        accent_fg,
                    );
                }
            }
        } else if let Some(cur) = cursor {
            if !value.is_empty() {
                let char_pos = value[..snap_to_char_boundary(value, cur)].chars().count();
                let prefix: String = shown.chars().take(char_pos).collect();
                let (pw, _) = surface.surface_measure_text(&prefix);
                let cx = ix + 8.0 + pw;
                surface.surface_fill_rect(
                    Rect::new(cx, row_rect.y + 3.0, 1.5, row_h - 6.0),
                    accent_fg,
                );
            }
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use crate::backend::ImagePaintResult;
        use crate::event::Viewport;
        use crate::primitives::form::{FormField, ToggleGroupItem};
        use crate::primitives::layout_metrics::{form_field_measure, form_row_height, TextMeasure};
        use crate::types::WidgetId;
        use crate::Image;

        /// Records every drawing verb `paint` issues, so a paint
        /// assertion can run on any host — no cairo, Core Graphics or
        /// Direct2D needed. The pixel backends' own probes
        /// (`macos::form`'s `BitmapSurface`, `gtk::form`'s
        /// `ImageSurface`) still cover "the verb reached real pixels";
        /// this covers "the shared painter emits the right verb at all",
        /// on every leg of the quality gate rather than only the macOS
        /// one.
        #[derive(Default)]
        struct RecordingSurface {
            fills: Vec<(Rect, Color)>,
            /// `(rect, text, color)` for every `surface_draw_text_run` call — tests
            /// assert a focused row's label/value colour, not just its fill.
            text_runs: Vec<(Rect, String, Color)>,
            /// `(rect, color, stroke_width)` for every
            /// `surface_stroke_rect` call, so tests can assert the drawn
            /// checkbox / text-input-box borders.
            strokes: Vec<(Rect, Color, f32)>,
        }

        /// 6 units per character — same fixed-width stand-in the
        /// `layout_metrics` tests use, so item widths stay predictable.
        struct FixedMeasure;

        impl TextMeasure for FixedMeasure {
            fn width_of(&self, text: &str) -> f32 {
                text.chars().count() as f32 * 6.0
            }
        }

        impl PaintSurface for RecordingSurface {
            fn surface_begin_frame(&mut self, _viewport: Viewport) {}
            fn surface_end_frame(&mut self) {}
            fn surface_viewport(&self) -> Viewport {
                Viewport::new(320.0, 160.0, 1.0)
            }
            fn surface_line_height(&self) -> f32 {
                14.0
            }
            fn surface_char_width(&self) -> f32 {
                6.0
            }
            fn surface_measure_text(&self, text: &str) -> (f32, f32) {
                (FixedMeasure.width_of(text), 12.0)
            }
            fn surface_fill_rect(&mut self, rect: Rect, color: Color) {
                self.fills.push((rect, color));
            }
            /// A checked `Toggle` fills its checkbox with
            /// `surface_fill_rounded_rect`. Records into the same
            /// `fills` list as `surface_fill_rect` (radius dropped).
            fn surface_fill_rounded_rect(&mut self, rect: Rect, _radius: f32, color: Color) {
                self.fills.push((rect, color));
            }
            fn surface_stroke_rect(&mut self, rect: Rect, color: Color, stroke_width: f32) {
                self.strokes.push((rect, color, stroke_width));
            }
            fn surface_stroke_rounded_rect(
                &mut self,
                _rect: Rect,
                _radius: f32,
                _color: Color,
                _stroke_width: f32,
            ) {
            }
            fn surface_draw_text_run(&mut self, rect: Rect, text: &str, color: Color) {
                self.text_runs.push((rect, text.to_string(), color));
            }
            fn surface_draw_line(
                &mut self,
                _from: crate::Point,
                _to: crate::Point,
                _color: Color,
                _stroke_width: f32,
            ) {
            }
            fn surface_push_clip(&mut self, _rect: Rect) {}
            fn surface_pop_clip(&mut self) {}
            fn surface_draw_image(&mut self, _rect: Rect, _image: &Image) -> ImagePaintResult {
                ImagePaintResult::Unsupported
            }
        }

        /// Lay `form` out the way every pixel backend's `form_layout`
        /// does, paint it through the shared painter, and hand back the
        /// recorded fills alongside the layout.
        fn paint_recorded(form: &Form) -> (RecordingSurface, FormLayout) {
            let row_h = form_row_height(14.0);
            let flayout = form.layout(320.0, 160.0, |i| {
                form_field_measure(&form.fields[i], row_h, &FixedMeasure)
            });
            let mut surface = RecordingSurface::default();
            paint(
                form,
                &flayout,
                &mut surface,
                &Theme::default(),
                crate::Point::new(0.0, 0.0),
            );
            (surface, flayout)
        }

        fn one_field_form(id: &str, kind: FieldKind) -> Form {
            Form {
                id: WidgetId::new("form"),
                fields: vec![FormField {
                    id: WidgetId::new(id),
                    label: StyledText::default(),
                    kind,
                    hint: StyledText::default(),
                    disabled: false,
                    validation: None,
                }],
                focused_field: None,
                scroll_offset: 0,
                has_focus: false,
            }
        }

        /// The pill a selected item paints: full item width, inset 2 at
        /// top and bottom.
        fn expected_pill(item: &Rect) -> Rect {
            Rect::new(item.x, item.y + 2.0, item.width, item.height - 4.0)
        }

        /// The shared painter must paint an on-toggle background, matching
        #[test]
        fn toggle_group_fills_selected_bg_behind_on_items_only() {
            let form = one_field_form(
                "flags",
                FieldKind::ToggleGroup {
                    toggles: vec![
                        ToggleGroupItem {
                            id: WidgetId::new("case"),
                            label: "Aa".into(),
                            value: false,
                        },
                        ToggleGroupItem {
                            id: WidgetId::new("regex"),
                            label: ".*".into(),
                            value: true,
                        },
                    ],
                },
            );
            let (surface, flayout) = paint_recorded(&form);
            let theme = Theme::default();
            let items = &flayout.visible_fields[0].item_bounds;
            let on = &items
                .iter()
                .find(|(id, _)| id == &WidgetId::new("regex"))
                .expect("on toggle laid out")
                .1;
            let off = &items
                .iter()
                .find(|(id, _)| id == &WidgetId::new("case"))
                .expect("off toggle laid out")
                .1;

            assert!(
                surface
                    .fills
                    .contains(&(expected_pill(on), theme.selected_bg)),
                "on toggle should fill selected_bg inset 2 vertically; fills were {:?}",
                surface.fills,
            );
            assert!(
                !surface
                    .fills
                    .iter()
                    .any(|(r, c)| r.x == off.x && *c == theme.selected_bg),
                "off toggle must not paint a selected_bg pill; fills were {:?}",
                surface.fills,
            );
        }

        /// The selected segment must fill `selected_bg` as a pill, not `hover_bg`
        #[test]
        fn segmented_control_fills_selected_bg_behind_the_selected_segment_only() {
            let form = one_field_form(
                "scope",
                FieldKind::SegmentedControl {
                    options: vec!["File".into(), "Folder".into(), "Project".into()],
                    selected_idx: 1,
                },
            );
            let (surface, flayout) = paint_recorded(&form);
            let theme = Theme::default();
            let items = &flayout.visible_fields[0].item_bounds;
            assert_eq!(items.len(), 3, "three segments should be laid out");

            assert!(
                surface
                    .fills
                    .contains(&(expected_pill(&items[1].1), theme.selected_bg)),
                "selected segment should fill selected_bg inset 2 vertically; \
                 fills were {:?}",
                surface.fills,
            );
            for idx in [0usize, 2] {
                let seg = &items[idx].1;
                assert!(
                    !surface
                        .fills
                        .iter()
                        .any(|(r, c)| r.x == seg.x && *c == theme.selected_bg),
                    "unselected segment {idx} must not paint a selected_bg pill; \
                     fills were {:?}",
                    surface.fills,
                );
            }
            assert!(
                !surface.fills.iter().any(|(_, c)| *c == theme.hover_bg),
                "no segment should paint hover_bg — nothing is hovered; \
                 fills were {:?}",
                surface.fills,
            );
        }

        /// A focused row painted its label in
        /// `theme.foreground` — no guaranteed contrast against
        /// `selected_bg` (both near-black on mid-blue under
        /// `vscode-light`) — while `Tree`'s equivalent focused row
        /// already used `theme.header_fg`. Also covers the `ReadOnly`
        /// field kind, whose value was unconditionally painted in
        /// `theme.muted_fg` regardless of focus — the second half of
        /// the issue's "value is unreadable" report.
        #[test]
        fn focused_row_paints_label_and_value_in_header_fg_not_foreground_or_muted_fg() {
            let mut form = one_field_form(
                "note",
                FieldKind::ReadOnly {
                    value: StyledText::plain("hello"),
                },
            );
            form.fields[0].label = StyledText::plain("Note");
            form.focused_field = Some(WidgetId::new("note"));
            form.has_focus = true;

            let (surface, _flayout) = paint_recorded(&form);
            let theme = Theme::default();

            let (_, _, label_fg) = surface
                .text_runs
                .iter()
                .find(|(_, text, _)| text == "Note")
                .expect("label text run recorded");
            assert_eq!(
                *label_fg, theme.header_fg,
                "focused row's label must use theme.header_fg (Tree's \
                 on-selection convention), not theme.foreground; text runs \
                 were {:?}",
                surface.text_runs,
            );

            let (_, _, value_fg) = surface
                .text_runs
                .iter()
                .find(|(_, text, _)| text == "hello")
                .expect("value text run recorded");
            assert_eq!(
                *value_fg, theme.header_fg,
                "a focused ReadOnly row's value must track the row's \
                 on-selection foreground, not an unconditional \
                 theme.muted_fg; text runs were {:?}",
                surface.text_runs,
            );
        }

        /// A `Toggle` paints as a drawn checkbox (a stroked box when
        /// off, a filled rounded box when on) — never the `[x]` /
        /// `[ ]` text glyph the TUI painter still uses.
        #[test]
        fn toggle_paints_drawn_checkbox_not_bracket_glyph() {
            let off = one_field_form("flag", FieldKind::Toggle { value: false });
            let (surface, _) = paint_recorded(&off);
            assert!(
                !surface.text_runs.iter().any(|(_, t, _)| t.contains('[')),
                "an unchecked toggle must not paint a bracket glyph; \
                 text runs were {:?}",
                surface.text_runs,
            );
            assert_eq!(
                surface.strokes.len(),
                1,
                "an unchecked toggle strokes exactly one box; strokes \
                 were {:?}",
                surface.strokes,
            );

            let on = one_field_form("flag", FieldKind::Toggle { value: true });
            let (surface, _) = paint_recorded(&on);
            assert!(
                !surface.text_runs.iter().any(|(_, t, _)| t.contains('[')),
                "a checked toggle must not paint a bracket glyph either; \
                 text runs were {:?}",
                surface.text_runs,
            );
            let theme = Theme::default();
            assert!(
                surface.fills.iter().any(|(_, c)| *c == theme.accent_fg),
                "a checked toggle fills its box with accent_fg; fills \
                 were {:?}",
                surface.fills,
            );
        }

        /// `TextInput` paints a stroked box around the value, not
        /// literal `[`/`]` text glyphs.
        #[test]
        fn text_input_paints_stroked_box_not_bracket_glyphs() {
            let form = one_field_form(
                "name",
                FieldKind::TextInput {
                    value: "hello".into(),
                    placeholder: String::new(),
                    cursor: None,
                    selection_anchor: None,
                },
            );
            let (surface, _) = paint_recorded(&form);
            assert!(
                !surface
                    .text_runs
                    .iter()
                    .any(|(_, t, _)| t == "[" || t == "]"),
                "no bracket glyph should be painted around the value; \
                 text runs were {:?}",
                surface.text_runs,
            );
            assert!(
                surface.text_runs.iter().any(|(_, t, _)| t == "hello"),
                "the value itself must still be painted; text runs \
                 were {:?}",
                surface.text_runs,
            );
            assert_eq!(
                surface.strokes.len(),
                1,
                "exactly one stroked box should bound the input; strokes \
                 were {:?}",
                surface.strokes,
            );
        }

        /// A field's validation message must not overlap its label —
        /// regression for the bug where both were painted vertically
        /// centred in the same row.
        #[test]
        fn validation_message_does_not_overlap_label() {
            let mut form = one_field_form(
                "name",
                FieldKind::TextInput {
                    value: String::new(),
                    placeholder: String::new(),
                    cursor: None,
                    selection_anchor: None,
                },
            );
            form.fields[0].label = StyledText::plain("Name");
            form.fields[0].validation = Some(ValidationState::Error("Required".to_string()));

            let row_h = form_row_height(14.0);
            let measure = form_field_measure(&form.fields[0], row_h, &FixedMeasure);
            let flayout = form.layout(320.0, 160.0, |_| measure.clone());
            let mut surface = RecordingSurface::default();
            paint(
                &form,
                &flayout,
                &mut surface,
                &Theme::default(),
                crate::Point::new(0.0, 0.0),
            );

            let (label_rect, _, _) = surface
                .text_runs
                .iter()
                .find(|(_, t, _)| t == "Name")
                .expect("label text run recorded");
            let (msg_rect, _, _) = surface
                .text_runs
                .iter()
                .find(|(_, t, _)| t == "Required")
                .expect("validation message text run recorded");

            let label_bottom = label_rect.y + label_rect.height;
            assert!(
                label_bottom <= msg_rect.y + 0.01,
                "validation message (y={}) must start at or below the \
                 label's bottom edge (y={}); label was {:?}, message was {:?}",
                msg_rect.y,
                label_bottom,
                label_rect,
                msg_rect,
            );
        }

        // The pill's inset math (degenerate-row fallback, the normal
        // inset-by-2 case, the exact-boundary case) and the
        // widget-state → "does this item get filled at all" decision
        // both live in `paint_geometry` now and have their own
        // tests there (`form_selection_pill_*`, `selected_item_fill_*`)
        // — deliberately not duplicated here. What this module's tests
        // above still own is the one thing `paint_geometry`'s pure-math
        // tests can't see: that `paint()` actually wires `Form` state
        // through to `selected_item_fill` and issues the resulting fill
        // via `PaintSurface`, exercised through `RecordingSurface`.
    }
}

// `#[allow(unused_imports)]`: see `mod native_surface_paint`'s doc — a
// `--features win` build on a non-Windows host has no reachable call site
// for `paint` (the Win one is further gated to `target_os = "windows"`).
#[cfg(any(
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
#[allow(unused_imports)]
pub(crate) use native_surface_paint::paint;

/// Events a `Form` emits back to the app.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum FormEvent {
    /// A `Toggle` field's value changed.
    ToggleChanged { id: WidgetId, value: bool },
    /// A `TextInput` field's text changed. Fires on every keystroke that
    /// modifies the value.
    TextInputChanged { id: WidgetId, value: String },
    /// A `TextInput` received Enter while focused.
    TextInputCommitted { id: WidgetId, value: String },
    /// A `Slider` field's value changed (drag, arrow key, Home/End).
    SliderChanged { id: WidgetId, value: f32 },
    /// A `ColorPicker` field produced a new colour.
    ColorChanged { id: WidgetId, value: crate::Color },
    /// A `Dropdown` field committed a new selection.
    DropdownChanged { id: WidgetId, selected_idx: usize },
    /// A `SegmentedControl` field committed a new selection.
    SegmentedControlChanged { id: WidgetId, selected_idx: usize },
    /// A `DatePicker` field confirmed a new date (Enter on the focused
    /// day). Mirrors `TextInputCommitted`'s "fires once, on confirm" shape
    /// rather than `TextInputChanged`'s "fires every keystroke" shape —
    /// moving the focused day without confirming does not emit this.
    DateChanged {
        id: WidgetId,
        value: crate::primitives::date_picker::CalendarDate,
    },
    /// Keyboard focus moved to a different field.
    FocusChanged { id: WidgetId },
    /// A `Button` was clicked or activated with Enter / Space.
    ButtonClicked { id: WidgetId },
    /// An action button inside a [`FieldKind::Toolbar`] field was
    /// clicked. `field_id` identifies the form field; `button_id`
    /// identifies the toolbar action within it.
    ToolbarButtonClicked {
        field_id: WidgetId,
        button_id: WidgetId,
    },
    /// A key was pressed while the form had focus and the primitive did
    /// not consume it. The app may interpret it (e.g. `?` opens help).
    KeyPressed { key: String, modifiers: Modifiers },
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::Color;

    #[test]
    fn form_roundtrip_serde() {
        let form = Form {
            id: WidgetId::new("settings"),
            fields: vec![
                FormField {
                    id: WidgetId::new("header"),
                    label: StyledText::plain("Editor"),
                    kind: FieldKind::Label,
                    hint: StyledText::default(),
                    disabled: false,
                    validation: None,
                },
                FormField {
                    id: WidgetId::new("line-numbers"),
                    label: StyledText::plain("Show line numbers"),
                    kind: FieldKind::Toggle { value: true },
                    hint: StyledText::default(),
                    disabled: false,
                    validation: None,
                },
                FormField {
                    id: WidgetId::new("tabstop"),
                    label: StyledText::plain("Tab width"),
                    kind: FieldKind::TextInput {
                        value: "4".to_string(),
                        placeholder: "2".to_string(),
                        cursor: Some(1),
                        selection_anchor: None,
                    },
                    hint: StyledText::plain("Number of spaces per tab"),
                    disabled: false,
                    validation: None,
                },
                FormField {
                    id: WidgetId::new("save"),
                    label: StyledText::plain("Save settings"),
                    kind: FieldKind::Button,
                    hint: StyledText::default(),
                    disabled: false,
                    validation: None,
                },
            ],
            focused_field: Some(WidgetId::new("line-numbers")),
            scroll_offset: 0,
            has_focus: true,
        };
        let json = serde_json::to_string(&form).unwrap();
        let back: Form = serde_json::from_str(&json).unwrap();
        assert_eq!(form, back);
    }

    #[test]
    fn form_event_roundtrip_serde() {
        let events = vec![
            FormEvent::ToggleChanged {
                id: WidgetId::new("line-numbers"),
                value: false,
            },
            FormEvent::TextInputChanged {
                id: WidgetId::new("tabstop"),
                value: "8".to_string(),
            },
            FormEvent::TextInputCommitted {
                id: WidgetId::new("tabstop"),
                value: "8".to_string(),
            },
            FormEvent::FocusChanged {
                id: WidgetId::new("save"),
            },
            FormEvent::ButtonClicked {
                id: WidgetId::new("save"),
            },
            FormEvent::KeyPressed {
                key: "Escape".to_string(),
                modifiers: Modifiers::default(),
            },
        ];
        for event in &events {
            let json = serde_json::to_string(event).unwrap();
            let back: FormEvent = serde_json::from_str(&json).unwrap();
            assert_eq!(event, &back);
        }
    }

    #[test]
    fn form_slider_field_serde() {
        let field = FormField {
            id: WidgetId::new("font-size"),
            label: StyledText::plain("Font size"),
            kind: FieldKind::Slider {
                value: 14.0,
                min: 8.0,
                max: 32.0,
                step: 1.0,
            },
            hint: StyledText::plain("Editor font size in px"),
            disabled: false,
            validation: None,
        };
        let json = serde_json::to_string(&field).unwrap();
        let back: FormField = serde_json::from_str(&json).unwrap();
        assert_eq!(field, back);
    }

    #[test]
    fn form_color_picker_field_serde() {
        let field = FormField {
            id: WidgetId::new("accent"),
            label: StyledText::plain("Accent colour"),
            kind: FieldKind::ColorPicker {
                value: Color::rgb(0x78, 0xb4, 0xff),
            },
            hint: StyledText::default(),
            disabled: false,
            validation: None,
        };
        let json = serde_json::to_string(&field).unwrap();
        let back: FormField = serde_json::from_str(&json).unwrap();
        assert_eq!(field, back);
    }

    #[test]
    fn form_dropdown_field_serde() {
        let field = FormField {
            id: WidgetId::new("theme"),
            label: StyledText::plain("Theme"),
            kind: FieldKind::Dropdown {
                options: vec![
                    StyledText::plain("One Dark"),
                    StyledText::plain("Solarized Light"),
                    StyledText::plain("Monokai"),
                ],
                selected_idx: 0,
            },
            hint: StyledText::default(),
            disabled: false,
            validation: None,
        };
        let json = serde_json::to_string(&field).unwrap();
        let back: FormField = serde_json::from_str(&json).unwrap();
        assert_eq!(field, back);
    }

    #[test]
    fn form_slider_legacy_deserialize_with_default_step() {
        // A client might omit `step` — it defaults to 1.0 via serde.
        let json = r#"{
            "id": "x",
            "label": {"spans":[{"text":"X","fg":null,"bg":null}]},
            "kind": {"Slider": {"value": 5.0, "min": 0.0, "max": 10.0}},
            "hint": {"spans":[]}
        }"#;
        let field: FormField = serde_json::from_str(json).unwrap();
        match field.kind {
            FieldKind::Slider { step, .. } => assert_eq!(step, 1.0),
            _ => panic!("expected Slider"),
        }
    }

    #[test]
    fn form_toggle_group_serde() {
        let field = FormField {
            id: WidgetId::new("opts"),
            label: StyledText::plain("Options"),
            kind: FieldKind::ToggleGroup {
                toggles: vec![
                    ToggleGroupItem {
                        id: WidgetId::new("case"),
                        label: "Aa".into(),
                        value: true,
                    },
                    ToggleGroupItem {
                        id: WidgetId::new("word"),
                        label: "Ab|".into(),
                        value: false,
                    },
                ],
            },
            hint: StyledText::default(),
            disabled: false,
            validation: None,
        };
        let json = serde_json::to_string(&field).unwrap();
        let back: FormField = serde_json::from_str(&json).unwrap();
        assert_eq!(field, back);
    }

    #[test]
    fn form_button_row_serde() {
        let field = FormField {
            id: WidgetId::new("actions"),
            label: StyledText::default(),
            kind: FieldKind::ButtonRow {
                buttons: vec![
                    ButtonRowItem {
                        id: WidgetId::new("next"),
                        label: "Find Next".into(),
                        disabled: false,
                        icon: None,
                    },
                    ButtonRowItem {
                        id: WidgetId::new("all"),
                        label: "Replace All".into(),
                        disabled: true,
                        icon: None,
                    },
                ],
            },
            hint: StyledText::default(),
            disabled: false,
            validation: None,
        };
        let json = serde_json::to_string(&field).unwrap();
        let back: FormField = serde_json::from_str(&json).unwrap();
        assert_eq!(field, back);
    }

    // ── D6 Form layout API tests ──────────────────────────────────────

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

    fn make_form(fields: Vec<FormField>, scroll: usize) -> Form {
        Form {
            id: WidgetId::new("f"),
            fields,
            focused_field: None,
            scroll_offset: scroll,
            has_focus: true,
        }
    }

    #[test]
    fn form_layout_empty() {
        let f = make_form(vec![], 0);
        let layout = f.layout(40.0, 20.0, |_| FormFieldMeasure::new(1.0));
        assert_eq!(layout.visible_fields.len(), 0);
        assert_eq!(layout.hit_test(5.0, 5.0), FormHit::Empty);
    }

    #[test]
    fn form_layout_stacks_fields() {
        let f = make_form(
            vec![
                make_form_field("header", "Editor", FieldKind::Label),
                make_form_field("toggle1", "Line numbers", FieldKind::Toggle { value: true }),
                make_form_field("btn", "Save", FieldKind::Button),
            ],
            0,
        );
        let layout = f.layout(40.0, 10.0, |_| FormFieldMeasure::new(1.0));
        assert_eq!(layout.visible_fields.len(), 3);
        assert_eq!(layout.visible_fields[0].bounds.y, 0.0);
        assert_eq!(layout.visible_fields[1].bounds.y, 1.0);
        assert_eq!(layout.visible_fields[2].bounds.y, 2.0);
        match layout.hit_test(10.0, 1.5) {
            FormHit::Field(id) => assert_eq!(id.as_str(), "toggle1"),
            _ => panic!("expected Field(toggle1)"),
        }
    }

    #[test]
    fn form_layout_hit_carries_widget_id_not_index() {
        // Adding fields in arbitrary order — hit_test returns the id,
        // not the flat index, so apps don't care about ordering.
        let f = make_form(
            vec![
                make_form_field("zebra", "Zebra", FieldKind::Button),
                make_form_field("alpha", "Alpha", FieldKind::Button),
            ],
            0,
        );
        let layout = f.layout(40.0, 5.0, |_| FormFieldMeasure::new(1.0));
        match layout.hit_test(10.0, 0.5) {
            FormHit::Field(id) => assert_eq!(id.as_str(), "zebra"),
            _ => panic!(),
        }
        match layout.hit_test(10.0, 1.5) {
            FormHit::Field(id) => assert_eq!(id.as_str(), "alpha"),
            _ => panic!(),
        }
    }

    #[test]
    fn form_layout_scroll_offset_skips() {
        let f = make_form(
            (0..5)
                .map(|i| make_form_field(&format!("f{i}"), &format!("F{i}"), FieldKind::Button))
                .collect(),
            2,
        );
        let layout = f.layout(40.0, 10.0, |_| FormFieldMeasure::new(1.0));
        assert_eq!(layout.visible_fields[0].field_idx, 2);
        assert_eq!(layout.visible_fields[0].id.as_str(), "f2");
    }

    #[test]
    fn form_layout_varying_heights_by_kind() {
        // Fields with hints are taller; Label rows can be shorter.
        let fields = vec![
            make_form_field("hdr", "Header", FieldKind::Label),
            make_form_field(
                "txt",
                "Name",
                FieldKind::TextInput {
                    value: "John".to_string(),
                    placeholder: String::new(),
                    cursor: Some(4),
                    selection_anchor: None,
                },
            ),
        ];
        let f = make_form(fields.clone(), 0);
        let layout = f.layout(40.0, 10.0, |i| {
            // Pretend TextInput fields are 2 rows tall (room for hint), Label is 1.
            match fields[i].kind {
                FieldKind::TextInput { .. } => FormFieldMeasure::new(2.0),
                _ => FormFieldMeasure::new(1.0),
            }
        });
        assert_eq!(layout.visible_fields[0].bounds.height, 1.0);
        assert_eq!(layout.visible_fields[1].bounds.y, 1.0);
        assert_eq!(layout.visible_fields[1].bounds.height, 2.0);
    }

    #[test]
    fn text_input_cursor_and_selection_serde() {
        // Round-trip a TextInput variant with explicit cursor + selection state.
        let field = FormField {
            id: WidgetId::new("name"),
            label: StyledText::plain("Name"),
            kind: FieldKind::TextInput {
                value: "hello world".to_string(),
                placeholder: String::new(),
                cursor: Some(5),
                selection_anchor: Some(0),
            },
            hint: StyledText::default(),
            disabled: false,
            validation: None,
        };
        let json = serde_json::to_string(&field).unwrap();
        let back: FormField = serde_json::from_str(&json).unwrap();
        assert_eq!(field, back);

        // Legacy shape without cursor/selection_anchor also deserializes
        // (new fields default to None) — ensures the extension is
        // backward-compatible with pre-A.3d serialised forms.
        let legacy = r#"{
            "id": "legacy",
            "label": {"spans":[{"text":"Legacy","fg":null,"bg":null}]},
            "kind": {"TextInput": {"value": "x"}},
            "hint": {"spans":[]}
        }"#;
        let parsed: FormField = serde_json::from_str(legacy).unwrap();
        match parsed.kind {
            FieldKind::TextInput {
                cursor,
                selection_anchor,
                ..
            } => {
                assert_eq!(cursor, None);
                assert_eq!(selection_anchor, None);
            }
            other => panic!("unexpected kind: {:?}", other),
        }
    }
}