teksilo-core 0.9.0

Core of the Teksilo GUI framework — widget trait, arena, layout engine, event dispatch, focus, signals and theming.
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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech

//! WidgetBuilder trait — blanket-implemented for all Widget types.
//!
//! Provides attached event handler methods and framework-level properties.
//! Each method wraps the widget in a `WidgetWithHandlers<W>` that stores
//! the handlers and metadata alongside the widget. When the widget is
//! inserted into the arena, the handler set is extracted and applied to
//! the `WidgetNode`.
//!
//! The four click-style handlers (`on_tap` / `on_double_tap` /
//! `on_triple_tap` / `on_long_press`) all receive a borrowed
//! [`crate::gesture::TapEvent`] (position + button + modifiers) and
//! default to [`crate::event::ButtonMask::PRIMARY`] acceptance. Widen
//! that filter via the matching `accept_*_buttons(...)` knob — see the
//! "Event System" section in `docs/events-and-gestures.md` for the
//! full contract and examples.

use teksilo_canvas::Point;

use crate::event::{ButtonMask, EventResponse, WidgetEvent};
use crate::event_handlers::EventHandlers;
use crate::gesture::{DragPhase, PinchPhase, SwipeDirection, TapEvent};
use crate::signal::Prop;
use crate::widget::{CursorIcon, EventContext, Widget};
use crate::widget_id::WidgetId;

// ---------------------------------------------------------------------------
// Accessibility overrides
// ---------------------------------------------------------------------------

/// Subtree visibility / merge mode applied by the accessibility tree walker.
///
/// Set via `WidgetBuilder::access_exclude_subtree()` /
/// `access_merge_subtree()`. The walker honors the mode after the parent
/// node has been emitted, before recursing into descendants.
#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
pub enum AccessSubtreeMode {
    /// Normal walk — descendants emitted as their own AT nodes.
    #[default]
    Inherit,
    /// Descendants pruned from the AT tree entirely. Parent node still
    /// emitted normally. Equivalent to Flutter's `excludeSemantics: true`.
    Exclude,
    /// Descendants' labels / descriptions / values / actions are
    /// concatenated into the parent's emitted node, then descendants are
    /// pruned. The parent reads as a single AT element. Equivalent to
    /// Flutter's `mergeAllDescendants: true` and SwiftUI's
    /// `.accessibilityElement(children: .combine)`.
    Merge,
}

/// Builder-level accessibility overrides.
///
/// Carried on `HandlerSet` during builder-chain construction, mirrored
/// onto `WidgetNode::access_overrides` at arena insertion (parallel to
/// `clips_children` / `cursor` / `focus_within_signal`), then applied by
/// the accessibility tree walker after the inner widget's
/// `accessibility(&self, builder)` runs.
///
/// User-visible string fields store a `Prop<String>` rather than a
/// resolved `String`, so they stay reactive to locale changes.
/// `teksilo-core` can't name `LocalizedString` (that lives in the
/// downstream `teksilo-i18n` crate), but `Prop<String>` is a core type
/// and `impl From<LocalizedString> for Prop<String>` in `teksilo-i18n`
/// yields a `Prop::Bound` over a locale-observing `Signal<String>`. So
/// `.access_label(tr!(save()))` stores a bound prop; the accessibility
/// walker reads `.get()` at AT-build time, and `sync_accessibility`
/// re-walks on locale change so the announced value follows the locale.
/// The `_literal` builder variants store `Prop::Static` and are the
/// `#[doc(hidden)]` grep markers for explicitly untranslated call sites
/// (the only literal path reachable from within `teksilo-core`).
#[derive(Default)]
pub struct AccessibilityOverrides {
    // -- Tier 1: labeling / state -----------------------------------------
    pub label: Option<Prop<String>>,
    pub description: Option<Prop<String>>,
    pub value: Option<Prop<String>>,
    pub role: Option<accesskit::Role>,
    /// Reactive hidden-from-AT flag. `Some(prop)` where the prop reads
    /// `true` hides the node from assistive technologies; `false` un-sets a
    /// hidden state the inner widget emitted unconditionally. Bound props are
    /// registered at `AccessibilityOnly` so the AT tree re-walks when they
    /// flip (see the insertion paths in `widget_tree.rs`).
    pub hidden: Option<Prop<bool>>,
    pub disabled: Option<bool>,

    // -- Tier 2: relationships / live / identity --------------------------
    pub identifier: Option<String>,
    pub controls: Vec<WidgetId>,
    pub described_by: Vec<WidgetId>,
    pub labelled_by: Vec<WidgetId>,
    pub live: Option<accesskit::Live>,
    pub aria_current: Option<accesskit::AriaCurrent>,
    /// Pre-formatted shortcut announcement string (e.g. `"Ctrl+S"`).
    /// Used by `access_shortcut_literal`. For chords routed through a
    /// `Shortcut` registration, prefer `access_shortcut_id` (stored
    /// in `shortcut_id`) so the announcement tracks rebinds.
    pub shortcut: Option<String>,
    /// Registered shortcut id (e.g. `"app.save"`). The accessibility
    /// walker resolves the current keystroke from
    /// `WidgetTree::shortcut_registry()` at AT-build time and writes
    /// the formatted string to `Node::keyboard_shortcut`. Refreshes
    /// automatically when the user rebinds (the registry's `version`
    /// signal triggers a re-sync).
    pub shortcut_id: Option<String>,
    pub has_popup: Option<accesskit::HasPopup>,
    pub orientation: Option<accesskit::Orientation>,

    // -- Tier 3: numeric / actions / escape hatch -------------------------
    pub numeric_value: Option<f64>,
    pub min_numeric_value: Option<f64>,
    pub max_numeric_value: Option<f64>,
    pub numeric_step: Option<f64>,

    /// Standard `accesskit::Action` advertisements with their handlers.
    /// Dispatched by `event_dispatch_impl.rs` when handling
    /// `WidgetEvent::AccessAction`, layered on top of any
    /// user-installed `on_access_action` / `on_access_action_request`
    /// handlers (both fire for the same dispatched event).
    pub actions: Vec<(accesskit::Action, Box<dyn FnMut(&mut EventContext)>)>,

    /// Actions to remove from the widget-emitted action list (called
    /// after the widget's `accessibility()` runs, before custom-action
    /// emission).
    pub removed_actions: Vec<accesskit::Action>,

    /// Custom-named actions (SwiftUI `.accessibilityAction(named:_:)`).
    /// Each entry pairs a (reactive) description prop with a handler.
    /// Index in the vec is the stable `i32` `CustomAction::id` exposed
    /// to AT software.
    pub custom_actions: Vec<(Prop<String>, Box<dyn FnMut(&mut EventContext)>)>,

    /// Final escape hatch — invoked **last** in `apply()` with full
    /// `&mut AccessNodeBuilder` access (including `inner_mut()`). Used
    /// for sub-node surgery (synthetic children) and for cases the
    /// typed surface doesn't cover.
    pub customize: Option<Box<dyn Fn(&mut crate::accessibility::AccessNodeBuilder)>>,
}

impl std::fmt::Debug for AccessibilityOverrides {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AccessibilityOverrides")
            .field("label", &self.label)
            .field("description", &self.description)
            .field("value", &self.value)
            .field("role", &self.role)
            .field("hidden", &self.hidden)
            .field("disabled", &self.disabled)
            .field("identifier", &self.identifier)
            .field("shortcut", &self.shortcut)
            .field("shortcut_id", &self.shortcut_id)
            .field("controls_len", &self.controls.len())
            .field("described_by_len", &self.described_by.len())
            .field("labelled_by_len", &self.labelled_by.len())
            .field("actions_len", &self.actions.len())
            .field("removed_actions", &self.removed_actions)
            .field("custom_actions_len", &self.custom_actions.len())
            .finish()
    }
}

impl AccessibilityOverrides {
    /// Apply the override scalar / list fields onto a builder. Called by
    /// the accessibility tree walker after the inner widget's
    /// `accessibility(&self, builder)` runs and before the framework
    /// finalizes the node.
    pub(crate) fn apply(&self, b: &mut crate::accessibility::AccessNodeBuilder) {
        use crate::accessibility::widget_id_to_node_id;

        if let Some(ref p) = self.label {
            b.set_name(p.get());
        }
        if let Some(ref p) = self.description {
            b.set_description(p.get());
        }
        if let Some(ref p) = self.value {
            b.set_value(p.get());
        }
        if let Some(role) = self.role {
            b.set_role(role);
        }
        match self.hidden.as_ref().map(|p| p.get()) {
            Some(true) => b.set_hidden(),
            Some(false) => b.clear_hidden(),
            None => {}
        }
        match self.disabled {
            Some(true) => b.set_disabled(),
            Some(false) => b.clear_disabled(),
            None => {}
        }
        if let Some(ref s) = self.identifier {
            b.set_author_id(s.clone());
        }
        for &id in &self.controls {
            b.push_controlled(widget_id_to_node_id(id));
        }
        for &id in &self.described_by {
            b.push_described_by(widget_id_to_node_id(id));
        }
        for &id in &self.labelled_by {
            b.push_labelled_by(widget_id_to_node_id(id));
        }
        if let Some(live) = self.live {
            b.set_live(live);
        }
        if let Some(c) = self.aria_current {
            b.set_aria_current(c);
        }
        if let Some(ref s) = self.shortcut {
            b.set_keyboard_shortcut(s.clone());
        }
        // `shortcut_id` resolution happens in the accessibility tree
        // walker (where the `ShortcutRegistry` is reachable) — see
        // `accessibility_impl::build_accessibility_recursive`.
        if let Some(p) = self.has_popup {
            b.set_has_popup(p);
        }
        if let Some(o) = self.orientation {
            b.set_orientation(o);
        }
        if let Some(v) = self.numeric_value {
            b.set_numeric_value(v);
        }
        if let Some(v) = self.min_numeric_value {
            b.set_min_numeric_value(v);
        }
        if let Some(v) = self.max_numeric_value {
            b.set_max_numeric_value(v);
        }
        if let Some(v) = self.numeric_step {
            b.set_numeric_value_step(v);
        }
        // Suppression first, then advertisement — so `access_remove_action`
        // can prune what the widget emitted, but a subsequent
        // `access_action(same_action, ...)` re-advertises with the
        // override-installed handler.
        for &a in &self.removed_actions {
            b.remove_action(a);
        }
        for (action, _) in &self.actions {
            b.add_action(*action);
        }
        if !self.custom_actions.is_empty() {
            let custom: Vec<accesskit::CustomAction> = self
                .custom_actions
                .iter()
                .enumerate()
                .map(|(i, (label, _))| accesskit::CustomAction {
                    id: i as i32,
                    description: label.get(),
                })
                .collect();
            b.set_custom_actions(custom);
        }
        if let Some(ref f) = self.customize {
            f(b);
        }
    }
}

// ---------------------------------------------------------------------------
// HandlerSet — temporary storage before arena insertion
// ---------------------------------------------------------------------------

/// Type alias for a context-menu content factory.
///
/// The factory is invoked on every right-click that lands on a widget
/// owning the factory (or on a descendant whose nearest ancestor with
/// a factory is this one). It receives:
///
/// - `position`: pointer position in widget-local coordinates of the
///   factory-owning widget. Useful when the menu's contents depend on
///   *what* was right-clicked (a row in a list, a node in a tree, an
///   item under a hit-test, …).
/// - `ctx`: a full [`EventContext`], so the factory can read window
///   state, query app state, send intents (e.g. for analytics), or
///   update Signals before the menu mounts.
///
/// The factory returns:
///
/// - `Some(widget)` to mount `widget` as the menu overlay anchored at
///   the factory-owning widget, placed at `position`.
/// - `None` to **decline this right-click**. The framework continues
///   walking up the parent chain looking for the next ancestor with a
///   factory. This lets a widget conditionally suppress its own menu
///   without uninstalling the factory.
pub type ContextMenuFactory = Box<dyn Fn(Point, &mut EventContext) -> Option<Box<dyn Widget>>>;

/// Temporary storage for handlers and metadata accumulated via builder
/// methods. Transferred to the `WidgetNode` during arena insertion.
pub struct HandlerSet {
    pub(crate) handlers: EventHandlers,
    pub(crate) focusable: Option<bool>,
    pub(crate) tab_index: Option<i32>,
    pub(crate) cursor: Option<CursorIcon>,
    pub(crate) clips_children: Option<bool>,
    /// When `Some(..)`, declares the node a text-input surface and the OS
    /// input method is enabled (with this purpose) while it is focused.
    /// `None` leaves the node default (no OS IME). The platform reads the
    /// focused node's descriptor at focus-change time. See [`crate::ime`].
    pub(crate) ime: Option<crate::ime::ImeContext>,
    /// When `Some(true)`, the widget node is invisible to pointer
    /// hit-testing — events fall through to whatever sits behind it.
    /// Used by the debug inspector's overlay widgets.
    pub(crate) event_pass_through: Option<bool>,
    /// When `Some(true)`, a press in this node's subtree must not arm a
    /// drag/swipe on any ancestor above it (a *gesture dead zone*). See
    /// [`super::arena::WidgetNode::gesture_dead_zone`].
    pub(crate) gesture_dead_zone: Option<bool>,
    /// When `Some(true)` and this node holds keyboard focus, a `KeyDown`
    /// bypasses shortcut resolution and is delivered straight to it (a
    /// *keyboard capture* surface — terminals, game viewports). See
    /// [`super::arena::WidgetNode::keyboard_capture`].
    pub(crate) keyboard_capture: Option<bool>,
    /// When `Some(true)`, this node and its WHOLE subtree are invisible
    /// to pointer hit-testing (decorative overlays — count badges,
    /// watermarks). See [`super::arena::WidgetNode::hit_transparent`].
    pub(crate) hit_transparent: Option<bool>,
    pub(crate) context_menu_factory: Option<ContextMenuFactory>,
    /// User-bound signal that the framework writes whenever the
    /// focused widget is a strict descendant of this node. See
    /// [`HandlerSet::focus_within`].
    pub(crate) focus_within: Option<crate::signal::Signal<bool>>,
    /// User-bound signal that the framework writes whenever the
    /// hovered widget is a strict descendant of this node. See
    /// [`HandlerSet::hover_within`].
    pub(crate) hover_within: Option<crate::signal::Signal<bool>>,
    /// User-bound visibility binding (`bool` / `Signal<bool>` / `Prop<bool>`).
    /// Applied at insertion via `WidgetTree::visible_when`, exactly like the
    /// `ctx.visible_when(id, ..)` form, so `teksu!` can write `visible_when: sig`
    /// as a plain widget property. See [`HandlerSet::visible_when`].
    pub(crate) visible_when: Option<Prop<bool>>,
    /// Builder-level accessibility overrides. Mirrored to
    /// `WidgetNode::access_overrides` at insertion. Action callbacks
    /// (`actions`, `custom_actions`) are dispatched by
    /// `event_dispatch_impl.rs` when handling
    /// `WidgetEvent::AccessAction`, in addition to the user's
    /// `on_access_action` / `on_access_action_request` handlers — so
    /// builder order doesn't matter.
    pub(crate) access: Option<Box<AccessibilityOverrides>>,
    /// Subtree visibility / merge mode. Mirrored to
    /// `WidgetNode::access_subtree`.
    pub(crate) access_subtree: Option<AccessSubtreeMode>,
}

impl HandlerSet {
    /// Create an empty handler set for use in `BuildContext::apply_self_handlers()`.
    pub fn new() -> Self {
        Self {
            handlers: EventHandlers::new(),
            focusable: None,
            tab_index: None,
            cursor: None,
            clips_children: None,
            ime: None,
            event_pass_through: None,
            gesture_dead_zone: None,
            keyboard_capture: None,
            hit_transparent: None,
            context_menu_factory: None,
            focus_within: None,
            hover_within: None,
            visible_when: None,
            access: None,
            access_subtree: None,
        }
    }

    /// Get a `&mut` to the override block, lazily allocating it on first
    /// access. Used by all `access_*` builder methods.
    pub(crate) fn access_mut(&mut self) -> &mut AccessibilityOverrides {
        self.access
            .get_or_insert_with(|| Box::new(AccessibilityOverrides::default()))
    }

    // -- Builder methods (mirror WidgetWithHandlers) --

    /// Set the on_tap handler. The closure receives a borrowed
    /// [`TapEvent`] carrying the position in
    /// widget-local coordinates, the finalising mouse button, and the
    /// modifier state at that moment.
    ///
    /// Default acceptance is [`ButtonMask::PRIMARY`] — left-click only.
    /// Use [`accept_tap_buttons`](Self::accept_tap_buttons) to widen
    /// the set if you need right-click, middle-click, or auxiliary
    /// buttons to fire this handler.
    pub fn on_tap(mut self, f: impl FnMut(&TapEvent, &mut EventContext) + 'static) -> Self {
        self.handlers.on_tap = Some(Box::new(f));
        self
    }

    /// Set the on_double_tap handler. See [`on_tap`](Self::on_tap) for
    /// the callback contract.
    pub fn on_double_tap(mut self, f: impl FnMut(&TapEvent, &mut EventContext) + 'static) -> Self {
        self.handlers.on_double_tap = Some(Box::new(f));
        self
    }

    /// Set the on_triple_tap handler — fires on the third click within the
    /// recognizer's window (same 300 ms / 10 px defaults as double tap).
    /// Runs independently of `on_double_tap` via cooperative gesture
    /// recognizers (`GestureRecognizer::resets_on_peer_recognition`).
    pub fn on_triple_tap(mut self, f: impl FnMut(&TapEvent, &mut EventContext) + 'static) -> Self {
        self.handlers.on_triple_tap = Some(Box::new(f));
        self
    }

    /// Set the on_long_press handler. The callback receives a borrowed
    /// [`TapEvent`] whose modifiers are
    /// captured from the held `Down` (since long-press recognises on a
    /// timer before any `Up`).
    pub fn on_long_press(mut self, f: impl FnMut(&TapEvent, &mut EventContext) + 'static) -> Self {
        self.handlers.on_long_press = Some(Box::new(f));
        self
    }

    /// Restrict (or extend) the set of pointer buttons that fire
    /// [`on_tap`](Self::on_tap). Default is [`ButtonMask::PRIMARY`]
    /// (left-click only). Pass `ButtonMask::ALL` or
    /// `ButtonMask::PRIMARY | ButtonMask::SECONDARY`, etc.
    pub fn accept_tap_buttons(mut self, mask: impl Into<ButtonMask>) -> Self {
        self.handlers.tap_buttons = Some(mask.into());
        self
    }

    /// Restrict (or extend) the set of pointer buttons that fire
    /// [`on_double_tap`](Self::on_double_tap). Default
    /// [`ButtonMask::PRIMARY`].
    pub fn accept_double_tap_buttons(mut self, mask: impl Into<ButtonMask>) -> Self {
        self.handlers.double_tap_buttons = Some(mask.into());
        self
    }

    /// Restrict (or extend) the set of pointer buttons that fire
    /// [`on_triple_tap`](Self::on_triple_tap). Default
    /// [`ButtonMask::PRIMARY`].
    pub fn accept_triple_tap_buttons(mut self, mask: impl Into<ButtonMask>) -> Self {
        self.handlers.triple_tap_buttons = Some(mask.into());
        self
    }

    /// Restrict (or extend) the set of pointer buttons that fire
    /// [`on_long_press`](Self::on_long_press). Default
    /// [`ButtonMask::PRIMARY`].
    pub fn accept_long_press_buttons(mut self, mask: impl Into<ButtonMask>) -> Self {
        self.handlers.long_press_buttons = Some(mask.into());
        self
    }

    /// Set the on_hover handler.
    pub fn on_hover(mut self, f: impl FnMut(bool, &mut EventContext) + 'static) -> Self {
        self.handlers.on_hover = Some(Box::new(f));
        self
    }

    /// Set the on_key handler.
    pub fn on_key(
        mut self,
        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
    ) -> Self {
        self.handlers.on_key = Some(Box::new(f));
        self
    }

    /// Set the strict-ancestor key preview handler. Fires on every
    /// ancestor of the focused widget (root → parent-of-target)
    /// before the focused widget's `on_key` runs. Return
    /// `EventResponse::Handled` to consume the event.
    pub fn on_key_preview(
        mut self,
        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
    ) -> Self {
        self.handlers.on_key_preview = Some(Box::new(f));
        self
    }

    /// Set the on_drag handler (gesture-based drag). The closure receives
    /// a [`DragPhase`] — `Started`, then zero or more `Moved`, then
    /// `Ended`.
    pub fn on_drag(mut self, f: impl FnMut(DragPhase, &mut EventContext) + 'static) -> Self {
        self.handlers.on_drag = Some(Box::new(f));
        self
    }

    /// Set the on_swipe handler. Fires once per swipe with the direction
    /// and velocity (pixels/second).
    pub fn on_swipe(
        mut self,
        f: impl FnMut(SwipeDirection, f32, &mut EventContext) + 'static,
    ) -> Self {
        self.handlers.on_swipe = Some(Box::new(f));
        self
    }

    /// Set the on_pinch handler. On desktop the phases are produced from
    /// OS trackpad gestures (winit `TouchpadMagnify` / `RotationGesture`).
    pub fn on_pinch(mut self, f: impl FnMut(PinchPhase, &mut EventContext) + 'static) -> Self {
        self.handlers.on_pinch = Some(Box::new(f));
        self
    }

    /// Set the on_focus handler. `f` is called with `true` on focus gain and
    /// `false` on focus loss.
    ///
    /// **WCAG 3.2.1 (On Focus).** Use this only to update *local* visual or
    /// reactive state. Do NOT open a window, navigate, submit, or otherwise
    /// change context from here: a context change triggered merely by a control
    /// receiving focus is a Success Criterion 3.2.1 failure — keyboard users
    /// tabbing through the UI would trigger it unexpectedly. (A debug-only guard
    /// warns if `ctx.open_window(...)` / `ctx.focus_window(...)` is called from
    /// inside focus dispatch.)
    pub fn on_focus(mut self, f: impl FnMut(bool, &mut EventContext) + 'static) -> Self {
        self.handlers.on_focus = Some(Box::new(f));
        self
    }

    /// Set the on_pointer_event handler (low-level escape hatch).
    pub fn on_pointer_event(
        mut self,
        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
    ) -> Self {
        self.handlers.on_pointer_event = Some(Box::new(f));
        self
    }

    /// Set the on_scroll handler.
    pub fn on_scroll(
        mut self,
        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
    ) -> Self {
        self.handlers.on_scroll = Some(Box::new(f));
        self
    }

    /// Set the on_access_action handler.
    pub fn on_access_action(
        mut self,
        f: impl FnMut(accesskit::Action, &mut EventContext) -> EventResponse + 'static,
    ) -> Self {
        self.handlers.on_access_action = Some(Box::new(f));
        self
    }

    /// Set the full AccessKit action-request handler. Receives the
    /// action, target NodeId (may be a synthetic widget-emitted
    /// child), and optional `ActionData` payload (e.g.
    /// `SetTextSelection(TextSelection)` or `Value(Box<str>)`).
    /// When this slot is set it's called INSTEAD of
    /// `on_access_action` for the same event.
    pub fn on_access_action_request(
        mut self,
        f: impl FnMut(
            accesskit::Action,
            accesskit::NodeId,
            Option<accesskit::ActionData>,
            &mut EventContext,
        ) -> EventResponse
        + 'static,
    ) -> Self {
        self.handlers.on_access_action_request = Some(Box::new(f));
        self
    }

    /// Set the focusable flag.
    pub fn focusable(mut self, focusable: bool) -> Self {
        self.focusable = Some(focusable);
        self
    }

    /// Set the cursor icon.
    pub fn cursor(mut self, cursor: CursorIcon) -> Self {
        self.cursor = Some(cursor);
        self
    }

    /// Set the clips_children flag.
    pub fn clips_children(mut self, clips: bool) -> Self {
        self.clips_children = Some(clips);
        self
    }

    /// Declare this node a text-input surface, enabling the OS input method
    /// (with `ctx`'s purpose) while it is focused. Leaving it unset (the
    /// default) means no OS IME. The platform reads the focused node's
    /// descriptor at focus-change time. See [`crate::ime`].
    pub fn ime_input(mut self, ctx: crate::ime::ImeContext) -> Self {
        self.ime = Some(ctx);
        self
    }

    /// Make the widget invisible to pointer hit-testing. With
    /// `pass_through = true`, pointer events traverse this node as if
    /// it were not there — useful for purely decorative overlays that
    /// must not absorb clicks (the debug inspector's `HighlightLayer`
    /// and `HoverProbe` use this).
    pub fn event_pass_through(mut self, pass_through: bool) -> Self {
        self.event_pass_through = Some(pass_through);
        self
    }

    /// Mark this widget's subtree a **gesture dead zone**: a pointer press
    /// inside it must not arm a drag/swipe recognizer on any ancestor above
    /// it. Use to let interactive controls (buttons, a `⋮` menu) sit inside a
    /// draggable / swipeable container (a dock-panel header, a card, a list
    /// row) without a few px of click jitter starting the ancestor's drag.
    /// The container's own drag still works everywhere else. Honored by
    /// `arm_drag_observers`; see the `DeadZone` wrapper widget.
    pub fn gesture_dead_zone(mut self, dead_zone: bool) -> Self {
        self.gesture_dead_zone = Some(dead_zone);
        self
    }

    /// Mark this widget a **keyboard capture** surface: while it holds
    /// focus, every `KeyDown` is delivered straight to its `on_key`
    /// handler, bypassing shortcut → intent → action resolution. Use for
    /// a terminal emulator that must forward `Ctrl+C` / `Ctrl+W` /
    /// `Alt+<letter>` to a child process instead of triggering the host
    /// app's shortcuts, a game viewport, or a modal text surface.
    ///
    /// # The escape contract
    ///
    /// **`Ctrl+Tab` / `Ctrl+Shift+Tab` are reserved and always move focus
    /// out.** The dispatcher cycles focus on that chord before the capture
    /// node is consulted, so a capture surface cannot become a keyboard trap
    /// (WCAG 2.1.2) however greedily its `on_key` behaves. Do not bind them.
    ///
    /// Nothing else is reserved. In particular Escape is **not**: overlay
    /// back-navigation runs first only while an overlay is actually open, so
    /// a focused capture surface with no overlay above it does receive
    /// Escape and may consume it. See
    /// [`super::arena::WidgetNode::keyboard_capture`].
    pub fn keyboard_capture(mut self, capture: bool) -> Self {
        self.keyboard_capture = Some(capture);
        self
    }

    /// Make this widget AND its whole subtree invisible to pointer
    /// hit-testing. Stronger than [`event_pass_through`](Self::event_pass_through):
    /// that one keeps descendants hittable, this one excludes them too.
    /// For purely decorative composite overlays (a count badge over a
    /// button, a watermark) whose own children would otherwise swallow
    /// the click meant for the control underneath.
    pub fn hit_transparent(mut self, transparent: bool) -> Self {
        self.hit_transparent = Some(transparent);
        self
    }

    /// Bind a user-owned `Signal<bool>` that the framework will set
    /// to `true` whenever the focused widget is a *strict descendant*
    /// of this node, and `false` otherwise. Useful for unified focus
    /// halos around composite widgets (a chat composer that highlights
    /// when its `RichTextEditor` or "Send" button is focused, a
    /// `Panel` wrapping a `SpinBox`, etc).
    ///
    /// Strict-ancestors only — a widget that *is* itself focused does
    /// not also see its own `focus_within` signal flipped to `true`.
    /// Combine with `on_focus` if you want both behaviours.
    pub fn focus_within(mut self, signal: crate::signal::Signal<bool>) -> Self {
        self.focus_within = Some(signal);
        self
    }

    /// Bind a user-owned `Signal<bool>` that the framework will set
    /// to `true` whenever the hovered widget is a *strict descendant*
    /// of this node. Symmetric to [`focus_within`](Self::focus_within).
    pub fn hover_within(mut self, signal: crate::signal::Signal<bool>) -> Self {
        self.hover_within = Some(signal);
        self
    }

    /// Bind this node's visibility to a `bool` / `Signal<bool>` / `Prop<bool>`.
    /// A bound value shows/hides the node reactively (registered at
    /// `Relayout`). Equivalent to `ctx.visible_when(id, ..)`; exposed as a
    /// builder method so `teksu!` can write `visible_when: sig` as a property.
    pub fn visible_when(mut self, state: impl Into<Prop<bool>>) -> Self {
        self.visible_when = Some(state.into());
        self
    }

    /// Set a context-menu factory. See [`ContextMenuFactory`] for the
    /// full contract: the closure receives the click position
    /// (widget-local) and a full [`EventContext`], and returns
    /// `Some(menu)` to mount or `None` to decline (falling through to
    /// the nearest ancestor with a factory).
    pub fn context_menu(
        mut self,
        factory: impl Fn(Point, &mut EventContext) -> Option<Box<dyn Widget>> + 'static,
    ) -> Self {
        self.context_menu_factory = Some(Box::new(factory));
        self
    }

    /// Set the drag hover handler. Called when a drag payload hovers over this widget.
    /// Return `DropFeedback` to indicate acceptance and visual feedback.
    pub fn on_drag_hover(
        mut self,
        f: impl FnMut(
            &crate::drag_payload::DragPayload,
            teksilo_canvas::Point,
            &mut EventContext,
        ) -> crate::drag_state::DropFeedback
        + 'static,
    ) -> Self {
        self.handlers.on_drag_hover = Some(Box::new(f));
        self
    }

    /// Set the drag-leave handler. Fires when a drag that was over this
    /// widget moves to another target, completes (drop on any target), or
    /// is cancelled. Widgets that stash transient feedback state in
    /// `on_drag_hover` must clear it here.
    pub fn on_drag_leave(mut self, f: impl FnMut(&mut EventContext) + 'static) -> Self {
        self.handlers.on_drag_leave = Some(Box::new(f));
        self
    }

    /// Set the per-frame drag-tick handler. Fires once per frame while a
    /// drag is active and this widget is the current drop target. The
    /// closure receives the current pointer position in widget-local
    /// coordinates. Use for behaviours that must keep running even when
    /// the pointer is stationary — viewport-edge auto-scroll and
    /// spring-loaded folders.
    pub fn on_drag_tick(
        mut self,
        f: impl FnMut(teksilo_canvas::Point, &mut EventContext) + 'static,
    ) -> Self {
        self.handlers.on_drag_tick = Some(Box::new(f));
        self
    }

    /// Set the drop handler. Called when a payload is dropped on this widget.
    /// Return `true` if the drop was accepted.
    pub fn on_drop(
        mut self,
        f: impl FnMut(
            crate::drag_payload::DragPayload,
            teksilo_canvas::Point,
            &mut EventContext,
        ) -> bool
        + 'static,
    ) -> Self {
        self.handlers.on_drop = Some(Box::new(f));
        self
    }

    /// Set the drag-ended handler on a drag **source**. Fires when a drag
    /// this widget started ends — dropped on an in-app target, exported to
    /// another application via the OS (copy / move), or cancelled. Use it to
    /// react to the outcome, e.g. remove the dragged item on a
    /// [`DropOutcome::OsMove`](crate::drag_payload::DropOutcome::OsMove).
    pub fn on_drag_ended(
        mut self,
        f: impl FnMut(crate::drag_payload::DropOutcome, &mut EventContext) + 'static,
    ) -> Self {
        self.handlers.on_drag_ended = Some(Box::new(f));
        self
    }
}

impl Default for HandlerSet {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for HandlerSet {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HandlerSet")
            .field("handlers", &self.handlers)
            .field("focusable", &self.focusable)
            .field("tab_index", &self.tab_index)
            .field("cursor", &self.cursor)
            .finish()
    }
}

// ---------------------------------------------------------------------------
// WidgetWithHandlers<W> — wrapper storing widget + accumulated handlers
// ---------------------------------------------------------------------------

/// A widget wrapped with attached event handlers and framework metadata.
/// Created by calling builder methods from `WidgetBuilder` on any widget.
pub struct WidgetWithHandlers<W: Widget> {
    pub(crate) widget: W,
    pub(crate) handler_set: HandlerSet,
}

impl<W: Widget> WidgetWithHandlers<W> {
    fn new(widget: W) -> Self {
        Self {
            widget,
            handler_set: HandlerSet::new(),
        }
    }

    /// Take the handler set out, leaving defaults.
    pub(crate) fn take_handler_set(&mut self) -> HandlerSet {
        std::mem::take(&mut self.handler_set)
    }

    // -- Gesture handlers --

    pub fn on_tap(mut self, f: impl FnMut(&TapEvent, &mut EventContext) + 'static) -> Self {
        self.handler_set.handlers.on_tap = Some(Box::new(f));
        self
    }

    pub fn on_double_tap(mut self, f: impl FnMut(&TapEvent, &mut EventContext) + 'static) -> Self {
        self.handler_set.handlers.on_double_tap = Some(Box::new(f));
        self
    }

    pub fn on_triple_tap(mut self, f: impl FnMut(&TapEvent, &mut EventContext) + 'static) -> Self {
        self.handler_set.handlers.on_triple_tap = Some(Box::new(f));
        self
    }

    pub fn on_long_press(mut self, f: impl FnMut(&TapEvent, &mut EventContext) + 'static) -> Self {
        self.handler_set.handlers.on_long_press = Some(Box::new(f));
        self
    }

    /// Restrict (or extend) the set of pointer buttons that fire
    /// `on_tap`. Default is [`ButtonMask::PRIMARY`].
    pub fn accept_tap_buttons(mut self, mask: impl Into<ButtonMask>) -> Self {
        self.handler_set.handlers.tap_buttons = Some(mask.into());
        self
    }

    /// Restrict (or extend) the set of pointer buttons that fire
    /// `on_double_tap`. Default [`ButtonMask::PRIMARY`].
    pub fn accept_double_tap_buttons(mut self, mask: impl Into<ButtonMask>) -> Self {
        self.handler_set.handlers.double_tap_buttons = Some(mask.into());
        self
    }

    /// Restrict (or extend) the set of pointer buttons that fire
    /// `on_triple_tap`. Default [`ButtonMask::PRIMARY`].
    pub fn accept_triple_tap_buttons(mut self, mask: impl Into<ButtonMask>) -> Self {
        self.handler_set.handlers.triple_tap_buttons = Some(mask.into());
        self
    }

    /// Restrict (or extend) the set of pointer buttons that fire
    /// `on_long_press`. Default [`ButtonMask::PRIMARY`].
    pub fn accept_long_press_buttons(mut self, mask: impl Into<ButtonMask>) -> Self {
        self.handler_set.handlers.long_press_buttons = Some(mask.into());
        self
    }

    pub fn on_drag(mut self, f: impl FnMut(DragPhase, &mut EventContext) + 'static) -> Self {
        self.handler_set.handlers.on_drag = Some(Box::new(f));
        self
    }

    pub fn on_swipe(
        mut self,
        f: impl FnMut(SwipeDirection, f32, &mut EventContext) + 'static,
    ) -> Self {
        self.handler_set.handlers.on_swipe = Some(Box::new(f));
        self
    }

    pub fn on_pinch(mut self, f: impl FnMut(PinchPhase, &mut EventContext) + 'static) -> Self {
        self.handler_set.handlers.on_pinch = Some(Box::new(f));
        self
    }

    // -- Focus and keyboard --

    pub fn on_focus(mut self, f: impl FnMut(bool, &mut EventContext) + 'static) -> Self {
        self.handler_set.handlers.on_focus = Some(Box::new(f));
        self
    }

    pub fn on_key(
        mut self,
        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
    ) -> Self {
        self.handler_set.handlers.on_key = Some(Box::new(f));
        self
    }

    /// Set the strict-ancestor key preview handler. See
    /// [`HandlerSet::on_key_preview`].
    pub fn on_key_preview(
        mut self,
        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
    ) -> Self {
        self.handler_set.handlers.on_key_preview = Some(Box::new(f));
        self
    }

    pub fn focusable(mut self, focusable: bool) -> Self {
        self.handler_set.focusable = Some(focusable);
        self
    }

    pub fn tab_index(mut self, index: i32) -> Self {
        self.handler_set.tab_index = Some(index);
        self
    }

    // -- Pointer (low-level escape hatch) --

    pub fn on_pointer_event(
        mut self,
        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
    ) -> Self {
        self.handler_set.handlers.on_pointer_event = Some(Box::new(f));
        self
    }

    pub fn on_hover(mut self, f: impl FnMut(bool, &mut EventContext) + 'static) -> Self {
        self.handler_set.handlers.on_hover = Some(Box::new(f));
        self
    }

    pub fn cursor(mut self, cursor: CursorIcon) -> Self {
        self.handler_set.cursor = Some(cursor);
        self
    }

    // -- Scroll --

    pub fn on_scroll(
        mut self,
        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
    ) -> Self {
        self.handler_set.handlers.on_scroll = Some(Box::new(f));
        self
    }

    // -- Accessibility actions --

    pub fn on_access_action(
        mut self,
        f: impl FnMut(accesskit::Action, &mut EventContext) -> EventResponse + 'static,
    ) -> Self {
        self.handler_set.handlers.on_access_action = Some(Box::new(f));
        self
    }

    pub fn on_access_action_request(
        mut self,
        f: impl FnMut(
            accesskit::Action,
            accesskit::NodeId,
            Option<accesskit::ActionData>,
            &mut EventContext,
        ) -> EventResponse
        + 'static,
    ) -> Self {
        self.handler_set.handlers.on_access_action_request = Some(Box::new(f));
        self
    }

    // -- Framework-level properties --

    pub fn clips_children(mut self, clips: bool) -> Self {
        self.handler_set.clips_children = Some(clips);
        self
    }

    /// Declare this node a text-input surface, enabling the OS input method
    /// (with `ctx`'s purpose) while it is focused. See [`crate::ime`].
    pub fn ime_input(mut self, ctx: crate::ime::ImeContext) -> Self {
        self.handler_set.ime = Some(ctx);
        self
    }

    /// Make the widget invisible to pointer hit-testing. See
    /// [`HandlerSet::event_pass_through`].
    pub fn event_pass_through(mut self, pass_through: bool) -> Self {
        self.handler_set.event_pass_through = Some(pass_through);
        self
    }

    /// Mark this widget's subtree a gesture dead zone. See
    /// [`HandlerSet::gesture_dead_zone`].
    pub fn gesture_dead_zone(mut self, dead_zone: bool) -> Self {
        self.handler_set.gesture_dead_zone = Some(dead_zone);
        self
    }

    /// Mark this widget a keyboard capture surface: while focused, every
    /// `KeyDown` bypasses shortcut resolution and reaches its `on_key`
    /// handler (terminals, game viewports). See
    /// [`HandlerSet::keyboard_capture`].
    pub fn keyboard_capture(mut self, capture: bool) -> Self {
        self.handler_set.keyboard_capture = Some(capture);
        self
    }

    /// Make this widget and its whole subtree invisible to pointer
    /// hit-testing. See [`HandlerSet::hit_transparent`].
    pub fn hit_transparent(mut self, transparent: bool) -> Self {
        self.handler_set.hit_transparent = Some(transparent);
        self
    }

    /// Set a context-menu factory. See
    /// [`HandlerSet::context_menu`] for the full contract.
    pub fn context_menu(
        mut self,
        factory: impl Fn(Point, &mut EventContext) -> Option<Box<dyn Widget>> + 'static,
    ) -> Self {
        self.handler_set.context_menu_factory = Some(Box::new(factory));
        self
    }

    /// Bind a `Signal<bool>` the framework writes when a strict
    /// descendant has focus. See [`HandlerSet::focus_within`].
    pub fn focus_within(mut self, signal: crate::signal::Signal<bool>) -> Self {
        self.handler_set.focus_within = Some(signal);
        self
    }

    /// Bind a `Signal<bool>` the framework writes when a strict
    /// descendant is hovered. See [`HandlerSet::hover_within`].
    pub fn hover_within(mut self, signal: crate::signal::Signal<bool>) -> Self {
        self.handler_set.hover_within = Some(signal);
        self
    }

    /// Bind this node's visibility. See [`HandlerSet::visible_when`].
    pub fn visible_when(mut self, state: impl Into<Prop<bool>>) -> Self {
        self.handler_set.visible_when = Some(state.into());
        self
    }

    /// Set the drag hover handler. Called when a drag payload hovers over this widget.
    pub fn on_drag_hover(
        mut self,
        f: impl FnMut(
            &crate::drag_payload::DragPayload,
            teksilo_canvas::Point,
            &mut EventContext,
        ) -> crate::drag_state::DropFeedback
        + 'static,
    ) -> Self {
        self.handler_set.handlers.on_drag_hover = Some(Box::new(f));
        self
    }

    /// Set the drag-leave handler. See [`HandlerSet::on_drag_leave`].
    pub fn on_drag_leave(mut self, f: impl FnMut(&mut EventContext) + 'static) -> Self {
        self.handler_set.handlers.on_drag_leave = Some(Box::new(f));
        self
    }

    /// Set the per-frame drag-tick handler. See [`HandlerSet::on_drag_tick`].
    pub fn on_drag_tick(
        mut self,
        f: impl FnMut(teksilo_canvas::Point, &mut EventContext) + 'static,
    ) -> Self {
        self.handler_set.handlers.on_drag_tick = Some(Box::new(f));
        self
    }

    /// Set the drop handler. Called when a payload is dropped on this widget.
    pub fn on_drop(
        mut self,
        f: impl FnMut(
            crate::drag_payload::DragPayload,
            teksilo_canvas::Point,
            &mut EventContext,
        ) -> bool
        + 'static,
    ) -> Self {
        self.handler_set.handlers.on_drop = Some(Box::new(f));
        self
    }

    /// Set the drag-ended handler on a drag source. See
    /// [`HandlerSet::on_drag_ended`].
    pub fn on_drag_ended(
        mut self,
        f: impl FnMut(crate::drag_payload::DropOutcome, &mut EventContext) + 'static,
    ) -> Self {
        self.handler_set.handlers.on_drag_ended = Some(Box::new(f));
        self
    }

    // ── Accessibility overrides ────────────────────────────────────────
    //
    // The user-visible string methods take `impl Into<Prop<String>>` so
    // they stay reactive. With the `i18n` feature, `LocalizedString`
    // (produced by `tr!(...)`) provides `From<LocalizedString> for
    // Prop<String>`, which yields a locale-observing `Prop::Bound`, so
    // `.access_label(tr!(save()))` follows the locale. A bare `&str`
    // does NOT convert to `Prop<String>`, so untranslated literals must
    // go through `lit!(...)` (downstream crates) or the `_literal`
    // twins (which store `Prop::Static` — the only literal path
    // reachable from within `teksilo-core`).

    /// Override the accessibility label (`Node::label`) of this widget.
    /// Replaces whatever the inner widget emitted via `set_name`.
    ///
    /// Accepts any `impl Into<Prop<String>>`. With the `i18n` feature,
    /// `LocalizedString` (produced by `tr!(...)`)
    /// implements `From<LocalizedString> for Prop<String>`, so
    /// `.access_label(tr!(save()))` stays reactive — the announced
    /// value re-resolves on locale change (the accessibility tree
    /// re-walks via `sync_accessibility`).
    pub fn access_label(mut self, label: impl Into<Prop<String>>) -> Self {
        self.handler_set.access_mut().label = Some(label.into());
        self
    }

    /// `#[doc(hidden)]` grep marker for explicitly-untranslated label
    /// strings — the same convention as `Button::new_literal`. Stores a
    /// `Prop::Static`. The distinct name makes untranslated call sites
    /// greppable as a one-pass audit, and it's the literal path
    /// reachable from within `teksilo-core` (where `lit!` isn't usable).
    #[doc(hidden)]
    pub fn access_label_literal(self, label: impl Into<String>) -> Self {
        self.access_label(Prop::Static(label.into()))
    }

    /// Override the accessibility description (`Node::description`).
    /// Same conversion rules as `access_label`.
    pub fn access_description(mut self, description: impl Into<Prop<String>>) -> Self {
        self.handler_set.access_mut().description = Some(description.into());
        self
    }

    #[doc(hidden)]
    pub fn access_description_literal(self, description: impl Into<String>) -> Self {
        self.access_description(Prop::Static(description.into()))
    }

    /// Long-form context hint. Alias of `access_description` —
    /// AccessKit has no separate hint slot (SwiftUI's split is
    /// VoiceOver-specific). Provided for SwiftUI parity.
    pub fn access_hint(self, hint: impl Into<Prop<String>>) -> Self {
        self.access_description(hint)
    }

    #[doc(hidden)]
    pub fn access_hint_literal(self, hint: impl Into<String>) -> Self {
        self.access_description(Prop::Static(hint.into()))
    }

    /// Override the accessibility value (`Node::value`).
    /// Same conversion rules as `access_label`.
    pub fn access_value(mut self, value: impl Into<Prop<String>>) -> Self {
        self.handler_set.access_mut().value = Some(value.into());
        self
    }

    #[doc(hidden)]
    pub fn access_value_literal(self, value: impl Into<String>) -> Self {
        self.access_value(Prop::Static(value.into()))
    }

    /// Override the accessibility role.
    pub fn access_role(mut self, role: accesskit::Role) -> Self {
        self.handler_set.access_mut().role = Some(role);
        self
    }

    /// Hide (or un-hide) this node from assistive technologies. Accepts a
    /// plain `bool`, a `Signal<bool>`, or a `Prop<bool>`: a bound value makes
    /// the node appear/disappear from the AT tree reactively (the binding is
    /// registered at `AccessibilityOnly`, so the tree re-walks on change).
    /// `false` un-sets a hidden state the inner widget may have emitted
    /// unconditionally (e.g. `Panel::a11y_presentational`).
    pub fn access_hidden(mut self, hidden: impl Into<Prop<bool>>) -> Self {
        self.handler_set.access_mut().hidden = Some(hidden.into());
        self
    }

    /// Mark (or un-mark) this widget as disabled for AT. `false`
    /// clears both widget-emitted disabled state AND the framework's
    /// arena-driven disabled gate at
    /// `accessibility_impl::build_accessibility_recursive`.
    pub fn access_disabled(mut self, disabled: bool) -> Self {
        self.handler_set.access_mut().disabled = Some(disabled);
        self
    }

    /// Stable test/debug identifier (`Node::author_id`). Not
    /// user-visible — used by accessibility inspectors and UI tests.
    pub fn access_identifier(mut self, id: impl Into<String>) -> Self {
        self.handler_set.access_mut().identifier = Some(id.into());
        self
    }

    /// Append a `controls` relationship. The target widget's NodeId
    /// is included in this node's `aria-controls`-equivalent list.
    pub fn access_controls(mut self, target: WidgetId) -> Self {
        self.handler_set.access_mut().controls.push(target);
        self
    }

    /// Append a `described_by` relationship.
    pub fn access_described_by(mut self, target: WidgetId) -> Self {
        self.handler_set.access_mut().described_by.push(target);
        self
    }

    /// Append a `labelled_by` relationship.
    pub fn access_labelled_by(mut self, target: WidgetId) -> Self {
        self.handler_set.access_mut().labelled_by.push(target);
        self
    }

    /// Set the live-region politeness (`Node::live`).
    pub fn access_live(mut self, mode: accesskit::Live) -> Self {
        self.handler_set.access_mut().live = Some(mode);
        self
    }

    /// Mark this node as the current item within its container
    /// (`aria-current`).
    pub fn access_current(mut self, current: accesskit::AriaCurrent) -> Self {
        self.handler_set.access_mut().aria_current = Some(current);
        self
    }

    /// Pre-formatted shortcut announcement (e.g. `"Ctrl+S"`). Used for
    /// chords NOT routed through the `Shortcut` system — platform-native
    /// keys, app-internal hotkeys not exposed to user rebinding. For
    /// `Shortcut`-registered chords prefer
    /// [`access_shortcut_id`](Self::access_shortcut_id), which tracks
    /// rebinds automatically.
    pub fn access_shortcut_literal(mut self, shortcut: impl Into<String>) -> Self {
        self.handler_set.access_mut().shortcut = Some(shortcut.into());
        self
    }

    /// Bind the announced shortcut to a registered `Shortcut` id (the
    /// same id you pass to `Shortcut::new("app.save")`). The
    /// accessibility tree walker resolves the current keystroke from
    /// `WidgetTree::shortcut_registry()` at AT-build time, formats it
    /// via `KeyStroke::Display` (`"Ctrl+S"`), and writes it to
    /// `Node::keyboard_shortcut`. Auto-refreshes on rebind.
    ///
    /// If the registry has no entry for `id` (no widget registered the
    /// shortcut yet), the announcement is omitted — same fallback as
    /// `MenuItem::for_shortcut(...)`.
    pub fn access_shortcut_id(mut self, id: impl Into<String>) -> Self {
        self.handler_set.access_mut().shortcut_id = Some(id.into());
        self
    }

    /// Indicate that activating this widget pops up a menu / listbox /
    /// dialog (`aria-haspopup`).
    pub fn access_has_popup(mut self, kind: accesskit::HasPopup) -> Self {
        self.handler_set.access_mut().has_popup = Some(kind);
        self
    }

    /// Override orientation (`Node::orientation`) — used on sliders,
    /// scrollbars, separators.
    pub fn access_orientation(mut self, orientation: accesskit::Orientation) -> Self {
        self.handler_set.access_mut().orientation = Some(orientation);
        self
    }

    /// Prune all descendants from the accessibility tree. The widget's
    /// own AT node is still emitted; only children disappear. Use for
    /// purely decorative composites. Flutter's `excludeSemantics: true`.
    pub fn access_exclude_subtree(mut self) -> Self {
        self.handler_set.access_subtree = Some(AccessSubtreeMode::Exclude);
        self
    }

    /// Lift descendants' labels / descriptions / values / actions into
    /// this widget's AT node, then prune the descendants. The whole
    /// composite reads as a single AT element. Flutter's
    /// `mergeAllDescendants: true` and SwiftUI's
    /// `.accessibilityElement(children: .combine)`.
    pub fn access_merge_subtree(mut self) -> Self {
        self.handler_set.access_subtree = Some(AccessSubtreeMode::Merge);
        self
    }

    /// Set an explicit subtree mode.
    pub fn access_subtree(mut self, mode: AccessSubtreeMode) -> Self {
        self.handler_set.access_subtree = Some(mode);
        self
    }

    /// Override `Node::numeric_value`.
    pub fn access_numeric_value(mut self, value: f64) -> Self {
        self.handler_set.access_mut().numeric_value = Some(value);
        self
    }

    /// Override `Node::min_numeric_value` and `max_numeric_value`.
    pub fn access_numeric_range(mut self, min: f64, max: f64) -> Self {
        let access = self.handler_set.access_mut();
        access.min_numeric_value = Some(min);
        access.max_numeric_value = Some(max);
        self
    }

    /// Override `Node::numeric_value_step`.
    pub fn access_numeric_step(mut self, step: f64) -> Self {
        self.handler_set.access_mut().numeric_step = Some(step);
        self
    }

    /// Advertise an accessibility action and the callback that fires
    /// when AT software invokes it. Multiple `access_action` calls
    /// register separate callbacks for distinct actions; calling twice
    /// with the same action records both — they fire in order.
    pub fn access_action<F>(mut self, action: accesskit::Action, handler: F) -> Self
    where
        F: FnMut(&mut EventContext) + 'static,
    {
        self.handler_set
            .access_mut()
            .actions
            .push((action, Box::new(handler)));
        self
    }

    /// Suppress an action the inner widget emitted (e.g. neutralize
    /// `Action::Click` on a Button used purely as a layout shim).
    /// Applied after the widget's `accessibility()` runs but before
    /// override-advertised actions, so a subsequent `access_action`
    /// for the same action re-advertises it with the override-installed
    /// callback.
    pub fn access_remove_action(mut self, action: accesskit::Action) -> Self {
        self.handler_set.access_mut().removed_actions.push(action);
        self
    }

    /// Advertise a custom-named action (SwiftUI parity:
    /// `.accessibilityAction(named:_:)`). The label is exposed
    /// verbatim by AT software (e.g. VoiceOver's Actions rotor).
    /// Accepts `tr!(...)` via `From<LocalizedString> for Prop<String>`
    /// in `teksilo-i18n`, so the announced name follows the locale.
    pub fn access_custom_action<F>(mut self, label: impl Into<Prop<String>>, handler: F) -> Self
    where
        F: FnMut(&mut EventContext) + 'static,
    {
        self.handler_set
            .access_mut()
            .custom_actions
            .push((label.into(), Box::new(handler)));
        self
    }

    #[doc(hidden)]
    pub fn access_custom_action_literal<F>(self, label: impl Into<String>, handler: F) -> Self
    where
        F: FnMut(&mut EventContext) + 'static,
    {
        self.access_custom_action(Prop::Static(label.into()), handler)
    }

    /// Final escape hatch — invoked after all typed override setters,
    /// with full `&mut AccessNodeBuilder` access (including
    /// `inner_mut()`). Use for synthetic-child surgery (rich text
    /// paragraphs, text runs) or any AccessKit field the typed
    /// surface doesn't cover.
    pub fn access_customize<F>(mut self, f: F) -> Self
    where
        F: Fn(&mut crate::accessibility::AccessNodeBuilder) + 'static,
    {
        self.handler_set.access_mut().customize = Some(Box::new(f));
        self
    }
}

// Delegate all Widget trait methods to the inner widget.
impl<W: Widget> std::fmt::Debug for WidgetWithHandlers<W> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("WidgetWithHandlers")
            .field("widget", &self.widget)
            .field("handler_set", &self.handler_set)
            .finish()
    }
}

impl<W: Widget + 'static> Widget for WidgetWithHandlers<W> {
    fn build(
        &mut self,
        ctx: &mut crate::build_context::BuildContext,
    ) -> Vec<crate::widget_id::WidgetId> {
        self.widget.build(ctx)
    }

    fn layout_response(
        &self,
        proposal: teksilo_canvas::SizeProposal,
        ctx: &crate::widget::LayoutContext,
    ) -> crate::widget::LayoutResponse {
        self.widget.layout_response(proposal, ctx)
    }

    fn place_children(
        &self,
        bounds: teksilo_canvas::Rect,
        proposal: teksilo_canvas::SizeProposal,
        children: &mut [crate::widget::WidgetPlacement],
        ctx: &crate::widget::LayoutContext,
    ) {
        self.widget.place_children(bounds, proposal, children, ctx)
    }

    fn paint(
        &self,
        bounds: teksilo_canvas::Rect,
        canvas: &mut teksilo_canvas::Canvas,
        ctx: &crate::widget::PaintContext,
    ) {
        self.widget.paint(bounds, canvas, ctx)
    }

    fn accessibility(&self, builder: &mut crate::accessibility::AccessNodeBuilder) {
        self.widget.accessibility(builder)
    }

    fn children(&self) -> Vec<crate::widget_id::WidgetId> {
        self.widget.children()
    }

    fn as_any(&self) -> Option<&dyn std::any::Any> {
        self.widget.as_any()
    }

    /// Mutable counterpart of [`as_any`](Widget::as_any), forwarded for the
    /// same reason it is.
    ///
    /// A composing container that reads a child's concrete type must see the
    /// same widget whether or not a builder method wrapped it. `MenuList` reads
    /// a `MenuItem` this way for its mnemonic, its type-ahead label, its radio
    /// group and its safe-triangle state; without this forward,
    /// `MenuItem::new(..).context_menu(..)` silently stops being a `MenuItem`
    /// to its parent — no error, just a row that lost all four.
    fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
        self.widget.as_any_mut()
    }

    fn clips_children(&self) -> bool {
        self.handler_set
            .clips_children
            .unwrap_or_else(|| self.widget.clips_children())
    }

    fn take_handler_set(&mut self) -> Option<HandlerSet> {
        Some(self.take_handler_set())
    }
}

// ---------------------------------------------------------------------------
// WidgetBuilder trait — the entry point
// ---------------------------------------------------------------------------

/// Blanket trait providing attached handler methods for all Widget types.
/// The first builder method call wraps the widget in `WidgetWithHandlers`.
pub trait WidgetBuilder: Widget + Sized + 'static {
    fn on_tap(
        self,
        f: impl FnMut(&TapEvent, &mut EventContext) + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_tap(f)
    }

    fn on_double_tap(
        self,
        f: impl FnMut(&TapEvent, &mut EventContext) + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_double_tap(f)
    }

    fn on_triple_tap(
        self,
        f: impl FnMut(&TapEvent, &mut EventContext) + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_triple_tap(f)
    }

    fn on_long_press(
        self,
        f: impl FnMut(&TapEvent, &mut EventContext) + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_long_press(f)
    }

    /// Restrict (or extend) the set of pointer buttons that fire
    /// `on_tap`. Default is [`ButtonMask::PRIMARY`].
    fn accept_tap_buttons(self, mask: impl Into<ButtonMask>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).accept_tap_buttons(mask)
    }

    /// Restrict (or extend) the set of pointer buttons that fire
    /// `on_double_tap`. Default [`ButtonMask::PRIMARY`].
    fn accept_double_tap_buttons(self, mask: impl Into<ButtonMask>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).accept_double_tap_buttons(mask)
    }

    /// Restrict (or extend) the set of pointer buttons that fire
    /// `on_triple_tap`. Default [`ButtonMask::PRIMARY`].
    fn accept_triple_tap_buttons(self, mask: impl Into<ButtonMask>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).accept_triple_tap_buttons(mask)
    }

    /// Restrict (or extend) the set of pointer buttons that fire
    /// `on_long_press`. Default [`ButtonMask::PRIMARY`].
    fn accept_long_press_buttons(self, mask: impl Into<ButtonMask>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).accept_long_press_buttons(mask)
    }

    /// Dim this widget's subtree to `factor` opacity whenever the host window
    /// is **inactive** (not focused / occluded), restoring full opacity when it
    /// becomes active again. The opt-in, per-widget layer of the window-active
    /// appearance model — for custom content an app wants to fade back when its
    /// window isn't the active one. Stock widgets handle their own
    /// inactive appearance (caret hiding, selection desaturation) and need no
    /// wrapping. Layout- and a11y-transparent; the opacity snaps (no tween),
    /// which is correct under `prefers-reduced-motion`. See
    /// [`DimWhenInactive`](crate::dim_when_inactive::DimWhenInactive).
    fn dim_when_inactive(self, factor: f32) -> crate::dim_when_inactive::DimWhenInactive {
        crate::dim_when_inactive::DimWhenInactive::new()
            .child(self)
            .factor(factor)
    }

    /// [`dim_when_inactive`](Self::dim_when_inactive) with the default factor
    /// ([`DEFAULT_DIM_FACTOR`](crate::dim_when_inactive::DEFAULT_DIM_FACTOR), 70 %).
    fn dim_when_inactive_default(self) -> crate::dim_when_inactive::DimWhenInactive {
        crate::dim_when_inactive::DimWhenInactive::new().child(self)
    }

    fn on_drag(
        self,
        f: impl FnMut(DragPhase, &mut EventContext) + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_drag(f)
    }

    fn on_swipe(
        self,
        f: impl FnMut(SwipeDirection, f32, &mut EventContext) + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_swipe(f)
    }

    fn on_pinch(
        self,
        f: impl FnMut(PinchPhase, &mut EventContext) + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_pinch(f)
    }

    fn on_focus(
        self,
        f: impl FnMut(bool, &mut EventContext) + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_focus(f)
    }

    fn on_key(
        self,
        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_key(f)
    }

    /// Strict-ancestor key preview. See [`HandlerSet::on_key_preview`].
    fn on_key_preview(
        self,
        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_key_preview(f)
    }

    fn on_pointer_event(
        self,
        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_pointer_event(f)
    }

    fn on_hover(
        self,
        f: impl FnMut(bool, &mut EventContext) + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_hover(f)
    }

    fn on_scroll(
        self,
        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_scroll(f)
    }

    fn on_access_action(
        self,
        f: impl FnMut(accesskit::Action, &mut EventContext) -> EventResponse + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_access_action(f)
    }

    fn focusable(self, focusable: bool) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).focusable(focusable)
    }

    fn tab_index(self, index: i32) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).tab_index(index)
    }

    fn cursor(self, cursor: CursorIcon) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).cursor(cursor)
    }

    fn clips_children_on(self, clips: bool) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).clips_children(clips)
    }

    /// Declare this node a text-input surface, enabling the OS input method
    /// (with `ctx`'s purpose) while it is focused. See [`crate::ime`].
    fn ime_input(self, ctx: crate::ime::ImeContext) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).ime_input(ctx)
    }

    /// Make the widget invisible to pointer hit-testing. See
    /// [`HandlerSet::event_pass_through`].
    fn event_pass_through(self, pass_through: bool) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).event_pass_through(pass_through)
    }

    /// Mark this widget's subtree a gesture dead zone. See
    /// [`HandlerSet::gesture_dead_zone`].
    fn gesture_dead_zone(self, dead_zone: bool) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).gesture_dead_zone(dead_zone)
    }

    /// Mark this widget a keyboard capture surface (terminals, game
    /// viewports): while focused, `KeyDown`s bypass shortcut resolution.
    /// See [`HandlerSet::keyboard_capture`].
    fn keyboard_capture(self, capture: bool) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).keyboard_capture(capture)
    }

    /// Make this widget and its whole subtree invisible to pointer
    /// hit-testing (decorative overlays). See
    /// [`HandlerSet::hit_transparent`].
    fn hit_transparent(self, transparent: bool) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).hit_transparent(transparent)
    }

    /// Set a context-menu factory. See
    /// [`HandlerSet::context_menu`] for the full contract.
    fn context_menu(
        self,
        factory: impl Fn(Point, &mut EventContext) -> Option<Box<dyn Widget>> + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).context_menu(factory)
    }

    /// Bind a `Signal<bool>` the framework writes when a strict
    /// descendant has focus. See [`HandlerSet::focus_within`].
    fn focus_within(self, signal: crate::signal::Signal<bool>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).focus_within(signal)
    }

    /// Bind a `Signal<bool>` the framework writes when a strict
    /// descendant is hovered. See [`HandlerSet::hover_within`].
    fn hover_within(self, signal: crate::signal::Signal<bool>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).hover_within(signal)
    }

    /// Bind this node's visibility (`bool` / `Signal<bool>` / `Prop<bool>`) as
    /// a builder property, so `teksu!` can write `visible_when: sig`. Equivalent
    /// to `ctx.visible_when(id, ..)`. See [`HandlerSet::visible_when`].
    fn visible_when(self, state: impl Into<Prop<bool>>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).visible_when(state)
    }

    fn on_drag_hover(
        self,
        f: impl FnMut(
            &crate::drag_payload::DragPayload,
            teksilo_canvas::Point,
            &mut EventContext,
        ) -> crate::drag_state::DropFeedback
        + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_drag_hover(f)
    }

    fn on_drag_leave(self, f: impl FnMut(&mut EventContext) + 'static) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_drag_leave(f)
    }

    fn on_drag_tick(
        self,
        f: impl FnMut(teksilo_canvas::Point, &mut EventContext) + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_drag_tick(f)
    }

    fn on_drop(
        self,
        f: impl FnMut(
            crate::drag_payload::DragPayload,
            teksilo_canvas::Point,
            &mut EventContext,
        ) -> bool
        + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_drop(f)
    }

    /// Set the drag-ended handler on a drag source. See
    /// [`HandlerSet::on_drag_ended`].
    fn on_drag_ended(
        self,
        f: impl FnMut(crate::drag_payload::DropOutcome, &mut EventContext) + 'static,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).on_drag_ended(f)
    }

    // ── Accessibility overrides ────────────────────────────────────────
    //
    // Trait-level entry points: each method wraps the widget into a
    // `WidgetWithHandlers` (the first builder call in any chain) and
    // forwards to the inherent method of the same name. See
    // `WidgetWithHandlers` for full rustdoc on each method's semantics.
    // For translated strings, `LocalizedString` flows through
    // `impl Into<Prop<String>>` via `teksilo-i18n`'s
    // `From<LocalizedString> for Prop<String>` impl, staying reactive.

    fn access_label(self, label: impl Into<Prop<String>>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_label(label)
    }

    #[doc(hidden)]
    fn access_label_literal(self, label: impl Into<String>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_label_literal(label)
    }

    fn access_description(self, description: impl Into<Prop<String>>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_description(description)
    }

    #[doc(hidden)]
    fn access_description_literal(
        self,
        description: impl Into<String>,
    ) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_description_literal(description)
    }

    fn access_hint(self, hint: impl Into<Prop<String>>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_hint(hint)
    }

    #[doc(hidden)]
    fn access_hint_literal(self, hint: impl Into<String>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_hint_literal(hint)
    }

    fn access_value(self, value: impl Into<Prop<String>>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_value(value)
    }

    #[doc(hidden)]
    fn access_value_literal(self, value: impl Into<String>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_value_literal(value)
    }

    fn access_role(self, role: accesskit::Role) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_role(role)
    }

    fn access_hidden(self, hidden: impl Into<Prop<bool>>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_hidden(hidden)
    }

    fn access_disabled(self, disabled: bool) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_disabled(disabled)
    }

    fn access_identifier(self, id: impl Into<String>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_identifier(id)
    }

    fn access_controls(self, target: WidgetId) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_controls(target)
    }

    fn access_described_by(self, target: WidgetId) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_described_by(target)
    }

    fn access_labelled_by(self, target: WidgetId) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_labelled_by(target)
    }

    fn access_live(self, mode: accesskit::Live) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_live(mode)
    }

    fn access_current(self, current: accesskit::AriaCurrent) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_current(current)
    }

    fn access_shortcut_literal(self, shortcut: impl Into<String>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_shortcut_literal(shortcut)
    }

    fn access_shortcut_id(self, id: impl Into<String>) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_shortcut_id(id)
    }

    fn access_has_popup(self, kind: accesskit::HasPopup) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_has_popup(kind)
    }

    fn access_orientation(self, orientation: accesskit::Orientation) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_orientation(orientation)
    }

    fn access_exclude_subtree(self) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_exclude_subtree()
    }

    fn access_merge_subtree(self) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_merge_subtree()
    }

    fn access_subtree(self, mode: AccessSubtreeMode) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_subtree(mode)
    }

    fn access_numeric_value(self, value: f64) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_numeric_value(value)
    }

    fn access_numeric_range(self, min: f64, max: f64) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_numeric_range(min, max)
    }

    fn access_numeric_step(self, step: f64) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_numeric_step(step)
    }

    fn access_action<F>(self, action: accesskit::Action, handler: F) -> WidgetWithHandlers<Self>
    where
        F: FnMut(&mut EventContext) + 'static,
    {
        WidgetWithHandlers::new(self).access_action(action, handler)
    }

    fn access_remove_action(self, action: accesskit::Action) -> WidgetWithHandlers<Self> {
        WidgetWithHandlers::new(self).access_remove_action(action)
    }

    fn access_custom_action<F>(
        self,
        label: impl Into<Prop<String>>,
        handler: F,
    ) -> WidgetWithHandlers<Self>
    where
        F: FnMut(&mut EventContext) + 'static,
    {
        WidgetWithHandlers::new(self).access_custom_action(label, handler)
    }

    #[doc(hidden)]
    fn access_custom_action_literal<F>(
        self,
        label: impl Into<String>,
        handler: F,
    ) -> WidgetWithHandlers<Self>
    where
        F: FnMut(&mut EventContext) + 'static,
    {
        WidgetWithHandlers::new(self).access_custom_action_literal(label, handler)
    }

    fn access_customize<F>(self, f: F) -> WidgetWithHandlers<Self>
    where
        F: Fn(&mut crate::accessibility::AccessNodeBuilder) + 'static,
    {
        WidgetWithHandlers::new(self).access_customize(f)
    }
}

// Blanket implementation for all Widget types.
impl<W: Widget + Sized + 'static> WidgetBuilder for W {}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::widget::WidgetPlacement;
    use crate::widget_id::WidgetId;
    use crate::widget_tree::WidgetTree;

    #[derive(Debug)]
    struct CompositeLeaf {
        child_id: Option<WidgetId>,
    }

    impl CompositeLeaf {
        fn new() -> Self {
            Self { child_id: None }
        }
    }

    impl Widget for CompositeLeaf {
        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
            let child = ctx.add(crate::test_widgets::FillWidget::new());
            self.child_id = Some(child);
            vec![child]
        }

        fn layout_response(
            &self,
            proposal: teksilo_canvas::SizeProposal,
            _ctx: &crate::widget::LayoutContext,
        ) -> crate::widget::LayoutResponse {
            proposal.resolve(120.0, 40.0).into()
        }

        fn place_children(
            &self,
            bounds: teksilo_canvas::Rect,
            _proposal: teksilo_canvas::SizeProposal,
            children: &mut [WidgetPlacement],
            _ctx: &crate::widget::LayoutContext,
        ) {
            for child in children.iter_mut() {
                child.origin = bounds.origin();
                child.size = bounds.size();
            }
        }

        fn children(&self) -> Vec<WidgetId> {
            self.child_id.into_iter().collect()
        }
    }

    #[test]
    fn external_handlers_survive_rebuild() {
        // Regression check: handlers attached externally via the
        // `WidgetBuilder` builder (e.g. `MyCompositeWidget::new().on_tap(...)`)
        // must continue to fire after the widget rebuilds in place.
        // My handler-clearing fix in `rebuild_single_widget` wiped
        // `node.handlers` to stop accumulation of `apply_self_handlers`
        // calls across rebuilds — but the extracted-once-at-insertion
        // HandlerSet is gone by rebuild time and would be lost.
        use std::cell::Cell;
        use std::rc::Rc;

        let tap_count = Rc::new(Cell::new(0_u32));
        let tc = tap_count.clone();

        let mut tree = WidgetTree::new();
        let id = tree.add(CompositeLeaf::new().on_tap(move |_pos, _ctx| {
            tc.set(tc.get() + 1);
        }));
        tree.layout(teksilo_canvas::SizeProposal::exact(200.0, 100.0));

        // Trip a rebuild of the composite — its child gets torn down &
        // rebuilt; node.handlers gets cleared and reset.
        tree.arena_mark_needs_rebuild_for_testing(id);
        tree.layout(teksilo_canvas::SizeProposal::exact(200.0, 100.0));

        // Click through the composite; the externally-attached on_tap
        // must still be wired up.
        tree.click(id);
        assert_eq!(
            tap_count.get(),
            1,
            "externally-attached on_tap must survive a rebuild"
        );
    }

    #[test]
    fn wrapped_composite_widget_still_builds_children() {
        let mut tree = WidgetTree::new();
        let root = tree.add(CompositeLeaf::new().on_tap(|_pos, _ctx| {}));
        tree.layout(teksilo_canvas::SizeProposal::exact(200.0, 100.0));

        assert_eq!(tree.children(root).len(), 1);
    }

    /// A widget that exposes both downcast hooks, like every widget a
    /// composing container reads its child's concrete type through.
    #[derive(Debug)]
    struct Reflective {
        marker: u32,
    }

    impl Widget for Reflective {
        fn layout_response(
            &self,
            proposal: teksilo_canvas::SizeProposal,
            _ctx: &crate::widget::LayoutContext,
        ) -> crate::widget::LayoutResponse {
            proposal.resolve(0.0, 0.0).into()
        }

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

        fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
            Some(self)
        }
    }

    /// Decorating a widget must not hide its concrete type from a parent that
    /// reads it. `as_any` was already forwarded; `as_any_mut` was not, so a
    /// container reading a child through the mutable hook (`MenuList` does, for
    /// mnemonics, the type-ahead label and radio grouping) silently saw nothing
    /// the moment any builder method was called on that child.
    #[test]
    fn both_downcast_hooks_see_through_the_handler_wrapper() {
        let mut wrapped = Reflective { marker: 7 }.focusable(true);

        let seen = wrapped
            .as_any()
            .and_then(|a| a.downcast_ref::<Reflective>())
            .map(|r| r.marker);
        assert_eq!(seen, Some(7), "as_any must forward through the wrapper");

        let seen_mut = wrapped
            .as_any_mut()
            .and_then(|a| a.downcast_mut::<Reflective>())
            .map(|r| r.marker);
        assert_eq!(
            seen_mut,
            Some(7),
            "as_any_mut must forward through the wrapper too"
        );
    }
}