teksilo-widgets 0.9.2

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

//! `TextInputField` — editable single-line text surface primitive.
//!
//! This is the raw editing primitive that powers the styled
//! [`TextInput`](crate::text_input::TextInput) composite and any
//! other widget that needs inline editable text — [`SpinBox`] being
//! the primary second consumer.
//!
//! Unlike `TextInput`, `TextInputField` paints no frame, no
//! placeholder overlay, no validation border, and hosts no trailing
//! slots: it is the focusable text area only. Compose it yourself
//! with `RectWidget`, `Padding`, icons, clear buttons, etc. to
//! build a styled control. Focus indication is the composite's
//! responsibility — the Int UI convention is to thicken the
//! enclosing frame's border to `focus_ring_width` and recolor it
//! to the accent focus-ring color.
//!
//! Features:
//! - Bound `Signal<String>` for two-way text binding.
//! - Full keyboard editing (arrow keys, Home/End, Backspace/Delete,
//!   Ctrl+X/C/V, Ctrl+A, Ctrl+Z/Y), IME commit, and pointer caret
//!   positioning and drag-select.
//! - Optional per-character input filter
//!   ([`TextInputField::char_filter`]), max-length cap
//!   ([`TextInputField::max_length`]), and read-only mode
//!   ([`TextInputField::read_only`]).
//! - Commit hooks: Enter fires
//!   [`on_submit_fn`](TextInputField::on_submit_fn) and focus loss
//!   fires [`on_blur_fn`](TextInputField::on_blur_fn).
//! - Non-editable trailing
//!   [`suffix`](TextInputField::suffix), rendered flush-right inside
//!   the field's bounds (Qt's `QSpinBox::suffix`). Caret cannot
//!   enter it; clicks past the text end clamp to the last
//!   character.
//! - Right-click context menu (Cut / Copy / Paste / Select All).
//! - AccessKit `Role::TextInput` with value, selection, and
//!   character/word boundary metadata.
//!
//! # Example
//!
//! ```ignore
//! let text = ctx.signal(String::new());
//! ctx.add(
//!     TextInputField::new(text.clone())
//!         .placeholder("Enter a name…")
//!         .char_filter(|c| !c.is_ascii_digit())
//!         .on_submit_fn(|ctx| ctx.send_intent(MyIntent::Save)),
//! );
//! ```
//!
//! [`SpinBox`]: crate::spin_box::SpinBox

mod keyboard;
pub mod mask;
mod mouse;
pub(crate) mod state;
pub mod validator;

use std::rc::Rc;
use teksilo_i18n::tr_widget;

use teksilo_canvas::{Canvas, Point, Rect, Size, SizeProposal};
use teksilo_core::accessibility::AccessNodeBuilder;
use teksilo_core::build_context::BuildContext;
use teksilo_core::event::{EventResponse, Key};
use teksilo_core::shortcut::KeyStroke;
use teksilo_core::signal::{Prop, Signal};
use teksilo_core::widget::{
    CursorIcon, EventContext, LayoutContext, PaintContext, Widget, WidgetPlacement,
};
use teksilo_core::widget_builder::HandlerSet;
use teksilo_core::widget_id::WidgetId;
use teksilo_text::text_document::{SelectionType, TextDocument};
use teksilo_text::{CursorAffinity, CursorDisplay, RichTextEngine, SharedTypesetter};
use teksilo_tokens::TextStyle;

use crate::button::InteractionState;
use crate::keystroke_format::format_keystroke;
use crate::menu_item::MenuItem;
use crate::menu_list::{MenuList, MenuSeparator};
use crate::rich_text::paint::{PaintParams, paint_frame};

pub(crate) use self::state::{CharFilter, CommandFactory};
use self::state::{SharedState, TextInputConfig, TextInputState, sync_cursor_signals};

pub use self::mask::{InputMask, MaskClass, MaskError, MaskPosition};
pub use self::validator::{ValidationFeedback, ValidationOutcome, ValidatorFn};

// The caret blink period and the debounce window are shared with every other
// text surface — see `common::editor_runtime`. They used to be re-declared
// here as private constants ("same as RichTextEditor", said the comment),
// which is exactly the kind of duplication that drifts silently: two carets
// blinking at different rates is invisible to tests and obvious to users.
use crate::common::editor_runtime::CaretPolicy;

/// Horizontal scroll margin in pixels. The caret stays at least this
/// far from the left/right edge of the viewport.
const SCROLL_MARGIN: f32 = 4.0;

/// Default text-area height when the caller does not override it
/// via [`TextInputField::text_height`]. Picked to match the Int UI
/// `text_field.height` token minus 2×border — the value the
/// `TextInput` composite reports — so a bare `TextInputField`
/// added to a tree without its composite still looks right.
const DEFAULT_TEXT_HEIGHT: f32 = 20.0;

/// The semantic purpose of a text field, surfaced to assistive technology as
/// a specialised AccessKit role (WCAG 1.3.5 Identify Input Purpose / EN 301 549).
///
/// This is the in-framework-achievable part of SC 1.3.5: a screen reader
/// announces "email, edit text" instead of a generic "edit text". The FULL
/// HTML `autocomplete`-token vocabulary (`given-name`, `postal-code`,
/// `cc-number`, …) that drives OS/browser autofill has **no representation in
/// AccessKit 0.24** and therefore cannot be exposed from Teksilo — see
/// `docs/a11y/a11y_issues.md`. Password entry is configured via
/// [`TextInputField::secure`], not here.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum InputPurpose {
    /// Ordinary free text (`Role::TextInput`).
    #[default]
    Normal,
    /// Email address (`Role::EmailInput`).
    Email,
    /// Telephone number (`Role::PhoneNumberInput`).
    Phone,
    /// URL (`Role::UrlInput`).
    Url,
    /// Numeric entry — e.g. a quantity or code (`Role::NumberInput`).
    Number,
    /// Search query (`Role::SearchInput`).
    Search,
}

impl InputPurpose {
    /// The AccessKit role for a non-secure field with this purpose.
    pub(crate) fn to_role(self) -> teksilo_core::accesskit::Role {
        use teksilo_core::accesskit::Role;
        match self {
            InputPurpose::Normal => Role::TextInput,
            InputPurpose::Email => Role::EmailInput,
            InputPurpose::Phone => Role::PhoneNumberInput,
            InputPurpose::Url => Role::UrlInput,
            InputPurpose::Number => Role::NumberInput,
            InputPurpose::Search => Role::SearchInput,
        }
    }
}

/// How a secure ([`TextInputField::secure`]) field echoes typed
/// characters. Mirrors Qt's `QLineEdit::EchoMode`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum EchoMode {
    /// Replace every character with the echo glyph (default `'•'`).
    /// The plaintext stays in the bound `Signal<String>` but never
    /// reaches the text engine while masked.
    #[default]
    Masked,
    /// Show nothing at all — not even the length. The caret stays at
    /// the start. Qt's `NoEcho`.
    NoEcho,
    /// Show plaintext while the field is focused (being edited) and
    /// re-mask on blur. Qt's `PasswordEchoOnEdit`.
    RevealWhileTyping,
}

/// How a *revealed* secure field reports to assistive technology.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AtRevealPolicy {
    /// When revealed, expose the field as a normal `Role::TextInput`
    /// carrying the plaintext value — matching what is visibly on
    /// screen and the web `type=password ↔ type=text` swap. When
    /// masked, it reverts to `Role::PasswordInput`. (Default.)
    #[default]
    SwapRole,
    /// Always report `Role::PasswordInput` and never expose plaintext
    /// to assistive tech, even while visually revealed. Higher
    /// confidentiality at the cost of consistency with the screen.
    AlwaysProtected,
}

/// Editable single-line text surface primitive.
///
/// See the [module docs](self) for the full feature list and a
/// compositional example.
pub struct TextInputField {
    // ── Configuration (builder methods, consumed in build) ───────────
    text: Signal<String>,
    /// Enabled state, static or reactive; forwarded to the arena at build
    /// time.
    enabled: Prop<bool>,
    read_only: bool,
    max_length: Option<usize>,
    placeholder: String,
    on_submit: Option<CommandFactory>,
    on_blur: Option<CommandFactory>,
    char_filter: Option<CharFilter>,
    /// Fixed trailing label rendered inside the field's border.
    /// Accepts both plain strings and `Signal<String>` — when bound,
    /// the field re-measures the suffix and relayouts each time the
    /// signal fires, so composites like `SpinBox` can derive the
    /// suffix from the widget state (e.g. hide it while
    /// `special_value_text` is active).
    suffix: Prop<String>,
    text_height: Option<f32>,
    external_interaction: Option<Signal<InteractionState>>,

    /// Optional input mask. When set, the field auto-derives a
    /// placeholder template (`__/__/____` for `99/99/9999`) and
    /// rejects non-fitting characters via a position-aware filter
    /// composed with the user's `char_filter`. See [`InputMask`] for
    /// the grammar.
    mask: Option<InputMask>,
    /// Visible char used for unfilled editable positions in the mask
    /// template. Defaults to the theme's
    /// `text_field.mask_placeholder_char` (typically `_`).
    mask_placeholder_override: Option<char>,
    /// Validator closure called on every commit (Enter, Tab-out,
    /// blur). Returns a [`ValidationOutcome`] that drives
    /// [`feedback`](Self::validation_feedback_signal).
    validator: Option<ValidatorFn>,
    /// Published feedback signal. Composites bind to this to render
    /// the inline validation strip below the field.
    feedback: Signal<ValidationFeedback>,

    // ── Secure / password masking (set via `secure`) ────────────────
    secure: bool,
    echo_mode: EchoMode,
    echo_char: char,
    revealed: Option<Signal<bool>>,
    at_reveal_policy: AtRevealPolicy,
    allow_copy: bool,

    /// Semantic purpose → specialised AT role (WCAG 1.3.5). Ignored while the
    /// field is `secure` (password role wins).
    input_purpose: InputPurpose,

    /// ARIA combobox wiring — see [`active_descendant`](Self::active_descendant).
    active_descendant: Option<Signal<Option<WidgetId>>>,
    /// The listbox this field drives, if any — see
    /// [`controls`](Self::controls).
    controls: Option<Signal<Option<WidgetId>>>,

    // ── Internal (set during build) ─────────────────────────────────
    state: Option<SharedState>,
    /// Interaction signal actually used at runtime. Either the one
    /// supplied by a wrapping composite via
    /// [`TextInputField::interaction_signal`] or a fresh one owned
    /// by the field. Read by the focus handler to repaint a
    /// parent's focus ring / border on gain/loss.
    interaction: Signal<InteractionState>,
    /// Mirror of the inner state's `cursor_position` for external
    /// readers. Wired in `build()` via a `ctx.effect`. Composing
    /// widgets that need the caret (e.g. `DateEdit` for segment
    /// stepping) read this via [`TextInputField::caret_position`].
    caret_position: Signal<usize>,
    /// Late-bound handle to the inner `SharedState`, populated in
    /// `build()`. Lets composing widgets capture a `caret_setter`
    /// closure BEFORE the field is moved into the tree, then call
    /// it later to programmatically reposition the caret. Required
    /// because the inner state doesn't exist before `build()` runs,
    /// but the composing widget loses ownership of `self` once it
    /// hands the field to `ctx.add(...)`.
    state_slot: std::rc::Rc<std::cell::RefCell<Option<SharedState>>>,
    /// Minted with the widget, not with its state, so a [`TextFieldHandle`]
    /// taken before `build` observes the signal the built widget writes.
    focus_signal: Signal<bool>,
    /// Natural intrinsic width in logical pixels, cached at the end
    /// of `build()`. When an [`InputMask`] is set, this measures the
    /// mask's empty template (e.g. `__/__/____`) in the theme body
    /// font and adds a small caret slack — so a date / time / phone
    /// field reports a width that matches its content envelope
    /// instead of the generic 200 dp fallback. Composing widgets
    /// like `DateEdit` rely on this so their unconstrained natural
    /// width tracks the format pattern.
    natural_width: f32,
}

impl std::fmt::Debug for TextInputField {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TextInputField")
            .field("placeholder", &self.placeholder)
            .field("enabled", &self.enabled.get())
            .field("read_only", &self.read_only)
            .finish_non_exhaustive()
    }
}

impl TextInputField {
    /// Construct a new field bound to `text`.
    pub fn new(text: Signal<String>) -> Self {
        Self {
            text,
            enabled: Prop::Static(true),
            read_only: false,
            max_length: None,
            placeholder: String::new(),
            on_submit: None,
            on_blur: None,
            char_filter: None,
            suffix: Prop::Static(String::new()),
            text_height: None,
            external_interaction: None,
            mask: None,
            mask_placeholder_override: None,
            validator: None,
            feedback: Signal::new(ValidationFeedback::Pristine),
            secure: false,
            echo_mode: EchoMode::Masked,
            echo_char: '\u{2022}',
            revealed: None,
            at_reveal_policy: AtRevealPolicy::SwapRole,
            allow_copy: true,
            input_purpose: InputPurpose::Normal,
            active_descendant: None,
            controls: None,
            state: None,
            interaction: Signal::new(InteractionState::Idle),
            caret_position: Signal::new(0),
            state_slot: std::rc::Rc::new(std::cell::RefCell::new(None)),
            focus_signal: Signal::new(false),
            natural_width: 200.0,
        }
    }

    /// Declarative placeholder string. The field itself paints
    /// nothing for placeholder — that visual is the composite
    /// parent's responsibility (`TextInput` overlays a
    /// `TextWidget`). The string is still stored here and published
    /// via AccessKit's `placeholder` property so screen readers
    /// announce it.
    pub fn placeholder(mut self, text: impl Into<String>) -> Self {
        self.placeholder = text.into();
        self
    }

    /// Set the enabled state, statically or reactively. Disabled blocks
    /// input and AccessKit interaction. Forwarded to the arena at build
    /// time.
    pub fn enabled(mut self, enabled: impl Into<Prop<bool>>) -> Self {
        self.enabled = enabled.into();
        self
    }

    /// Mark the field read-only. Caret and selection still work;
    /// inserts, deletes, paste, undo/redo, and cut are all no-ops.
    pub fn read_only(mut self, read_only: bool) -> Self {
        self.read_only = read_only;
        self
    }

    /// Hard cap on document length in `char`s (grapheme count is
    /// approximated — each `char` counts as one unit, matching
    /// `String::chars().count()`).
    pub fn max_length(mut self, max_length: usize) -> Self {
        self.max_length = Some(max_length);
        self
    }

    /// Closure fired on `Enter`. Unlike `on_blur_fn`, this does
    /// not move focus — the field stays focused and the caret
    /// stays where it was.
    pub fn on_submit_fn(mut self, f: impl Fn(&mut EventContext) + 'static) -> Self {
        self.on_submit = Some(Box::new(f));
        self
    }

    /// Closure fired once per focus-loss, after selection/scroll
    /// have been reset. SpinBox-style callers parse and reformat
    /// here; validators revalidate here.
    pub fn on_blur_fn(mut self, f: impl Fn(&mut EventContext) + 'static) -> Self {
        self.on_blur = Some(Box::new(f));
        self
    }

    /// Per-character input-filter predicate. Applied uniformly to
    /// keyboard input, IME commits, and clipboard paste so a filtered
    /// field cannot receive disallowed characters through any path.
    /// Composes with `max_length` and the built-in control/newline
    /// strip (filter runs after the strip). Whole-string validity
    /// (e.g. "at most one decimal point") is a commit-time concern
    /// for `on_blur` / `on_submit`.
    pub fn char_filter(mut self, f: impl Fn(char) -> bool + 'static) -> Self {
        self.char_filter = Some(Rc::new(f));
        self
    }

    /// Static non-editable trailing string rendered flush-right
    /// inside the field's bounds (Qt's `QSpinBox::suffix`). The
    /// caret cannot enter the suffix; clicks past the text end
    /// position the caret at the last editable character.
    ///
    /// Accepts a static `String`/`&str` or a reactive `Signal<String>` /
    /// `Prop<String>`; when bound, the field re-measures the suffix glyphs
    /// and relayouts the editable text viewport each time the signal fires.
    /// Typical use: a `SpinBox` with `special_value_text` binds an empty
    /// string to the suffix whenever the value equals `min`, and the
    /// configured unit string otherwise.
    pub fn suffix(mut self, text: impl Into<Prop<String>>) -> Self {
        self.suffix = text.into();
        self
    }

    /// Override the intrinsic text-area height. The field is a
    /// pure leaf with no theme lookup of its own; by default it
    /// reports `DEFAULT_TEXT_HEIGHT`. A wrapping composite like
    /// `TextInput` passes its theme's `text_field.height` minus
    /// border + padding here so the visuals line up with the
    /// rest of the form.
    pub fn text_height(mut self, height: f32) -> Self {
        self.text_height = Some(height);
        self
    }

    /// Bind an externally-owned `InteractionState` signal. The
    /// field writes `Focused` on focus gain and `Idle` on loss;
    /// other states (`Hovered`, `Pressed`, `Disabled`) are the
    /// composite's responsibility. When unset, the field owns a
    /// private signal that observers can still read via
    /// [`interaction`](TextInputField::interaction), but composites
    /// that drive a focus ring or border color usually want to
    /// push their own.
    pub fn interaction_signal(mut self, signal: Signal<InteractionState>) -> Self {
        self.external_interaction = Some(signal);
        self
    }

    /// Set an input mask (Qt grammar). Constrains accepted characters
    /// per position, auto-derives the empty-state template
    /// (`__/__/____` for `99/99/9999`), and routes typed chars
    /// through the mask's class filter.
    ///
    /// Composes with [`char_filter`](Self::char_filter): a char must
    /// pass *both* the mask's per-position class AND the user's
    /// `char_filter` to be accepted.
    ///
    /// On parse error (only the trailing-backslash case in practice),
    /// the mask is silently dropped — the field falls back to its
    /// no-mask behaviour rather than panicking.
    pub fn input_mask(mut self, mask: impl AsRef<str>) -> Self {
        match InputMask::parse(mask.as_ref()) {
            Ok(m) => self.mask = Some(m),
            Err(_) => self.mask = None,
        }
        self
    }

    /// Override the visible character used for unfilled editable mask
    /// positions. Default: the theme's
    /// `text_field.mask_placeholder_char` (typically `_`).
    pub fn mask_placeholder(mut self, c: char) -> Self {
        self.mask_placeholder_override = Some(c);
        self
    }

    /// Install a validator. The closure runs on every commit (Enter,
    /// Tab-out, focus loss) and returns a [`ValidationOutcome`] that
    /// drives [`validation_feedback_signal`](Self::validation_feedback_signal).
    ///
    /// **Does not run per-keystroke** — that's [`char_filter`](Self::char_filter)'s
    /// job. Mixing per-keystroke text rewriting with validation
    /// produces caret-jump bugs and is explicitly out of scope.
    pub fn validator(mut self, f: impl Fn(&str) -> ValidationOutcome + 'static) -> Self {
        self.validator = Some(Rc::new(f));
        self
    }

    /// Turn this into a secure (password) field with the given
    /// [`EchoMode`]. Masking happens at the text-engine layer (one echo
    /// glyph per source `char`), so the plaintext never reaches the
    /// shaper or glyph atlas while masked, and caret / selection /
    /// hit-test stay correct. Also defaults `allow_copy` to `false` and
    /// opts the focused node out of OS IME composition. Pair with
    /// [`revealed`](Self::revealed) for a reveal toggle.
    pub fn secure(mut self, echo_mode: EchoMode) -> Self {
        self.secure = true;
        self.echo_mode = echo_mode;
        self.allow_copy = false;
        self
    }

    /// Declare the field's semantic [`InputPurpose`] (WCAG 1.3.5), which
    /// selects a specialised AccessKit role (`EmailInput`, `PhoneNumberInput`,
    /// …) so screen readers announce the field's kind. Ignored while `secure`
    /// (the password role wins). Does not change IME behaviour — winit's
    /// `ImePurpose` has no email/number/url variants — nor drive OS autofill,
    /// which AccessKit cannot express (see `docs/a11y/a11y_issues.md`).
    pub fn input_purpose(mut self, purpose: InputPurpose) -> Self {
        self.input_purpose = purpose;
        self
    }

    /// Publish `active_descendant` pointing at the row a *separate* list is
    /// currently highlighting — the ARIA combobox pattern.
    ///
    /// Keyboard focus stays in this field while arrow keys move a highlight
    /// through a listbox elsewhere in the tree (a command palette, a
    /// type-ahead picker, a suggestion popup). Assistive technology follows
    /// the focused node's active descendant, so the announcement has to be
    /// published **here**, on the node that actually holds focus — not on the
    /// composite ancestor that owns the list. Without it the arrow keys move a
    /// highlight that is announced to nobody.
    ///
    /// Bound at `AccessibilityOnly`, so moving the highlight re-walks the AT
    /// tree without a rebuild or a repaint. Pair with [`controls`](Self::controls).
    pub fn active_descendant(mut self, active: Signal<Option<WidgetId>>) -> Self {
        self.active_descendant = Some(active);
        self
    }

    /// Publish a `controls` relation to the listbox this field drives, so an
    /// AT client can navigate from the input to the list it is filtering.
    /// The companion of [`active_descendant`](Self::active_descendant).
    pub fn controls(mut self, listbox: Signal<Option<WidgetId>>) -> Self {
        self.controls = Some(listbox);
        self
    }

    /// Override the masking glyph (default `'•'`, U+2022). Any
    /// uniform-width character works; the engine emits exactly one per
    /// source `char`.
    pub fn echo_char(mut self, c: char) -> Self {
        self.echo_char = c;
        self
    }

    /// Bind the reveal toggle. When the signal is `true` the field
    /// shows plaintext regardless of [`EchoMode`]; when `false` it
    /// masks. Shared with the eye [`IconButton::visibility_toggle`].
    ///
    /// [`IconButton::visibility_toggle`]: crate::IconButton::visibility_toggle
    pub fn revealed(mut self, revealed: Signal<bool>) -> Self {
        self.revealed = Some(revealed);
        self
    }

    /// How a *revealed* secure field reports to assistive tech. Default
    /// [`AtRevealPolicy::SwapRole`].
    pub fn at_reveal_policy(mut self, policy: AtRevealPolicy) -> Self {
        self.at_reveal_policy = policy;
        self
    }

    /// Permit (or forbid) copy / cut. Plain fields default `true`;
    /// [`secure`](Self::secure) flips the default to `false`. Even when
    /// `false`, copy is allowed while the field is revealed.
    pub fn allow_copy(mut self, allow: bool) -> Self {
        self.allow_copy = allow;
        self
    }

    /// Reactive handle on the published [`ValidationFeedback`] state.
    /// Composites bind to this to render the inline feedback strip
    /// below the field. Always present; reads `Pristine` until the
    /// first commit (or forever if no validator is installed).
    pub fn validation_feedback_signal(&self) -> Signal<ValidationFeedback> {
        self.feedback.clone()
    }

    /// The `Signal<String>` this field is bound to.
    pub fn text(&self) -> Signal<String> {
        self.text.clone()
    }

    /// Adopt an existing handle instead of minting one.
    ///
    /// For a composing widget — `TextInput` wraps this field — that must hand
    /// out a handle of its own **before** it builds the field it will delegate
    /// to. Sharing the slot and the focus signal makes the wrapper's handle and
    /// the field's the same handle, rather than two that agree by accident.
    pub fn share_handle(mut self, handle: &TextFieldHandle) -> Self {
        self.state_slot = handle.slot.clone();
        self.focus_signal = handle.focus_signal.clone();
        self
    }

    /// A live handle on this field, valid before and after `build`.
    ///
    /// The counterpart of `RichTextEditor::handle`, and the reason it exists:
    /// an application that routes Undo, Cut, Copy, Paste and Select All to
    /// "whichever text surface holds the caret" has to be able to *drive* every
    /// such surface, not only the rich editors. Without this, a menu built for
    /// those commands can only grey them out over a rename field or a search
    /// box while the field's own key handling still works — a menu that lies
    /// about what the keyboard can do.
    ///
    /// Like `caret_setter`, the handle reaches its state through the slot the
    /// widget late-populates, so it may be taken while the tree is being
    /// described and used once it is live.
    pub fn handle(&self) -> TextFieldHandle {
        TextFieldHandle {
            slot: self.state_slot.clone(),
            focus_signal: self.focus_signal.clone(),
        }
    }

    /// The interaction signal this field writes on focus changes.
    /// Call before inserting the field into the tree.
    pub fn interaction(&self) -> Signal<InteractionState> {
        self.interaction.clone()
    }

    /// Reactive caret position in the field's text (in `usize` char
    /// offsets). Updates after every keyboard or pointer action that
    /// moves the cursor. Used by composing widgets that need to know
    /// where the caret is — e.g. `DateEdit` reads this to figure out
    /// which date segment Up/Down should step.
    pub fn caret_position(&self) -> Signal<usize> {
        self.caret_position.clone()
    }

    /// Returns a callable that programmatically sets the caret
    /// position (in char offsets) on the field. Capture this on the
    /// builder BEFORE `ctx.add(...)` consumes the field; call it
    /// after a programmatic text rewrite to restore the caret to the
    /// right column instead of leaving it at the document end (the
    /// default behaviour of `cursor.insert_text`).
    ///
    /// The returned closure becomes a no-op until `build()` runs;
    /// after build it walks the field's inner state and moves the
    /// document cursor to `position`, clamped to the document
    /// length. Used by `DateEdit` / `TimeEdit` segment-stepping to
    /// keep the caret within its current segment after Up/Down.
    pub fn caret_setter(&self) -> std::rc::Rc<dyn Fn(usize)> {
        let slot = self.state_slot.clone();
        std::rc::Rc::new(move |position: usize| {
            if let Some(state) = slot.borrow().as_ref() {
                let st = state.borrow();
                st.cursor
                    .set_position(position, teksilo_text::text_document::MoveMode::MoveAnchor);
                let actual = st.cursor.position();
                if st.cursor_position.get() != actual {
                    st.cursor_position.set(actual);
                }
            }
        })
    }
}

impl Widget for TextInputField {
    fn as_any(&self) -> Option<&dyn std::any::Any> {
        Some(self)
    }

    fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
        // Tell the framework this widget edits text.
        //
        // What it buys: an application may take `Ctrl+Z`, `Ctrl+C` and friends
        // for itself — a single Undo command over the whole app has to — and
        // registered shortcuts resolve before any widget sees the raw key. This
        // is how the host can tell that the caret is *here*, and either drive
        // this surface or step aside so it keeps its own keys. Without it, an
        // application that routes those chords silently breaks every text
        // widget it does not personally know about. See
        // `teksilo_core::text_surface`.
        ctx.register_text_surface(std::rc::Rc::new(self.handle()));
        // Resolve the interaction signal (external override wins).
        if let Some(signal) = self.external_interaction.take() {
            self.interaction = signal;
        }

        // Resolve the mask placeholder character. Caller override wins;
        // otherwise pull from the recipe constant. The theme snapshot
        // is still captured for downstream typography reads below.
        let theme_snapshot = ctx.theme_signal().get();
        let mask_placeholder_char = self
            .mask_placeholder_override
            .unwrap_or(crate::styles::recipe_text_input_style::TEXT_FIELD_MASK_PLACEHOLDER_CHAR);

        // Auto-derive placeholder from mask when none was explicitly
        // set: an empty masked field paints `__/__/____` rather than
        // a blank surface, giving the user a self-documenting template.
        if self.placeholder.is_empty()
            && let Some(ref m) = self.mask
        {
            self.placeholder = m.empty_template(mask_placeholder_char);
        }

        // Cache mask-aware natural width. When a mask is set, the
        // visual content envelope is the FILLED template — every
        // editable position holding its widest plausible glyph
        // (`0` for digits, `M` for letters, etc.) and every fixed
        // position holding its literal. Measuring the empty
        // (`__/__/____`) template instead would shortchange the
        // field by the difference between an underscore and a real
        // glyph: ~2 dp per digit slot for `0`, ~5 dp per letter
        // slot for `M`, which adds up to a multi-character shortfall
        // for date / 12h time fields. We want the natural width to
        // hold the fully-typed value without overflow.
        //
        // Without a mask the 200 dp fallback (set in `new()`) stays.
        if let Some(ref m) = self.mask {
            // Measure the worst-case glyph row PLUS one extra `M` of
            // safety: one for caret breathing room past the last
            // position, plus a defensive cushion for any per-glyph
            // measurement variance between our heuristic fallback
            // and the real glyph shaper. Without this safety char,
            // dates were observed to clip the trailing 2 characters
            // and 12h time fields clipped the AM/PM letters.
            let mut widest = worst_case_template(m);
            widest.push('M');
            let style = &theme_snapshot.typography.body;
            let measured = measure_width_px(ctx, &widest, style);
            let slack = style.size;
            self.natural_width = measured + slack;
        }

        // Compose the user's char_filter with the mask's class filter.
        // The mask doesn't know the cursor position here (this is a
        // pre-position filter), so it accepts any char that fits *any*
        // editable position class — a permissive gate that catches
        // gross mismatches (typing "a" into a digits-only mask) without
        // requiring per-keystroke position tracking. Per-position
        // gating happens at commit time via the validator.
        if let Some(ref mask) = self.mask {
            let mask_for_filter = mask.clone();
            let user_filter = self.char_filter.take();
            let combined: CharFilter = Rc::new(move |c: char| {
                // Always allow fixed-separator characters (they're
                // legitimate input even if user types them — the
                // formatter consumes them).
                let in_mask_class = mask_for_filter.positions().any(|p| match p {
                    MaskPosition::Editable { class, .. } => class.accepts(c),
                    MaskPosition::Fixed(sep) => *sep == c,
                });
                if !in_mask_class {
                    return false;
                }
                match user_filter.as_ref() {
                    Some(f) => f(c),
                    None => true,
                }
            });
            self.char_filter = Some(combined);
        }

        // Build the shared state from the configured builder values.
        let mut on_submit = self.on_submit.take().map(Rc::new);
        let mut on_blur = self.on_blur.take().map(Rc::new);

        // Wrap commit callbacks with the validator pipeline. The
        // wrapping closure: snapshots the bound text, runs the
        // validator, applies the outcome (writes feedback, mutates
        // text on `Corrected`), then chains the user's callback so
        // composites can react to the now-updated state.
        if let Some(validator) = self.validator.clone() {
            let bound_text = self.text.clone();
            let feedback = self.feedback.clone();
            let prev_on_blur = on_blur.take();
            on_blur = Some(Rc::new(Box::new({
                let validator = validator.clone();
                let feedback = feedback.clone();
                let bound_text = bound_text.clone();
                move |evt_ctx: &mut EventContext| {
                    run_validator_and_apply(&validator, &bound_text, &feedback);
                    if let Some(cb) = prev_on_blur.as_ref() {
                        cb(evt_ctx);
                    }
                }
            }) as CommandFactory));
            let prev_on_submit = on_submit.take();
            on_submit = Some(Rc::new(Box::new({
                let validator = validator.clone();
                let feedback = feedback.clone();
                let bound_text = bound_text.clone();
                move |evt_ctx: &mut EventContext| {
                    run_validator_and_apply(&validator, &bound_text, &feedback);
                    if let Some(cb) = prev_on_submit.as_ref() {
                        cb(evt_ctx);
                    }
                }
            }) as CommandFactory));
        }

        let initial_text = self.text.get();
        // `read_only_effective` snapshots the build-time state so the
        // shared TextInputState's read-only mode is set once. Disabled
        // is now arena-driven and propagates per-paint via
        // `effective_enabled`; the field's interaction handlers also
        // check `ctx.is_enabled(self_id)` for keystroke gating. The
        // shared state's read_only stays a separate, document-level
        // concept (allows selection / no edits).
        let read_only_effective = self.read_only || !self.enabled.get();

        let initial_suffix = self.suffix.get();
        let shared_state = TextInputState::new(TextInputConfig {
            initial_text,
            max_length: self.max_length,
            read_only: read_only_effective,
            on_submit,
            on_blur,
            char_filter: self.char_filter.take(),
            placeholder: self.placeholder.clone(),
            suffix: initial_suffix,
            secure: self.secure,
            echo_mode: self.echo_mode,
            echo_char: self.echo_char,
            revealed: self.revealed.clone(),
            at_reveal_policy: self.at_reveal_policy,
            allow_copy: self.allow_copy,
            focus_signal: self.focus_signal.clone(),
        });
        self.state = Some(shared_state.clone());
        // Late-populate the slot so `caret_setter()` closures captured
        // before build can now reach the inner state. Idempotent on
        // rebuild — overwrites the slot with the freshly created
        // SharedState.
        *self.state_slot.borrow_mut() = Some(shared_state.clone());

        // Reset feedback to Pristine whenever the user types — prior
        // Invalid / Corrected announcements should clear as soon as
        // the user starts editing again so they don't shout stale
        // errors at someone trying to fix them.
        {
            let feedback = self.feedback.clone();
            ctx.effect(&self.text, move |_| {
                if !matches!(feedback.get(), ValidationFeedback::Pristine) {
                    feedback.set(ValidationFeedback::Pristine);
                }
            });
        }

        // Mirror the inner state's `cursor_position` onto the field's
        // public `caret_position` so callers of `caret_position()` see
        // live caret updates. The state's signal is keyed by the
        // shared state's identity (created in `TextInputState::new`),
        // not by the field's; this effect bridges the two.
        {
            let inner = shared_state.borrow().cursor_position.clone();
            let outer = self.caret_position.clone();
            outer.set(inner.get());
            ctx.effect(&inner, move |pos| {
                if outer.get() != *pos {
                    outer.set(*pos);
                }
            });
        }

        // Bind feedback at AccessibilityOnly so the field's AT node
        // refreshes its `set_invalid` state when feedback changes.
        {
            let self_id = ctx.self_id();
            self.feedback.bind_to(
                self_id,
                ctx.binding_registry(),
                teksilo_core::binding::BindingLevel::AccessibilityOnly,
            );
        }

        // Combobox wiring: a moved highlight in the list this field drives must
        // re-walk the AT tree so the new `active_descendant` is announced.
        // AccessibilityOnly — nothing about this field's own pixels changed.
        for sig in [self.active_descendant.as_ref(), self.controls.as_ref()]
            .into_iter()
            .flatten()
        {
            sig.bind_to(
                ctx.self_id(),
                ctx.binding_registry(),
                teksilo_core::binding::BindingLevel::AccessibilityOnly,
            );
        }

        // Secure fields: flipping the reveal toggle must repaint AND
        // refresh AT. `RepaintOnly` dirties this node for the render
        // walker so `paint()` runs and re-lays-out the masked/unmasked
        // glyphs via the `needs_full_layout` flag the effect below sets
        // — without it the flag is set but nothing calls `paint()`, so
        // the visual only updates on the next unrelated repaint
        // (hover / focus). This mirrors how `text_signal` is bound for
        // edits. The parallel `AccessibilityOnly` bind swaps the AT
        // role/value (PasswordInput ↔ TextInput under SwapRole); it lives
        // in its own bucket and does not imply repaint, so both are
        // required.
        if self.secure
            && let Some(revealed) = self.revealed.clone()
        {
            let id = ctx.self_id();
            let reg = ctx.binding_registry();
            revealed.bind_to(id, reg, teksilo_core::binding::BindingLevel::RepaintOnly);
            revealed.bind_to(
                id,
                reg,
                teksilo_core::binding::BindingLevel::AccessibilityOnly,
            );
        }

        let text_signal = shared_state.borrow().text_signal.clone();

        // Sync external text signal → internal state. A programmatic
        // update on the bound signal rewrites the document; the
        // caret ends up at the end of the inserted text (cursor
        // behavior is documented in
        // `text_document::TextCursor::insert_text`).
        //
        // `insert_text` only enqueues a `ContentsChanged` document
        // event — `tick()` drains it on the next frame and propagates
        // the new text to `text_signal`. Frames are demand-driven, so
        // we ping `frame_request` here to guarantee a tick runs even
        // when the external writer (e.g. an HSV-canvas drag feeding a
        // spinner / hex bridge) is the only thing changing on screen.
        // Without it, the document stays in sync with the bound signal
        // but the visible glyphs lag until something else (focus, a
        // keystroke, an animation frame) wakes the loop.
        {
            let ext = self.text.clone();
            let state_for_sync = shared_state.clone();
            ctx.effect(&ext, move |new_text| {
                let st = state_for_sync.borrow();
                let current = st.document.to_plain_text().unwrap_or_default();
                if current != *new_text {
                    st.cursor.select(SelectionType::Document);
                    let _ = st.cursor.insert_text(new_text);
                    if let Some(handle) = &st.frame_request {
                        handle.set(true);
                    }
                }
            });
        }

        // Sync internal text signal → external. Every edit that
        // reaches `text_signal` also updates the caller-owned
        // signal, so observers bound to it see every keystroke
        // (after the debounce in `tick`).
        {
            let ext = self.text.clone();
            ctx.effect(&text_signal, move |new_text| {
                if ext.get() != *new_text {
                    ext.set(new_text.clone());
                }
            });
        }

        // Secure reveal toggle: flipping the bound `revealed` signal
        // swaps the laid-out glyphs wholesale (bullets ↔ plaintext), so
        // mark the layout dirty and ping the frame loop to re-lay-out.
        if self.secure
            && let Some(revealed) = self.revealed.clone()
        {
            let state_for_reveal = shared_state.clone();
            ctx.effect(&revealed, move |_| {
                let mut st = state_for_reveal.borrow_mut();
                st.needs_full_layout = true;
                if let Some(handle) = &st.frame_request {
                    handle.set(true);
                }
            });
        }

        // Swap the private engine for one sharing the app's
        // `SharedTypesetter` so glyphs land in the atlas
        // teksilo-render uploads to the GPU. When no typesetter is
        // installed (headless tests), the pre-built private
        // engine stays in place.
        if let Some(shared) = ctx.app_state::<SharedTypesetter>() {
            let mut st = self.state().borrow_mut();
            let mut engine = RichTextEngine::from_shared(shared.clone());
            engine.set_wrap_mode(teksilo_text::WrapMode::None);
            st.engine = engine;
            st.needs_full_layout = true;
        }

        // Apply theme colors to the (possibly freshly swapped-in) engine.
        // Setting them before the swap would be lost. The rich-text
        // engine stores colors in GPU-ready form, so we register an
        // effect on the theme signal that re-applies the palette on
        // every theme switch instead of capturing a single snapshot.
        //
        // The text / caret / suffix *foreground* colours are deliberately
        // NOT set here — `paint` owns them, because they depend on the
        // effective enabled state as well as the theme (see the resolve
        // block there). Selection is theme + window-active only, so it
        // stays on this effect path.
        let theme_signal = ctx.theme_signal();
        // The selection colour is also window-active-aware. `ctx.effect` can
        // only observe *mutable* signals (a derived `theme.zip(window_active)`
        // would panic), so the theme effect reads the live window-active value
        // via `.get()`, and the separate window-active effect (below, near the
        // frame handles) re-applies the selection colour reading the live
        // theme. Between them, a change to either axis re-applies correctly.
        {
            let theme = theme_signal.get();
            let colors = &theme.colors;
            let mut st = self.state().borrow_mut();
            let tint = field_selection_color(colors, ctx.window_active(), st.has_focus);
            st.selection_tint = tint;
            st.engine.set_selection_color(tint);
        }
        {
            let state = self.state().clone();
            let wa_signal = ctx.window_active_signal();
            ctx.effect(&theme_signal, move |theme| {
                let colors = &theme.colors;
                let mut st = state.borrow_mut();
                let tint = field_selection_color(colors, wa_signal.get(), st.has_focus);
                st.selection_tint = tint;
                st.engine.set_selection_color(tint);
            });
        }

        // Suffix engine: second independent `RichTextEngine` used
        // to paint the non-editable trailing string (Qt's
        // `QSpinBox` `suffix`). Shares the app's typesetter when
        // available so glyphs land in the same atlas as the main
        // document; falls back to a private engine under headless
        // tests.
        //
        // `suffix_width` is cached on `TextInputState` and drives
        // both the effective text viewport (so the scroll logic
        // keeps the caret visible without sliding text behind the
        // suffix) and the suffix paint origin at the right edge
        // of the field. When the suffix is bound to a signal, a
        // reactive effect below re-lays the engine out each time
        // the signal fires.
        let text_area_height = self.text_height.unwrap_or(DEFAULT_TEXT_HEIGHT).max(1.0);
        let needs_suffix_engine = matches!(self.suffix, Prop::Bound(_)) || {
            let st = self.state().borrow();
            !st.suffix.is_empty()
        };
        if needs_suffix_engine {
            let mut suffix_engine = if let Some(shared) = ctx.app_state::<SharedTypesetter>() {
                RichTextEngine::from_shared(shared.clone())
            } else {
                RichTextEngine::private_default()
            };
            suffix_engine.set_wrap_mode(teksilo_text::WrapMode::None);
            {
                let theme = theme_signal.get();
                let secondary = theme.colors.text_secondary.to_array();
                suffix_engine.set_text_color(secondary);
                suffix_engine.set_cursor_color(secondary);
                suffix_engine.set_selection_color([0.0, 0.0, 0.0, 0.0]);
            }
            suffix_engine.set_viewport(10_000.0, text_area_height);

            {
                let mut st = self.state().borrow_mut();
                st.suffix_engine = Some(suffix_engine);
            }
            // Initial layout from the current suffix value.
            let initial = self.state().borrow().suffix.clone();
            relayout_suffix(self.state(), &initial);
        }

        // Reactive suffix: observe the signal and re-lay out on
        // every change. `Relayout` dirty-tracking ensures the
        // surrounding layout sees the new `suffix_width` and the
        // text viewport narrows/widens accordingly.
        if let Prop::Bound(signal) = &self.suffix {
            let self_id = ctx.self_id();
            signal.bind_to(
                self_id,
                ctx.binding_registry(),
                teksilo_core::binding::BindingLevel::Relayout,
            );
            let state_for_effect = self.state().clone();
            ctx.effect(signal, move |new_text| {
                relayout_suffix(&state_for_effect, new_text);
            });
        }

        // Bind caret_visible for repaint.
        {
            let st = self.state().borrow();
            let caret_visible = st.caret_visible.clone();
            drop(st);
            let self_id = ctx.self_id();
            caret_visible.bind_to(
                self_id,
                ctx.binding_registry(),
                teksilo_core::binding::BindingLevel::RepaintOnly,
            );
        }

        // Bind text_signal at RepaintOnly AND AccessibilityOnly.
        //
        // RepaintOnly: when the text changes by any route — local
        // typing, IME, clipboard paste, the ext→internal sync
        // effect firing because a composite parent (SpinBox etc.)
        // drove the bound signal — the field must redraw. During
        // typing the caret-blink signal already keeps the widget
        // repainting, which used to mask a missing repaint trigger
        // on programmatic text changes to an unfocused field. With
        // the explicit bind, no path depends on blink.
        //
        // AccessibilityOnly: screen readers see edits as soon as
        // the text signal updates, independent of whether a paint
        // happens this frame.
        {
            let st = self.state().borrow();
            let text_signal = st.text_signal.clone();
            drop(st);
            let self_id = ctx.self_id();
            let registry = ctx.binding_registry();
            text_signal.bind_to(
                self_id,
                registry,
                teksilo_core::binding::BindingLevel::RepaintOnly,
            );
            text_signal.bind_to(
                self_id,
                registry,
                teksilo_core::binding::BindingLevel::AccessibilityOnly,
            );
        }

        // Stash frame infrastructure handles and self_id.
        {
            let mut st = self.state().borrow_mut();
            st.frame_request = Some(ctx.frame_request_handle());
            st.frame_wake_at = Some(ctx.wake_at_handle());
            st.field_widget_id = Some(ctx.self_id());
        }

        // Same dormancy discipline as `RichTextEditor`: a field parked in a
        // non-selected `Switcher` / `visible_when(false)` branch must not
        // keep the event loop awake (caret `wake_at`, frame-tick work,
        // window-active re-arm). See that widget's build for the full story.
        let activation = ctx.activation_signal(ctx.self_id());
        if activation.get() {
            ctx.request_frame();
        }

        {
            let state = self.state().clone();
            let interaction = self.interaction.clone();
            ctx.effect(&activation, move |&active| {
                if active {
                    // **Re-activated** — re-arm the frame loop. The dormant branch
                    // below does not re-arm `frame_request` (a parked surface has
                    // nothing to paint) and the frame-tick effect is skipped
                    // entirely while dormant, so nothing restarts the tick on the
                    // way back. Same defect and same fix as `RichTextEditor` /
                    // `CodeEditor`: the in-tree modal path builds content, parks it
                    // dormant, mounts it, activates it and *then* moves focus in
                    // (`present_in_tree_modal_request`), so without this a field in
                    // a dialog draws no caret at all.
                    let st = state.borrow();
                    if let Some(handle) = &st.frame_request {
                        handle.set(true);
                    }
                    return;
                }
                let mut st = state.borrow_mut();
                if st.has_focus {
                    st.has_focus = false;
                    st.focus_signal.set(false);
                    // Mirror the on_focus(false) interaction write so a
                    // Focused chrome style doesn't stick on a parked field.
                    interaction.set(InteractionState::Idle);
                }
                if st.caret_visible.get() {
                    st.caret_visible.set(false);
                }
                st.blink.reset();
            });
        }

        // Frame-tick effect: flushes pending chars, drains document
        // events, drives the caret blink, and debounces undo/redo
        // state changes.
        //
        // IMPORTANT: the mutable borrow must be dropped BEFORE
        // setting `text_signal`. Setting it fires observers
        // synchronously, which chain into the ext→internal sync
        // effect that borrows the same state. Holding `borrow_mut`
        // across `signal.set()` would panic.
        {
            let state = self.state().clone();
            let active = activation.clone();
            let tick_signal = ctx.frame_tick();
            ctx.effect(&tick_signal, move |delta| {
                if !active.get() {
                    return;
                }
                let (more, pending_text) = {
                    let mut st = state.borrow_mut();
                    let more = tick(&mut st, *delta);
                    st.has_selection.set(st.cursor.has_selection());
                    let pending = st.deferred_text_update.take();
                    (more, pending)
                };
                if let Some(text) = pending_text {
                    let st = state.borrow();
                    if st.text_signal.get() != text {
                        st.text_signal.set(text);
                    }
                }
                if more {
                    let st = state.borrow();
                    if let Some(handle) = &st.frame_request {
                        handle.set(true);
                    }
                }
            });
        }

        // Window-active effect — mirror the tree's window-active state onto the
        // field state so the frame loop (no context) can gate the caret, and
        // re-apply the window-aware selection colour (reading the live theme,
        // since `ctx.effect` can't observe a derived theme×active signal). The
        // loop may not tick while the window is inactive (animation scheduler
        // parked), so on deactivation hide the caret synchronously here and
        // request a frame so it reaches a paint pass — only while this field
        // is itself active (a dormant field must not re-arm the loop).
        {
            let state = self.state().clone();
            let active = activation.clone();
            let wa_signal = ctx.window_active_signal();
            let theme_for_sel = theme_signal.clone();
            ctx.effect(&wa_signal, move |&window_active| {
                let mut st = state.borrow_mut();
                st.window_active = window_active;
                let theme = theme_for_sel.get();
                let tint = field_selection_color(&theme.colors, window_active, st.has_focus);
                st.selection_tint = tint;
                st.engine.set_selection_color(tint);
                if window_active {
                    // Reactivated: show the caret immediately if still focused
                    // (restart the blink phase), rather than waiting one interval.
                    if st.has_focus && !st.caret_visible.get() {
                        st.caret_visible.set(true);
                    }
                    st.blink.reset();
                } else {
                    // Deactivated: hide the caret synchronously (the frame loop
                    // may not tick while the window is inactive).
                    if st.caret_visible.get() {
                        st.caret_visible.set(false);
                    }
                    st.blink.reset();
                }
                if active.get()
                    && let Some(handle) = &st.frame_request
                {
                    handle.set(true);
                }
            });
        }

        // Forward the enabled state into the arena. Disabled state no
        // longer seeded into the interaction signal — the framework's
        // arena enabled-state is the single source of truth (events
        // gated, leaves resolve Disabled role).
        let self_id = ctx.self_id();
        ctx.enabled_when(self_id, self.enabled.clone());

        // Attach handlers. Focus-origin inference mirrors the
        // `Slider` pattern: hover cached, focus event checks hover
        // to distinguish keyboard vs pointer origin for the
        // select-all-on-keyboard-focus rule.
        let hovered = std::rc::Rc::new(std::cell::Cell::new(false));
        let hovered_for_focus = hovered.clone();
        let hovered_for_hover = hovered.clone();

        let state_for_focus = self.state().clone();
        let interaction_for_focus = self.interaction.clone();
        // The selection band's tint depends on focus, so the focus handler has
        // to re-apply it — and needs the live theme to do so.
        let theme_for_focus = theme_signal.clone();
        let state_for_pointer = self.state().clone();
        let state_for_key = self.state().clone();
        let state_for_double = self.state().clone();
        let state_for_triple = self.state().clone();
        let state_for_access = self.state().clone();
        let state_for_menu = self.state().clone();

        let handlers = HandlerSet::new()
            .focusable(true)
            .cursor(CursorIcon::Text)
            // Secure fields opt the focused node out of OS IME
            // composition so the preedit / candidate window can't
            // surface plaintext. Read by the platform IME layer at
            // focus-change time (default `true` for plain fields).
            .ime_input(if self.secure {
                teksilo_core::ime::ImeContext::password()
            } else {
                teksilo_core::ime::ImeContext::text()
            })
            .on_hover(move |entered, _ctx| {
                hovered_for_hover.set(entered);
            })
            .on_focus(move |gained, ctx| {
                interaction_for_focus.set(if gained {
                    InteractionState::Focused
                } else {
                    InteractionState::Idle
                });

                let mut st = state_for_focus.borrow_mut();
                st.has_focus = gained;
                st.focus_signal.set(gained);
                // Re-tint the selection band: `has_focus` is half of what
                // decides it, so losing focus inside an active window has to
                // re-apply just as losing the window does.
                let sel_theme = theme_for_focus.get();
                let tint = field_selection_color(&sel_theme.colors, st.window_active, gained);
                st.selection_tint = tint;
                st.engine.set_selection_color(tint);
                // RevealWhileTyping shows plaintext while focused and
                // re-masks on blur — both transitions need a relayout.
                if st.secure && st.echo_mode == EchoMode::RevealWhileTyping {
                    st.needs_full_layout = true;
                }
                let mut blur_callback: Option<Rc<CommandFactory>> = None;
                if gained {
                    st.blink.restart();
                    st.caret_visible.set(true);
                    let is_keyboard = !hovered_for_focus.get();
                    drop(st);
                    if is_keyboard {
                        let st = state_for_focus.borrow();
                        st.cursor.select(SelectionType::Document);
                        drop(st);
                        sync_cursor_signals(&state_for_focus);
                    }
                    // Seed the OS IME candidate area at the caret so the
                    // first composition appears in the right place.
                    keyboard::report_ime_cursor_area(&state_for_focus, ctx);
                } else {
                    // Preserve `cursor`'s selection across focus loss
                    // — clearing it here breaks the right-click
                    // context menu path (the framework focuses the
                    // newly-mounted menu, which dispatches `FocusLost`
                    // here, and `Cut` / `Copy` invoked from the menu
                    // afterwards find an empty selection). Native
                    // macOS / Windows text fields keep the selection
                    // on blur too — typically the visual is dimmed
                    // but the selection state is preserved so the
                    // next focus-gain or context-menu invocation
                    // still operates on it.
                    st.scroll_x = 0.0;
                    st.caret_visible.set(false);
                    st.drag_state = state::DragState::Idle;
                    // Drop the IME-area dedup cache. The OS candidate area is a
                    // single per-window resource a sibling field may re-point
                    // while we are unfocused; clearing this forces the next
                    // focus-gain report to re-seed it instead of being deduped.
                    st.last_ime_area = None;
                    blur_callback = st.on_blur.clone();
                    drop(st);
                    // Abandon any in-progress composition on blur — remove
                    // the tentative preedit text from the document.
                    keyboard::clear_ime_preedit(&state_for_focus);
                    sync_cursor_signals(&state_for_focus);
                }
                if let Some(cb) = blur_callback {
                    cb(ctx);
                }
                ctx.request_frame();
            })
            .on_pointer_event(move |event, ctx| {
                mouse::handle_pointer_event(&state_for_pointer, event, ctx)
            })
            .on_key(move |event, ctx| keyboard::handle_key(&state_for_key, event, ctx))
            .on_double_tap(move |event, ctx| {
                mouse::handle_double_tap(&state_for_double, event.position, ctx)
            })
            .on_triple_tap(move |event, ctx| {
                mouse::handle_triple_tap(&state_for_triple, event.position, ctx)
            })
            .on_access_action_request(move |action, _target_node, data, ctx| {
                handle_access_action(&state_for_access, action, data, ctx)
            })
            // Right-click context menu — built fresh per click so the
            // enabled state of each item reflects the live selection /
            // clipboard state at the moment the menu opens. The framework
            // handles overlay placement, focus restoration, and dismissal.
            .context_menu(move |position, ctx| {
                let _ = ctx;
                // Framework gates pointer events on `arena.is_enabled`
                // before reaching this closure — a disabled field
                // never receives the right-click that would open the
                // context menu.
                // Reposition the caret to the click position when the
                // click lands outside the existing selection — the
                // platform convention for "right-click then Cut /
                // Copy / Paste at the new caret".
                mouse::reposition_caret_for_context_menu(&state_for_menu, position);
                Some(build_context_menu_widget(&state_for_menu))
            });

        ctx.apply_self_handlers(handlers);
        Vec::new()
    }

    fn layout_response(
        &self,
        proposal: SizeProposal,
        ctx: &LayoutContext,
    ) -> teksilo_core::widget::LayoutResponse {
        // Default unwrap is the cached natural width (mask-aware when
        // a mask is set; 200 dp fallback otherwise). Composing widgets
        // that wrap us in a constraint pass `Some(width)` and we use
        // that; the natural width is what surfaces in unconstrained
        // intrinsic queries (ZStack measurement with `unspecified()`,
        // etc.) so the chain reports a sensible content size.
        //
        // The cached `natural_width` / `text_height` are 1.0-scale baselines;
        // multiply by `ctx.text_scale` so the field box grows with the global
        // accessibility text scale (the engine grows the glyphs to match — see
        // `paint`). A caller-supplied width constraint is honored as-is.
        let scale = ctx.text_scale;
        let w = proposal
            .width
            .unwrap_or(self.natural_width * scale)
            .max(0.0);
        let h = (self.text_height.unwrap_or(DEFAULT_TEXT_HEIGHT) * scale).max(0.0);
        Size::new(w, h).into()
    }

    fn place_children(
        &self,
        bounds: Rect,
        _proposal: SizeProposal,
        _children: &mut [WidgetPlacement],
        _ctx: &LayoutContext,
    ) {
        // Layout runs before paint, so this is the authoritative point to adopt
        // the field's viewport. `sync_viewport` welds the width write to the
        // `needs_full_layout` flag it also serves as the detector for (see its
        // docs); paint calls it again as an idempotent echo.
        if let Some(state) = self.state.as_ref() {
            state.borrow_mut().sync_viewport(bounds);
        }
    }

    fn paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
        let Some(state) = self.state.as_ref() else {
            return;
        };
        let mut st = state.borrow_mut();

        // Grow the shaped text with the global accessibility scale. Must run
        // before the relayout block below so the larger glyphs are shaped this
        // frame; no-op when the scale is unchanged.
        st.apply_font_scale(ctx.text_scale);
        // Idempotent echo — `place_children` already adopted these exact bounds
        // during layout, so this is normally a no-op.
        st.sync_viewport(bounds);

        // Resolve the glyph / caret / suffix colours against the *effective*
        // enabled state, exactly as `TextWidget` and `RectWidget` resolve a
        // `ColorProp` at paint time. `paint` is the single writer of these:
        // the field shapes through a `RichTextEngine`, which takes raw GPU
        // colours and so never passes through `ColorProp::resolve` — the
        // disabled substitution that greys every role-driven leaf for free
        // cannot reach it. Doing it here (rather than as a build-time effect
        // on `effective_enabled_signal`) is also the only correct option:
        // that signal is *derived* whenever an ancestor binds `enabled`, and
        // `Signal::observe` panics on derived signals. Cheap — the engine
        // stores the colour and the render-frame builder reads it, so there
        // is no relayout and no reshaping.
        let text_color = if ctx.effective_enabled {
            ctx.theme.colors.text_primary
        } else {
            ctx.theme.colors.text_disabled
        };
        st.engine.set_text_color(text_color.to_array());
        st.engine.set_cursor_color(text_color.to_array());

        let suffix_width = st.suffix_width;
        let text_viewport_width = (bounds.width - suffix_width).max(0.0);

        st.engine.set_viewport(10_000.0, bounds.height);

        if st.needs_full_layout || !st.engine.has_full_layout() {
            st.layout_full_masked();
            st.needs_full_layout = false;
            st.content_dirty = true;
        }

        // Suppress the caret in an inactive window for every paint — the
        // authoritative gate, covering the frame between a window-active flip
        // and the build-time effect running.
        let caret_on = st.caret_visible.get() && st.has_focus && st.window_active;
        // `NoEcho` while masked lays out an *empty* source, so the real
        // document cursor (which may sit past 0) must not be handed to
        // the engine — pin the displayed caret/selection to the start.
        // The real `cursor` still tracks the true position for editing.
        let hide_all = st.echo_mode == EchoMode::NoEcho && st.should_mask();
        let (disp_pos, disp_anchor) = if hide_all {
            (0, 0)
        } else {
            (st.cursor.position(), st.cursor.anchor())
        };
        // Single-line input has no wrap → affinity is moot; the
        // default Downstream matches pre-affinity behavior.
        let cursor_display = CursorDisplay {
            position: disp_pos,
            anchor: disp_anchor,
            affinity: CursorAffinity::Downstream,
            visible: caret_on,
            selected_cells: Vec::new(),
        };
        st.engine.set_cursor(&cursor_display);

        ensure_caret_visible_h(&mut st, text_viewport_width);

        let scroll_x = st.scroll_x;

        let text_clip = Rect::new(bounds.x, bounds.y, text_viewport_width, bounds.height);
        canvas.set_clip(text_clip);

        {
            let state_ref: &mut TextInputState = &mut st;
            let TextInputState {
                ref mut engine,
                ref document,
                ref mut image_cache,
                ..
            } = *state_ref;

            engine.with_render_frame(|frame| {
                paint_frame(
                    canvas,
                    PaintParams {
                        frame,
                        origin: Point::new(bounds.x - scroll_x, bounds.y),
                        document,
                        image_cache,
                        // No inline images on this surface, so none can be missing.
                        image_resolver: None,
                        selection: None,
                        selection_color: [0.0; 4],
                        selected_image_out: None,
                        resize_preview: None,
                        draw_caret: caret_on,
                    },
                );
            });
        }

        // IME preedit underline: a thin line under the composing range so
        // the user sees the text is tentative. Single line → one segment;
        // on a secure field it sits under the masked bullets. Drawn inside
        // the text clip so it never spills past the viewport.
        if let Some(range) = st.ime_preedit_range.clone()
            && st.engine.has_full_layout()
            && range.start < range.end
        {
            let start_c = st
                .engine
                .caret_rect(range.start, CursorAffinity::Downstream);
            let end_c = st.engine.caret_rect(range.end, CursorAffinity::Downstream);
            let x0 = bounds.x - scroll_x + start_c[0];
            let x1 = bounds.x - scroll_x + end_c[0];
            let y = bounds.y + start_c[1] + start_c[3] - 1.0;
            canvas.draw_line(
                Point::new(x0, y),
                Point::new(x1, y),
                ctx.theme.colors.text_primary,
                teksilo_canvas::StrokeStyle::solid(1.0),
            );
        }

        canvas.clear_clip();

        if suffix_width > 0.0
            && let Some(suffix_engine) = st.suffix_engine.as_mut()
        {
            // The suffix dims with the value it annotates — a crisp " %"
            // beside greyed-out digits reads as a rendering bug.
            let suffix_color = if ctx.effective_enabled {
                ctx.theme.colors.text_secondary
            } else {
                ctx.theme.colors.text_disabled
            };
            suffix_engine.set_text_color(suffix_color.to_array());
            let suffix_clip = Rect::new(
                bounds.x + text_viewport_width,
                bounds.y,
                suffix_width,
                bounds.height,
            );
            canvas.set_clip(suffix_clip);
            let suffix_origin = Point::new(bounds.x + text_viewport_width, bounds.y);
            suffix_engine.with_render_frame(|frame| {
                paint_suffix_glyphs(canvas, frame, suffix_origin);
            });
            canvas.clear_clip();
        }
    }

    fn accessibility(&self, builder: &mut AccessNodeBuilder) {
        use teksilo_core::accesskit::{Action, Role};

        let Some(state) = self.state.as_ref() else {
            return;
        };
        let st = state.borrow();

        let text = st.document.to_plain_text().unwrap_or_default();

        // AT-protection tracks the *explicit* reveal toggle only — not
        // the visual `RevealWhileTyping` focus-reveal (a sighted-only
        // convenience that a screen reader shouldn't surface as
        // plaintext, and that has no AT-dirty trigger on focus). The
        // reveal signal is bound at AccessibilityOnly in `build`, so the
        // role/value swap reaches AT when it flips. `Role::PasswordInput`
        // is the sole mechanism telling AT not to speak the value —
        // accesskit has no separate `protected` flag.
        let explicitly_revealed = st.revealed.as_ref().is_some_and(|s| s.get());
        let protected = st.secure
            && match st.at_reveal_policy {
                AtRevealPolicy::AlwaysProtected => true,
                AtRevealPolicy::SwapRole => !explicitly_revealed,
            };

        if protected {
            builder.set_role(Role::PasswordInput);
            // Expose a bullet string of the right length (NoEcho hides
            // even that) so AT can announce the character count, never
            // the secret. Deliberately omit character lengths, word
            // starts, and the text selection: the caret model stays
            // opaque so no structure about the secret leaks.
            if st.echo_mode != EchoMode::NoEcho {
                let count = text.chars().count();
                if count > 0 {
                    builder.set_value(st.echo_char.to_string().repeat(count));
                }
            }
        } else {
            // Plain field, or a revealed field under `SwapRole`: report
            // as a text input exposing the real value, mirroring the web
            // `type=password ↔ type=text` swap. The specialised role from
            // `input_purpose` (WCAG 1.3.5) applies here; `Role::TextInput` is
            // the `Normal` default.
            builder.set_role(self.input_purpose.to_role());
            // Keep the value on the input node so the focus announcement is
            // unchanged: accesskit resolves `value()` from `data().value()`
            // first, falling back to the TextRun text only when unset.
            if !text.is_empty() {
                builder.set_value(&text);
            }

            // Expose the editable content as a child `Role::TextRun`, NOT as
            // `character_lengths` on the input node itself. accesskit_consumer's
            // `supports_text_ranges()` is false for a childless input that only
            // hosts character data on its own node, so the macOS adapter never
            // fires `AXSelectedTextChanged` — VoiceOver reads the value once on
            // focus but never echoes characters/words while typing. Emit the run
            // even when empty so `supports_text_ranges()` is already true before
            // the first keystroke (the change-diff's *old* node must support
            // ranges too for the notification to fire). `position()` / `anchor()`
            // are character indices (text-document is char-space), matching the
            // TextRun's `character_index` contract — correct for multibyte text.
            let char_lengths: Vec<u8> = text.chars().map(|c| c.len_utf8() as u8).collect();
            let word_starts = compute_word_starts(&text);
            let word_starts = (!word_starts.is_empty()).then_some(word_starts);
            let run_id =
                builder.push_text_run_child_on_self(0, text.clone(), char_lengths, word_starts);

            // While composing (IME preedit active), expose the composition
            // as a selection so screen readers / braille track the tentative
            // text — the composing characters are already in `value`. Falls
            // back to the live cursor/selection when not composing. (The
            // secure branch above never reaches here, so a password preedit
            // is never exposed.) Selection now references the TextRun child.
            let (anchor, pos) = match st.ime_preedit_range.clone() {
                Some(range) => (range.start, range.end),
                None => (st.cursor.anchor(), st.cursor.position()),
            };
            builder.set_text_selection_to((run_id, anchor), (run_id, pos));
        }

        if !st.placeholder.is_empty() {
            builder.set_placeholder(st.placeholder.clone());
        }

        if st.read_only {
            builder.set_read_only();
        }

        builder.add_action(Action::Focus);
        if !st.read_only {
            builder.add_action(Action::SetValue);
            builder.add_action(Action::ReplaceSelectedText);
        }
        // Only meaningful when the caret model is exposed to AT.
        if !protected {
            builder.add_action(Action::SetTextSelection);
        }

        // Validation feedback → accesskit `aria-invalid`. Surface
        // `Invalid` as `Invalid::True`; `Corrected` doesn't carry an
        // invalid marker (the data is now valid) but the composite's
        // Live region announces the correction. The framework's
        // AccessNodeBuilder doesn't yet wrap `set_invalid`, so reach
        // through `inner_mut()` which is the documented escape hatch.
        if self.feedback.get().is_invalid() {
            builder
                .inner_mut()
                .set_invalid(teksilo_core::accesskit::Invalid::True);
        }

        // ARIA combobox wiring. This node is the one that actually holds
        // keyboard focus, which is why the relation is published here and not
        // on whichever composite owns the list — AT follows the *focused*
        // node's active descendant.
        if let Some(listbox) = self.controls.as_ref().and_then(|s| s.get()) {
            builder.push_controlled(teksilo_core::accessibility::widget_id_to_node_id(listbox));
        }
        if let Some(active) = self.active_descendant.as_ref().and_then(|s| s.get()) {
            builder
                .inner_mut()
                .set_active_descendant(teksilo_core::accessibility::widget_id_to_node_id(active));
        }
    }
}

impl TextInputField {
    /// Borrow the shared state. Panics if called before `build()`
    /// has run — the state is allocated in `build()` from the
    /// builder config.
    fn state(&self) -> &SharedState {
        self.state
            .as_ref()
            .expect("TextInputField::state called before build")
    }
}

/// Adjust `scroll_x` so the caret stays within the visible viewport.
///
/// `text_viewport_width` is the portion of the viewport reserved for
/// editable text, i.e. `viewport_width - suffix_width`. Callers pass
/// the reduced width explicitly so the scroll never slides text
/// behind the non-editable suffix.
fn ensure_caret_visible_h(st: &mut TextInputState, text_viewport_width: f32) {
    if !st.engine.has_full_layout() || text_viewport_width <= 0.0 {
        return;
    }
    let pos = st.cursor.position();
    // Single-line input: no wrap, affinity is a no-op.
    let caret = st.engine.caret_rect(pos, CursorAffinity::Downstream);
    let caret_x = caret[0];
    let caret_w = caret[2].max(1.0);
    let vw = text_viewport_width;

    if caret_x - st.scroll_x < SCROLL_MARGIN {
        st.scroll_x = (caret_x - SCROLL_MARGIN).max(0.0);
    } else if caret_x + caret_w - st.scroll_x > vw - SCROLL_MARGIN {
        st.scroll_x = caret_x + caret_w - vw + SCROLL_MARGIN;
    }
}

/// Update the cached suffix text and re-run layout on the suffix
/// engine. Called from `build()` for the initial value and from
/// the reactive effect when the bound suffix signal fires.
fn relayout_suffix(state: &SharedState, new_text: &str) {
    let mut st = state.borrow_mut();
    st.suffix = new_text.to_string();
    if new_text.is_empty() {
        st.suffix_width = 0.0;
        // Leave the engine in place (cheap to reuse) but don't
        // lay out — paint skips the suffix when width is zero.
        return;
    }
    let Some(engine) = st.suffix_engine.as_mut() else {
        // No engine allocated (pure-static path that started
        // empty and never became non-empty). Allocate lazily so
        // late signal flips still render.
        return;
    };
    let doc = TextDocument::new();
    let _ = doc.set_plain_text(new_text);
    let flow = doc.snapshot_flow();
    engine.layout_full(&flow);
    st.suffix_width = engine.max_content_width();
}

/// Paint glyphs from a pre-laid-out suffix `RenderFrame` at a fixed
/// origin. Decorations, selection rectangles, and caret are ignored —
/// the suffix is plain non-editable text, so only the glyph pass is
/// needed. Kept inline (rather than reusing `paint_frame`) to avoid
/// the `TextDocument` / `ImageCache` parameters `paint_frame`
/// requires for inline images the suffix never contains.
fn paint_suffix_glyphs(canvas: &mut Canvas, frame: &teksilo_text::RenderFrame, origin: Point) {
    use teksilo_canvas::GlyphQuad as CanvasGlyphQuad;
    for g in frame.glyphs.iter() {
        let quad = CanvasGlyphQuad {
            screen: [
                g.screen[0] + origin.x,
                g.screen[1] + origin.y,
                g.screen[2],
                g.screen[3],
            ],
            atlas: g.atlas,
            color: g.color,
            is_color: g.is_color,
        };
        canvas.draw_glyph_quad(quad);
    }
}

/// Selection-highlight colour for a text field: the vivid `selection_bg_active`
/// while the host window is active, the muted `selection_bg_inactive` while it
/// is inactive — so a field's selection desaturates in a background window
/// (the universal desktop convention; the same `selection_bg_inactive` the OS
/// uses for unfocused selection).
/// The band a selection is painted in — the **active** tint only while this
/// field is the one the keystrokes would go to.
///
/// Two axes, and both are needed. The window losing focus was already handled;
/// what was missing is the field losing it *within* an active window, which is
/// the common case: click into a cell editor, then click a button, and the
/// field went on showing a fully-lit selection as though it were still taking
/// input. Two fields on screen could both look focused at once.
///
/// The selection *state* is deliberately kept across blur — see the
/// `on_focus(false)` arm, which spells out why (the right-click Copy path needs
/// it, and native fields keep it too). This is the other half of that same
/// sentence: the state is preserved, the **visual is dimmed**. Only the second
/// half was implemented.
fn field_selection_color(
    colors: &teksilo_tokens::ColorTokens,
    window_active: bool,
    has_focus: bool,
) -> [f32; 4] {
    if window_active && has_focus {
        colors.selection_bg_active.to_array()
    } else {
        colors.selection_bg_inactive.to_array()
    }
}

/// Simplified frame-loop tick for single-line text input.
fn tick(state: &mut TextInputState, delta: f32) -> bool {
    if !state.pending_chars.is_empty() {
        let batch = std::mem::take(&mut state.pending_chars);
        let _ = state.cursor.insert_text(&batch);
        state.pending_text_changed = true;
    }

    let had_events = state.drain_events();

    // Blink only when focused AND the host window is active — the caret hides
    // in an inactive window (the universal desktop convention). The else-branch
    // below then turns it off, since `!blinking_active` now also covers the
    // window-inactive case.
    let caret_active = state.has_focus && state.window_active;
    let caret_visible = state.caret_visible.clone();
    let wake = state.frame_wake_at.clone();
    // A single-line field always blinks (no read-only/static presets), so it
    // hands the shared machine a fixed `Blinking` policy.
    state.blink.tick(
        CaretPolicy::Blinking,
        caret_active,
        &caret_visible,
        wake.as_ref(),
    );

    if state.needs_full_layout && state.viewport_width > 0.0 {
        state.layout_full_masked();
        state.needs_full_layout = false;
        state.content_dirty = true;
    }

    if state.pending_text_changed {
        let new_text = state.document.to_plain_text().unwrap_or_default();
        if state.text_signal.get() != new_text {
            state.deferred_text_update = Some(new_text);
        }
    }

    if state.debounce.tick(delta) {
        if state.pending_text_changed {
            state.pending_text_changed = false;
        }
        if let Some((cu, cr)) = state.pending_undo_redo.take() {
            if state.can_undo.get() != cu {
                state.can_undo.set(cu);
            }
            if state.can_redo.get() != cr {
                state.can_redo.set(cr);
            }
        }
    }
    let debounce_work = state.pending_text_changed || state.pending_undo_redo.is_some();

    had_events || debounce_work
}

/// Handle AccessKit actions (SetValue, SetTextSelection, Focus).
fn handle_access_action(
    state: &SharedState,
    action: teksilo_core::accesskit::Action,
    data: Option<teksilo_core::accesskit::ActionData>,
    ctx: &mut EventContext,
) -> EventResponse {
    use teksilo_core::accesskit::{Action, ActionData};

    match (action, data) {
        (Action::SetTextSelection, Some(ActionData::SetTextSelection(sel))) => {
            let st = state.borrow();
            st.cursor.set_position(
                sel.anchor.character_index,
                teksilo_text::text_document::MoveMode::MoveAnchor,
            );
            st.cursor.set_position(
                sel.focus.character_index,
                teksilo_text::text_document::MoveMode::KeepAnchor,
            );
            drop(st);
            sync_cursor_signals(state);
            ctx.request_frame();
            EventResponse::Handled
        }
        (Action::SetValue, Some(ActionData::Value(value))) => {
            let st = state.borrow();
            st.cursor.select(SelectionType::Document);
            let _ = st.cursor.insert_text(value.as_ref());
            drop(st);
            sync_cursor_signals(state);
            ctx.request_frame();
            EventResponse::Handled
        }
        (Action::ReplaceSelectedText, Some(ActionData::Value(value))) => {
            // Insert at the caret, replacing the active selection (if
            // any) — NOT the whole document like `SetValue`. This is the
            // AT-SPI (Linux) / UIA (Windows) braille-keyboard and
            // dictation insertion path; macOS routes insertion through
            // `SetValue` instead, so this never fires there. We advertise
            // the action in `accessibility()`, so we must service it.
            let st = state.borrow();
            let _ = st.cursor.insert_text(value.as_ref());
            drop(st);
            sync_cursor_signals(state);
            ctx.request_frame();
            EventResponse::Handled
        }
        (Action::Focus, _) => {
            if let Some(id) = state.borrow().field_widget_id {
                ctx.request_focus(id);
            }
            EventResponse::Handled
        }
        _ => EventResponse::Ignored,
    }
}

/// Compute word-start character indices for AccessKit.
fn compute_word_starts(text: &str) -> Vec<u8> {
    let mut starts = Vec::new();
    let mut in_word = false;
    for (char_index, ch) in text.chars().enumerate() {
        let is_word_char = ch.is_alphanumeric() || ch == '_';
        if is_word_char
            && !in_word
            && let Ok(idx) = u8::try_from(char_index)
        {
            starts.push(idx);
        }
        in_word = is_word_char;
    }
    starts
}

/// Build a fresh right-click context menu widget. Called from the
/// `.context_menu(...)` factory on every right-click, so each open
/// reads live `has_selection` / `is_empty` state when computing each
/// item's enabled flag.
fn build_context_menu_widget(state: &SharedState) -> Box<dyn Widget> {
    let st = state.borrow();
    let has_selection = st.cursor.has_selection();
    let doc_non_empty = !st.document.to_plain_text().unwrap_or_default().is_empty();
    // Secure fields suppress Cut / Copy while masked (still allowed when
    // revealed or when the developer opted in via `allow_copy`).
    let copy_allowed = st.copy_allowed();
    drop(st);

    let state_cut = state.clone();
    let state_copy = state.clone();
    let state_paste = state.clone();
    let state_select_all = state.clone();

    Box::new(
        MenuList::new()
            .item(
                MenuItem::new(tr_widget!(menu_cut()))
                    .shortcut_label(format_keystroke(KeyStroke::command(Key::X)))
                    .enabled(has_selection && copy_allowed)
                    .on_activate_fn(move |ctx| {
                        {
                            let mut st = state_cut.borrow_mut();
                            keyboard::clipboard_cut(&mut st, ctx);
                        }
                        sync_cursor_signals(&state_cut);
                        ctx.request_frame();
                    }),
            )
            .item(
                MenuItem::new(tr_widget!(menu_copy()))
                    .shortcut_label(format_keystroke(KeyStroke::command(Key::C)))
                    .enabled(has_selection && copy_allowed)
                    .on_activate_fn(move |ctx| {
                        let mut st = state_copy.borrow_mut();
                        keyboard::clipboard_copy(&mut st, ctx);
                    }),
            )
            .item(
                MenuItem::new(tr_widget!(menu_paste()))
                    .shortcut_label(format_keystroke(KeyStroke::command(Key::V)))
                    .on_activate_fn(move |ctx| {
                        {
                            let mut st = state_paste.borrow_mut();
                            keyboard::clipboard_paste(&mut st, ctx);
                        }
                        sync_cursor_signals(&state_paste);
                        ctx.request_frame();
                    }),
            )
            .item(MenuSeparator)
            .item(
                MenuItem::new(tr_widget!(menu_select_all()))
                    .shortcut_label(format_keystroke(KeyStroke::command(Key::A)))
                    .enabled(doc_non_empty)
                    .on_activate_fn(move |ctx| {
                        {
                            let st = state_select_all.borrow();
                            st.cursor.select(SelectionType::Document);
                        }
                        sync_cursor_signals(&state_select_all);
                        ctx.request_frame();
                    }),
            ),
    )
}

/// Run the validator on the bound text and update the feedback signal.
///
/// On `Corrected`, also writes the corrected text back to the bound
/// signal — the field's external→internal sync effect picks this up
/// and rewrites the document in the next frame. On `Invalid`, the
/// text is left as-typed; composites that want a "revert on invalid"
/// behaviour observe the feedback signal and rewrite the text from
/// their own source of truth (e.g., `DateEdit` reformats from its
/// `Signal<Option<Date>>`).
fn run_validator_and_apply(
    validator: &ValidatorFn,
    bound_text: &Signal<String>,
    feedback: &Signal<ValidationFeedback>,
) {
    let raw = bound_text.get();
    match validator(&raw) {
        ValidationOutcome::Valid => {
            feedback.set(ValidationFeedback::Valid);
        }
        ValidationOutcome::Corrected { corrected, message } => {
            // Write the corrected text first so observers of the
            // bound signal see the new value before the feedback
            // signal flips. Composites that bind to BOTH signals
            // (rare) will see a consistent pair: text + correction
            // notice describing the change.
            if bound_text.get() != corrected {
                bound_text.set(corrected);
            }
            feedback.set(ValidationFeedback::Corrected {
                message,
                since: std::time::Instant::now(),
            });
        }
        ValidationOutcome::Invalid { message } => {
            feedback.set(ValidationFeedback::Invalid { message });
        }
    }
}

/// Build the worst-case-glyph version of an [`InputMask`] for
/// natural-width measurement: every editable slot holds the widest
/// plausible character its class can accept, and every fixed slot
/// holds its literal. Used by `build()` to size the field's
/// intrinsic envelope so a fully-typed value never overflows the
/// reported natural width.
///
/// Per-class worst-case glyph (Inter and most UI sans-serifs):
/// - `Digit` → `0` (tabular figures are constant-width, but `0` is
///   representative for fonts that aren't)
/// - `Letter` / `Alphanumeric` / `Any` → `M` (widest cap glyph)
/// - `HexDigit` → `0`
fn worst_case_template(mask: &InputMask) -> String {
    let mut s = String::with_capacity(mask.len());
    for pos in mask.positions() {
        match pos {
            MaskPosition::Editable { class, .. } => {
                s.push(match class {
                    MaskClass::Digit | MaskClass::HexDigit => '0',
                    MaskClass::Letter | MaskClass::Alphanumeric | MaskClass::Any => 'M',
                });
            }
            MaskPosition::Fixed(c) => s.push(*c),
        }
    }
    s
}

/// Measure the advance width of `text` in logical pixels using the
/// app-wide `SharedTypesetter` (the same backend the field paints
/// with). Falls back to a per-character-class heuristic when no
/// typesetter is installed (headless tests) so the caller still gets
/// a non-zero width and any natural-width / cap logic behaves
/// reasonably even there. The fallback weights match Inter's body
/// proportions closely enough that the difference between an
/// underscore and a wide cap glyph (`M`) shows up in headless tests
/// — important for verifying the worst-case-glyph mask measurement
/// without booting a typesetter.
fn measure_width_px(ctx: &mut BuildContext, text: &str, style: &TextStyle) -> f32 {
    if text.is_empty() {
        return 0.0;
    }
    if let Some(ts) = ctx.app_state::<SharedTypesetter>() {
        let backend = ts.as_text_backend();
        let layout = backend.borrow_mut().layout_single_line(text, style, None);
        return layout.width;
    }
    let em = style.size;
    text.chars()
        .map(|c| match c {
            ' ' => 0.30,
            '_' => 0.45,
            ':' | '.' | ',' | ';' | '/' | '|' | '!' | 'i' | 'l' | 'I' => 0.30,
            '0'..='9' => 0.55,
            'M' | 'W' | 'm' | 'w' => 0.85,
            'A'..='Z' => 0.65,
            'a'..='z' => 0.50,
            _ => 0.55,
        })
        .map(|w: f32| w * em)
        .sum()
}

#[cfg(test)]
mod window_active_tests {
    use super::*;
    use teksilo_canvas::{Point, SizeProposal};
    use teksilo_core::event::{Modifiers, PointerButton, WidgetEvent};
    use teksilo_core::signal::Signal;
    use teksilo_core::widget_tree::WidgetTree;

    #[test]
    fn field_selection_color_swaps_on_window_active() {
        let colors = teksilo_core::presets::intui::light().colors;
        assert_eq!(
            field_selection_color(&colors, true, true),
            colors.selection_bg_active.to_array(),
            "active window uses the vivid selection colour"
        );
        assert_eq!(
            field_selection_color(&colors, false, true),
            colors.selection_bg_inactive.to_array(),
            "inactive window uses the muted selection colour"
        );
        assert_ne!(
            field_selection_color(&colors, true, true),
            field_selection_color(&colors, false, true)
        );
    }

    /// **A field that is not focused dims its selection, even in an active
    /// window.**
    ///
    /// Only the window axis was ever consulted, so clicking from one field to
    /// another left both showing a fully-lit selection: two controls claiming
    /// the keystrokes at once. The selection *state* is kept on blur on
    /// purpose — the `on_focus(false)` arm explains why, and native fields do
    /// the same — and this is the other half of that sentence, which had never
    /// been written.
    #[test]
    fn field_selection_color_dims_when_the_field_is_not_focused() {
        let colors = teksilo_core::presets::intui::light().colors;
        assert_eq!(
            field_selection_color(&colors, true, false),
            colors.selection_bg_inactive.to_array(),
            "an unfocused field must dim its selection even in an active window"
        );
        assert_eq!(
            field_selection_color(&colors, false, false),
            colors.selection_bg_inactive.to_array()
        );
    }

    /// ...and the live field re-tints as focus comes and goes, rather than
    /// keeping whatever colour it was built with.
    #[test]
    fn a_field_re_tints_its_selection_when_focus_leaves_it() {
        let colors = teksilo_core::presets::intui::light().colors;
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let a = tree.add(TextInputField::new(Signal::new("hello".to_string())));
        let b = tree.add(TextInputField::new(Signal::new("world".to_string())));
        tree.layout(SizeProposal::exact(200.0, 40.0));

        let tint = |tree: &WidgetTree, id| {
            tree.widget_as_any(id)
                .and_then(|w| w.downcast_ref::<TextInputField>())
                .and_then(|f| f.state.as_ref())
                .map(|st| st.borrow().selection_tint)
                .expect("a built field")
        };

        tree.focus(a);
        assert_eq!(
            tint(&tree, a),
            colors.selection_bg_active.to_array(),
            "the focused field paints its selection live"
        );

        tree.focus(b);
        assert_eq!(
            tint(&tree, a),
            colors.selection_bg_inactive.to_array(),
            "focus moved to another field and the first kept a lit selection"
        );
        assert_eq!(tint(&tree, b), colors.selection_bg_active.to_array());
    }

    #[test]
    fn caret_hidden_when_window_inactive() {
        let text = Signal::new("hello".to_string());
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let id = tree.add(TextInputField::new(text));
        tree.layout(SizeProposal::exact(200.0, 40.0));
        let _ = tree.render();

        // Reach the built field's shared state (created lazily in build()) to
        // observe the caret-gate inputs directly — the caret paints as an
        // engine-internal fill, not a top-level decoration.
        let state = tree
            .widget_as_any(id)
            .and_then(|a| a.downcast_ref::<TextInputField>())
            .map(|f| f.state().clone())
            .expect("built TextInputField is reachable via as_any");

        // Focus the field by clicking its centre.
        let b = tree.bounds(id);
        tree.dispatch_event(WidgetEvent::PointerDown {
            position: Point::new(b.x + b.width / 2.0, b.y + b.height / 2.0),
            button: PointerButton::Primary,
            modifiers: Modifiers::NONE,
        });
        // One frame so the blink turns the caret on (on_focus sets it on; the
        // 500 ms interval hasn't elapsed after a single 16 ms tick).
        tree.request_frame();
        tree.tick_animations(std::time::Duration::from_millis(16));
        tree.layout(SizeProposal::exact(200.0, 40.0));

        assert!(state.borrow().has_focus, "field took focus");
        assert!(state.borrow().window_active);
        assert!(
            state.borrow().caret_visible.get(),
            "caret visible when focused in an active window"
        );

        // Window blur: caret hidden (effect clears it synchronously).
        tree.set_window_active(false);
        assert!(!state.borrow().window_active);
        assert!(
            !state.borrow().caret_visible.get(),
            "caret hidden while the window is inactive"
        );

        // Reactivate: caret returns immediately (field still holds focus).
        tree.set_window_active(true);
        assert!(
            state.borrow().caret_visible.get(),
            "caret restored on window reactivate"
        );
    }
}

/// **A key the platform decorates with control text must still bubble.**
///
/// These dispatch `KeyDown` with the `text` a real keyboard carries. Every
/// synthetic helper in the workspace sends `text: None`, which skips the branch
/// under test entirely — so a test written with `press_key` passes on the bug.
#[cfg(test)]
mod key_text_bubbling_tests {
    use super::*;
    use std::cell::Cell;
    use teksilo_canvas::{Point, SizeProposal};
    use teksilo_core::WidgetBuilder;
    use teksilo_core::event::{Modifiers, PointerButton, WidgetEvent};
    use teksilo_core::signal::Signal;
    use teksilo_core::widget_tree::WidgetTree;

    /// Dispatch one `KeyDown` to a focused field that sits *inside* a widget
    /// carrying an `on_key`, and report whether that outer handler saw it.
    ///
    /// The nesting is the point. Hanging the handler on the field itself puts
    /// it on the same node the click focuses, above the field's own handler
    /// rather than behind it, and the bubble under test never happens — which
    /// is exactly how an earlier version of this test passed on the bug.
    fn outer_handler_sees(key: Key, text: Option<&str>, field: TextInputField) -> bool {
        let seen = Rc::new(Cell::new(false));
        let seen_for_handler = seen.clone();
        let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
        let outer = tree.add(crate::primitives::VStack::new().child(field).on_key(
            move |_ev, _ctx| {
                seen_for_handler.set(true);
                EventResponse::Handled
            },
        ));
        tree.layout(SizeProposal::exact(200.0, 40.0));

        let b = tree.bounds(outer);
        let centre = Point::new(b.x + b.width / 2.0, b.y + b.height / 2.0);
        tree.dispatch_event(WidgetEvent::PointerDown {
            position: centre,
            button: PointerButton::Primary,
            modifiers: Modifiers::NONE,
        });
        tree.dispatch_event(WidgetEvent::PointerUp {
            position: centre,
            button: PointerButton::Primary,
            modifiers: Modifiers::NONE,
        });
        let focused = tree.focused().expect("the click focused something");
        assert_ne!(
            focused, outer,
            "focus must land on the field, or nothing below the outer handler is being tested"
        );

        tree.dispatch_event(WidgetEvent::KeyDown {
            key,
            modifiers: Modifiers::NONE,
            text: text.map(str::to_string),
        });
        seen.get()
    }

    /// The bug: winit gives Escape `text: Some("\u{1b}")`, the field had no
    /// `Escape` arm so it fell into the printable-character branch, the control
    /// character was filtered out, and the empty result was read as "input
    /// rejected" — which swallows the key. Escape therefore never left a
    /// focused field, and anything above it that closes on Escape stayed open.
    #[test]
    fn escape_bubbles_out_of_a_field_even_carrying_its_control_text() {
        assert!(
            outer_handler_sees(
                Key::Escape,
                Some("\u{1b}"),
                TextInputField::new(Signal::new("hello".to_string()))
            ),
            "Escape must reach the widget above the field"
        );
    }

    /// ...and it made no difference with `text: None`, which is why the whole
    /// suite went green on the bug. Kept so the two cases stay visibly paired.
    #[test]
    fn escape_bubbles_out_of_a_field_without_text() {
        assert!(outer_handler_sees(
            Key::Escape,
            None,
            TextInputField::new(Signal::new("hello".to_string()))
        ));
    }

    /// The other half of the guard, and the reason it is written against the
    /// *text* rather than the `Key` variant: a character the field's filter
    /// rejects is still swallowed, so a digits-only field does not let a
    /// rejected letter fall through and match a shortcut.
    ///
    /// A typed letter arrives as `Key::A`, not `Key::Character('a')`, so a
    /// variant test here would have silently stopped swallowing letters.
    #[test]
    fn a_filter_rejected_character_is_still_swallowed() {
        let digits_only = TextInputField::new(Signal::new(String::new()))
            .char_filter(|c: char| c.is_ascii_digit());
        assert!(
            !outer_handler_sees(Key::A, Some("a"), digits_only),
            "a rejected letter must not bubble into a shortcut match"
        );
    }
}

/// A live handle on a [`TextInputField`] — its text-editing commands, for a
/// caller outside the widget.
///
/// Every method is a no-op before the field is built (and after it is
/// destroyed), which is the honest answer rather than a panic: a menu row bound
/// to a field that is no longer on screen should do nothing, not crash.
#[derive(Clone)]
pub struct TextFieldHandle {
    slot: std::rc::Rc<std::cell::RefCell<Option<SharedState>>>,
    focus_signal: Signal<bool>,
}

impl std::fmt::Debug for TextFieldHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TextFieldHandle")
            .field("live", &self.slot.borrow().is_some())
            .field("focused", &self.focus_signal.get())
            .finish()
    }
}

impl TextFieldHandle {
    /// A handle not yet attached to any field — for a composing widget that
    /// hands one out before building the field it will delegate to. Every
    /// method answers "nothing" until [`TextInputField::share_handle`] binds it.
    pub fn detached() -> Self {
        Self {
            slot: std::rc::Rc::new(std::cell::RefCell::new(None)),
            focus_signal: Signal::new(false),
        }
    }

    /// `true` while this field holds the keyboard focus. Observable, so a
    /// router can follow the caret without polling.
    pub fn focused_signal(&self) -> Signal<bool> {
        self.focus_signal.clone()
    }

    /// Is the widget built and still alive?
    pub fn is_live(&self) -> bool {
        self.slot.borrow().is_some()
    }

    fn with<R>(&self, f: impl FnOnce(&mut TextInputState) -> R) -> Option<R> {
        let slot = self.slot.borrow();
        let state = slot.as_ref()?;
        let mut st = state.borrow_mut();
        Some(f(&mut st))
    }

    /// The field's current text.
    pub fn text(&self) -> String {
        self.with(|st| st.document.to_plain_text().unwrap_or_default())
            .unwrap_or_default()
    }

    /// Is any text selected right now?
    pub fn has_selection(&self) -> bool {
        self.with(|st| st.cursor.has_selection()).unwrap_or(false)
    }

    /// May this field's content be copied at all? A password field says no —
    /// see [`TextInputField::allow_copy`].
    pub fn allows_copy(&self) -> bool {
        self.with(|st| st.allow_copy).unwrap_or(false)
    }

    /// Is the field refusing edits? Cut and Paste are meaningless when it is.
    pub fn is_read_only(&self) -> bool {
        self.with(|st| st.read_only).unwrap_or(true)
    }

    /// Select the whole field.
    pub fn select_all(&self) {
        self.with(|st| st.cursor.select(SelectionType::Document));
    }

    /// Copy the selection to the clipboard.
    pub fn copy(&self, ctx: &EventContext) {
        self.with(|st| keyboard::clipboard_copy(st, ctx));
    }

    /// Cut the selection to the clipboard.
    pub fn cut(&self, ctx: &EventContext) {
        self.with(|st| keyboard::clipboard_cut(st, ctx));
    }

    /// Paste over the selection.
    pub fn paste(&self, ctx: &EventContext) {
        self.with(|st| keyboard::clipboard_paste(st, ctx));
    }

    /// Undo this field's own last edit.
    pub fn undo(&self) {
        self.with(|st| {
            let _ = st.document.undo();
        });
    }

    /// Redo this field's own last undone edit.
    pub fn redo(&self) {
        self.with(|st| {
            let _ = st.document.redo();
        });
    }

    /// Is there anything to undo? Debounced like the editor's twin.
    pub fn can_undo(&self) -> Signal<bool> {
        self.with(|st| st.can_undo.clone())
            .unwrap_or_else(|| Signal::new(false))
    }

    /// Is there anything to redo?
    pub fn can_redo(&self) -> Signal<bool> {
        self.with(|st| st.can_redo.clone())
            .unwrap_or_else(|| Signal::new(false))
    }
}

// ── The framework's uniform view of a text-editing widget ────────────────────

impl teksilo_core::text_surface::TextSurface for TextFieldHandle {
    fn can_undo(&self) -> bool {
        TextFieldHandle::can_undo(self).get()
    }

    fn can_redo(&self) -> bool {
        TextFieldHandle::can_redo(self).get()
    }

    fn undo(&self) {
        TextFieldHandle::undo(self);
    }

    fn redo(&self) {
        TextFieldHandle::redo(self);
    }

    fn has_selection(&self) -> bool {
        TextFieldHandle::has_selection(self)
    }

    fn is_read_only(&self) -> bool {
        TextFieldHandle::is_read_only(self)
    }

    fn allows_copy(&self) -> bool {
        TextFieldHandle::allows_copy(self)
    }

    fn cut(&self, ctx: &teksilo_core::widget::EventContext<'_>) {
        TextFieldHandle::cut(self, ctx);
    }

    fn copy(&self, ctx: &teksilo_core::widget::EventContext<'_>) {
        TextFieldHandle::copy(self, ctx);
    }

    fn paste(&self, ctx: &teksilo_core::widget::EventContext<'_>) {
        TextFieldHandle::paste(self, ctx);
    }

    /// A one-line field carries no formatting to strip, so the plain paste
    /// *is* the paste. Answering "nothing" here would make Edit ▸ Paste without
    /// formatting silently dead over a rename box.
    fn paste_plain(&self, ctx: &teksilo_core::widget::EventContext<'_>) {
        TextFieldHandle::paste(self, ctx);
    }

    fn select_all(&self) {
        TextFieldHandle::select_all(self);
    }
}