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
//! [`TextInput`] — standalone multi-line text input primitive.
//!
//! Used for free-form text entry (commit messages, multi-line search,
//! note-taking). Stores text as a `Vec<String>` of lines, with cursor
//! position tracked as `(line, col)`. The primitive handles vertical
//! scroll auto-clamp (cursor stays in viewport) and emits hit regions
//! per visible line so consumers route clicks back to text positions.
//!
//! V1 is line-based (consumer pre-splits long input into lines). Word
//! wrap inside the primitive is a future extension; today consumers
//! split on `\n` or pre-wrap at their preferred width.
//!
//! ## Editing — [`EditOp`] / [`TextEditor`]
//!
//! [`EditOp`] is a closed set of edit intents (insert, delete, cursor
//! movement, selection, undo/redo); [`TextEditor::apply`] is the single
//! mutator that turns one into the next buffer/cursor/selection state,
//! so every consumer gets the same (correct, multibyte-safe) editing
//! behaviour. [`EditOp::from_key`] maps a plain keypress to the `EditOp`
//! it means; [`EditOp::from_key_binding`] maps the universal
//! [`crate::accelerator::KeyBinding::Undo`] /
//! [`crate::accelerator::KeyBinding::Redo`] /
//! [`crate::accelerator::KeyBinding::SelectAll`] accelerators the same
//! way.
//!
//! ## Why the editing state is a wrapper, not new `TextInput` fields
//!
//! [`TextEditor`] is a *wrapper* around `TextInput`, not a set of extra
//! fields on it, and that split is load-bearing rather than stylistic.
//!
//! `TextInput` is this crate's public paint-time snapshot type: all eight
//! of its fields are `pub`, and external consumers construct it with an
//! **exhaustive struct literal**. Rust gives no way to grow such a
//! struct without breaking those call sites:
//!
//! * a **private** field makes every external `TextInput { .. }` literal
//!   fail with `E0451`, and `..Default::default()` does *not* rescue it;
//! * a **public** field makes the same literal fail with `E0063`
//!   (`missing field`), unless every call site already used `..base`.
//!
//! Either way it is a breaking change under this repo's *Downstream
//! consumers* policy (`CLAUDE.md`) and `docs/PRIMITIVE_RULES.md` rule 8,
//! whose first preference is "a shape that isn't breaking at all". So
//! **both** pieces of live editing state — the selection anchor and the
//! undo history — live on `TextEditor`, and `TextInput`'s field list is
//! unchanged.
//!
//! `TextEditor` `Deref`s to the wrapped `TextInput`, so `.lines`,
//! `.cursor_line`, `.layout(..)` and `backend.draw_text_input(rect, &ed)`
//! all work directly on it. Every content-mutating op records the
//! pre-mutation snapshot into a bounded [`crate::undo::UndoStack`]; pure
//! cursor movement does not, so moving the cursor between two edits
//! doesn't split them into separate undo steps.
//!
//! Selection is therefore readable via [`TextEditor::selection_range`] /
//! [`TextEditor::selected_text`] rather than off a bare `&TextInput`. No
//! rasteriser paints a selection highlight yet; when one does, it takes
//! the range as an argument (a new function alongside the old one — the
//! non-breaking shape rule 8 asks for) rather than reading a new
//! `TextInput` field.

use serde::{Deserialize, Serialize};

use crate::accelerator::KeyBinding;
use crate::event::{Key, NamedKey, Rect};
use crate::types::{Modifiers, WidgetId};
use crate::undo::UndoStack;

/// Multi-line text input. Text is stored as one entry per line — empty
/// lines are empty strings. Cursor is `(line, col)` in *char columns*
/// (not bytes); the rasterisers convert as needed.
///
/// `PartialEq`/`Eq` are derived: every field here is content/cursor/
/// viewport state with no runtime-only editing state attached — see this
/// module's *Why the editing state is a wrapper* section for why the
/// selection anchor and undo history live on [`TextEditor`] instead of
/// being fields here (short version: adding **any** field, `pub` or
/// private, breaks external exhaustive `TextInput { .. }` literals).
///
/// Every field below has a matching `with_*` builder on [`TextInput::new`],
/// and the type implements `Default`, so a consumer constructs with
/// `TextInput::new(id)` / `TextInput::default()` and chains `with_*`
/// instead of an exhaustive struct literal.
///
/// # Examples
///
/// ```
/// use quadraui::{Rect, TextInput, TextInputMeasure, WidgetId};
///
/// let input = TextInput::new(WidgetId::new("input:commit_message"))
///     .with_lines(vec!["fix: typo".to_string()])
///     .with_cursor_col(9)
///     .with_has_focus(true);
///
/// let rect = Rect::new(0.0, 0.0, 40.0, 3.0);
/// let layout = input.layout(rect, TextInputMeasure::new(1.0, 1.0));
///
/// assert_eq!(layout.visible_lines.len(), 1);
/// assert!(layout.cursor_bounds.is_some());
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TextInput {
    pub id: WidgetId,
    /// One entry per logical line. Newlines are implicit between
    /// consecutive entries. Empty input is `vec![String::new()]`.
    pub lines: Vec<String>,
    /// Cursor line index. Clamped to `lines.len().saturating_sub(1)`
    /// by [`Self::layout`].
    #[serde(default)]
    pub cursor_line: usize,
    /// Cursor column within the cursor line, in *char columns*.
    /// Clamped to the line's char count by [`Self::layout`].
    #[serde(default)]
    pub cursor_col: usize,
    /// Optional placeholder shown when `lines` is empty or contains a
    /// single empty string. Rendered in muted color.
    #[serde(default)]
    pub placeholder: Option<String>,
    /// First visible line index. The primitive clamps this so the
    /// cursor stays inside the viewport.
    #[serde(default)]
    pub scroll_offset: usize,
    /// Horizontal scroll, in char columns. Applied to *every* line.
    /// The primitive clamps this so the cursor stays in view.
    #[serde(default)]
    pub scroll_col: usize,
    /// Whether the input has keyboard focus. Controls cursor visibility
    /// and border color (rasteriser-defined).
    #[serde(default)]
    pub has_focus: bool,
}

impl TextInput {
    pub fn new(id: WidgetId) -> Self {
        Self {
            id,
            lines: vec![String::new()],
            cursor_line: 0,
            cursor_col: 0,
            placeholder: None,
            scroll_offset: 0,
            scroll_col: 0,
            has_focus: false,
        }
    }

    /// Replace [`Self::lines`] — one entry per logical line.
    #[must_use]
    pub fn with_lines(mut self, lines: Vec<String>) -> Self {
        self.lines = lines;
        self
    }

    /// Set [`Self::cursor_line`].
    #[must_use]
    pub fn with_cursor_line(mut self, cursor_line: usize) -> Self {
        self.cursor_line = cursor_line;
        self
    }

    /// Set [`Self::cursor_col`].
    #[must_use]
    pub fn with_cursor_col(mut self, cursor_col: usize) -> Self {
        self.cursor_col = cursor_col;
        self
    }

    /// Set [`Self::placeholder`].
    #[must_use]
    pub fn with_placeholder(mut self, placeholder: impl Into<String>) -> Self {
        self.placeholder = Some(placeholder.into());
        self
    }

    /// Set [`Self::scroll_offset`].
    #[must_use]
    pub fn with_scroll_offset(mut self, scroll_offset: usize) -> Self {
        self.scroll_offset = scroll_offset;
        self
    }

    /// Set [`Self::scroll_col`].
    #[must_use]
    pub fn with_scroll_col(mut self, scroll_col: usize) -> Self {
        self.scroll_col = scroll_col;
        self
    }

    /// Set [`Self::has_focus`].
    #[must_use]
    pub fn with_has_focus(mut self, has_focus: bool) -> Self {
        self.has_focus = has_focus;
        self
    }
}

/// Same shape as [`TextInput::new`] with an empty `WidgetId` — the
/// `new(required…)`/`with_*`/`Default` trio that lets a
/// consumer build a `TextInput` without an exhaustive struct literal.
impl Default for TextInput {
    fn default() -> Self {
        Self::new(WidgetId::new(String::new()))
    }
}

/// An edit intent for [`TextEditor::apply`] — see the module doc.
///
/// Every variant that moves the cursor (`Move*`, `SetCursor`) carries an
/// `extend` flag: `false` collapses any active selection and moves the
/// cursor normally (a plain arrow-key press); `true` starts a selection
/// at the cursor's pre-move position if none is active yet, then moves
/// only the cursor (a shift-held arrow key, or a mouse drag).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EditOp {
    /// Insert one character at the cursor. `'\n'` splits the current
    /// line. If a selection is active, it is deleted first (so this also
    /// implements "type over the selection").
    InsertChar(char),
    /// Insert a (possibly multi-line) string at the cursor — e.g. a
    /// clipboard paste. Same selection-replace behaviour as
    /// [`Self::InsertChar`].
    InsertText(String),
    /// Backspace: delete the selection if one is active, else the one
    /// character before the cursor (merging with the previous line at
    /// column 0).
    DeleteBackward,
    /// Delete (forward-delete): delete the selection if one is active,
    /// else the one character after the cursor (merging with the next
    /// line at end-of-line).
    DeleteForward,
    /// Delete the active selection with no replacement. A no-op (returns
    /// `false` from [`TextEditor::apply`]) when no selection is active —
    /// callers doing "Cut" should read [`TextEditor::selected_text`]
    /// first, then apply this.
    DeleteSelection,
    /// Move the cursor one character left (or to the end of the previous
    /// line, if already at column 0).
    MoveLeft { extend: bool },
    /// Move the cursor one character right (or to the start of the next
    /// line, if already at end-of-line).
    MoveRight { extend: bool },
    /// Move the cursor up one line, clamping the column to the target
    /// line's length.
    MoveUp { extend: bool },
    /// Move the cursor down one line, clamping the column to the target
    /// line's length.
    MoveDown { extend: bool },
    /// Move the cursor to column 0 of the current line.
    MoveLineStart { extend: bool },
    /// Move the cursor to the end of the current line.
    MoveLineEnd { extend: bool },
    /// Move the cursor to `(0, 0)`.
    MoveDocStart { extend: bool },
    /// Move the cursor to the end of the last line.
    MoveDocEnd { extend: bool },
    /// Jump the cursor to an arbitrary `(line, col)` — e.g. from
    /// [`TextInputLayout::hit_test`] resolving a mouse click, or a drag
    /// extending a selection to the drag position.
    SetCursor {
        line: usize,
        col: usize,
        extend: bool,
    },
    /// Select the entire buffer.
    SelectAll,
    /// Undo the last content-mutating op. No-op if there's nothing to
    /// undo.
    Undo,
    /// Redo the last undone op. No-op if there's nothing to redo (or a
    /// new edit was made since the last undo).
    Redo,
}

impl EditOp {
    /// Map a plain keypress to the [`EditOp`] it means, for widgets
    /// wiring [`crate::event::UiEvent::KeyPressed`] straight into
    /// [`TextEditor::apply`]. Returns `None` for keys `TextEditor` doesn't
    /// interpret (function keys, Escape, Tab, ...) — callers handle
    /// those themselves (Escape to blur, Tab to move focus, etc.).
    ///
    /// `Ctrl+Home`/`Ctrl+End` map to [`EditOp::MoveDocStart`]/
    /// [`EditOp::MoveDocEnd`]; plain `Home`/`End` map to
    /// [`EditOp::MoveLineStart`]/[`EditOp::MoveLineEnd`]. `modifiers.shift`
    /// becomes every movement op's `extend` flag.
    pub fn from_key(key: &Key, modifiers: Modifiers) -> Option<EditOp> {
        let extend = modifiers.shift;
        match key {
            Key::Char(c) => Some(EditOp::InsertChar(*c)),
            Key::Named(NamedKey::Enter) => Some(EditOp::InsertChar('\n')),
            Key::Named(NamedKey::Backspace) => Some(EditOp::DeleteBackward),
            Key::Named(NamedKey::Delete) => Some(EditOp::DeleteForward),
            Key::Named(NamedKey::Left) => Some(EditOp::MoveLeft { extend }),
            Key::Named(NamedKey::Right) => Some(EditOp::MoveRight { extend }),
            Key::Named(NamedKey::Up) => Some(EditOp::MoveUp { extend }),
            Key::Named(NamedKey::Down) => Some(EditOp::MoveDown { extend }),
            Key::Named(NamedKey::Home) if modifiers.ctrl => Some(EditOp::MoveDocStart { extend }),
            Key::Named(NamedKey::End) if modifiers.ctrl => Some(EditOp::MoveDocEnd { extend }),
            Key::Named(NamedKey::Home) => Some(EditOp::MoveLineStart { extend }),
            Key::Named(NamedKey::End) => Some(EditOp::MoveLineEnd { extend }),
            _ => None,
        }
    }

    /// Map a universal [`KeyBinding`] accelerator to the [`EditOp`] it
    /// represents — wires [`KeyBinding::Undo`]/[`KeyBinding::Redo`]/
    /// [`KeyBinding::SelectAll`] to real `TextInput` behaviour. Apps register
    /// an [`crate::accelerator::Accelerator`] with one of these bindings and,
    /// on the matching [`crate::event::UiEvent::Accelerator`], call
    /// `text_input.apply(op)` with the result.
    ///
    /// Returns `None` for every other binding: `Copy`/`Cut`/`Paste` need
    /// clipboard content that arrives via
    /// [`crate::event::UiEvent::ClipboardPaste`]/`TextCopied`, not the
    /// accelerator alone, so they're not represented as an `EditOp` — callers
    /// wire `Cut`/`Copy` through [`TextEditor::selected_text`] plus
    /// (for `Cut`) [`EditOp::DeleteSelection`], and `Paste` through
    /// [`EditOp::InsertText`] fed by `ClipboardPaste`'s payload.
    pub fn from_key_binding(binding: &KeyBinding) -> Option<EditOp> {
        match binding {
            KeyBinding::Undo => Some(EditOp::Undo),
            KeyBinding::Redo => Some(EditOp::Redo),
            KeyBinding::SelectAll => Some(EditOp::SelectAll),
            _ => None,
        }
    }
}

/// Snapshot of the editable state — everything [`EditOp::Undo`]/
/// [`EditOp::Redo`] restore. Deliberately excludes `id`/`placeholder`/
/// `scroll_offset`/`scroll_col`/`has_focus`: those aren't buffer content,
/// so undoing an edit shouldn't also snap the viewport back.
#[derive(Debug, Clone, PartialEq, Eq)]
struct TextInputSnapshot {
    lines: Vec<String>,
    cursor_line: usize,
    cursor_col: usize,
    selection_anchor: Option<(usize, usize)>,
}

/// Byte offset of the `col`-th char boundary in `line` (`col` in char
/// columns), clamped to `line.len()` if `col` exceeds the line's char
/// count.
fn byte_offset_for_col(line: &str, col: usize) -> usize {
    line.char_indices()
        .nth(col)
        .map(|(b, _)| b)
        .unwrap_or(line.len())
}

/// Buffer-level primitives shared by [`TextEditor`]'s [`EditOp`]
/// handling.
///
/// These are deliberately **private** and selection-unaware: they rewrite
/// `lines` and move the cursor, and leave everything to do with the
/// selection anchor or the undo history to [`TextEditor`], which is where
/// that state lives (see this module's *Why the editing state is a
/// wrapper* section). Keeping them on `TextInput` means each one operates
/// on exactly the fields it mutates; keeping them private means they add
/// nothing to `TextInput`'s public surface.
impl TextInput {
    fn line_len(&self, line: usize) -> usize {
        self.lines.get(line).map_or(0, |l| l.chars().count())
    }

    fn clamp_pos(&self, line: usize, col: usize) -> (usize, usize) {
        let line = line.min(self.lines.len().saturating_sub(1));
        let col = col.min(self.line_len(line));
        (line, col)
    }

    fn text_in_range(&self, start: (usize, usize), end: (usize, usize)) -> String {
        let (sl, sc) = start;
        let (el, ec) = end;
        if sl == el {
            let line = self.lines.get(sl).map(String::as_str).unwrap_or("");
            let sb = byte_offset_for_col(line, sc);
            let eb = byte_offset_for_col(line, ec);
            return line[sb.min(eb)..sb.max(eb)].to_string();
        }
        let mut out = String::new();
        let first = self.lines.get(sl).map(String::as_str).unwrap_or("");
        out.push_str(&first[byte_offset_for_col(first, sc)..]);
        for line in &self.lines[sl + 1..el] {
            out.push('\n');
            out.push_str(line);
        }
        out.push('\n');
        let last = self.lines.get(el).map(String::as_str).unwrap_or("");
        out.push_str(&last[..byte_offset_for_col(last, ec)]);
        out
    }

    /// Delete `start..end` and leave the cursor at `start`. Clearing the
    /// selection anchor is the caller's job — this type has no anchor.
    fn delete_range(&mut self, start: (usize, usize), end: (usize, usize)) {
        let (sl, sc) = start;
        let (el, ec) = end;
        if sl == el {
            if let Some(line) = self.lines.get_mut(sl) {
                let sb = byte_offset_for_col(line, sc);
                let eb = byte_offset_for_col(line, ec);
                line.replace_range(sb..eb, "");
            }
        } else {
            let head = {
                let line = self.lines.get(sl).map(String::as_str).unwrap_or("");
                line[..byte_offset_for_col(line, sc)].to_string()
            };
            let tail = {
                let line = self.lines.get(el).map(String::as_str).unwrap_or("");
                line[byte_offset_for_col(line, ec)..].to_string()
            };
            self.lines.splice(sl..=el, [format!("{head}{tail}")]);
        }
        self.cursor_line = sl;
        self.cursor_col = sc;
    }

    fn insert_char_raw(&mut self, ch: char) {
        if self.lines.is_empty() {
            self.lines.push(String::new());
        }
        if ch == '\n' {
            let line = self.lines[self.cursor_line].as_str();
            let byte = byte_offset_for_col(line, self.cursor_col);
            let rest = self.lines[self.cursor_line][byte..].to_string();
            self.lines[self.cursor_line].truncate(byte);
            self.lines.insert(self.cursor_line + 1, rest);
            self.cursor_line += 1;
            self.cursor_col = 0;
        } else {
            let line = &mut self.lines[self.cursor_line];
            let byte = byte_offset_for_col(line, self.cursor_col);
            line.insert(byte, ch);
            self.cursor_col += 1;
        }
    }

    fn insert_text_raw(&mut self, text: &str) {
        for ch in text.chars() {
            self.insert_char_raw(ch);
        }
    }

    fn delete_backward_raw(&mut self) -> bool {
        if self.cursor_col > 0 {
            let line = &mut self.lines[self.cursor_line];
            let end = byte_offset_for_col(line, self.cursor_col);
            let start = byte_offset_for_col(line, self.cursor_col - 1);
            line.replace_range(start..end, "");
            self.cursor_col -= 1;
            true
        } else if self.cursor_line > 0 {
            let current = self.lines.remove(self.cursor_line);
            self.cursor_line -= 1;
            let prev_len = self.line_len(self.cursor_line);
            self.lines[self.cursor_line].push_str(&current);
            self.cursor_col = prev_len;
            true
        } else {
            false
        }
    }

    fn delete_forward_raw(&mut self) -> bool {
        let len = self.line_len(self.cursor_line);
        if self.cursor_col < len {
            let line = &mut self.lines[self.cursor_line];
            let start = byte_offset_for_col(line, self.cursor_col);
            let end = byte_offset_for_col(line, self.cursor_col + 1);
            line.replace_range(start..end, "");
            true
        } else if self.cursor_line + 1 < self.lines.len() {
            let next = self.lines.remove(self.cursor_line + 1);
            self.lines[self.cursor_line].push_str(&next);
            true
        } else {
            false
        }
    }
}

/// Bounded so a long-lived editor (e.g. a persistent chat input, or a
/// large commit-message buffer) doesn't accumulate unbounded history —
/// each undo step clones the full `lines: Vec<String>`. 200 steps is
/// generous for interactive editing while keeping worst-case memory
/// proportional to a small constant times the buffer size, not to how
/// long the widget has been alive.
const UNDO_HISTORY_LIMIT: usize = 200;

/// An editing session over a [`TextInput`] — handles insert / delete /
/// cursor-movement / selection / undo behaviour.
///
/// `TextEditor` owns the two pieces of live editing state that
/// deliberately are **not** `TextInput` fields: the selection anchor, and
/// a bounded [`crate::undo::UndoStack`] of buffer snapshots. See this
/// module's *Why the editing state is a wrapper* section for why — the
/// short version is that adding **any** field to `TextInput`, `pub` or
/// private, breaks external exhaustive `TextInput { .. }` struct literals
/// (`E0063` / `E0451`).
///
/// Access the wrapped `TextInput` through the public [`Self::input`]
/// field or through `Deref`/`DerefMut`, so `.lines`, `.cursor_line`,
/// `.layout(..)` and `backend.draw_text_input(rect, &editor)` all work
/// directly on a `TextEditor`.
/// ```
/// use quadraui::{EditOp, TextEditor, TextInput, WidgetId};
///
/// let mut ed = TextEditor::new(TextInput::new(WidgetId::new("demo")));
/// ed.apply(EditOp::InsertText("hi".into()));
/// ed.apply(EditOp::MoveLeft { extend: true });
/// assert_eq!(ed.selected_text().as_deref(), Some("i"));
/// ed.apply(EditOp::Undo);
/// assert_eq!(ed.lines, vec![String::new()]);
/// ```
#[derive(Debug, Clone)]
pub struct TextEditor {
    /// The wrapped paint-time state — hand this to a rasteriser.
    pub input: TextInput,
    selection_anchor: Option<(usize, usize)>,
    undo_stack: UndoStack<TextInputSnapshot>,
}

impl TextEditor {
    /// Start an editing session over `input`, with an empty undo history
    /// and no active selection.
    pub fn new(input: TextInput) -> Self {
        Self {
            input,
            selection_anchor: None,
            undo_stack: UndoStack::with_limit(UNDO_HISTORY_LIMIT),
        }
    }

    /// The selection anchor `(line, col)`, in the same char-column space
    /// as [`TextInput::cursor_line`]/[`TextInput::cursor_col`]. The
    /// cursor is the *moving* end of a selection; this is the *fixed*
    /// end. `None` means no active selection. A selection exists only
    /// when this is `Some` **and** differs from the cursor position —
    /// see [`Self::selection_range`].
    pub fn selection_anchor(&self) -> Option<(usize, usize)> {
        self.selection_anchor
    }

    /// Set (or clear) the selection anchor directly. Most callers should
    /// go through [`EditOp`]'s `extend` flag instead; this exists for
    /// backends driving a selection from a native gesture that doesn't
    /// decompose into `EditOp`s.
    pub fn set_selection_anchor(&mut self, anchor: Option<(usize, usize)>) {
        self.selection_anchor = anchor;
    }

    /// The selection as an ordered `(start, end)` pair of `(line, col)`
    /// positions, or `None` if no selection is active (the anchor is
    /// `None`, or equals the current cursor position).
    pub fn selection_range(&self) -> Option<((usize, usize), (usize, usize))> {
        let anchor = self.selection_anchor?;
        let cursor = (self.input.cursor_line, self.input.cursor_col);
        if anchor == cursor {
            return None;
        }
        Some(if anchor <= cursor {
            (anchor, cursor)
        } else {
            (cursor, anchor)
        })
    }

    /// The text currently selected, or `None` if no selection is active.
    /// Multi-line selections join lines with `'\n'`, mirroring how
    /// [`EditOp::InsertText`] would re-insert the same text verbatim.
    pub fn selected_text(&self) -> Option<String> {
        let (start, end) = self.selection_range()?;
        Some(self.input.text_in_range(start, end))
    }

    fn snapshot(&self) -> TextInputSnapshot {
        TextInputSnapshot {
            lines: self.input.lines.clone(),
            cursor_line: self.input.cursor_line,
            cursor_col: self.input.cursor_col,
            selection_anchor: self.selection_anchor,
        }
    }

    fn restore(&mut self, snap: TextInputSnapshot) {
        self.input.lines = snap.lines;
        self.input.cursor_line = snap.cursor_line;
        self.input.cursor_col = snap.cursor_col;
        self.selection_anchor = snap.selection_anchor;
    }

    /// Delete the active selection, if any. Returns whether anything was
    /// deleted. Does **not** record undo itself — that's [`Self::apply`]'s
    /// job, so a delete-then-insert op pair stays one undo step.
    fn delete_selection(&mut self) -> bool {
        match self.selection_range() {
            Some((start, end)) => {
                self.input.delete_range(start, end);
                self.selection_anchor = None;
                true
            }
            None => false,
        }
    }

    /// Move the cursor to `pos`, updating (or clearing) the selection
    /// anchor per `extend`. Returns whether anything actually changed.
    fn move_cursor_to(&mut self, pos: (usize, usize), extend: bool) -> bool {
        let before = (self.input.cursor_line, self.input.cursor_col);
        let anchor_before = self.selection_anchor;
        if extend {
            if self.selection_anchor.is_none() {
                self.selection_anchor = Some(before);
            }
        } else {
            self.selection_anchor = None;
        }
        self.input.cursor_line = pos.0;
        self.input.cursor_col = pos.1;
        before != pos || self.selection_anchor != anchor_before
    }

    /// Apply one [`EditOp`], mutating the wrapped [`TextInput`] in place.
    /// Returns whether anything actually changed (useful for deciding
    /// whether a redraw is needed).
    ///
    /// `Undo`/`Redo` are served from this editor's history. Every other
    /// op mutates the buffer/cursor/selection, with a pre-mutation
    /// snapshot recorded first for content-mutating ops (insert/delete)
    /// so undo can restore it. Pure cursor/selection movement is not
    /// recorded, so moving the cursor between two edits doesn't split
    /// them into separate undo steps.
    pub fn apply(&mut self, op: EditOp) -> bool {
        match op {
            EditOp::Undo => {
                let current = self.snapshot();
                match self.undo_stack.undo(current) {
                    Some(prev) => {
                        self.restore(prev);
                        true
                    }
                    None => false,
                }
            }
            EditOp::Redo => {
                let current = self.snapshot();
                match self.undo_stack.redo(current) {
                    Some(next) => {
                        self.restore(next);
                        true
                    }
                    None => false,
                }
            }
            other => {
                let content_mutating = matches!(
                    other,
                    EditOp::InsertChar(_)
                        | EditOp::InsertText(_)
                        | EditOp::DeleteBackward
                        | EditOp::DeleteForward
                        | EditOp::DeleteSelection
                );
                if content_mutating {
                    let snap = self.snapshot();
                    let changed = self.apply_edit(other);
                    if changed {
                        self.undo_stack.record(snap);
                    }
                    changed
                } else {
                    self.apply_edit(other)
                }
            }
        }
    }

    /// Every [`EditOp`] except `Undo`/`Redo`, with no history
    /// bookkeeping — [`Self::apply`] wraps this.
    fn apply_edit(&mut self, op: EditOp) -> bool {
        match op {
            EditOp::InsertChar(ch) => {
                self.delete_selection();
                self.input.insert_char_raw(ch);
                true
            }
            EditOp::InsertText(text) => {
                self.delete_selection();
                self.input.insert_text_raw(&text);
                true
            }
            EditOp::DeleteBackward => {
                if self.delete_selection() {
                    true
                } else {
                    self.input.delete_backward_raw()
                }
            }
            EditOp::DeleteForward => {
                if self.delete_selection() {
                    true
                } else {
                    self.input.delete_forward_raw()
                }
            }
            EditOp::DeleteSelection => self.delete_selection(),
            EditOp::MoveLeft { extend } => {
                // An unmodified arrow press while a selection is active
                // collapses to the selection's near edge instead of also
                // taking a step from the cursor's (moving-end) position —
                // otherwise a single Left press after a rightward
                // shift-selection would visually jump two characters.
                if !extend {
                    if let Some((start, _end)) = self.selection_range() {
                        return self.move_cursor_to(start, false);
                    }
                }
                let (line, col) = (self.input.cursor_line, self.input.cursor_col);
                let target = if col > 0 {
                    (line, col - 1)
                } else if line > 0 {
                    (line - 1, self.input.line_len(line - 1))
                } else {
                    (line, col)
                };
                self.move_cursor_to(target, extend)
            }
            EditOp::MoveRight { extend } => {
                // See `MoveLeft`: collapses to the selection's far edge.
                if !extend {
                    if let Some((_start, end)) = self.selection_range() {
                        return self.move_cursor_to(end, false);
                    }
                }
                let (line, col) = (self.input.cursor_line, self.input.cursor_col);
                let len = self.input.line_len(line);
                let target = if col < len {
                    (line, col + 1)
                } else if line + 1 < self.input.lines.len() {
                    (line + 1, 0)
                } else {
                    (line, col)
                };
                self.move_cursor_to(target, extend)
            }
            EditOp::MoveUp { extend } => {
                let target = if self.input.cursor_line > 0 {
                    self.input
                        .clamp_pos(self.input.cursor_line - 1, self.input.cursor_col)
                } else {
                    (self.input.cursor_line, self.input.cursor_col)
                };
                self.move_cursor_to(target, extend)
            }
            EditOp::MoveDown { extend } => {
                let target = if self.input.cursor_line + 1 < self.input.lines.len() {
                    self.input
                        .clamp_pos(self.input.cursor_line + 1, self.input.cursor_col)
                } else {
                    (self.input.cursor_line, self.input.cursor_col)
                };
                self.move_cursor_to(target, extend)
            }
            EditOp::MoveLineStart { extend } => {
                self.move_cursor_to((self.input.cursor_line, 0), extend)
            }
            EditOp::MoveLineEnd { extend } => {
                let len = self.input.line_len(self.input.cursor_line);
                self.move_cursor_to((self.input.cursor_line, len), extend)
            }
            EditOp::MoveDocStart { extend } => self.move_cursor_to((0, 0), extend),
            EditOp::MoveDocEnd { extend } => {
                let last = self.input.lines.len().saturating_sub(1);
                let len = self.input.line_len(last);
                self.move_cursor_to((last, len), extend)
            }
            EditOp::SetCursor { line, col, extend } => {
                let target = self.input.clamp_pos(line, col);
                self.move_cursor_to(target, extend)
            }
            EditOp::SelectAll => {
                let last = self.input.lines.len().saturating_sub(1);
                let end = (last, self.input.line_len(last));
                if end == (0, 0) {
                    false
                } else {
                    self.selection_anchor = Some((0, 0));
                    self.input.cursor_line = end.0;
                    self.input.cursor_col = end.1;
                    true
                }
            }
            // Handled by `apply`, which never forwards them here.
            EditOp::Undo | EditOp::Redo => false,
        }
    }
}

impl std::ops::Deref for TextEditor {
    type Target = TextInput;
    fn deref(&self) -> &TextInput {
        &self.input
    }
}

impl std::ops::DerefMut for TextEditor {
    fn deref_mut(&mut self) -> &mut TextInput {
        &mut self.input
    }
}

/// Hit-test classification for clicks inside a `TextInput`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TextInputHit {
    /// Click landed on a text line — the consumer maps `(line, col)`
    /// to a new cursor position.
    Line { line_idx: usize },
    /// Click landed in the content area but past the last line.
    EmptyArea,
}

/// One visible line resolved by layout.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct VisibleTextInputLine {
    /// Index into [`TextInput::lines`].
    pub line_idx: usize,
    pub bounds: Rect,
}

/// Fully-resolved layout.
#[derive(Debug, Clone, PartialEq)]
pub struct TextInputLayout {
    /// Outer bounds (matches the `rect` argument to layout).
    pub bounds: Rect,
    /// Content bounds (inside any border/padding the rasteriser draws).
    pub content_bounds: Rect,
    pub visible_lines: Vec<VisibleTextInputLine>,
    /// Cursor bounds in viewport pixels/cells when the cursor is inside
    /// the visible window, otherwise `None`. Rasterisers paint a cursor
    /// glyph (TUI) or vertical bar (GTK) at this rect.
    pub cursor_bounds: Option<Rect>,
    /// Vertical scroll offset after auto-clamp. The primitive
    /// guarantees the cursor is visible by adjusting this.
    pub resolved_scroll_offset: usize,
    /// Horizontal scroll offset (char columns) after auto-clamp.
    /// Rasterisers slice each line `[resolved_scroll_col..]` before
    /// painting.
    pub resolved_scroll_col: usize,
    /// Per-region hit map for click routing.
    pub hit_regions: Vec<(Rect, TextInputHit)>,
    /// True when the placeholder was rendered (lines empty / single
    /// empty line). Rasterisers consult this to draw the placeholder
    /// in a muted color.
    pub placeholder_active: bool,
}

impl TextInputLayout {
    /// Hit-test a click at surface-native coordinates `(x, y)` against
    /// this layout's `hit_regions`.
    ///
    /// Coordinate frame: **ABSOLUTE** — matches [`TextInputLayout`]'s own
    /// convention (`bounds`/`content_bounds`/`hit_regions` all carry
    /// `rect.x`/`rect.y`, per `PRIMITIVE_RULES.md`'s coordinate-frame
    /// table). Returns [`TextInputHit::EmptyArea`] when `(x, y)` falls
    /// outside every region.
    pub fn hit_test(&self, x: f32, y: f32) -> TextInputHit {
        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();
            }
        }
        TextInputHit::EmptyArea
    }
}

/// Per-line measurement supplied by the backend.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextInputMeasure {
    /// Height of one row in surface-native units (TUI: 1.0 cells;
    /// GTK: line_height pixels).
    pub row_height: f32,
    /// Width of one character column in surface-native units. TUI: 1.0
    /// (cells). GTK: the monospace `char_width` from the backend — used to
    /// position the cursor and route clicks back to columns.
    pub char_width: f32,
}

impl TextInputMeasure {
    pub fn new(row_height: f32, char_width: f32) -> Self {
        Self {
            row_height,
            char_width,
        }
    }

    /// Build from the backend's own [`crate::backend::Metrics`]
    /// (`backend.measure()`) instead of hand-threading
    /// `backend.line_height()` / `backend.char_width()` through
    /// [`Self::new`] — the two are identical, this just names the
    /// intent.
    pub fn from_metrics(m: &crate::backend::Metrics) -> Self {
        Self::new(m.line_height, m.char_width)
    }
}

/// Border (1 cell/px) + horizontal padding (1 char column) inset shared by
/// [`TextInput::layout`] (which uses it to compute `content_bounds`) and
/// [`TextInput::content_cols`] (which uses it to compute a pre-wrap column
/// budget) — kept as one function so the two computations can't drift
/// apart.
fn content_x_inset(char_w: f32) -> f32 {
    let border = 1.0;
    let pad_x = char_w;
    border + pad_x
}

impl TextInput {
    /// Compute layout for `rect`. `measure` supplies row height + char
    /// width in the backend's native units.
    pub fn layout(&self, rect: Rect, measure: TextInputMeasure) -> TextInputLayout {
        let row_h = measure.row_height.max(1.0);
        let char_w = measure.char_width.max(1.0);

        // Border (1 cell / 1 px) + horizontal padding (1 char column).
        // Vertical padding is zero so each row neatly fills `row_h`.
        let border = 1.0;
        let inset = content_x_inset(char_w);
        let content_x = rect.x + inset;
        let content_y = rect.y + border;
        let content_w = (rect.width - inset * 2.0).max(0.0);
        let content_h = (rect.height - border * 2.0).max(0.0);
        let content_bounds = Rect::new(content_x, content_y, content_w, content_h);

        let total_lines = self.lines.len().max(1);
        let max_rows = ((content_h / row_h).floor() as usize).max(1);
        let visible_cols = ((content_w / char_w).floor() as usize).max(1);

        // Clamp cursor line/col to text bounds.
        let cursor_line = self.cursor_line.min(total_lines.saturating_sub(1));
        let cursor_col = {
            let line = self.lines.get(cursor_line).map_or("", String::as_str);
            self.cursor_col.min(line.chars().count())
        };

        // Vertical scroll auto-clamp.
        let max_scroll = total_lines.saturating_sub(max_rows);
        let mut scroll = self.scroll_offset.min(max_scroll);
        if cursor_line < scroll {
            scroll = cursor_line;
        } else if cursor_line >= scroll + max_rows {
            scroll = cursor_line + 1 - max_rows;
        }
        scroll = scroll.min(max_scroll);

        // Horizontal scroll auto-clamp — keep cursor inside [scroll_col,
        // scroll_col + visible_cols). Reserve one column of slack so the
        // cursor itself stays visible (not flush against the right edge).
        let mut scroll_col = self.scroll_col;
        if cursor_col < scroll_col {
            scroll_col = cursor_col;
        } else if cursor_col >= scroll_col + visible_cols {
            scroll_col = cursor_col + 1 - visible_cols;
        }

        let visible_count = total_lines.saturating_sub(scroll).min(max_rows);
        let mut visible_lines: Vec<VisibleTextInputLine> = Vec::with_capacity(visible_count);
        let mut hit_regions: Vec<(Rect, TextInputHit)> = Vec::with_capacity(visible_count + 1);

        let placeholder_active = self.placeholder.is_some()
            && (self.lines.is_empty() || (self.lines.len() == 1 && self.lines[0].is_empty()));

        for i in 0..visible_count {
            let line_idx = scroll + i;
            let row_y = content_y + i as f32 * row_h;
            let row_bounds = Rect::new(content_x, row_y, content_w, row_h);
            visible_lines.push(VisibleTextInputLine {
                line_idx,
                bounds: row_bounds,
            });
            hit_regions.push((row_bounds, TextInputHit::Line { line_idx }));
        }

        // Empty-area hit zone: any vertical space below the last
        // visible line.
        let used_h = visible_count as f32 * row_h;
        if used_h < content_h {
            hit_regions.push((
                Rect::new(content_x, content_y + used_h, content_w, content_h - used_h),
                TextInputHit::EmptyArea,
            ));
        }

        // Cursor bounds — only when in the visible window.
        let cursor_bounds = if cursor_line >= scroll && cursor_line < scroll + visible_count {
            let row_off = cursor_line - scroll;
            let col_off = cursor_col.saturating_sub(scroll_col);
            let cursor_x = content_x + col_off as f32 * char_w;
            let cursor_y = content_y + row_off as f32 * row_h;
            Some(Rect::new(cursor_x, cursor_y, char_w, row_h))
        } else {
            None
        };

        TextInputLayout {
            bounds: rect,
            content_bounds,
            visible_lines,
            cursor_bounds,
            resolved_scroll_offset: scroll,
            resolved_scroll_col: scroll_col,
            hit_regions,
            placeholder_active,
        }
    }

    /// Content width in *char columns* for an outer `TextInput` width of
    /// `width` at `char_width` — the same border+padding inset
    /// [`Self::layout`] uses internally to compute `content_bounds`, minus
    /// the row-height/height terms `layout` also needs (a column budget
    /// doesn't depend on `rect.height`).
    ///
    /// Exposed so callers that need to pre-wrap text to a fixed width
    /// *before* calling [`Self::layout`] — e.g.
    /// [`crate::compose::ChatController`]'s soft-wrapping, auto-growing
    /// chat input — compute the same budget `layout` will
    /// end up rendering into, without duplicating the border/padding
    /// constants (and risking the two drifting apart).
    pub fn content_cols(width: f32, char_width: f32) -> usize {
        let char_w = char_width.max(1.0);
        let inset = content_x_inset(char_w);
        let content_w = (width - inset * 2.0).max(0.0);
        ((content_w / char_w).floor() as usize).max(1)
    }
}

// ── PaintSurface paint ─────────────────────────────────────────────────
//
// This module provides a portable paint implementation for `MacBackend`'s
// `draw_text_input`. Unlike `TextDisplay`/`Form`/`FindReplacePanel`, GTK
// and Windows already carry their own per-backend `draw_text_input`
// rasterisers. This module avoids a fourth bespoke per-backend copy by
// building once against the portable `PaintSurface` verbs.
//
// Shape mirrors the Windows implementation (the simplest of the three
// existing twins — no selection-range painting, since `TextInput`
// itself carries none; see this module's own doc, "Selection is
// therefore readable via `TextEditor::selection_range`..."): fill the
// background, stroke a focus-aware border, paint the placeholder or each
// visible (post-h-scroll) line, then — only when focused — a 2-unit-wide
// cursor bar at `TextInputLayout::cursor_bounds`, the exact rect
// `text_input_layout` already hands a host for click routing and IME
// placement. No geometry is re-derived here — the whole point of taking
// an already-resolved `&TextInputLayout` rather than laying out `ti`
// itself.
#[cfg(all(feature = "macos", target_os = "macos"))]
#[allow(dead_code)]
mod native_surface_paint {
    use super::{TextInput, TextInputLayout};
    use crate::event::Rect;
    use crate::paint_surface::PaintSurface;
    use crate::theme::Theme;

    /// Insert-cursor width in surface-native units. Matches
    /// `win::text_input::CURSOR_W_DIP` / `gtk::text_input`'s cursor bar.
    const CURSOR_W: f32 = 2.0;

    /// Slice `line` at char offset `off`, returning the tail (the part
    /// visible given horizontal scroll) — same idiom every existing
    /// `draw_text_input` twin uses independently.
    fn slice_from(line: &str, off: usize) -> String {
        if off == 0 {
            line.to_string()
        } else {
            line.chars().skip(off).collect()
        }
    }

    /// Paint `ti` using `layout` (must be the same layout the caller
    /// hit-tests against — typically `ti.layout(rect, measure)`'s own
    /// return value) via `surface`'s [`PaintSurface`] verbs.
    pub(crate) fn paint(
        ti: &TextInput,
        layout: &TextInputLayout,
        surface: &mut dyn PaintSurface,
        theme: &Theme,
    ) {
        let rect = layout.bounds;
        if rect.width <= 0.0 || rect.height <= 0.0 {
            return;
        }

        surface.surface_fill_rect(rect, theme.background);
        let border_color = if ti.has_focus {
            theme.accent_fg
        } else {
            theme.border_fg
        };
        surface.surface_stroke_rect(rect, border_color, 1.0);

        let h_scroll = layout.resolved_scroll_col;

        if layout.placeholder_active {
            if let (Some(text), Some(first)) =
                (ti.placeholder.as_ref(), layout.visible_lines.first())
            {
                surface.surface_draw_text_run(first.bounds, text, theme.muted_fg);
            }
        } else {
            for vis in &layout.visible_lines {
                let full = ti.lines.get(vis.line_idx).map(String::as_str).unwrap_or("");
                let visible = slice_from(full, h_scroll);
                if visible.is_empty() {
                    continue;
                }
                surface.surface_draw_text_run(vis.bounds, &visible, theme.foreground);
            }
        }

        if ti.has_focus {
            if let Some(cb) = layout.cursor_bounds {
                let cursor_rect = Rect::new(cb.x, cb.y, CURSOR_W, cb.height);
                surface.surface_fill_rect(cursor_rect, theme.cursor);
            }
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use crate::backend::ImagePaintResult;
        use crate::primitives::text_input::TextInputMeasure;
        use crate::types::{Color, WidgetId};
        use crate::{Image, Point, Viewport};

        /// Records every `PaintSurface` verb `paint` calls, without a
        /// real pixel backend — the same fake shape
        /// `find_replace::native_surface_paint::tests::RecordingSurface`
        /// and `form::native_surface_paint::tests::RecordingSurface`
        /// already use.
        #[derive(Default)]
        struct RecordingSurface {
            fills: Vec<(Rect, Color)>,
            strokes: Vec<(Rect, Color, f32)>,
            text_runs: Vec<(Rect, String, Color)>,
        }

        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(0.0, 0.0, 1.0)
            }
            fn surface_line_height(&self) -> f32 {
                16.0
            }
            fn surface_char_width(&self) -> f32 {
                8.0
            }
            fn surface_measure_text(&self, text: &str) -> (f32, f32) {
                (text.chars().count() as f32 * 8.0, 16.0)
            }
            fn surface_fill_rect(&mut self, rect: Rect, color: Color) {
                self.fills.push((rect, color));
            }
            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,
            ) {
                self.strokes.push((rect, color, stroke_width));
            }
            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: Point,
                _to: 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
            }
        }

        fn sample(lines: Vec<&str>, cursor_line: usize, cursor_col: usize) -> TextInput {
            let mut ti = TextInput::new(WidgetId::new("ti"));
            ti.lines = lines.into_iter().map(String::from).collect();
            ti.cursor_line = cursor_line;
            ti.cursor_col = cursor_col;
            ti.has_focus = true;
            ti
        }

        /// A text input's value and cursor must both appear in the recorded
        /// paint.
        #[test]
        fn value_and_cursor_both_paint() {
            let ti = sample(vec!["hello"], 0, 3);
            let rect = Rect::new(0.0, 0.0, 200.0, 20.0);
            let layout = ti.layout(rect, TextInputMeasure::new(16.0, 8.0));
            let mut surface = RecordingSurface::default();
            let theme = Theme::default();

            paint(&ti, &layout, &mut surface, &theme);

            assert!(
                surface.text_runs.iter().any(|(_, t, _)| t == "hello"),
                "expected the input's value to be drawn as a text run, text runs were {:?}",
                surface.text_runs,
            );
            let cb = layout.cursor_bounds.expect("cursor visible");
            assert!(
                surface
                    .fills
                    .iter()
                    .any(|(r, c)| *c == theme.cursor && (r.x - cb.x).abs() < 0.01),
                "expected a cursor-colored fill at cursor_bounds.x, fills were {:?}",
                surface.fills,
            );
        }

        #[test]
        fn unfocused_input_paints_no_cursor() {
            let mut ti = sample(vec!["hello"], 0, 3);
            ti.has_focus = false;
            let rect = Rect::new(0.0, 0.0, 200.0, 20.0);
            let layout = ti.layout(rect, TextInputMeasure::new(16.0, 8.0));
            let mut surface = RecordingSurface::default();
            let theme = Theme::default();

            paint(&ti, &layout, &mut surface, &theme);

            assert!(
                !surface.fills.iter().any(|(_, c)| *c == theme.cursor),
                "unfocused input must not paint a cursor, fills were {:?}",
                surface.fills,
            );
            assert!(surface.text_runs.iter().any(|(_, t, _)| t == "hello"));
        }

        #[test]
        fn placeholder_paints_in_muted_fg_when_empty() {
            let mut ti = TextInput::new(WidgetId::new("ti"));
            ti.placeholder = Some("type here".into());
            ti.has_focus = false;
            let rect = Rect::new(0.0, 0.0, 200.0, 20.0);
            let layout = ti.layout(rect, TextInputMeasure::new(16.0, 8.0));
            let mut surface = RecordingSurface::default();
            let theme = Theme::default();

            paint(&ti, &layout, &mut surface, &theme);

            assert!(surface
                .text_runs
                .iter()
                .any(|(_, t, c)| t == "type here" && *c == theme.muted_fg));
        }

        #[test]
        fn zero_size_rect_is_a_no_op() {
            let ti = sample(vec!["hello"], 0, 0);
            let rect = Rect::new(0.0, 0.0, 0.0, 20.0);
            let layout = ti.layout(rect, TextInputMeasure::new(16.0, 8.0));
            let mut surface = RecordingSurface::default();
            let theme = Theme::default();

            paint(&ti, &layout, &mut surface, &theme);

            assert!(surface.fills.is_empty());
            assert!(surface.strokes.is_empty());
            assert!(surface.text_runs.is_empty());
        }
    }
}

#[cfg(all(feature = "macos", target_os = "macos"))]
pub(crate) use native_surface_paint::paint;

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

    fn input(lines: Vec<&str>) -> TextInput {
        let mut ti = TextInput::new(WidgetId::new("ti"));
        ti.lines = lines.into_iter().map(String::from).collect();
        ti.has_focus = true;
        ti
    }

    /// An editing session over [`input`]'s buffer — the entry point for
    /// every `apply(EditOp)` test below. `TextEditor` `Deref`s to the
    /// wrapped `TextInput`, so `.lines` / `.cursor_col` reads and writes
    /// in these tests still go straight through to the primitive.
    fn editor(lines: Vec<&str>) -> TextEditor {
        TextEditor::new(input(lines))
    }

    fn measure() -> TextInputMeasure {
        TextInputMeasure::new(1.0, 1.0)
    }

    fn rect(w: f32, h: f32) -> Rect {
        Rect::new(0.0, 0.0, w, h)
    }

    #[test]
    fn empty_input_renders_one_row() {
        let ti = TextInput::new(WidgetId::new("ti"));
        let l = ti.layout(rect(20.0, 10.0), measure());
        assert_eq!(l.visible_lines.len(), 1);
        assert_eq!(l.visible_lines[0].line_idx, 0);
    }

    #[test]
    fn placeholder_active_when_empty() {
        let mut ti = TextInput::new(WidgetId::new("ti"));
        ti.placeholder = Some("type here".into());
        let l = ti.layout(rect(20.0, 10.0), measure());
        assert!(l.placeholder_active);
    }

    #[test]
    fn placeholder_inactive_with_content() {
        let mut ti = input(vec!["hello"]);
        ti.placeholder = Some("type here".into());
        let l = ti.layout(rect(20.0, 10.0), measure());
        assert!(!l.placeholder_active);
    }

    #[test]
    fn cursor_bounds_at_origin_when_empty() {
        let ti = TextInput::new(WidgetId::new("ti"));
        let l = ti.layout(rect(20.0, 10.0), measure());
        let cb = l.cursor_bounds.unwrap();
        // Border (1) + horizontal padding (1 char_width) -> content starts at x=2.
        // Vertical padding is zero so content_y = border = 1.
        assert_eq!(cb.x, 2.0);
        assert_eq!(cb.y, 1.0);
        assert_eq!(cb.width, 1.0);
        assert_eq!(cb.height, 1.0);
    }

    #[test]
    fn cursor_bounds_track_col() {
        let mut ti = input(vec!["hello"]);
        ti.cursor_col = 3;
        let l = ti.layout(rect(20.0, 10.0), measure());
        assert_eq!(l.cursor_bounds.unwrap().x, 2.0 + 3.0); // content_x + col
    }

    #[test]
    fn cursor_col_clamped_to_line_length() {
        let mut ti = input(vec!["hi"]);
        ti.cursor_col = 99;
        let l = ti.layout(rect(20.0, 10.0), measure());
        assert_eq!(l.cursor_bounds.unwrap().x, 2.0 + 2.0); // clamped to 2
    }

    #[test]
    fn cursor_line_clamped_to_total() {
        let mut ti = input(vec!["a", "b", "c"]);
        ti.cursor_line = 99;
        let l = ti.layout(rect(20.0, 10.0), measure());
        assert!(l.cursor_bounds.is_some());
        // Cursor lands on line index 2 (last available).
        let cb = l.cursor_bounds.unwrap();
        assert_eq!(cb.y, 1.0 + 2.0); // border + 2 rows
    }

    // ── Horizontal scroll ────────────────────────────────────────────

    #[test]
    fn h_scroll_auto_pulls_cursor_into_view_rightward() {
        // Wide line, narrow viewport.
        let mut ti = input(vec!["abcdefghijklmnopqrstuvwxyz"]);
        // content_w = 10 - 2(border) - 2(pad) = 6 -> visible_cols = 6.
        ti.cursor_col = 20;
        let l = ti.layout(rect(10.0, 5.0), measure());
        // Cursor should be visible: scroll_col = 20 + 1 - 6 = 15.
        assert_eq!(l.resolved_scroll_col, 15);
        // Cursor x = content_x + (cursor_col - scroll_col) * char_w = 2 + 5 = 7.
        assert_eq!(l.cursor_bounds.unwrap().x, 7.0);
    }

    #[test]
    fn h_scroll_auto_pulls_cursor_into_view_leftward() {
        let mut ti = input(vec!["abcdefghijklmnopqrstuvwxyz"]);
        ti.cursor_col = 2;
        ti.scroll_col = 20; // stale — cursor is left of view
        let l = ti.layout(rect(10.0, 5.0), measure());
        assert_eq!(l.resolved_scroll_col, 2);
    }

    #[test]
    fn h_scroll_zero_when_line_fits() {
        let mut ti = input(vec!["short"]);
        ti.cursor_col = 5;
        let l = ti.layout(rect(20.0, 5.0), measure());
        assert_eq!(l.resolved_scroll_col, 0);
    }

    #[test]
    fn scroll_auto_pulls_cursor_into_view_downward() {
        // 10 lines, viewport fits 3, cursor on line 7.
        let mut ti = input(vec!["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]);
        ti.cursor_line = 7;
        // content height = 5 - 2 (border) = 3, max_rows = 3.
        let l = ti.layout(rect(20.0, 5.0), measure());
        // Cursor should be visible: scroll = 7 + 1 - 3 = 5
        assert_eq!(l.resolved_scroll_offset, 5);
        assert!(l.cursor_bounds.is_some());
    }

    #[test]
    fn scroll_auto_pulls_cursor_into_view_upward() {
        let mut ti = input(vec!["0", "1", "2", "3", "4", "5"]);
        ti.cursor_line = 1;
        ti.scroll_offset = 4; // stale — cursor is above viewport
        let l = ti.layout(rect(20.0, 5.0), measure());
        assert_eq!(l.resolved_scroll_offset, 1);
    }

    #[test]
    fn scroll_clamped_when_cursor_in_view() {
        let mut ti = input(vec!["0", "1", "2", "3"]);
        ti.cursor_line = 0;
        ti.scroll_offset = 99; // wildly stale
        let l = ti.layout(rect(20.0, 10.0), measure());
        // max_scroll = 4 - (10-2)/1 = 4 - 8 = 0, so clamp to 0
        assert_eq!(l.resolved_scroll_offset, 0);
    }

    #[test]
    fn hit_regions_one_per_visible_line() {
        let ti = input(vec!["a", "b", "c"]);
        let l = ti.layout(rect(20.0, 10.0), measure());
        let line_hits: Vec<_> = l
            .hit_regions
            .iter()
            .filter(|(_, h)| matches!(h, TextInputHit::Line { .. }))
            .collect();
        assert_eq!(line_hits.len(), 3);
    }

    #[test]
    fn empty_area_hit_region_below_last_line() {
        let ti = input(vec!["only"]);
        let l = ti.layout(rect(20.0, 10.0), measure());
        let empty = l
            .hit_regions
            .iter()
            .find(|(_, h)| matches!(h, TextInputHit::EmptyArea));
        assert!(empty.is_some());
    }

    #[test]
    fn hit_test_line_returns_line_idx() {
        let ti = input(vec!["a", "b", "c"]);
        let l = ti.layout(rect(20.0, 10.0), measure());
        // Row 1 (0-indexed) is line_idx 1, at content_y=1.0 + 1*row_h=1.0.
        assert_eq!(l.hit_test(5.0, 2.0), TextInputHit::Line { line_idx: 1 });
    }

    #[test]
    fn hit_test_below_last_line_returns_empty_area() {
        let ti = input(vec!["only"]);
        let l = ti.layout(rect(20.0, 10.0), measure());
        assert_eq!(l.hit_test(5.0, 8.0), TextInputHit::EmptyArea);
    }

    #[test]
    fn hit_test_outside_bounds_returns_empty_area() {
        let ti = input(vec!["only"]);
        let l = ti.layout(rect(20.0, 10.0), measure());
        assert_eq!(l.hit_test(-5.0, -5.0), TextInputHit::EmptyArea);
    }

    #[test]
    fn cursor_bounds_none_when_off_screen() {
        // Force scroll_offset stale by manipulating cursor_line.
        // Build 10 lines, cursor on 0, but max_rows shows 3 — should
        // auto-scroll to keep cursor in view (so this is harder to test).
        // Test the literal off-screen case: cursor_line clamped to 2,
        // scroll forced to 0, max_rows = 1.
        let mut ti = input(vec!["a", "b", "c"]);
        ti.cursor_line = 2;
        ti.scroll_offset = 0;
        let l = ti.layout(rect(20.0, 3.0), measure()); // content_h = 1, max_rows = 1
                                                       // Auto-scroll keeps cursor in view, so it's still visible:
        assert!(l.cursor_bounds.is_some());
        assert_eq!(l.resolved_scroll_offset, 2);
    }

    // ── content_cols (column budget for pre-wrap) ──────────────────────────

    #[test]
    fn content_cols_matches_layouts_content_width() {
        // Same rect/measure `layout()` would use — the column budget must
        // agree with what `content_bounds.width` actually renders, or a
        // caller pre-wrapping text to `content_cols` would produce rows
        // that don't fit (or leave slack) once painted.
        let ti = TextInput::new(WidgetId::new("ti"));
        let l = ti.layout(rect(20.0, 10.0), measure());
        let cols = TextInput::content_cols(20.0, 1.0);
        assert_eq!(cols, l.content_bounds.width as usize);
    }

    #[test]
    fn content_cols_never_below_one() {
        // A pathologically narrow rect must still yield a usable (>=1)
        // wrap budget, not zero (which would make callers loop forever
        // trying to fit even a single character per row).
        assert_eq!(TextInput::content_cols(0.0, 1.0), 1);
        assert_eq!(TextInput::content_cols(1.0, 8.0), 1);
    }

    // ── apply(EditOp) — insert / delete / cursor / selection / undo ─────

    #[test]
    fn insert_char_advances_cursor() {
        let mut ti = editor(vec![""]);
        assert!(ti.apply(EditOp::InsertChar('h')));
        assert!(ti.apply(EditOp::InsertChar('i')));
        assert_eq!(ti.lines, vec!["hi".to_string()]);
        assert_eq!((ti.cursor_line, ti.cursor_col), (0, 2));
    }

    #[test]
    fn insert_char_newline_splits_line() {
        let mut ti = editor(vec!["helloworld"]);
        ti.cursor_col = 5;
        assert!(ti.apply(EditOp::InsertChar('\n')));
        assert_eq!(ti.lines, vec!["hello".to_string(), "world".to_string()]);
        assert_eq!((ti.cursor_line, ti.cursor_col), (1, 0));
    }

    #[test]
    fn insert_char_is_multibyte_safe() {
        // Cursor sits after 'h' + é (a 2-byte char) — inserting must not
        // panic slicing mid-char, and must land after the é (char column
        // 2), not the byte offset.
        let mut ti = editor(vec!["héllo"]);
        ti.cursor_col = 2; // after 'h', 'é'
        assert!(ti.apply(EditOp::InsertChar('X')));
        assert_eq!(ti.lines, vec!["héXllo".to_string()]);
    }

    #[test]
    fn insert_text_with_embedded_newline_creates_lines() {
        let mut ti = editor(vec![""]);
        assert!(ti.apply(EditOp::InsertText("ab\ncd".to_string())));
        assert_eq!(ti.lines, vec!["ab".to_string(), "cd".to_string()]);
        assert_eq!((ti.cursor_line, ti.cursor_col), (1, 2));
    }

    #[test]
    fn delete_backward_removes_prior_char() {
        let mut ti = editor(vec!["hi"]);
        ti.cursor_col = 2;
        assert!(ti.apply(EditOp::DeleteBackward));
        assert_eq!(ti.lines, vec!["h".to_string()]);
        assert_eq!(ti.cursor_col, 1);
    }

    #[test]
    fn delete_backward_at_line_start_merges_with_previous_line() {
        let mut ti = editor(vec!["foo", "bar"]);
        ti.cursor_line = 1;
        ti.cursor_col = 0;
        assert!(ti.apply(EditOp::DeleteBackward));
        assert_eq!(ti.lines, vec!["foobar".to_string()]);
        assert_eq!((ti.cursor_line, ti.cursor_col), (0, 3));
    }

    #[test]
    fn delete_backward_at_doc_start_is_a_no_op() {
        let mut ti = editor(vec!["hi"]);
        assert!(!ti.apply(EditOp::DeleteBackward));
        assert_eq!(ti.lines, vec!["hi".to_string()]);
    }

    #[test]
    fn delete_forward_removes_next_char() {
        let mut ti = editor(vec!["hi"]);
        assert!(ti.apply(EditOp::DeleteForward));
        assert_eq!(ti.lines, vec!["i".to_string()]);
        assert_eq!(ti.cursor_col, 0);
    }

    #[test]
    fn delete_forward_at_line_end_merges_next_line() {
        let mut ti = editor(vec!["foo", "bar"]);
        ti.cursor_col = 3; // end of "foo"
        assert!(ti.apply(EditOp::DeleteForward));
        assert_eq!(ti.lines, vec!["foobar".to_string()]);
    }

    #[test]
    fn delete_forward_at_doc_end_is_a_no_op() {
        let mut ti = editor(vec!["hi"]);
        ti.cursor_col = 2;
        assert!(!ti.apply(EditOp::DeleteForward));
    }

    #[test]
    fn move_right_then_left_round_trips() {
        let mut ti = editor(vec!["hi"]);
        assert!(ti.apply(EditOp::MoveRight { extend: false }));
        assert_eq!(ti.cursor_col, 1);
        assert!(ti.apply(EditOp::MoveLeft { extend: false }));
        assert_eq!(ti.cursor_col, 0);
    }

    #[test]
    fn move_right_at_line_end_wraps_to_next_line() {
        let mut ti = editor(vec!["ab", "cd"]);
        ti.cursor_col = 2;
        assert!(ti.apply(EditOp::MoveRight { extend: false }));
        assert_eq!((ti.cursor_line, ti.cursor_col), (1, 0));
    }

    #[test]
    fn move_left_at_line_start_wraps_to_previous_line_end() {
        let mut ti = editor(vec!["ab", "cd"]);
        ti.cursor_line = 1;
        assert!(ti.apply(EditOp::MoveLeft { extend: false }));
        assert_eq!((ti.cursor_line, ti.cursor_col), (0, 2));
    }

    #[test]
    fn move_up_down_clamp_column_to_shorter_line() {
        let mut ti = editor(vec!["abcdef", "xy"]);
        ti.cursor_col = 5;
        assert!(ti.apply(EditOp::MoveDown { extend: false }));
        assert_eq!((ti.cursor_line, ti.cursor_col), (1, 2)); // clamped to "xy"'s length
        assert!(ti.apply(EditOp::MoveUp { extend: false }));
        assert_eq!((ti.cursor_line, ti.cursor_col), (0, 2)); // clamped col preserved
    }

    #[test]
    fn move_line_start_end_and_doc_start_end() {
        let mut ti = editor(vec!["abc", "de"]);
        ti.cursor_line = 1;
        ti.cursor_col = 1;
        assert!(ti.apply(EditOp::MoveLineEnd { extend: false }));
        assert_eq!(ti.cursor_col, 2);
        assert!(ti.apply(EditOp::MoveLineStart { extend: false }));
        assert_eq!(ti.cursor_col, 0);
        assert!(ti.apply(EditOp::MoveDocEnd { extend: false }));
        assert_eq!((ti.cursor_line, ti.cursor_col), (1, 2));
        assert!(ti.apply(EditOp::MoveDocStart { extend: false }));
        assert_eq!((ti.cursor_line, ti.cursor_col), (0, 0));
    }

    #[test]
    fn set_cursor_clamps_out_of_range_position() {
        let mut ti = editor(vec!["abc"]);
        assert!(ti.apply(EditOp::SetCursor {
            line: 99,
            col: 99,
            extend: false
        }));
        assert_eq!((ti.cursor_line, ti.cursor_col), (0, 3));
    }

    // ── selection ─────────────────────────────────────────────────────

    #[test]
    fn extend_move_creates_selection_and_selected_text() {
        let mut ti = editor(vec!["hello"]);
        ti.apply(EditOp::MoveRight { extend: true });
        ti.apply(EditOp::MoveRight { extend: true });
        assert_eq!(ti.selection_range(), Some(((0, 0), (0, 2))));
        assert_eq!(ti.selected_text().as_deref(), Some("he"));
    }

    #[test]
    fn plain_move_after_extend_collapses_selection() {
        let mut ti = editor(vec!["hello"]);
        ti.apply(EditOp::MoveRight { extend: true });
        ti.apply(EditOp::MoveRight { extend: false });
        assert_eq!(ti.selection_range(), None);
    }

    #[test]
    fn unmodified_left_after_selection_lands_on_near_edge() {
        // Selecting rightward then pressing plain Left should land the
        // cursor exactly on the selection's start, not one further step
        // left of the (moving-end) cursor position.
        let mut ti = editor(vec!["hello"]);
        ti.apply(EditOp::MoveRight { extend: true });
        ti.apply(EditOp::MoveRight { extend: true }); // selects "he", cursor at col 2
        assert!(ti.apply(EditOp::MoveLeft { extend: false }));
        assert_eq!((ti.cursor_line, ti.cursor_col), (0, 0));
        assert_eq!(ti.selection_range(), None);
    }

    #[test]
    fn unmodified_right_after_selection_lands_on_far_edge() {
        // Same as above, mirrored: plain Right lands on the selection's
        // end rather than stepping one further right of the cursor.
        let mut ti = editor(vec!["hello"]);
        ti.apply(EditOp::MoveRight { extend: true });
        ti.apply(EditOp::MoveRight { extend: true }); // selects "he", cursor at col 2
        assert!(ti.apply(EditOp::MoveRight { extend: false }));
        assert_eq!((ti.cursor_line, ti.cursor_col), (0, 2));
        assert_eq!(ti.selection_range(), None);
    }

    #[test]
    fn unmodified_left_after_leftward_selection_lands_on_near_edge() {
        // Selecting *leftward* (cursor is the near edge already) then
        // pressing plain Left should still land on the selection start —
        // exercising the anchor > cursor ordering in `selection_range`.
        let mut ti = editor(vec!["hello"]);
        ti.cursor_col = 3;
        ti.apply(EditOp::MoveLeft { extend: true });
        ti.apply(EditOp::MoveLeft { extend: true }); // selects "el" (cols 1..3), cursor at col 1
        assert!(ti.apply(EditOp::MoveLeft { extend: false }));
        assert_eq!((ti.cursor_line, ti.cursor_col), (0, 1));
        assert_eq!(ti.selection_range(), None);
    }

    #[test]
    fn select_all_selects_entire_buffer() {
        let mut ti = editor(vec!["ab", "cde"]);
        assert!(ti.apply(EditOp::SelectAll));
        assert_eq!(ti.selected_text().as_deref(), Some("ab\ncde"));
    }

    #[test]
    fn insert_over_selection_replaces_it() {
        let mut ti = editor(vec!["hello"]);
        ti.apply(EditOp::MoveRight { extend: true });
        ti.apply(EditOp::MoveRight { extend: true }); // selects "he"
        assert!(ti.apply(EditOp::InsertChar('X')));
        assert_eq!(ti.lines, vec!["Xllo".to_string()]);
        assert_eq!(ti.selection_range(), None);
    }

    #[test]
    fn delete_backward_over_selection_deletes_selection_not_one_char() {
        let mut ti = editor(vec!["hello"]);
        ti.apply(EditOp::MoveRight { extend: true });
        ti.apply(EditOp::MoveRight { extend: true }); // selects "he"
        assert!(ti.apply(EditOp::DeleteBackward));
        assert_eq!(ti.lines, vec!["llo".to_string()]);
    }

    #[test]
    fn delete_selection_op_clears_selection_with_no_replacement() {
        let mut ti = editor(vec!["hello"]);
        ti.apply(EditOp::MoveRight { extend: true });
        ti.apply(EditOp::MoveRight { extend: true });
        assert!(ti.apply(EditOp::DeleteSelection));
        assert_eq!(ti.lines, vec!["llo".to_string()]);
        assert_eq!(ti.selection_range(), None);
    }

    #[test]
    fn delete_selection_with_no_selection_is_a_no_op() {
        let mut ti = editor(vec!["hello"]);
        assert!(!ti.apply(EditOp::DeleteSelection));
    }

    #[test]
    fn multiline_selection_spans_lines() {
        let mut ti = editor(vec!["abc", "def"]);
        ti.apply(EditOp::MoveDown { extend: true });
        ti.apply(EditOp::MoveLineEnd { extend: true });
        assert_eq!(ti.selected_text().as_deref(), Some("abc\ndef"));
    }

    // ── undo / redo (via `TextEditor` — see its module doc for
    //    why history is not a `TextInput` field) ─────────────────────

    #[test]
    fn redo_with_no_history_is_a_no_op() {
        let mut ti = editor(vec![""]);
        ti.apply(EditOp::InsertChar('h'));
        assert!(!ti.apply(EditOp::Redo), "nothing has been undone yet");
        assert_eq!(ti.lines, vec!["h".to_string()]);
    }

    #[test]
    fn undo_reverts_last_insert() {
        let mut ti = editor(vec![""]);
        ti.apply(EditOp::InsertChar('h'));
        ti.apply(EditOp::InsertChar('i'));
        assert_eq!(ti.lines, vec!["hi".to_string()]);
        assert!(ti.apply(EditOp::Undo));
        assert_eq!(ti.lines, vec!["h".to_string()]);
        assert!(ti.apply(EditOp::Undo));
        assert_eq!(ti.lines, vec!["".to_string()]);
    }

    #[test]
    fn undo_with_no_history_is_a_no_op() {
        let mut ti = editor(vec![""]);
        assert!(!ti.apply(EditOp::Undo));
    }

    #[test]
    fn redo_restores_undone_edit() {
        let mut ti = editor(vec![""]);
        ti.apply(EditOp::InsertChar('h'));
        ti.apply(EditOp::Undo);
        assert_eq!(ti.lines, vec!["".to_string()]);
        assert!(ti.apply(EditOp::Redo));
        assert_eq!(ti.lines, vec!["h".to_string()]);
    }

    #[test]
    fn new_edit_after_undo_clears_redo_history() {
        let mut ti = editor(vec![""]);
        ti.apply(EditOp::InsertChar('a'));
        ti.apply(EditOp::Undo);
        ti.apply(EditOp::InsertChar('b'));
        assert!(
            !ti.apply(EditOp::Redo),
            "redo history should have been invalidated by the new edit"
        );
        assert_eq!(ti.lines, vec!["b".to_string()]);
    }

    #[test]
    fn cursor_movement_does_not_create_an_undo_step() {
        // Typing, then moving, then undoing should undo the typing — not
        // a no-op "undo the move" step.
        let mut ti = editor(vec![""]);
        ti.apply(EditOp::InsertChar('a'));
        ti.apply(EditOp::MoveLeft { extend: false });
        assert!(ti.apply(EditOp::Undo));
        assert_eq!(ti.lines, vec!["".to_string()]);
    }

    #[test]
    fn undo_restores_selection_state() {
        let mut ti = editor(vec!["hello"]);
        ti.apply(EditOp::MoveRight { extend: true });
        ti.apply(EditOp::MoveRight { extend: true }); // selects "he"
        ti.apply(EditOp::DeleteSelection);
        assert_eq!(ti.lines, vec!["llo".to_string()]);
        assert!(ti.apply(EditOp::Undo));
        assert_eq!(ti.lines, vec!["hello".to_string()]);
        assert_eq!(ti.selection_range(), Some(((0, 0), (0, 2))));
    }

    #[test]
    fn undo_history_is_bounded() {
        // Regression test for the unbounded-memory concern: recording
        // more than `UNDO_HISTORY_LIMIT` steps evicts the oldest ones
        // instead of growing forever.
        let mut ti = editor(vec![""]);
        for _ in 0..UNDO_HISTORY_LIMIT + 50 {
            ti.apply(EditOp::InsertChar('a'));
        }
        let mut undone = 0;
        while ti.apply(EditOp::Undo) {
            undone += 1;
        }
        assert_eq!(undone, UNDO_HISTORY_LIMIT);
    }

    // ── EditOp::from_key / from_key_binding ──────────────────────────

    #[test]
    fn from_key_maps_plain_char_to_insert() {
        assert_eq!(
            EditOp::from_key(&Key::Char('x'), Modifiers::default()),
            Some(EditOp::InsertChar('x'))
        );
    }

    #[test]
    fn from_key_maps_arrows_with_shift_to_extend() {
        let shift = Modifiers {
            shift: true,
            ..Modifiers::default()
        };
        assert_eq!(
            EditOp::from_key(&Key::Named(NamedKey::Right), shift),
            Some(EditOp::MoveRight { extend: true })
        );
        assert_eq!(
            EditOp::from_key(&Key::Named(NamedKey::Right), Modifiers::default()),
            Some(EditOp::MoveRight { extend: false })
        );
    }

    #[test]
    fn from_key_ctrl_home_end_map_to_doc_start_end() {
        let ctrl = Modifiers {
            ctrl: true,
            ..Modifiers::default()
        };
        assert_eq!(
            EditOp::from_key(&Key::Named(NamedKey::Home), ctrl),
            Some(EditOp::MoveDocStart { extend: false })
        );
        assert_eq!(
            EditOp::from_key(&Key::Named(NamedKey::End), ctrl),
            Some(EditOp::MoveDocEnd { extend: false })
        );
        assert_eq!(
            EditOp::from_key(&Key::Named(NamedKey::Home), Modifiers::default()),
            Some(EditOp::MoveLineStart { extend: false })
        );
    }

    #[test]
    fn from_key_unmapped_key_returns_none() {
        assert_eq!(
            EditOp::from_key(&Key::Named(NamedKey::Escape), Modifiers::default()),
            None
        );
    }

    #[test]
    fn from_key_binding_wires_undo_redo_select_all() {
        assert_eq!(
            EditOp::from_key_binding(&KeyBinding::Undo),
            Some(EditOp::Undo)
        );
        assert_eq!(
            EditOp::from_key_binding(&KeyBinding::Redo),
            Some(EditOp::Redo)
        );
        assert_eq!(
            EditOp::from_key_binding(&KeyBinding::SelectAll),
            Some(EditOp::SelectAll)
        );
        assert_eq!(EditOp::from_key_binding(&KeyBinding::Copy), None);
    }

    // ── TextInput value equality ignores undo history ────────────────

    #[test]
    fn equality_ignores_undo_history() {
        // `TextInput` carries no history at all (see `TextEditor`'s
        // module doc for why), so its `PartialEq` never has history to
        // ignore in the first place. Demonstrate that at the wrapper
        // level: `a` reaches "x" directly, `b` reaches "x" via an extra
        // insert-then-undo round trip that leaves `b`'s redo stack
        // non-empty (unlike `a`'s) — the wrapped `TextInput`s are still
        // equal.
        let mut a = editor(vec![""]);
        let mut b = editor(vec![""]);
        a.apply(EditOp::InsertChar('x'));
        b.apply(EditOp::InsertChar('x'));
        b.apply(EditOp::InsertChar('y'));
        b.apply(EditOp::Undo);
        assert_eq!(a.lines, b.lines);
        assert_eq!(
            a.input, b.input,
            "equality must compare content, not undo history"
        );
    }

    // ── `new`/`with_*`/`Default` builders ──────────────────────────────

    /// `Default::default()` matches `TextInput::new` with an empty id —
    /// the `new(required…)`/`with_*`/`Default` trio only differs in what
    /// `id` it carries.
    #[test]
    fn default_matches_new_with_empty_id() {
        assert_eq!(TextInput::default(), TextInput::new(WidgetId::new("")));
    }

    /// Chaining every `with_*` builder reaches exactly the values the
    /// exhaustive literal in `tests/downstream_struct_literals.rs` sets
    /// field-for-field, without writing a struct literal at all.
    #[test]
    fn with_builders_reach_every_field_a_struct_literal_can_set() {
        let ti = TextInput::new(WidgetId::new("sc:commit_input"))
            .with_lines(vec![
                "subject".to_string(),
                String::new(),
                "body".to_string(),
            ])
            .with_cursor_line(2)
            .with_cursor_col(4)
            .with_placeholder("Message (press c)")
            .with_scroll_offset(0)
            .with_scroll_col(0)
            .with_has_focus(true);

        assert_eq!(
            ti,
            TextInput {
                id: WidgetId::new("sc:commit_input"),
                lines: vec!["subject".to_string(), String::new(), "body".to_string()],
                cursor_line: 2,
                cursor_col: 4,
                placeholder: Some("Message (press c)".to_string()),
                scroll_offset: 0,
                scroll_col: 0,
                has_focus: true,
            }
        );
    }
}